Initial commit: Lumen Android puzzle notebook v1.7

This commit is contained in:
Hadrian Burkhardt
2026-10-31 03:28:48 +01:00
commit 07e9253663
76 changed files with 3770 additions and 0 deletions
+8
View File
@@ -0,0 +1,8 @@
.gradle/
local.properties
**/build/
*.jks
*.keystore
artifacts/
__pycache__/
.venv/
+106
View File
@@ -0,0 +1,106 @@
# Lumen — The Last Light (Android 1.7)
A native Android 7.0+ app styled as a lightkeeper’s family notebook: faded blue cloth, stitched binding, warm ruled paper, a ribbon bookmark and pressed heather. A hand-drawn twilight harbour connects the home screen to the island story. No account or game backend. Players restore a darkened island through picture puzzles, or play generated 5×5 daily and classic grids.
The opening six-leaf storybook prototype is implemented. The wider [product roadmap](ROADMAP.md) describes the next chapters and further exploration features.
## Opening notebook prototype
Open Mara’s notebook from the home screen. The opening trail contains:
1. Gran’s handwritten dedication.
2. A cottage entry with an original watercolour illustration.
3. The existing match puzzle, using its original save key.
4. A match sketch and a personal memory.
5. A folded note that can be opened and kept.
6. A lantern illustration with a repair detail to inspect.
Use the corner arrows or swipe horizontally from a page margin. Gestures starting inside the grid cannot turn the page. Navigation stays fixed below the reading area; text can overflow-scroll for larger fonts or landscape. A short fade/slide respects disabled system animations. Contents links to these leaves, a ribbon bookmark, and the existing three-chapter campaign. The final lantern leaf links to the next existing entry; the rest of the campaign still uses the earlier screens.
Five pre-rendered readings ship as lossless FLAC files, with editable 24 kHz mono WAV masters in `assets/narration/wav/`. Android MediaPlayer provides play, pause, exact-position resume, stop and replay, optional speed settings, and passage highlighting. There is no Android text-to-speech service, runtime synthesis, voice download, or per-listen network request. These are synthetic British-English readings rendered during development, not a human actor’s performance. Playback stops on page changes and when the app backgrounds. See [audio provenance and regeneration](assets/narration/README.md).
The last leaf, explicit ribbon bookmark, opened note, inspected handle and viewed-page flags are saved independently of puzzle completion. Closing the app in the notebook restores the same leaf. Reading ahead from an unsolved puzzle asks once per attempted turn and keeps all marks without awarding completion. Existing campaign grids and counts are preserved; the original match can be revisited if already solved. The opening prototype contains no interstitials, and narration/discoveries require no ad.
The cottage and lantern PNGs were generated using the built-in image tool with alpha backgrounds. Originals and exact prompts are in `assets/artwork/`; sampled decoded copies are used for the small on-page illustrations.
For isolated tablet smoke tests:
```sh
JAVA_HOME=/path/to/jdk-21 ./gradlew :app:assembleDebug -PqaBuild=true
adb -s YOUR_SERIAL install -r app/build/outputs/apk/debug/app-debug.apk
python3 scripts/check_storybook.py --serial YOUR_SERIAL
```
The test script enforces a `.qa` package because it writes disposable fixtures. It checks edge swipes, bundled recording playback, pause/resume and speed settings, grid gesture isolation, read-ahead, folded-note persistence, bookmarks, process restart, completion without duplicate awards, and rotation. It restores the tablet’s original rotation settings. Screenshots and results go to `artifacts/storybook-check/`.
## The Last Light
Twelve 7×7 picture puzzles across three chapters: the keeper’s cottage, the tidal crossing, and the lighthouse. Follow grandmother Mara’s notebook to recover a match, lantern, key, compass, boat, anchor, bridge, bell, gear, lens, lighthouse and home. Each solution is the actual pictured object, shown as clean pixel art after completion. Story pages appear before and after each puzzle; recovered pictures remain in the notebook. Everything ships in the APK.
The first two patterns teach row and column totals. Patterns 3–12 add three overlapping rectangular areas. Select A, B or C to highlight its cells; shared cells count in both totals. Later puzzles **cannot** be completed by line saturation alone. Subtracting overlapping constraints resolves cells outside their overlap; tests verify this technique is necessary and sufficient, without branching/guessing. These are introductory area puzzles, not a promise of expert-level challenge.
Campaign completion unlocks the next page, increments the existing solved counter once, and preserves all prior classic/daily data. Campaign progress is separate from the daily streak. Every fourth story page can show an interstitial when turning to the next chapter, once per chapter transition; re-reading never repeats it. No ad interrupts a story reveal. Campaign replay currently means re-reading recovered pages, not resetting puzzles.
Hints now explain a forced line or area deduction and mark one cell. If an earlier player mark is wrong, a hint corrects one such cell first. Each puzzle has one free hint, with additional hints requiring the AdMob reward callback.
## Notebook theme
The home screen now uses newly generated watercolour harbour and faded-blue notebook-cover PNGs (`HomeArtwork.java`), with a native handwritten cover label. All app-created headings, passages, menus, captions, puzzle clues and dialogs use the cursive handwriting family; system consent screens retain their provider styling. Recovered objects sit on taped paper keepsakes. The lighthouse app icon uses a vector drawable.
The book cover on the home screen opens a generated 1024×1536 single diary page, bundled without density scaling. `NotebookPage.java` positions transparent content directly on its blank writing area, with no floating panel. Portrait shows the whole page; landscape crops vertically through the blank paper, retaining the binding. Handwritten menu actions have a fine ink underline, and empty puzzle cells have thin pencil outlines so the paper stays visible. The grid sizes to available width and scrolls into view on entry. Source artwork and the exact generation prompt are in `assets/artwork/`. All drawings are static apart from the existing short picture fade; paper texture work is limited to the visible part of the page. Existing puzzle definitions and save keys are unchanged.
## Classic and daily modes
- Deterministic generated practice levels and a date-seeded daily puzzle.
- Easy, Medium, and Hard practice, with independent saved progress and a remembered selection.
- Solver checks uniqueness and rates boards by simultaneous deduction rounds: Easy 1–2, Medium 3–4, Hard 5. A round fills lines where all unknown cells must be lit or all must be crossed out; later rounds use those deductions. No guessing is needed.
- Generation tries up to 256 deterministic candidates, then uses a permuted known board of the requested grade. These are relative chain-depth ratings, not a calibrated measure of solve time.
- Existing daily grids retain their original generation. Earlier in-progress practice is accessible through “Continue earlier puzzle.”
- Saved boards, level progress, daily streaks and completion counts on device.
- Undo, one free explained hint per board, then optional rewarded hints.
- Interstitials at a natural transition after every fourth practice completion across all difficulties. No ads during a board or when returning home.
- AdMob and UMP consent flow; ads only requested when consent information permits.
- Google test IDs by default. Games remain playable without connectivity or ad availability.
Campaign grids use fixed `story_v1_…` save keys. Preserve the order, pictures, givens and area layouts of existing entries when adding future pages; changing an existing puzzle requires a new save-key version.
## Build
Requires JDK 17–24 (JDK 21 recommended) and Android SDK 36. Set `sdk.dir` in your own `local.properties` or configure `ANDROID_HOME`.
```sh
JAVA_HOME=/path/to/jdk-21 ./gradlew :app:testDebugUnitTest :app:assembleDebug
```
Debug APK: `app/build/outputs/apk/debug/app-debug.apk`. A shareable copy of version 1.7 is in `artifacts/lumen-1.7.apk`.
For an isolated device test build, add `-PqaBuild=true` to `assembleDebug`; it installs as `com.lumen.daily.qa`, with independent progress. Build without that property for the normal app. Device smoke-test screenshots and results are under `artifacts/`.
## Before publishing on Google Play
1. Choose a permanent application ID in `app/build.gradle` (currently `com.lumen.daily`).
2. Create the Android app and rewarded/interstitial ad units in AdMob. Configure Privacy & messaging for the markets you serve.
3. Supply production IDs via Gradle properties `ADMOB_APP_ID`, `ADMOB_REWARDED_ID`, and `ADMOB_INTERSTITIAL_ID`. Keep Google test IDs in development builds.
4. Configure your private upload signing key outside version control, then build a signed release AAB. Release signing is intentionally not supplied by this repository.
5. Supply a public privacy policy, store artwork, support contact, content rating, target audience, ads declaration and accurate Data safety answers based on the Google ads SDK and your final configuration. The in-app privacy summary is not a replacement for a published policy.
6. Test consent (including refusal/revocation), reward completion/cancellation, no-fill, offline play, process restart, device rotation and small screens on physical devices. Complete Play testing requirements for your developer account.
The daily date uses the device’s local calendar. Progress and streaks are local, not protected against clock changes or restored after uninstall. A daily puzzle remains available to replay after completion; a solved practice board advances the practice counter. Puzzle generation guarantees a unique answer and grades deduction depth.
## Source map
- `Campaign.java`: authored story, 7×7 pixel patterns, precomputed fixed clues and area layouts.
- `LogicSolver.java`: count-constraint search, line/area deductions and explained hints.
- `CampaignTest.java`: all twelve unique pictures; necessary area deductions on pages 3–12; hint completion and restoration checks.
- `LogicSolverTest.java`: deductions and solution counts compared with exhaustive enumeration over 1,000 small overlapping constraint systems.
- `Puzzle.java`: seeded classic generation, general constraints, solution counting, deduction grading, completion validation.
- `Difficulty.java`: difficulty names, descriptions and grade thresholds.
- `DifficultyTest.java`: 1,500 generated boards checked for requested grades and uniqueness, deterministic regeneration, legacy compatibility and ambiguous-board rejection.
- `StoryBook.java`: stable six-leaf story records and narration sentence boundaries.
- `StoryNotebook.java`: page layouts, fixed navigation, folded note and inspection interaction.
- `StoryNarrator.java`: bundled recording playback, passage progress, audio focus and speed settings.
- `PageTurnGesture.java`: page-margin gesture recognition, tested against grid drags.
- `MainActivity.java`: notebook routing, puzzle completion, local progress, streaks, hints.
- `Ads.java`: consent, ad loading and presentation.
- `PuzzleTest.java`: uniqueness, determinism and completion across 500 seeds.
- `DailyStreakTest.java`: consecutive days, replay handling and missed-day reset.
+160
View File
@@ -0,0 +1,160 @@
# Lumen — a notebook worth exploring
Status: opening slice updated in Android version 1.7. 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. There are no delivery dates yet; review the opening slice before expanding it.
## The experience we are building
Lumen is an illustrated story notebook about Mara, her grandchild, and the island they call home. The pleasure of opening the notebook should come from wondering what is on the next page. Puzzles are one way to uncover its memories, alongside reading, listening, examining drawings, and finding things tucked between the leaves.
The central promise: **every page offers something worth noticing, and every discovery brings the story a little closer.**
Keep the existing gentle tone and the three-chapter journey to restore the lighthouse. Make the relationship with Gran more tangible through her own words, everyday habits, small jokes, repairs, and things she chose to keep. Let the player learn about her gradually. Preserve the current reunion with Mara; do not introduce a bereavement twist simply to manufacture emotion.
Success is the player wanting to turn another page, remember a detail, or return to a favourite passage. Completing grids and maintaining a streak remain secondary activities.
## What exists today
- 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.
- 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.
- Existing campaign pages beyond this prototype retain their previous navigation. Overflow scrolling remains for large text and shorter viewports.
## Phase 1 — make it a book
First milestone: a small, complete slice of the cottage chapter that can be read and played by turning pages.
- 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.
- Turn pages with horizontal swipes near the edges 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.
- 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.
- Keep vertical scrolling as an accessibility fallback when large text cannot fit on a leaf. Never shrink text just to preserve a page layout.
- Lay out landscape content on the same sheet or repaginate it; do not move the game into a separate floating panel.
**Ready when:** the first chapter can be traversed forward and backward, the full puzzle and its essential controls are usable, accidental page turns do not occur during grid input, and restarting or rotating the app restores the correct place. Existing saved puzzles still load.
## Phase 2 — let Gran’s entries be heard
Every diary entry pairs a short passage with a small original illustration and an optional listen control.
- Bundle prerecorded WAV or lossless FLAC passages; never depend on the Android reader or a device-installed voice. The opening prototype now has five pre-rendered synthetic readings, WAV masters and FLAC playback assets.
- Review the warm, unhurried delivery before expanding production. Consider a recorded actor performance for Mara; keep synthetic prototype recordings clearly identified in the asset provenance.
- Distinguish Mara’s first-person diary entries from present-day narration and the grandchild’s annotations. Make the speaker clear in the writing and listen control.
- Offer play, pause, exact-position resume, stop and replay. Keep narration opt-in, without autoplay on page entry.
- Highlight the current passage using timing cues while keeping all text accessible.
- Stop playback when a page is turned or the app backgrounds; pause on audio interruption. Never overlap recordings.
- Keep reading available if an asset cannot be played. Audio requires no download, game backend or per-listen server call.
- Match each recording to its stable page ID and exact script, preserve uncompressed masters, and verify bundled FLACs against them.
Review pronunciation, pacing, emotional tone, and the experience with sound turned off before recording the remaining chapters. Tide and reunion passages still need recordings when their new notebook leaves are authored.
**Ready when:** the five opening readings play offline, pause/resume and speed settings work, navigation stops playback, and the voice has been reviewed on the tablet. Technical playback is implemented; the final narrative performance remains an art decision.
## Phase 3 — every leaf has its own identity
Each page should have a distinct composition and a specific narrative detail. Variety should come from what Mara kept and what happened there, rather than random decoration.
| Page type | What makes the player curious | Small interaction |
| --- | --- | --- |
| A handwritten entry | An unfinished thought beside a little cottage sketch | Listen to the entry or examine the sketch |
| A taped illustration | A boat, key, or lantern drawn larger than the solved pixel pattern | Tap to see a short handwritten caption |
| A folded letter | A greeting peeking from an envelope | Unfold it and read the message |
| A harbour map | Mara’s pencilled route and a mark near the bridge | Trace the route between already discovered places |
| A pressed-flower leaf | Heather gathered on a day the player has just read about | Lift its label to find the remembered date or place |
| A repair note | A gear sketch with arrows and a practical aside from Gran | Compare it with a recovered puzzle object |
| A weather entry | A rain stain, a tide observation, and a sketch of the sea | Reveal a short note beneath a paper flap |
| A quiet domestic page | A tea stain, shopping scrap, or recipe note | Read a small optional memory with no puzzle attached |
| A puzzle leaf | A pattern that matters to the current scene | Restore it with logic, then see the object illustrated |
| A closing leaf | A drawing and a new note from the grandchild | Revisit the memories collected along the way |
Visual rules:
- Keep one consistent diary, ink palette, and handwriting family. Vary the placement of text, the kind of illustration, the paper scraps, and the use of blank space.
- Give every authored story leaf at least one unique illustration or meaningful detail. Do not count a changed page number or stain as sufficient variety.
- Compose in defined writing and illustration areas. Keep decorative art outside puzzle clues, text, navigation, and touch targets.
- Render readable text in the app, not baked into generated images. This allows narration, translation, larger fonts, and screen-reader access.
- Let illustrations invite inspection, but keep the main story readable without finding tiny hidden targets.
- Use small motions sparingly: a flap opening, a ribbon moving, or a lantern warming after a discovery. The notebook should also work with motion and sound disabled.
- Reuse a few base paper textures and layout families to keep production manageable. Give each leaf its own small illustration and writing rather than generating a whole new background for every screen.
- Keep each page’s design stable across visits. Do not randomly rearrange objects that the player has learned to recognise.
**Ready when:** six consecutive prototype leaves are recognisably different, all remain part of the same notebook, and a reader can explain what each picture contributes to the story.
## Phase 4 — connect discoveries into a story
Expand the twelve puzzle beats into a proposed 30–40-leaf first notebook. Confirm the exact count after editing and accessibility pagination. Reading and exploration leaves should appear between puzzles, so another grid is not the only reward for finishing one.
Chapter direction:
| Chapter | Emotional purpose | Visual language | Discoveries to develop |
| --- | --- | --- | --- |
| I · The keeper’s cottage | Establish affection and familiar routines | Warm ink, cloth repairs, indoor sketches | A dedication, a lantern drawing, the key’s label, a tucked-away letter |
| II · Across the tide | Build curiosity and a sense of distance | Sea-blue washes, maps, tide marks | Mara’s crossing notes, a boat sketch, bridge annotations, the meaning of the bell signal |
| III · The last light | Bring earlier details together through shared work | Mechanical pencil drawings, glass, amber light | A repair diagram, the lens, Mara’s reply, the grandchild’s final entry |
Story principles:
- Establish a small question before a discovery and answer or deepen it afterward. Who repaired the lantern? Why does Mara ring twice? What did she leave under the floorboard?
- Revisit earlier details with new meaning. A casual bell note in the cottage can pay off when someone answers from the hill.
- Write some entries in Gran’s own voice, including ordinary details rather than only wisdom and instructions.
- Include calm pages with no task at all. Listening to a memory or looking at a sketch is a valid part of play.
- Allow free exploration of discovered pages and optional leaves within the current chapter. Use clear bookmarks for the main thread, rather than a maze of locks.
- Keep puzzles tied to the scene and reward them with a picture, a memory, or a change in understanding. Avoid presenting them as unrelated tolls between paragraphs.
- Prototype a story-first option: offer a guided solution or a way to continue the narrative when a player is stuck. Preserve the unsolved puzzle for later, and distinguish viewed story progress from solved-puzzle progress.
- Require neither a rewarded ad nor a streak to read an entry, hear its narration, or reach the next essential story beat.
**Ready when:** someone can enjoy the cottage chapter primarily as a story, describe their relationship with Mara, and identify a reason to explore the next chapter beyond receiving another puzzle.
## Phase 5 — make the notebook rewarding to revisit
After the first chapter proves the direction:
- Add ribbon bookmarks, a pocket of collected scraps, and a small illustrated island index linking to discovered memories.
- Let players replay narration and re-examine recovered objects without replaying puzzles or seeing repeated ads.
- Add optional margin notes that become understandable after later discoveries. Keep the original writing intact, so the change feels like an annotation rather than a rewritten memory.
- Consider very quiet optional ambience: sea outside the window, a kettle, or a lighthouse mechanism. Give ambience, narration, and page sounds separate controls, and lower ambience during speech.
- Make daily puzzles feel like spare pages at the back of the book. Keep them available without interrupting the authored story or requiring daily attendance.
- Offer optional puzzle replay with its own state, preserving the notebook’s discovered memories and completion history.
- Consider another notebook only after this one has a satisfying ending. Reuse the page system rather than committing to a continuous stream of new story content.
## Monetization that respects exploration
Keep optional rewarded hints. Review moving campaign interstitials out of the story flow: the preferred direction is to keep diary reading, narration, page turns, and re-reading uninterrupted. Occasional ads can remain at natural breaks in classic practice. Assess the revenue tradeoff before a public release; do not turn every page into an ad opportunity.
## Production approach
Keep the first notebook finite, authored, bundled, and playable offline. Generated classic and daily puzzles provide replayability without continual campaign maintenance.
Move toward stable page records instead of treating each puzzle level as an entire story unit. Proposed fields:
`pageId`, `chapterId`, `type`, `speaker`, `text`, `illustrationAsset`, `layoutId`, `narrationText`, `puzzleId`, `discoveryId`, and `unlockCondition`.
Store the current bookmark, viewed pages, discoveries, and puzzle solutions separately. Preserve existing `story_v1_…` puzzle keys and completion counts when migrating. Splitting a passage or adding an optional leaf must not erase an existing solution or mark an unseen entry as read.
Create a page checklist for each authored leaf: its story purpose, unique visual detail, reading order, optional audio, interaction, and what it reveals. Maintain one art guide and an asset list with prompts and intended placement. Check every generated illustration in the real page layout before accepting it.
## First implementation slice
Build and review this sequence before producing the full notebook:
1. A dedication leaf with Gran’s signature and optional narration.
2. A short cottage entry with a small illustration and listen control.
3. The existing match puzzle on its own leaf, with all essential controls visible.
4. A recovered-match illustration and a personal memory that rewards completion.
5. A folded note that the player opens without solving a puzzle.
6. A lantern sketch that raises a question answered on a later leaf.
Use this slice to judge page turning, narration, visual variety, readability, and curiosity together. Expand the rest of the story only after these leaves feel worth exploring in their own right.
## Review questions
- Does each page give the reader a reason to look, listen, or turn the next leaf?
- Can the player describe Mara as a person, beyond knowing that she gives puzzle instructions?
- Are the picture and interaction relevant to the passage, or merely decorative?
- Is the notebook comfortable with sound off, larger text, reduced motion, or a screen reader?
- Can players return to a favourite memory and resume their current place without friction?
- Do puzzles support discovery without becoming compulsory obstacles to enjoying the story?
For optional playtests, collect answers and observations with the player’s knowledge. No analytics service or backend is required for this roadmap.
+26
View File
@@ -0,0 +1,26 @@
plugins { id 'com.android.application' }
android {
namespace 'com.lumen.daily'
compileSdk 36
defaultConfig {
applicationId 'com.lumen.daily'
minSdk 24
targetSdk 36
versionCode 8
versionName '1.7'
manifestPlaceholders = [admobAppId: providers.gradleProperty('ADMOB_APP_ID').getOrElse('ca-app-pub-3940256099942544~3347511713')]
buildConfigField 'String', 'REWARDED_ID', '"' + providers.gradleProperty('ADMOB_REWARDED_ID').getOrElse('ca-app-pub-3940256099942544/5224354917') + '"'
buildConfigField 'String', 'INTERSTITIAL_ID', '"' + providers.gradleProperty('ADMOB_INTERSTITIAL_ID').getOrElse('ca-app-pub-3940256099942544/1033173712') + '"'
}
buildTypes { debug { if (providers.gradleProperty("qaBuild").getOrElse("false") == "true") applicationIdSuffix ".qa" } }
androidResources { noCompress += ['flac'] }
buildFeatures { buildConfig true }
compileOptions { sourceCompatibility JavaVersion.VERSION_17; targetCompatibility JavaVersion.VERSION_17; coreLibraryDesugaringEnabled true }
}
dependencies {
implementation 'androidx.activity:activity:1.12.4'
implementation 'com.google.android.gms:play-services-ads:25.5.0'
implementation 'com.google.android.ump:user-messaging-platform:4.0.0'
coreLibraryDesugaring 'com.android.tools:desugar_jdk_libs:2.1.5'
testImplementation 'junit:junit:4.13.2'
}
+7
View File
@@ -0,0 +1,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET"/><uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application android:theme="@style/AppTheme" android:label="Lumen" android:icon="@drawable/ic_launcher" android:allowBackup="false" android:fullBackupContent="false" android:dataExtractionRules="@xml/data_extraction_rules" android:supportsRtl="true">
<meta-data android:name="com.google.android.gms.ads.APPLICATION_ID" android:value="${admobAppId}"/>
<activity android:name=".MainActivity" android:exported="true"><intent-filter><action android:name="android.intent.action.MAIN"/><category android:name="android.intent.category.LAUNCHER"/></intent-filter></activity>
</application>
</manifest>
@@ -0,0 +1,20 @@
package com.lumen.daily;
import android.app.Activity;
import com.google.android.gms.ads.*;
import com.google.android.gms.ads.rewarded.*;
import com.google.android.gms.ads.interstitial.*;
import com.google.android.ump.*;
final class Ads {
final Activity activity; final ConsentInformation consent;
RewardedAd reward; InterstitialAd interstitial; boolean initialized, loadingReward, loadingInterstitial; long rewardAt, interstitialAt;
Ads(Activity a){activity=a;consent=UserMessagingPlatform.getConsentInformation(a);consent.requestConsentInfoUpdate(a,new ConsentRequestParameters.Builder().build(),()->UserMessagingPlatform.loadAndShowConsentFormIfRequired(a,e->start()),e->start());}
void start(){if(!consent.canRequestAds()||initialized)return;initialized=true;MobileAds.initialize(activity,s->activity.runOnUiThread(this::load));}
void load(){
if(!consent.canRequestAds())return;
if(!loadingReward&&reward==null){loadingReward=true;RewardedAd.load(activity,BuildConfig.REWARDED_ID,new AdRequest.Builder().build(),new RewardedAdLoadCallback(){public void onAdLoaded(RewardedAd a){reward=a;rewardAt=android.os.SystemClock.elapsedRealtime();loadingReward=false;} public void onAdFailedToLoad(LoadAdError e){loadingReward=false;}});}
if(!loadingInterstitial&&interstitial==null){loadingInterstitial=true;InterstitialAd.load(activity,BuildConfig.INTERSTITIAL_ID,new AdRequest.Builder().build(),new InterstitialAdLoadCallback(){public void onAdLoaded(InterstitialAd a){interstitial=a;interstitialAt=android.os.SystemClock.elapsedRealtime();loadingInterstitial=false;} public void onAdFailedToLoad(LoadAdError e){loadingInterstitial=false;}});}
}
boolean hint(Runnable earned){if(android.os.SystemClock.elapsedRealtime()-rewardAt>3500000)reward=null;if(reward==null||!consent.canRequestAds()){load();return false;}RewardedAd a=reward;reward=null;a.setFullScreenContentCallback(new FullScreenContentCallback(){public void onAdDismissedFullScreenContent(){load();}public void onAdFailedToShowFullScreenContent(AdError e){load();}});a.show(activity,r->earned.run());return true;}
void between(Runnable next){if(android.os.SystemClock.elapsedRealtime()-interstitialAt>3500000)interstitial=null;if(interstitial==null||!consent.canRequestAds()){next.run();load();return;}InterstitialAd a=interstitial;interstitial=null;a.setFullScreenContentCallback(new FullScreenContentCallback(){public void onAdDismissedFullScreenContent(){next.run();load();}public void onAdFailedToShowFullScreenContent(AdError e){next.run();load();}});a.show(activity);}
void privacy(){if(consent.getPrivacyOptionsRequirementStatus()==ConsentInformation.PrivacyOptionsRequirementStatus.REQUIRED)UserMessagingPlatform.showPrivacyOptionsForm(activity,e->{});else new android.app.AlertDialog.Builder(activity).setMessage("No advertising privacy options are currently required for your region. Game progress stays on this device. Google advertising services may process device and ad interaction data when ads are available.").setPositiveButton("OK",null).show();}
}
@@ -0,0 +1,119 @@
package com.lumen.daily;
/** An offline, authored story. The pictures are the actual puzzle solutions. */
public final class Campaign {
public static final String TITLE = "The Last Light";
public static final String PREMISE = "The storm has passed, but the island is still dark. In your grandmother Mara’s notebook, you find a promise: no one comes home to an unlit shore. Recover what the storm scattered. Bring the lighthouse back to life.";
public static final class Level {
public final String chapter, title, object, before, after;
public final int[] picture;
Level(String chapter, String title, String object, String before, String after, String... rows) {
this.chapter = chapter; this.title = title; this.object = object;
this.before = before; this.after = after;
if (rows.length != 7) throw new IllegalArgumentException("Picture must have seven rows");
picture = new int[49];
for (int r = 0; r < 7; r++) {
if (rows[r].length() != 7) throw new IllegalArgumentException("Picture must have seven columns");
for (int c = 0; c < 7; c++) picture[r * 7 + c] = rows[r].charAt(c) == '1' ? 1 : 0;
}
}
}
public static final Level[] LEVELS = {
new Level("I · The keeper’s cottage", "A spark in the drawer", "A match",
"You find Mara’s cottage with its windows shuttered. On the table is her notebook: ‘Start with one small light.’ The first page is water-stained. Restore its pattern.",
"A dry match, hidden in a tin. You strike it against the hearth. For a moment, the cottage feels like it remembers you.",
"0011000", "0111100", "0011000", "0001000", "0001000", "0001000", "0001000"),
new Level("I · The keeper’s cottage", "Something to carry the flame", "The lantern",
"A small flame will not survive the wind. Mara’s next page shows what she carried on her evening rounds.",
"The lantern is soot-black but sound. Its warm circle of light reaches the cottage door. Beneath the handle, Mara has scratched your initials.",
"0011100", "0010100", "0111110", "0100010", "0101010", "0100010", "0111110"),
new Level("I · The keeper’s cottage", "Under the loose floorboard", "The brass key",
"‘Some clues belong to more than one place,’ Mara wrote. Compare the overlapping areas on this page; a shared cell counts in both. A loose floorboard waits by the door.",
"A brass key turns up beneath the board. The tag reads ‘harbour store’. Someone prepared for a journey and never quite made it out of the cottage.",
"0011100", "0100010", "0100010", "0011100", "0001000", "0001100", "0001000"),
new Level("I · The keeper’s cottage", "A direction in the dark", "Mara’s compass",
"The lane has vanished beneath fallen branches. One last page in the cottage points you towards the harbour. Use what the areas share to work out what lies outside them.",
"The compass needle settles towards the sea. Tucked inside its lid is a note: ‘When the path disappears, keep your bearings.’ You step into the rain.",
"0001000", "0011100", "0101010", "1111111", "0101010", "0011100", "0001000"),
new Level("II · Across the tide", "At the water’s edge", "The little boat",
"The tide has covered the causeway. A shape knocks gently against the harbour steps. Mara’s notebook has a page for this crossing too.",
"The little boat is still tied fast. You bail out the rainwater, set the lantern in the bow, and push away from the steps.",
"0001000", "0001100", "0001110", "0001000", "1111111", "0111110", "1000001"),
new Level("II · Across the tide", "What holds us steady", "The anchor",
"The current tugs you towards the outer rocks. Something heavy is tangled beneath the seat. The pattern tells you what to reach for.",
"The anchor catches. The boat swings into calmer water. In the pause, you hear a bell somewhere beyond the fog.",
"0011100", "0010100", "0011100", "0001000", "1001001", "0101010", "0011100"),
new Level("II · Across the tide", "The old crossing", "The stone bridge",
"You land beneath the lighthouse hill. The old crossing is hidden by reeds. Mara marked its outline long before the storm.",
"The bridge is intact. You cross with the lantern held high. On the far bank, a fresh bootprint tells you someone else has passed this way.",
"0000000", "0111110", "1100011", "1000001", "1000001", "1111111", "0000000"),
new Level("II · Across the tide", "An answer through the fog", "The harbour bell",
"A rope hangs from a timber frame. The bell above it has fallen silent. Restore the pattern before you call out across the water.",
"One clear note travels into the fog. Two notes answer from the hill. Someone is waiting at the lighthouse.",
"0001000", "0011100", "0010100", "0100010", "0100010", "1111111", "0001000"),
new Level("III · The last light", "Inside the turning room", "The missing gear",
"Mara opens the lighthouse door. ‘I knew you’d find the notebook,’ she says. The storm stopped the turning mechanism. Together, you lay out its scattered parts.",
"The missing gear slips into place. You turn the handle; the mechanism answers with a familiar, steady ticking. Mara smiles without looking up.",
"0010100", "0111110", "1100011", "0101010", "1100011", "0111110", "0010100"),
new Level("III · The last light", "A circle of glass", "The beacon lens",
"The great lens is clouded with salt. Mara holds the lantern while you work. The areas overlap like the rings in the glass; compare them carefully.",
"You wipe the last salt from the lens. The lantern’s tiny flame stretches into a bright arc across the walls. Everything is ready.",
"0011100", "0100010", "1001001", "1001101", "1001001", "0100010", "0011100"),
new Level("III · The last light", "No unlit shore", "The lighthouse",
"Mara gives you the handle. Below the windows, the island lies dark. This is the pattern all the other pages were leading towards.",
"The beacon turns. Its light sweeps the harbour, the bridge, the little boat. Far offshore, a ship sounds its horn. The island has its light again.",
"0001000", "0011100", "1111111", "0011100", "0010100", "0110110", "1111111"),
new Level("III · The last light", "A light in the window", "Home",
"Dawn finds you walking back with Mara. There is one blank page at the end of the notebook. ‘That one is yours,’ she says.",
"You light the cottage window. Mara puts the kettle on. Beneath your new drawing, you write: ‘No one comes home to an unlit shore.’ The notebook closes. Your watch has begun.",
"0001000", "0011100", "0111110", "1111111", "0100010", "0101010", "0111110")
};
private static final String[] CLUES = {
"",
"1,5,9,11",
"",
"15,36",
"",
"11,36,40",
"",
"2",
"9,24",
"7,13,36,40",
"",
""
};
private static final String[] AREAS = {
"",
"",
"1,2,4,3;3,2,2,4;3,2,2,3",
"1,3,2,2;3,2,3,3;2,0,3,5",
"0,3,5,2;3,1,3,3;2,2,4,4",
"2,3,3,3;2,1,4,2;1,1,3,4",
"2,1,3,5;0,2,5,3;2,3,2,2",
"3,2,3,3;2,0,4,4;0,3,5,2",
"2,3,3,3;1,3,5,3;1,2,4,3",
"1,2,5,3;2,3,3,2;2,2,3,2",
"1,3,4,2;0,3,2,2;2,2,4,2",
"0,1,6,2;2,3,4,3;0,2,4,3"
};
public static Puzzle puzzle(int index) {
if (index < 0 || index >= LEVELS.length) throw new IllegalArgumentException("Unknown chapter");
Puzzle puzzle = new Puzzle(7, LEVELS[index].picture);
if (!CLUES[index].isEmpty()) for (String cell : CLUES[index].split(",")) puzzle.given[Integer.parseInt(cell)] = true;
if (!AREAS[index].isEmpty()) {
String[] regions = AREAS[index].split(";");
for (int i = 0; i < regions.length; i++) {
String[] values = regions[i].split(",");
puzzle.regions.add(new Puzzle.Region("" + (char) ('A' + i), Integer.parseInt(values[0]), Integer.parseInt(values[1]), Integer.parseInt(values[2]), Integer.parseInt(values[3])));
}
}
return puzzle;
}
public static int unlocked(int stored) { return Math.max(0, Math.min(LEVELS.length - 1, stored)); }
private Campaign() {}
}
@@ -0,0 +1,6 @@
package com.lumen.daily;
/** Local calendar-day streak rules; replaying a day cannot increment a streak. */
final class DailyStreak {
static int visible(long last, int count, long today){return last>=today-1?count:0;}
static int afterCompletion(long last, int count, long day){return day<=last?count:last==day-1?count+1:1;}
}
@@ -0,0 +1,29 @@
package com.lumen.daily;
public enum Difficulty {
EASY("Easy", "Short deductions. A gentle place to begin."),
MEDIUM("Medium", "Link deductions across rows and columns."),
HARD("Hard", "Follow longer chains to uncover the pattern.");
public final String label;
public final String description;
Difficulty(String label, String description) {
this.label = label;
this.description = description;
}
public static Difficulty fromRounds(int rounds) {
if (rounds <= 2) return EASY;
if (rounds <= 4) return MEDIUM;
return HARD;
}
public static Difficulty fromStored(String value) {
try {
return valueOf(value);
} catch (IllegalArgumentException e) {
return EASY;
}
}
}
@@ -0,0 +1,54 @@
package com.lumen.daily;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.Gravity;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
/** Original watercolour assets with crisp native handwriting on the cover label. */
final class HomeArtwork {
private static Bitmap harbour, cover;
private static Bitmap load(Context context, int resource) {
BitmapFactory.Options options=new BitmapFactory.Options(); options.inScaled=false; options.inSampleSize=2;
return BitmapFactory.decodeResource(context.getResources(),resource,options);
}
static ImageView harbour(Context context) {
if(harbour==null)harbour=load(context,R.drawable.home_harbour);
ImageView image=new ImageView(context);image.setImageBitmap(harbour);image.setScaleType(ImageView.ScaleType.FIT_CENTER);
image.setContentDescription("Watercolour of the island at dusk, the lighthouse beam crossing the bay to Gran’s cottage.");
return image;
}
static final class Cover extends ViewGroup {
private final ImageView picture;
private final TextView label;
private int imageLeft,imageTop,imageWidth,imageHeight;
Cover(Context context) {
super(context);
if(cover==null)cover=load(context,R.drawable.home_notebook_cover);
picture=new ImageView(context);picture.setImageBitmap(cover);picture.setScaleType(ImageView.ScaleType.FIT_CENTER);
picture.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
label=new TextView(context);label.setText("Mara’s\nisland notebook");label.setTypeface(JournalArt.HAND);label.setTextSize(25);
label.setRotation(-2.5f);
label.setTextColor(JournalArt.INK);label.setGravity(Gravity.CENTER);label.setImportantForAccessibility(IMPORTANT_FOR_ACCESSIBILITY_NO);
addView(picture);addView(label);
}
@Override protected void onMeasure(int widthSpec,int heightSpec) {
int w=MeasureSpec.getSize(widthSpec),h=MeasureSpec.getSize(heightSpec);setMeasuredDimension(w,h);
float scale=Math.min(w/(float)cover.getWidth(),h/(float)cover.getHeight());
imageWidth=Math.round(cover.getWidth()*scale);imageHeight=Math.round(cover.getHeight()*scale);
imageLeft=(w-imageWidth)/2;imageTop=(h-imageHeight)/2;
picture.measure(MeasureSpec.makeMeasureSpec(w,MeasureSpec.EXACTLY),MeasureSpec.makeMeasureSpec(h,MeasureSpec.EXACTLY));
label.measure(MeasureSpec.makeMeasureSpec(Math.round(imageWidth*.49f),MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(Math.round(imageHeight*.34f),MeasureSpec.EXACTLY));
}
@Override protected void onLayout(boolean changed,int left,int top,int right,int bottom) {
picture.layout(0,0,getWidth(),getHeight());
int x=imageLeft+Math.round(imageWidth*.27f),y=imageTop+Math.round(imageHeight*.32f);
label.layout(x,y,x+label.getMeasuredWidth(),y+label.getMeasuredHeight());
}
}
private HomeArtwork(){}
}
@@ -0,0 +1,185 @@
package com.lumen.daily;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.Shader;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.view.View;
/** Small, offline illustrations drawn at device resolution, without image downloads. */
final class JournalArt {
static final int PAPER = Color.rgb(243, 231, 204);
static final int INK = Color.rgb(57, 65, 63);
static final int BLUE = Color.rgb(39, 73, 86);
static final int FADED = Color.rgb(112, 96, 75);
static final Typeface HAND = Typeface.create("cursive", Typeface.NORMAL);
static final Typeface SERIF = Typeface.create("serif", Typeface.NORMAL);
static final class Paper extends Drawable {
private final Paint paint = new Paint(3);
private final float density;
private final boolean ruled;
Paper(Context context, boolean ruled) { density = context.getResources().getDisplayMetrics().density; this.ruled = ruled; }
@Override public void draw(Canvas canvas) {
Rect b = getBounds();
paint.setShader(new LinearGradient(b.left, 0, b.right, 0,
new int[]{0xffd2bd94, PAPER, 0xfff8efd9, 0xffe0cda8}, new float[]{0, .035f, .9f, 1}, Shader.TileMode.CLAMP));
canvas.drawRect(b, paint); paint.setShader(null);
Rect clip = canvas.getClipBounds();
// Stable paper fibres, limited to the visible page.
paint.setColor(0x166b583d); paint.setStrokeWidth(density * .45f);
int step = Math.max(4, (int)(density * 6));
for (int y = Math.max(0, clip.top / step * step); y < Math.min(b.bottom, clip.bottom) + step; y += step) {
for (int x = b.left + step; x < b.right; x += step * 3) {
int offset = Math.floorMod(x * 73 + y * 19, step * 2);
canvas.drawLine(x + offset, y, x + offset + density * 1.8f, y + density * .5f, paint);
}
}
if (ruled) {
paint.setColor(0x226b8990); paint.setStrokeWidth(density * .5f);
float spacing = density * 32;
float start = (float)Math.floor(clip.top / spacing) * spacing;
for (float y = start; y < Math.min(b.bottom, clip.bottom); y += spacing) canvas.drawLine(density * 24, y, b.right - density * 13, y, paint);
paint.setColor(0x458f5543); canvas.drawLine(density * 20, b.top, density * 20, b.bottom, paint);
}
paint.setColor(0x465c4935); paint.setStrokeWidth(density * .7f);
canvas.drawLine(b.right - density * 4, b.top, b.right - density * 4, b.bottom, paint);
canvas.drawLine(density * 8, b.top, density * 8, b.bottom, paint);
paint.setColor(0xffbba77f);
for (float y = density * 54; y < b.bottom; y += density * 138) {
if (y > clip.top - density * 20 && y < clip.bottom + density * 20) {
canvas.drawOval(density * 5, y, density * 11, y + density * 5, paint);
paint.setColor(0xfff6ecd4); paint.setStrokeWidth(density);
canvas.drawLine(density * 7, y - density * 8, density * 9, y + density * 14, paint);
paint.setColor(0xffbba77f);
}
}
}
@Override public void setAlpha(int alpha) {}
@Override public void setColorFilter(ColorFilter filter) {}
@Override public int getOpacity() { return PixelFormat.OPAQUE; }
}
/** A pencil rule under a handwritten action, without a floating button card. */
static final class InkLine extends Drawable {
private final Paint paint = new Paint(3);
private final int color;
private final float density;
InkLine(Context context, int color) { this.color = color; density = context.getResources().getDisplayMetrics().density; }
@Override public void draw(Canvas canvas) {
Rect bounds = getBounds();
paint.setColor(color); paint.setAlpha(105); paint.setStrokeWidth(density * .65f);
canvas.drawLine(bounds.left + density * 2, bounds.bottom - density * 2,
bounds.right - density * 5, bounds.bottom - density * 3, paint);
}
@Override public void setAlpha(int alpha) { paint.setAlpha(alpha); }
@Override public void setColorFilter(ColorFilter filter) { paint.setColorFilter(filter); }
@Override public int getOpacity() { return PixelFormat.TRANSLUCENT; }
}
static final class Cover extends View {
private final Paint p = new Paint(3);
Cover(Context context) { super(context); setContentDescription("Mara’s weathered blue cloth notebook, with a handwritten label, stitched spine and a pressed sprig of heather."); }
@Override protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float w = Math.min(getWidth() - 12, getHeight() * 1.72f), h = getHeight() - 18;
float x = (getWidth() - w) / 2, y = 4;
canvas.save(); canvas.translate(x, y);
p.setColor(0x25583e27); canvas.drawRoundRect(6, 10, w + 4, h + 8, 8, 8, p);
p.setColor(0xffd1bd93); canvas.drawRoundRect(7, 5, w, h + 3, 7, 7, p);
p.setColor(0xffe8d8b6);
for (int i = 0; i < 3; i++) canvas.drawLine(12, h - 2 + i * 2, w - 4, h - 2 + i * 2, p);
p.setColor(BLUE); canvas.drawRoundRect(0, 0, w - 3, h - 3, 9, 9, p);
canvas.save(); canvas.clipRect(0, 0, w - 3, h - 3);
p.setStrokeWidth(.6f); p.setColor(0x247e9b9d);
for (float line = 0; line < w; line += 5) canvas.drawLine(line, 0, line, h, p);
for (float line = 0; line < h; line += 5) canvas.drawLine(0, line, w, line, p);
canvas.restore();
p.setShader(new LinearGradient(0, 0, w * .08f, 0, 0xff162f3a, 0xff395b65, Shader.TileMode.CLAMP));
canvas.drawRect(0, 5, w * .065f, h - 8, p); p.setShader(null);
p.setColor(0xff9b9276); p.setStrokeWidth(1.5f);
for (float stitch = 12; stitch < h - 12; stitch += 14) canvas.drawLine(w * .075f, stitch, w * .075f, stitch + 5, p);
p.setColor(0x779eaf9e); p.setStyle(Paint.Style.STROKE); p.setStrokeWidth(1);
canvas.drawRoundRect(w * .11f, h * .07f, w * .93f, h * .92f, 4, 4, p); p.setStyle(Paint.Style.FILL);
// An old label, slightly crooked rather than a digital card.
canvas.save(); canvas.rotate(-2, w * .47f, h * .49f);
p.setColor(0x32533b27); canvas.drawRect(w * .18f + 2, h * .18f + 3, w * .78f + 2, h * .76f + 3, p);
p.setColor(0xffeaddbc); canvas.drawRect(w * .18f, h * .18f, w * .78f, h * .76f, p);
p.setStyle(Paint.Style.STROKE); p.setStrokeWidth(1); p.setColor(0xffae9c77);
canvas.drawRect(w * .20f, h * .21f, w * .76f, h * .73f, p); p.setStyle(Paint.Style.FILL);
p.setColor(INK); p.setTextAlign(Paint.Align.CENTER); p.setTypeface(HAND); p.setTextSize(h * .17f);
canvas.drawText("Mara’s", w * .48f, h * .41f, p);
p.setTypeface(SERIF); p.setTextSize(h * .095f); canvas.drawText("island notebook", w * .48f, h * .55f, p);
p.setTypeface(HAND); p.setTextSize(h * .071f); p.setColor(FADED); canvas.drawText("a few things worth keeping", w * .48f, h * .66f, p);
canvas.restore();
// Faded ribbon poking out of the lower edge.
p.setColor(0xffa35c48); Path ribbon = new Path(); ribbon.moveTo(w * .83f, h * .68f); ribbon.lineTo(w * .89f, h * .68f); ribbon.lineTo(w * .89f, h + 7); ribbon.lineTo(w * .86f, h - 1); ribbon.lineTo(w * .83f, h + 7); ribbon.close(); canvas.drawPath(ribbon, p);
canvas.save(); canvas.translate(w * .80f, h * .20f); canvas.scale(h / 210, h / 210); flower(canvas, p); canvas.restore();
p.setTextAlign(Paint.Align.LEFT); canvas.restore();
}
}
static final class Flower extends View {
private final Paint p = new Paint(3);
Flower(Context context) { super(context); setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO); }
@Override protected void onDraw(Canvas canvas) {
float scale = getHeight() / 150f;
canvas.save(); canvas.translate(getWidth() - 80 * scale, 0); canvas.scale(scale, scale); flower(canvas, p); canvas.restore();
p.setColor(0x586f7154); p.setStrokeWidth(1);
canvas.drawLine(0, getHeight() * .7f, getWidth() - 65 * scale, getHeight() * .7f, p);
}
}
private static void flower(Canvas c, Paint p) {
p.setColor(0xff68765c); p.setStrokeWidth(2.2f); p.setStyle(Paint.Style.STROKE);
Path stem = new Path(); stem.moveTo(12, 137); stem.cubicTo(48, 100, 32, 58, 49, 6); c.drawPath(stem, p);
p.setStyle(Paint.Style.FILL);
for (int i = 0; i < 7; i++) {
float y = 23 + i * 13, x = 47 - i * 2;
p.setColor(i < 4 ? 0xff937f86 : 0xffa59598);
c.save(); c.rotate(i % 2 == 0 ? -35 : 35, x, y);
c.drawOval(x - 9, y - 5, x + 1, y + 5, p); c.drawOval(x + 1, y - 8, x + 10, y + 1, p); c.restore();
}
p.setColor(0xff7e8764); c.save(); c.rotate(-35, 29, 112); c.drawOval(14, 107, 39, 115, p); c.restore();
p.setColor(0x99c5aa77); c.drawRect(12, 118, 52, 132, p);
}
static final class Harbour extends View {
private final Paint p = new Paint(3);
Harbour(Context context) { super(context); setContentDescription("Evening on Mara’s island: a cottage window and a lighthouse beam above the sea."); }
@Override protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.save(); canvas.scale(getWidth() / 600f, getHeight() / 200f);
p.setShader(new LinearGradient(0, 0, 0, 200, new int[]{0xff243f50, 0xff5b7b83, 0xffbbac8f}, null, Shader.TileMode.CLAMP));
canvas.drawRect(0, 0, 600, 200, p); p.setShader(null);
p.setColor(0xffe5d6aa); canvas.drawCircle(111, 37, 10, p);
p.setColor(0xffe9dcb4); for (int i = 0; i < 12; i++) canvas.drawCircle(25 + (i * 71) % 550, 13 + (i * 19) % 65, i % 3 == 0 ? 1.1f : .6f, p);
p.setColor(0xff486772); canvas.drawRect(0, 118, 600, 200, p);
p.setStrokeWidth(.7f); p.setColor(0x686f9698);
for (int i = 0; i < 16; i++) canvas.drawLine((i * 47) % 600, 128 + i * 4, (i * 47) % 600 + 40, 128 + i * 4, p);
p.setColor(0xff233e42); Path land = new Path(); land.moveTo(280, 200); land.cubicTo(330, 150, 375, 166, 408, 127); land.cubicTo(460, 103, 503, 156, 600, 140); land.lineTo(600, 200); land.close(); canvas.drawPath(land, p);
p.setShader(new LinearGradient(430, 78, 80, 91, 0x99f2d88e, 0x00f2d88e, Shader.TileMode.CLAMP));
Path beam = new Path(); beam.moveTo(434, 75); beam.lineTo(35, 44); beam.lineTo(35, 110); beam.close(); canvas.drawPath(beam, p); p.setShader(null);
p.setColor(0xffe6dcc1); Path tower = new Path(); tower.moveTo(426, 89); tower.lineTo(443, 89); tower.lineTo(451, 136); tower.lineTo(419, 136); tower.close(); canvas.drawPath(tower, p);
p.setColor(0xff9c5b43); canvas.drawRect(422, 104, 448, 112, p);
p.setColor(0xffeac577); canvas.drawRect(424, 72, 445, 84, p);
p.setColor(0xff273f47); canvas.drawRect(419, 84, 450, 89, p); Path roof = new Path(); roof.moveTo(419, 72); roof.lineTo(435, 61); roof.lineTo(450, 72); roof.close(); canvas.drawPath(roof, p);
canvas.drawRect(431, 121, 439, 136, p);
p.setColor(0xff927a5c); canvas.drawRect(519, 142, 561, 166, p);
p.setColor(0xff263f42); Path cottage = new Path(); cottage.moveTo(513, 143); cottage.lineTo(541, 123); cottage.lineTo(567, 143); cottage.close(); canvas.drawPath(cottage, p);
p.setColor(0xffe7bf70); canvas.drawRect(529, 148, 537, 157, p); canvas.drawRect(545, 148, 553, 157, p);
p.setColor(0xff203c40); Path front = new Path(); front.moveTo(0, 182); front.cubicTo(90, 158, 175, 175, 255, 200); front.lineTo(0, 200); front.close(); canvas.drawPath(front, p);
canvas.restore();
}
}
private JournalArt() {}
}
@@ -0,0 +1,181 @@
package com.lumen.daily;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/** Count constraints, including overlapping areas. Does not know the hidden picture. */
public final class LogicSolver {
public static final class Constraint {
public final int[] cells;
public final int total;
public final String name;
public Constraint(int[] cells, int total) {
this(cells,total,"Clue");
}
public Constraint(int[] cells,int total,String name) {
this.name = name;
this.cells = cells.clone();
this.total = total;
}
}
public static final class Analysis {
public final boolean solved;
public final int areaDeductions;
public final int[] cells;
Analysis(boolean solved, int areaDeductions, int[] cells) {
this.solved = solved;
this.areaDeductions = areaDeductions;
this.cells = cells.clone();
}
}
private final int cellCount;
private final List<Constraint> constraints;
private final int[] degree;
public LogicSolver(int cellCount, List<Constraint> constraints) {
this.cellCount = cellCount;
this.constraints = new ArrayList<>(constraints);
degree = new int[cellCount];
for (Constraint c : constraints) for (int i : c.cells) degree[i]++;
}
private int remaining(Constraint c, int[] known) {
int total = c.total;
for (int i : c.cells) if (known[i] == 1) total--;
return total;
}
private int unknown(Constraint c, int[] known) {
int count = 0;
for (int i : c.cells) if (known[i] < 0) count++;
return count;
}
/** Returns -1 for a contradiction, otherwise number of newly fixed cells. */
private int singles(int[] known) {
int changes = 0;
for (Constraint c : constraints) {
int need = remaining(c, known), count = unknown(c, known);
if (need < 0 || need > count) return -1;
if (count == 0 || (need != 0 && need != count)) continue;
for (int i : c.cells) if (known[i] < 0) {
known[i] = need == 0 ? 0 : 1;
changes++;
}
}
return changes;
}
private boolean contains(int[] cells, int index) {
for (int i : cells) if (i == index) return true;
return false;
}
/**
* Subtract two overlapping constraints. Shared unknown cells cancel.
* If A-only minus B-only reaches a bound, those cells are all forced.
*/
private int differences(int[] known) {
int changes = 0;
for (int a = 0; a < constraints.size(); a++) {
Constraint first = constraints.get(a);
for (int b = a + 1; b < constraints.size(); b++) {
Constraint second = constraints.get(b);
int onlyA = 0, onlyB = 0;
for (int i : first.cells) if (known[i] < 0 && !contains(second.cells, i)) onlyA++;
for (int i : second.cells) if (known[i] < 0 && !contains(first.cells, i)) onlyB++;
int difference = remaining(first, known) - remaining(second, known);
if (difference > onlyA || difference < -onlyB) return -1;
if (onlyA + onlyB == 0 || (difference != onlyA && difference != -onlyB)) continue;
int valueA = difference == onlyA ? 1 : 0;
for (int i : first.cells) if (known[i] < 0 && !contains(second.cells, i)) {
known[i] = valueA;
changes++;
}
for (int i : second.cells) if (known[i] < 0 && !contains(first.cells, i)) {
known[i] = 1 - valueA;
changes++;
}
}
}
return changes;
}
public static final class Hint {
public final int cell, value;
public final String explanation;
Hint(int cell, int value, String explanation) {
this.cell = cell; this.value = value; this.explanation = explanation;
}
}
public Hint nextHint(int[] known) {
for (Constraint c : constraints) {
int need = remaining(c, known), count = unknown(c, known);
if (need < 0 || need > count) return null;
if (count == 0 || (need != 0 && need != count)) continue;
for (int cell : c.cells) if (known[cell] < 0) return new Hint(cell, need == 0 ? 0 : 1,
c.name + (need == 0 ? " already has all its lights. Every remaining cell in it must be crossed out."
: " needs " + need + " more lights and has exactly " + count + " empty cells. They must all be lit."));
}
for (int a = 0; a < constraints.size(); a++) for (int b = a + 1; b < constraints.size(); b++) {
Constraint first = constraints.get(a), second = constraints.get(b);
int onlyA = 0, onlyB = 0;
for (int i : first.cells) if (known[i] < 0 && !contains(second.cells, i)) onlyA++;
for (int i : second.cells) if (known[i] < 0 && !contains(first.cells, i)) onlyB++;
int needA = remaining(first, known), needB = remaining(second, known), difference = needA - needB;
if (onlyA + onlyB == 0 || (difference != onlyA && difference != -onlyB)) continue;
int valueA = difference == onlyA ? 1 : 0;
String explanation = "Compare " + first.name + " (" + needA + " more lights) with " + second.name
+ " (" + needB + " more). Shared empty cells cancel. The difference forces the cells outside their overlap.";
for (int i : first.cells) if (known[i] < 0 && !contains(second.cells, i)) return new Hint(i, valueA, explanation);
for (int i : second.cells) if (known[i] < 0 && !contains(first.cells, i)) return new Hint(i, 1 - valueA, explanation);
}
return null;
}
public Analysis analyze(int[] initial, boolean useAreas) {
int[] known = initial.clone();
int areaDeductions = 0;
while (true) {
int changed = singles(known);
if (changed < 0) return new Analysis(false, areaDeductions, known);
if (changed > 0) continue;
if (useAreas) {
changed = differences(known);
if (changed < 0) return new Analysis(false, areaDeductions, known);
if (changed > 0) { areaDeductions += changed; continue; }
}
for (int i : known) if (i < 0) return new Analysis(false, areaDeductions, known);
return new Analysis(true, areaDeductions, known);
}
}
public int countSolutions(int[] initial) { return search(initial.clone()); }
private int search(int[] known) {
int changed;
do { changed = singles(known); if (changed < 0) return 0; } while (changed > 0);
int choice = -1;
for (int i = 0; i < cellCount; i++) {
if (known[i] < 0 && (choice < 0 || degree[i] > degree[choice])) choice = i;
}
if (choice < 0) return 1;
int[] branch = known.clone();
branch[choice] = 0;
int count = search(branch);
if (count >= 2) return 2;
known[choice] = 1;
return Math.min(2, count + search(known));
}
public static int[] initial(Puzzle puzzle) {
int[] known = new int[puzzle.solution.length];
Arrays.fill(known, -1);
for (int i = 0; i < known.length; i++) if (puzzle.given[i]) known[i] = puzzle.solution[i];
return known;
}
}
@@ -0,0 +1,851 @@
package com.lumen.daily;
import androidx.activity.ComponentActivity;
import androidx.activity.OnBackPressedCallback;
import android.app.AlertDialog;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.view.accessibility.AccessibilityNodeProvider;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.Space;
import android.widget.TextView;
import android.widget.Toast;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class MainActivity extends ComponentActivity {
private static final int BG = JournalArt.PAPER;
private static final int INK = JournalArt.INK;
private static final int GREEN = JournalArt.BLUE;
private static final int MUTED = Color.rgb(111, 98, 79);
private static final int GOLD = Color.rgb(224, 181, 104);
private static final int AREA = Color.rgb(170, 91, 42);
private enum Mode { DAILY, CLASSIC, CAMPAIGN }
private enum Screen { HOME, MAP, BRIEFING, GAME, REVEAL, STORY }
private SharedPreferences prefs;
private Ads ads;
private StoryNarrator narrator;
private int storyIndex;
private boolean inStoryPuzzle;
private final OnBackPressedCallback back = new OnBackPressedCallback(false) {
@Override public void handleOnBackPressed() { navigateBack(); }
};
private LinearLayout root;
private Puzzle puzzle;
private int[] cells;
private boolean won, legacyPractice;
private Difficulty selected;
private int playingLevel, campaignIndex, selectedArea;
private String key;
private LocalDate date;
private Mode mode = Mode.CLASSIC;
private Screen screen = Screen.HOME;
private Board board;
private final ArrayDeque<int[]> undo = new ArrayDeque<>();
private final List<Button> areaButtons = new ArrayList<>();
@Override public void onCreate(Bundle state) {
super.onCreate(state);
prefs = getSharedPreferences("lumen", 0);
selected = Difficulty.fromStored(prefs.getString("difficulty", "EASY"));
ads = new Ads(this);
narrator = new StoryNarrator(this, prefs);
getOnBackPressedDispatcher().addCallback(this, back);
if (state == null) {
if (prefs.getBoolean("notebook_open", false)) openNotebook(); else home();
return;
}
campaignIndex = Math.max(0, Math.min(Campaign.LEVELS.length - 1, state.getInt("campaign", 0)));
String savedScreen = state.getString("screen", "HOME");
if (savedScreen.equals("STORY")) showStory(StoryBook.indexOf(state.getString("storyPage", StoryBook.PAGES[0].id)));
else if (savedScreen.equals("MAP")) campaignMap();
else if (savedScreen.equals("BRIEFING")) briefing(campaignIndex);
else if (savedScreen.equals("REVEAL")) campaignReveal(campaignIndex);
else if (savedScreen.equals("GAME")) {
String savedMode = state.getString("mode", "CLASSIC");
if (savedMode.equals("CAMPAIGN")) startCampaign(campaignIndex);
else if (savedMode.equals("DAILY")) startDaily(LocalDate.parse(state.getString("date", LocalDate.now().toString())));
else startClassic(state.getBoolean("legacy", false), state.getInt("level", 1));
} else home();
}
@Override protected void onSaveInstanceState(Bundle state) {
super.onSaveInstanceState(state);
state.putString("screen", screen.name());
state.putString("storyPage", StoryBook.PAGES[storyIndex].id);
state.putString("mode", mode.name());
state.putInt("campaign", campaignIndex);
state.putInt("level", playingLevel);
state.putBoolean("legacy", legacyPractice);
if (date != null) state.putString("date", date.toString());
}
private void navigateBack() {
if (screen == Screen.STORY) { if (storyIndex > 0) turnStory(-1); else home(); return; }
if (screen == Screen.MAP) home();
else if (screen == Screen.BRIEFING || screen == Screen.REVEAL || mode == Mode.CAMPAIGN) campaignMap();
else home();
}
@Override protected void onPause() {
if (narrator != null) narrator.stop();
super.onPause();
}
@Override protected void onDestroy() {
if (narrator != null) narrator.close();
super.onDestroy();
}
private int accessibleCampaign() { return Math.max(campaignUnlocked(), Campaign.unlocked(prefs.getInt("story_access_level", 0))); }
private void openNotebook() {
showStory(StoryBook.indexOf(prefs.getString("notebook_last_page", StoryBook.PAGES[0].id)));
}
private void showStory(int index) {
index = Math.max(0, Math.min(StoryBook.PAGES.length - 1, index));
boolean retainPuzzle = inStoryPuzzle && index == 2 && puzzle != null && "story_v1_0".equals(key);
narrator.bind(null); narrator.stop();
storyIndex = index;
inStoryPuzzle = index == 2;
mode = Mode.CAMPAIGN;
campaignIndex = 0;
screen = Screen.STORY;
back.setEnabled(true);
board = null; areaButtons.clear();
if (inStoryPuzzle && !retainPuzzle) readPuzzle(Campaign.puzzle(0), campaignKey(0));
prefs.edit().putString("notebook_last_page", StoryBook.PAGES[index].id)
.putBoolean("notebook_open", true).putBoolean("viewed_" + StoryBook.PAGES[index].id, true).apply();
StoryNotebook notebook = new StoryNotebook(this, prefs, narrator, index, new StoryNotebook.Actions() {
@Override public void turn(int direction) { turnStory(direction); }
@Override public void contents() { storyContents(); }
@Override public void home() { MainActivity.this.home(); }
@Override public void refresh() { showStory(storyIndex); }
@Override public View puzzle() { return storyPuzzleView(); }
@Override public void continueCampaign() {
prefs.edit().putInt("story_access_level", Math.max(1, prefs.getInt("story_access_level", 0))).apply();
briefing(1);
}
});
setContentView(notebook.view);
}
private void turnStory(int direction) {
int next = StoryBook.turn(storyIndex, direction);
if (next == storyIndex) return;
if (storyIndex == 2 && direction > 0 && !won) {
narrator.stop();
new AlertDialog.Builder(this).setTitle("Leave a ribbon here?")
.setMessage("Your puzzle marks are saved. You can read the memory now and come back to solve the pattern whenever you like.")
.setNegativeButton("Keep solving", null).setPositiveButton("Read ahead", (dialog, which) -> {
prefs.edit().putBoolean("notebook_read_ahead", true).apply(); showStory(next);
}).show();
} else showStory(next);
}
private void storyContents() {
narrator.stop();
String[] titles = new String[StoryBook.PAGES.length + 3];
for (int i = 0; i < StoryBook.PAGES.length; i++) titles[i] = (i + 1) + " · " + StoryBook.PAGES[i].title;
titles[6] = "Return to my ribbon bookmark";
titles[7] = "All three chapters";
titles[8] = "Close the notebook";
new AlertDialog.Builder(this).setTitle("The cottage · opening leaves").setItems(titles, (dialog, which) -> {
if (which < StoryBook.PAGES.length) showStory(which);
else if (which == 6) showStory(StoryBook.indexOf(prefs.getString("notebook_manual_bookmark", StoryBook.PAGES[0].id)));
else if (which == 7) campaignMap();
else home();
}).setNegativeButton("Keep reading", null).show();
}
private View storyPuzzleView() {
LinearLayout body = new LinearLayout(this); body.setOrientation(LinearLayout.VERTICAL);
board = new Board();
body.addView(board, new LinearLayout.LayoutParams(-1, -2));
body.addView(text(won ? "Already restored. Turn the leaf to revisit the memory." : "Tap: light → cross → clear. Mark every cell.", 12, MUTED));
if (!won) {
LinearLayout controls = new LinearLayout(this);
for (int i = 0; i < 2; i++) {
final boolean isHint = i == 1;
Button control = new Button(this);
control.setAllCaps(false); control.setTextSize(20); control.setTypeface(JournalArt.HAND);
control.setTextColor(GREEN); control.setStateListAnimator(null); control.setElevation(0);
control.setBackground(new JournalArt.InkLine(this, MUTED));
control.setText(isHint ? prefs.getBoolean("hint_" + key, false) ? "Hint · rewarded ad" : "Hint · free" : "Undo a mark");
control.setOnClickListener(v -> { if (isHint) hint(); else if (!undo.isEmpty()) { cells = undo.pop(); save(); refreshBoard(); } });
controls.addView(control, new LinearLayout.LayoutParams(0, dp(48), 1));
}
body.addView(controls);
}
return body;
}
private int dp(float n) { return (int) (n * getResources().getDisplayMetrics().density + .5f); }
private TextView text(String value, int size, int color) {
TextView view = new TextView(this);
view.setText(value);
view.setTextSize(size <= 12 ? 14 : size);
view.setTextColor(color);
view.setTypeface(JournalArt.HAND);
view.setLineSpacing(dp(2), 1.07f);
view.setPadding(0, dp(5), 0, dp(5));
return view;
}
private void base(Screen nextScreen) {
if (narrator != null) { narrator.bind(null); narrator.stop(); }
inStoryPuzzle = false;
prefs.edit().putBoolean("notebook_open", false).apply();
screen = nextScreen;
back.setEnabled(screen != Screen.HOME);
board = null;
areaButtons.clear();
ScrollView scroll = new ScrollView(this);
scroll.setFillViewport(true);
root = new LinearLayout(this);
root.setOrientation(LinearLayout.VERTICAL);
if (nextScreen != Screen.HOME) {
root.setPadding(dp(10), dp(12), dp(10), dp(20));
root.setBackgroundColor(Color.TRANSPARENT);
scroll.addView(root);
setContentView(new NotebookPage(this, scroll));
return;
}
root.setPadding(dp(30), dp(26), dp(24), dp(34));
root.setBackground(new JournalArt.Paper(this, nextScreen != Screen.HOME));
scroll.setBackgroundColor(Color.rgb(49, 67, 69));
scroll.addView(root);
scroll.setOnApplyWindowInsetsListener((v, insets) -> {
v.setPadding(insets.getSystemWindowInsetLeft() + dp(8), insets.getSystemWindowInsetTop(),
insets.getSystemWindowInsetRight() + dp(8), insets.getSystemWindowInsetBottom());
return insets;
});
setContentView(scroll);
}
private void gap(int size) { root.addView(new Space(this), new LinearLayout.LayoutParams(1, dp(size))); }
private GradientDrawable background(int color, int stroke) {
GradientDrawable result = new GradientDrawable();
result.setColor(color);
result.setCornerRadius(dp(4));
if (stroke != 0) result.setStroke(dp(2), stroke);
return result;
}
private Button button(String title, boolean primary, Runnable action) {
Button view = new Button(this);
view.setText(title);
view.setAllCaps(false);
view.setTextSize(22);
view.setTypeface(JournalArt.HAND);
view.setStateListAnimator(null);
view.setElevation(0);
view.setTextColor(primary ? Color.WHITE : GREEN);
view.setBackground(background(primary ? GREEN : Color.rgb(235, 220, 189), primary ? 0 : Color.rgb(178, 158, 124)));
view.setMinHeight(dp(56));
view.setPadding(dp(14), dp(8), dp(14), dp(8));
if (screen != Screen.HOME) {
view.setTypeface(JournalArt.HAND);
view.setTextSize(primary ? 25 : 22);
view.setTextColor(primary ? GREEN : INK);
view.setGravity(android.view.Gravity.START | android.view.Gravity.CENTER_VERTICAL);
view.setPadding(dp(3), dp(8), dp(3), dp(8));
view.setBackground(new JournalArt.InkLine(this, primary ? GREEN : MUTED));
}
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(-1, -2);
params.setMargins(0, dp(8), 0, 0);
root.addView(view, params);
view.setOnClickListener(v -> action.run());
return view;
}
private TextView handwritten(String value) {
TextView note = text(value, 23, Color.rgb(111, 78, 57));
note.setTypeface(JournalArt.HAND);
note.setLineSpacing(dp(3), 1.08f);
return note;
}
private void flowerDivider() {
root.addView(new JournalArt.Flower(this), new LinearLayout.LayoutParams(-1, dp(58)));
}
private void folio(int index) {
TextView page = text("MARA’S NOTEBOOK / LEAF " + String.format(Locale.ROOT, "%02d", index + 1), 10, MUTED);
root.addView(page);
}
private String granNote(int index) {
String[] notes = {
"My dear, begin with the smallest light.\nThe rest will follow. — Gran",
"A little warmth goes a long way. — M.",
"I always kept a spare here.\nYou never know when it might be needed. — M.",
"Trust your bearings, love. — M.",
"Mind the tide. And take the lantern. — M.",
"There is no shame in stopping a while. — M.",
"The old stones will hold.\nThey have carried us before. — M.",
"If you need me, ring twice. — M.",
"Small things keep the great things turning. — M.",
"A soft cloth, patience, and a steady hand. — M.",
"No one comes home to an unlit shore. — M.",
"This last page is yours, my dear.\nWith all my love, Gran"
};
return notes[index];
}
private int streak() {
return DailyStreak.visible(prefs.getLong("lastDaily", -99999), prefs.getInt("streak", 0), LocalDate.now().toEpochDay());
}
private String campaignKey(int index) { return "story_v1_" + index; }
private boolean recovered(int index) { return prefs.getBoolean("done_" + campaignKey(index), false); }
private int campaignUnlocked() { return Campaign.unlocked(prefs.getInt("campaignUnlocked", 0)); }
private int recoveredCount() {
int count = 0;
for (int i = 0; i < Campaign.LEVELS.length; i++) if (recovered(i)) count++;
return count;
}
private void home() {
base(Screen.HOME);
root.addView(text("L U M E N / AN ISLAND STORY", 11, GREEN));
root.addView(text("A light to come\nhome to.", 36, INK));
root.addView(HomeArtwork.harbour(this), new LinearLayout.LayoutParams(-1, dp(220)));
gap(10);
root.addView(handwritten("Some things are worth keeping. — Gran"));
gap(8);
HomeArtwork.Cover cover = new HomeArtwork.Cover(this);
cover.setFocusable(true);
cover.setOnClickListener(v -> openNotebook());
cover.setContentDescription("Open Mara’s cloth-bound island notebook. " + recoveredCount() + " of 12 memories recovered.");
root.addView(cover, new LinearLayout.LayoutParams(-1, dp(218)));
button(recoveredCount() == Campaign.LEVELS.length ? "Open the keepsake notebook ✓" : "Open Mara’s notebook · " + recoveredCount() + " / 12", true, this::openNotebook);
gap(14);
LinearLayout stats = new LinearLayout(this);
for (String value : new String[]{streak() + "\nDAY STREAK", prefs.getInt("solved", 0) + "\nPATTERNS FOUND"}) {
TextView view = text(value, 14, GREEN);
view.setGravity(android.view.Gravity.CENTER);
stats.addView(view, new LinearLayout.LayoutParams(0, dp(70), 1));
}
root.addView(stats);
flowerDivider();
root.addView(text("A SMALL DAILY RITUAL", 11, MUTED));
root.addView(text(LocalDate.now().format(DateTimeFormatter.ofPattern("EEEE, d MMMM", Locale.getDefault())), 22, INK));
boolean done = prefs.getBoolean("done_d" + LocalDate.now(), false);
button(done ? "Revisit today’s puzzle ✓" : "Play today’s puzzle →", false, () -> startDaily(LocalDate.now()));
gap(18);
root.addView(text("BY THE COTTAGE WINDOW", 11, MUTED));
root.addView(text("A few spare pages for practice. For overlapping-area puzzles, follow the notebook’s story.", 16, MUTED));
button("Difficulty · " + selected.label + " ▾", false, this::chooseDifficulty);
button("Practice · " + selected.label + " · Level " + practiceLevel(), false, () -> startClassic(false, practiceLevel()));
String old = "p" + prefs.getInt("level", 1);
if (prefs.contains("grid_" + old) && !prefs.getBoolean("done_" + old, false)) {
button("Continue earlier puzzle", false, () -> startClassic(true, prefs.getInt("level", 1)));
}
gap(12);
button("How to play", false, this::rules);
button("Privacy & advertising", false, () -> ads.privacy());
gap(12);
root.addView(handwritten("Leave a light in the window."));
}
private void campaignMap() {
base(Screen.MAP);
root.addView(text("THE NOTEBOOK BELONGS TO", 10, MUTED));
TextView owner = handwritten("Mara Wren");
owner.setTextSize(38);
root.addView(owner);
root.addView(text("The Last Light", 28, INK));
root.addView(handwritten("For you, when you are ready.\nWith all my love, Gran."));
flowerDivider();
root.addView(text(Campaign.PREMISE, 16, INK));
gap(10);
root.addView(text(recoveredCount() + " / 12 memories tucked between these pages", 13, MUTED));
for (int i = 0; i < Campaign.LEVELS.length; i++) {
final int index = i;
Campaign.Level level = Campaign.LEVELS[i];
if (i % 4 == 0) { gap(24); root.addView(text(level.chapter, 24, GREEN)); root.addView(handwritten(i < 4 ? "Begin here, my dear." : i < 8 ? "Take care on the crossing." : "I will keep the kettle warm.")); }
boolean done = recovered(i), unlocked = i <= accessibleCampaign();
String label = String.format(Locale.ROOT, "%02d", i + 1) + " · " + (done ? level.object + " ✓" : level.title);
Button entry = button(unlocked ? label : label + " · not yet", false, () -> {
if (recovered(index)) campaignReveal(index); else briefing(index);
});
entry.setTypeface(JournalArt.HAND);
entry.setTextSize(23);
entry.setGravity(android.view.Gravity.START | android.view.Gravity.CENTER_VERTICAL);
entry.setPadding(dp(12), dp(14), dp(12), dp(14));
entry.setBackground(new JournalArt.InkLine(this, unlocked && !done ? GREEN : MUTED));
entry.setEnabled(unlocked);
entry.setTextColor(unlocked ? INK : MUTED);
if (done) {
PictureView miniature = new PictureView(level.picture, 7);
miniature.setContentDescription("Recovered pixel picture: " + level.object);
root.addView(miniature, new LinearLayout.LayoutParams(-1, dp(92)));
}
}
gap(16);
button("Back to home", false, this::home);
}
private void briefing(int index) {
if (index > accessibleCampaign()) { campaignMap(); return; }
campaignIndex = index;
mode = Mode.CAMPAIGN;
base(Screen.BRIEFING);
Campaign.Level level = Campaign.LEVELS[index];
folio(index);
root.addView(text(level.chapter, 13, GREEN));
root.addView(text(level.title, 32, INK));
gap(12);
root.addView(text(level.before, 19, INK));
flowerDivider();
root.addView(handwritten(granNote(index)));
gap(18);
if (index < 2) {
root.addView(text("READ THE NOTEBOOK", 12, GREEN));
root.addView(text("Light the cells to match each row and column total. Cross out the cells that stay dark. The finished 7 × 7 grid is a picture from the story.", 16, MUTED));
} else {
root.addView(text(index == 2 ? "NEW · OVERLAPPING AREAS" : "COMPARE WHAT THE CLUES SHARE", 12, AREA));
root.addView(text("A, B and C are outlined areas with their own light totals. Tap an area’s button to see its boundary. Shared cells count in each area they belong to.", 16, MUTED));
if (index == 2) root.addView(text("Compare two clues: if one area lies inside another, subtract their totals to find the lights outside the smaller area. Rows and columns can be compared with areas too. Every puzzle can be solved without guessing.", 16, INK));
}
button(prefs.contains("grid_" + campaignKey(index)) ? "Continue this pattern →" : "Restore the pattern →", true, () -> startCampaign(index));
button("Back to notebook", false, this::campaignMap);
}
private void campaignReveal(int index) {
if (!recovered(index)) { briefing(index); return; }
campaignIndex = index;
mode = Mode.CAMPAIGN;
base(Screen.REVEAL);
Campaign.Level level = Campaign.LEVELS[index];
folio(index);
root.addView(handwritten("Something found. Something remembered."));
root.addView(text(level.object, 34, INK));
PictureView picture = new PictureView(level.picture, 7);
picture.setContentDescription("Recovered pixel picture: " + level.object);
root.addView(picture, new LinearLayout.LayoutParams(-1, dp(260)));
picture.setAlpha(0f);
picture.animate().alpha(1f).setDuration(850).start();
gap(10);
root.addView(text(level.after, 19, INK));
gap(10);
root.addView(handwritten("Kept safe, between these pages. — M."));
flowerDivider();
if (index == Campaign.LEVELS.length - 1) {
root.addView(text("THE END · YOUR WATCH HAS BEGUN", 12, GREEN));
root.addView(text("Twelve patterns. One light brought home. The daily puzzle will be here whenever you return.", 16, MUTED));
button("Return to the notebook", true, this::campaignMap);
button("Today’s puzzle", false, () -> startDaily(LocalDate.now()));
} else {
button("Turn the page →", true, () -> {
Runnable nextPage = () -> briefing(index + 1);
if ((index + 1) % 4 == 0 && !prefs.getBoolean("storyAd_" + index, false)) {
prefs.edit().putBoolean("storyAd_" + index, true).apply();
ads.between(nextPage);
} else nextPage.run();
});
button("Back to notebook", false, this::campaignMap);
}
}
private void rules() {
new AlertDialog.Builder(this).setTitle("Find the light").setMessage(
"Light exactly as many cells as the number beside each row and above each column.\n\nTap to cycle: empty → light → crossed out → empty. Mark every cell to finish. Small dots mark fixed clues.\n\nIn the story, A, B and C are overlapping areas with their own totals. Tap their buttons to see each boundary. Shared cells count in both areas. Compare clues and subtract their shared parts to find new deductions.\n\nEvery story grid reveals an object. Later pages require area comparisons; all are solvable without guessing. Classic practice grades the length of simpler row and column chains.\n\nOne free explained hint per puzzle, then optional rewarded hints. Streaks count consecutive daily-puzzle completions on this device.")
.setPositiveButton("Got it", null).show();
}
private int practiceLevel() { return prefs.getInt("level_" + selected.name(), 1); }
private void chooseDifficulty() {
String[] labels = new String[3];
for (Difficulty d : Difficulty.values()) labels[d.ordinal()] = d.label + " — " + d.description;
new AlertDialog.Builder(this).setTitle("Classic practice pace").setSingleChoiceItems(labels, selected.ordinal(), (dialog, which) -> {
selected = Difficulty.values()[which];
prefs.edit().putString("difficulty", selected.name()).apply();
dialog.dismiss();
home();
}).setNegativeButton("Cancel", null).show();
}
private void startDaily(LocalDate day) {
mode = Mode.DAILY;
date = day;
legacyPractice = false;
load(new Puzzle(date.toEpochDay() * 7919L), "d" + date);
}
private void startClassic(boolean legacy, int level) {
mode = Mode.CLASSIC;
legacyPractice = legacy;
playingLevel = level;
load(legacy ? new Puzzle(1000000L + level) : Puzzle.generate(1000000L + level, selected),
legacy ? "p" + level : "v2_" + selected.name() + "_" + level);
}
private void startCampaign(int index) {
if (index > accessibleCampaign()) { campaignMap(); return; }
mode = Mode.CAMPAIGN;
campaignIndex = index;
legacyPractice = false;
if (recovered(index)) { campaignReveal(index); return; }
load(Campaign.puzzle(index), campaignKey(index));
}
private void load(Puzzle nextPuzzle, String nextKey) {
inStoryPuzzle = false;
readPuzzle(nextPuzzle, nextKey);
game();
}
private void readPuzzle(Puzzle nextPuzzle, String nextKey) {
puzzle = nextPuzzle;
key = nextKey;
cells = new int[puzzle.solution.length];
String saved = prefs.getString("grid_" + key, "");
for (int i = 0; i < cells.length; i++) {
int value = saved.length() == cells.length ? saved.charAt(i) - '0' : 0;
cells[i] = value >= 0 && value <= 2 ? value : 0;
if (puzzle.given[i]) cells[i] = puzzle.solution[i] == 1 ? 1 : 2;
}
won = prefs.getBoolean("done_" + key, false);
selectedArea = 0;
undo.clear();
save();
}
private void save() {
StringBuilder value = new StringBuilder();
for (int cell : cells) value.append(cell);
prefs.edit().putString("grid_" + key, value.toString()).apply();
}
private void game() {
base(Screen.GAME);
String heading = mode == Mode.DAILY ? "DAILY / " + date.format(DateTimeFormatter.ofPattern("dd MMM"))
: mode == Mode.CAMPAIGN ? "THE LAST LIGHT / " + (campaignIndex + 1) + " OF 12"
: "CLASSIC / " + puzzle.difficulty().label.toUpperCase(Locale.ROOT) + " / LEVEL " + playingLevel;
root.addView(text(heading, 12, GREEN));
root.addView(text(mode == Mode.CAMPAIGN ? Campaign.LEVELS[campaignIndex].title : "Find the light.", 30, INK));
root.addView(text(puzzle.regions.isEmpty() ? "Match the totals. Let the pattern emerge." : "Compare rows, columns and overlapping areas.", 15, MUTED));
if (!puzzle.regions.isEmpty()) {
LinearLayout areas = new LinearLayout(this);
for (int i = 0; i < puzzle.regions.size(); i++) {
final int region = i;
Button chip = new Button(this);
chip.setAllCaps(false);
chip.setTextSize(15);
chip.setMinHeight(dp(52));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, dp(56), 1);
if (i > 0) params.setMargins(dp(6), 0, 0, 0);
areas.addView(chip, params);
chip.setOnClickListener(v -> { selectedArea = region; updateAreas(); if (board != null) board.invalidate(); });
areaButtons.add(chip);
}
root.addView(areas);
root.addView(text("Tap A, B or C to highlight its area · lit / required", 12, AREA));
updateAreas();
}
gap(8);
board = new Board();
root.addView(board, new LinearLayout.LayoutParams(-1, -2));
root.addView(text(won ? "Beautifully solved. Take a breath." : "Tap: light → cross → clear • dots are fixed", 13, MUTED));
if (!won) {
button("Undo last move", false, () -> {
if (!undo.isEmpty()) { cells = undo.pop(); save(); refreshBoard(); }
});
button(prefs.getBoolean("hint_" + key, false) ? "Watch an ad · explained hint" : "One explained hint · free", true, this::hint);
} else button(mode == Mode.DAILY ? "Back to today" : "Next puzzle →", true, this::next);
button(mode == Mode.CAMPAIGN ? "Back to notebook" : "Back to home", false, mode == Mode.CAMPAIGN ? this::campaignMap : this::home);
Board visibleBoard = board;
visibleBoard.post(() -> {
if (visibleBoard.isAttachedToWindow()) visibleBoard.requestRectangleOnScreen(
new Rect(0, 0, visibleBoard.getWidth(), visibleBoard.getHeight()), true);
});
}
private void updateAreas() {
for (int i = 0; i < areaButtons.size(); i++) {
Puzzle.Region region = puzzle.regions.get(i);
int lit = 0;
for (int cell = 0; cell < cells.length; cell++) if (cells[cell] == 1 && region.contains(cell, puzzle.size)) lit++;
Button chip = areaButtons.get(i);
chip.setText(String.format(Locale.getDefault(), "%s %d / %d", region.label, lit, puzzle.regionTotal(region)));
chip.setTextColor(AREA);
chip.setTypeface(JournalArt.HAND, i == selectedArea ? Typeface.BOLD : Typeface.NORMAL);
chip.setStateListAnimator(null);
chip.setElevation(0);
chip.setBackground(new JournalArt.InkLine(this, i == selectedArea ? AREA : MUTED));
chip.setContentDescription("Area " + region.label + ", " + lit + " lit out of " + puzzle.regionTotal(region) + " required. Tap to highlight its boundary.");
}
}
private void refreshBoard() { updateAreas(); if (board != null) board.invalidate(); }
private void hint() {
if (won) return;
if (!prefs.getBoolean("hint_" + key, false)) {
prefs.edit().putBoolean("hint_" + key, true).apply();
explainHint();
} else {
new AlertDialog.Builder(this).setTitle("A little nudge?").setMessage("Watch a rewarded ad for one explained hint.")
.setNegativeButton("Keep thinking", null).setPositiveButton("Watch ad", (dialog, which) -> {
String requested = key;
if (!ads.hint(() -> { if (key.equals(requested) && (screen == Screen.GAME || screen == Screen.STORY && inStoryPuzzle) && !won) explainHint(); })) {
Toast.makeText(this, "No ad available. Please try again later.", Toast.LENGTH_LONG).show();
}
}).show();
}
}
private void explainHint() {
int cell = -1, value = -1;
String explanation = "";
for (int i = 0; i < cells.length; i++) {
if (cells[i] != 0 && cells[i] != (puzzle.solution[i] == 1 ? 1 : 2)) {
cell = i; value = puzzle.solution[i];
explanation = "An earlier mark at this cell conflicts with the clues. Correct it, then continue comparing the totals.";
break;
}
}
if (cell < 0) {
int[] known = new int[cells.length];
for (int i = 0; i < cells.length; i++) known[i] = cells[i] == 0 ? -1 : cells[i] == 1 ? 1 : 0;
LogicSolver.Hint hint = new LogicSolver(cells.length, puzzle.constraints()).nextHint(known);
if (hint != null) { cell = hint.cell; value = hint.value; explanation = hint.explanation; }
}
if (cell < 0) return;
undo.push(cells.clone());
cells[cell] = value == 1 ? 1 : 2;
save();
refreshBoard();
String title = "Row " + (cell / puzzle.size + 1) + ", column " + (cell % puzzle.size + 1);
String action = value == 1 ? "This cell is lit." : "This cell stays dark.";
if (inStoryPuzzle) showStory(2); else game();
new AlertDialog.Builder(this).setTitle(title).setMessage(explanation + "\n\n" + action)
.setPositiveButton("Keep going", (dialog, which) -> check()).show();
}
private void check() {
if (won || !puzzle.solved(cells)) return;
won = true;
SharedPreferences.Editor edit = prefs.edit().putBoolean("done_" + key, true).putInt("solved", prefs.getInt("solved", 0) + 1);
if (mode == Mode.DAILY) {
long day = date.toEpochDay(), last = prefs.getLong("lastDaily", -99999);
if (day > last) edit.putLong("lastDaily", day).putInt("streak", DailyStreak.afterCompletion(last, prefs.getInt("streak", 0), day));
} else if (mode == Mode.CAMPAIGN) {
edit.putInt("campaignUnlocked", Math.max(campaignUnlocked(), Math.min(Campaign.LEVELS.length - 1, campaignIndex + 1)));
} else {
edit.putInt(legacyPractice ? "level" : "level_" + selected.name(), playingLevel + 1);
edit.putInt("practiceCompleted", prefs.getInt("practiceCompleted", 0) + 1);
}
edit.apply();
if (mode == Mode.CAMPAIGN) { if (inStoryPuzzle) showStory(3); else campaignReveal(campaignIndex); return; }
game();
new AlertDialog.Builder(this).setTitle("A moment of clarity.")
.setMessage(mode == Mode.DAILY ? "Today’s grid is complete. Come back tomorrow for a fresh challenge." : "Another pattern found. Ready for the next one?")
.setPositiveButton(mode == Mode.DAILY ? "Lovely" : "Next puzzle", (dialog, which) -> next())
.setNegativeButton("Stay here", null).show();
}
private void next() {
if (mode == Mode.DAILY) { home(); return; }
Runnable nextBoard = () -> startClassic(false, practiceLevel());
if (prefs.getInt("practiceCompleted", 0) > 0 && prefs.getInt("practiceCompleted", 0) % 4 == 0) ads.between(nextBoard);
else nextBoard.run();
}
private final class PictureView extends View {
private final int[] pixels;
private final int size;
private final Paint paint = new Paint(3);
PictureView(int[] pixels, int size) { super(MainActivity.this); this.pixels = pixels; this.size = size; }
@Override protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
float unit = Math.min(getWidth(), getHeight()) / (size + 2f);
float left = (getWidth() - size * unit) / 2, top = (getHeight() - size * unit) / 2;
float cardLeft = left - unit * .55f, cardTop = top - unit * .55f;
float cardRight = left + unit * (size + .55f), cardBottom = top + unit * (size + .55f);
paint.setColor(0x285d4930);
canvas.drawRect(cardLeft + dp(3), cardTop + dp(4), cardRight + dp(3), cardBottom + dp(4), paint);
paint.setColor(Color.rgb(250, 241, 216));
canvas.drawRect(cardLeft, cardTop, cardRight, cardBottom, paint);
paint.setColor(0x90c5ae7e);
canvas.save(); canvas.rotate(-18, cardLeft + unit, cardTop);
canvas.drawRect(cardLeft, cardTop - unit * .2f, cardLeft + unit * 2, cardTop + unit * .25f, paint); canvas.restore();
canvas.save(); canvas.rotate(15, cardRight - unit, cardTop);
canvas.drawRect(cardRight - unit * 2, cardTop - unit * .2f, cardRight, cardTop + unit * .25f, paint); canvas.restore();
paint.setColor(GREEN);
for (int i = 0; i < pixels.length; i++) if (pixels[i] == 1) {
float x = left + i % size * unit, y = top + i / size * unit;
canvas.drawRect(x, y, x + unit + .5f, y + unit + .5f, paint);
}
}
}
private final class Board extends View {
private final Paint paint = new Paint(3);
private float unit, left, top;
private int accessibilityFocus = -1;
Board() {
super(MainActivity.this);
setLayerType(View.LAYER_TYPE_SOFTWARE, null);
setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
setContentDescription("Puzzle grid. Row and column numbers show required lit cells. Tap each cell to change it.");
}
@Override protected void onMeasure(int widthSpec, int heightSpec) {
int width = MeasureSpec.getSize(widthSpec);
int desiredHeight = Math.min(width, dp(inStoryPuzzle ? 350 : puzzle.size == 7 ? 414 : 350));
setMeasuredDimension(width, resolveSize(desiredHeight, heightSpec));
}
private void label(Canvas canvas, String value, float x, float y, int color, float size) {
paint.setColor(color);
paint.setTypeface(JournalArt.HAND);
paint.setTextSize(size);
paint.setTextAlign(Paint.Align.CENTER);
canvas.drawText(value, x, y, paint);
}
@Override protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int n = puzzle.size;
unit = Math.min(getWidth() / (n + 1f), getHeight() / (n + 1f));
left = (getWidth() - unit * (n + 1)) / 2;
top = (getHeight() - unit * (n + 1)) / 2;
for (int row = 0; row < n; row++) {
int lit = 0; for (int col = 0; col < n; col++) if (cells[row * n + col] == 1) lit++;
label(canvas, "" + puzzle.rows[row], left + unit * .4f, top + unit * (row + 1.64f), lit == puzzle.rows[row] ? GREEN : MUTED, unit * .33f);
}
for (int col = 0; col < n; col++) {
int lit = 0; for (int row = 0; row < n; row++) if (cells[row * n + col] == 1) lit++;
label(canvas, "" + puzzle.cols[col], left + unit * (col + 1.5f), top + unit * .64f, lit == puzzle.cols[col] ? GREEN : MUTED, unit * .33f);
}
Puzzle.Region active = puzzle.regions.isEmpty() ? null : puzzle.regions.get(selectedArea);
for (int i = 0; i < cells.length; i++) {
float x = left + unit * (i % n + 1), y = top + unit * (i / n + 1), pad = unit * .055f;
boolean highlighted = active != null && active.contains(i, n);
paint.setColor(cells[i] == 1 ? GREEN : highlighted ? 0x259F6335 : 0x076A6045);
canvas.drawRoundRect(x + pad, y + pad, x + unit - pad, y + unit - pad, unit * .055f, unit * .055f, paint);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(dp(.7f));
paint.setColor(cells[i] == 1 ? GREEN : 0xAA8C8064);
canvas.drawRoundRect(x + pad, y + pad, x + unit - pad, y + unit - pad, unit * .055f, unit * .055f, paint);
paint.setStyle(Paint.Style.FILL);
if (cells[i] == 1) { paint.setColor(GOLD); canvas.drawCircle(x + unit * .5f, y + unit * .5f, unit * .14f, paint); }
if (cells[i] == 2) {
paint.setColor(MUTED); paint.setStrokeWidth(dp(1.5f));
canvas.drawLine(x + unit * .4f, y + unit * .4f, x + unit * .6f, y + unit * .6f, paint);
canvas.drawLine(x + unit * .6f, y + unit * .4f, x + unit * .4f, y + unit * .6f, paint);
}
if (puzzle.given[i]) { paint.setColor(cells[i] == 1 ? Color.WHITE : MUTED); canvas.drawCircle(x + unit * .78f, y + unit * .22f, unit * .035f, paint); }
}
if (active != null) {
paint.setColor(AREA); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(dp(2.5f));
float x = left + unit * (active.left + 1), y = top + unit * (active.top + 1);
canvas.drawRoundRect(x + 1, y + 1, x + unit * active.width - 1, y + unit * active.height - 1, unit * .12f, unit * .12f, paint);
paint.setStyle(Paint.Style.FILL);
}
if (accessibilityFocus >= 0) {
int row = accessibilityFocus / n, col = accessibilityFocus % n;
paint.setColor(INK); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(dp(2));
canvas.drawRect(left + unit * (col + 1), top + unit * (row + 1), left + unit * (col + 2), top + unit * (row + 2), paint);
paint.setStyle(Paint.Style.FILL);
}
}
private int cellAt(float x, float y) {
if (unit <= 0) return -1;
int col = (int) Math.floor((x - left) / unit) - 1, row = (int) Math.floor((y - top) / unit) - 1;
return row >= 0 && row < puzzle.size && col >= 0 && col < puzzle.size ? row * puzzle.size + col : -1;
}
private void changeCell(int cell) {
if (cell < 0 || cell >= cells.length || won || puzzle.given[cell]) return;
undo.push(cells.clone());
cells[cell] = (cells[cell] + 1) % 3;
save(); refreshBoard(); check();
}
@Override public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) { changeCell(cellAt(event.getX(), event.getY())); performClick(); }
return true;
}
@Override public boolean performClick() { super.performClick(); return true; }
private void focusEvent(int cell, int type) {
AccessibilityEvent event = AccessibilityEvent.obtain(type);
event.setSource(this, cell);
event.setPackageName(getPackageName());
event.setClassName("android.widget.Button");
if (getParent() != null) getParent().requestSendAccessibilityEvent(this, event);
}
@Override public boolean dispatchHoverEvent(MotionEvent event) {
android.view.accessibility.AccessibilityManager manager = (android.view.accessibility.AccessibilityManager) getSystemService(ACCESSIBILITY_SERVICE);
if (manager != null && manager.isTouchExplorationEnabled()) {
int cell = cellAt(event.getX(), event.getY());
if (cell >= 0 && event.getAction() != MotionEvent.ACTION_HOVER_EXIT) {
focusEvent(cell, AccessibilityEvent.TYPE_VIEW_HOVER_ENTER);
return true;
}
if (accessibilityFocus >= 0) focusEvent(accessibilityFocus, AccessibilityEvent.TYPE_VIEW_HOVER_EXIT);
}
return super.dispatchHoverEvent(event);
}
@Override public AccessibilityNodeProvider getAccessibilityNodeProvider() {
return new AccessibilityNodeProvider() {
@Override public AccessibilityNodeInfo createAccessibilityNodeInfo(int id) {
if (id == View.NO_ID) {
AccessibilityNodeInfo node = AccessibilityNodeInfo.obtain(Board.this);
onInitializeAccessibilityNodeInfo(node);
for (int i = 0; i < cells.length; i++) node.addChild(Board.this, i);
return node;
}
if (id < 0 || id >= cells.length) return null;
AccessibilityNodeInfo node = AccessibilityNodeInfo.obtain();
node.setSource(Board.this, id); node.setParent(Board.this); node.setPackageName(getPackageName());
node.setClassName("android.widget.Button"); node.setEnabled(true); node.setVisibleToUser(isShown()); node.setFocusable(true);
node.setClickable(!won && !puzzle.given[id]);
node.setAccessibilityFocused(accessibilityFocus == id);
String description = "Row " + (id / puzzle.size + 1) + ", column " + (id % puzzle.size + 1) + ", "
+ (cells[id] == 1 ? "lit" : cells[id] == 2 ? "crossed out" : "empty") + (puzzle.given[id] ? ", fixed clue" : "")
+ ". Row needs " + puzzle.rows[id / puzzle.size] + ", column needs " + puzzle.cols[id % puzzle.size];
for (Puzzle.Region region : puzzle.regions) if (region.contains(id, puzzle.size)) description += ". In area " + region.label + ", total " + puzzle.regionTotal(region);
node.setContentDescription(description);
int x = (int) (left + unit * (id % puzzle.size + 1)), y = (int) (top + unit * (id / puzzle.size + 1));
Rect bounds = new Rect(x, y, (int) (x + unit), (int) (y + unit));
node.setBoundsInParent(bounds);
int[] location = new int[2]; getLocationOnScreen(location); bounds.offset(location[0], location[1]); node.setBoundsInScreen(bounds);
if (!won && !puzzle.given[id]) node.addAction(AccessibilityNodeInfo.ACTION_CLICK);
node.addAction(accessibilityFocus == id ? AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS : AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS);
return node;
}
@Override public boolean performAction(int id, int action, Bundle arguments) {
if (id < 0 || id >= cells.length) return false;
if (action == AccessibilityNodeInfo.ACTION_CLICK && !won && !puzzle.given[id]) { changeCell(id); return true; }
if (action == AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS) {
accessibilityFocus = id; invalidate(); focusEvent(id, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUSED); return true;
}
if (action == AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS) {
accessibilityFocus = -1; invalidate(); focusEvent(id, AccessibilityEvent.TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED); return true;
}
return false;
}
};
}
}
}
@@ -0,0 +1,114 @@
package com.lumen.daily;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Rect;
import android.view.View;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ScrollView;
/** Positions actual writing on one continuous diary page. */
final class NotebookPage extends ViewGroup {
private static Bitmap artwork;
private final ImageView image;
private final View content;
interface PageTurn { void turn(int direction); }
private PageTurn pageTurn;
private final PageTurnGesture gesture = new PageTurnGesture();
void setPageTurn(PageTurn listener) { pageTurn = listener; }
private final Rect imageBounds = new Rect();
private final Rect contentBounds = new Rect();
private final float density;
NotebookPage(Context context, View content) {
super(context);
this.content = content;
density = getResources().getDisplayMetrics().density;
setBackgroundColor(Color.rgb(64, 49, 35));
if (artwork == null) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;
artwork = BitmapFactory.decodeResource(getResources(), R.drawable.mara_diary_page, options);
}
image = new ImageView(context);
image.setImageBitmap(artwork);
image.setScaleType(ImageView.ScaleType.FIT_CENTER);
image.setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_NO);
addView(image);
addView(content);
setOnApplyWindowInsetsListener((view, insets) -> {
setPadding(insets.getSystemWindowInsetLeft(), insets.getSystemWindowInsetTop(),
insets.getSystemWindowInsetRight(), insets.getSystemWindowInsetBottom());
return insets;
});
}
@Override public boolean onInterceptTouchEvent(MotionEvent event) {
if (pageTurn == null) return false;
if (event.getActionMasked() == MotionEvent.ACTION_DOWN) {
gesture.begin(event.getX(),event.getY(),contentBounds.left,contentBounds.right,22*density);
} else if (event.getActionMasked() == MotionEvent.ACTION_MOVE) {
return gesture.intercept(event.getX(),event.getY(),28*density);
} else if (event.getActionMasked() == MotionEvent.ACTION_CANCEL) gesture.cancel();
return false;
}
@Override public boolean onTouchEvent(MotionEvent event) {
if (pageTurn == null) return super.onTouchEvent(event);
if (event.getActionMasked() == MotionEvent.ACTION_DOWN)
return gesture.begin(event.getX(),event.getY(),contentBounds.left,contentBounds.right,22*density);
if (!gesture.active()) return false;
if (event.getActionMasked() == MotionEvent.ACTION_UP) {
int direction=gesture.finish(event.getX(),event.getY(),48*density);
if(direction!=0){pageTurn.turn(direction);performClick();}
} else if (event.getActionMasked() == MotionEvent.ACTION_CANCEL) gesture.cancel();
return true;
}
@Override public boolean performClick() { super.performClick(); return true; }
private void arrange(int width, int height) {
int x = getPaddingLeft(), y = getPaddingTop();
int w = Math.max(1, width - x - getPaddingRight());
int h = Math.max(1, height - y - getPaddingBottom());
if (w > h * 1.15f) {
// Crop the blank middle of the same sheet in landscape, keeping text on paper.
// Crop only vertically: the left-edge binding remains visible.
image.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageBounds.set(x, y, x + w, y + h);
int writingWidth = Math.min(Math.round(w * .78f), Math.round(640 * density));
int writingLeft = x + (w - writingWidth) / 2;
contentBounds.set(writingLeft, y + Math.round(h * .06f),
writingLeft + writingWidth, y + Math.round(h * .94f));
} else {
image.setScaleType(ImageView.ScaleType.FIT_CENTER);
float scale = Math.min(w / (float)artwork.getWidth(), h / (float)artwork.getHeight());
int bookWidth = Math.round(artwork.getWidth() * scale), bookHeight = Math.round(artwork.getHeight() * scale);
int left = x + (w - bookWidth) / 2, top = y + (h - bookHeight) / 2;
imageBounds.set(left, top, left + bookWidth, top + bookHeight);
// The single page has no centre gutter. Leave the right margin for heather.
boolean narrow = w / density < 480;
contentBounds.set(left + Math.round(bookWidth * (narrow ? .08f : .11f)), top + Math.round(bookHeight * .12f),
left + Math.round(bookWidth * (narrow ? .91f : .83f)), top + Math.round(bookHeight * .91f));
}
}
@Override protected void onMeasure(int widthSpec, int heightSpec) {
int width = MeasureSpec.getSize(widthSpec), height = MeasureSpec.getSize(heightSpec);
setMeasuredDimension(width, height);
arrange(width, height);
image.measure(MeasureSpec.makeMeasureSpec(imageBounds.width(), MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(imageBounds.height(), MeasureSpec.EXACTLY));
content.measure(MeasureSpec.makeMeasureSpec(contentBounds.width(), MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(contentBounds.height(), MeasureSpec.EXACTLY));
}
@Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
image.layout(imageBounds.left, imageBounds.top, imageBounds.right, imageBounds.bottom);
content.layout(contentBounds.left, contentBounds.top, contentBounds.right, contentBounds.bottom);
}
}
@@ -0,0 +1,20 @@
package com.lumen.daily;
/** Only gestures starting in a page margin can become page turns. */
final class PageTurnGesture {
private float startX, startY;
private boolean active;
boolean begin(float x,float y,float left,float right,float margin) {
startX=x;startY=y;active=x<left+margin||x>right-margin;return active;
}
boolean intercept(float x,float y,float threshold) {
float dx=x-startX,dy=y-startY;
return active&&Math.abs(dx)>threshold&&Math.abs(dx)>Math.abs(dy)*1.5f;
}
int finish(float x,float y,float threshold) {
boolean turn=intercept(x,y,threshold);active=false;
return turn?(x<startX?1:-1):0;
}
void cancel(){active=false;}
boolean active(){return active;}
}
@@ -0,0 +1,118 @@
package com.lumen.daily;
import java.util.*;
/** Binary grid constrained by row/column totals and immutable given cells. */
public final class Puzzle {
public final int size;
public final int[] solution, rows, cols;
public final boolean[] given;
public final List<Region> regions = new ArrayList<>();
public static final class Region {
public final String label;
public final int top, left, height, width;
public Region(String label,int top,int left,int height,int width){this.label=label;this.top=top;this.left=left;this.height=height;this.width=width;}
public boolean contains(int index,int size){int r=index/size,c=index%size;return r>=top&&r<top+height&&c>=left&&c<left+width;}
}
public Puzzle(int size,int[] picture){
this.size=size;solution=picture.clone();rows=new int[size];cols=new int[size];given=new boolean[size*size];
if(picture.length!=size*size)throw new IllegalArgumentException("Wrong picture size");
for(int i=0;i<solution.length;i++){if(solution[i]!=0&&solution[i]!=1)throw new IllegalArgumentException("Non-binary picture");rows[i/size]+=solution[i];cols[i%size]+=solution[i];}
}
public int regionTotal(Region region){int total=0;for(int i=0;i<solution.length;i++)if(region.contains(i,size))total+=solution[i];return total;}
public List<LogicSolver.Constraint> constraints(){
List<LogicSolver.Constraint> result=new ArrayList<>();
for(int line=0;line<size;line++){int[] row=new int[size],col=new int[size];for(int pos=0;pos<size;pos++){row[pos]=line*size+pos;col[pos]=pos*size+line;}result.add(new LogicSolver.Constraint(row,rows[line],"Row "+(line+1)));result.add(new LogicSolver.Constraint(col,cols[line],"Column "+(line+1)));}
for(Region region:regions){int[] indices=new int[region.height*region.width];int at=0;for(int r=region.top;r<region.top+region.height;r++)for(int c=region.left;c<region.left+region.width;c++)indices[at++]=r*size+c;result.add(new LogicSolver.Constraint(indices,regionTotal(region),"Area "+region.label));}return result;
}
public Puzzle(long seed) {
size=5;solution=new int[25];rows=new int[5];cols=new int[5];given=new boolean[25];
Random random = new Random(seed);
for(int i=0;i<25;i++){ solution[i]=random.nextBoolean()?1:0; rows[i/5]+=solution[i]; cols[i%5]+=solution[i]; }
List<Integer> order=new ArrayList<>(); for(int i=0;i<25;i++)order.add(i); Collections.shuffle(order,random);
for(int i:order){ if(countSolutions()==1)break; given[i]=true; }
}
/** Keep the original constructor stable so existing saved grids remain valid. */
public static Puzzle generate(long seed, Difficulty difficulty) {
Random seeds = new Random(seed);
for (int attempt = 0; attempt < 256; attempt++) {
Puzzle candidate = new Puzzle(seeds.nextLong());
if (difficulty != Difficulty.EASY) candidate.removeRedundantClues();
if (candidate.difficulty() == difficulty) return candidate;
}
// Bounded generation: known graded boards, varied by row/column permutations.
Puzzle fallback = new Puzzle(difficulty == Difficulty.HARD ? 2L : 0L);
if (difficulty != Difficulty.EASY) fallback.removeRedundantClues();
fallback.permute(seeds);
return fallback;
}
private void removeRedundantClues() {
for (int i = 0; i < 25; i++) {
if (!given[i]) continue;
given[i] = false;
if (countSolutions() != 1) given[i] = true;
}
}
private void permute(Random random) {
List<Integer> r = new ArrayList<>(), c = new ArrayList<>();
for (int i = 0; i < 5; i++) { r.add(i); c.add(i); }
Collections.shuffle(r, random); Collections.shuffle(c, random);
int[] oldSolution = solution.clone(); boolean[] oldGiven = given.clone();
Arrays.fill(rows, 0); Arrays.fill(cols, 0);
for (int i = 0; i < 25; i++) {
int from = r.get(i / 5) * 5 + c.get(i % 5);
solution[i] = oldSolution[from]; given[i] = oldGiven[from];
rows[i / 5] += solution[i]; cols[i % 5] += solution[i];
}
}
/**
* Count simultaneous rounds of human deductions. A line is forced when its
* remaining total is zero or equals its unknown cells. Each round reads only
* the previous round's state, so scan order cannot affect the rating.
* The solution is deliberately not consulted except to read the printed clues.
*/
public int deductionRounds() {
int[] known = new int[solution.length]; Arrays.fill(known, -1);
for (int i = 0; i < solution.length; i++) if (given[i]) known[i] = solution[i];
int rounds = 0;
while (true) {
int remaining = 0; for (int value : known) if (value < 0) remaining++;
if (remaining == 0) return rounds;
int[] next = known.clone(); boolean changed = false;
for (int axis = 0; axis < 2; axis++) for (int line = 0; line < size; line++) {
int lit = 0, unknown = 0;
for (int pos = 0; pos < size; pos++) {
int index = axis == 0 ? line * size + pos : pos * size + line;
if (known[index] < 0) unknown++; else lit += known[index];
}
int need = (axis == 0 ? rows[line] : cols[line]) - lit;
if (need < 0 || need > unknown) throw new IllegalStateException("Contradictory puzzle");
if (unknown == 0 || (need != 0 && need != unknown)) continue;
for (int pos = 0; pos < size; pos++) {
int index = axis == 0 ? line * size + pos : pos * size + line;
if (known[index] < 0) { next[index] = need == 0 ? 0 : 1; changed = true; }
}
}
if (!changed) throw new IllegalStateException("Puzzle requires guessing");
known = next; rounds++;
}
}
public Difficulty difficulty() { return Difficulty.fromRounds(deductionRounds()); }
public int countSolutions(){return size==5&&regions.isEmpty()?search(0,new int[5]):new LogicSolver(solution.length,constraints()).countSolutions(LogicSolver.initial(this));}
private int search(int row,int[] totals){
if(row==5)return Arrays.equals(totals,cols)?1:0;
int count=0;
for(int mask=0;mask<32;mask++){
if(Integer.bitCount(mask)!=rows[row])continue;
boolean ok=true; int[] next=totals.clone();
for(int c=0;c<5;c++){int v=(mask>>c)&1; int i=row*5+c; next[c]+=v;
if((given[i]&&solution[i]!=v)||next[c]>cols[c]||next[c]+4-row<cols[c])ok=false;
}
if(ok)count+=search(row+1,next); if(count>=2)return 2;
}return count;
}
public boolean solved(int[] cells){if(cells==null||cells.length!=solution.length)return false;for(int i=0;i<solution.length;i++)if(cells[i]!=(solution[i]==1?1:2))return false;return true;}
}
@@ -0,0 +1,36 @@
package com.lumen.daily;
/** Stable, authored page records. Puzzle save IDs remain independent of reading progress. */
final class StoryBook {
enum Kind { DEDICATION, ENTRY, PUZZLE, MEMORY, LETTER, LANTERN }
static final class Page {
final String id, title, speaker, text;
final Kind kind;
Page(String id, Kind kind, String title, String speaker, String text) {
this.id = id; this.kind = kind; this.title = title; this.speaker = speaker; this.text = text;
}
}
static final Page[] PAGES = {
new Page("cottage.dedication", Kind.DEDICATION, "For you, when you are ready", "Mara",
"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"),
new Page("cottage.window", Kind.ENTRY, "By the cottage window", "Mara",
"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."),
new Page("cottage.match.puzzle", Kind.PUZZLE, "A spark in the drawer", "Notebook",
"Restore the small pattern on this page. Match the row and column totals, and mark every cell. You can also leave it for later and read on."),
new Page("cottage.match.memory", Kind.MEMORY, "One small light", "Mara",
"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."),
new Page("cottage.folded.note", Kind.LETTER, "A note I nearly forgot", "Mara",
"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"),
new Page("cottage.lantern.sketch", Kind.LANTERN, "The handle, carefully mended", "Mara",
"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.")
};
static int indexOf(String id) {
for (int i = 0; i < PAGES.length; i++) if (PAGES[i].id.equals(id)) return i;
return 0;
}
static int turn(int index, int direction) { return Math.max(0, Math.min(PAGES.length - 1, index + direction)); }
static String[] sentences(String text) {
return text.trim().split("(?<=[.!?])\\s+|\\n+");
}
private StoryBook() {}
}
@@ -0,0 +1,156 @@
package com.lumen.daily;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.SharedPreferences;
import android.content.res.AssetFileDescriptor;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.PlaybackParams;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import org.json.JSONArray;
import org.json.JSONObject;
/** Plays bundled, pre-rendered FLAC recordings. No text-to-speech service is used. */
final class StoryNarrator {
private final Activity activity;
private final SharedPreferences prefs;
private final AudioManager audio;
private final Handler handler = new Handler(Looper.getMainLooper());
private final AudioManager.OnAudioFocusChangeListener focus;
private JSONObject tracks = new JSONObject();
private MediaPlayer player;
private Runnable changed;
private String pageId = "", error = "";
private boolean loading, prepared, playing, paused, finished;
private final Runnable tick = new Runnable() {
@Override public void run() {
if (playing) { notifyChanged(); handler.postDelayed(this, 200); }
}
};
StoryNarrator(Activity activity, SharedPreferences prefs) {
this.activity = activity; this.prefs = prefs;
audio = (AudioManager)activity.getSystemService(Activity.AUDIO_SERVICE);
focus = change -> { if (change < 0) handler.post(this::pause); };
try (InputStream input = activity.getResources().openRawResource(R.raw.narration_manifest);
ByteArrayOutputStream bytes = new ByteArrayOutputStream()) {
byte[] buffer = new byte[4096]; int count;
while ((count = input.read(buffer)) != -1) bytes.write(buffer, 0, count);
tracks = new JSONObject(new String(bytes.toByteArray(), StandardCharsets.UTF_8)).getJSONObject("tracks");
} catch (Exception e) { error = "The recorded readings could not be opened."; }
}
void bind(Runnable listener) { changed = listener; notifyChanged(); }
boolean isPlaying() { return playing; }
boolean isPaused() { return paused; }
boolean isLoading() { return loading; }
boolean hasRecording(String id) { return resource(id) != 0; }
String controlLabel() { return loading ? "Opening recording…" : playing ? "Pause recording" : paused ? "Resume recording" : finished ? "Replay recording" : "Play this reading"; }
String status() {
if (!error.isEmpty()) return error;
if (loading) return "Opening the reading kept with this page…";
if (playing || paused) return (paused ? "Paused · " : "Playing · ") + time(position()) + " / " + time(duration());
return finished ? "End of the reading · listen again whenever you like" : "A recorded reading, kept with this page";
}
private String time(int milliseconds) { int s = milliseconds / 1000; return (s / 60) + ":" + (s % 60 < 10 ? "0" : "") + s % 60; }
private int position() { try { return player != null && prepared ? player.getCurrentPosition() : 0; } catch (IllegalStateException e) { return 0; } }
private int duration() { try { return player != null && prepared ? player.getDuration() : 0; } catch (IllegalStateException e) { return 0; } }
String currentPassage() {
if (!playing && !paused) return "";
JSONObject track = tracks.optJSONObject(pageId);
JSONArray cues = track == null ? null : track.optJSONArray("cues");
int at = position();
if (cues != null) for (int i = 0; i < cues.length(); i++) {
JSONObject cue = cues.optJSONObject(i);
if (cue != null && at >= cue.optInt("startMs") && at < cue.optInt("endMs")) return cue.optString("text");
}
return "";
}
private int resource(String id) {
JSONObject track = tracks.optJSONObject(id);
return track == null ? 0 : activity.getResources().getIdentifier(track.optString("resource"), "raw", activity.getPackageName());
}
void toggle(String id) {
if (loading) return;
if (playing && pageId.equals(id)) { pause(); return; }
if (paused && pageId.equals(id) && prepared) { start(); return; }
int source = resource(id);
if (source == 0) { Toast.makeText(activity,"This page has no recording yet. Its text is always available.",Toast.LENGTH_LONG).show(); return; }
stop(); pageId = id; error = ""; loading = true;
MediaPlayer current = new MediaPlayer(); player = current;
current.setAudioAttributes(new AudioAttributes.Builder().setUsage(AudioAttributes.USAGE_MEDIA)
.setContentType(AudioAttributes.CONTENT_TYPE_SPEECH).build());
current.setOnPreparedListener(p -> {
if (p != player) return;
loading = false; prepared = true; start();
});
current.setOnCompletionListener(p -> {
if (p != player) return;
playing = false; paused = false; finished = true;
handler.removeCallbacks(tick); releaseFocus(); notifyChanged();
});
current.setOnErrorListener((p, what, extra) -> {
if (p == player) fail();
return true;
});
try (AssetFileDescriptor file = activity.getResources().openRawResourceFd(source)) {
if (file == null) throw new IllegalStateException("Recording unavailable");
current.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
current.prepareAsync(); notifyChanged();
} catch (Exception e) { fail(); }
}
private void start() {
if (player == null || !prepared) return;
if (audio != null && audio.requestAudioFocus(focus, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT)
!= AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
paused = true; notifyChanged();
Toast.makeText(activity,"Another app is using the audio. Try again when it finishes.",Toast.LENGTH_SHORT).show(); return;
}
try {
applySpeed(); player.start(); playing = true; paused = false; finished = false;
handler.removeCallbacks(tick); handler.post(tick); notifyChanged();
} catch (IllegalStateException e) { fail(); }
}
private void applySpeed() {
if (player == null || !prepared) return;
float speed = prefs.getFloat("recording_speed", 1f);
try { player.setPlaybackParams(new PlaybackParams().setPitch(1f).setSpeed(speed)); }
catch (IllegalArgumentException | IllegalStateException e) {
Toast.makeText(activity,"This device plays the recording at its original speed.",Toast.LENGTH_SHORT).show();
}
}
void pause() {
if (!playing || player == null) return;
try { player.pause(); } catch (IllegalStateException e) { fail(); return; }
playing = false; paused = true; handler.removeCallbacks(tick); releaseFocus(); notifyChanged();
}
void stop() {
playing = false; paused = false; loading = false; prepared = false; finished = false;
handler.removeCallbacks(tick);
MediaPlayer previous = player; player = null;
if (previous != null) previous.release();
pageId = ""; releaseFocus(); notifyChanged();
}
private void fail() { stop(); error = "This recording could not be played. You can still read the entry."; notifyChanged(); }
private void releaseFocus() { if (audio != null) audio.abandonAudioFocus(focus); }
private void notifyChanged() { if (changed != null) changed.run(); }
void close() { changed = null; stop(); }
void settings() {
pause();
float speed = prefs.getFloat("recording_speed", 1f);
new AlertDialog.Builder(activity).setTitle("Recording speed")
.setSingleChoiceItems(new String[]{"Unhurried · 0.85×", "Original reading · 1.0×", "A little faster · 1.15×"},
speed < .95f ? 0 : speed > 1.05f ? 2 : 1, (dialog, which) -> {
prefs.edit().putFloat("recording_speed", new float[]{.85f,1f,1.15f}[which]).apply(); dialog.dismiss();
}).setNegativeButton("Keep this speed",null).show();
}
}
@@ -0,0 +1,210 @@
package com.lumen.daily;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Typeface;
import android.os.Build;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.BackgroundColorSpan;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
/** Six opening leaves, with fixed navigation and overflow scrolling for larger text. */
final class StoryNotebook {
interface Actions {
void turn(int direction);
void contents();
void home();
void refresh();
void continueCampaign();
View puzzle();
}
final NotebookPage view;
private final Activity activity;
private final SharedPreferences prefs;
private final StoryNarrator narrator;
private final Actions actions;
private final StoryBook.Page page;
private final LinearLayout body;
private TextView narrationText;
private static Bitmap cottage, lantern;
StoryNotebook(Activity activity, SharedPreferences prefs, StoryNarrator narrator, int index, Actions actions) {
this.activity = activity; this.prefs = prefs; this.narrator = narrator; this.actions = actions;
page = StoryBook.PAGES[index];
LinearLayout sheet = column();
sheet.setPadding(dp(10), dp(8), dp(10), dp(6));
ScrollView reader = new ScrollView(activity);
reader.setFillViewport(false);
body = column();
reader.addView(body);
sheet.addView(reader, new LinearLayout.LayoutParams(-1, 0, 1));
addLabel("MARA’S NOTEBOOK / " + (index + 1) + " OF 6", 10, JournalArt.BLUE, false);
addLabel(page.title, page.kind == StoryBook.Kind.DEDICATION ? 29 : 25, JournalArt.INK, false);
buildPage();
navigation(sheet, index);
view = new NotebookPage(activity, sheet);
view.setPageTurn(actions::turn);
if (Build.VERSION.SDK_INT >= 26 && android.animation.ValueAnimator.areAnimatorsEnabled()) {
sheet.setAlpha(.35f); sheet.setTranslationX(dp(12));
sheet.animate().alpha(1f).translationX(0).setDuration(180).start();
}
}
private int dp(float value) { return (int)(value * activity.getResources().getDisplayMetrics().density + .5f); }
private LinearLayout column() { LinearLayout v = new LinearLayout(activity); v.setOrientation(LinearLayout.VERTICAL); return v; }
private TextView label(String value, int size, int color, boolean hand) {
TextView v = new TextView(activity); v.setText(value); v.setTextSize(size <= 11 ? 13 : size == 18 ? 21 : size < 18 ? 18 : size >= 25 ? 29 : size); v.setTextColor(color);
v.setTypeface(JournalArt.HAND);
v.setLineSpacing(dp(2), 1.03f); v.setPadding(0, dp(5), 0, dp(5)); return v;
}
private TextView addLabel(String value, int size, int color, boolean hand) { TextView v = label(value,size,color,hand);body.addView(v);return v; }
private Button action(String title, Runnable run) {
Button v = new Button(activity); v.setText(title);v.setAllCaps(false);v.setTextSize(19);v.setTypeface(JournalArt.HAND);
v.setTextColor(JournalArt.BLUE);v.setStateListAnimator(null);v.setElevation(0);v.setMinHeight(dp(48));
v.setPadding(dp(3),dp(3),dp(3),dp(3));v.setBackground(new JournalArt.InkLine(activity,JournalArt.FADED));
v.setOnClickListener(w -> run.run());return v;
}
private void narration(String text) {
LinearLayout controls = new LinearLayout(activity);
Button play = action(narrator.controlLabel(), () -> narrator.toggle(page.id));
Button stop = action("Stop", narrator::stop);
Button settings = action("Speed", narrator::settings);
controls.addView(play,new LinearLayout.LayoutParams(0,-2,2.7f));
controls.addView(stop,new LinearLayout.LayoutParams(0,-2,1));
controls.addView(settings,new LinearLayout.LayoutParams(0,-2,1));
body.addView(controls);
TextView state=addLabel("A reading kept with this page",10,JournalArt.FADED,false);
final String[] lastPassage = {null};
narrator.bind(() -> {
play.setText(narrator.controlLabel());
String status = narrator.status();
state.setText(status);
play.setEnabled(!narrator.isLoading() && narrator.hasRecording(page.id));
if (narrationText != null) {
SpannableString highlighted=new SpannableString(text);
String current=narrator.currentPassage();
if (current.equals(lastPassage[0])) return;
lastPassage[0] = current;
int at=text.indexOf(current);
if ((narrator.isPlaying()||narrator.isPaused())&&!current.isEmpty()&&at>=0)
highlighted.setSpan(new BackgroundColorSpan(0x55E0B568),at,at+current.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
narrationText.setText(highlighted);
}
});
}
private ImageView illustration(boolean isLantern,int height,String description) {
if (isLantern && lantern==null || !isLantern && cottage==null) {
BitmapFactory.Options options=new BitmapFactory.Options();options.inScaled=false;options.inSampleSize=2;
Bitmap bitmap=BitmapFactory.decodeResource(activity.getResources(),isLantern?R.drawable.story_lantern:R.drawable.story_cottage,options);
if(isLantern)lantern=bitmap;else cottage=bitmap;
}
ImageView image=new ImageView(activity);image.setImageBitmap(isLantern?lantern:cottage);
image.setScaleType(ImageView.ScaleType.FIT_CENTER);image.setContentDescription(description);
body.addView(image,new LinearLayout.LayoutParams(-1,dp(height)));return image;
}
private void buildPage() {
switch(page.kind) {
case DEDICATION:
addLabel("A few things worth keeping",17,JournalArt.FADED,true);
body.addView(new JournalArt.Flower(activity),new LinearLayout.LayoutParams(-1,dp(46)));
narrationText=addLabel(page.text,22,0xff70503b,true);
narration(page.text);
break;
case ENTRY:
illustration(false,155,"Watercolour of Gran’s stone cottage, blue door and a warm window.");
addLabel("A note beside the window · Mara",11,JournalArt.FADED,false);
narrationText=addLabel(page.text,18,JournalArt.INK,false);
narration(page.text);
break;
case PUZZLE:
addLabel("Restore a small light, or leave a bookmark and read on.",14,JournalArt.FADED,false);
body.addView(actions.puzzle());
break;
case MEMORY:
MatchSketch match=new MatchSketch(activity);match.setContentDescription("A pencil sketch of a single match and a small amber flame.");
body.addView(match,new LinearLayout.LayoutParams(-1,dp(140)));
addLabel(prefs.getBoolean("done_story_v1_0",false)?"A pattern restored · a memory kept":"A memory to read · your puzzle can wait",11,JournalArt.FADED,false);
narrationText=addLabel(page.text,18,JournalArt.INK,false);
narration(page.text);
break;
case LETTER:
boolean open=prefs.getBoolean("notebook_note_open",false);
if(!open) {
addLabel("A folded scrap, tucked between the leaves.",19,JournalArt.INK,true);
Envelope envelope=new Envelope(activity);envelope.setContentDescription("Folded note with a wax seal. Double tap to unfold Gran’s note.");
envelope.setFocusable(true);envelope.setOnClickListener(v -> openLetter());
body.addView(envelope,new LinearLayout.LayoutParams(-1,dp(190)));
body.addView(action("Unfold Gran’s note",this::openLetter));
addLabel("You don’t have to solve anything to discover this.",15,JournalArt.FADED,false);
} else {
addLabel("For the crossing",25,0xff70503b,true);
narrationText=addLabel(page.text,20,0xff70503b,true);
narration(page.text);
body.addView(action("Fold the note again",() -> {prefs.edit().putBoolean("notebook_note_open",false).apply();actions.refresh();}));
}
break;
case LANTERN:
ImageView image=illustration(true,155,"Watercolour of Mara’s blue storm lantern. Tap to examine the repaired handle.");
image.setFocusable(true);image.setOnClickListener(v -> inspectLantern());
addLabel(prefs.getBoolean("notebook_handle_seen",false)?"A repair made to keep small fingers safe.":"Tap the lantern to look a little closer.",15,JournalArt.FADED,true);
narrationText=addLabel(page.text,18,JournalArt.INK,false);
narration(page.text);
body.addView(action("Follow the lantern into the next entry →",actions::continueCampaign));
break;
}
}
private void openLetter(){prefs.edit().putBoolean("notebook_note_open",true).apply();actions.refresh();}
private void inspectLantern(){
prefs.edit().putBoolean("notebook_handle_seen",true).apply();
new android.app.AlertDialog.Builder(activity).setTitle("A careful repair")
.setMessage("The wire is hidden under a strip of cloth. In the margin, Gran has written: ‘The light matters. So do the hands carrying it.’")
.setPositiveButton("Keep that thought",(d,w)->actions.refresh()).show();
}
private void navigation(LinearLayout sheet,int index) {
LinearLayout tools=new LinearLayout(activity);
Button contents=action("Contents",actions::contents);
Button mark=action("Bookmark",()->{prefs.edit().putString("notebook_manual_bookmark",page.id).apply();Toast.makeText(activity,"A ribbon marks this page.",Toast.LENGTH_SHORT).show();});
Button home=action("Close book",actions::home);
for(Button button:new Button[]{contents,mark,home})tools.addView(button,new LinearLayout.LayoutParams(0,-2,1));
sheet.addView(tools);
LinearLayout turns=new LinearLayout(activity);
Button previous=action("← Previous leaf",()->actions.turn(-1));previous.setEnabled(index>0);previous.setAlpha(index>0?1f:.35f);
Button next=action(index==StoryBook.PAGES.length-1?"End of this trail":"Next leaf →",()->actions.turn(1));
next.setEnabled(index<StoryBook.PAGES.length-1);next.setAlpha(index<StoryBook.PAGES.length-1?1f:.35f);
turns.addView(previous,new LinearLayout.LayoutParams(0,-2,1));turns.addView(next,new LinearLayout.LayoutParams(0,-2,1));sheet.addView(turns);
}
private static final class MatchSketch extends View {
private final Paint p=new Paint(3);
MatchSketch(Activity c){super(c);}
@Override protected void onDraw(Canvas c){float h=getHeight(),x=getWidth()*.51f;
p.setColor(0xff997445);p.setStrokeWidth(h*.045f);c.drawLine(x-25,h*.88f,x+12,h*.36f,p);
p.setColor(0xff654539);c.drawOval(x+2,h*.27f,x+26,h*.41f,p);
p.setColor(0xAADEA94C);Path f=new Path();f.moveTo(x+12,h*.33f);f.cubicTo(x-24,h*.17f,x+30,h*.19f,x+17,h*.05f);f.cubicTo(x+56,h*.20f,x+32,h*.33f,x+12,h*.33f);c.drawPath(f,p);
p.setColor(0xff7d7360);p.setStrokeWidth(1);c.drawLine(x-85,h*.91f,x+80,h*.91f,p);
}
}
private static final class Envelope extends View {
private final Paint p=new Paint(3);
Envelope(Activity c){super(c);}
@Override protected void onDraw(Canvas c){float w=getWidth(),h=getHeight(),l=w*.1f,r=w*.9f,t=h*.15f,b=h*.86f;
p.setColor(0x255D4930);c.drawRect(l+4,t+5,r+4,b+5,p);p.setColor(0xffead9b2);c.drawRect(l,t,r,b,p);
p.setColor(0xffb8a17c);p.setStrokeWidth(2);p.setStyle(Paint.Style.STROKE);c.drawRect(l,t,r,b,p);
c.drawLine(l,t,w*.5f,h*.59f,p);c.drawLine(r,t,w*.5f,h*.59f,p);c.drawLine(l,b,w*.40f,h*.50f,p);c.drawLine(r,b,w*.60f,h*.50f,p);p.setStyle(Paint.Style.FILL);
p.setColor(0xff9e5f49);c.drawCircle(w*.5f,h*.57f,h*.075f,p);
}
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 MiB

@@ -0,0 +1,9 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="108dp" android:height="108dp" android:viewportWidth="108" android:viewportHeight="108">
<path android:fillColor="#274956" android:pathData="M0,0h108v108h-108z"/>
<path android:fillColor="#E0B568" android:fillAlpha="0.5" android:pathData="M58,34L7,19L7,49z"/>
<path android:fillColor="#F3E7CC" android:pathData="M53,45L68,45L76,87L45,87z"/>
<path android:fillColor="#A35C48" android:pathData="M49,65L72,65L73,73L48,73z"/>
<path android:fillColor="#E0B568" android:pathData="M51,31h19v12h-19z"/>
<path android:fillColor="#172F3A" android:pathData="M46,30L61,18L76,30z M47,43h27v5h-27z M57,77h8v10h-8z"/>
<path android:fillColor="#8A9F9B" android:pathData="M14,92h80v2h-80z M19,98h38v1h-38z M68,98h22v1h-22z"/>
</vector>
Binary file not shown.
@@ -0,0 +1,144 @@
{
"tracks": {
"cottage.dedication": {
"pageId": "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",
"file": "narration_cottage_dedication.flac",
"sampleRate": 24000,
"channels": 1,
"frames": 441184,
"durationMs": 18383,
"textSha256": "7ecbea473a70ab48a49861535bf30a3909005ce5735dcd048bc6abe576b1e017",
"flacSha256": "7606f2ea97386ed864155438d2785f6d8e6593fc04d785d432dfceb07bff52b7",
"cues": [
{
"startMs": 180,
"endMs": 9268,
"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."
},
{
"startMs": 9868,
"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"
}
]
},
"cottage.window": {
"pageId": "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.",
"file": "narration_cottage_window.flac",
"sampleRate": 24000,
"channels": 1,
"frames": 499104,
"durationMs": 20796,
"textSha256": "10b04750290618c667a1ab3e92247d59ea6796ac33c910906b292b6735da204c",
"flacSha256": "01864da94337c06445b60694faf2484c4a59f5f11fabc0f8d8b87a620ee09193",
"cues": [
{
"startMs": 180,
"endMs": 6473,
"text": "The wind has finally gone quiet. I have put the blue cup by the window, where you always liked to sit."
},
{
"startMs": 7073,
"endMs": 15009,
"text": "The latch still sticks. Lift it a little before you turn it. Some things on this island need a gentle hand, not a stronger one."
},
{
"startMs": 15609,
"endMs": 20196,
"text": "If you arrive after dark, there is something in the little drawer beside the hearth."
}
]
},
"cottage.match.memory": {
"pageId": "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.",
"file": "narration_cottage_match_memory.flac",
"sampleRate": 24000,
"channels": 1,
"frames": 506848,
"durationMs": 21119,
"textSha256": "b047af77227d4084883babe2d7bec9cbebf8a3d807cf8d45b72e76f72db9eac5",
"flacSha256": "6cd5fadf22ce6f8ebc6a9c8968e87fb1b31a0f1e52693c7e942d8498691a533c",
"cues": [
{
"startMs": 180,
"endMs": 6644,
"text": "You used to insist on lighting the evening lantern yourself. I held the matchbox, and you held your breath."
},
{
"startMs": 7244,
"endMs": 11212,
"text": "Once, you asked how such a little flame could help anyone out at sea."
},
{
"startMs": 11812,
"endMs": 15801,
"text": "It cannot, I told you. But it can help us find the next light."
},
{
"startMs": 16401,
"endMs": 20519,
"text": "I kept one dry match in a tin after that. Just in case."
}
]
},
"cottage.folded.note": {
"pageId": "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",
"file": "narration_cottage_folded_note.flac",
"sampleRate": 24000,
"channels": 1,
"frames": 425888,
"durationMs": 17745,
"textSha256": "2101efa580ab39cff6956a3e0011d5399e820aca79f9f60a25848487c6bcb9ad",
"flacSha256": "3675b260102c1b157e8741ff6ed9d062735860d33a15d1bbe397d997e91a2403",
"cues": [
{
"startMs": 180,
"endMs": 6964,
"text": "If the tide has covered the causeway, use the little boat by the harbour steps. The knot looks worse than it is."
},
{
"startMs": 7564,
"endMs": 12108,
"text": "Take the lantern. When you reach the bell, ring twice. I will know it is you."
},
{
"startMs": 12708,
"endMs": 17145,
"text": "And do not let the tea go cold while you are deciding.\n\nLove, Gran"
}
]
},
"cottage.lantern.sketch": {
"pageId": "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.",
"file": "narration_cottage_lantern_sketch.flac",
"sampleRate": 24000,
"channels": 1,
"frames": 366944,
"durationMs": 15289,
"textSha256": "fbfc663172995a1beb20b48e65b8f469b44b7bf26609721fe34b158ecc9bdf97",
"flacSha256": "60a823473a66b1ea4c5156889f66fe276bc103db475a3e6c831cd41649d7cbd3",
"cues": [
{
"startMs": 180,
"endMs": 8735,
"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."
},
{
"startMs": 9335,
"endMs": 14689,
"text": "People notice the flame first. I tend to notice the things that let us carry it."
}
]
}
}
}
+1
View File
@@ -0,0 +1 @@
<resources><style name="AppTheme" parent="BaseAppTheme"><item name="android:navigationBarColor">#F3E7CC</item><item name="android:windowLightNavigationBar">true</item></style></resources>
+1
View File
@@ -0,0 +1 @@
<resources><style name="BaseAppTheme" parent="android:style/Theme.Material.Light.NoActionBar"><item name="android:fontFamily">cursive</item><item name="android:colorAccent">#274956</item><item name="android:windowLightStatusBar">true</item><item name="android:statusBarColor">#F3E7CC</item><item name="android:navigationBarColor">#314345</item></style><style name="AppTheme" parent="BaseAppTheme"/></resources>
@@ -0,0 +1 @@
<data-extraction-rules><cloud-backup><exclude domain="root" path="."/><exclude domain="sharedpref" path="."/><exclude domain="database" path="."/><exclude domain="file" path="."/></cloud-backup><device-transfer><exclude domain="root" path="."/><exclude domain="sharedpref" path="."/><exclude domain="database" path="."/><exclude domain="file" path="."/></device-transfer></data-extraction-rules>
@@ -0,0 +1,76 @@
package com.lumen.daily;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import static org.junit.Assert.*;
public class CampaignTest {
@Test public void everyPictureIsUniqueAndSolvableWithoutSearch() {
Set<String> pictures = new HashSet<>();
assertEquals(12, Campaign.LEVELS.length);
for (int level = 0; level < Campaign.LEVELS.length; level++) {
Puzzle p = Campaign.puzzle(level);
assertEquals(7, p.size);
assertEquals(49, p.solution.length);
assertTrue(pictures.add(java.util.Arrays.toString(p.solution)));
assertEquals("level " + level, 1, p.countSolutions());
LogicSolver solver = new LogicSolver(49, p.constraints());
LogicSolver.Analysis a = solver.analyze(LogicSolver.initial(p), true);
assertTrue("level " + level, a.solved);
assertArrayEquals(p.solution, a.cells);
if (level >= 2) {
assertEquals(3, p.regions.size());
assertFalse("Area comparisons must actually be required at level " + level,
solver.analyze(LogicSolver.initial(p), false).solved);
assertTrue(a.areaDeductions > 0);
// The added areas genuinely resolve ambiguity in the original rules.
Puzzle rowsOnly = new Puzzle(7, p.solution);
System.arraycopy(p.given, 0, rowsOnly.given, 0, p.given.length);
assertEquals(2, rowsOnly.countSolutions());
}
for (Puzzle.Region r : p.regions) {
assertTrue(r.top >= 0 && r.left >= 0 && r.top + r.height <= 7 && r.left + r.width <= 7);
int sum = 0;
for (int cell = 0; cell < 49; cell++) if (r.contains(cell, 7)) sum += p.solution[cell];
assertEquals(sum, p.regionTotal(r));
}
}
}
@Test public void explainedHintsCanCompleteEveryStoryBoard() {
for (int level = 0; level < 12; level++) {
Puzzle p = Campaign.puzzle(level);
LogicSolver solver = new LogicSolver(49, p.constraints());
int[] known = LogicSolver.initial(p);
for (int step = 0; step < 49; step++) {
LogicSolver.Hint hint = solver.nextHint(known);
if (hint == null) break;
assertEquals(-1, known[hint.cell]);
assertEquals(p.solution[hint.cell], hint.value);
assertFalse(hint.explanation.isEmpty());
known[hint.cell] = hint.value;
}
assertArrayEquals("level " + level, p.solution, known);
}
}
@Test public void completionRequiresEveryMarkAndRegenerationIsStable() {
for (int level = 0; level < 12; level++) {
Puzzle p = Campaign.puzzle(level), q = Campaign.puzzle(level);
assertArrayEquals(p.solution, q.solution);
assertArrayEquals(p.given, q.given);
int[] marks = new int[49];
for (int i = 0; i < 49; i++) marks[i] = p.solution[i] == 1 ? 1 : 2;
assertTrue(p.solved(marks));
marks[48] = 0;
assertFalse(p.solved(marks));
}
}
@Test public void restoredProgressIsClamped() {
assertEquals(0, Campaign.unlocked(-2));
assertEquals(11, Campaign.unlocked(12));
assertEquals(5, Campaign.unlocked(5));
}
}
@@ -0,0 +1,6 @@
package com.lumen.daily;
import org.junit.Test;import static org.junit.Assert.*;
public class DailyStreakTest {
@Test public void consecutiveDaysAndReplay(){assertEquals(1,DailyStreak.afterCompletion(-99999,0,20000));assertEquals(4,DailyStreak.afterCompletion(20000,3,20001));assertEquals(3,DailyStreak.afterCompletion(20000,3,20000));}
@Test public void missedDayResetsAndGraceLastsThroughNextDay(){assertEquals(1,DailyStreak.afterCompletion(20000,3,20002));assertEquals(3,DailyStreak.visible(20000,3,20001));assertEquals(0,DailyStreak.visible(20000,3,20002));}
}
@@ -0,0 +1,49 @@
package com.lumen.daily;
import org.junit.Test;
import static org.junit.Assert.*;
public class DifficultyTest {
@Test public void everyModeMatchesItsGradeWithoutGuessing() {
for (Difficulty difficulty : Difficulty.values()) {
for (long seed = 0; seed < 500; seed++) {
Puzzle p = Puzzle.generate(seed, difficulty);
assertEquals("seed " + seed, difficulty, p.difficulty());
assertEquals(1, p.countSolutions());
int rounds = p.deductionRounds();
if (difficulty == Difficulty.EASY) assertTrue(rounds <= 2);
if (difficulty == Difficulty.MEDIUM) assertTrue(rounds >= 3 && rounds <= 4);
if (difficulty == Difficulty.HARD) assertEquals(5, rounds);
}
}
}
@Test public void generationIsStableForSavedBoards() {
for (Difficulty d : Difficulty.values()) for (int seed = 0; seed < 30; seed++) {
Puzzle a = Puzzle.generate(seed, d), b = Puzzle.generate(seed, d);
assertArrayEquals(a.solution, b.solution);
assertArrayEquals(a.given, b.given);
assertArrayEquals(a.rows, b.rows);
assertArrayEquals(a.cols, b.cols);
}
}
@Test public void graderUsesOnlyCluesAndRejectsAmbiguousBoards() {
Puzzle p = new Puzzle(0);
java.util.Arrays.fill(p.given, false);
java.util.Arrays.fill(p.rows, 2);
java.util.Arrays.fill(p.cols, 2);
try { p.deductionRounds(); fail("Ambiguous board must not receive a grade"); }
catch (IllegalStateException expected) { assertEquals("Puzzle requires guessing", expected.getMessage()); }
}
@Test public void originalBoardsStayCompatible() {
Puzzle p = new Puzzle(0);
assertArrayEquals(new int[]{1,1,0,1,1,0,1,0,1,1,0,0,0,1,1,1,1,0,1,0,0,0,0,0,0},p.solution);
}
@Test public void invalidStoredSelectionFallsBackToEasy() {
assertEquals(Difficulty.EASY, Difficulty.fromStored("UNKNOWN"));
assertEquals(Difficulty.HARD, Difficulty.fromStored("HARD"));
}
}
@@ -0,0 +1,64 @@
package com.lumen.daily;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import org.junit.Test;
import static org.junit.Assert.*;
public class LogicSolverTest {
@Test public void overlappingDifferenceFindsWhatSingleTotalsCannot() {
List<LogicSolver.Constraint> constraints = Arrays.asList(
new LogicSolver.Constraint(new int[]{0, 1, 2}, 1, "Area A"),
new LogicSolver.Constraint(new int[]{1, 2}, 1, "Area B"));
LogicSolver solver = new LogicSolver(3, constraints);
int[] initial = {-1, -1, -1};
assertArrayEquals(initial, solver.analyze(initial, false).cells);
LogicSolver.Hint hint = solver.nextHint(initial);
assertNotNull(hint);
assertEquals(0, hint.cell);
assertEquals(0, hint.value);
assertTrue(hint.explanation.contains("Shared"));
assertEquals(0, solver.analyze(initial, true).cells[0]);
}
@Test public void searchAndDeductionsAgreeWithExhaustiveEnumeration() {
Random random = new Random(18273);
for (int trial = 0; trial < 1000; trial++) {
List<LogicSolver.Constraint> constraints = new ArrayList<>();
for (int c = 0; c < 5; c++) {
List<Integer> indices = new ArrayList<>();
for (int i = 0; i < 6; i++) if (random.nextBoolean()) indices.add(i);
int[] cells = new int[indices.size()];
for (int i = 0; i < cells.length; i++) cells[i] = indices.get(i);
constraints.add(new LogicSolver.Constraint(cells, random.nextInt(cells.length + 1)));
}
int[] initial = {-1, -1, -1, -1, -1, -1};
if (random.nextBoolean()) initial[random.nextInt(6)] = random.nextInt(2);
List<int[]> solutions = new ArrayList<>();
for (int mask = 0; mask < 64; mask++) {
int[] values = new int[6]; boolean valid = true;
for (int i = 0; i < 6; i++) {
values[i] = (mask >> i) & 1;
if (initial[i] >= 0 && initial[i] != values[i]) valid = false;
}
for (LogicSolver.Constraint c : constraints) {
int sum = 0; for (int i : c.cells) sum += values[i];
if (sum != c.total) valid = false;
}
if (valid) solutions.add(values);
}
LogicSolver solver = new LogicSolver(6, constraints);
assertEquals(Math.min(2, solutions.size()), solver.countSolutions(initial));
if (!solutions.isEmpty()) {
LogicSolver.Hint hint = solver.nextHint(initial);
LogicSolver.Analysis analysis = solver.analyze(initial, true);
for (int[] solution : solutions) {
if (hint != null) assertEquals(solution[hint.cell], hint.value);
for (int i = 0; i < 6; i++) if (analysis.cells[i] >= 0) assertEquals(solution[i], analysis.cells[i]);
}
}
}
}
}
@@ -0,0 +1,8 @@
package com.lumen.daily;
import org.junit.Test;
import static org.junit.Assert.*;
public class PageTurnGestureTest {
@Test public void gridDragCannotBecomeAPageTurn(){PageTurnGesture g=new PageTurnGesture();assertFalse(g.begin(300,400,100,700,22));assertFalse(g.intercept(650,400,28));assertEquals(0,g.finish(650,400,48));}
@Test public void marginsTurnInBothDirections(){PageTurnGesture g=new PageTurnGesture();assertTrue(g.begin(690,400,100,700,22));assertTrue(g.intercept(600,401,28));assertEquals(1,g.finish(500,403,48));assertTrue(g.begin(110,400,100,700,22));assertEquals(-1,g.finish(300,410,48));}
@Test public void verticalScrollTinyMovesAndCancellationDoNotTurn(){PageTurnGesture g=new PageTurnGesture();g.begin(110,400,100,700,22);assertEquals(0,g.finish(120,650,48));g.begin(110,400,100,700,22);assertEquals(0,g.finish(135,402,48));g.begin(110,400,100,700,22);g.cancel();assertEquals(0,g.finish(300,400,48));}
}
@@ -0,0 +1,5 @@
package com.lumen.daily;
import org.junit.Test; import static org.junit.Assert.*;
public class PuzzleTest {
@Test public void generatedBoardsAreUniqueAndDeterministic(){for(long seed=0;seed<500;seed++){Puzzle p=new Puzzle(seed), q=new Puzzle(seed); assertEquals(1,p.countSolutions());assertArrayEquals(p.solution,q.solution);assertArrayEquals(p.given,q.given);int[] cells=new int[25];for(int i=0;i<25;i++)cells[i]=p.solution[i]==1?1:2;assertTrue(p.solved(cells));cells[0]=0;assertFalse(p.solved(cells));}}
}
@@ -0,0 +1,16 @@
package com.lumen.daily;
import org.junit.Test;
import static org.junit.Assert.*;
public class StoryBookTest {
@Test public void bookmarksResolveStableIdsAndUnknownIdsRecover(){
String[] ids={"cottage.dedication","cottage.window","cottage.match.puzzle","cottage.match.memory","cottage.folded.note","cottage.lantern.sketch"};
assertEquals(ids.length,StoryBook.PAGES.length);
for(int i=0;i<ids.length;i++){assertEquals(ids[i],StoryBook.PAGES[i].id);assertEquals(i,StoryBook.indexOf(ids[i]));}
assertEquals(0,StoryBook.indexOf("removed.page"));assertEquals(0,StoryBook.indexOf(null));
}
@Test public void pageBoundariesCannotEscapeTheBook(){assertEquals(0,StoryBook.turn(0,-1));assertEquals(5,StoryBook.turn(5,1));assertEquals(3,StoryBook.turn(2,1));}
@Test public void spokenPassagesKeepSentenceBoundaries(){
assertArrayEquals(new String[]{"My dear,","Come home.","Is the lamp lit?","Yes!"},StoryBook.sentences("My dear,\n\nCome home. Is the lamp lit? Yes!"));
for(StoryBook.Page page:StoryBook.PAGES)for(String sentence:StoryBook.sentences(page.text))assertFalse(sentence.trim().isEmpty());
}
}
+17
View File
@@ -0,0 +1,17 @@
# Diary artwork
The current asset is `mara-single-page-v2.png`, a 1024×1536 opaque PNG generated with the built-in image generation tool. Its exact prompt is in `mara-single-page-v2.prompt.txt`. An identical copy ships as `app/src/main/res/drawable-nodpi/mara_diary_page.png`.
Version 1.5 places text, handwritten menu entries and a pencil-outline puzzle directly on this single page, with no overlay card or centre seam. The binding is on the left; the right margin is reserved for the ribbon and heather. Portrait shows the whole page. Landscape crops the blank middle of the same sheet to fill the display while retaining its proportions and left binding. Content stays on the paper in both orientations.
The earlier `mara-notebook-background-v1.png` and its prompt are preserved for comparison. That two-page spread was used in version 1.4 and superseded because the central fold and floating content panel did not fit the desired diary presentation.
## Opening story illustrations
`cottage-vignette-v1.png` and `lantern-vignette-v1.png` were created with the built-in image generation tool. Their exact generation prompts are saved in the matching `.prompt.txt` files. Both originals retain alpha transparency. Identical copies ship as `story_cottage.png` and `story_lantern.png` in Android's `drawable-nodpi` resources, and the app decodes them with sampling for small illustrations.
## Refreshed home screen (1.7)
`home-harbour-v2.png` and `home-notebook-cover-v2.png` were generated with the built-in image generation tool, using new-image generation with transparent backgrounds. Their exact prompts are preserved in `home-harbour-v2.prompt.txt` and `home-notebook-cover-v2.prompt.txt`. Originals are copied to `drawable-nodpi/home_harbour.png` and `home_notebook_cover.png` for offline use.
The harbour is a soft-edged northern-island watercolour; the closed cover is faded blue linen with heather, repairs and a red ribbon. `HomeArtwork.java` preserves aspect ratio and places a native handwritten label on the cover’s blank paper label. These replace the earlier Canvas harbour and cover on the “A light to come home to” screen. No readable text was generated into either image.
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 MiB

@@ -0,0 +1 @@
Use case: illustration-story. Asset: a small illustration printed inside an elderly lighthouse keeper's diary. Delicate watercolour and fine graphite pencil, muted sea blue, warm ivory, faded rust and amber accents. Intimate northern European island storybook mood. Isolated vignette with genuinely transparent background, soft irregular fading pigment edges, no enclosing box or frame, no letters, no readable text, no watermark. The image should remain clear as a small illustration on warm paper. Subject: a tiny old stone coastal cottage, weathered blue front door, a single warmly lit window, slate roof, a little grass around the steps. Eye-level three-quarter view. Quiet, personal and carefully observed rather than cartoonish. Compact landscape composition.
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 MiB

@@ -0,0 +1,4 @@
Use case: illustration-story. Asset: wide home-screen illustration for Lumen, a gentle illustrated diary story about Mara, an elderly lighthouse keeper on a northern European island.
Create an original, carefully painted watercolour panorama of the island at dusk: an old stone lighthouse on a low coastal headland, a narrow sea inlet and a small stone cottage with one warm amber window. The lighthouse beam reaches softly across the bay. Quiet water, a weathered shoreline, a little heather, cool sea-blue air and a warm sense of coming home.
Style: delicate storybook watercolour, fine graphite details, visible but restrained pigment and paper texture, matching an antique ivory diary with sea-blue linen, rust-red ribbon and faded lavender. Natural materials and soft edges; affectionate and intimate rather than epic. Soft dusk lighting, no hard graphic shapes or geometric vector styling.
Composition: landscape 3:2, balanced at small size; lighthouse on one side, cottage on the other, sea between them. A complete scenic illustration framed only by gently feathered watercolour edges with a genuinely transparent background outside the painted vignette. No lettering, numbers, logos, interface elements or watermark. High resolution.
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 MiB

@@ -0,0 +1,5 @@
Use case: illustration-story. Asset: tappable notebook-cover illustration on the home screen of Lumen.
A single CLOSED keepsake notebook belonging to Mara, an elderly lighthouse keeper. Flat overhead view, landscape 3:2 composition. Faded sea-blue linen cover, carefully mended corners, a subtle stitched spine along the left edge, a slim rust-red ribbon peeking from the lower right, and a small pressed heather sprig secured with yellowed translucent tape near the outer right margin.
In the middle of the cover is ONE PLAIN BLANK ivory paper label, slightly crooked, occupying approximately x=24% to 78% and y=30% to 70% of the notebook. Keep that label clean and empty: native handwritten text will be overlaid in the app. No readable text, letters or numbers anywhere.
Style: hand-painted storybook watercolour with fine pencil observations, realistic cloth and old paper textures, warm cream, muted sea blue, faded lavender and soft rust. Treasured and repaired, not heavily damaged. Soft cottage-window illumination; very subtle grounding shadow only.
The whole notebook must be visible, centred, filling about 90% of the canvas. Genuinely transparent background outside the isolated notebook; no table or surrounding scene, no frame or watermark. High resolution.
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 MiB

@@ -0,0 +1 @@
Use case: illustration-story. Asset: a small illustration printed inside an elderly lighthouse keeper's diary. Delicate watercolour and fine graphite pencil, muted sea blue, warm ivory, faded rust and amber accents. Intimate northern European island storybook mood. Isolated vignette with genuinely transparent background, soft irregular fading pigment edges, no enclosing box or frame, no letters, no readable text, no watermark. The image should remain clear as a small illustration on warm paper. Subject: one old brass-and-blue storm lantern, with a little amber flame and signs of careful repair on its handle. Three-quarter view, fine hand-drawn details, affectionate observational sketch. Tall compact composition. No surrounding scene.
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 MiB

@@ -0,0 +1,9 @@
Use case: illustration-story
Asset type: Android game background asset, for review before integration.
Primary request: Create a game background showing an open keepsake notebook belonging to Mara, an elderly lighthouse keeper on a small northern European island. It should feel like a treasured family object used for decades.
Materials and details: Warm ivory paper with subtle fibres, gently worn edges, faint ruling, a stitched binding, and a faded blue linen cover visible around the edges. Include a pressed sprig of heather held with yellowed translucent tape, a rust-red ribbon bookmark, and a small pencil sketch of a coastal lighthouse in one corner. Add a few restrained water stains and signs of careful repair.
Mood: Intimate, comforting, and quietly nostalgic: a grandmother leaving memories and gentle guidance for her grandchild.
Palette: Muted sea blue, warm cream, faded lavender, soft graphite, and small amber accents.
Style: Hand-painted storybook illustration with delicate watercolour washes and pencil details, viewed straight down under soft cottage-window light.
Composition: Portrait 2:3, flat overhead view, notebook filling the frame. Keep the central 70% of the paper mostly blank and light enough for dark game text and a puzzle grid. Place decorative details near the margins.
Constraints: No readable text, letters, numbers, interface controls, or watermarks. Avoid glossy surfaces, strong shadows, exaggerated distressing, and cartoon styling. High resolution. Opaque background.
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 MiB

@@ -0,0 +1,9 @@
Use case: illustration-story
Asset type: portrait 2:3 background for a playable Android diary page.
Primary request: A SINGLE large, flat right-hand page from Mara's treasured keepsake diary, belonging to an elderly lighthouse keeper on a small northern European island. One uninterrupted sheet of warm ivory paper fills almost the entire frame. View straight down, completely flat, without perspective.
Composition requirement: ONLY ONE WRITING PAGE. The stitched book binding is along the extreme LEFT EDGE. A very narrow sliver of faded sea-blue linen cover may show outside the page. No second page, no open two-page spread, no centre gutter, no centre fold, no seam through the writing area. The writing page must occupy at least 90% of the image width and 94% of the image height.
Practical layout: The central 80% of the canvas is EMPTY, clean, pale ivory paper for game menus, dark handwriting and a large square puzzle grid. Keep the paper brightness and texture uniform through the entire writing area. No cards, panels, frames, placeholders, letters, numbers or text in this area. No visible ruling through the main area; only extremely subtle paper fibres.
Decoration: A tiny, delicate pencil-and-watercolour lighthouse sketch in the far top-right corner, occupying no more than 9% of the image width and 7% of its height. A small pressed sprig of faded lavender heather, held with a little yellowed translucent tape, along the extreme bottom-right margin. A slim rust-red ribbon peeking along the outside right edge. Small signs of careful repair and gentle wear only along the extreme corners. Decorations must never reach into the central writing area.
Style: Hand-painted storybook illustration with delicate watercolour washes and pencil details, intimate and comforting, the diary of a grandmother leaving memories for her grandchild. Muted sea blue, warm cream, faded lavender, soft graphite and tiny amber accents. Soft cottage-window light with very faint edge shadows only.
Avoid: two-page books, central creases, large flowers, large lighthouse illustrations, diagonal ribbons across the page, dark stains, heavy damage, strong shadows, glossy surfaces, cartoon styling, readable text, letters, numbers, watermarks and interface controls.
High-resolution portrait 2:3 opaque image.
+29
View File
@@ -0,0 +1,29 @@
# Bundled diary readings
Five fixed readings accompany the opening notebook leaves. They are **synthetic narration rendered during development**, using Kokoro v1.0 / `bf_emma` (British female), not human voice-actor recordings. The app only plays files using Android MediaPlayer. It contains no speech model, Android reader integration, runtime synthesis, or audio download.
- `scripts.json`: exact current non-puzzle text exported from `StoryBook.java`.
- `wav/`: reviewable 24 kHz mono PCM16 WAV masters.
- `manifest.json`: model/voice checksums, generator versions, exact scripts, passage timings and FLAC checksums.
- `app/src/main/res/raw/narration_*.flac`: lossless bundled copies. FLAC compression is disabled in APK packaging so MediaPlayer can open resource file descriptors.
- `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.
## Regeneration
Generator: [kokoro-onnx](https://github.com/thewh1teagle/kokoro-onnx). Model and voice data: `kokoro-v1.0.onnx` and `voices-v1.0.bin` from its [model-files-v1.0 release](https://github.com/thewh1teagle/kokoro-onnx/releases/tag/model-files-v1.0). See the upstream [voice guide](https://huggingface.co/hexgrad/Kokoro-82M/blob/main/VOICES.md).
Use Python 3.12, dependencies pinned in `requirements.txt`, ffmpeg and a JDK. Keep model data outside the Android project. Export updated scripts before regenerating:
```sh
mkdir -p /tmp/lumen-narration-export
javac -d /tmp/lumen-narration-export app/src/main/java/com/lumen/daily/StoryBook.java scripts/ExportNarration.java
java -cp /tmp/lumen-narration-export com.lumen.daily.ExportNarration > assets/narration/scripts.json
python scripts/render_narration.py --model /path/to/kokoro-v1.0.onnx --voices /path/to/voices-v1.0.bin
python3 scripts/check_narration_assets.py
```
The check requires only Python’s standard library, a JDK and ffmpeg. It verifies script freshness, cue coverage, master format, checksums and bit-identical WAV/FLAC decoding. It also rejects Android 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.
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 github.com/thewh1teagle
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+156
View File
@@ -0,0 +1,156 @@
{
"voice": "bf_emma",
"speed": 0.82,
"language": "en-gb",
"method": "Synthetic narration rendered during development; bundled file playback only.",
"modelSha256": "7d5df8ecf7d4b1878015a32686053fd0eebe2bc377234608764cc0ef3636a6c5",
"voicesSha256": "bca610b8308e8d99f32e6fe4197e7ec01679264efed0cac9140fe9c29f1fbf7d",
"packages": {
"kokoro-onnx": "0.6.1",
"onnxruntime": "1.31.1",
"soundfile": "0.14.0",
"espeakng-loader": "0.2.4"
},
"tracks": {
"cottage.dedication": {
"pageId": "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",
"file": "narration_cottage_dedication.flac",
"sampleRate": 24000,
"channels": 1,
"frames": 441184,
"durationMs": 18383,
"textSha256": "7ecbea473a70ab48a49861535bf30a3909005ce5735dcd048bc6abe576b1e017",
"flacSha256": "7606f2ea97386ed864155438d2785f6d8e6593fc04d785d432dfceb07bff52b7",
"cues": [
{
"startMs": 180,
"endMs": 9268,
"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."
},
{
"startMs": 9868,
"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"
}
]
},
"cottage.window": {
"pageId": "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.",
"file": "narration_cottage_window.flac",
"sampleRate": 24000,
"channels": 1,
"frames": 499104,
"durationMs": 20796,
"textSha256": "10b04750290618c667a1ab3e92247d59ea6796ac33c910906b292b6735da204c",
"flacSha256": "01864da94337c06445b60694faf2484c4a59f5f11fabc0f8d8b87a620ee09193",
"cues": [
{
"startMs": 180,
"endMs": 6473,
"text": "The wind has finally gone quiet. I have put the blue cup by the window, where you always liked to sit."
},
{
"startMs": 7073,
"endMs": 15009,
"text": "The latch still sticks. Lift it a little before you turn it. Some things on this island need a gentle hand, not a stronger one."
},
{
"startMs": 15609,
"endMs": 20196,
"text": "If you arrive after dark, there is something in the little drawer beside the hearth."
}
]
},
"cottage.match.memory": {
"pageId": "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.",
"file": "narration_cottage_match_memory.flac",
"sampleRate": 24000,
"channels": 1,
"frames": 506848,
"durationMs": 21119,
"textSha256": "b047af77227d4084883babe2d7bec9cbebf8a3d807cf8d45b72e76f72db9eac5",
"flacSha256": "6cd5fadf22ce6f8ebc6a9c8968e87fb1b31a0f1e52693c7e942d8498691a533c",
"cues": [
{
"startMs": 180,
"endMs": 6644,
"text": "You used to insist on lighting the evening lantern yourself. I held the matchbox, and you held your breath."
},
{
"startMs": 7244,
"endMs": 11212,
"text": "Once, you asked how such a little flame could help anyone out at sea."
},
{
"startMs": 11812,
"endMs": 15801,
"text": "It cannot, I told you. But it can help us find the next light."
},
{
"startMs": 16401,
"endMs": 20519,
"text": "I kept one dry match in a tin after that. Just in case."
}
]
},
"cottage.folded.note": {
"pageId": "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",
"file": "narration_cottage_folded_note.flac",
"sampleRate": 24000,
"channels": 1,
"frames": 425888,
"durationMs": 17745,
"textSha256": "2101efa580ab39cff6956a3e0011d5399e820aca79f9f60a25848487c6bcb9ad",
"flacSha256": "3675b260102c1b157e8741ff6ed9d062735860d33a15d1bbe397d997e91a2403",
"cues": [
{
"startMs": 180,
"endMs": 6964,
"text": "If the tide has covered the causeway, use the little boat by the harbour steps. The knot looks worse than it is."
},
{
"startMs": 7564,
"endMs": 12108,
"text": "Take the lantern. When you reach the bell, ring twice. I will know it is you."
},
{
"startMs": 12708,
"endMs": 17145,
"text": "And do not let the tea go cold while you are deciding.\n\nLove, Gran"
}
]
},
"cottage.lantern.sketch": {
"pageId": "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.",
"file": "narration_cottage_lantern_sketch.flac",
"sampleRate": 24000,
"channels": 1,
"frames": 366944,
"durationMs": 15289,
"textSha256": "fbfc663172995a1beb20b48e65b8f469b44b7bf26609721fe34b158ecc9bdf97",
"flacSha256": "60a823473a66b1ea4c5156889f66fe276bc103db475a3e6c831cd41649d7cbd3",
"cues": [
{
"startMs": 180,
"endMs": 8735,
"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."
},
{
"startMs": 9335,
"endMs": 14689,
"text": "People notice the flame first. I tend to notice the things that let us carry it."
}
]
}
}
}
+5
View File
@@ -0,0 +1,5 @@
kokoro-onnx==0.6.1
onnxruntime==1.31.1
soundfile==0.14.0
espeakng-loader==0.2.4
numpy==2.5.4
+1
View File
@@ -0,0 +1 @@
[{"pageId":"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"},{"pageId":"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."},{"pageId":"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."},{"pageId":"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"},{"pageId":"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."}]
Binary file not shown.
+1
View File
@@ -0,0 +1 @@
plugins { id 'com.android.application' version '8.13.2' apply false }
+2
View File
@@ -0,0 +1,2 @@
android.useAndroidX=true
org.gradle.jvmargs=-Xmx2048m
Binary file not shown.
+5
View File
@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.3-bin.zip
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
Vendored Executable
+248
View File
@@ -0,0 +1,248 @@
#!/bin/sh
#
# Copyright © 2015 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
+5
View File
@@ -0,0 +1,5 @@
package com.lumen.daily;
public class ExportNarration {
static String quote(String value){return "\""+value.replace("\\","\\\\").replace("\"","\\\"").replace("\n","\\n").replace("\r","\\r")+"\"";}
public static void main(String[] args){System.out.print("[");boolean first=true;for(StoryBook.Page p:StoryBook.PAGES){if(p.kind==StoryBook.Kind.PUZZLE)continue;if(!first)System.out.print(",");first=false;System.out.print("{\"pageId\":"+quote(p.id)+",\"resource\":"+quote("narration_"+p.id.replace('.','_'))+",\"text\":"+quote(p.text)+"}");}System.out.println("]");}
}
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env python3
"""Verify every bundled recording matches the current diary text and its WAV master."""
import array, hashlib, json, math, subprocess, tempfile, wave
from pathlib import Path
root=Path(__file__).resolve().parents[1]
source=root/'assets/narration';raw=root/'app/src/main/res/raw'
with tempfile.TemporaryDirectory(prefix='lumen-audio-text-') as temp:
subprocess.run(['javac','-d',temp,str(root/'app/src/main/java/com/lumen/daily/StoryBook.java'),str(root/'scripts/ExportNarration.java')],check=True)
canonical=json.loads(subprocess.check_output(['java','-cp',temp,'com.lumen.daily.ExportNarration']))
assert canonical==json.loads((source/'scripts.json').read_text()),'Regenerate the script export after editing diary text'
manifest=json.loads((source/'manifest.json').read_text());runtime=json.loads((raw/'narration_manifest.json').read_text())
assert runtime['tracks']==manifest['tracks']
assert len(canonical)==5==len(manifest['tracks'])
for record in canonical:
track=manifest['tracks'][record['pageId']]
assert track['text']==record['text']
assert track['textSha256']==hashlib.sha256(record['text'].encode()).hexdigest()
assert track['resource']==record['resource']
assert '\n\n'.join(cue['text'] for cue in track['cues'])==record['text']
previous=0
for cue in track['cues']:
assert previous<=cue['startMs']<cue['endMs']<=track['durationMs']
previous=cue['endMs']
wav=source/'wav'/(record['resource']+'.wav');flac=raw/track['file']
with wave.open(str(wav),'rb') as reader:
assert reader.getnchannels()==1 and reader.getsampwidth()==2 and reader.getframerate()==24000
assert reader.getnframes()==track['frames']
master=reader.readframes(reader.getnframes())
samples=array.array('h',master);peak=max(abs(v) for v in samples)
assert 1000<peak<32767,'Silent or clipped audio'
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 track['flacSha256']==hashlib.sha256(flac.read_bytes()).hexdigest()
print(f"PASS {record['pageId']}: {track['durationMs']/1000:.1f}s, lossless, text/cues match")
for p in (root/'app/src/main/java').rglob('*.java'):
assert 'android.speech.tts' not in p.read_text(),f'Android reader reintroduced in {p}'
assert 'TTS_SERVICE' not in (root/'app/src/main/AndroidManifest.xml').read_text()
print('All five recordings verified; no Android text-to-speech dependency.')
+160
View File
@@ -0,0 +1,160 @@
#!/usr/bin/env python3
"""Destructive test fixtures are restricted to the disposable .qa app, never the main app."""
import argparse
from pathlib import Path
import re
import subprocess
import time
import xml.etree.ElementTree as ET
parser=argparse.ArgumentParser()
parser.add_argument('--adb',default='/home/ubuntu/Android/Sdk/platform-tools/adb')
parser.add_argument('--serial',required=True)
parser.add_argument('--package',default='com.lumen.daily.qa')
parser.add_argument('--output',default='artifacts/storybook-check')
args=parser.parse_args()
assert re.fullmatch(r'[a-zA-Z0-9_.]+\.qa',args.package),'Only a disposable .qa app may be tested'
PKG=args.package
BASE=[args.adb,'-s',args.serial]
OUT=Path(args.output);OUT.mkdir(parents=True,exist_ok=True)
def adb(*cmd,stdin=None):
result=subprocess.run(BASE+list(cmd),input=stdin,capture_output=True,check=True)
return result.stdout
def tap_node(node):
b=list(map(int,re.findall(r'\d+',node.get('bounds'))))
adb('shell','input','tap',str((b[0]+b[2])//2),str((b[1]+b[3])//2))
def dump():
adb('shell','uiautomator','dump','/sdcard/lumen-story-test.xml')
tree=ET.fromstring(adb('exec-out','cat','/sdcard/lumen-story-test.xml'))
for n in tree.iter('node'):
if n.get('text')=='Do not consent':
tap_node(n)
return dump()
return tree
def find(text,scroll=False,exact=False):
for attempt in range(12 if scroll else 1):
tree=dump()
for n in tree.iter('node'):
value=n.get('text','')
if value.casefold()==text.casefold() if exact else text.casefold() in value.casefold():
return n
if scroll:adb('shell','input','swipe','600','1400','600','700','250')
raise AssertionError('Missing '+text+'; visible '+str([n.get('text') for n in tree.iter('node') if n.get('text')]))
def tap(text,scroll=False,exact=False):
tap_node(find(text,scroll,exact))
dump()
def shot(name):(OUT/name).write_bytes(adb('exec-out','screencap','-p'))
def launch():adb('shell','am','start','-n',PKG+'/com.lumen.daily.MainActivity')
def prefs():return ET.fromstring(adb('shell','run-as',PKG,'cat','shared_prefs/lumen.xml'))
def pref(name):
for n in prefs():
if n.get('name')==name:return n.get('value',n.text)
return None
def replace_prefs(changes):
adb('shell','am','force-stop',PKG)
root=prefs()
for key,(kind,value) in changes.items():
for n in list(root):
if n.get('name')==key:root.remove(n)
n=ET.SubElement(root,kind,{'name':key})
if kind=='string':n.text=value
else:n.set('value',value)
xml=ET.tostring(root,encoding='utf-8',xml_declaration=True)
adb('shell',f"run-as {PKG} sh -c 'cat > shared_prefs/lumen.xml'",stdin=xml)
def setting(name):return adb('shell','settings','get','system',name).decode().strip()
def page(expected):assert pref('notebook_last_page')==expected,(expected,pref('notebook_last_page'))
def cell_node(row,col):
for n in dump().iter('node'):
if n.get('content-desc','').startswith(f'Row {row}, column {col},'):return n
raise AssertionError('Missing accessible grid cell')
rotation=setting('user_rotation');auto=setting('accelerometer_rotation')
results=[]
try:
launch();dump()
# Reset only this disposable app's game data; keep its independent UMP choice.
replace_prefs({'notebook_open':('boolean','false'),'notebook_last_page':('string','cottage.dedication'),'solved':('int','0'),
'done_story_v1_0':('boolean','false'),'grid_story_v1_0':('string','0'*49),
'notebook_note_open':('boolean','false'),'notebook_handle_seen':('boolean','false')})
launch();dump();shot('00-home.png');tap('Open Mara’s notebook',scroll=True);dump()
if pref('notebook_open')!='true':
tap('Open Mara’s notebook',scroll=True);dump()
find('For you, when you are ready');page('cottage.dedication');shot('01-dedication.png')
# Swipe from outside the writing area; grid/body drags must not share this gesture.
adb('shell','input','swipe','1120','650','650','650','350')
find('By the cottage window');page('cottage.window');shot('02-cottage-entry.png')
results.append('PASS: edge swipe opens the next illustrated leaf')
print(results[-1],flush=True)
# Exercise the bundled FLAC recording; no device reader or voice download is used.
# UIAutomator waits for idle; continuously updating playback clocks can outlast
# a short recording. Toggle by the known button bounds, then inspect while paused.
play=find('Play this reading',scroll=True)
tap_node(play);time.sleep(2);shot('02-recording-playing.png');tap_node(play)
find('Resume recording')
paused_text=next(n.get('text') for n in dump().iter('node') if n.get('text','').startswith('Paused · '))
def elapsed(value):
minute,second=map(int,re.search(r'(\d+):(\d+)',value).groups());return minute*60+second
first=elapsed(paused_text)
assert 1<=first<8,paused_text
tap_node(play);time.sleep(2);tap_node(play)
find('Resume recording')
resumed_text=next(n.get('text') for n in dump().iter('node') if n.get('text','').startswith('Paused · '))
second=elapsed(resumed_text)
assert first+1<=second<=first+4,(paused_text,resumed_text)
tap('Stop',exact=True);find('Play this reading')
results.append('PASS: bundled recording play, pause, exact-position resume and stop')
print(results[-1],flush=True)
tap('Speed',scroll=True,exact=True);tap('Unhurried');dump();assert pref('recording_speed') is not None
tap('Next leaf');find('A spark in the drawer');page('cottage.match.puzzle');shot('03-match-puzzle.png')
before=pref('grid_story_v1_0')
node=cell_node(1,1);bounds=list(map(int,re.findall(r'\d+',node.get('bounds'))))
x=(bounds[0]+bounds[2])//2;y=(bounds[1]+bounds[3])//2
adb('shell','input','swipe',str(x),str(y),str(x+100),str(y),'300')
dump();page('cottage.match.puzzle')
assert pref('grid_story_v1_0')!=before
tap('Undo a mark');dump();assert pref('grid_story_v1_0')==before
results.append('PASS: grid drag edits a cell without turning; undo restores it')
print(results[-1],flush=True)
tap('Next leaf');tap('Read ahead');find('One small light');page('cottage.match.memory')
assert pref('done_story_v1_0')=='false' and pref('solved')=='0'
shot('04-match-memory.png');tap('Next leaf');find('A note I nearly forgot');shot('05-folded-note.png')
tap('Unfold Gran’s note');find('For the crossing');assert pref('notebook_note_open')=='true';shot('05-open-note.png')
tap('Bookmark');dump();assert pref('notebook_manual_bookmark')=='cottage.folded.note'
tap('Next leaf');find('The handle, carefully mended');shot('06-lantern-sketch.png')
# Select the accessible illustration, not its caption.
image=next(n for n in dump().iter('node') if n.get('content-desc','').startswith('Watercolour of Mara'))
tap_node(image);find('A careful repair');tap('Keep that thought');dump();assert pref('notebook_handle_seen')=='true'
tap('Contents');tap('Return to my ribbon bookmark');find('For the crossing');page('cottage.folded.note')
adb('shell','am','force-stop',PKG);launch();find('For the crossing');page('cottage.folded.note')
assert pref('notebook_note_open')=='true' and pref('solved')=='0'
results.append('PASS: read-ahead does not award a puzzle; note, inspection and ribbon persist across process restart')
print(results[-1],flush=True)
# Near-solved fixture verifies completion routing and no double award on revisiting.
picture=['0011000','0111100','0011000','0001000','0001000','0001000','0001000']
solution=''.join('1' if c=='1' else '2' for row in picture for c in row)
replace_prefs({'notebook_last_page':('string','cottage.match.puzzle'),'notebook_open':('boolean','true'),
'grid_story_v1_0':('string','0'+solution[1:])})
launch();find('A spark in the drawer');node=cell_node(1,1)
tap_node(node);tap_node(node)
find('One small light');page('cottage.match.memory');assert pref('done_story_v1_0')=='true' and pref('solved')=='1'
tap('Previous leaf');find('Already restored');tap('Next leaf');find('One small light');assert pref('solved')=='1'
results.append('PASS: solving reveals the memory and increments once; replay preserves completion')
print(results[-1],flush=True)
adb('shell','settings','put','system','accelerometer_rotation','0')
adb('shell','settings','put','system','user_rotation','1')
find('One small light');shot('07-landscape.png');page('cottage.match.memory')
results.append('PASS: orientation change restores the same leaf')
finally:
for name,value in [('user_rotation',rotation),('accelerometer_rotation',auto)]:
if value=='null':adb('shell','settings','delete','system',name)
else:adb('shell','settings','put','system',name,value)
dump()
(OUT/'results.txt').write_text('\n'.join(results)+'\n')
print('Story notebook checks completed; original rotation settings restored.',flush=True)
+61
View File
@@ -0,0 +1,61 @@
#!/usr/bin/env python3
"""Prepare immutable WAV masters and bundled FLACs; Android performs no speech synthesis."""
import argparse, hashlib, importlib.metadata, json, subprocess
from pathlib import Path
import numpy as np
import soundfile as sf
import onnxruntime as ort
import espeakng_loader
from kokoro_onnx import Kokoro
from kokoro_onnx.config import EspeakConfig
parser=argparse.ArgumentParser()
parser.add_argument('--model',type=Path,required=True)
parser.add_argument('--voices',type=Path,required=True)
parser.add_argument('--voice',default='bf_emma')
parser.add_argument('--speed',type=float,default=.82)
parser.add_argument('--root',type=Path,default=Path(__file__).resolve().parents[1])
a=parser.parse_args()
source=a.root/'assets/narration';raw=a.root/'app/src/main/res/raw'
(source/'wav').mkdir(parents=True,exist_ok=True);raw.mkdir(parents=True,exist_ok=True)
options=ort.SessionOptions();options.intra_op_num_threads=4;options.inter_op_num_threads=1
session=ort.InferenceSession(str(a.model),sess_options=options,providers=['CPUExecutionProvider'])
session.disable_fallback()
config=EspeakConfig(lib_path=str(espeakng_loader.get_library_path()),data_path=str(espeakng_loader.get_data_path()))
engine=Kokoro.from_session(session,str(a.voices),espeak_config=config)
tracks={}
for record in json.loads((source/'scripts.json').read_text()):
paragraphs=[]
for part in record['text'].split('\n\n'):
if paragraphs and len(part)<45:paragraphs[-1]+='\n\n'+part
elif paragraphs and len(paragraphs[-1])<45:paragraphs[-1]+='\n\n'+part
else:paragraphs.append(part)
rate=24000;pieces=[np.zeros(int(rate*.18),dtype=np.float32)];frames=len(pieces[0]);cues=[]
for part in paragraphs:
print(f"Rendering {record['pageId']} · {len(cues)+1}/{len(paragraphs)}",flush=True)
samples,sample_rate=engine.create(part.replace('\n',' '),voice=a.voice,speed=a.speed,lang='en-gb',sentence_pause=.38,clause_pause=.14)
assert sample_rate==rate
samples=np.asarray(samples,dtype=np.float32).reshape(-1)
assert len(samples)>rate*.3 and np.isfinite(samples).all()
fade=min(240,len(samples)//4)
samples[:fade]*=np.linspace(0,1,fade);samples[-fade:]*=np.linspace(1,0,fade)
start=frames;pieces.append(samples);frames+=len(samples)
cues.append({'startMs':round(start*1000/rate),'endMs':round(frames*1000/rate),'text':part})
pause=np.zeros(int(rate*.60),dtype=np.float32);pieces.append(pause);frames+=len(pause)
audio=np.concatenate(pieces);peak=float(np.max(np.abs(audio)));assert peak>.01
audio*=.86/peak
wav=source/'wav'/f"{record['resource']}.wav";flac=raw/f"{record['resource']}.flac"
sf.write(wav,audio,rate,subtype='PCM_16')
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')
assert check_rate==rate and np.array_equal(decoded,master)
tracks[record['pageId']]={**record,'file':flac.name,'sampleRate':rate,'channels':1,'frames':len(audio),
'durationMs':round(len(audio)*1000/rate),'textSha256':hashlib.sha256(record['text'].encode()).hexdigest(),
'flacSha256':hashlib.sha256(flac.read_bytes()).hexdigest(),'cues':cues}
print(f"Saved {wav.name}: {len(audio)/rate:.1f}s; lossless FLAC verified",flush=True)
manifest={'voice':a.voice,'speed':a.speed,'language':'en-gb','method':'Synthetic narration rendered during development; bundled file playback only.',
'modelSha256':hashlib.sha256(a.model.read_bytes()).hexdigest(),'voicesSha256':hashlib.sha256(a.voices.read_bytes()).hexdigest(),
'packages':{p:importlib.metadata.version(p) for p in ['kokoro-onnx','onnxruntime','soundfile','espeakng-loader']},'tracks':tracks}
(source/'manifest.json').write_text(json.dumps(manifest,ensure_ascii=False,indent=2)+'\n')
(raw/'narration_manifest.json').write_text(json.dumps({'tracks':tracks},ensure_ascii=False,indent=2)+'\n')
print('All five narration masters and runtime FLACs prepared.',flush=True)
+4
View File
@@ -0,0 +1,4 @@
pluginManagement { repositories { google(); mavenCentral(); gradlePluginPortal() } }
dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS); repositories { google(); mavenCentral() } }
rootProject.name = 'Lumen'
include ':app'