Rearrange landscape puzzle layout

Landscape leaves now lay the puzzle out in two columns: the whole grid
keeps one column (square, sized to the page) with the heading, area
totals, hint/undo and notes beside it, and the leaf navigation folds
into a single row. The game leaf also keeps its actions in a compact
bottom bar, so the board and controls are visible without scrolling.

- Leaf gains an optional wideBody used on landscape pages.
- Board gains maxWidth, defaulting to the previous 350.
- Split the puzzle body into area, board and note builders so both
  layouts share the same controls.
- Add a landscape widget regression test and document the layout.

This snapshot also carries the pending 2.0.2 notebook work already in
the tree: read-ahead restore, bundled PCM WAV narration assets, the
audio consistency comment, version 2.0.2+11, and the related unit,
integration and script updates.
This commit is contained in:
Hadrian Burkhardt
2026-10-31 06:21:36 +01:00
parent 302ad6d38e
commit a863b0ca93
22 changed files with 971 additions and 374 deletions
+10 -9
View File
@@ -1,4 +1,4 @@
# Lumen — The Last Light (Flutter 2.0) # Lumen — The Last Light (Flutter 2.0.2)
An illustrated island notebook about grandmother Mara, her grandchild, and restoring a lighthouse. The active app is now written in **Dart and Flutter**, with a thin Android Kotlin entry point. All puzzle generation, deductions, story navigation, progress, audio controls and advertising behavior live in `lib/`. An illustrated island notebook about grandmother Mara, her grandchild, and restoring a lighthouse. The active app is now written in **Dart and Flutter**, with a thin Android Kotlin entry point. All puzzle generation, deductions, story navigation, progress, audio controls and advertising behavior live in `lib/`.
@@ -7,9 +7,10 @@ Android is the tested target. iOS project scaffolding and test AdMob configurati
## Play ## Play
- Six opening notebook leaves: a dedication, illustrated cottage entry, match puzzle, memory, folded note and inspectable lantern. - Six opening notebook leaves: a dedication, illustrated cottage entry, match puzzle, memory, folded note and inspectable lantern.
- Margin swipes and corner arrows turn leaves. Grid gestures never turn pages. Navigation stays fixed; overflow scrolling supports smaller screens and larger text. - Horizontal swipes across the writing or blank paper, plus corner arrows, turn leaves. Grid and control gestures never turn pages; vertical drags still scroll. Navigation stays fixed; overflow scrolling supports smaller screens and larger text.
- Landscape pages rearrange themselves: a puzzle keeps its whole grid in one column, with the heading, area totals, hint and undo beside it, and the leaf navigation folds into a single row. The board stays fully visible without scrolling, even with larger text.
- A saved ribbon bookmark, opened note, inspected repair, viewed pages and current reading place. - A saved ribbon bookmark, opened note, inspected repair, viewed pages and current reading place.
- Twelve 7×7 picture puzzles across three chapters, with overlapping-area deductions on entries 3–12. Later chapters retain their earlier briefing/puzzle/reveal structure until the roadmap expands them. - Twelve 7×7 picture puzzles across three chapters, with overlapping-area deductions on entries 3–12. Later chapters retain their briefing/puzzle/reveal structure, now with swipes between those pages too. Reading ahead keeps unfinished boards and completion awards separate.
- Deterministic daily grids and generated Easy, Medium and Hard 5×5 practice. The grades measure deduction-chain depth, not expert-level difficulty. Every board has a unique solution and needs no guessing. - Deterministic daily grids and generated Easy, Medium and Hard 5×5 practice. The grades measure deduction-chain depth, not expert-level difficulty. Every board has a unique solution and needs no guessing.
- Undo, one free explained hint per puzzle, then optional rewarded hints. Later hints require the AdMob reward callback. An unavailable ad never blocks the board. - Undo, one free explained hint per puzzle, then optional rewarded hints. Later hints require the AdMob reward callback. An unavailable ad never blocks the board.
- Local daily streaks, independent difficulty levels and exactly-once puzzle completion awards. - Local daily streaks, independent difficulty levels and exactly-once puzzle completion awards.
@@ -19,9 +20,9 @@ Progress starts fresh in Flutter, as requested. Old Java `lumen.xml` saves are *
## Artwork and readings ## Artwork and readings
All app-created text uses the bundled Dancing Script handwriting font, including grid clues and menus. Original watercolour harbour, cloth cover, cottage, lantern and single-page art remain bundled for offline use. Native text sits directly on the page’s blank writing area. Art prompts and provenance are in [assets/artwork](assets/artwork/README.md); the font’s OFL license ships in the app’s open-source licenses. All app-created text uses the bundled Dancing Script handwriting font, including grid clues and menus. Lit cells are shaded with pencil strokes, and dark cells use a drawn cross; neither depends on a symbol-font fallback. Original watercolour harbour, cloth cover, cottage, lantern and single-page art remain bundled for offline use. Native text sits directly on the page’s blank writing area. Art prompts and provenance are in [assets/artwork](assets/artwork/README.md); the font’s OFL license ships in the app’s open-source licenses.
Five fixed, pre-rendered synthetic British-English readings ship as lossless FLAC assets, with PCM16 WAV masters for review. `just_audio` plays bundled files; there is no Android reader, runtime synthesis or audio download. Controls support play, pause, resume at the same position, stop, replay, speed and passage highlighting. Leaving a page or backgrounding the app stops playback. See [narration provenance](assets/narration/README.md). Five fixed, pre-rendered synthetic British-English readings play from bundled PCM16 WAV files, identical to the reviewed masters. Lossless FLAC exports are retained in the source project but excluded from the APK. WAV avoids a Huawei API 26 failure where FLAC playback advances its clock without creating an audio track. `just_audio` plays bundled files; there is no Android reader, runtime synthesis or audio download. Controls support play, pause, resume at the same position, stop, replay, speed and passage highlighting. Leaving a page or backgrounding the app stops playback. See [narration provenance](assets/narration/README.md).
## Build and run ## Build and run
@@ -44,7 +45,7 @@ flutter build apk --debug --flavor qa
flutter build apk --release --flavor prod --target-platform android-arm64 flutter build apk --release --flavor prod --target-platform android-arm64
``` ```
The normal application ID remains `com.lumen.daily`; version 2.0.0 uses build number 9. The review APK is `artifacts/lumen-flutter-2.0-arm64.apk`. Build outputs, screenshots, local SDK paths, IDE state and private signing keys are ignored by Git. `pubspec.lock` is tracked for reproducible package resolution. The normal application ID remains `com.lumen.daily`; version 2.0.2 uses build number 11. The review APK is `artifacts/lumen-flutter-2.0.2-arm64.apk`. Build outputs, screenshots, local SDK paths, IDE state and private signing keys are ignored by Git. `pubspec.lock` is tracked for reproducible package resolution.
The development release build currently uses the Android debug signing key so it can update the installed prototype. **Configure your private upload key before publishing.** No production signing material is included. The development release build currently uses the Android debug signing key so it can update the installed prototype. **Configure your private upload key before publishing.** No production signing material is included.
@@ -64,9 +65,9 @@ flutter drive --driver test_driver/integration_test.dart \
--dart-define=QA_TEST=true -d YOUR_ANDROID_DEVICE --dart-define=QA_TEST=true -d YOUR_ANDROID_DEVICE
``` ```
The nine unit/widget tests cover 40 Java reference boards (including signed 64-bit seeds), 300 graded generated boards, solver counts against 300 exhaustive small systems, all twelve campaign solutions, streaks, fresh progress, read-ahead, completion awards, gesture isolation, landscape and larger text. Reference parity protects the port’s rules; it is not used to migrate saves. The twelve unit/widget tests cover 40 Java reference boards (including signed 64-bit seeds), 300 graded generated boards, solver counts against 300 exhaustive small systems, all twelve campaign solutions, streaks, fresh progress, read-ahead, completion awards, campaign read-ahead restoration, gesture isolation, swipes over text and blank paper, cancelled drags, vertical scrolling, landscape and larger text; it also checks the landscape two-column puzzle leaf. Reference parity protects the port’s rules; it is not used to migrate saves.
The physical-device integration test uses a disposable in-memory game plus an isolated QA disk round-trip. It plays all five real FLAC files, checks pause/resume, explores the six leaves, verifies bookmarks/discoveries, solves match and lantern puzzles and checks exactly-once awards. Screenshots are saved in `artifacts/flutter-check/`. The release smoke script exercises the actual play/pause/resume UI and restores the last page after process restart, without injecting puzzle fixtures. The release build includes a targeted R8 keep rule for the database constructor used reflectively by AdMob’s WorkManager dependency. Advertising is disabled for the automated story tests; real UMP startup is checked separately in the normal build. Reward delivery, cancellation and ad no-fill still need manual release testing with your final AdMob configuration. The physical-device integration test uses a disposable in-memory game plus an isolated QA disk round-trip. It plays all five real WAV files, checks pause/resume, explores the six leaves, verifies bookmarks/discoveries, solves match and lantern puzzles and checks exactly-once awards. Screenshots are saved in `artifacts/flutter-check/`. The release smoke script requires an active, unmuted 24 kHz media track in the tablet’s audio mixer as well as exercising the actual play/pause/resume UI and restores the last page after process restart, without injecting puzzle fixtures. The release build includes a targeted R8 keep rule for the database constructor used reflectively by AdMob’s WorkManager dependency. Advertising is disabled for the automated story tests; real UMP startup is checked separately in the normal build. Reward delivery, cancellation and ad no-fill still need manual release testing with your final AdMob configuration.
## Source map ## Source map
@@ -80,7 +81,7 @@ The physical-device integration test uses a disposable in-memory game plus an is
| `lib/services/` | Local storage, bundled playback and consent-gated AdMob | | `lib/services/` | Local storage, bundled playback and consent-gated AdMob |
| `assets/campaign.json` | Authored twelve-picture campaign | | `assets/campaign.json` | Authored twelve-picture campaign |
| `assets/narration/scripts.json` | Canonical spoken diary text | | `assets/narration/scripts.json` | Canonical spoken diary text |
| `assets/audio/` | Runtime FLAC files and passage timing manifest | | `assets/audio/` | Runtime WAV files, archival FLAC exports and passage timing manifest |
| `legacy/` | Archived Java version 1.7, excluded from Flutter builds | | `legacy/` | Archived Java version 1.7, excluded from Flutter builds |
## Before publishing ## Before publishing
+4 -4
View File
@@ -1,6 +1,6 @@
# Lumen — a notebook worth exploring # Lumen — a notebook worth exploring
Status: opening slice ported to Dart and Flutter in version 2.0. The six-leaf opening slice below is implemented and ready for review: page-margin swipes, arrows, five bundled recorded readings, two on-page illustrations and refreshed home art, a saved ribbon bookmark, a folded note, a lantern inspection, and the existing match puzzle/reveal. Full chapter pagination, the larger 30–40-leaf story and later exploration features remain proposed. The Flutter port retains these features and starts fresh progress, as requested. Android is the tested target; iOS scaffolding is present but not yet validated. There are no delivery dates yet; review the opening slice before expanding it. Status: opening slice ported to Dart and Flutter in version 2.0. The six-leaf opening slice below is implemented and ready for review: reading-area swipes, arrows, five bundled recorded readings, two on-page illustrations and refreshed home art, a saved ribbon bookmark, a folded note, a lantern inspection, and the existing match puzzle/reveal. Full chapter pagination, the larger 30–40-leaf story and later exploration features remain proposed. The Flutter port retains these features and starts fresh progress, as requested. Android is the tested target; iOS scaffolding is present but not yet validated. There are no delivery dates yet; review the opening slice before expanding it.
## The experience we are building ## The experience we are building
@@ -17,8 +17,8 @@ Success is the player wanting to turn another page, remember a detail, or return
- Three chapters with twelve authored picture puzzles and short passages before and after them. - Three chapters with twelve authored picture puzzles and short passages before and after them.
- A single-page diary background, handwriting, recovered pixel pictures, and saved local progress. - A single-page diary background, handwriting, recovered pixel pictures, and saved local progress.
- Explained puzzle hints, generated classic practice, and a daily challenge. - Explained puzzle hints, generated classic practice, and a daily challenge.
- Six opening leaves with edge swipes and corner arrows, optional bundled recordings, cottage and lantern illustrations, a folded note, inspection, and independent reading bookmarks. - Six opening leaves with reading-area swipes and corner arrows, optional bundled recordings, cottage and lantern illustrations, a folded note, inspection, and independent reading bookmarks.
- Existing campaign pages beyond this prototype retain their previous navigation. Overflow scrolling remains for large text and shorter viewports. - Existing campaign pages beyond this prototype now support swipes between briefing, puzzle and memory screens, with optional read-ahead that preserves puzzle progress. Their full illustrated pagination remains proposed. Overflow scrolling remains for large text and shorter viewports.
## Phase 1 — make it a book ## Phase 1 — make it a book
@@ -26,7 +26,7 @@ First milestone: a small, complete slice of the cottage chapter that can be read
- Replace the long chapter list with a contents leaf for each chapter, showing four entries and a ribbon marking the current place. - Replace the long chapter list with a contents leaf for each chapter, showing four entries and a ribbon marking the current place.
- Give story entries, illustrations, puzzles, and discoveries their own pages. Split long passages at natural sentence or paragraph boundaries. - Give story entries, illustrations, puzzles, and discoveries their own pages. Split long passages at natural sentence or paragraph boundaries.
- Turn pages with horizontal swipes near the edges and small corner arrows. Provide a contents shortcut and a bookmark action. - Turn pages with horizontal swipes across the writing or blank paper and small corner arrows. Provide a contents shortcut and a bookmark action.
- Keep page-turn gestures outside the active puzzle grid and narration controls. An attempted mark must never turn the page. - Keep page-turn gestures outside the active puzzle grid and narration controls. An attempted mark must never turn the page.
- Use a short paper-turn animation, with an instant or reduced-motion alternative. Backtracking should feel immediate. - Use a short paper-turn animation, with an instant or reduced-motion alternative. Backtracking should feel immediate.
- Return to the exact page the player left, including an unfinished puzzle. Support returning to an earlier discovery without changing completion counts. - Return to the exact page the player left, including an unfinished puzzle. Support returning to an earlier discovery without changing completion counts.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+20 -10
View File
@@ -4,7 +4,7 @@
"pageId": "cottage.dedication", "pageId": "cottage.dedication",
"resource": "narration_cottage_dedication", "resource": "narration_cottage_dedication",
"text": "My dear,\n\nI never could keep a proper diary. I wrote down the tides, the things that needed mending, and whatever I was afraid I might forget.\n\nYou will find a little of all three in here. Take your time. There is no right way to turn these pages.\n\nWith all my love,\nGran", "text": "My dear,\n\nI never could keep a proper diary. I wrote down the tides, the things that needed mending, and whatever I was afraid I might forget.\n\nYou will find a little of all three in here. Take your time. There is no right way to turn these pages.\n\nWith all my love,\nGran",
"file": "narration_cottage_dedication.flac", "file": "narration_cottage_dedication.wav",
"sampleRate": 24000, "sampleRate": 24000,
"channels": 1, "channels": 1,
"frames": 441184, "frames": 441184,
@@ -22,13 +22,15 @@
"endMs": 17783, "endMs": 17783,
"text": "You will find a little of all three in here. Take your time. There is no right way to turn these pages.\n\nWith all my love,\nGran" "text": "You will find a little of all three in here. Take your time. There is no right way to turn these pages.\n\nWith all my love,\nGran"
} }
] ],
"flacFile": "narration_cottage_dedication.flac",
"wavSha256": "c99d66f356537aec9983c22ba7a22466e0a947e3823db7e6f4c266f0fbc8ed24"
}, },
"cottage.window": { "cottage.window": {
"pageId": "cottage.window", "pageId": "cottage.window",
"resource": "narration_cottage_window", "resource": "narration_cottage_window",
"text": "The wind has finally gone quiet. I have put the blue cup by the window, where you always liked to sit.\n\nThe latch still sticks. Lift it a little before you turn it. Some things on this island need a gentle hand, not a stronger one.\n\nIf you arrive after dark, there is something in the little drawer beside the hearth.", "text": "The wind has finally gone quiet. I have put the blue cup by the window, where you always liked to sit.\n\nThe latch still sticks. Lift it a little before you turn it. Some things on this island need a gentle hand, not a stronger one.\n\nIf you arrive after dark, there is something in the little drawer beside the hearth.",
"file": "narration_cottage_window.flac", "file": "narration_cottage_window.wav",
"sampleRate": 24000, "sampleRate": 24000,
"channels": 1, "channels": 1,
"frames": 499104, "frames": 499104,
@@ -51,13 +53,15 @@
"endMs": 20196, "endMs": 20196,
"text": "If you arrive after dark, there is something in the little drawer beside the hearth." "text": "If you arrive after dark, there is something in the little drawer beside the hearth."
} }
] ],
"flacFile": "narration_cottage_window.flac",
"wavSha256": "08f483f48e3c79f6294aa30ba5c676d0ad536235f609577ceb567f35d3ddf72c"
}, },
"cottage.match.memory": { "cottage.match.memory": {
"pageId": "cottage.match.memory", "pageId": "cottage.match.memory",
"resource": "narration_cottage_match_memory", "resource": "narration_cottage_match_memory",
"text": "You used to insist on lighting the evening lantern yourself. I held the matchbox, and you held your breath.\n\nOnce, you asked how such a little flame could help anyone out at sea.\n\nIt cannot, I told you. But it can help us find the next light.\n\nI kept one dry match in a tin after that. Just in case.", "text": "You used to insist on lighting the evening lantern yourself. I held the matchbox, and you held your breath.\n\nOnce, you asked how such a little flame could help anyone out at sea.\n\nIt cannot, I told you. But it can help us find the next light.\n\nI kept one dry match in a tin after that. Just in case.",
"file": "narration_cottage_match_memory.flac", "file": "narration_cottage_match_memory.wav",
"sampleRate": 24000, "sampleRate": 24000,
"channels": 1, "channels": 1,
"frames": 506848, "frames": 506848,
@@ -85,13 +89,15 @@
"endMs": 20519, "endMs": 20519,
"text": "I kept one dry match in a tin after that. Just in case." "text": "I kept one dry match in a tin after that. Just in case."
} }
] ],
"flacFile": "narration_cottage_match_memory.flac",
"wavSha256": "9972d88c8c6a93ac78528a96f4320f8f422009ba2fed78da8bc0f85ce92a840f"
}, },
"cottage.folded.note": { "cottage.folded.note": {
"pageId": "cottage.folded.note", "pageId": "cottage.folded.note",
"resource": "narration_cottage_folded_note", "resource": "narration_cottage_folded_note",
"text": "If the tide has covered the causeway, use the little boat by the harbour steps. The knot looks worse than it is.\n\nTake the lantern. When you reach the bell, ring twice. I will know it is you.\n\nAnd do not let the tea go cold while you are deciding.\n\nLove, Gran", "text": "If the tide has covered the causeway, use the little boat by the harbour steps. The knot looks worse than it is.\n\nTake the lantern. When you reach the bell, ring twice. I will know it is you.\n\nAnd do not let the tea go cold while you are deciding.\n\nLove, Gran",
"file": "narration_cottage_folded_note.flac", "file": "narration_cottage_folded_note.wav",
"sampleRate": 24000, "sampleRate": 24000,
"channels": 1, "channels": 1,
"frames": 425888, "frames": 425888,
@@ -114,13 +120,15 @@
"endMs": 17145, "endMs": 17145,
"text": "And do not let the tea go cold while you are deciding.\n\nLove, Gran" "text": "And do not let the tea go cold while you are deciding.\n\nLove, Gran"
} }
] ],
"flacFile": "narration_cottage_folded_note.flac",
"wavSha256": "cc8992b78771101daeb79b91b01702043cbeff3781b772492a0d43cfb6a02ead"
}, },
"cottage.lantern.sketch": { "cottage.lantern.sketch": {
"pageId": "cottage.lantern.sketch", "pageId": "cottage.lantern.sketch",
"resource": "narration_cottage_lantern_sketch", "resource": "narration_cottage_lantern_sketch",
"text": "Your grandfather repaired this handle with a piece of wire and far too much confidence. I wrapped the join so it would not catch your fingers.\n\nPeople notice the flame first. I tend to notice the things that let us carry it.", "text": "Your grandfather repaired this handle with a piece of wire and far too much confidence. I wrapped the join so it would not catch your fingers.\n\nPeople notice the flame first. I tend to notice the things that let us carry it.",
"file": "narration_cottage_lantern_sketch.flac", "file": "narration_cottage_lantern_sketch.wav",
"sampleRate": 24000, "sampleRate": 24000,
"channels": 1, "channels": 1,
"frames": 366944, "frames": 366944,
@@ -138,7 +146,9 @@
"endMs": 14689, "endMs": 14689,
"text": "People notice the flame first. I tend to notice the things that let us carry it." "text": "People notice the flame first. I tend to notice the things that let us carry it."
} }
] ],
"flacFile": "narration_cottage_lantern_sketch.flac",
"wavSha256": "53dd694b9933f94bcda72582d0c6b1bb5b656898a73c87d66ecfa0874ba3a29d"
} }
} }
} }
+6 -3
View File
@@ -4,8 +4,9 @@ Five fixed readings accompany the opening notebook leaves. They are **synthetic
- `scripts.json`: canonical non-puzzle text loaded directly by the Flutter story pages. - `scripts.json`: canonical non-puzzle text loaded directly by the Flutter story pages.
- `wav/`: reviewable 24 kHz mono PCM16 WAV masters. - `wav/`: reviewable 24 kHz mono PCM16 WAV masters.
- `manifest.json`: model/voice checksums, generator versions, exact scripts, passage timings and FLAC checksums. - `manifest.json`: model/voice checksums, generator versions, exact scripts, passage timings and WAV and FLAC checksums.
- `assets/audio/narration_*.flac`: lossless bundled copies. - `assets/audio/narration_*.wav`: bundled PCM16 copies, byte-identical to the WAV masters.
- `assets/audio/narration_*.flac`: archival lossless exports, excluded from the APK.
- `licenses/`: Kokoro ONNX wrapper MIT and model Apache 2.0 licenses. - `licenses/`: Kokoro ONNX wrapper MIT and model Apache 2.0 licenses.
The voice uses generation speed 0.82, short fades, paragraph pauses and peak normalization. The in-app speed control changes playback speed without changing pitch. Pausing preserves the actual recording position; leaving a page releases playback. Readings never autoplay on entry. The voice uses generation speed 0.82, short fades, paragraph pauses and peak normalization. The in-app speed control changes playback speed without changing pitch. Pausing preserves the actual recording position; leaving a page releases playback. Readings never autoplay on entry.
@@ -21,6 +22,8 @@ python scripts/render_narration.py --model /path/to/kokoro-v1.0.onnx --voices /p
python3 scripts/check_narration_assets.py python3 scripts/check_narration_assets.py
``` ```
The check requires only Python’s standard library and ffmpeg. It verifies script freshness, cue coverage, master format, checksums and bit-identical WAV/FLAC decoding. It also rejects Flutter device-reader imports in app code. Listen to new takes before accepting them; automated checks cannot judge performance or pronunciation. The check requires only Python’s standard library and ffmpeg. It verifies script freshness, cue coverage, master format, checksums and runtime WAV/master equality and bit-identical WAV/FLAC decoding. It also rejects Flutter device-reader imports in app code. Listen to new takes before accepting them; automated checks cannot judge performance or pronunciation.
A future actor recording can replace the masters and bundled assets while preserving stable page IDs. Update passage timings and checksums with that recording; never silently change the written script to fit audio. A future actor recording can replace the masters and bundled assets while preserving stable page IDs. Update passage timings and checksums with that recording; never silently change the written script to fit audio.
Playback uses PCM WAV because the connected Huawei API 26 tablet advanced the FLAC clock without creating an AudioTrack. WAV produces an active, unmuted 24 kHz mono PCM media track through the speaker, and the user confirmed audible speech. The release smoke test now checks that mixer track, in addition to pause/resume and elapsed time.
+20 -10
View File
@@ -16,7 +16,7 @@
"pageId": "cottage.dedication", "pageId": "cottage.dedication",
"resource": "narration_cottage_dedication", "resource": "narration_cottage_dedication",
"text": "My dear,\n\nI never could keep a proper diary. I wrote down the tides, the things that needed mending, and whatever I was afraid I might forget.\n\nYou will find a little of all three in here. Take your time. There is no right way to turn these pages.\n\nWith all my love,\nGran", "text": "My dear,\n\nI never could keep a proper diary. I wrote down the tides, the things that needed mending, and whatever I was afraid I might forget.\n\nYou will find a little of all three in here. Take your time. There is no right way to turn these pages.\n\nWith all my love,\nGran",
"file": "narration_cottage_dedication.flac", "file": "narration_cottage_dedication.wav",
"sampleRate": 24000, "sampleRate": 24000,
"channels": 1, "channels": 1,
"frames": 441184, "frames": 441184,
@@ -34,13 +34,15 @@
"endMs": 17783, "endMs": 17783,
"text": "You will find a little of all three in here. Take your time. There is no right way to turn these pages.\n\nWith all my love,\nGran" "text": "You will find a little of all three in here. Take your time. There is no right way to turn these pages.\n\nWith all my love,\nGran"
} }
] ],
"flacFile": "narration_cottage_dedication.flac",
"wavSha256": "c99d66f356537aec9983c22ba7a22466e0a947e3823db7e6f4c266f0fbc8ed24"
}, },
"cottage.window": { "cottage.window": {
"pageId": "cottage.window", "pageId": "cottage.window",
"resource": "narration_cottage_window", "resource": "narration_cottage_window",
"text": "The wind has finally gone quiet. I have put the blue cup by the window, where you always liked to sit.\n\nThe latch still sticks. Lift it a little before you turn it. Some things on this island need a gentle hand, not a stronger one.\n\nIf you arrive after dark, there is something in the little drawer beside the hearth.", "text": "The wind has finally gone quiet. I have put the blue cup by the window, where you always liked to sit.\n\nThe latch still sticks. Lift it a little before you turn it. Some things on this island need a gentle hand, not a stronger one.\n\nIf you arrive after dark, there is something in the little drawer beside the hearth.",
"file": "narration_cottage_window.flac", "file": "narration_cottage_window.wav",
"sampleRate": 24000, "sampleRate": 24000,
"channels": 1, "channels": 1,
"frames": 499104, "frames": 499104,
@@ -63,13 +65,15 @@
"endMs": 20196, "endMs": 20196,
"text": "If you arrive after dark, there is something in the little drawer beside the hearth." "text": "If you arrive after dark, there is something in the little drawer beside the hearth."
} }
] ],
"flacFile": "narration_cottage_window.flac",
"wavSha256": "08f483f48e3c79f6294aa30ba5c676d0ad536235f609577ceb567f35d3ddf72c"
}, },
"cottage.match.memory": { "cottage.match.memory": {
"pageId": "cottage.match.memory", "pageId": "cottage.match.memory",
"resource": "narration_cottage_match_memory", "resource": "narration_cottage_match_memory",
"text": "You used to insist on lighting the evening lantern yourself. I held the matchbox, and you held your breath.\n\nOnce, you asked how such a little flame could help anyone out at sea.\n\nIt cannot, I told you. But it can help us find the next light.\n\nI kept one dry match in a tin after that. Just in case.", "text": "You used to insist on lighting the evening lantern yourself. I held the matchbox, and you held your breath.\n\nOnce, you asked how such a little flame could help anyone out at sea.\n\nIt cannot, I told you. But it can help us find the next light.\n\nI kept one dry match in a tin after that. Just in case.",
"file": "narration_cottage_match_memory.flac", "file": "narration_cottage_match_memory.wav",
"sampleRate": 24000, "sampleRate": 24000,
"channels": 1, "channels": 1,
"frames": 506848, "frames": 506848,
@@ -97,13 +101,15 @@
"endMs": 20519, "endMs": 20519,
"text": "I kept one dry match in a tin after that. Just in case." "text": "I kept one dry match in a tin after that. Just in case."
} }
] ],
"flacFile": "narration_cottage_match_memory.flac",
"wavSha256": "9972d88c8c6a93ac78528a96f4320f8f422009ba2fed78da8bc0f85ce92a840f"
}, },
"cottage.folded.note": { "cottage.folded.note": {
"pageId": "cottage.folded.note", "pageId": "cottage.folded.note",
"resource": "narration_cottage_folded_note", "resource": "narration_cottage_folded_note",
"text": "If the tide has covered the causeway, use the little boat by the harbour steps. The knot looks worse than it is.\n\nTake the lantern. When you reach the bell, ring twice. I will know it is you.\n\nAnd do not let the tea go cold while you are deciding.\n\nLove, Gran", "text": "If the tide has covered the causeway, use the little boat by the harbour steps. The knot looks worse than it is.\n\nTake the lantern. When you reach the bell, ring twice. I will know it is you.\n\nAnd do not let the tea go cold while you are deciding.\n\nLove, Gran",
"file": "narration_cottage_folded_note.flac", "file": "narration_cottage_folded_note.wav",
"sampleRate": 24000, "sampleRate": 24000,
"channels": 1, "channels": 1,
"frames": 425888, "frames": 425888,
@@ -126,13 +132,15 @@
"endMs": 17145, "endMs": 17145,
"text": "And do not let the tea go cold while you are deciding.\n\nLove, Gran" "text": "And do not let the tea go cold while you are deciding.\n\nLove, Gran"
} }
] ],
"flacFile": "narration_cottage_folded_note.flac",
"wavSha256": "cc8992b78771101daeb79b91b01702043cbeff3781b772492a0d43cfb6a02ead"
}, },
"cottage.lantern.sketch": { "cottage.lantern.sketch": {
"pageId": "cottage.lantern.sketch", "pageId": "cottage.lantern.sketch",
"resource": "narration_cottage_lantern_sketch", "resource": "narration_cottage_lantern_sketch",
"text": "Your grandfather repaired this handle with a piece of wire and far too much confidence. I wrapped the join so it would not catch your fingers.\n\nPeople notice the flame first. I tend to notice the things that let us carry it.", "text": "Your grandfather repaired this handle with a piece of wire and far too much confidence. I wrapped the join so it would not catch your fingers.\n\nPeople notice the flame first. I tend to notice the things that let us carry it.",
"file": "narration_cottage_lantern_sketch.flac", "file": "narration_cottage_lantern_sketch.wav",
"sampleRate": 24000, "sampleRate": 24000,
"channels": 1, "channels": 1,
"frames": 366944, "frames": 366944,
@@ -150,7 +158,9 @@
"endMs": 14689, "endMs": 14689,
"text": "People notice the flame first. I tend to notice the things that let us carry it." "text": "People notice the flame first. I tend to notice the things that let us carry it."
} }
] ],
"flacFile": "narration_cottage_lantern_sketch.flac",
"wavSha256": "53dd694b9933f94bcda72582d0c6b1bb5b656898a73c87d66ecfa0874ba3a29d"
} }
} }
} }
+61 -1
View File
@@ -43,6 +43,16 @@ void main() {
await tester.dragFrom(Offset(width - 12, 300), const Offset(-180, 0)); await tester.dragFrom(Offset(width - 12, 300), const Offset(-180, 0));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(g.storyIndex, 1); expect(g.storyIndex, 1);
// A normal swipe over the writing must work, not just the edge.
await tester.drag(find.text('By the cottage window'), const Offset(170, 0));
await tester.pumpAndSettle();
expect(g.storyIndex, 0);
await tester.drag(
find.text('For you, when you are ready'),
const Offset(-170, 0),
);
await tester.pumpAndSettle();
expect(g.storyIndex, 1);
expect( expect(
tester tester
.getBottomRight(find.text('A recorded reading, kept with this page')) .getBottomRight(find.text('A recorded reading, kept with this page'))
@@ -50,7 +60,7 @@ void main() {
lessThan(tester.getTopLeft(find.text('Contents')).dy), lessThan(tester.getTopLeft(find.text('Contents')).dy),
); );
await shot('02-cottage'); await shot('02-cottage');
// Actual native decoder, all five files. Position must survive pause/resume. // Actual native WAV playback, all five files. Position must survive pause/resume.
final narrator = Narrator(book.tracks); final narrator = Narrator(book.tracks);
for (final id in book.tracks.keys) { for (final id in book.tracks.keys) {
await narrator.toggle(id, 1); await narrator.toggle(id, 1);
@@ -85,6 +95,14 @@ void main() {
await tester.tap(find.byKey(const ValueKey('cell-0'))); await tester.tap(find.byKey(const ValueKey('cell-0')));
await tester.pumpAndSettle(); await tester.pumpAndSettle();
expect(g.cells[0], 1); expect(g.cells[0], 1);
await tester.tap(find.byKey(const ValueKey('cell-1')));
await tester.pump();
await tester.tap(find.byKey(const ValueKey('cell-1')));
await tester.pumpAndSettle();
expect(g.cells[1], 2);
await shot('03-pencil-marks');
await tap('Undo a mark');
await tap('Undo a mark');
await tap('Undo a mark'); await tap('Undo a mark');
expect(g.cells, before); expect(g.cells, before);
await tap('Next leaf →'); await tap('Next leaf →');
@@ -146,6 +164,48 @@ void main() {
expect(g.screen, Screen.reveal); expect(g.screen, Screen.reveal);
expect(g.solved, 2); expect(g.solved, 2);
await shot('07-campaign-reveal'); await shot('07-campaign-reveal');
// The later campaign leaves need swipes too, including read-ahead.
Future<void> swipeWriting(String text, double dx) async {
final target = find.text(text);
await tester.ensureVisible(target);
await tester.drag(target, Offset(dx, 0));
await tester.pumpAndSettle();
}
await swipeWriting('The lantern', 170);
expect(g.screen, Screen.briefing);
await swipeWriting('Something to carry the flame', -170);
expect(g.screen, Screen.reveal);
await swipeWriting('The lantern', -170);
expect(g.screen, Screen.briefing);
expect(g.campaignIndex, 2);
await swipeWriting('Under the loose floorboard', -170);
expect(g.screen, Screen.game);
await tester.ensureVisible(find.byKey(const ValueKey('cell-0')));
await tester.tap(find.byKey(const ValueKey('cell-0')));
await tester.pumpAndSettle();
final keyMarks = List<int>.of(g.cells);
await swipeWriting('Under the loose floorboard', -170);
await tap('Keep solving');
expect(g.screen, Screen.game);
await swipeWriting('Under the loose floorboard', -170);
await tap('Read ahead');
expect(g.screen, Screen.reveal);
expect(g.recovered(2), false);
expect(g.solved, 2);
await shot('08-campaign-read-ahead');
await swipeWriting('The brass key', -170);
expect(g.screen, Screen.briefing);
expect(g.campaignIndex, 3);
await swipeWriting('A direction in the dark', 170);
expect(g.screen, Screen.reveal);
expect(g.campaignIndex, 2);
await swipeWriting('The brass key', 170);
expect(g.screen, Screen.briefing);
await swipeWriting('Under the loose floorboard', -170);
expect(g.screen, Screen.game);
expect(g.cells, keyMarks);
expect(g.solved, 2);
// Exercise real plugin persistence without touching main-app data. // Exercise real plugin persistence without touching main-app data.
final disk = await Progress.load(); final disk = await Progress.load();
await disk.set('qa_roundtrip', 'notebook-and-audio'); await disk.set('qa_roundtrip', 'notebook-and-audio');
+11 -4
View File
@@ -60,8 +60,9 @@ class Game extends ChangeNotifier {
contents(); contents();
} else if (saved == 'briefing') { } else if (saved == 'briefing') {
briefing(campaignIndex); briefing(campaignIndex);
} else if (saved == 'reveal' && recovered(campaignIndex)) { } else if (saved == 'reveal' &&
reveal(campaignIndex); (recovered(campaignIndex) || progress.flag('flutter_read_ahead'))) {
reveal(campaignIndex, readAhead: progress.flag('flutter_read_ahead'));
} else if (saved == 'game') { } else if (saved == 'game') {
final mode = progress.text('flutter_mode'); final mode = progress.text('flutter_mode');
if (mode == 'campaign') { if (mode == 'campaign') {
@@ -79,6 +80,12 @@ class Game extends ChangeNotifier {
void _route(Screen value) { void _route(Screen value) {
screen = value; screen = value;
unawaited(progress.set('flutter_screen', value.name)); unawaited(progress.set('flutter_screen', value.name));
unawaited(
progress.set(
'flutter_read_ahead',
value == Screen.reveal && !recovered(campaignIndex),
),
);
unawaited(progress.set('flutter_campaign', campaignIndex)); unawaited(progress.set('flutter_campaign', campaignIndex));
unawaited(progress.set('flutter_mode', mode.name)); unawaited(progress.set('flutter_mode', mode.name));
unawaited(progress.set('flutter_date', date.toIso8601String())); unawaited(progress.set('flutter_date', date.toIso8601String()));
@@ -125,8 +132,8 @@ class Game extends ChangeNotifier {
_route(Screen.briefing); _route(Screen.briefing);
} }
void reveal(int i) { void reveal(int i, {bool readAhead = false}) {
if (!recovered(i)) { if (!recovered(i) && (!readAhead || i > accessible)) {
briefing(i); briefing(i);
return; return;
} }
+317 -134
View File
@@ -1,4 +1,5 @@
import 'dart:async'; import 'dart:async';
import 'dart:math' as math;
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart'; import 'package:flutter/foundation.dart';
@@ -183,6 +184,67 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
g.showStory(next); g.showStory(next);
} }
Future<void> turnCampaign(int direction) async {
final index = g.campaignIndex;
switch (g.screen) {
case Screen.briefing:
if (direction > 0) {
g.startCampaign(index);
} else if (index > 0) {
g.reveal(index - 1, readAhead: true);
} else {
g.contents();
}
case Screen.game:
if (direction < 0) {
g.briefing(index);
return;
}
if (!g.won &&
!await confirm(
'Leave a ribbon here?',
'Your puzzle marks are saved. You can read the memory now and return to this pattern whenever you like.',
'Read ahead',
no: 'Keep solving',
)) {
return;
}
if (mounted) g.reveal(index, readAhead: true);
case Screen.reveal:
if (direction < 0) {
g.briefing(index);
} else {
nextCampaign();
}
default:
break;
}
}
void nextCampaign() {
final index = g.campaignIndex;
if (index == 11) {
g.contents();
return;
}
// Reading access is distinct from completed puzzles and their awards.
unawaited(
prefs.set('story_access_level', math.max(g.accessible, index + 1)),
);
void next() {
if (mounted) g.briefing(index + 1);
}
if (g.recovered(index) &&
(index + 1) % 4 == 0 &&
!prefs.flag('storyAd_$index')) {
unawaited(prefs.set('storyAd_$index', true));
ads.between(next);
} else {
next();
}
}
void back() { void back() {
if (g.busy) { if (g.busy) {
g.home(); g.home();
@@ -358,46 +420,62 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
), ),
), ),
); );
Widget navigation() => column([ void bookmark() {
Row( unawaited(
children: [ prefs.set('notebook_manual_bookmark', g.book.pages[g.storyIndex].id),
Expanded(child: InkButton('Contents', g.contents, size: 20)), );
const SizedBox(width: 6), toast('A ribbon marks this page.');
Expanded( }
child: InkButton('Bookmark', () {
unawaited( Widget navigation() {
prefs.set( final wide = MediaQuery.orientationOf(context) == Orientation.landscape;
'notebook_manual_bookmark', final previous = InkButton(
g.book.pages[g.storyIndex].id, '← Previous leaf',
), g.storyIndex > 0 ? () => turn(-1) : null,
); size: wide ? 19 : 21,
toast('A ribbon marks this page.'); );
}, size: 20), final next = InkButton(
), g.storyIndex == 5 ? 'End of this trail' : 'Next leaf →',
const SizedBox(width: 6), g.storyIndex < 5 ? () => turn(1) : null,
Expanded(child: InkButton('Close book', g.home, size: 20)), size: wide ? 19 : 21,
], );
), if (wide) {
Row( // One row keeps the shorter landscape page free for the illustration
children: [ // and the puzzle beside it.
Expanded( return Row(
child: InkButton( children: [
'← Previous leaf', Expanded(child: InkButton('Contents', g.contents, size: 19)),
g.storyIndex > 0 ? () => turn(-1) : null, const SizedBox(width: 6),
size: 21, Expanded(child: InkButton('Bookmark', bookmark, size: 19)),
), const SizedBox(width: 6),
), Expanded(child: InkButton('Close book', g.home, size: 19)),
const SizedBox(width: 8), const SizedBox(width: 6),
Expanded( Expanded(child: previous),
child: InkButton( const SizedBox(width: 6),
g.storyIndex == 5 ? 'End of this trail' : 'Next leaf →', Expanded(child: next),
g.storyIndex < 5 ? () => turn(1) : null, ],
size: 21, );
), }
), return column([
], Row(
), children: [
]); Expanded(child: InkButton('Contents', g.contents, size: 20)),
const SizedBox(width: 6),
Expanded(child: InkButton('Bookmark', bookmark, size: 20)),
const SizedBox(width: 6),
Expanded(child: InkButton('Close book', g.home, size: 20)),
],
),
Row(
children: [
Expanded(child: previous),
const SizedBox(width: 8),
Expanded(child: next),
],
),
]);
}
Widget reading(String text) => ListenableBuilder( Widget reading(String text) => ListenableBuilder(
listenable: narrator, listenable: narrator,
builder: (context, _) { builder: (context, _) {
@@ -472,10 +550,12 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
); );
Widget story() { Widget story() {
final p = g.book.pages[g.storyIndex]; final p = g.book.pages[g.storyIndex];
final body = <Widget>[ final heading = <Widget>[
folio('MARA’S NOTEBOOK / ${g.storyIndex + 1} OF 6'), folio('MARA’S NOTEBOOK / ${g.storyIndex + 1} OF 6'),
writing(p.title, size: 31), writing(p.title, size: 31),
]; ];
final body = <Widget>[...heading];
Widget? wideBody;
switch (g.storyIndex) { switch (g.storyIndex) {
case 0: case 0:
body.addAll([ body.addAll([
@@ -495,14 +575,15 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
audio(), audio(),
]); ]);
case 2: case 2:
body.addAll([ final intro = writing(
writing( 'Restore a small light, or leave a bookmark and read on.',
'Restore a small light, or leave a bookmark and read on.', size: 21,
size: 21, color: muted,
color: muted, );
), body.addAll([intro, puzzleBody()]);
puzzleBody(), wideBody = splitPuzzle(
]); side: [...heading, intro, areaPicker(), ...puzzleNotes()],
);
case 3: case 3:
body.addAll([ body.addAll([
const Sketch('match'), const Sketch('match'),
@@ -578,6 +659,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
key: ValueKey('story-${g.storyIndex}'), key: ValueKey('story-${g.storyIndex}'),
onTurn: (d) => turn(d), onTurn: (d) => turn(d),
body: column(body), body: column(body),
wideBody: wideBody,
footer: navigation(), footer: navigation(),
); );
} }
@@ -677,6 +759,7 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
final l = g.book.levels[g.campaignIndex]; final l = g.book.levels[g.campaignIndex];
return Leaf( return Leaf(
key: ValueKey('briefing-${g.campaignIndex}'), key: ValueKey('briefing-${g.campaignIndex}'),
onTurn: (d) => turnCampaign(d),
body: column([ body: column([
folio('MARA’S NOTEBOOK / LEAF ${g.campaignIndex + 1}'), folio('MARA’S NOTEBOOK / LEAF ${g.campaignIndex + 1}'),
writing(l.chapter, size: 20, color: blue), writing(l.chapter, size: 20, color: blue),
@@ -703,67 +786,116 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
); );
} }
Widget puzzleBody() { Widget puzzleBody() => column([areaPicker(), board(), ...puzzleNotes()]);
Widget areaPicker() {
final p = g.puzzle; final p = g.puzzle;
if (p == null) return const SizedBox.shrink(); if (p == null || p.regions.isEmpty) return const SizedBox.shrink();
return column([ return column([
if (p.regions.isNotEmpty) ...[ Wrap(
Wrap( spacing: 6,
spacing: 6, children: [
children: [ for (var i = 0; i < p.regions.length; i++)
for (var i = 0; i < p.regions.length; i++) InkButton(
InkButton( '${p.regions[i].label} · ${List.generate(g.cells.length, (j) => j).where((j) => p.regions[i].contains(j, p.size) && g.cells[j] == 1).length} / ${p.regionTotal(p.regions[i])}',
'${p.regions[i].label} · ${List.generate(g.cells.length, (j) => j).where((j) => p.regions[i].contains(j, p.size) && g.cells[j] == 1).length} / ${p.regionTotal(p.regions[i])}', () => g.area(i),
() => g.area(i), size: 21,
size: 21, primary: i == g.selectedArea,
primary: i == g.selectedArea,
),
],
),
writing('Tap A, B or C to highlight its area', size: 17, color: muted),
],
Board(
puzzle: p,
cells: g.cells,
onMark: g.mark,
selectedArea: g.selectedArea,
won: g.won,
),
writing(
g.won
? 'Already restored. Turn the leaf to revisit the memory.'
: 'Tap: light → cross → clear. Mark every cell.',
size: 18,
color: muted,
),
if (!g.won)
Row(
children: [
Expanded(
child: InkButton(
'Undo a mark',
g.canUndo ? g.undo : null,
size: 22,
),
), ),
const SizedBox(width: 8), ],
Expanded( ),
child: InkButton( writing('Tap A, B or C to highlight its area', size: 17, color: muted),
prefs.flag('hint_${g.key}')
? 'Hint · rewarded ad'
: 'Hint · free',
hint,
size: 22,
),
),
],
),
]); ]);
} }
Widget game() => Leaf( Widget board({double maxWidth = 350}) {
key: ValueKey('game-${g.key}'), final p = g.puzzle;
body: column([ if (p == null) return const SizedBox.shrink();
return Board(
puzzle: p,
cells: g.cells,
onMark: g.mark,
selectedArea: g.selectedArea,
won: g.won,
maxWidth: maxWidth,
);
}
List<Widget> puzzleNotes() => [
writing(
g.won
? 'Already restored. Turn the leaf to revisit the memory.'
: 'Tap: light → cross → clear. Mark every cell.',
size: 18,
color: muted,
),
if (!g.won)
Row(
children: [
Expanded(
child: InkButton(
'Undo a mark',
g.canUndo ? g.undo : null,
size: 22,
),
),
const SizedBox(width: 8),
Expanded(
child: InkButton(
prefs.flag('hint_${g.key}')
? 'Hint · rewarded ad'
: 'Hint · free',
hint,
size: 22,
),
),
],
),
];
/// Landscape puzzle leaf: the grid keeps the left column at its full height
/// while the heading, area clues and notes sit beside it, so nothing has to
/// be scrolled into view before the board can be played.
Widget splitPuzzle({required List<Widget> side}) => LayoutBuilder(
builder: (context, c) {
final width = math.min(c.maxWidth, 980.0),
height = c.maxHeight.isFinite ? c.maxHeight : c.maxWidth,
// Keep a readable column for the notes, then give the rest to the
// grid, which stays a square no taller than the page.
panel = math.min(
math.min(280.0, math.max(200.0, width * .40)),
width * .55,
),
grid = math.min(math.min(height, width - panel - 18), 520.0);
return Align(
alignment: Alignment.center,
child: SizedBox(
width: width,
height: height,
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SizedBox(
width: grid,
child: Center(child: board(maxWidth: grid)),
),
const SizedBox(width: 18),
Expanded(
child: SingleChildScrollView(
key: const PageStorageKey('leaf-side-scroll'),
padding: const EdgeInsets.fromLTRB(2, 0, 2, 8),
child: column(side),
),
),
],
),
),
);
},
);
Widget game() {
List<Widget> heading({bool compact = false}) => [
folio( folio(
g.mode == Mode.daily g.mode == Mode.daily
? 'DAILY / ${DateFormat('d MMMM').format(g.date)}' ? 'DAILY / ${DateFormat('d MMMM').format(g.date)}'
@@ -775,28 +907,79 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
g.mode == Mode.campaign g.mode == Mode.campaign
? g.book.levels[g.campaignIndex].title ? g.book.levels[g.campaignIndex].title
: 'Find the light.', : 'Find the light.',
size: 32, size: compact ? 27 : 32,
), ),
writing( writing(
g.puzzle!.regions.isEmpty g.puzzle?.regions.isEmpty ?? true
? 'Match the totals. Let the pattern emerge.' ? 'Match the totals. Let the pattern emerge.'
: 'Compare rows, columns and overlapping areas.', : 'Compare rows, columns and overlapping areas.',
size: 21, size: compact ? 18 : 21,
color: muted, color: muted,
), ),
puzzleBody(), ];
if (g.won) ...[ final actions = <({String label, VoidCallback run, bool primary})>[
writing('A moment of clarity.', size: 29), if (g.won)
action( (
g.mode == Mode.daily ? 'Return to the notebook' : 'Next puzzle →', label: g.mode == Mode.daily
g.mode == Mode.daily ? g.home : nextPractice, ? 'Return to the notebook'
: 'Next puzzle →',
run: g.mode == Mode.daily ? g.home : nextPractice,
primary: true, primary: true,
), ),
], (label: 'How to play', run: rules, primary: false),
action('How to play', rules), (
action('Back to notebook', g.mode == Mode.campaign ? g.contents : g.home), label: 'Back to notebook',
]), run: g.mode == Mode.campaign ? g.contents : g.home,
); primary: false,
),
];
final clarity = writing('A moment of clarity.', size: 29);
return Leaf(
key: ValueKey('game-${g.key}'),
onTurn: g.mode == Mode.campaign ? (d) => turnCampaign(d) : null,
body: column([
...heading(),
puzzleBody(),
if (g.won) clarity,
for (final a in actions) action(a.label, a.run, primary: a.primary),
]),
// Landscape: the heading and notes sit beside the grid while the leaf's
// actions stay in a compact bar that does not take room from the board.
wideBody: Column(
children: [
Expanded(
child: splitPuzzle(
side: [
...heading(compact: true),
areaPicker(),
...puzzleNotes(),
if (g.won) writing('A moment of clarity.', size: 23),
],
),
),
Padding(
padding: const EdgeInsets.only(top: 6, bottom: 4),
child: Row(
children: [
for (var i = 0; i < actions.length; i++) ...[
if (i > 0) const SizedBox(width: 8),
Expanded(
child: InkButton(
actions[i].label,
actions[i].run,
size: 20,
primary: actions[i].primary,
),
),
],
],
),
),
],
),
);
}
Future<void> hint() async { Future<void> hint() async {
final requested = g.key; final requested = g.key;
void give() async { void give() async {
@@ -847,10 +1030,13 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
final i = g.campaignIndex, l = g.book.levels[i]; final i = g.campaignIndex, l = g.book.levels[i];
return Leaf( return Leaf(
key: ValueKey('reveal-$i'), key: ValueKey('reveal-$i'),
onTurn: (d) => turnCampaign(d),
body: column([ body: column([
folio('MARA’S NOTEBOOK / LEAF ${i + 1}'), folio('MARA’S NOTEBOOK / LEAF ${i + 1}'),
writing( writing(
'Something found. Something remembered.', g.recovered(i)
? 'Something found. Something remembered.'
: 'A memory to read · your pattern can wait',
size: 23, size: 23,
color: muted, color: muted,
), ),
@@ -859,31 +1045,28 @@ class _NotebookState extends State<Notebook> with WidgetsBindingObserver {
writing(l.after, size: 25), writing(l.after, size: 25),
gap(), gap(),
writing( writing(
'Kept safe, between these pages. — M.', g.recovered(i)
? 'Kept safe, between these pages. — M.'
: 'Your pattern is saved for another day.',
size: 23, size: 23,
color: const Color(0xff70503b), color: const Color(0xff70503b),
), ),
divider(), divider(),
if (i == 11) ...[ if (i == 11) ...[
folio('THE END · YOUR WATCH HAS BEGUN'), folio(
g.recoveredCount == 12
? 'THE END · YOUR WATCH HAS BEGUN'
: 'THE LAST PAGE · COME BACK WHENEVER YOU LIKE',
),
writing( writing(
'Twelve patterns. One light brought home. The daily puzzle will be here whenever you return.', g.recoveredCount == 12
? 'Twelve patterns. One light brought home. The daily puzzle will be here whenever you return.'
: 'A light kept in these pages. Your unfinished patterns will be here whenever you return.',
), ),
action('Return to the notebook', g.contents, primary: true), action('Return to the notebook', g.contents, primary: true),
action('Today’s puzzle', () => g.startDaily(DateTime.now())), action('Today’s puzzle', () => g.startDaily(DateTime.now())),
] else ] else
action('Turn the page →', () { action('Turn the page →', nextCampaign, primary: true),
void next() {
if (mounted) g.briefing(i + 1);
}
if ((i + 1) % 4 == 0 && !prefs.flag('storyAd_$i')) {
unawaited(prefs.set('storyAd_$i', true));
ads.between(next);
} else {
next();
}
}, primary: true),
action('Back to notebook', g.contents), action('Back to notebook', g.contents),
]), ]),
); );
+1
View File
@@ -67,6 +67,7 @@ class Narrator extends ChangeNotifier {
await session.configure(const AudioSessionConfiguration.speech()); await session.configure(const AudioSessionConfiguration.speech());
if (generation != _generation) return; if (generation != _generation) return;
page = id; page = id;
// PCM WAV avoids silent FLAC playback on the API 26 Huawei tablet.
await _player.setAsset('assets/audio/${tracks[id]['file']}'); await _player.setAsset('assets/audio/${tracks[id]['file']}');
if (generation != _generation) return; if (generation != _generation) return;
} else if (finished) { } else if (finished) {
+211 -127
View File
@@ -1,3 +1,5 @@
import 'dart:math' as math;
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import '../domain/puzzle.dart'; import '../domain/puzzle.dart';
@@ -11,163 +13,245 @@ class Board extends StatelessWidget {
required this.onMark, required this.onMark,
this.selectedArea = 0, this.selectedArea = 0,
this.won = false, this.won = false,
this.maxWidth = 350,
}); });
final Puzzle puzzle; final Puzzle puzzle;
final List<int> cells; final List<int> cells;
final ValueChanged<int> onMark; final ValueChanged<int> onMark;
final int selectedArea; final int selectedArea;
final bool won; final bool won;
/// Wide leaves give the grid more room; it still stays a square.
final double maxWidth;
@override @override
Widget build(BuildContext context) => Center( Widget build(BuildContext context) => PageSwipeBlocker(
child: ConstrainedBox( child: Center(
constraints: const BoxConstraints(maxWidth: 350), child: ConstrainedBox(
child: AspectRatio( constraints: BoxConstraints(maxWidth: maxWidth),
aspectRatio: 1, child: AspectRatio(
child: LayoutBuilder( aspectRatio: 1,
builder: (context, c) { child: LayoutBuilder(
final n = puzzle.size, builder: (context, c) {
u = c.maxWidth / (n + 1.3), final n = puzzle.size,
r = puzzle.regions.isEmpty u = c.maxWidth / (n + 1.3),
? null r = puzzle.regions.isEmpty
: puzzle.regions[selectedArea]; ? null
Widget clue(String text, bool complete) => SizedBox( : puzzle.regions[selectedArea];
width: u, Widget clue(String text, bool complete) => SizedBox(
height: u, width: u,
child: Center( height: u,
child: Text( child: Center(
text, child: Text(
style: hand( text,
(u * .42).clamp(16, 23), style: hand(
color: complete ? blue : muted, (u * .42).clamp(16, 23),
color: complete ? blue : muted,
),
), ),
), ),
), );
); bool complete(Iterable<int> indices, int total) =>
bool complete(Iterable<int> indices, int total) => indices.where((i) => cells[i] == 1).length == total;
indices.where((i) => cells[i] == 1).length == total; return Align(
return Align( alignment: Alignment.center,
alignment: Alignment.center, child: Column(
child: Column( mainAxisSize: MainAxisSize.min,
mainAxisSize: MainAxisSize.min, children: [
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
SizedBox(width: u, height: u),
for (var col = 0; col < n; col++)
clue(
'${puzzle.cols[col]}',
complete(
List.generate(n, (i) => i * n + col),
puzzle.cols[col],
),
),
],
),
for (var row = 0; row < n; row++)
Row( Row(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
clue( SizedBox(width: u, height: u),
'${puzzle.rows[row]}',
complete(
List.generate(n, (i) => row * n + i),
puzzle.rows[row],
),
),
for (var col = 0; col < n; col++) for (var col = 0; col < n; col++)
Builder( clue(
builder: (context) { '${puzzle.cols[col]}',
final i = row * n + col, complete(
value = cells[i], List.generate(n, (i) => i * n + col),
fixed = puzzle.given[i], puzzle.cols[col],
inside = r?.contains(i, n) ?? false; ),
final state = value == 0 ),
? 'empty' ],
: value == 1 ),
? 'lit' for (var row = 0; row < n; row++)
: 'crossed out'; Row(
return Semantics( mainAxisAlignment: MainAxisAlignment.center,
label: children: [
'Row ${row + 1}, column ${col + 1}, $state${fixed ? ', fixed clue' : ''}', clue(
button: !fixed && !won, '${puzzle.rows[row]}',
enabled: !fixed && !won, complete(
onTap: fixed || won ? null : () => onMark(i), List.generate(n, (i) => row * n + i),
excludeSemantics: true, puzzle.rows[row],
child: GestureDetector( ),
key: ValueKey('cell-$i'), ),
behavior: HitTestBehavior.opaque, for (var col = 0; col < n; col++)
Builder(
builder: (context) {
final i = row * n + col,
value = cells[i],
fixed = puzzle.given[i],
inside = r?.contains(i, n) ?? false;
final state = value == 0
? 'empty'
: value == 1
? 'lit'
: 'crossed out';
return Semantics(
label:
'Row ${row + 1}, column ${col + 1}, $state${fixed ? ', fixed clue' : ''}',
button: !fixed && !won,
enabled: !fixed && !won,
onTap: fixed || won ? null : () => onMark(i), onTap: fixed || won ? null : () => onMark(i),
child: SizedBox( excludeSemantics: true,
width: u, child: GestureDetector(
height: u, key: ValueKey('cell-$i'),
child: Padding( behavior: HitTestBehavior.opaque,
padding: const EdgeInsets.all(2), onTap: fixed || won
child: DecoratedBox( ? null
decoration: BoxDecoration( : () => onMark(i),
color: value == 1 child: SizedBox(
? blue width: u,
: inside height: u,
? amber.withValues(alpha: .22) child: Padding(
: Colors.transparent, padding: const EdgeInsets.all(2),
borderRadius: BorderRadius.circular( child: DecoratedBox(
2, decoration: BoxDecoration(
),
border: Border.all(
color: inside color: inside
? const Color(0xffaa5b2a) ? amber.withValues(alpha: .22)
: muted.withValues(alpha: .48), : Colors.transparent,
width: inside ? 1.4 : .65, borderRadius: BorderRadius.circular(
2,
),
border: Border.all(
color: inside
? const Color(0xffaa5b2a)
: muted.withValues(
alpha: .48,
),
width: inside ? 1.4 : .65,
),
), ),
), child: Stack(
child: Stack( children: [
children: [ if (value != 0)
if (value == 2) Positioned.fill(
Center( child: CustomPaint(
child: Text( painter: PencilMark(
'×', value: value,
style: hand( variation: i,
u * .62, ),
color: muted,
), ),
), ),
), if (fixed)
if (fixed) Positioned(
Positioned( right: 3,
right: 3, bottom: 3,
bottom: 3, child: Container(
child: Container( width: 4,
width: 4, height: 4,
height: 4, decoration: BoxDecoration(
decoration: BoxDecoration( color: muted,
color: value == 1 shape: BoxShape.circle,
? cream ),
: muted,
shape: BoxShape.circle,
), ),
), ),
), ],
], ),
), ),
), ),
), ),
), ),
), );
); },
}, ),
), ],
], ),
), ],
], ),
), );
); },
}, ),
), ),
), ),
), ),
); );
} }
/// Deterministic pencil strokes stay put when the player revisits a cell.
/// Both marks use paths, so their appearance never depends on a fallback font.
class PencilMark extends CustomPainter {
const PencilMark({required this.value, required this.variation});
final int value, variation;
@override
void paint(Canvas canvas, Size size) {
final unit = math.min(size.width, size.height);
final wobble = ((variation % 5) - 2) * .006;
final paint = Paint()
..isAntiAlias = true
..style = PaintingStyle.stroke
..strokeCap = StrokeCap.round
..strokeJoin = StrokeJoin.round;
canvas.save();
canvas.scale(size.width, size.height);
if (value == 1) {
paint
..color = blue.withValues(alpha: .78)
..strokeWidth = 1.65 / unit;
// Closely spaced, slightly wandering strokes shade the cell by hand.
canvas.clipRect(const Rect.fromLTWH(.13, .13, .74, .74));
for (var line = -12; line <= 20; line++) {
final x = line * .065;
canvas.drawPath(
Path()
..moveTo(x, .90)
..quadraticBezierTo(x + .34 + wobble, .52, x + .68, .09),
paint,
);
}
paint
..color = blue.withValues(alpha: .34)
..strokeWidth = .8 / unit;
for (var line = -6; line <= 12; line++) {
final x = line * .13;
canvas.drawPath(
Path()
..moveTo(x, .12)
..quadraticBezierTo(x + .3, .50 + wobble, x + .59, .89),
paint,
);
}
} else {
paint
..color = muted
..strokeWidth = 1.8 / unit;
canvas.drawPath(
Path()
..moveTo(.26, .24 + wobble)
..cubicTo(.43, .38, .58, .64, .76, .77),
paint,
);
canvas.drawPath(
Path()
..moveTo(.75, .22)
..cubicTo(.61, .42 + wobble, .40, .59, .24, .78),
paint,
);
paint
..color = muted.withValues(alpha: .30)
..strokeWidth = .65 / unit;
canvas.drawPath(
Path()
..moveTo(.28, .25)
..quadraticBezierTo(.54, .56, .74, .79),
paint,
);
}
canvas.restore();
}
@override
bool shouldRepaint(PencilMark old) =>
value != old.value || variation != old.variation;
}
class PixelPicture extends StatelessWidget { class PixelPicture extends StatelessWidget {
const PixelPicture( const PixelPicture(
this.picture, { this.picture, {
+114 -61
View File
@@ -1,6 +1,7 @@
import 'dart:math' as math; import 'dart:math' as math;
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart';
const ink = Color(0xff36413c), const ink = Color(0xff36413c),
blue = Color(0xff274956), blue = Color(0xff274956),
@@ -31,23 +32,25 @@ class InkButton extends StatelessWidget {
final double size; final double size;
final bool primary; final bool primary;
@override @override
Widget build(BuildContext context) => DecoratedBox( Widget build(BuildContext context) => PageSwipeBlocker(
decoration: BoxDecoration( child: DecoratedBox(
border: Border( decoration: BoxDecoration(
bottom: BorderSide(color: blue.withValues(alpha: primary ? .5 : .18)), border: Border(
bottom: BorderSide(color: blue.withValues(alpha: primary ? .5 : .18)),
),
), ),
), child: TextButton(
child: TextButton( onPressed: onPressed,
onPressed: onPressed, style: TextButton.styleFrom(
style: TextButton.styleFrom( foregroundColor: blue,
foregroundColor: blue, disabledForegroundColor: muted.withValues(alpha: .4),
disabledForegroundColor: muted.withValues(alpha: .4), textStyle: hand(size),
textStyle: hand(size), minimumSize: const Size(48, 48),
minimumSize: const Size(48, 48), padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 8),
padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 8), shape: const RoundedRectangleBorder(),
shape: const RoundedRectangleBorder(), ),
child: Text(label, textAlign: TextAlign.center),
), ),
child: Text(label, textAlign: TextAlign.center),
), ),
); );
} }
@@ -61,7 +64,8 @@ class Paper extends StatefulWidget {
} }
class _PaperState extends State<Paper> { class _PaperState extends State<Paper> {
Offset? start; Offset _drag = Offset.zero;
Offset _origin = Offset.zero;
@override @override
Widget build(BuildContext context) => ColoredBox( Widget build(BuildContext context) => ColoredBox(
color: const Color(0xff314345), color: const Color(0xff314345),
@@ -91,38 +95,55 @@ class _PaperState extends State<Paper> {
top + h * .91, top + h * .91,
); );
return Listener( return Listener(
onPointerDown: (e) { onPointerCancel: (_) {
start = _drag = Offset.zero;
(e.localPosition.dx < content.left ||
e.localPosition.dx > content.right)
? e.localPosition
: null;
}, },
onPointerUp: (e) { child: GestureDetector(
final origin = start; behavior: HitTestBehavior.opaque,
start = null; dragStartBehavior: DragStartBehavior.down,
if (origin == null) return; onHorizontalDragStart: widget.onTurn == null
final d = e.localPosition - origin; ? null
if (d.dx.abs() > 55 && d.dx.abs() > d.dy.abs() * 1.5) { : (details) {
widget.onTurn?.call(d.dx < 0 ? 1 : -1); _origin = details.globalPosition;
} _drag = Offset.zero;
}, },
child: Stack( onHorizontalDragUpdate: widget.onTurn == null
clipBehavior: Clip.hardEdge, ? null
children: [ : (details) {
Positioned( _drag = details.globalPosition - _origin;
left: left, },
top: top, onHorizontalDragCancel: widget.onTurn == null
width: w, ? null
height: h, : () {
child: Image.asset( _drag = Offset.zero;
'assets/artwork/mara-single-page-v2.png', },
fit: BoxFit.fill, onHorizontalDragEnd: widget.onTurn == null
excludeFromSemantics: true, ? null
: (_) {
final drag = _drag;
_drag = Offset.zero;
if (drag.dx.abs() >= 48 &&
drag.dx.abs() > drag.dy.abs() * 1.3) {
widget.onTurn?.call(drag.dx < 0 ? 1 : -1);
}
},
child: Stack(
clipBehavior: Clip.hardEdge,
children: [
Positioned(
left: left,
top: top,
width: w,
height: h,
child: Image.asset(
'assets/artwork/mara-single-page-v2.png',
fit: BoxFit.fill,
excludeFromSemantics: true,
),
), ),
), Positioned.fromRect(rect: content, child: widget.child),
Positioned.fromRect(rect: content, child: widget.child), ],
], ),
), ),
); );
}, },
@@ -131,27 +152,59 @@ class _PaperState extends State<Paper> {
); );
} }
/// A descendant horizontal recognizer wins over the page recognizer on drags.
/// Taps still reach the controls, and vertical drags can reach a ScrollView.
class PageSwipeBlocker extends StatelessWidget {
const PageSwipeBlocker({super.key, required this.child});
final Widget child;
@override
Widget build(BuildContext context) => GestureDetector(
behavior: HitTestBehavior.opaque,
onHorizontalDragStart: (_) {},
onHorizontalDragUpdate: (_) {},
onHorizontalDragEnd: (_) {},
child: child,
);
}
class Leaf extends StatelessWidget { class Leaf extends StatelessWidget {
const Leaf({super.key, required this.body, this.footer, this.onTurn}); const Leaf({
super.key,
required this.body,
this.wideBody,
this.footer,
this.onTurn,
});
final Widget body; final Widget body;
/// Replaces [body] on a landscape page. The shorter page suits side-by-side
/// columns better than one long scroll, so it should arrange its own panes.
final Widget? wideBody;
final Widget? footer; final Widget? footer;
final ValueChanged<int>? onTurn; final ValueChanged<int>? onTurn;
@override @override
Widget build(BuildContext context) => Paper( Widget build(BuildContext context) {
onTurn: onTurn, final wide =
child: Column( wideBody != null &&
children: [ MediaQuery.orientationOf(context) == Orientation.landscape;
Expanded( return Paper(
child: SingleChildScrollView( onTurn: onTurn,
key: const PageStorageKey('leaf-scroll'), child: Column(
padding: const EdgeInsets.fromLTRB(4, 0, 4, 8), children: [
child: body, Expanded(
child: wide
? wideBody!
: SingleChildScrollView(
key: const PageStorageKey('leaf-scroll'),
padding: const EdgeInsets.fromLTRB(4, 0, 4, 8),
child: body,
),
), ),
), ?footer,
?footer, ],
], ),
), );
); }
} }
class Cover extends StatelessWidget { class Cover extends StatelessWidget {
+7 -2
View File
@@ -1,7 +1,7 @@
name: lumen name: lumen
description: Mara's island notebook — an offline illustrated logic puzzle. description: Mara's island notebook — an offline illustrated logic puzzle.
publish_to: none publish_to: none
version: 2.0.0+9 version: 2.0.2+11
environment: environment:
sdk: '>=3.13.0 <4.0.0' sdk: '>=3.13.0 <4.0.0'
dependencies: dependencies:
@@ -29,7 +29,12 @@ flutter:
- assets/artwork/cottage-vignette-v1.png - assets/artwork/cottage-vignette-v1.png
- assets/artwork/lantern-vignette-v1.png - assets/artwork/lantern-vignette-v1.png
- assets/narration/scripts.json - assets/narration/scripts.json
- assets/audio/ - assets/audio/narration_manifest.json
- assets/audio/narration_cottage_dedication.wav
- assets/audio/narration_cottage_window.wav
- assets/audio/narration_cottage_match_memory.wav
- assets/audio/narration_cottage_folded_note.wav
- assets/audio/narration_cottage_lantern_sketch.wav
fonts: fonts:
- family: MaraHand - family: MaraHand
fonts: fonts:
+24 -5
View File
@@ -24,10 +24,29 @@ launch();time.sleep(2)
# Leave the player's actual consent decision to them if UMP requires it. # Leave the player's actual consent decision to them if UMP requires it.
root=dump() root=dump()
assert not any('Welcome to Publisher Test Ads' in value(n) for n in root.iter('node')),'Consent form is awaiting the player’s choice.' assert not any('Welcome to Publisher Test Ads' in value(n) for n in root.iter('node')),'Consent form is awaiting the player’s choice.'
if any('Close book' in value(n) for n in root.iter('node')):tap('Close book') for attempt in range(8):
root=dump()
if any('Open Mara’s notebook' in value(n) for n in root.iter('node')):break
if any('Close book' in value(n) for n in root.iter('node')):tap('Close book')
else:adb('shell','input','keyevent','4')
else:raise AssertionError('Could not return to the home screen')
if a.expect_fresh:find('0 / 12');find('0\nPATTERNS FOUND') if a.expect_fresh:find('0 / 12');find('0\nPATTERNS FOUND')
shot('main-home.png');tap('Open Mara’s notebook');find('For you, when you are ready');tap('Next leaf');find('By the cottage window') shot('main-home.png');tap('Open Mara’s notebook');tap('Contents');tap('1 · For you, when you are ready')
play=find('Play this reading');tapnode(play);time.sleep(2);shot('main-recording.png');tapnode(play);find('Resume recording') def swipe_text(text,dx):
n=find(text);x1,y1,x2,y2=map(int,re.findall(r'\d+',n.get('bounds')));x=(x1+x2)//2;y=(y1+y2)//2
adb('shell','input','swipe',str(x),str(y),str(x+dx),str(y),'350')
swipe_text('For you, when you are ready',-360);find('By the cottage window')
swipe_text('By the cottage window',360);find('For you, when you are ready')
tap('Next leaf');find('By the cottage window')
play=find('Play this reading');tapnode(play);time.sleep(2)
# A clock can advance even when the decoder creates no audio track. Inspect
# the real mixer while playback is active (verified on the API 26 tablet).
pid=adb('shell','pidof',a.package).decode().strip().split()[0]
mixer=adb('shell','dumpsys','media.audio_flinger').decode(errors='replace')
(out/'active-audio-track.txt').write_text(mixer)
tracks=[line.split() for line in mixer.splitlines()]
assert any(len(t)>13 and t[1]=='yes' and t[2]==pid and t[3]=='3' and t[8]=='A' and t[10]=='24000' and all(v!='-inf' for v in t[11:14]) for t in tracks),'The timer is not enough: no active, unmuted 24 kHz media track for this app'
shot('main-recording.png');tapnode(play);find('Resume recording')
def seconds(): def seconds():
n=find('Paused ·');m=re.search(r'(\d+):(\d+)',value(n));return int(m[1])*60+int(m[2]) n=find('Paused ·');m=re.search(r'(\d+):(\d+)',value(n));return int(m[1])*60+int(m[2])
first=seconds();assert first>=1 first=seconds();assert first>=1
@@ -36,5 +55,5 @@ tap('Stop');find('Play this reading')
adb('shell','am','force-stop',a.package);launch();find('By the cottage window');find('Play this reading');shot('main-restored-page.png') adb('shell','am','force-stop',a.package);launch();find('By the cottage window');find('Play this reading');shot('main-restored-page.png')
tap('Close book') tap('Close book')
if a.expect_fresh:find('0 / 12');find('0\nPATTERNS FOUND') if a.expect_fresh:find('0 / 12');find('0\nPATTERNS FOUND')
print('PASS: optimized app launches, starts fresh, plays through its UI, resumes audio, restores the reading place after process restart and leaves puzzle counts unchanged.') print('PASS: optimized app launches, swipes over the writing in both directions, plays through its UI, resumes audio and restores the reading place after process restart.')
(out/'release-smoke.txt').write_text('PASS: fresh Flutter progress; release startup; UI FLAC playback/pause/resume/stop; process restart restores page; 0 puzzles awarded by reading.\n') (out/'release-smoke.txt').write_text('PASS: '+('fresh Flutter progress; ' if a.expect_fresh else '')+'release startup; writing-area swipes both ways; active PCM audio track; UI WAV playback/pause/resume/stop; process restart restores page.\n')
+4 -2
View File
@@ -18,7 +18,9 @@ for record in canonical:
for cue in track['cues']: for cue in track['cues']:
assert previous<=cue['startMs']<cue['endMs']<=track['durationMs'] assert previous<=cue['startMs']<cue['endMs']<=track['durationMs']
previous=cue['endMs'] previous=cue['endMs']
wav=source/'wav'/(record['resource']+'.wav');flac=raw/track['file'] wav=source/'wav'/(record['resource']+'.wav');flac=raw/track['flacFile']
assert (raw/track['file']).read_bytes()==wav.read_bytes(),'Runtime WAV differs from its reviewed master'
assert track['wavSha256']==hashlib.sha256(wav.read_bytes()).hexdigest()
with wave.open(str(wav),'rb') as reader: with wave.open(str(wav),'rb') as reader:
assert reader.getnchannels()==1 and reader.getsampwidth()==2 and reader.getframerate()==24000 assert reader.getnchannels()==1 and reader.getsampwidth()==2 and reader.getframerate()==24000
assert reader.getnframes()==track['frames'] assert reader.getnframes()==track['frames']
@@ -28,7 +30,7 @@ for record in canonical:
decoded=subprocess.check_output(['ffmpeg','-v','error','-i',str(flac),'-f','s16le','-acodec','pcm_s16le','-']) decoded=subprocess.check_output(['ffmpeg','-v','error','-i',str(flac),'-f','s16le','-acodec','pcm_s16le','-'])
assert decoded==master,'Runtime FLAC must preserve the WAV master exactly' assert decoded==master,'Runtime FLAC must preserve the WAV master exactly'
assert track['flacSha256']==hashlib.sha256(flac.read_bytes()).hexdigest() assert track['flacSha256']==hashlib.sha256(flac.read_bytes()).hexdigest()
print(f"PASS {record['pageId']}: {track['durationMs']/1000:.1f}s, lossless, text/cues match") print(f"PASS {record['pageId']}: {track['durationMs']/1000:.1f}s, WAV/master match, FLAC lossless, text/cues match")
for p in (root/'lib').rglob('*.dart'): for p in (root/'lib').rglob('*.dart'):
assert 'flutter_tts' not in p.read_text(),f'Device reader reintroduced in {p}' assert 'flutter_tts' not in p.read_text(),f'Device reader reintroduced in {p}'
print('All five recordings verified; bundled file playback only.') print('All five recordings verified; bundled file playback only.')
+3 -2
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""Prepare immutable WAV masters and bundled FLACs; Android performs no speech synthesis.""" """Prepare immutable WAV masters and bundled FLACs; Android performs no speech synthesis."""
import argparse, hashlib, importlib.metadata, json, subprocess import argparse, hashlib, importlib.metadata, json, subprocess, shutil
from pathlib import Path from pathlib import Path
import numpy as np import numpy as np
import soundfile as sf import soundfile as sf
@@ -46,10 +46,11 @@ for record in json.loads((source/'scripts.json').read_text()):
audio*=.86/peak audio*=.86/peak
wav=source/'wav'/f"{record['resource']}.wav";flac=raw/f"{record['resource']}.flac" wav=source/'wav'/f"{record['resource']}.wav";flac=raw/f"{record['resource']}.flac"
sf.write(wav,audio,rate,subtype='PCM_16') sf.write(wav,audio,rate,subtype='PCM_16')
shutil.copyfile(wav,raw/wav.name)
subprocess.run(['ffmpeg','-v','error','-y','-i',str(wav),'-c:a','flac','-compression_level','8',str(flac)],check=True) subprocess.run(['ffmpeg','-v','error','-y','-i',str(wav),'-c:a','flac','-compression_level','8',str(flac)],check=True)
decoded,check_rate=sf.read(flac,dtype='int16');master,_=sf.read(wav,dtype='int16') decoded,check_rate=sf.read(flac,dtype='int16');master,_=sf.read(wav,dtype='int16')
assert check_rate==rate and np.array_equal(decoded,master) assert check_rate==rate and np.array_equal(decoded,master)
tracks[record['pageId']]={**record,'file':flac.name,'sampleRate':rate,'channels':1,'frames':len(audio), tracks[record['pageId']]={**record,'file':wav.name,'flacFile':flac.name,'wavSha256':hashlib.sha256(wav.read_bytes()).hexdigest(),'sampleRate':rate,'channels':1,'frames':len(audio),
'durationMs':round(len(audio)*1000/rate),'textSha256':hashlib.sha256(record['text'].encode()).hexdigest(), 'durationMs':round(len(audio)*1000/rate),'textSha256':hashlib.sha256(record['text'].encode()).hexdigest(),
'flacSha256':hashlib.sha256(flac.read_bytes()).hexdigest(),'cues':cues} 'flacSha256':hashlib.sha256(flac.read_bytes()).hexdigest(),'cues':cues}
print(f"Saved {wav.name}: {len(audio)/rate:.1f}s; lossless FLAC verified",flush=True) print(f"Saved {wav.name}: {len(audio)/rate:.1f}s; lossless FLAC verified",flush=True)
+21
View File
@@ -160,4 +160,25 @@ void main() {
g.selectDifficulty(Difficulty.easy); g.selectDifficulty(Difficulty.easy);
expect(g.practiceLevel, 1); expect(g.practiceLevel, 1);
}); });
test('campaign read-ahead restores without awarding or losing an unfinished board', () async {
final store = Progress.memory({'story_access_level': 2});
final g = Game(await Book.load(), store);
g.startCampaign(2);
g.mark(0);
final marks = List<int>.of(g.cells);
g.reveal(2, readAhead: true);
expect(g.screen, Screen.reveal);
expect(g.recovered(2), false);
expect(g.solved, 0);
final restored = Game(g.book, Progress.memory(store.snapshot));
await restored.restore();
expect(restored.screen, Screen.reveal);
expect(restored.campaignIndex, 2);
expect(restored.solved, 0);
restored.startCampaign(2);
expect(restored.cells, marks);
restored.reveal(5, readAhead: true);
expect(restored.screen, Screen.briefing);
expect(restored.campaignIndex, 2);
});
} }
+137
View File
@@ -1,6 +1,10 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_test/flutter_test.dart';
import 'package:lumen/domain/book.dart';
import 'package:lumen/domain/game.dart';
import 'package:lumen/domain/puzzle.dart'; import 'package:lumen/domain/puzzle.dart';
import 'package:lumen/main.dart';
import 'package:lumen/services/progress.dart';
import 'package:lumen/ui/board.dart'; import 'package:lumen/ui/board.dart';
import 'package:lumen/ui/paper.dart'; import 'package:lumen/ui/paper.dart';
@@ -42,6 +46,98 @@ void main() {
expect(marks, 1); expect(marks, 1);
expect(tester.takeException(), isNull); expect(tester.takeException(), isNull);
}); });
testWidgets(
'reading swipes turn both ways; controls, scrolling and cancelled drags do not',
(tester) async {
tester.view.physicalSize = const Size(600, 960);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
var turns = 0, plays = 0;
final scroll = ScrollController();
addTearDown(scroll.dispose);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Paper(
onTurn: (direction) => turns += direction,
child: Column(
children: [
Expanded(
child: SingleChildScrollView(
controller: scroll,
child: Column(
children: [
SizedBox(
key: const ValueKey('reading-zone'),
height: 130,
width: double.infinity,
child: writing(
'My dear, take your time with these pages.',
),
),
SizedBox(
key: const ValueKey('blank-zone'),
height: 100,
width: double.infinity,
),
for (var i = 0; i < 12; i++)
SizedBox(
height: 80,
child: writing('A remembered passage $i.'),
),
],
),
),
),
InkButton('Play this reading', () => plays++),
],
),
),
),
),
);
await tester.pumpAndSettle();
await tester.drag(
find.byKey(const ValueKey('reading-zone')),
const Offset(-150, 0),
);
await tester.pumpAndSettle();
expect(turns, 1);
await tester.dragFrom(
tester.getCenter(find.byKey(const ValueKey('blank-zone'))),
const Offset(150, 0),
);
await tester.pumpAndSettle();
expect(turns, 0);
await tester.drag(find.text('Play this reading'), const Offset(-120, 0));
await tester.pumpAndSettle();
expect(turns, 0);
expect(plays, 0);
await tester.tap(find.text('Play this reading'));
expect(plays, 1);
await tester.drag(
find.byKey(const ValueKey('reading-zone')),
const Offset(-30, 0),
);
await tester.pumpAndSettle();
expect(turns, 0);
final drag = await tester.startGesture(
tester.getCenter(find.byKey(const ValueKey('reading-zone'))),
);
await drag.moveBy(const Offset(-140, 0));
await drag.cancel();
await tester.pumpAndSettle();
expect(turns, 0);
await tester.drag(
find.byKey(const ValueKey('reading-zone')),
const Offset(0, -200),
);
await tester.pumpAndSettle();
expect(scroll.offset, greaterThan(0));
expect(turns, 0);
expect(tester.takeException(), isNull);
},
);
testWidgets('paper supports small and landscape viewports and larger text', ( testWidgets('paper supports small and landscape viewports and larger text', (
tester, tester,
) async { ) async {
@@ -75,4 +171,45 @@ void main() {
expect(tester.takeException(), isNull); expect(tester.takeException(), isNull);
} }
}); });
testWidgets('landscape pages keep the whole grid beside its notes', (
tester,
) async {
const width = 960.0, height = 600.0;
tester.view.physicalSize = const Size(width, height);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final book = await Book.load();
final game = Game(book, Progress.memory());
game.startCampaign(0);
await tester.pumpWidget(LumenApp(game: game, adsEnabled: false));
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
// The campaign leaf gives the board its own column, with the heading and
// controls beside it rather than above the fold.
final lastCell = tester.getRect(find.byKey(const ValueKey('cell-48')));
expect(lastCell.bottom, lessThan(height * .94));
expect(
tester.getTopLeft(find.text('A spark in the drawer')).dx,
greaterThan(lastCell.right),
);
expect(find.text('Hint · free'), findsOneWidget);
expect(find.text('Back to notebook'), findsOneWidget);
expect(tester.takeException(), isNull);
// The opening notebook's puzzle leaf uses the same two columns, with the
// grid on the page and its controls beside it.
game.showStory(2);
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
final storyLast = tester.getRect(find.byKey(const ValueKey('cell-48')));
expect(storyLast.bottom, lessThan(height * .94));
expect(
tester.getTopLeft(find.text('Hint · free')).dx,
greaterThan(storyLast.right),
);
expect(find.text('Next leaf →'), findsOneWidget);
expect(tester.takeException(), isNull);
});
} }