Modern Apps git

← Modern-Apps.git

logicgate: Computer/Sandbox tabs, custom components, grouped chip tray

Commit
9f90ad4fdaef072a19ddbfbb56138a57277ddaf9
Author
Vayun Mathur <[email protected]>
When
2026-11-06 18:00 UTC (29 days ago)
Parents
56d2ed7
Adds a bottom bar with two tabs. Computer is the existing level map.
Sandbox is new: players build their own components and can use them
inside other components and in any Computer level.

Sandbox components
- A component is a Board (circuit + editable LevelIo). Pins are placed
  from a "Pins" tray tab (1/4/8-bit inputs and outputs); their
  top-to-bottom order on the board is their order on the chip.
- The sandbox tray offers only unlocked built-ins
  (LevelRegistry.unlockedChips), plus every component that does not
  contain the open one, so a component can never include itself.
- A details sheet sets name and group, renames or deletes pins, and
  deletes the component (with confirmation).
- Components are usable in every level. Their cost is the recursive sum
  of everything inside, so stars and par comparisons stay fair.

Simulation
- New Behavior.Composite and ChipCatalog (built-ins + components,
  resolved eagerly so it is immutable and safe on the verify thread;
  self-containing components resolve to null).
- Flattener inlines composites into primitive gates before simulating,
  so one Simulator runs the whole board and feedback across component
  boundaries is exact (latches, registers, outer loops). Top-level ids
  are kept; oscillation inside a component is reported on its top-level
  gate, and custom gate output pins are aliased for live wire values.
  Running a black-box simulator per instance was rejected: slower, and
  wrong for loops that cross the boundary.
- The NO_RAM check now finds a RAM16 inside components too.

Pin rewiring
- When an edit reorders or removes a component's pins, remapChipPins
  rewires every other component and saved level draft using it, so
  wires follow their pin instead of jumping to another.

Grouped tray
- ChipGroups sorts tray chips into tabs: Pins, built-ins by the chapter
  that first gifts/unlocks them, then player group names A-Z. A
  FilterChip row appears when there is more than one group; levels open
  on the current chapter's tab.

Structure
- Editor logic moved from LogicViewModel into platform/EditorSession
  (undo/redo over Boards, debounced verify, live probe), which both
  modes share. The view model was at detekt's function limit.
- GameUiState now carries mode (Level | Sandbox), board and catalog.
- New ComponentStore (DataStore key logicgate2_components, already
  covered by the backup agent). CircuitStore gains rewriteAll.
- Adds IconMemory() to library/ui Icons.kt for the Computer tab.
- English strings only; other locales fall back until translated.

Known limits: undoing a pin deletion does not restore dependents' wires
to that pin. Deleting a component drops its copies elsewhere.

Verified: testDevUnitTest (57 tests, 14 new in FlattenerTest and
CustomChipTest), compileDevKotlin, compileDevScreenshotTestKotlin, and
./check games/logicgate (detekt + lint) all pass. Not yet exercised on
a device: ./install refuses emulators and no phone was attached.

Diff

games/logicgate/AGENTS.md
diff --git a/games/logicgate/AGENTS.md b/games/logicgate/AGENTS.mdindex b799fb1dba..ac7311a8bf 100644--- a/games/logicgate/AGENTS.md+++ b/games/logicgate/AGENTS.md@@ -12,14 +12,16 @@ _Install: ./install games/logicgate (dev by default)._ - Rust: no / screenshotTest: yes  ## Overview-**Purpose:** NAND-to-computer circuit puzzle. 28 levels in 5 chapters (Basics, Routing & buses, Arithmetic, Memory, CPU). Every level is checked by a real cycle-accurate simulator, finishing with a CPU that runs three programs out of RAM. 100% offline.-**Game shape:** `domain/` (pure Kotlin: circuit model, chip catalog, simulator, verifier, levels) → `platform/LogicViewModel` (undo/redo, debounced re-verify on `Dispatchers.Default`) → `ui/` (one-canvas editor, chip tray, test panel, level map). `data/` persists drafts (DataStore key `logicgate2_circuits`) and best costs (`LevelStatsRepository` prefs `logicgate2_stats`).-**Entry points:** `Route` → `MainActivity.kt` → `Navigation.kt` → `ui/GamePage.kt` → `ui/GameScreen.kt` → `platform/LogicViewModel.kt` → `domain/sim/Verifier.kt`.+**Purpose:** NAND-to-computer circuit puzzle. Two bottom-bar tabs. **Computer** has 28 levels in 5 chapters (Basics, Routing & buses, Arithmetic, Memory, CPU), each checked by a real cycle-accurate simulator, finishing with a CPU that runs three programs out of RAM. In **Sandbox**, players build their own components (custom pins, unlocked built-ins and other components) and can then use them in any level. 100% offline.+**Game shape:** `domain/` (pure Kotlin: circuit model, chip catalog, simulator, verifier, levels) → `platform/LogicViewModel` (progression, components, catalog) + `platform/EditorSession` (undo/redo, debounced re-verify on `Dispatchers.Default`) → `ui/` (one-canvas editor, grouped chip tray, test panel, level map, sandbox list). `data/` persists drafts (DataStore key `logicgate2_circuits`), components (DataStore key `logicgate2_components`) and best costs (`LevelStatsRepository` prefs `logicgate2_stats`).+**Entry points:** `Route` → `MainActivity.kt` → `Navigation.kt` → `ui/GamePage.kt` / `ui/ComponentPage.kt` → `ui/GameScreen.kt` → `platform/EditorSession.kt` → `domain/sim/Verifier.kt`. **Model:** - Signals are `Int` bit masks on typed 1/4/8-bit pins. SPLIT/JOIN chips convert widths, and wires must match widths. - Level I/O are real `LevelInput`/`LevelOutput` nodes. Unconnected inputs read 0. - One tick of an implicit global clock = settle, then latch. Feedback loops iterate Gauss-Seidel (cap 64 passes → oscillation). State-only chips (DFF/REG/PC) break loops. - Solving a level unlocks its chip as a trusted native behaviour (`domain/model/Chips.kt`). Level pins, tests and par for reward levels derive from that chip (`ChipLevel.kt`), so they cannot drift.+- Sandbox components (`domain/model/CustomChip.kt`, ids `custom:<uuid>`) are a `Board` (circuit + editable `LevelIo`) behind `Behavior.Composite`. `ChipCatalog` resolves built-ins + components (costs summed recursively; self-containing components resolve to null). `domain/sim/Flattener.kt` inlines composites before simulating, so feedback across component boundaries is exact. Chip pin order is the board's pin nodes sorted top-to-bottom. When an edit reorders or removes pins, `remapChipPins` rewires every other component and level draft that uses the component.+- Sandbox tray = `LevelRegistry.unlockedChips(completed)` + components that don't contain the open one + `PinChips` (pseudo-chips `pin:in|out:{1,4,8}` that add board pins). Level tray = `allowedChips(level)` + every component. Tray tabs come from `domain/levels/ChipGroups.kt` (Pins, built-ins by chapter, player group names). - ISA (`domain/model/Isa.kt`): `op[4]|operand[4]`, LDA STA ADD SUB LDI JMP JZ HLT, one instruction per tick via dual-port RAM16. **Gotchas:** - Pars are asserted equal to the reference solution costs in `src/test/.../domain/LevelSolutionsTest.kt`. Change a chip's `nandCost` and its reference together.@@ -31,17 +33,20 @@ _Install: ./install games/logicgate (dev by default)._ ## Key files ### domain/ — pure, unit-tested - domain/model/Circuit.kt — nodes, pins, wires, immutable edits, `sanitized`+- domain/model/Board.kt (circuit + io, pin add/remove/rename), domain/model/CustomChip.kt (+ `PinChips`, `pinRemap`, `remapChipPins`), domain/model/ChipCatalog.kt - domain/model/ChipSpec.kt, domain/model/Chips.kt, domain/model/ChipInfo.kt (chip name + blurb string ids), domain/model/Isa.kt - domain/sim/Simulator.kt, domain/sim/Scheduler.kt — tick semantics, SCC ordering-- domain/sim/Verifier.kt, domain/sim/TestSpec.kt, domain/sim/Scoring.kt+- domain/sim/Verifier.kt, domain/sim/TestSpec.kt, domain/sim/Scoring.kt, domain/sim/Flattener.kt+- domain/levels/ChipGroups.kt (tray tabs) - domain/levels/LevelRegistry.kt + {Basics,Routing,Arithmetic,Memory,Cpu}Levels.kt ### data/ + platform/-- data/CircuitStore.kt, data/ProgressStore.kt-- platform/LogicUiContract.kt (state + `LogicActions.Noop`), platform/LogicViewModel.kt+- data/CircuitStore.kt, data/ComponentStore.kt, data/ProgressStore.kt+- platform/LogicUiContract.kt (state + `LogicActions.Noop`, `EditorMode` Level/Sandbox), platform/EditorSession.kt, platform/LogicViewModel.kt - platform/LogicAchievements.kt (`assets/achievements.json`, ids `lg2_*`), platform/AppBackupAgent.kt ### ui/ - ui/GameScreen.kt, ui/CircuitCanvas.kt, ui/ChipTray.kt, ui/TestPanel.kt, ui/SelectionBar.kt - ui/BriefSheet.kt, ui/ChipInfoSheet.kt, ui/PinLine.kt, ui/BusValueDialog.kt, ui/LevelCompleteOverlay.kt, ui/ProgressionScreen.kt, ui/StarRating.kt+- ui/SandboxPage.kt, ui/SandboxScreen.kt, ui/ComponentPage.kt, ui/ComponentSheet.kt (name, group, pins, delete) - ui/canvas/ — Camera, CameraState, GateGeometry (layout), HitTest, CanvasGestures, CanvasController, GatePainter, GateShapes  ## Verify (this module only)
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/Navigation.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/Navigation.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/Navigation.ktindex 8916e7ff00..3054ad157f 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/Navigation.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/Navigation.kt@@ -3,35 +3,64 @@ package com.vayunmathur.games.logicgate import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.runtime.Composable+import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue+import androidx.compose.runtime.remember import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource import com.vayunmathur.games.logicgate.platform.LogicViewModel+import com.vayunmathur.games.logicgate.ui.ComponentPage import com.vayunmathur.games.logicgate.ui.GamePage+import com.vayunmathur.games.logicgate.ui.LocalChipNames import com.vayunmathur.games.logicgate.ui.ProgressionPage+import com.vayunmathur.games.logicgate.ui.SandboxPage import com.vayunmathur.library.ui.AchievementNotification import com.vayunmathur.library.ui.GameCenterScreen+import com.vayunmathur.library.ui.IconMemory+import com.vayunmathur.library.ui.IconScience+import com.vayunmathur.library.util.BottomBarItem+import com.vayunmathur.library.util.BottomNavBar import com.vayunmathur.library.util.FullscreenPage import com.vayunmathur.library.util.GameHubComposeHook import com.vayunmathur.library.util.MainNavigation+import com.vayunmathur.library.util.SiblingPage import com.vayunmathur.library.util.rememberNavBackStack  @Composable fun Navigation(viewModel: LogicViewModel) {     val backStack = rememberNavBackStack<Route>(Route.Progression)     val newAchievement by viewModel.achievementsManager.newAchievement.collectAsState()+    val catalog by viewModel.catalog.collectAsState()+    val names = remember(catalog) { catalog.customs.associate { it.id to it.name } }     GameHubComposeHook("logicgate", viewModel.achievementsManager)-    Box(modifier = Modifier.fillMaxSize()) {-        MainNavigation(backStack) {-            entry<Route.Progression> { ProgressionPage(backStack, viewModel) }-            entry<Route.Game>(metadata = FullscreenPage()) { GamePage(backStack, viewModel, it.levelId) }-            entry<Route.GameCenter> {-                GameCenterScreen(-                    manager = viewModel.achievementsManager,-                    onBack = { backStack.pop() },-                )+    val pages: List<BottomBarItem<out Route>> = listOf(+        BottomBarItem(stringResource(R.string.lg_tab_computer), Route.Progression) { IconMemory() },+        BottomBarItem(stringResource(R.string.lg_tab_sandbox), Route.Sandbox) { IconScience() },+    )+    CompositionLocalProvider(LocalChipNames provides names) {+        Box(modifier = Modifier.fillMaxSize()) {+            MainNavigation(+                backStack,+                bottomBar = {+                    val cur = backStack.last()+                    if (cur == Route.Progression || cur == Route.Sandbox) BottomNavBar(backStack, pages, cur)+                },+            ) {+                entry<Route.Progression>(metadata = SiblingPage()) { ProgressionPage(backStack, viewModel) }+                entry<Route.Game>(metadata = FullscreenPage()) { GamePage(backStack, viewModel, it.levelId) }+                entry<Route.Sandbox>(metadata = SiblingPage()) { SandboxPage(backStack, viewModel) }+                entry<Route.Component>(metadata = FullscreenPage()) {+                    ComponentPage(backStack, viewModel, it.componentId)+                }+                entry<Route.GameCenter> {+                    GameCenterScreen(+                        manager = viewModel.achievementsManager,+                        onBack = { backStack.pop() },+                    )+                }             }+            newAchievement?.let { AchievementNotification(it) { viewModel.dismissAchievement() } }         }-        newAchievement?.let { AchievementNotification(it) { viewModel.dismissAchievement() } }     } }
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/Route.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/Route.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/Route.ktindex a9c96df9c7..4ea2bfe76f 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/Route.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/Route.kt@@ -6,12 +6,18 @@ import kotlinx.serialization.Serializable /** Navigation destinations. */ @Serializable sealed interface Route : NavKey {-    /** The level map. */+    /** The level map (Computer tab). */     @Serializable data object Progression : Route      /** The circuit editor for one level. */     @Serializable data class Game(val levelId: String) : Route +    /** The player's components (Sandbox tab). */+    @Serializable data object Sandbox : Route++    /** The editor for one sandbox component. */+    @Serializable data class Component(val componentId: String) : Route+     /** Achievements. */     @Serializable data object GameCenter : Route }
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitStore.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitStore.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitStore.ktindex 49c3bc03ef..11af08f1e2 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitStore.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/CircuitStore.kt@@ -67,6 +67,13 @@ class CircuitStore(context: Context, dispatcher: CoroutineDispatcher) {         }     } +    /** Applies [transform] to every saved draft, e.g. to follow a component whose pins moved. */+    suspend fun rewriteAll(transform: (Circuit) -> Circuit) {+        ds.updateString(KEY) { old ->+            json.encodeToString(decode(old).mapValues { (_, dto) -> transform(dto.toDomain()).toDto() })+        }+    }+     private fun decode(raw: String?): Map<String, CircuitDto> {         if (raw.isNullOrEmpty()) return emptyMap()         return try {
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ComponentStore.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ComponentStore.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ComponentStore.ktnew file mode 100644index 0000000000..d27a7a7e90--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/data/ComponentStore.kt@@ -0,0 +1,88 @@+package com.vayunmathur.games.logicgate.data++import android.content.Context+import com.vayunmathur.games.logicgate.domain.model.Board+import com.vayunmathur.games.logicgate.domain.model.CustomChip+import com.vayunmathur.games.logicgate.domain.model.LevelIo+import com.vayunmathur.games.logicgate.domain.model.Pin+import com.vayunmathur.library.util.DataStoreUtils+import kotlinx.coroutines.CoroutineDispatcher+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Job+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.delay+import kotlinx.coroutines.launch+import kotlinx.serialization.SerializationException+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json++/** Saved pin of a component's board. */+@Serializable+data class PinSpecDto(val name: String, val width: Int)++/** Saved sandbox component. */+@Serializable+data class ComponentDto(+    val id: String,+    val name: String,+    val group: String,+    val inputs: List<PinSpecDto>,+    val outputs: List<PinSpecDto>,+    val circuit: CircuitDto,+)++/**+ * The player's sandbox components, as one JSON list in the shared DataStore. Like [CircuitStore],+ * saves are debounced on the store's own scope so the last edit lands after the screen closes.+ */+class ComponentStore(context: Context, dispatcher: CoroutineDispatcher) {+    private val ds = DataStoreUtils.getInstance(context)+    private val scope = CoroutineScope(SupervisorJob() + dispatcher)+    private val json = Json { ignoreUnknownKeys = true }+    private var pending: Job? = null++    suspend fun load(): List<CustomChip> = decode(ds.getStringAwait(KEY)).map { it.toDomain() }++    fun save(components: List<CustomChip>) {+        pending?.cancel()+        pending = scope.launch {+            delay(SAVE_DEBOUNCE_MS)+            val dto = components.map { it.toDto() }+            ds.updateString(KEY) { json.encodeToString(dto) }+        }+    }++    private fun decode(raw: String?): List<ComponentDto> {+        if (raw.isNullOrEmpty()) return emptyList()+        return try {+            json.decodeFromString<List<ComponentDto>>(raw)+        } catch (ignored: SerializationException) {+            emptyList()+        }+    }++    private companion object {+        const val KEY = "logicgate2_components"+        const val SAVE_DEBOUNCE_MS = 400L+    }+}++private fun Pin.toDto() = PinSpecDto(name, width)++private fun PinSpecDto.toDomain() = Pin(name, width)++private fun CustomChip.toDto() = ComponentDto(+    id = id,+    name = name,+    group = group,+    inputs = board.io.inputs.map { it.toDto() },+    outputs = board.io.outputs.map { it.toDto() },+    circuit = board.circuit.toDto(),+)++private fun ComponentDto.toDomain() = CustomChip(+    id = id,+    name = name,+    group = group,+    board = Board(circuit.toDomain(), LevelIo(inputs.map { it.toDomain() }, outputs.map { it.toDomain() })),+)
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/ChipGroups.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/ChipGroups.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/ChipGroups.ktnew file mode 100644index 0000000000..e01a239e06--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/ChipGroups.kt@@ -0,0 +1,55 @@+package com.vayunmathur.games.logicgate.domain.levels++import com.vayunmathur.games.logicgate.domain.model.ChipCatalog+import com.vayunmathur.games.logicgate.domain.model.ChipSpec+import com.vayunmathur.games.logicgate.domain.model.Chips+import com.vayunmathur.games.logicgate.domain.model.PinChips++/** A tab of the chip tray. */+sealed interface TrayGroup {+    /** Board inputs and outputs (sandbox only). */+    data object Pins : TrayGroup++    /** Built-in chips first earned or gifted in [chapter]. */+    data class Builtin(val chapter: Chapter) : TrayGroup++    /** Player-built chips the player filed under [name]. */+    data class Custom(val name: String) : TrayGroup+}++/** One tray tab and its chips, in tray order. */+data class TraySection(val group: TrayGroup, val chips: List<ChipSpec>)++/** Sorts chips into tray tabs: pins, then built-ins by chapter, then the player's groups A-Z. */+object ChipGroups {+    private val chapterOf: Map<String, Chapter> = buildMap {+        for (id in Chips.base) put(id, Chapter.BASICS)+        for (level in LevelRegistry.levels) {+            for (id in level.gifts + level.unlocks) putIfAbsent(id, level.chapter)+        }+    }++    fun chapterOf(chipId: String): Chapter = chapterOf[chipId] ?: Chapter.BASICS++    fun groupOf(chipId: String, catalog: ChipCatalog): TrayGroup = when {+        PinChips.isPin(chipId) -> TrayGroup.Pins+        else -> catalog.custom(chipId)?.let { TrayGroup.Custom(it.group) } ?: TrayGroup.Builtin(chapterOf(chipId))+    }++    fun sections(chips: List<ChipSpec>, catalog: ChipCatalog): List<TraySection> {+        val grouped = chips.groupBy { groupOf(it.id, catalog) }+        return grouped.keys.sortedWith(ORDER).map { TraySection(it, grouped.getValue(it)) }+    }++    private val ORDER = compareBy<TrayGroup>(+        {+            when (it) {+                TrayGroup.Pins -> 0+                is TrayGroup.Builtin -> 1+                is TrayGroup.Custom -> 2+            }+        },+        { (it as? TrayGroup.Builtin)?.chapter?.ordinal ?: 0 },+        { (it as? TrayGroup.Custom)?.name?.lowercase().orEmpty() },+    )+}
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/LevelRegistry.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/LevelRegistry.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/LevelRegistry.ktindex 90800eb1c1..657120b111 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/LevelRegistry.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/levels/LevelRegistry.kt@@ -40,4 +40,18 @@ object LevelRegistry {         chips += Chips.base         return chips.toList()     }++    /**+     * The sandbox palette, newest first: the gifts of every open level, everything earned by a+     * solved level, then NAND and the constants.+     */+    fun unlockedChips(completed: Set<String>): List<String> {+        val chips = LinkedHashSet<String>()+        for (level in levels.asReversed()) {+            if (level.id in completed) chips += level.unlocks+            if (isUnlocked(level.id, completed)) chips += level.gifts+        }+        chips += Chips.base+        return chips.toList()+    } }
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Board.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Board.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Board.ktnew file mode 100644index 0000000000..9a7fcf8125--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Board.kt@@ -0,0 +1,65 @@+package com.vayunmathur.games.logicgate.domain.model++/**+ * What the editor works on: a circuit plus the pins its input/output nodes carry. In a level the+ * pins are fixed; in the sandbox the player adds, removes and renames them.+ */+data class Board(val circuit: Circuit, val io: LevelIo) {++    /** Adds a [width]-bit input or output node at [pos] with the first unused default name. */+    fun addPin(input: Boolean, width: Int, pos: Point): Board {+        val pins = if (input) io.inputs else io.outputs+        val taken = pins.map { it.name }.toSet()+        val names = if (input) INPUT_NAMES else OUTPUT_NAMES+        val name = names.firstOrNull { it !in taken } ?: generateSequence(pins.size + 1) { it + 1 }+            .map { (if (input) "in" else "out") + it }+            .first { it !in taken }+        val pin = Pin(name, width)+        val id = NodeId(circuit.nextId)+        val node = if (input) LevelInput(id, io.inputs.size, pos) else LevelOutput(id, io.outputs.size, pos)+        val nextIo = if (input) io.copy(inputs = io.inputs + pin) else io.copy(outputs = io.outputs + pin)+        return Board(circuit.copy(nodes = circuit.nodes + node, nextId = circuit.nextId + 1), nextIo)+    }++    /** Removes an input or output node, its wires and its pin; later pins shift down one index. */+    fun removePin(id: NodeId): Board {+        val node = circuit.node(id)+        val (ins, outs) = when (node) {+            is LevelInput -> io.inputs.filterIndexed { i, _ -> i != node.index } to io.outputs+            is LevelOutput -> io.inputs to io.outputs.filterIndexed { i, _ -> i != node.index }+            else -> return this+        }+        val nodes = circuit.nodes.filterNot { it.id == id }.map { n ->+            when {+                node is LevelInput && n is LevelInput && n.index > node.index -> n.copy(index = n.index - 1)+                node is LevelOutput && n is LevelOutput && n.index > node.index -> n.copy(index = n.index - 1)+                else -> n+            }+        }+        val wires = circuit.wires.filterNot { it.from.node == id || it.to.node == id }+        return Board(circuit.copy(nodes = nodes, wires = wires), LevelIo(ins, outs))+    }++    /** Renames the pin behind an input or output node. Blank names are ignored. */+    fun renamePin(id: NodeId, name: String): Board {+        val trimmed = name.trim().take(MAX_PIN_NAME)+        if (trimmed.isEmpty()) return this+        return when (val node = circuit.node(id)) {+            is LevelInput -> copy(io = io.copy(inputs = io.inputs.rename(node.index, trimmed)))+            is LevelOutput -> copy(io = io.copy(outputs = io.outputs.rename(node.index, trimmed)))+            else -> this+        }+    }++    private fun List<Pin>.rename(index: Int, name: String) =+        mapIndexed { i, p -> if (i == index) p.copy(name = name) else p }++    /** Default pin names. */+    companion object {+        const val MAX_PIN_NAME = 8+        private val INPUT_NAMES = ('a'..'n').map { it.toString() }+        private val OUTPUT_NAMES = ('o'..'z').map { it.toString() }++        val Empty = Board(Circuit(), LevelIo(emptyList(), emptyList()))+    }+}
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipCatalog.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipCatalog.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipCatalog.ktnew file mode 100644index 0000000000..4ff7e02ece--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipCatalog.kt@@ -0,0 +1,53 @@+package com.vayunmathur.games.logicgate.domain.model++/**+ * Every placeable chip: the built-ins plus the player's [customs]. Custom specs are resolved once+ * up front (so the catalog is immutable and safe to share with the verifier's thread); a component+ * that contains itself, directly or not, resolves to nothing and drops out like an unknown chip.+ */+class ChipCatalog(val customs: List<CustomChip> = emptyList()) {+    private val byId: Map<String, CustomChip> = customs.associateBy { it.id }+    private val specs: Map<String, ChipSpec>++    init {+        val resolved = HashMap<String, ChipSpec?>()+        val resolving = HashSet<String>()+        fun resolve(id: String): ChipSpec? {+            Chips[id]?.let { return it }+            if (id in resolved) return resolved[id]+            val chip = byId[id] ?: return null+            if (!resolving.add(id)) return null+            val gates = chip.board.circuit.nodes.filterIsInstance<Gate>()+            val inner = gates.map { resolve(it.chipId) }+            resolving.remove(id)+            val cyclic = gates.zip(inner).any { (g, s) -> s == null && byId[g.chipId] != null }+            val spec = if (cyclic) null else chip.toSpec(inner.sumOf { it?.nandCost ?: 0 })+            resolved[id] = spec+            return spec+        }+        customs.forEach { resolve(it.id) }+        specs = resolved.mapNotNull { (k, v) -> v?.let { k to it } }.toMap()+    }++    operator fun get(id: String): ChipSpec? = Chips[id] ?: specs[id]++    fun custom(id: String): CustomChip? = byId[id]++    fun lookup(io: LevelIo): PinLookup = Chips.lookup(io, ::get)++    /** True when [id] is [target] or contains it at any depth. */+    fun uses(id: String, target: String): Boolean {+        val seen = HashSet<String>()+        fun visit(c: String): Boolean {+            if (c == target) return true+            if (!seen.add(c)) return false+            return byId[c]?.board?.circuit?.nodes?.any { it is Gate && visit(it.chipId) } == true+        }+        return visit(id)+    }++    /** Built-ins only. */+    companion object {+        val Builtin = ChipCatalog()+    }+}
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipInfo.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipInfo.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipInfo.ktindex f69283daa2..42fdccd949 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipInfo.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipInfo.kt@@ -58,7 +58,13 @@ object ChipInfo {          Chips.DECODER to ChipText(R.string.lg_chip_decoder_label, R.string.lg_chip_decoder_info),         Chips.CPU to ChipText(R.string.lg_chip_cpu_label, R.string.lg_chip_cpu_info),-    )+    ) + PinChips.all.associate { pin ->+        pin.id to if (PinChips.isInput(pin.id)) {+            ChipText(R.string.lg_chip_input_label, R.string.lg_chip_input_info)+        } else {+            ChipText(R.string.lg_chip_output_label, R.string.lg_chip_output_info)+        }+    }      /** The name of [chipId] as a string resource, or null for a chip with no entry. */     @StringRes
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipSpec.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipSpec.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipSpec.ktindex 2d70405467..c13de7a998 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipSpec.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/ChipSpec.kt@@ -20,6 +20,12 @@ sealed interface Behavior {         val next: (state: IntArray, inputs: IntArray) -> IntArray,         val readsInputs: Boolean = false,     ) : Behavior++    /**+     * A player-built chip. The simulator inlines [circuit] rather than running it as a black box;+     * chip input `k` feeds inner node [inputNodes]`[k]` and chip output `k` reads [outputNodes]`[k]`.+     */+    class Composite(val circuit: Circuit, val inputNodes: List<NodeId>, val outputNodes: List<NodeId>) : Behavior }  /** A placeable chip: its pins, what it costs in NAND gates, and its trusted native behaviour. */
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Chips.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Chips.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Chips.ktindex 1afe008114..9a54a4b461 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Chips.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/Chips.kt@@ -212,10 +212,10 @@ object Chips {      operator fun get(id: String): ChipSpec? = byId[id] -    /** Pin lookup for a board with the level pins [io]. */-    fun lookup(io: LevelIo): PinLookup = PinLookup { node ->+    /** Pin lookup for a board with the level pins [io], resolving chips through [spec]. */+    fun lookup(io: LevelIo, spec: (String) -> ChipSpec? = { byId[it] }): PinLookup = PinLookup { node ->         when (node) {-            is Gate -> byId[node.chipId]?.let { NodePins(it.inputs, it.outputs) }+            is Gate -> spec(node.chipId)?.let { NodePins(it.inputs, it.outputs) }             is LevelInput -> io.inputs.getOrNull(node.index)?.let { NodePins(emptyList(), listOf(it)) }             is LevelOutput -> io.outputs.getOrNull(node.index)?.let { NodePins(listOf(it), emptyList()) }         }
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/CustomChip.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/CustomChip.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/CustomChip.ktnew file mode 100644index 0000000000..715fada637--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/model/CustomChip.kt@@ -0,0 +1,93 @@+package com.vayunmathur.games.logicgate.domain.model++/**+ * A component the player built in the sandbox. Its pins are the board's inputs and outputs, in+ * top-to-bottom order (then left-to-right), so moving a pin node on the board reorders the chip.+ */+data class CustomChip(+    val id: String,+    val name: String,+    val group: String,+    val board: Board,+) {+    val inputNodes: List<LevelInput>+        get() = board.circuit.nodes.filterIsInstance<LevelInput>()+            .filter { it.index in board.io.inputs.indices }+            .sortedWith(BOARD_ORDER)++    val outputNodes: List<LevelOutput>+        get() = board.circuit.nodes.filterIsInstance<LevelOutput>()+            .filter { it.index in board.io.outputs.indices }+            .sortedWith(BOARD_ORDER)++    val inputs: List<Pin> get() = inputNodes.map { board.io.inputs[it.index] }+    val outputs: List<Pin> get() = outputNodes.map { board.io.outputs[it.index] }++    fun toSpec(nandCost: Int): ChipSpec = ChipSpec(+        id = id,+        inputs = inputs,+        outputs = outputs,+        nandCost = nandCost,+        behavior = Behavior.Composite(board.circuit, inputNodes.map { it.id }, outputNodes.map { it.id }),+    )++    /** Ids and naming. */+    companion object {+        const val PREFIX = "custom:"+        const val DEFAULT_GROUP = "My components"++        fun isCustom(chipId: String): Boolean = chipId.startsWith(PREFIX)++        private val BOARD_ORDER = compareBy<Node>({ it.pos.y }, { it.pos.x })+    }+}++/**+ * How [old]'s chip pins moved in [new]: for each old input/output position, its new position or+ * -1 when the pin is gone. Null when nothing moved.+ */+fun pinRemap(old: CustomChip, new: CustomChip): Pair<IntArray, IntArray>? {+    fun map(before: List<Node>, after: List<Node>): IntArray {+        val pos = after.withIndex().associate { (i, n) -> n.id to i }+        return IntArray(before.size) { pos[before[it].id] ?: -1 }+    }+    val ins = map(old.inputNodes, new.inputNodes)+    val outs = map(old.outputNodes, new.outputNodes)+    val identity = ins.withIndex().all { (i, v) -> i == v } && outs.withIndex().all { (i, v) -> i == v }+    return if (identity) null else ins to outs+}++/**+ * Rewires every [chipId] gate after its pins moved: [inMap]/[outMap] give each old pin index its+ * new one (-1 drops the wire).+ */+fun Circuit.remapChipPins(chipId: String, inMap: IntArray, outMap: IntArray): Circuit {+    val gates = nodes.filter { it is Gate && it.chipId == chipId }.map { it.id }.toSet()+    if (gates.isEmpty()) return this+    val rewired = wires.mapNotNull { w ->+        val from = if (w.from.node in gates) w.from.copy(index = outMap.getOrElse(w.from.index) { -1 }) else w.from+        val to = if (w.to.node in gates) w.to.copy(index = inMap.getOrElse(w.to.index) { -1 }) else w.to+        if (from.index < 0 || to.index < 0) null else Wire(from, to)+    }+    return copy(wires = rewired)+}++/** The sandbox tray's pin nodes: inputs and outputs of each bus width, placed like chips. */+object PinChips {+    private const val IN = "pin:in:"+    private const val OUT = "pin:out:"+    private val widths = listOf(1, 4, 8)++    val all: List<ChipSpec> =+        widths.map { spec(IN + it, emptyList(), listOf(Pin("in", it))) } ++            widths.map { spec(OUT + it, listOf(Pin("out", it)), emptyList()) }++    fun isPin(chipId: String): Boolean = chipId.startsWith(IN) || chipId.startsWith(OUT)++    fun isInput(chipId: String): Boolean = chipId.startsWith(IN)++    fun width(chipId: String): Int = chipId.substringAfterLast(':').toIntOrNull() ?: 1++    private fun spec(id: String, inputs: List<Pin>, outputs: List<Pin>) =+        ChipSpec(id, inputs, outputs, 0, Behavior.Comb { IntArray(outputs.size) })+}
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Flattener.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Flattener.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Flattener.ktnew file mode 100644index 0000000000..9a2e63d665--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Flattener.kt@@ -0,0 +1,140 @@+package com.vayunmathur.games.logicgate.domain.sim++import com.vayunmathur.games.logicgate.domain.model.Behavior+import com.vayunmathur.games.logicgate.domain.model.ChipSpec+import com.vayunmathur.games.logicgate.domain.model.Circuit+import com.vayunmathur.games.logicgate.domain.model.Gate+import com.vayunmathur.games.logicgate.domain.model.LevelInput+import com.vayunmathur.games.logicgate.domain.model.LevelOutput+import com.vayunmathur.games.logicgate.domain.model.Node+import com.vayunmathur.games.logicgate.domain.model.NodeId+import com.vayunmathur.games.logicgate.domain.model.PinRef+import com.vayunmathur.games.logicgate.domain.model.PinSide+import com.vayunmathur.games.logicgate.domain.model.Wire++/**+ * A circuit with every player-built chip inlined. [owner] maps each inlined node to the top-level+ * gate it came from; [aliases] maps each top-level composite output pin to the flat pin driving it.+ */+internal class Flattened(+    val circuit: Circuit,+    val owner: Map<NodeId, NodeId>,+    val aliases: Map<PinRef, PinRef>,+)++/**+ * Inlines [Behavior.Composite] chips into their primitive gates so one simulator runs the whole+ * board cycle-accurately, including feedback that crosses component boundaries. Top-level nodes+ * keep their ids. A wire chased through ports into a loop with no gate on it reads 0.+ */+internal object Flattener {++    fun flatten(circuit: Circuit, catalog: (String) -> ChipSpec?): Flattened {+        val composite = circuit.nodes.any { it is Gate && catalog(it.chipId)?.behavior is Behavior.Composite }+        if (!composite) return Flattened(circuit, emptyMap(), emptyMap())+        return Builder(circuit, catalog).build()+    }++    private class Inst(+        val key: Int,+        val circuit: Circuit,+        val parent: Inst?,+        val gate: Gate?,+        val ports: Behavior.Composite?,+        val owner: NodeId?,+        val chain: Set<String>,+    )++    private class Builder(private val top: Circuit, private val catalog: (String) -> ChipSpec?) {+        private val insts = mutableListOf<Inst>()+        private val flatId = HashMap<Pair<Int, NodeId>, NodeId>()+        private val children = HashMap<Pair<Int, NodeId>, Inst>()+        private val nodes = mutableListOf<Node>()+        private val owner = HashMap<NodeId, NodeId>()+        private var next = maxOf(top.nextId, (top.nodes.maxOfOrNull { it.id.raw } ?: -1) + 1)++        fun build(): Flattened {+            val root = Inst(0, top, null, null, null, null, emptySet()).also { insts += it }+            collect(root)+            val wires = insts.flatMap { inst ->+                inst.circuit.wires.mapNotNull { w ->+                    val to = flatId[inst.key to w.to.node] ?: return@mapNotNull null+                    resolve(inst, w.from, HashSet())?.let { Wire(it, PinRef(to, PinSide.IN, w.to.index)) }+                }+            }+            val aliases = HashMap<PinRef, PinRef>()+            for (n in top.nodes) {+                val ports = children[0 to n.id]?.ports ?: continue+                for (k in ports.outputNodes.indices) {+                    val ref = PinRef(n.id, PinSide.OUT, k)+                    resolve(root, ref, HashSet())?.let { aliases[ref] = it }+                }+            }+            return Flattened(Circuit(nodes, wires, next), owner, aliases)+        }++        private fun collect(inst: Inst) {+            val nested = inst.parent != null+            for (n in inst.circuit.nodes) {+                when (n) {+                    is LevelInput, is LevelOutput -> if (!nested) place(inst, n, n.id)+                    is Gate -> {+                        val spec = catalog(n.chipId) ?: continue+                        val ports = spec.behavior as? Behavior.Composite+                        when {+                            ports == null -> place(inst, n, if (nested) NodeId(next++) else n.id)+                            n.chipId in inst.chain || inst.chain.size >= MAX_DEPTH -> Unit+                            else -> {+                                val child = Inst(+                                    insts.size, ports.circuit, inst, n, ports,+                                    inst.owner ?: n.id, inst.chain + n.chipId,+                                )+                                insts += child+                                children[inst.key to n.id] = child+                                collect(child)+                            }+                        }+                    }+                }+            }+        }++        private fun place(inst: Inst, n: Node, id: NodeId) {+            flatId[inst.key to n.id] = id+            nodes += when (n) {+                is Gate -> n.copy(id = id)+                else -> n+            }+            inst.owner?.let { owner[id] = it }+        }++        /** The flat output pin that ultimately drives [ref], an output pin in [inst]'s circuit. */+        private fun resolve(inst: Inst, ref: PinRef, seen: MutableSet<Triple<Int, NodeId, Int>>): PinRef? {+            if (!seen.add(Triple(inst.key, ref.node, ref.index))) return null+            val flat = flatId[inst.key to ref.node]+            val child = children[inst.key to ref.node]+            val parent = inst.parent+            return when {+                flat != null -> PinRef(flat, PinSide.OUT, ref.index)+                child != null -> driverOfOutput(child, ref.index)?.let { resolve(child, it, seen) }+                parent != null -> driverOfInput(inst, parent, ref.node)?.let { resolve(parent, it, seen) }+                else -> null+            }+        }++        /** The pin inside [child] wired to its output port [k]. */+        private fun driverOfOutput(child: Inst, k: Int): PinRef? {+            val port = child.ports?.outputNodes?.getOrNull(k) ?: return null+            return child.circuit.wireInto(PinRef(port, PinSide.IN, 0))?.from+        }++        /** The pin in [parent] wired to the chip input that [inst]'s input node [node] stands for. */+        private fun driverOfInput(inst: Inst, parent: Inst, node: NodeId): PinRef? {+            val gate = inst.gate ?: return null+            val k = inst.ports?.inputNodes?.indexOf(node)?.takeIf { it >= 0 } ?: return null+            return parent.circuit.wireInto(PinRef(gate.id, PinSide.IN, k))?.from+        }+    }++    private const val MAX_DEPTH = 32+}
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Simulator.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Simulator.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Simulator.ktindex 1a8a874067..42d10255e5 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Simulator.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Simulator.kt@@ -31,7 +31,8 @@ class Simulator(     io: LevelIo,     catalog: (String) -> ChipSpec? = Chips::get, ) {-    private val nodes = circuit.nodes+    private val board = Flattener.flatten(circuit, catalog)+    private val nodes = board.circuit.nodes     private val specs: Array<ChipSpec?> = Array(nodes.size) { (nodes[it] as? Gate)?.let { g -> catalog(g.chipId) } }     private val inPins: Array<List<Pin>>     private val outPins: Array<List<Pin>>@@ -65,7 +66,7 @@ class Simulator(         val index = HashMap<NodeId, Int>()         nodes.forEachIndexed { i, n -> index[n.id] = i }         inSrc = Array(nodes.size) { IntArray(inPins[it].size) { -1 } }-        for (w in circuit.wires) {+        for (w in board.circuit.wires) {             val src = index[w.from.node] ?: continue             val dst = index[w.to.node] ?: continue             if (w.from.index !in outPins[src].indices || w.to.index !in inPins[dst].indices) continue@@ -76,7 +77,7 @@ class Simulator(             if (n is LevelOutput && n.index in outputNodes.indices) outputNodes[n.index] = i         }         stateOnly = nodes.indices.filter { specs[it]?.isStateOnly == true }.toIntArray()-        val order = Scheduler.groups(nodes.size, edges(index, circuit), stateOnly.toSet())+        val order = Scheduler.groups(nodes.size, edges(index, board.circuit), stateOnly.toSet())         groups = order.map { it.first }         cyclic = BooleanArray(order.size) { order[it].second }         reset()@@ -118,7 +119,7 @@ class Simulator(                 pass++             }             if (changed) {-                for (i in group) if (evaluate(i)) oscillating += nodes[i].id+                for (i in group) if (evaluate(i)) oscillating += board.owner[nodes[i].id] ?: nodes[i].id             }         }         return oscillating@@ -154,6 +155,9 @@ class Simulator(         }     } +    /** True when [chipId] is on the board, including inside player-built chips. */+    fun contains(chipId: String): Boolean = specs.any { it?.id == chipId }+     fun stateOf(id: NodeId): IntArray? = nodes.indexOfFirst { it.id == id }.takeIf { it >= 0 }?.let { states[it] }      /** Current value on every output pin, which is also the value of every wire leaving it. */@@ -162,6 +166,7 @@ class Simulator(         for (i in nodes.indices) {             for (k in outPins[i].indices) map[PinRef(nodes[i].id, PinSide.OUT, k)] = values[outBase[i] + k]         }+        for ((alias, src) in board.aliases) map[alias] = map[src] ?: 0         return map     } @@ -184,6 +189,7 @@ class Simulator(             is Gate -> when (val b = specs[i]?.behavior ?: return false) {                 is Behavior.Comb -> b.eval(gather(i))                 is Behavior.Seq -> b.outputs(states[i] ?: b.init, gather(i))+                is Behavior.Composite -> return false             }         }         var changed = false
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Verifier.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Verifier.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Verifier.ktindex fec085c966..8e5d7f1d2d 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Verifier.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/domain/sim/Verifier.kt@@ -3,7 +3,6 @@ package com.vayunmathur.games.logicgate.domain.sim import com.vayunmathur.games.logicgate.domain.model.ChipSpec import com.vayunmathur.games.logicgate.domain.model.Chips import com.vayunmathur.games.logicgate.domain.model.Circuit-import com.vayunmathur.games.logicgate.domain.model.Gate import com.vayunmathur.games.logicgate.domain.model.LevelIo import com.vayunmathur.games.logicgate.domain.model.NodeId import com.vayunmathur.games.logicgate.domain.model.PinRef@@ -49,21 +48,32 @@ object Verifier {         return when (tests) {             is TestSpec.Comb -> verifyComb(sim, tests)             is TestSpec.Seq -> verifySeq(sim, tests)-            is TestSpec.Programs -> verifyPrograms(sim, io, tests, circuit)+            is TestSpec.Programs -> verifyPrograms(sim, io, tests)         }     }      /** Wire values with the level inputs held at [inputs], from reset. */-    fun manual(io: LevelIo, circuit: Circuit, inputs: List<Int>): Probe {-        val sim = Simulator(circuit, io)+    fun manual(+        io: LevelIo,+        circuit: Circuit,+        inputs: List<Int>,+        catalog: (String) -> ChipSpec? = Chips::get,+    ): Probe {+        val sim = Simulator(circuit, io, catalog)         sim.setInputs(inputs.toIntArray())         val osc = sim.settle()         return Probe(sim.pinValues(), osc)     }      /** Wire values at test row [caseIndex], replaying earlier ticks for sequential levels. */-    fun probe(io: LevelIo, tests: TestSpec, circuit: Circuit, caseIndex: Int): Probe {-        val sim = Simulator(circuit, io)+    fun probe(+        io: LevelIo,+        tests: TestSpec,+        circuit: Circuit,+        caseIndex: Int,+        catalog: (String) -> ChipSpec? = Chips::get,+    ): Probe {+        val sim = Simulator(circuit, io, catalog)         val osc: Set<NodeId> = when (tests) {             is TestSpec.Comb -> {                 sim.setInputs(tests.cases[caseIndex].inputs.toIntArray())@@ -106,10 +116,10 @@ object Verifier {         return VerifyResult(results, osc)     } -    private fun verifyPrograms(sim: Simulator, io: LevelIo, tests: TestSpec.Programs, circuit: Circuit): VerifyResult {+    private fun verifyPrograms(sim: Simulator, io: LevelIo, tests: TestSpec.Programs): VerifyResult {         val accIdx = io.outputs.indexOfFirst { it.name == "acc" }         val haltIdx = io.outputs.indexOfFirst { it.name == "halt" }-        val noRam = !tests.harness && circuit.nodes.none { it is Gate && it.chipId == Chips.RAM16 }+        val noRam = !tests.harness && !sim.contains(Chips.RAM16)         val osc = LinkedHashSet<NodeId>()         val results = tests.programs.map { p ->             val expected = io.outputs.indices.map { k ->
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/AppBackupAgent.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/AppBackupAgent.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/AppBackupAgent.ktindex e22053d7a9..14334e5b3c 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/AppBackupAgent.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/AppBackupAgent.kt@@ -4,8 +4,9 @@ import com.vayunmathur.games.logicgate.data.ProgressStore import com.vayunmathur.library.util.BaseBackupAgent  /**- * Backs up the stats prefs and the shared DataStore file, which holds the circuit drafts- * (`logicgate2_circuits` is a key inside it, not a file of its own).+ * Backs up the stats prefs and the shared DataStore file, which holds the circuit drafts and the+ * sandbox components (`logicgate2_circuits` and `logicgate2_components` are keys inside it, not+ * files of their own).  */ class AppBackupAgent : BaseBackupAgent() {     override val prefNames: List<String>
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/EditorSession.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/EditorSession.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/EditorSession.ktnew file mode 100644index 0000000000..0578866ab0--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/EditorSession.kt@@ -0,0 +1,248 @@+package com.vayunmathur.games.logicgate.platform++import com.vayunmathur.games.logicgate.domain.model.Board+import com.vayunmathur.games.logicgate.domain.model.ChipSpec+import com.vayunmathur.games.logicgate.domain.model.Circuit+import com.vayunmathur.games.logicgate.domain.model.Gate+import com.vayunmathur.games.logicgate.domain.model.LevelInput+import com.vayunmathur.games.logicgate.domain.model.NodeId+import com.vayunmathur.games.logicgate.domain.model.PinChips+import com.vayunmathur.games.logicgate.domain.model.PinRef+import com.vayunmathur.games.logicgate.domain.model.Point+import com.vayunmathur.games.logicgate.domain.sim.Probe+import com.vayunmathur.games.logicgate.domain.sim.Scoring+import com.vayunmathur.games.logicgate.domain.sim.Verifier+import com.vayunmathur.games.logicgate.domain.sim.VerifyResult+import kotlinx.coroutines.CoroutineDispatcher+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Job+import kotlinx.coroutines.delay+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.flow.update+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++/**+ * The open editor, for a level or a sandbox component: an undo/redo stack of immutable boards,+ * and after every committed edit a debounced re-verification on [compute] (levels) or a fresh+ * live probe (sandbox), cancelling any older run. [persist] saves each edit; [solved] fires+ * whenever a level's tests all pass.+ */+class EditorSession(+    private val scope: CoroutineScope,+    private val compute: CoroutineDispatcher,+    private val persist: (GameUiState) -> Unit,+    private val solved: (GameUiState) -> Unit,+) : LogicActions {+    private val _state = MutableStateFlow<GameUiState?>(null)+    val state: StateFlow<GameUiState?> = _state.asStateFlow()++    private val history = ArrayDeque<Board>()+    private val future = ArrayDeque<Board>()+    private var verifyJob: Job? = null+    private var liveJob: Job? = null+    private var wasSolved = false++    /** Replaces whatever was open with [initial] (or nothing while it loads). */+    fun open(initial: GameUiState?) {+        verifyJob?.cancel()+        liveJob?.cancel()+        history.clear()+        future.clear()+        wasSolved = false+        _state.value = initial+        if (initial?.level != null) reverify(announce = false) else refreshLive()+    }++    /** A change outside the undo stack, such as a new best cost. */+    fun update(transform: (GameUiState) -> GameUiState) = _state.update { it?.let(transform) }++    override fun placeChip(chipId: String, at: Point) {+        val s = _state.value ?: return+        when {+            PinChips.isPin(chipId) && s.sandbox != null ->+                commit(s.board.addPin(PinChips.isInput(chipId), PinChips.width(chipId), at))+            s.chips.any { it.id == chipId } -> commit(s.board.copy(circuit = s.circuit.addGate(chipId, at).first))+        }+    }++    override fun moveNode(id: NodeId, to: Point) {+        val s = _state.value ?: return+        commit(s.board.copy(circuit = s.circuit.moveNode(id, to)))+    }++    override fun connect(a: PinRef, b: PinRef) {+        val s = _state.value ?: return+        s.circuit.connect(a, b, s.catalog.lookup(s.io))?.let { commit(s.board.copy(circuit = it)) }+    }++    override fun select(selection: Selection?) = update { it.copy(selection = selection) }++    override fun deleteSelection() {+        val s = _state.value ?: return+        when (val sel = s.selection) {+            is Selection.OfNode -> deleteNode(sel.id)+            is Selection.OfWire -> commit(s.board.copy(circuit = s.circuit.removeWire(sel.wire)))+            null -> Unit+        }+        update { it.copy(selection = null) }+    }++    override fun deleteNode(id: NodeId) {+        val s = _state.value ?: return+        when {+            s.circuit.node(id) is Gate -> commit(s.board.copy(circuit = s.circuit.removeNode(id)))+            s.sandbox != null -> commit(s.board.removePin(id))+        }+    }++    override fun undo() {+        val s = _state.value ?: return+        val previous = history.removeLastOrNull() ?: return+        future.addLast(s.board)+        show(s, previous)+    }++    override fun redo() {+        val s = _state.value ?: return+        val next = future.removeLastOrNull() ?: return+        history.addLast(s.board)+        show(s, next)+    }++    override fun setInput(index: Int, value: Int) {+        update { s ->+            s.copy(manualInputs = s.manualInputs.mapIndexed { i, v -> if (i == index) value else v }, probeCase = null)+        }+        refreshLive()+    }++    override fun probe(caseIndex: Int?) {+        update { it.copy(probeCase = caseIndex) }+        refreshLive()+    }++    override fun showBrief(show: Boolean) = update { it.copy(showBrief = show) }++    override fun showChipInfo(chip: ChipSpec?) = update { it.copy(infoChip = chip) }++    override fun dismissWin() = update { it.copy(won = false) }++    override fun renamePin(id: NodeId, name: String) {+        val s = _state.value ?: return+        if (s.sandbox != null) commit(s.board.renamePin(id, name))+    }++    override fun renameComponent(name: String, group: String) {+        val s = _state.value ?: return+        val mode = s.sandbox ?: return+        val next = mode.copy(name = name.trim().ifEmpty { mode.name }, group = group.trim().ifEmpty { mode.group })+        if (next == mode) return+        update { it.copy(mode = next) }+        _state.value?.let(persist)+    }++    private fun commit(next: Board) {+        val s = _state.value ?: return+        if (next == s.board) return+        history.addLast(s.board)+        if (history.size > UNDO_LIMIT) history.removeFirst()+        future.clear()+        show(s, next)+    }++    private fun show(s: GameUiState, board: Board) {+        val selection = when (val sel = s.selection) {+            is Selection.OfNode -> sel.takeIf { board.circuit.node(it.id) != null }+            is Selection.OfWire -> sel.takeIf { it.wire in board.circuit.wires }+            null -> null+        }+        val next = s.copy(+            board = board,+            manualInputs = carryInputs(s, board),+            selection = selection,+            canUndo = history.isNotEmpty(),+            canRedo = future.isNotEmpty(),+            cost = cost(s, board.circuit),+        )+        _state.value = next+        persist(next)+        if (next.level != null) reverify(announce = true) else refreshLive()+    }++    private fun reverify(announce: Boolean) {+        val s = _state.value ?: return+        val level = s.level ?: return+        verifyJob?.cancel()+        verifyJob = scope.launch {+            delay(VERIFY_DEBOUNCE_MS)+            val result = withContext(compute) { Verifier.verify(s.io, level.tests, s.circuit, s.catalog::get) }+            val now = _state.value?.takeIf { it.circuit == s.circuit } ?: return@launch+            val probed = now.copy(verify = result, probeCase = now.probeCase?.takeIf { it < result.total })+            val live = withContext(compute) { liveProbe(probed) }+            applyVerify(probed, result, live, announce)+        }+    }++    private fun applyVerify(probed: GameUiState, result: VerifyResult, live: Probe, announce: Boolean) {+        val level = probed.level ?: return+        val newlySolved = announce && result.solved && !wasSolved+        wasSolved = result.solved+        _state.update { cur ->+            if (cur?.circuit != probed.circuit) return@update cur+            cur.copy(+                verify = result,+                probeCase = probed.probeCase,+                live = if (cur.sameProbe(probed)) live else cur.live,+                stars = Scoring.stars(result.solved, cur.cost, level.par),+                won = cur.won || newlySolved,+            )+        }+        if (result.solved) solved(probed)+    }++    private fun refreshLive() {+        val s = _state.value ?: return+        liveJob?.cancel()+        liveJob = scope.launch {+            val live = withContext(compute) { liveProbe(s) }+            _state.update { cur ->+                if (cur?.circuit == s.circuit && cur.sameProbe(s)) cur.copy(live = live) else cur+            }+        }+    }++    private companion object {+        const val UNDO_LIMIT = 50+        const val VERIFY_DEBOUNCE_MS = 120L+    }+}++/** NAND cost of [circuit] with [s]'s chips. */+internal fun cost(s: GameUiState, circuit: Circuit): Int = Scoring.cost(circuit) { s.catalog[it]?.nandCost }++private fun liveProbe(s: GameUiState): Probe {+    val case = s.probeCase+    val level = s.level+    return if (level != null && case != null && case < (s.verify?.total ?: 0)) {+        Verifier.probe(s.io, level.tests, s.circuit, case, s.catalog::get)+    } else {+        Verifier.manual(s.io, s.circuit, s.manualInputs, s.catalog::get)+    }+}++private fun GameUiState.sameProbe(other: GameUiState) =+    probeCase == other.probeCase && manualInputs == other.manualInputs++/** Keeps each input node's manual value across edits that add, remove or reindex inputs. */+private fun carryInputs(s: GameUiState, board: Board): List<Int> {+    val byNode = s.circuit.nodes.filterIsInstance<LevelInput>()+        .associate { it.id to s.manualInputs.getOrElse(it.index) { 0 } }+    val values = IntArray(board.io.inputs.size)+    for (n in board.circuit.nodes) {+        if (n is LevelInput && n.index in values.indices) values[n.index] = byNode[n.id] ?: 0+    }+    return values.toList()+}
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/LogicUiContract.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/LogicUiContract.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/LogicUiContract.ktindex bb903f6c42..2eeaa5353e 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/LogicUiContract.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/LogicUiContract.kt@@ -3,8 +3,13 @@ package com.vayunmathur.games.logicgate.platform import androidx.annotation.StringRes import com.vayunmathur.games.logicgate.domain.levels.Chapter import com.vayunmathur.games.logicgate.domain.levels.LevelDef+import com.vayunmathur.games.logicgate.domain.levels.TrayGroup+import com.vayunmathur.games.logicgate.domain.levels.TraySection+import com.vayunmathur.games.logicgate.domain.model.Board+import com.vayunmathur.games.logicgate.domain.model.ChipCatalog import com.vayunmathur.games.logicgate.domain.model.ChipSpec import com.vayunmathur.games.logicgate.domain.model.Circuit+import com.vayunmathur.games.logicgate.domain.model.LevelIo import com.vayunmathur.games.logicgate.domain.model.NodeId import com.vayunmathur.games.logicgate.domain.model.PinRef import com.vayunmathur.games.logicgate.domain.model.Point@@ -36,6 +41,31 @@ data class ProgressionUiState(val levels: List<LevelCard> = emptyList()) {     val solved: Int get() = levels.count { it.completed } } +/** One component on the sandbox list. [cost] is null for a component that contains itself. */+data class ComponentCard(+    val id: String,+    val name: String,+    val group: String,+    val inputs: Int,+    val outputs: Int,+    val cost: Int?,+)++/** The sandbox list, components grouped by the player's group names. */+data class SandboxUiState(val components: List<ComponentCard> = emptyList()) {+    val groups: List<Pair<String, List<ComponentCard>>>+        get() = components.groupBy { it.group }.toSortedMap(String.CASE_INSENSITIVE_ORDER).toList()+}++/** What the editor is editing. */+sealed interface EditorMode {+    /** A Computer level, checked against its tests. */+    data class Level(val def: LevelDef) : EditorMode++    /** A sandbox component the player names, files under [group], and gives its own pins. */+    data class Sandbox(val id: String, val name: String, val group: String) : EditorMode+}+ /** What is selected on the canvas. */ sealed interface Selection {     /** A gate. */@@ -45,12 +75,16 @@ sealed interface Selection {     data class OfWire(val wire: Wire) : Selection } -/** Everything the editor draws for one level. */+/** Everything the editor draws for one level or sandbox component. */ data class GameUiState(-    val level: LevelDef,-    val circuit: Circuit,+    val mode: EditorMode,+    val board: Board,+    val catalog: ChipCatalog,     val chips: List<ChipSpec>,     val manualInputs: List<Int>,+    /** [chips] split into tray tabs, and the tab to open first. */+    val tray: List<TraySection> = emptyList(),+    val defaultGroup: TrayGroup? = null,     val selection: Selection? = null,     val verify: VerifyResult? = null,     val probeCase: Int? = null,@@ -67,7 +101,12 @@ data class GameUiState(     /** Bumped when the canvas should frame the whole circuit, e.g. on opening a level. */     val fitToken: Int = 0,     val nextLevelId: String? = null,-)+) {+    val circuit: Circuit get() = board.circuit+    val io: LevelIo get() = board.io+    val level: LevelDef? get() = (mode as? EditorMode.Level)?.def+    val sandbox: EditorMode.Sandbox? get() = mode as? EditorMode.Sandbox+}  /** Editor callbacks. Every method has a no-op default so a preview needs only [Noop]. */ interface LogicActions {@@ -84,6 +123,8 @@ interface LogicActions {     fun showBrief(show: Boolean) {}     fun showChipInfo(chip: ChipSpec?) {}     fun dismissWin() {}+    fun renamePin(id: NodeId, name: String) {}+    fun renameComponent(name: String, group: String) {}      /** Ready-made instances. */     companion object {
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/LogicViewModel.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/LogicViewModel.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/LogicViewModel.ktindex 583e7672a8..9e33d3c134 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/LogicViewModel.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/platform/LogicViewModel.kt@@ -4,41 +4,44 @@ import android.app.Application import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.vayunmathur.games.logicgate.data.CircuitStore+import com.vayunmathur.games.logicgate.data.ComponentStore import com.vayunmathur.games.logicgate.data.ProgressStore+import com.vayunmathur.games.logicgate.domain.levels.Chapter+import com.vayunmathur.games.logicgate.domain.levels.ChipGroups import com.vayunmathur.games.logicgate.domain.levels.LevelDef import com.vayunmathur.games.logicgate.domain.levels.LevelRegistry+import com.vayunmathur.games.logicgate.domain.levels.TrayGroup+import com.vayunmathur.games.logicgate.domain.model.Board+import com.vayunmathur.games.logicgate.domain.model.ChipCatalog import com.vayunmathur.games.logicgate.domain.model.ChipSpec-import com.vayunmathur.games.logicgate.domain.model.Chips import com.vayunmathur.games.logicgate.domain.model.Circuit-import com.vayunmathur.games.logicgate.domain.model.NodeId-import com.vayunmathur.games.logicgate.domain.model.PinRef-import com.vayunmathur.games.logicgate.domain.model.Point-import com.vayunmathur.games.logicgate.domain.sim.Probe+import com.vayunmathur.games.logicgate.domain.model.CustomChip+import com.vayunmathur.games.logicgate.domain.model.PinChips+import com.vayunmathur.games.logicgate.domain.model.pinRemap+import com.vayunmathur.games.logicgate.domain.model.remapChipPins import com.vayunmathur.games.logicgate.domain.sim.Scoring-import com.vayunmathur.games.logicgate.domain.sim.Verifier-import com.vayunmathur.games.logicgate.domain.sim.VerifyResult import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.Job-import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow-import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext+import java.util.UUID  /**- * Owns progression and the open level's editor: an undo/redo stack of immutable circuits, and a- * debounced re-verification on [compute] after every committed edit, cancelling any older run.+ * Owns progression, the player's sandbox components, and the open [editor]. Components are kept+ * in memory and saved as a whole; when an edit moves a component's pins, every circuit that uses+ * it is rewired to follow.  */ class LogicViewModel @JvmOverloads constructor(     application: Application,-    private val compute: CoroutineDispatcher = Dispatchers.Default,+    compute: CoroutineDispatcher = Dispatchers.Default,     private val io: CoroutineDispatcher = Dispatchers.IO,-) : AndroidViewModel(application), LogicActions {+) : AndroidViewModel(application) {      private val circuits = CircuitStore(application, io)+    private val components = ComponentStore(application, io)     private val progress = ProgressStore(application)      val achievementsManager: LogicAchievements = LogicAchievements(@@ -47,21 +50,25 @@ class LogicViewModel @JvmOverloads constructor(         progress,     ) +    val editor = EditorSession(viewModelScope, compute, ::persist, ::recordSolve)+    val game: StateFlow<GameUiState?> = editor.state+     private val _progression = MutableStateFlow(ProgressionUiState())     val progression: StateFlow<ProgressionUiState> = _progression.asStateFlow() -    private val _game = MutableStateFlow<GameUiState?>(null)-    val game: StateFlow<GameUiState?> = _game.asStateFlow()+    private val _sandbox = MutableStateFlow(SandboxUiState())+    val sandbox: StateFlow<SandboxUiState> = _sandbox.asStateFlow()++    private val _catalog = MutableStateFlow(ChipCatalog.Builtin)+    val catalog: StateFlow<ChipCatalog> = _catalog.asStateFlow() -    private val history = ArrayDeque<Circuit>()-    private val future = ArrayDeque<Circuit>()-    private var verifyJob: Job? = null-    private var liveJob: Job? = null-    private var wasSolved = false+    private var completed: Set<String> = emptySet()     private var fitToken = 0+    private var justCreated: String? = null      init {         viewModelScope.launch {+            setCustoms(withContext(io) { components.load() }, save = false)             refreshProgression()             withContext(io) { achievementsManager.checkExistingAchievements() }         }@@ -70,165 +77,121 @@ class LogicViewModel @JvmOverloads constructor(     fun dismissAchievement() = achievementsManager.dismissNotification()      fun openLevel(id: String) {-        if (_game.value?.level?.id == id) return+        if (game.value?.level?.id == id) return         val level = LevelRegistry[id] ?: return-        verifyJob?.cancel()-        liveJob?.cancel()-        history.clear()-        future.clear()-        _game.value = null+        editor.open(null)         viewModelScope.launch {             val saved = withContext(io) { circuits.load(id) }             val firstVisit = withContext(io) { progress.markBriefSeen(id) }-            val circuit = (saved ?: Circuit.forLevel(level.io)).sanitized(level.io, Chips.lookup(level.io))-            _game.value = GameUiState(-                level = level,-                circuit = circuit,-                chips = LevelRegistry.allowedChips(id).mapNotNull { Chips[it] },+            val catalog = _catalog.value+            val circuit = (saved ?: Circuit.forLevel(level.io)).sanitized(level.io, catalog.lookup(level.io))+            val chips = levelChips(level, catalog)+            val state = GameUiState(+                mode = EditorMode.Level(level),+                board = Board(circuit, level.io),+                catalog = catalog,+                chips = chips,                 manualInputs = List(level.inputs.size) { 0 },-                cost = cost(circuit),+                tray = ChipGroups.sections(chips, catalog),+                defaultGroup = TrayGroup.Builtin(level.chapter),                 bestCost = _progression.value.levels.firstOrNull { it.id == id }?.bestCost,                 showBrief = firstVisit,                 fitToken = ++fitToken,                 nextLevelId = LevelRegistry.next(id)?.id,             )-            wasSolved = false-            reverify(announce = false)+            editor.open(state.copy(cost = cost(state, circuit)))         }     } -    override fun placeChip(chipId: String, at: Point) {-        val s = _game.value ?: return-        if (s.chips.any { it.id == chipId }) commit(s.circuit.addGate(chipId, at).first)-    }--    override fun moveNode(id: NodeId, to: Point) {-        val s = _game.value ?: return-        commit(s.circuit.moveNode(id, to))+    /** Opens sandbox component [id] in the editor. */+    fun openComponent(id: String) {+        if (game.value?.sandbox?.id == id) return+        val catalog = _catalog.value+        val chip = catalog.custom(id) ?: return+        val pins = chip.board.io+        val board = chip.board.copy(circuit = chip.board.circuit.sanitized(pins, catalog.lookup(pins)))+        val chips = sandboxChips(id, catalog)+        val state = GameUiState(+            mode = EditorMode.Sandbox(id, chip.name, chip.group),+            board = board,+            catalog = catalog,+            chips = chips,+            manualInputs = List(board.io.inputs.size) { 0 },+            tray = ChipGroups.sections(chips, catalog),+            defaultGroup = TrayGroup.Builtin(Chapter.BASICS),+            showBrief = id == justCreated,+            fitToken = ++fitToken,+        )+        justCreated = null+        editor.open(state.copy(cost = cost(state, board.circuit)))     } -    override fun connect(a: PinRef, b: PinRef) {-        val s = _game.value ?: return-        s.circuit.connect(a, b, Chips.lookup(s.level.io))?.let(::commit)+    /** Adds an empty component named [name] in [group] and returns its id. */+    fun createComponent(name: String, group: String): String {+        val id = CustomChip.PREFIX + UUID.randomUUID()+        val chip = CustomChip(id, name.trim(), group.trim().ifEmpty { CustomChip.DEFAULT_GROUP }, Board.Empty)+        setCustoms(_catalog.value.customs + chip)+        justCreated = id+        return id     } -    override fun select(selection: Selection?) {-        _game.update { it?.copy(selection = selection) }+    /** Deletes component [id]; any copies of it on other boards drop out as unknown chips. */+    fun deleteComponent(id: String) {+        if (game.value?.sandbox?.id == id) editor.open(null)+        setCustoms(_catalog.value.customs.filterNot { it.id == id })     } -    override fun deleteSelection() {-        val s = _game.value ?: return-        val next = when (val sel = s.selection) {-            is Selection.OfNode -> s.circuit.removeNode(sel.id)-            is Selection.OfWire -> s.circuit.removeWire(sel.wire)-            null -> return+    private fun persist(state: GameUiState) {+        when (val mode = state.mode) {+            is EditorMode.Level -> circuits.save(mode.def.id, state.circuit)+            is EditorMode.Sandbox -> saveComponent(CustomChip(mode.id, mode.name, mode.group, state.board))         }-        _game.update { it?.copy(selection = null) }-        commit(next)-    }--    override fun deleteNode(id: NodeId) {-        val s = _game.value ?: return-        commit(s.circuit.removeNode(id))-    }--    override fun undo() {-        val s = _game.value ?: return-        val previous = history.removeLastOrNull() ?: return-        future.addLast(s.circuit)-        show(s, previous)-    }--    override fun redo() {-        val s = _game.value ?: return-        val next = future.removeLastOrNull() ?: return-        history.addLast(s.circuit)-        show(s, next)     } -    override fun setInput(index: Int, value: Int) {-        _game.update { s ->-            s?.copy(manualInputs = s.manualInputs.mapIndexed { i, v -> if (i == index) value else v }, probeCase = null)+    private fun saveComponent(chip: CustomChip) {+        val old = _catalog.value.custom(chip.id) ?: return+        val remap = pinRemap(old, chip)+        val customs = _catalog.value.customs.map { c ->+            when {+                c.id == chip.id -> chip+                remap != null -> c.copy(board = c.board.copy(circuit = c.board.circuit.remapChipPins(chip.id, remap)))+                else -> c+            }+        }+        setCustoms(customs)+        if (remap != null) {+            viewModelScope.launch(io) { circuits.rewriteAll { it.remapChipPins(chip.id, remap) } }         }-        refreshLive()-    }--    override fun probe(caseIndex: Int?) {-        _game.update { it?.copy(probeCase = caseIndex) }-        refreshLive()-    }--    override fun showBrief(show: Boolean) {-        _game.update { it?.copy(showBrief = show) }-    }--    override fun showChipInfo(chip: ChipSpec?) {-        _game.update { it?.copy(infoChip = chip) }-    }--    override fun dismissWin() {-        _game.update { it?.copy(won = false) }     } -    private fun commit(next: Circuit) {-        val s = _game.value ?: return-        if (next == s.circuit) return-        history.addLast(s.circuit)-        if (history.size > UNDO_LIMIT) history.removeFirst()-        future.clear()-        show(s, next)-    }+    private fun Circuit.remapChipPins(chipId: String, remap: Pair<IntArray, IntArray>) =+        remapChipPins(chipId, remap.first, remap.second) -    private fun show(s: GameUiState, circuit: Circuit) {-        val selection = when (val sel = s.selection) {-            is Selection.OfNode -> sel.takeIf { circuit.node(it.id) != null }-            is Selection.OfWire -> sel.takeIf { it.wire in circuit.wires }-            null -> null-        }-        _game.value = s.copy(-            circuit = circuit,-            selection = selection,-            canUndo = history.isNotEmpty(),-            canRedo = future.isNotEmpty(),-            cost = cost(circuit),+    private fun setCustoms(customs: List<CustomChip>, save: Boolean = true) {+        val catalog = ChipCatalog(customs)+        _catalog.value = catalog+        if (save) components.save(customs)+        _sandbox.value = SandboxUiState(+            customs.map { c ->+                ComponentCard(c.id, c.name, c.group, c.inputs.size, c.outputs.size, catalog[c.id]?.nandCost)+            },         )-        circuits.save(s.level.id, circuit)-        reverify(announce = true)     } -    private fun reverify(announce: Boolean) {-        val s = _game.value ?: return-        verifyJob?.cancel()-        verifyJob = viewModelScope.launch {-            delay(VERIFY_DEBOUNCE_MS)-            val result = withContext(compute) { Verifier.verify(s.level.io, s.level.tests, s.circuit) }-            val now = _game.value?.takeIf { it.circuit == s.circuit } ?: return@launch-            val probed = now.copy(verify = result, probeCase = now.probeCase?.takeIf { it < result.total })-            val live = withContext(compute) { liveProbe(probed) }-            applyVerify(probed, result, live, announce)-        }-    }+    private fun levelChips(level: LevelDef, catalog: ChipCatalog): List<ChipSpec> =+        (LevelRegistry.allowedChips(level.id) + catalog.customs.map { it.id }).mapNotNull { catalog[it] } -    private fun applyVerify(probed: GameUiState, result: VerifyResult, live: Probe, announce: Boolean) {-        val newlySolved = announce && result.solved && !wasSolved-        wasSolved = result.solved-        _game.update { cur ->-            if (cur?.circuit != probed.circuit) return@update cur-            cur.copy(-                verify = result,-                probeCase = probed.probeCase,-                live = if (cur.sameProbe(probed)) live else cur.live,-                stars = Scoring.stars(result.solved, cur.cost, cur.level.par),-                won = cur.won || newlySolved,-            )-        }-        if (result.solved) recordSolve(probed.level, probed.cost)+    /** Unlocked built-ins, pins, and every component that does not contain [id]. */+    private fun sandboxChips(id: String, catalog: ChipCatalog): List<ChipSpec> {+        val customs = catalog.customs.filterNot { catalog.uses(it.id, id) }.map { it.id }+        return (LevelRegistry.unlockedChips(completed) + customs).mapNotNull { catalog[it] } + PinChips.all     } -    private fun recordSolve(level: LevelDef, cost: Int) {+    private fun recordSolve(state: GameUiState) {+        val level = state.level ?: return         viewModelScope.launch {             withContext(io) {-                progress.record(level.id, cost)+                progress.record(level.id, state.cost)                 achievementsManager.checkExistingAchievements()             }             refreshProgression()@@ -237,6 +200,7 @@ class LogicViewModel @JvmOverloads constructor(      private suspend fun refreshProgression() {         val best = withContext(io) { progress.bestCosts() }+        completed = best.keys         _progression.value = ProgressionUiState(             LevelRegistry.levels.mapIndexed { i, l ->                 LevelCard(@@ -251,37 +215,6 @@ class LogicViewModel @JvmOverloads constructor(                 )             },         )-        _game.update { s -> s?.copy(bestCost = best[s.level.id]) }-    }--    private fun refreshLive() {-        val s = _game.value ?: return-        liveJob?.cancel()-        liveJob = viewModelScope.launch {-            val live = withContext(compute) { liveProbe(s) }-            _game.update { cur ->-                if (cur?.circuit == s.circuit && cur.sameProbe(s)) cur.copy(live = live) else cur-            }-        }-    }--    private fun liveProbe(s: GameUiState): Probe {-        val case = s.probeCase-        val total = s.verify?.total ?: 0-        return if (case != null && case < total) {-            Verifier.probe(s.level.io, s.level.tests, s.circuit, case)-        } else {-            Verifier.manual(s.level.io, s.circuit, s.manualInputs)-        }-    }--    private fun GameUiState.sameProbe(other: GameUiState) =-        probeCase == other.probeCase && manualInputs == other.manualInputs--    private fun cost(circuit: Circuit) = Scoring.cost(circuit) { Chips[it]?.nandCost }--    private companion object {-        const val UNDO_LIMIT = 50-        const val VERIFY_DEBOUNCE_MS = 120L+        editor.update { s -> s.level?.let { s.copy(bestCost = best[it.id]) } ?: s }     } }
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/ChipInfoSheet.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/ChipInfoSheet.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/ChipInfoSheet.ktindex 9834c7a84c..9a32c13dbf 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/ChipInfoSheet.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/ChipInfoSheet.kt@@ -19,11 +19,11 @@ import com.vayunmathur.library.ui.Spacing import com.vayunmathur.library.ui.Text  /**- * What a tray chip is and how it behaves, opened by tapping its card. [onAdd] places it on the- * board — the same thing tapping the card used to do directly.+ * What a tray chip is and how it behaves, opened by tapping its card. [group] is set for a+ * component the player built. [onAdd] places it on the board.  */ @Composable-fun ChipInfoSheet(chip: ChipSpec, onAdd: () -> Unit, onDismiss: () -> Unit) {+fun ChipInfoSheet(chip: ChipSpec, group: String?, onAdd: () -> Unit, onDismiss: () -> Unit) {     ModalBottomSheet(onDismissRequest = onDismiss) {         Column(             Modifier@@ -39,7 +39,9 @@ fun ChipInfoSheet(chip: ChipSpec, onAdd: () -> Unit, onDismiss: () -> Unit) {                 style = MaterialTheme.typography.labelLarge,                 color = MaterialTheme.colorScheme.onSurfaceVariant,             )-            ChipInfo.blurb(chip.id)?.let { Text(stringResource(it), style = MaterialTheme.typography.bodyLarge) }+            val blurb = ChipInfo.blurb(chip.id)?.let { stringResource(it) }+                ?: group?.let { stringResource(R.string.lg_chip_custom_info, it) }+            blurb?.let { Text(it, style = MaterialTheme.typography.bodyLarge) }             PinLine(stringResource(R.string.lg_brief_inputs), chip.inputs)             PinLine(stringResource(R.string.lg_brief_outputs), chip.outputs)             Button(onClick = onAdd, modifier = Modifier.fillMaxWidth()) { Text(stringResource(R.string.lg_add_to_board)) }
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/ChipLabels.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/ChipLabels.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/ChipLabels.ktindex 1eb3dcdf21..fd5c65e7f8 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/ChipLabels.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/ChipLabels.kt@@ -1,21 +1,28 @@ package com.vayunmathur.games.logicgate.ui  import androidx.compose.runtime.Composable+import androidx.compose.runtime.compositionLocalOf import androidx.compose.runtime.remember import androidx.compose.ui.platform.LocalResources import androidx.compose.ui.res.stringResource import com.vayunmathur.games.logicgate.domain.model.ChipInfo import com.vayunmathur.games.logicgate.domain.model.Chips+import com.vayunmathur.games.logicgate.domain.model.PinChips -/** The localized name of [chipId], falling back to the id. */+/** The player's component names by chip id, provided once at the root. */+val LocalChipNames = compositionLocalOf<Map<String, String>> { emptyMap() }++/** The localized name of [chipId] (or the player's name for a component), falling back to the id. */ @Composable-fun chipLabel(chipId: String): String = ChipInfo.label(chipId)?.let { stringResource(it) } ?: chipId+fun chipLabel(chipId: String): String =+    LocalChipNames.current[chipId] ?: ChipInfo.label(chipId)?.let { stringResource(it) } ?: chipId -/** Every chip's localized name by id, for measuring and drawing outside composition. */+/** Every chip's displayed name by id, for measuring and drawing outside composition. */ @Composable fun rememberChipLabels(): Map<String, String> {     val resources = LocalResources.current-    return remember(resources) {-        Chips.all.associate { chip -> chip.id to (ChipInfo.label(chip.id)?.let(resources::getString) ?: chip.id) }+    val custom = LocalChipNames.current+    return remember(resources, custom) {+        (Chips.all + PinChips.all).associate { chip -> chip.id to (ChipInfo.label(chip.id)?.let(resources::getString) ?: chip.id) } + custom     } }
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/ChipTray.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/ChipTray.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/ChipTray.ktindex d372bddc75..398ee3e4e5 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/ChipTray.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/ChipTray.kt@@ -18,6 +18,7 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember+import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier@@ -32,7 +33,11 @@ import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import com.vayunmathur.games.logicgate.R+import com.vayunmathur.games.logicgate.domain.levels.Chapter+import com.vayunmathur.games.logicgate.domain.levels.TrayGroup+import com.vayunmathur.games.logicgate.domain.levels.TraySection import com.vayunmathur.games.logicgate.domain.model.ChipSpec+import com.vayunmathur.library.ui.FilterChip import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Spacing import com.vayunmathur.library.ui.Surface@@ -43,29 +48,72 @@ import kotlin.math.abs data class TrayDrag(val chipId: String, val root: Offset)  /**- * The chip palette. Pull a card up onto the board to place it where you let go, or tap it to open- * its info sheet (which can also place it). Sideways swipes scroll the row.+ * The chip palette, one tab per [TraySection] (opening on [defaultGroup]). Pull a card up onto the+ * board to place it where you let go, or tap it to open its info sheet (which can also place it).+ * Sideways swipes scroll the row.  */ @Composable fun ChipTray(-    chips: List<ChipSpec>,+    sections: List<TraySection>,+    defaultGroup: TrayGroup?,     onTap: (String) -> Unit,     onDragUpdate: (TrayDrag?) -> Unit,     onDrop: (TrayDrag) -> Unit,     modifier: Modifier = Modifier, ) {+    var selectedKey by rememberSaveable { mutableStateOf(defaultGroup?.let(::groupKey)) }+    val current = sections.firstOrNull { groupKey(it.group) == selectedKey }+        ?: sections.firstOrNull { it.group == defaultGroup }+        ?: sections.firstOrNull()     Surface(modifier.fillMaxWidth(), color = MaterialTheme.colorScheme.surfaceContainer) {-        LazyRow(-            contentPadding = PaddingValues(horizontal = Spacing.md, vertical = Spacing.sm),-            horizontalArrangement = Arrangement.spacedBy(Spacing.sm),-        ) {-            items(chips, key = { it.id }) { chip ->-                ChipCard(chip, onTap, onDragUpdate, onDrop)+        Column {+            if (sections.size > 1) {+                LazyRow(+                    contentPadding = PaddingValues(start = Spacing.md, end = Spacing.md, top = Spacing.xs),+                    horizontalArrangement = Arrangement.spacedBy(Spacing.sm),+                ) {+                    items(sections, key = { groupKey(it.group) }) { section ->+                        FilterChip(+                            selected = section == current,+                            onClick = { selectedKey = groupKey(section.group) },+                            label = { Text(groupLabel(section.group)) },+                        )+                    }+                }+            }+            LazyRow(+                contentPadding = PaddingValues(horizontal = Spacing.md, vertical = Spacing.sm),+                horizontalArrangement = Arrangement.spacedBy(Spacing.sm),+            ) {+                items(current?.chips.orEmpty(), key = { it.id }) { chip ->+                    ChipCard(chip, onTap, onDragUpdate, onDrop)+                }             }         }     } } +private fun groupKey(group: TrayGroup): String = when (group) {+    TrayGroup.Pins -> "pins"+    is TrayGroup.Builtin -> "builtin:" + group.chapter.name+    is TrayGroup.Custom -> "custom:" + group.name+}++@Composable+private fun groupLabel(group: TrayGroup): String = when (group) {+    TrayGroup.Pins -> stringResource(R.string.lg_group_pins)+    is TrayGroup.Custom -> group.name+    is TrayGroup.Builtin -> stringResource(+        when (group.chapter) {+            Chapter.BASICS -> R.string.lg_chapter_basics+            Chapter.ROUTING -> R.string.lg_chapter_routing+            Chapter.ARITHMETIC -> R.string.lg_chapter_arithmetic+            Chapter.MEMORY -> R.string.lg_chapter_memory+            Chapter.CPU -> R.string.lg_chapter_cpu+        },+    )+}+ @Composable private fun ChipCard(     chip: ChipSpec,
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/CircuitCanvas.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/CircuitCanvas.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/CircuitCanvas.ktindex 79f76b73c9..caf48405f1 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/CircuitCanvas.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/CircuitCanvas.kt@@ -72,7 +72,7 @@ fun CircuitCanvas(     val haptics = rememberHaptics()     val resources = LocalResources.current     val scope = rememberCoroutineScope()-    val lookup = remember(state.level) { Chips.lookup(state.level.io) }+    val lookup = remember(state.catalog, state.io) { state.catalog.lookup(state.io) }     val controller = remember(cameraState, trash) { CanvasController(cameraState, density, trash) }     val shake = remember { Animatable(0f) }     var shakePin by remember { mutableStateOf<PinRef?>(null) }@@ -152,9 +152,10 @@ fun CircuitCanvas(     }      editingInput?.let { i ->+        val pin = state.io.inputs.getOrNull(i) ?: return@let         BusValueDialog(-            pin = state.level.inputs[i],-            value = state.manualInputs[i],+            pin = pin,+            value = state.manualInputs.getOrElse(i) { 0 },             onValue = { actions.setInput(i, it) },             onDismiss = { editingInput = null },         )
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/ComponentPage.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/ComponentPage.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/ComponentPage.ktnew file mode 100644index 0000000000..974fd5181e--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/ComponentPage.kt@@ -0,0 +1,40 @@+package com.vayunmathur.games.logicgate.ui++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import com.vayunmathur.games.logicgate.Route+import com.vayunmathur.games.logicgate.platform.LogicViewModel+import com.vayunmathur.library.ui.CircularProgressIndicator+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.util.NavBackStack++/** Opens sandbox component [componentId] in [LogicViewModel] and binds it to [GameScreen]. */+@Composable+fun ComponentPage(backStack: NavBackStack<Route>, viewModel: LogicViewModel, componentId: String) {+    LaunchedEffect(componentId) { viewModel.openComponent(componentId) }+    val game by viewModel.game.collectAsState()+    val state = game+    if (state == null || state.sandbox?.id != componentId) {+        Box(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background), contentAlignment = Alignment.Center) {+            CircularProgressIndicator()+        }+        return+    }+    GameScreen(+        state = state,+        actions = viewModel.editor,+        onBack = { backStack.pop() },+        onNext = {},+        onDelete = {+            backStack.pop()+            viewModel.deleteComponent(componentId)+        },+    )+}
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/ComponentSheet.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/ComponentSheet.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/ComponentSheet.ktnew file mode 100644index 0000000000..dff8322d93--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/ComponentSheet.kt@@ -0,0 +1,161 @@+package com.vayunmathur.games.logicgate.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyRow+import androidx.compose.foundation.lazy.items+import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.verticalScroll+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateMapOf+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.saveable.rememberSaveable+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.semantics+import com.vayunmathur.games.logicgate.R+import com.vayunmathur.games.logicgate.domain.model.Board+import com.vayunmathur.games.logicgate.domain.model.CustomChip+import com.vayunmathur.games.logicgate.domain.model.LevelInput+import com.vayunmathur.games.logicgate.domain.model.LevelOutput+import com.vayunmathur.games.logicgate.domain.model.Node+import com.vayunmathur.games.logicgate.domain.model.NodeId+import com.vayunmathur.games.logicgate.domain.model.Pin+import com.vayunmathur.games.logicgate.platform.GameUiState+import com.vayunmathur.games.logicgate.platform.LogicActions+import com.vayunmathur.library.ui.AssistChip+import com.vayunmathur.library.ui.Button+import com.vayunmathur.library.ui.ConfirmDialog+import com.vayunmathur.library.ui.IconButton+import com.vayunmathur.library.ui.IconDelete+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.ModalBottomSheet+import com.vayunmathur.library.ui.OutlinedTextField+import com.vayunmathur.library.ui.Spacing+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton++/**+ * A sandbox component's details: its name and group (with the player's other groups one tap+ * away), its pins in chip order with rename and delete, and deleting the whole component. Name,+ * group and pin names are applied when the sheet closes.+ */+@Composable+fun ComponentSheet(state: GameUiState, actions: LogicActions, onDelete: () -> Unit, onDismiss: () -> Unit) {+    val mode = state.sandbox ?: return+    var name by rememberSaveable(mode.id) { mutableStateOf(mode.name) }+    var group by rememberSaveable(mode.id) { mutableStateOf(mode.group) }+    val pinNames = remember(mode.id) { mutableStateMapOf<NodeId, String>() }+    var confirmDelete by remember { mutableStateOf(false) }+    val groups = remember(state.catalog) { state.catalog.customs.map { it.group }.distinct().sorted() }+    val chip = CustomChip(mode.id, mode.name, mode.group, state.board)+    val pins: List<Node> = chip.inputNodes + chip.outputNodes++    fun close() {+        actions.renameComponent(name, group)+        for ((id, pinName) in pinNames) actions.renamePin(id, pinName)+        onDismiss()+    }++    ModalBottomSheet(onDismissRequest = ::close) {+        Column(+            Modifier+                .fillMaxWidth()+                .verticalScroll(rememberScrollState())+                .padding(horizontal = Spacing.xl)+                .padding(bottom = Spacing.xl),+            verticalArrangement = Arrangement.spacedBy(Spacing.md),+        ) {+            OutlinedTextField(+                value = name,+                onValueChange = { name = it },+                label = { Text(stringResource(R.string.lg_component_name)) },+                singleLine = true,+                modifier = Modifier.fillMaxWidth(),+            )+            OutlinedTextField(+                value = group,+                onValueChange = { group = it },+                label = { Text(stringResource(R.string.lg_component_group)) },+                singleLine = true,+                modifier = Modifier.fillMaxWidth(),+            )+            if (groups.size > 1 || groups.singleOrNull() != group) {+                LazyRow(horizontalArrangement = Arrangement.spacedBy(Spacing.sm)) {+                    items(groups) { g -> AssistChip(onClick = { group = g }, label = { Text(g) }) }+                }+            }+            Text(stringResource(R.string.lg_component_pins), style = MaterialTheme.typography.titleMedium)+            Text(+                stringResource(R.string.lg_component_pins_hint),+                style = MaterialTheme.typography.bodySmall,+                color = MaterialTheme.colorScheme.onSurfaceVariant,+            )+            if (pins.isEmpty()) Text(stringResource(R.string.lg_component_no_pins), style = MaterialTheme.typography.bodyMedium)+            for (node in pins) {+                val pin = pinOf(state.board, node) ?: continue+                PinRow(+                    node = node,+                    pin = pin,+                    value = pinNames[node.id] ?: pin.name,+                    onValue = { pinNames[node.id] = it.take(Board.MAX_PIN_NAME) },+                    onDelete = {+                        pinNames.remove(node.id)+                        actions.deleteNode(node.id)+                    },+                )+            }+            Button(onClick = ::close, modifier = Modifier.fillMaxWidth()) { Text(stringResource(R.string.lg_done)) }+            TextButton(onClick = { confirmDelete = true }, modifier = Modifier.fillMaxWidth()) {+                Text(stringResource(R.string.lg_component_delete), color = MaterialTheme.colorScheme.error)+            }+        }+    }+    if (confirmDelete) {+        ConfirmDialog(+            title = stringResource(R.string.lg_component_delete_title, mode.name),+            message = stringResource(R.string.lg_component_delete_message),+            confirmLabel = stringResource(R.string.lg_delete),+            destructive = true,+            onConfirm = {+                confirmDelete = false+                onDismiss()+                onDelete()+            },+            onDismiss = { confirmDelete = false },+        )+    }+}++@Composable+private fun PinRow(node: Node, pin: Pin, value: String, onValue: (String) -> Unit, onDelete: () -> Unit) {+    val kind = stringResource(if (node is LevelInput) R.string.lg_chip_input_label else R.string.lg_chip_output_label)+    val badge = if (pin.width > 1) " · " + stringResource(R.string.lg_bus_badge, pin.width) else ""+    val deleteDescription = stringResource(R.string.lg_cd_delete_pin, value)+    Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(Spacing.sm)) {+        OutlinedTextField(+            value = value,+            onValueChange = onValue,+            label = { Text(kind + badge) },+            singleLine = true,+            modifier = Modifier.weight(1f),+        )+        IconButton(onClick = onDelete, modifier = Modifier.semantics { contentDescription = deleteDescription }) {+            IconDelete(tint = MaterialTheme.colorScheme.error)+        }+    }+}++private fun pinOf(board: Board, node: Node): Pin? = when (node) {+    is LevelInput -> board.io.inputs.getOrNull(node.index)+    is LevelOutput -> board.io.outputs.getOrNull(node.index)+    else -> null+}
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/GamePage.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/GamePage.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/GamePage.ktindex b56a8b4a66..1c0c5f8ae6 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/GamePage.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/GamePage.kt@@ -21,7 +21,7 @@ fun GamePage(backStack: NavBackStack<Route>, viewModel: LogicViewModel, levelId:     LaunchedEffect(levelId) { viewModel.openLevel(levelId) }     val game by viewModel.game.collectAsState()     val state = game-    if (state == null || state.level.id != levelId) {+    if (state == null || state.level?.id != levelId) {         Box(Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background), contentAlignment = Alignment.Center) {             CircularProgressIndicator()         }@@ -29,7 +29,7 @@ fun GamePage(backStack: NavBackStack<Route>, viewModel: LogicViewModel, levelId:     }     GameScreen(         state = state,-        actions = viewModel,+        actions = viewModel.editor,         onBack = { backStack.pop() },         onNext = { backStack.setLast(Route.Game(it)) },     )
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/GameScreen.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/GameScreen.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/GameScreen.ktindex ee740afe7e..b351c43dd7 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/GameScreen.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/GameScreen.kt@@ -26,7 +26,6 @@ import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.toSize import com.vayunmathur.games.logicgate.R import com.vayunmathur.games.logicgate.domain.levels.LevelRegistry-import com.vayunmathur.games.logicgate.domain.model.Chips import com.vayunmathur.games.logicgate.platform.GameUiState import com.vayunmathur.games.logicgate.platform.LogicActions import com.vayunmathur.games.logicgate.ui.canvas.CameraState@@ -49,8 +48,9 @@ import com.vayunmathur.library.ui.rememberHaptics import kotlin.math.roundToInt  /**- * The editor: the board fills the screen, with tests and the chip tray beneath it. [onNext]- * opens the following level from the completion overlay.+ * The editor, for a level or a sandbox component: the board fills the screen, with tests and the+ * chip tray beneath it. [onNext] opens the following level from the completion overlay;+ * [onDelete] deletes the open component.  */ @Composable fun GameScreen(@@ -59,12 +59,14 @@ fun GameScreen(     onBack: () -> Unit,     onNext: (String) -> Unit,     modifier: Modifier = Modifier,+    onDelete: () -> Unit = {}, ) {     val density = LocalDensity.current.density     val cameraState = remember { CameraState(density) }-    val lookup = remember(state.level) { Chips.lookup(state.level.io) }+    val lookup = remember(state.catalog, state.io) { state.catalog.lookup(state.io) }     val labels = rememberChipLabels()-    val number = LevelRegistry.indexOf(state.level.id) + 1+    val level = state.level+    val number = level?.let { LevelRegistry.indexOf(it.id) + 1 } ?: 0     var trayDrag by remember { mutableStateOf<TrayDrag?>(null) }     val trash = remember { TrashZone() }     val haptics = rememberHaptics()@@ -75,7 +77,7 @@ fun GameScreen(         actions.placeChip(chipId, CircuitLayout(state.circuit, lookup, labels).freeSpot(chipId, world, lookup))      AppScaffold(-        title = stringResource(R.string.lg_level_title, number, stringResource(state.level.title)),+        title = level?.let { stringResource(R.string.lg_level_title, number, stringResource(it.title)) } ?: state.sandbox?.name.orEmpty(),         modifier = modifier,         onNavigateBack = onBack,         actions = {@@ -109,8 +111,9 @@ fun GameScreen(                     Column {                         TestPanel(state, actions)                         ChipTray(-                            chips = state.chips,-                            onTap = { id -> Chips[id]?.let(actions::showChipInfo) },+                            sections = state.tray,+                            defaultGroup = state.defaultGroup,+                            onTap = { id -> state.chips.firstOrNull { it.id == id }?.let(actions::showChipInfo) },                             onDragUpdate = { drag ->                                 trayDrag = drag                                 if (trash.carry(drag?.root)) haptics.tick()@@ -126,19 +129,27 @@ fun GameScreen(                 }             }             trayDrag?.let { DragGhost(chipLabel(it.chipId), it.root - rootOrigin) }-            if (state.won) {+            if (state.won && level != null) {                 LevelCompleteOverlay(                     state = state,+                    level = level,                     onNext = state.nextLevelId?.let { id -> { onNext(id) } },                     onDismiss = actions::dismissWin,                 )             }         }     }-    if (state.showBrief) BriefSheet(state.level, number, onDismiss = { actions.showBrief(false) })+    if (state.showBrief) {+        if (level != null) {+            BriefSheet(level, number, onDismiss = { actions.showBrief(false) })+        } else {+            ComponentSheet(state, actions, onDelete = onDelete, onDismiss = { actions.showBrief(false) })+        }+    }     state.infoChip?.let { chip ->         ChipInfoSheet(             chip = chip,+            group = state.catalog.custom(chip.id)?.group,             onAdd = {                 placeNear(chip.id, cameraState.centerWorld())                 actions.showChipInfo(null)
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/LevelCompleteOverlay.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/LevelCompleteOverlay.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/LevelCompleteOverlay.ktindex 3309029e16..a93839e032 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/LevelCompleteOverlay.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/LevelCompleteOverlay.kt@@ -5,6 +5,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.vayunmathur.games.logicgate.R+import com.vayunmathur.games.logicgate.domain.levels.LevelDef import com.vayunmathur.games.logicgate.platform.GameUiState import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Text@@ -14,6 +15,7 @@ import com.vayunmathur.library.ui.game.GameResultOverlay @Composable fun LevelCompleteOverlay(     state: GameUiState,+    level: LevelDef,     onNext: (() -> Unit)?,     onDismiss: () -> Unit,     modifier: Modifier = Modifier,@@ -29,9 +31,9 @@ fun LevelCompleteOverlay(         backLabel = stringResource(R.string.lg_keep_editing),     ) {         StarRating(state.stars, size = 36.dp)-        Text(stringResource(R.string.lg_cost_vs_par, state.cost, state.level.par), style = MaterialTheme.typography.titleMedium)-        if (state.level.unlocks.isNotEmpty()) {-            val chips = state.level.unlocks.map { chipLabel(it) }.joinToString()+        Text(stringResource(R.string.lg_cost_vs_par, state.cost, level.par), style = MaterialTheme.typography.titleMedium)+        if (level.unlocks.isNotEmpty()) {+            val chips = level.unlocks.map { chipLabel(it) }.joinToString()             Text(stringResource(R.string.lg_new_chips, chips), color = MaterialTheme.colorScheme.primary)         }     }
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/SandboxPage.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/SandboxPage.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/SandboxPage.ktnew file mode 100644index 0000000000..8ac5ed6d31--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/SandboxPage.kt@@ -0,0 +1,24 @@+package com.vayunmathur.games.logicgate.ui++import androidx.compose.runtime.Composable+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.res.stringResource+import com.vayunmathur.games.logicgate.R+import com.vayunmathur.games.logicgate.Route+import com.vayunmathur.games.logicgate.platform.LogicViewModel+import com.vayunmathur.library.util.NavBackStack++/** Binds [LogicViewModel]'s components to the stateless [SandboxScreen]. */+@Composable+fun SandboxPage(backStack: NavBackStack<Route>, viewModel: LogicViewModel) {+    val state by viewModel.sandbox.collectAsState()+    val name = stringResource(R.string.lg_component_default_name, state.components.size + 1)+    val group = stringResource(R.string.lg_component_default_group)+    SandboxScreen(+        state = state,+        onOpen = { backStack.add(Route.Component(it)) },+        onCreate = { backStack.add(Route.Component(viewModel.createComponent(name, group))) },+        onOpenGameCenter = { backStack.add(Route.GameCenter) },+    )+}
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/SandboxScreen.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/SandboxScreen.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/SandboxScreen.ktnew file mode 100644index 0000000000..d91a13a326--- /dev/null+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/SandboxScreen.kt@@ -0,0 +1,102 @@+package com.vayunmathur.games.logicgate.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.PaddingValues+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.lazy.LazyColumn+import androidx.compose.foundation.lazy.items+import androidx.compose.runtime.Composable+import androidx.compose.ui.Modifier+import androidx.compose.ui.res.stringResource+import com.vayunmathur.games.logicgate.R+import com.vayunmathur.games.logicgate.platform.ComponentCard+import com.vayunmathur.games.logicgate.platform.SandboxUiState+import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.ExtendedFloatingActionButton+import com.vayunmathur.library.ui.IconAdd+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Spacing+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.appBarScrollBehavior+import com.vayunmathur.library.ui.game.GameTopBarActions++/** The player's components under their group names, with a button to start a new one. */+@Composable+fun SandboxScreen(+    state: SandboxUiState,+    onOpen: (String) -> Unit,+    onCreate: () -> Unit,+    onOpenGameCenter: () -> Unit,+    modifier: Modifier = Modifier,+) {+    AppScaffold(+        title = stringResource(R.string.lg_sandbox_title),+        modifier = modifier,+        actions = { GameTopBarActions(onOpenGameCenter = onOpenGameCenter) },+        scrollBehavior = appBarScrollBehavior(),+        floatingActionButton = {+            ExtendedFloatingActionButton(+                text = { Text(stringResource(R.string.lg_new_component)) },+                icon = { IconAdd() },+                onClick = onCreate,+            )+        },+    ) { padding ->+        LazyColumn(+            Modifier.fillMaxSize(),+            contentPadding = PaddingValues(+                start = Spacing.lg,+                end = Spacing.lg,+                top = padding.calculateTopPadding() + Spacing.sm,+                bottom = padding.calculateBottomPadding() + FAB_CLEARANCE,+            ),+            verticalArrangement = Arrangement.spacedBy(Spacing.sm),+        ) {+            item(key = "header") {+                Text(stringResource(R.string.lg_sandbox_tagline), style = MaterialTheme.typography.titleMedium)+            }+            if (state.components.isEmpty()) {+                item(key = "empty") {+                    Text(+                        stringResource(R.string.lg_sandbox_empty),+                        style = MaterialTheme.typography.bodyMedium,+                        color = MaterialTheme.colorScheme.onSurfaceVariant,+                        modifier = Modifier.padding(top = Spacing.lg),+                    )+                }+            }+            for ((group, cards) in state.groups) {+                item(key = "group:$group") {+                    Text(+                        group,+                        style = MaterialTheme.typography.titleLarge,+                        color = MaterialTheme.colorScheme.primary,+                        modifier = Modifier.padding(top = Spacing.lg),+                    )+                }+                items(cards, key = { it.id }) { card -> ComponentRow(card, onOpen) }+            }+        }+    }+}++@Composable+private fun ComponentRow(card: ComponentCard, onOpen: (String) -> Unit) {+    Card(onClick = { onOpen(card.id) }, modifier = Modifier.fillMaxWidth()) {+        Column(Modifier.padding(Spacing.md)) {+            Text(card.name, style = MaterialTheme.typography.titleMedium)+            Text(+                card.cost?.let { stringResource(R.string.lg_component_summary, card.inputs, card.outputs, it) }+                    ?: stringResource(R.string.lg_component_broken, card.inputs, card.outputs),+                style = MaterialTheme.typography.bodySmall,+                color = MaterialTheme.colorScheme.onSurfaceVariant,+            )+        }+    }+}++private val FAB_CLEARANCE = Spacing.xl * 4
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/TestPanel.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/TestPanel.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/TestPanel.ktindex f30e5dcf09..92599f8633 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/TestPanel.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/TestPanel.kt@@ -55,6 +55,10 @@ import com.vayunmathur.library.ui.TextButton fun TestPanel(state: GameUiState, actions: LogicActions, modifier: Modifier = Modifier) {     var expanded by rememberSaveable { mutableStateOf(false) }     val verify = state.verify+    if (state.level == null) {+        SandboxStatus(state, modifier)+        return+    }     Surface(modifier.fillMaxWidth(), color = MaterialTheme.colorScheme.surface) {         Column {             Row(@@ -95,6 +99,26 @@ fun TestPanel(state: GameUiState, actions: LogicActions, modifier: Modifier = Mo     } } +@Composable+private fun SandboxStatus(state: GameUiState, modifier: Modifier) {+    Surface(modifier.fillMaxWidth(), color = MaterialTheme.colorScheme.surface) {+        Row(+            Modifier.padding(horizontal = Spacing.lg, vertical = Spacing.sm),+            verticalAlignment = Alignment.CenterVertically,+        ) {+            Text(+                stringResource(R.string.lg_sandbox_status),+                style = MaterialTheme.typography.titleSmall,+                color = MaterialTheme.colorScheme.onSurfaceVariant,+                maxLines = 1,+                overflow = TextOverflow.Ellipsis,+                modifier = Modifier.weight(1f),+            )+            Text(stringResource(R.string.lg_cost, state.cost), style = MaterialTheme.typography.labelLarge)+        }+    }+}+ @Composable private fun Notes(state: GameUiState) {     val verify = state.verify ?: return@@ -113,7 +137,7 @@ private fun ProbeControls(state: GameUiState, actions: LogicActions) {     Row(Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {         if (probe == null) {             val hint = stringResource(R.string.lg_probe_hint)-            val live = if (state.level.inputs.isEmpty()) "" else " " + stringResource(R.string.lg_live_hint)+            val live = if (state.io.inputs.isEmpty()) "" else " " + stringResource(R.string.lg_live_hint)             Text(                 hint + live,                 style = MaterialTheme.typography.bodySmall,@@ -125,7 +149,7 @@ private fun ProbeControls(state: GameUiState, actions: LogicActions) {         IconButton(onClick = { actions.probe(probe - 1) }, enabled = probe > 0) { IconKeyboardArrowLeft() }         val title = state.verify?.cases?.getOrNull(probe)?.title.orEmpty()         Text(-            if (state.level.isSequential) stringResource(R.string.lg_tick, probe + 1, title) else title,+            if (state.level?.isSequential == true) stringResource(R.string.lg_tick, probe + 1, title) else title,             style = MaterialTheme.typography.labelLarge,             maxLines = 1,             overflow = TextOverflow.Ellipsis,@@ -156,7 +180,7 @@ private fun CaseList(state: GameUiState, cases: List<CaseResult>, actions: Logic             }             CaseRow(                 title = c.title,-                actual = c.actual?.let { format(it, state.level.outputs) } ?: "–",+                actual = c.actual?.let { format(it, state.io.outputs) } ?: "–",                 background = background,                 actualColor = if (c.ok) MaterialTheme.colorScheme.onSurfaceVariant else MaterialTheme.colorScheme.error,                 modifier = Modifier.clickable { actions.probe(if (state.probeCase == i) null else i) },
games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/canvas/CanvasController.kt
diff --git a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/canvas/CanvasController.kt b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/canvas/CanvasController.ktindex b76b2a4cbc..d17a6982ac 100644--- a/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/canvas/CanvasController.kt+++ b/games/logicgate/src/main/java/com/vayunmathur/games/logicgate/ui/canvas/CanvasController.kt@@ -90,8 +90,9 @@ class CanvasController(         val s = state ?: return         when (val node = s.circuit.node(id)) {             is LevelInput -> {-                val width = s.level.inputs.getOrNull(node.index)?.width ?: return-                if (width == 1) actions.setInput(node.index, 1 - s.manualInputs[node.index]) else onEditBus(node.index)+                val width = s.io.inputs.getOrNull(node.index)?.width ?: return+                val current = s.manualInputs.getOrElse(node.index) { 0 }+                if (width == 1) actions.setInput(node.index, 1 - current) else onEditBus(node.index)             }             is Gate -> actions.select(Selection.OfNode(id))             else -> actions.select(null)@@ -131,7 +132,7 @@ class CanvasController(     override fun startMove(id: NodeId) {         val node = state?.circuit?.node(id) ?: return         drag = Drag.Moving(id, node.pos, Offset.Zero)-        trash.armed = node is Gate+        trash.armed = node is Gate || state?.sandbox != null         onPickup()     } 
games/logicgate/src/main/res/values/strings.xml
diff --git a/games/logicgate/src/main/res/values/strings.xml b/games/logicgate/src/main/res/values/strings.xmlindex 70f8c5ba18..2019147850 100644--- a/games/logicgate/src/main/res/values/strings.xml+++ b/games/logicgate/src/main/res/values/strings.xml@@ -458,4 +458,57 @@     <string name="lg_chip_cpu_label">CPU</string>     <!-- Chip info sheet: explanation of the CPU chip. Sentences -->     <string name="lg_chip_cpu_info">This is a complete processor. On each tick it runs the instruction on instr, using data, the byte that memory sends back. Its outputs are:\n• pc: the address of the instruction being run.\n• addr: the memory address this instruction reads from or writes to.\n• dout and we: when we is 1, the byte on dout should be written to memory.\n• acc: the accumulator, which holds the number the CPU is working on.\n• halt: 1 when the program has finished.</string>++    <!-- Bottom bar: tab holding the level map. Short noun -->+    <string name="lg_tab_computer">Computer</string>+    <!-- Bottom bar: tab holding the player's own components. Short noun -->+    <string name="lg_tab_sandbox">Sandbox</string>+    <!-- Sandbox list: title. Short noun -->+    <string name="lg_sandbox_title">Sandbox</string>+    <!-- Sandbox list: line under the title. Sentence -->+    <string name="lg_sandbox_tagline">Build your own chips from anything you have unlocked, then use them anywhere.</string>+    <!-- Sandbox list: shown when there are no components yet. Sentence -->+    <string name="lg_sandbox_empty">No components yet. Tap New component to build your first one.</string>+    <!-- Sandbox list: floating button that creates a component. Short verb phrase -->+    <string name="lg_new_component">New component</string>+    <!-- Sandbox list: default name for a newly created component -->+    <string name="lg_component_default_name">Component <xliff:g id="number" example="3">%1$d</xliff:g></string>+    <!-- Sandbox list: default group a new component is filed under. Short noun phrase -->+    <string name="lg_component_default_group">My components</string>+    <!-- Sandbox list card: pin and cost summary -->+    <string name="lg_component_summary"><xliff:g id="inputs" example="2">%1$d</xliff:g> in · <xliff:g id="outputs" example="1">%2$d</xliff:g> out · <xliff:g id="cost" example="4">%3$d</xliff:g> NAND</string>+    <!-- Sandbox list card: summary when the component cannot be built because it contains itself -->+    <string name="lg_component_broken"><xliff:g id="inputs" example="2">%1$d</xliff:g> in · <xliff:g id="outputs" example="1">%2$d</xliff:g> out · contains itself</string>+    <!-- Component sheet: name field label -->+    <string name="lg_component_name">Name</string>+    <!-- Component sheet: group field label -->+    <string name="lg_component_group">Group</string>+    <!-- Component sheet: explains how pins work. Sentences -->+    <string name="lg_component_pins_hint">Drag inputs and outputs onto the board from the Pins tab. Their order from top to bottom is their order on the chip.</string>+    <!-- Component sheet: heading over the list of pins -->+    <string name="lg_component_pins">Pins</string>+    <!-- Component sheet: shown when the component has no pins yet. Sentence -->+    <string name="lg_component_no_pins">No pins yet.</string>+    <!-- Component sheet: delete button -->+    <string name="lg_component_delete">Delete component</string>+    <!-- Delete component dialog: title -->+    <string name="lg_component_delete_title">Delete <xliff:g id="name" example="Adder">%1$s</xliff:g>?</string>+    <!-- Delete component dialog: message. Sentence -->+    <string name="lg_component_delete_message">Any copies of it in your other components and levels will be removed too.</string>+    <!-- Component sheet: content description of the button deleting one pin -->+    <string name="lg_cd_delete_pin">Delete pin <xliff:g id="name" example="a">%1$s</xliff:g></string>+    <!-- Sandbox editor: status line under the board -->+    <string name="lg_sandbox_status">Sandbox · tap an input on the board to flip it.</string>+    <!-- Chip tray: tab for board inputs and outputs. Short noun -->+    <string name="lg_group_pins">Pins</string>+    <!-- Chip tray and canvas: name of a board input placed from the tray. Short noun -->+    <string name="lg_chip_input_label">IN</string>+    <!-- Chip info sheet: explanation of a board input. Sentences -->+    <string name="lg_chip_input_info">An input of your component. On the finished chip it becomes an input pin. Tap it on the board to set its value while testing.</string>+    <!-- Chip tray and canvas: name of a board output placed from the tray. Short noun -->+    <string name="lg_chip_output_label">OUT</string>+    <!-- Chip info sheet: explanation of a board output. Sentences -->+    <string name="lg_chip_output_info">An output of your component. On the finished chip it becomes an output pin.</string>+    <!-- Chip info sheet: shown for a component the player built. Sentence -->+    <string name="lg_chip_custom_info">A component you built in the sandbox, filed under <xliff:g id="group" example="Adders">%1$s</xliff:g>.</string> </resources>
games/logicgate/src/screenshotTest/kotlin/com/vayunmathur/games/logicgate/ui/MetadataPreviews.kt
diff --git a/games/logicgate/src/screenshotTest/kotlin/com/vayunmathur/games/logicgate/ui/MetadataPreviews.kt b/games/logicgate/src/screenshotTest/kotlin/com/vayunmathur/games/logicgate/ui/MetadataPreviews.ktindex 7515e1e9c2..ce4f3427a7 100644--- a/games/logicgate/src/screenshotTest/kotlin/com/vayunmathur/games/logicgate/ui/MetadataPreviews.kt+++ b/games/logicgate/src/screenshotTest/kotlin/com/vayunmathur/games/logicgate/ui/MetadataPreviews.kt@@ -3,7 +3,11 @@ package com.vayunmathur.games.logicgate.ui import androidx.compose.runtime.Composable import androidx.compose.ui.tooling.preview.Preview import com.android.tools.screenshot.PreviewTest+import com.vayunmathur.games.logicgate.domain.levels.ChipGroups import com.vayunmathur.games.logicgate.domain.levels.LevelRegistry+import com.vayunmathur.games.logicgate.domain.levels.TrayGroup+import com.vayunmathur.games.logicgate.domain.model.Board+import com.vayunmathur.games.logicgate.domain.model.ChipCatalog import com.vayunmathur.games.logicgate.domain.model.Chips import com.vayunmathur.games.logicgate.domain.model.Circuit import com.vayunmathur.games.logicgate.domain.model.LevelInput@@ -14,6 +18,7 @@ import com.vayunmathur.games.logicgate.domain.model.PinSide import com.vayunmathur.games.logicgate.domain.model.Point import com.vayunmathur.games.logicgate.domain.sim.Scoring import com.vayunmathur.games.logicgate.domain.sim.Verifier+import com.vayunmathur.games.logicgate.platform.EditorMode import com.vayunmathur.games.logicgate.platform.GameUiState import com.vayunmathur.games.logicgate.platform.LevelCard import com.vayunmathur.games.logicgate.platform.LogicActions@@ -61,11 +66,15 @@ class MetadataPreviews {         val result = Verifier.verify(xor.io, xor.tests, circuit)         val cost = Scoring.cost(circuit) { Chips[it]?.nandCost }         val live = probe?.let { Verifier.probe(xor.io, xor.tests, circuit, it) } ?: Verifier.manual(xor.io, circuit, listOf(1, 0))+        val chips = LevelRegistry.allowedChips(xor.id).mapNotNull { Chips[it] }         return GameUiState(-            level = xor,-            circuit = circuit,-            chips = LevelRegistry.allowedChips(xor.id).mapNotNull { Chips[it] },+            mode = EditorMode.Level(xor),+            board = Board(circuit, xor.io),+            catalog = ChipCatalog.Builtin,+            chips = chips,             manualInputs = listOf(1, 0),+            tray = ChipGroups.sections(chips, ChipCatalog.Builtin),+            defaultGroup = TrayGroup.Builtin(xor.chapter),             verify = result,             probeCase = probe,             live = live,
games/logicgate/src/test/java/com/vayunmathur/games/logicgate/domain/CustomChipTest.kt
diff --git a/games/logicgate/src/test/java/com/vayunmathur/games/logicgate/domain/CustomChipTest.kt b/games/logicgate/src/test/java/com/vayunmathur/games/logicgate/domain/CustomChipTest.ktnew file mode 100644index 0000000000..18e1c67049--- /dev/null+++ b/games/logicgate/src/test/java/com/vayunmathur/games/logicgate/domain/CustomChipTest.kt@@ -0,0 +1,116 @@+package com.vayunmathur.games.logicgate.domain++import com.vayunmathur.games.logicgate.domain.levels.ChipGroups+import com.vayunmathur.games.logicgate.domain.levels.Chapter+import com.vayunmathur.games.logicgate.domain.levels.LevelRegistry+import com.vayunmathur.games.logicgate.domain.levels.TrayGroup+import com.vayunmathur.games.logicgate.domain.model.Board+import com.vayunmathur.games.logicgate.domain.model.ChipCatalog+import com.vayunmathur.games.logicgate.domain.model.Chips+import com.vayunmathur.games.logicgate.domain.model.Circuit+import com.vayunmathur.games.logicgate.domain.model.CustomChip+import com.vayunmathur.games.logicgate.domain.model.LevelInput+import com.vayunmathur.games.logicgate.domain.model.NodeId+import com.vayunmathur.games.logicgate.domain.model.PinChips+import com.vayunmathur.games.logicgate.domain.model.PinRef+import com.vayunmathur.games.logicgate.domain.model.PinSide+import com.vayunmathur.games.logicgate.domain.model.Point+import com.vayunmathur.games.logicgate.domain.model.Wire+import com.vayunmathur.games.logicgate.domain.model.pinRemap+import com.vayunmathur.games.logicgate.domain.model.remapChipPins+import kotlin.test.Test+import kotlin.test.assertContentEquals+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertNotNull+import kotlin.test.assertNull+import kotlin.test.assertTrue++class CustomChipTest {++    private fun threeInputs(): Board = Board.Empty+        .addPin(true, 1, Point(0f, 200f))+        .addPin(true, 4, Point(0f, 0f))+        .addPin(true, 8, Point(0f, 100f))+        .addPin(false, 1, Point(400f, 0f))++    @Test+    fun pinsGetDefaultNamesAndChipOrderFollowsTheBoardTopToBottom() {+        val board = threeInputs()+        assertEquals(listOf("a", "b", "c"), board.io.inputs.map { it.name })+        assertEquals(listOf("o"), board.io.outputs.map { it.name })+        val chip = CustomChip("custom:t", "t", "g", board)+        assertEquals(listOf("b", "c", "a"), chip.inputs.map { it.name })+        assertEquals(listOf(4, 8, 1), chip.inputs.map { it.width })+    }++    @Test+    fun removingAPinShiftsLaterIndicesAndDropsItsWires() {+        var board = threeInputs()+        val (c, not) = board.circuit.addGate(Chips.NOT, Point(200f, 200f))+        board = board.copy(circuit = c.copy(wires = listOf(Wire(PinRef(NodeId(0), PinSide.OUT, 0), PinRef(not, PinSide.IN, 0)))))+        board = board.removePin(NodeId(0))+        assertEquals(listOf("b", "c"), board.io.inputs.map { it.name })+        assertEquals(listOf(0, 1), board.circuit.nodes.filterIsInstance<LevelInput>().map { it.index }.sorted())+        assertTrue(board.circuit.wires.isEmpty())+        assertEquals("a", board.addPin(true, 1, Point(0f, 0f)).io.inputs.last().name)+    }++    @Test+    fun renamingTrimsAndIgnoresBlanks() {+        val board = threeInputs()+        assertEquals("sel", board.renamePin(NodeId(1), "  sel ").io.inputs[1].name)+        assertEquals(board, board.renamePin(NodeId(1), "   "))+    }++    @Test+    fun movingAPinRemapsWiresInCircuitsThatUseTheChip() {+        val before = CustomChip("custom:t", "t", "g", threeInputs())+        val moved = before.copy(board = before.board.copy(circuit = before.board.circuit.moveNode(NodeId(0), Point(0f, -50f))))+        val (ins, outs) = assertNotNull(pinRemap(before, moved))+        assertContentEquals(intArrayOf(1, 2, 0), ins)+        assertContentEquals(intArrayOf(0), outs)+        assertNull(pinRemap(before, before))++        val (c0, g) = Circuit().addGate(before.id, Point(0f, 0f))+        val (c1, src) = c0.addGate(Chips.HIGH, Point(-100f, 0f))+        val wired = c1.copy(wires = listOf(Wire(PinRef(src, PinSide.OUT, 0), PinRef(g, PinSide.IN, 2))))+        assertEquals(PinRef(g, PinSide.IN, 0), wired.remapChipPins(before.id, ins, outs).wires.single().to)++        val gone = intArrayOf(0, 1, -1)+        assertTrue(wired.remapChipPins(before.id, gone, outs).wires.isEmpty())+    }++    @Test+    fun catalogUsesIsTransitive() {+        val inner = CustomChip("custom:inner", "inner", "g", Board.Empty)+        val outer = CustomChip("custom:outer", "outer", "g", Board(Circuit().addGate(inner.id, Point(0f, 0f)).first, Board.Empty.io))+        val catalog = ChipCatalog(listOf(inner, outer))+        assertTrue(catalog.uses(outer.id, inner.id))+        assertFalse(catalog.uses(inner.id, outer.id))+        assertEquals(0, catalog[outer.id]?.nandCost)+    }++    @Test+    fun theSandboxOffersOnlyWhatIsUnlocked() {+        assertEquals(Chips.base.toSet(), LevelRegistry.unlockedChips(emptySet()).toSet())+        assertTrue(Chips.NOT in LevelRegistry.unlockedChips(setOf("not")))+        val throughBus = LevelRegistry.levels.takeWhile { it.id != "nibble_swap" }.map { it.id }.toSet()+        assertTrue(Chips.SPLIT8 in LevelRegistry.unlockedChips(throughBus))+        assertFalse(Chips.ADD8 in LevelRegistry.unlockedChips(throughBus))+        val all = LevelRegistry.levels.map { it.id }.toSet()+        assertEquals(Chips.all.map { it.id }.toSet(), LevelRegistry.unlockedChips(all).toSet())+    }++    @Test+    fun trayGroupsPutPinsFirstThenChaptersThenPlayerGroups() {+ 

Diff truncated.