import 'services/browser_assets.dart'; import 'dart:async'; import 'dart:math' as math; import 'package:flutter/material.dart'; import 'ui/translation.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:intl/intl.dart'; import 'package:intl/date_symbol_data_local.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'domain/library.dart'; import 'services/translation.dart'; import 'domain/book.dart'; import 'domain/game.dart'; import 'domain/puzzle.dart'; import 'domain/postcards.dart'; import 'services/ad_pacing.dart'; import 'services/play_metrics.dart'; import 'ui/postcards.dart'; import 'services/ads.dart'; import 'services/ambience.dart'; import 'services/narrator.dart'; import 'services/progress.dart'; import 'ui/board.dart'; import 'ui/library.dart'; import 'ui/discovery.dart'; import 'ui/paper.dart'; part 'ui/mara_story.dart'; Future main() async { WidgetsFlutterBinding.ensureInitialized(); LicenseRegistry.addLicense(() async* { yield LicenseEntryWithLineBreaks([ 'Dancing Script', ], await rootBundle.loadString('assets/fonts/OFL.txt')); }); LicenseRegistry.addLicense(() async* { yield LicenseEntryWithLineBreaks([ 'Noto Sans', 'Noto Sans Symbols', 'Noto Sans Symbols 2', 'Noto Sans Math', ], await rootBundle.loadString('assets/fonts/NOTO-LICENSE.txt')); }); SystemChrome.setSystemUIOverlayStyle( const SystemUiOverlayStyle( statusBarColor: cream, statusBarIconBrightness: Brightness.dark, systemNavigationBarColor: Color(0xff314345), ), ); await initializeDateFormatting(); final library = await StoryLibrary.load(), progress = await Progress.load(); final deviceLanguage = WidgetsBinding.instance.platformDispatcher.locale .toLanguageTag(); final preference = progress.text('language', 'system'); final book = await library.open( progress.text('selected_story', 'mara-island'), language: preference == 'system' ? deviceLanguage : preference, ); final game = Game(book, progress, library: library) ..deviceLanguage = deviceLanguage; await game.restore(); // The shelf is the first window. `restore()` has already positioned each // book's saved leaf, so choosing a book resumes exactly where it was left. game.showLibrary(); runApp(LumenApp(game: game)); } class LumenApp extends StatefulWidget { const LumenApp({super.key, required this.game, this.adsEnabled = true}); final Game game; final bool adsEnabled; @override State createState() => _LumenAppState(); } class _LumenAppState extends State { Game get game => widget.game; late Book _book; late String _language; @override void initState() { super.initState(); _book = game.book; _language = game.requestedLanguage; game.addListener(_configurationChanged); } void _configurationChanged() { // Puzzle marks and navigation are already handled by Notebook. Rebuilding // MaterialApp and its theme for each cell press needlessly rebuilds the app. if (identical(_book, game.book) && _language == game.requestedLanguage) { return; } setState(() { _book = game.book; _language = game.requestedLanguage; }); } @override void didUpdateWidget(LumenApp oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.game != game) { oldWidget.game.removeListener(_configurationChanged); game.addListener(_configurationChanged); } _book = game.book; _language = game.requestedLanguage; } @override void dispose() { game.removeListener(_configurationChanged); super.dispose(); } @override Widget build(BuildContext context) { final catalog = game.library?.copy ?? TranslationCatalog.english; final language = game.requestedLanguage.replaceAll('_', '-'); final locale = localeFromTag(language); final parts = language.split('-'); final languages = { ...catalog.languages.keys, ...?game.library?.stories.expand((s) => s.languages.keys), }; final latin = const [ 'en', 'de', 'fr', 'es', 'it', 'pt', 'nl', 'da', 'sv', 'no', 'fi', ].contains(parts.first); return MaterialApp( title: 'Lumen', debugShowCheckedModeBanner: false, locale: locale, supportedLocales: languages.map(localeFromTag).toList(), localizationsDelegates: GlobalMaterialLocalizations.delegates, builder: (context, child) => CopyScope( catalog: catalog, language: language, overrides: game.book.copy, child: child!, ), theme: ThemeData( fontFamilyFallback: kIsWeb ? const ['LumenText', 'LumenSymbols', 'LumenSymbols2', 'LumenMath'] : null, colorScheme: ColorScheme.fromSeed(seedColor: blue, surface: cream), scaffoldBackgroundColor: cream, fontFamily: latin ? 'MaraHand' : null, textTheme: ThemeData.light().textTheme.apply( fontFamily: latin ? 'MaraHand' : null, bodyColor: ink, displayColor: ink, ), dialogTheme: const DialogThemeData(backgroundColor: cream), textButtonTheme: TextButtonThemeData( style: TextButton.styleFrom( textStyle: hand(22), foregroundColor: blue, ), ), ), home: Notebook(game: game, adsEnabled: widget.adsEnabled), ); } } class Notebook extends StatefulWidget { const Notebook({ super.key, required this.game, required this.adsEnabled, this.narrator, this.ambience, this.ads, }); final Game game; final bool adsEnabled; final Narrator? narrator; final Ambience? ambience; final Ads? ads; @override State createState() => _NotebookState(); } class _NotebookState extends State with WidgetsBindingObserver { Game get g => widget.game; Progress get prefs => g.progress; late final Narrator narrator; late final Narrator postcardNarrator; late final Ambience ambience; late final Ads ads; late final PlayMetrics metrics; bool _foreground = true; String _route = ''; Future>? _shelf; String _shelfLanguage = ''; String get route => '${g.book.id}:${g.book.language}:${g.screen.name}:${g.screen == Screen.story ? g.storyIndex : g.campaignIndex}'; @override void initState() { super.initState(); unawaited(initializeDateFormatting()); narrator = widget.narrator ?? Narrator(g.book.tracks); postcardNarrator = Narrator({ for (final card in islandPostcards) card.id: {'asset': 'assets/postcards/audio/${card.id}.wav'}, }); ambience = widget.ambience ?? Ambience(); narrator.addListener(_syncAtmosphere); metrics = PlayMetrics(g.store)..visit(); ads = widget.ads ?? Ads( enabled: widget.adsEnabled, pacing: AdPacing(g.store), metrics: metrics, ); g.addListener(_changed); _route = route; WidgetsBinding.instance.addObserver(this); WidgetsBinding.instance.addPostFrameCallback((_) { unawaited(ads.start()); _syncAtmosphere(); if (mounted) _scheduleAutoplay(); }); } void _changed() { if (!identical(narrator.tracks, g.book.tracks)) { narrator.replaceTracks(g.book.tracks); } if (_route != route) { _route = route; unawaited(narrator.stop()); unawaited(postcardNarrator.stop()); _scheduleAutoplay(); } _syncAtmosphere(); if (mounted) setState(() {}); } bool get atmosphereEnabled => !prefs.contains('ambience_enabled') || prefs.flag('ambience_enabled'); void _scheduleAutoplay() { final recordedPage = _foreground && [Screen.story, Screen.briefing, Screen.reveal].contains(g.screen) && !(g.screen == Screen.story && g.book.isMara && g.storyPage.type == StoryPageType.note && !prefs.flag('notebook_note_open')); narrator.scheduleAutoplay( recordedPage ? recordingId : null, prefs.decimal('recording_speed'), ); } void _syncAtmosphere() { final inStory = g.mode == Mode.campaign && [ Screen.story, Screen.briefing, Screen.game, Screen.reveal, ].contains(g.screen); ambience.update( scene: !inStory ? null : g.book.isMara ? soundscapeFor(g.campaignIndex) : g.screen == Screen.story ? g.book.atmosphere[g.storyPage.id] : null, enabled: atmosphereEnabled, foreground: _foreground, narrating: narrator.playing || narrator.loading, volume: prefs.decimal('ambience_volume', .7), ); } @override void didChangeLocales(List? locales) { g.deviceLanguage = locales?.firstOrNull?.toLanguageTag() ?? 'en'; if (g.languagePreference == 'system') { unawaited( g.selectLanguage('system').catchError((Object _) { if (mounted) { toast('This language could not be opened. Please try again.'); } }), ); } } @override void didChangeAppLifecycleState(AppLifecycleState state) { _foreground = state == AppLifecycleState.resumed; ads.foreground = _foreground; if (_foreground) metrics.visit(); _syncAtmosphere(); if (state != AppLifecycleState.resumed) { metrics.endVisit(); unawaited(narrator.stop()); unawaited(postcardNarrator.stop()); unawaited(prefs.flushed); } } @override void dispose() { WidgetsBinding.instance.removeObserver(this); g.removeListener(_changed); narrator.removeListener(_syncAtmosphere); ambience.dispose(); narrator.dispose(); postcardNarrator.dispose(); ads.dispose(); super.dispose(); } void toast(String text) { if (mounted) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: CopyText(text, style: hand(20, color: cream)), ), ); } } Future confirm( String title, String text, String yes, { String no = 'Keep reading', }) async => await showDialog( context: context, builder: (c) => AlertDialog( title: CopyText(title, style: hand(29)), content: CopyText(text, style: hand(23)), actions: [ TextButton( onPressed: () => Navigator.pop(c, false), child: CopyText(no), ), TextButton( onPressed: () => Navigator.pop(c, true), child: CopyText(yes), ), ], ), ) ?? false; Future message( String title, String text, { String close = 'Keep going', }) async { await showDialog( context: context, builder: (c) => AlertDialog( title: CopyText(title, style: hand(29)), content: SingleChildScrollView(child: CopyText(text, style: hand(23))), actions: [ TextButton(onPressed: () => Navigator.pop(c), child: CopyText(close)), ], ), ); } Future turn(int direction) async { if (direction > 0 && g.storyIndex == g.book.pages.length - 1) { readingBreak(g.book.pages.length, crossToHarbour); return; } final next = (g.storyIndex + direction).clamp(0, g.book.pages.length - 1); if (next == g.storyIndex) return; final pageId = g.storyPage.id; if (g.storyPage.type == StoryPageType.puzzle && direction > 0 && !g.won) { unawaited(narrator.stop()); if (!await confirm( 'Leave a ribbon here?', 'Your puzzle marks are saved. You can read the memory now and come back to solve the pattern whenever you like.', 'Read ahead', no: 'Keep solving', )) { return; } await prefs.set('notebook_read_ahead', true); } if (mounted && g.storyPage.id == pageId) { if (direction > 0) { readingBreak(next, () => g.showStory(next)); } else { g.showStory(next); } } } void readingBreak(int position, VoidCallback next) { final book = g.book; final legacyLevels = book.continueAt == null ? 0 : book.levels.length - book.continueAt!; final total = book.pages.length + legacyLevels * 3; if (g.claimBookAd(position, total)) { unawaited(narrator.stop()); ads.between(() { if (mounted && g.book == book) next(); }); } else { next(); } } void crossToHarbour() { g.leaveCottage(); } Future turnCampaign(int direction) async { final index = g.campaignIndex; switch (g.screen) { case Screen.briefing: if (direction > 0) { g.startCampaign(index); } else if (index > 0) { if (index == g.book.continueAt) { g.showStory(g.book.pages.length - 1); } else { g.reveal(index - 1, readAhead: true); } } else { g.contents(); } case Screen.game: if (direction < 0) { g.briefing(index); return; } if (!g.won && !await confirm( 'Leave a ribbon here?', 'Your puzzle marks are saved. You can read the memory now and return to this pattern whenever you like.', 'Read ahead', no: 'Keep solving', )) { return; } if (mounted) g.reveal(index, readAhead: true); case Screen.reveal: if (direction < 0) { g.startCampaign(index); } else { nextCampaign(); } default: break; } } void nextCampaign() { final index = g.campaignIndex; if (index == g.book.levels.length - 1) { readingBreak( g.book.pages.length + (index - (g.book.continueAt ?? 0) + 1) * 3, g.contents, ); return; } // Reading access is distinct from completed puzzles and their awards. unawaited( prefs.set('story_access_level', math.max(g.accessible, index + 1)), ); void next() { if (mounted) g.briefing(index + 1); } readingBreak( g.book.pages.length + (index - (g.book.continueAt ?? 0) + 1) * 3, next, ); } void back() { if (g.screen == Screen.postcards) { g.library == null ? g.home() : g.showLibrary(); return; } if (g.screen == Screen.game && g.mode == Mode.postcard) { g.showPostcards(); return; } if (g.screen == Screen.game && g.mode != Mode.campaign && g.library != null) { g.showLibrary(); return; } if (g.busy) { g.home(); return; } if (g.screen == Screen.library) return; if (g.screen == Screen.home) { // With a catalogue the shelf is the app's root; without one (widget tests // and embedders) the book's home stays the first and last leaf. if (g.library != null) g.showLibrary(); return; } g.home(); } @override Widget build(BuildContext context) => PaperSkin( // Reading pages follow the selected book; the library draws its own surface. asset: g.screen == Screen.library ? null : g.book.paperAsset, child: PopScope( canPop: (g.screen == Screen.library || (g.screen == Screen.home && g.library == null)) && !g.busy, onPopInvokedWithResult: (didPop, result) { if (!didPop) back(); }, child: Scaffold( body: Stack( children: [ switch (g.screen) { Screen.library => libraryScreen(), Screen.home => home(), Screen.story => story(), Screen.contents => contents(), Screen.briefing => briefing(), Screen.game => game(), Screen.reveal => reveal(), Screen.postcards => PostcardCollectionView( game: g, onBack: back, onOpen: g.startPostcard, onRead: (index) => unawaited(readPostcard(index)), ), }, if (g.busy) Positioned.fill( child: ColoredBox( color: cream.withValues(alpha: .9), child: Center( child: Column( mainAxisSize: MainAxisSize.min, children: [ const CircularProgressIndicator(color: blue), writing('Finding a fresh pattern…'), InkButton('Back to the notebook', g.home), ], ), ), ), ), ], ), ), ), ); Widget column(List children) => Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: children, ); Widget action(String title, VoidCallback run, {bool primary = false}) => Padding( padding: const EdgeInsets.symmetric(vertical: 5), child: InkButton(title, run, primary: primary), ); Widget gap([double n = 16]) => SizedBox(height: n); Widget divider() => Padding( padding: const EdgeInsets.symmetric(vertical: 18), child: Row( children: [ Expanded(child: Divider(color: muted.withValues(alpha: .3))), Padding( padding: const EdgeInsets.symmetric(horizontal: 12), child: CopyText('❦', style: hand(27, color: muted)), ), Expanded(child: Divider(color: muted.withValues(alpha: .3))), ], ), ); Widget folio(String text) => writing(text, size: 15, color: blue); /// The app's first window: every installed book on one shelf. Tapping a card /// selects that story and lets `Game.restore()` reopen its saved leaf. Widget libraryScreen() { final catalogue = g.library; if (catalogue == null) { return Leaf( key: const ValueKey('library'), body: column([ folio('L U M E N / STORY LIBRARY'), writing('No stories are installed.', size: 24, color: muted), action('Back to the notebook', g.home), ]), ); } return LibraryShelf( key: const ValueKey('library'), onSettings: settings, activities: ShelfActivities(game: g, onPostcards: g.showPostcards), builder: (context, width) => FutureBuilder>( future: shelfBooks(catalogue), builder: (context, snapshot) { if (snapshot.hasError) { return column([ writing( 'This story could not be opened. Please try again.', size: 21, color: muted, ), action( 'Try again', () => setState(() { _shelf = null; _shelfLanguage = ''; }), ), ]); } final books = snapshot.data; if (books == null) { return const Padding( padding: EdgeInsets.symmetric(vertical: 40), child: Center(child: CircularProgressIndicator(color: blue)), ); } if (books.isEmpty) { return writing('No stories are installed.', size: 22, color: muted); } final columns = width >= 900 ? 3 : (width >= 560 ? 2 : 1); const spacing = 28.0; final cardWidth = (width - spacing * (columns - 1)) / columns; return Wrap( spacing: spacing, runSpacing: 36, children: [ for (final story in books) SizedBox(width: cardWidth, child: bookCard(story)), ], ); }, ), ); } /// Selection still restores the saved leaf independently for each story. Widget bookCard(Book story) { final catalogue = g.library; if (catalogue == null) return const SizedBox.shrink(); final store = g.store.forStory(story.id); final restored = [ for (var i = 0; i < story.levels.length; i++) store.flag('done_${story.puzzleKey(i)}'), ].where((done) => done).length; final saved = store.text('flutter_screen', 'home'); return LibraryBookCard( story: story, restored: restored, resuming: saved != Screen.home.name && saved != Screen.library.name, languages: catalogue .definition(story.id) .languages .values .map((entry) => entry['label'] as String? ?? '') .where((label) => label.isNotEmpty) .toList(), onOpen: () => unawaited(openStory(story.id)), ); } /// Loads the whole catalogue once per requested language. A broken package is /// skipped so the rest of the shelf stays usable. Future> shelfBooks(StoryLibrary catalogue) { final language = g.requestedLanguage; final cached = _shelf; if (cached != null && _shelfLanguage == language) return cached; _shelfLanguage = language; return _shelf = () async { final books = []; for (final story in catalogue.stories) { try { books.add(await catalogue.open(story.id, language: language)); } catch (_) { continue; } } return books; }(); } /// Waits for the shelf before switching screens, so the home button never /// flashes a loading state and its tap settles in one pump. Future openLibrary() async { narrator.cancelAutoplay(); final catalogue = g.library; if (catalogue == null) return; await shelfBooks(catalogue); if (mounted) g.showLibrary(); } Future openStory(String id) async { narrator.cancelAutoplay(); try { await g.selectStory(id); } catch (_) { if (mounted) toast('This story could not be opened. Please try again.'); } } Widget home() => ColoredBox( key: ValueKey('home-${g.book.id}'), color: cream, child: SafeArea( child: Column( children: [ Padding( padding: const EdgeInsets.fromLTRB(28, 34, 28, 8), child: Center( child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 650), child: SizedBox( width: double.infinity, child: folio( g.book.isMara ? 'L U M E N / AN ISLAND STORY' : 'L U M E N / STORY LIBRARY', ), ), ), ), ), Expanded( child: SingleChildScrollView( key: const ValueKey('home-scroll'), padding: const EdgeInsets.fromLTRB(28, 0, 28, 36), child: Center( child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 650), child: column([ writing( g.book.isMara ? 'A light to come\nhome to.' : g.book.title, size: 40, ), if (g.book.isMara) Image.asset( artworkAsset('assets/artwork/home-harbour-v2.png'), height: 220, fit: BoxFit.contain, semanticLabel: 'Watercolour of the island at dusk, with the lighthouse and Gran’s cottage.', ), writing( g.book.isMara ? 'Some things are worth keeping. — Gran' : g.book.description, size: 25, color: const Color(0xff70503b), ), if (g.book.isMara) Cover(onTap: g.openNotebook) else if (g.book.coverAsset case final asset?) InkWell( onTap: g.openNotebook, child: Image.asset( artworkAsset(asset), height: 220, semanticLabel: g.book.title, ), ), action( 'Open ${g.book.title} · ${g.recoveredCount} / ${g.book.levels.length}', g.openNotebook, primary: true, ), action('Story library', () => unawaited(openLibrary())), action('Settings', settings), if (g.requestedLanguage .replaceAll('_', '-') .split('-') .first != g.book.language.split('-').first) writing( 'This story is shown in its original language.', size: 18, color: muted, ), gap(), Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Expanded( child: CopyText( '${g.streak}\nDAY STREAK', textAlign: TextAlign.center, style: hand(18, color: blue), ), ), Expanded( child: CopyText( '${g.solved}\nPATTERNS FOUND', textAlign: TextAlign.center, style: hand(18, color: blue), ), ), ], ), divider(), folio('A SMALL DAILY RITUAL'), action('Island postcards', g.showPostcards), writing( DateFormat( 'EEEE, d MMMM', Localizations.localeOf(context).languageCode, ).format(DateTime.now()), size: 27, ), action( 'Play today’s puzzle →', () => g.startDaily(DateTime.now()), ), gap(), folio('BY THE COTTAGE WINDOW'), writing( 'A few spare pages for practice. For overlapping-area puzzles, follow the notebook’s story.', size: 22, color: muted, ), action( 'Difficulty · ${g.difficulty.label} ▾', chooseDifficulty, ), action( 'Practice · ${g.difficulty.label} · Level ${g.practiceLevel}', () => unawaited(g.startPractice()), ), action('How to play', rules), action( 'Open-source licenses', () => showLicensePage( context: context, applicationName: 'Lumen', ), ), gap(), writing( 'Leave a light in the window.', size: 26, color: const Color(0xff70503b), ), ]), ), ), ), ), ], ), ), ); Future settings() => showDialog( context: context, builder: (c) => SimpleDialog( title: const CopyText('Settings'), children: [ for (final option in <(String, VoidCallback)>[ ('Language', chooseLanguage), ('Sound & atmosphere', soundSettings), ('Recording speed', speed), ('Privacy & advertising', privacy), if (kDebugMode || appFlavor == 'qa' || appFlavor == 'check') ('Playtest report', playtestReport), ]) SimpleDialogOption( onPressed: () { Navigator.pop(c); option.$2(); }, child: CopyText(option.$1), ), ], ), ); Future playtestReport() => showDialog( context: context, builder: (c) => AlertDialog( title: const Text('Local playtest report'), content: SingleChildScrollView(child: SelectableText(metrics.export())), actions: [ TextButton( onPressed: () async { await Clipboard.setData(ClipboardData(text: metrics.export())); if (c.mounted) Navigator.pop(c); }, child: const Text('Copy report'), ), TextButton( onPressed: () => Navigator.pop(c), child: const Text('Close'), ), ], ), ); Future readPostcard(int index, {bool completedNow = false}) async { if (g.postcardSolved(index) != 3) return; final card = islandPostcards[index]; postcardNarrator.scheduleAutoplay( card.id, prefs.decimal('recording_speed'), ); final kept = await showDialog( context: context, builder: (c) => AlertDialog( backgroundColor: const Color(0xfffffbef), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(3), side: const BorderSide(color: Color(0xffc8b797)), ), title: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( children: [ const Expanded( child: Text( 'P O S T C A R D', style: TextStyle( fontFamily: 'sans-serif', fontSize: 13, letterSpacing: 2, ), ), ), Container( width: 48, height: 54, decoration: BoxDecoration( border: Border.all( color: const Color(0xffa78361), width: 2, ), color: const Color(0xffdbe7df), ), child: const Icon( Icons.light_mode_outlined, color: Color(0xff8a6a4f), ), ), ], ), const SizedBox(height: 12), Text(card.title), ], ), content: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisSize: MainAxisSize.min, children: [ AnimatedBuilder( animation: postcardNarrator, builder: (context, _) => Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( postcardNarrator.status, style: const TextStyle( fontFamily: 'sans-serif', fontSize: 13, ), ), TextButton.icon( key: const ValueKey('postcard-play'), onPressed: () => unawaited( postcardNarrator.toggle( card.id, prefs.decimal('recording_speed'), ), ), icon: Icon( postcardNarrator.playing ? Icons.pause : Icons.play_arrow, ), label: CopyText(postcardNarrator.label), ), ], ), ), const Divider(), SelectableText( card.message, key: const ValueKey('postcard-message'), style: hand(25).copyWith(height: 1.4), ), ], ), ), actions: [ TextButton( onPressed: () => Navigator.pop(c, true), child: const CopyText('Keep this postcard'), ), ], ), ); await postcardNarrator.stop(); if (kept != true || !mounted) return; await showDialog( context: context, builder: (c) => AlertDialog( key: const ValueKey('postcard-reveal'), backgroundColor: const Color(0xfffffbef), title: Text(card.title, style: hand(28)), content: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 560), child: AspectRatio( aspectRatio: 1.7, child: PostcardRevealArt(card: card), ), ), actions: [ TextButton( onPressed: () => Navigator.pop(c), child: const CopyText('Back to collection'), ), ], ), ); if (!mounted || !completedNow || g.mode != Mode.postcard || g.postcardIndex != index || g.screen != Screen.game) { return; } if (g.claimPostcardBreak()) { await ads.between(() { if (mounted) g.showPostcards(); }); } else { g.showPostcards(); } } Future chooseLanguage() async { narrator.cancelAutoplay(); final catalogue = g.library; if (catalogue == null) return; final languages = {...catalogue.copy.languages}; for (final story in catalogue.stories) { for (final entry in story.languages.entries) { languages[entry.key] = entry.value['label']; } } final selected = await showDialog( context: context, builder: (c) => SimpleDialog( title: const CopyText('Language'), children: [ SimpleDialogOption( onPressed: () => Navigator.pop(c, 'system'), child: CopyText( '${g.languagePreference == 'system' ? '✓ ' : ''}Follow device language', ), ), for (final entry in languages.entries) SimpleDialogOption( onPressed: () => Navigator.pop(c, entry.key), child: Text( '${g.languagePreference == entry.key ? '✓ ' : ''}${entry.value}', ), ), Padding( padding: const EdgeInsets.all(20), child: CopyText( 'Missing translations use the story’s original language. Your reading position and puzzle marks are shared across languages.', style: hand(18), ), ), ], ), ); if (selected == null || !mounted) return; try { await g.selectLanguage(selected); } catch (_) { if (mounted) { toast('This language could not be opened. Please try again.'); } } } Widget standardStory() { final p = g.storyPage; final heading = [ folio('${g.book.title} / ${g.storyIndex + 1} OF ${g.book.pages.length}'), writing(p.title, size: 31), ]; final body = [ ...heading, if (p.speaker.isNotEmpty) writing(p.speaker, size: 17, color: muted), if (p.illustrationAsset case final asset?) Image.asset( artworkAsset(asset), height: 155, fit: BoxFit.contain, semanticLabel: p.caption.isEmpty ? p.title : p.caption, ), if (p.caption.isNotEmpty) reading(p.caption, size: 18), if (p.type == StoryPageType.memory) discoveryArt(g.book.levels[p.campaignIndex!], height: 155), if (p.text.isNotEmpty) reading(p.text), if (p.continuation.isNotEmpty) reading(p.continuation), if (g.book.tracks.containsKey(p.id)) audio(), if (p.type == StoryPageType.puzzle) puzzleBody(), if (p.type == StoryPageType.memory) action( g.recovered(p.campaignIndex!) ? 'View the solved pattern' : 'Return to this pattern', () => g.startCampaign(p.campaignIndex!), ), ]; return Leaf( key: ValueKey('${g.book.id}-story-${p.id}'), onTurn: (d) => turn(d), body: column(body), fittedBody: p.type == StoryPageType.puzzle ? fittedPuzzle( details: [ areaPicker(), ...puzzleNotes(), ...heading, if (p.text.isNotEmpty) reading(p.text), if (p.continuation.isNotEmpty) reading(p.continuation), if (g.book.tracks.containsKey(p.id)) audio(), ], ) : null, wideBody: p.type == StoryPageType.puzzle ? splitPuzzle( side: [ ...heading, if (p.text.isNotEmpty) reading(p.text, size: 18), areaPicker(), ...puzzleNotes(), ], ) : null, footer: navigation(), ); } Widget navigation() { final wide = MediaQuery.orientationOf(context) == Orientation.landscape; final previous = InkButton( '← Previous leaf', g.storyIndex > 0 ? () => turn(-1) : null, size: wide ? 19 : 21, ); final next = InkButton( g.storyIndex == g.book.pages.length - 1 ? (g.book.isMara ? 'Across the tide →' : 'Back to contents') : 'Next leaf →', () => turn(1), size: wide ? 19 : 21, ); return Row( children: [ Expanded(child: previous), const SizedBox(width: 8), Expanded(child: next), ], ); } String get recordingId => g.screen == Screen.story ? g.storyPage.id : 'campaign.${g.campaignIndex}.${g.screen == Screen.briefing ? 'before' : 'after'}'; Widget reading(String text, {double? size}) => ValueListenableBuilder( valueListenable: narrator.highlightedPassage, builder: (context, passage, _) { final index = passage.isEmpty ? -1 : text.indexOf(passage); return Padding( padding: const EdgeInsets.symmetric(vertical: 8), child: Text.rich( TextSpan( style: hand(size ?? (g.storyIndex == 0 ? 22 : 21)) .copyWith(fontFamily: g.book.fontFamily ?? 'sans-serif'), children: index < 0 ? [TextSpan(text: text)] : [ TextSpan(text: text.substring(0, index)), TextSpan( text: passage, style: TextStyle( backgroundColor: amber.withValues(alpha: .35), ), ), TextSpan(text: text.substring(index + passage.length)), ], ), ), ); }, ); Widget audio() => ListenableBuilder( listenable: narrator, builder: (context, _) => column([ writing( (narrator.page == recordingId ? narrator.speaker : g.book.tracks[recordingId]?['speaker']) == 'Narrator' ? 'Narrator · recorded story' : g.book.isMara ? 'Mara · diary reading' : '${narrator.page == recordingId ? narrator.speaker : g.book.tracks[recordingId]?['speaker'] ?? g.storyPage.speaker} · recorded story', size: 17, color: muted, ), Row( children: [ Expanded( flex: 3, child: InkButton( narrator.label, narrator.loading ? null : () => narrator.toggle( recordingId, prefs.decimal('recording_speed'), ), size: 21, ), ), const SizedBox(width: 5), Expanded(child: InkButton('Stop', () => narrator.stop(), size: 21)), const SizedBox(width: 5), Expanded(child: InkButton('Speed', speed, size: 21)), ], ), writing(narrator.status, size: 17, color: muted), InkButton('Sound & atmosphere', soundSettings, size: 18), ]), ); void refreshNotebook() => setState(() {}); Widget story() => g.book.isMara ? maraStory() : standardStory(); Future speed() async { await narrator.pause(); if (!mounted) return; await showDialog( context: context, builder: (c) => SimpleDialog( title: CopyText('Recording speed', style: hand(29)), children: [ for (final entry in [ (0.85, 'Unhurried · 0.85×'), (1.0, 'Original reading · 1.0×'), (1.15, 'A little faster · 1.15×'), ]) SimpleDialogOption( onPressed: () { unawaited(prefs.set('recording_speed', entry.$1)); Navigator.pop(c); }, child: CopyText(entry.$2, style: hand(23)), ), ], ), ); } Future soundSettings() { narrator.cancelAutoplay(); return showDialog( context: context, builder: (dialogContext) => StatefulBuilder( builder: (context, refresh) { void save(String key, Object value) { unawaited(prefs.set(key, value)); _syncAtmosphere(); if (mounted) setState(() {}); refresh(() {}); } return AlertDialog( title: CopyText('Sound & atmosphere', style: hand(29)), content: SingleChildScrollView( child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ SwitchListTile( contentPadding: EdgeInsets.zero, title: CopyText('Environmental sounds', style: hand(23)), value: atmosphereEnabled, onChanged: (value) => save('ambience_enabled', value), ), writing( 'Water at the harbour and bridge, wind around the tower. The atmosphere grows quieter while the story is read.', size: 20, ), writing('Atmosphere volume', size: 20), Slider( label: '${(prefs.decimal('ambience_volume', .7) * 100).round()}%', value: prefs.decimal('ambience_volume', .7).clamp(0.0, 1.0), divisions: 10, onChanged: atmosphereEnabled ? (value) => save('ambience_volume', value) : null, ), writing( 'Readings start 3 seconds after opening a page. You can play, pause or stop them at any time. Your device volume controls the voice.', size: 18, color: muted, ), if (ambience.error.isNotEmpty) writing(ambience.error, size: 18), ], ), ), actions: [ TextButton( onPressed: () => Navigator.pop(dialogContext), child: const CopyText('Keep going'), ), ], ); }, ), ); } Widget contents() { final chapter = g.contentsChapter; final indices = g.book.chapterLevels(chapter); final first = indices.first; final savedId = prefs.text('notebook_last_page'); final saved = g.book.pages.where((p) => p.id == savedId).firstOrNull; final bookmarkId = prefs.text('notebook_manual_bookmark'); final ribbon = g.book.pages.where((p) => p.id == bookmarkId).firstOrNull; return Leaf( key: ValueKey('contents-$chapter'), body: column([ folio('${g.book.title.toUpperCase()} · CONTENTS'), writing(g.book.levels[first].chapter, size: 34), if (!g.book.isMara) ...[ if (chapter == 0) reading(g.book.premise), action('Continue reading', g.openNotebook), if (ribbon != null) action( 'Return to my ribbon bookmark', () => g.showStory(g.book.pages.indexOf(ribbon)), ), ], if (chapter == 0 && g.book.isMara) ...[ writing( 'For you, when you are ready. With all my love, Gran.', color: const Color(0xff70503b), ), action('Open the dedication', () => g.showStory(0)), if (saved != null) action('Continue reading · ${saved.title}', g.openNotebook), if (ribbon != null) action( 'Return to my ribbon bookmark', () => g.showStory(g.book.pages.indexOf(ribbon)), ), divider(), ], for (final i in indices) ...[ InkButton( '${i + 1} · ${g.book.levels[i].title}${g.recovered(i) ? ' ✓' : ''}${chapter == 0 && ribbon?.campaignIndex == i ? ' · ribbon' : ''}', i <= g.accessible ? () { if (g.recovered(i)) { g.reveal(i); } else { g.briefing(i); } } : null, ), ], if (chapter == 0 && g.book.isMara) ...[ divider(), action('The folded note', () => g.showStory(4)), action('Gran’s repair note', () => g.showStory(5)), action( 'Before you leave', () => g.showStory(g.book.pages.length - 1), ), ], writing( '${g.recoveredCount} / ${g.book.levels.length} memories restored', size: 20, color: muted, ), ]), footer: column([ Row( children: [ Expanded( child: InkButton( '← Previous chapter', chapter > 0 ? () => g.contents(chapter - 1) : null, size: 19, ), ), Expanded( child: InkButton( 'Next chapter →', chapter + 1 < g.book.chapters.length && g.book.chapterLevels(chapter + 1).first <= g.accessible ? () => g.contents(chapter + 1) : null, size: 19, ), ), ], ), InkButton('Close the notebook', g.home, size: 19), ]), ); } Widget briefing() { final l = g.book.levels[g.campaignIndex]; return Leaf( key: ValueKey('briefing-${g.campaignIndex}'), onTurn: (d) => turnCampaign(d), body: column([ folio('${g.book.title.toUpperCase()} / LEAF ${g.campaignIndex + 1}'), writing(l.chapter, size: 20, color: blue), writing(l.title, size: 33), gap(), reading(l.before, size: 25), if (l.beforeContinuation.isNotEmpty) reading(l.beforeContinuation), if (g.book.tracks.containsKey(recordingId)) audio(), divider(), writing( g.campaignIndex < 2 ? 'Light the cells to match each row and column total. Cross out the cells that stay dark. The finished grid is a picture from the story.' : 'A, B and C are outlined areas with their own light totals. Shared cells count in each area they belong to. Compare clues and subtract their shared parts to find new deductions.', size: 22, color: muted, ), action( g.recovered(g.campaignIndex) ? 'View the solved pattern →' : prefs.contains('grid_${g.book.puzzleKey(g.campaignIndex)}') ? 'Continue this pattern →' : 'Restore the pattern →', () => g.startCampaign(g.campaignIndex), primary: true, ), action('Back to notebook', g.contents), ]), ); } Widget puzzleBody() => column([areaPicker(), board(), ...puzzleNotes()]); Widget areaPicker() { final p = g.puzzle; if (p == null || p.regions.isEmpty) return const SizedBox.shrink(); return column([ Wrap( spacing: 6, children: [ for (var i = 0; i < p.regions.length; i++) RegionButton( key: ValueKey('area-$i'), label: '${p.regions[i].label} · ${List.generate(g.cells.length, (j) => j).where((j) => p.regions[i].contains(j, p.size) && g.cells[j] == 1).length} / ${p.regionTotal(p.regions[i])}', onPressed: () => g.area(i), selected: i == g.selectedArea, ), ], ), writing('Tap A, B or C to highlight its area', size: 17, color: muted), ]); } Widget board({double maxWidth = 350}) { final p = g.puzzle; if (p == null) return const SizedBox.shrink(); return RepaintBoundary( child: Board( puzzle: p, cells: g.cells, onMark: g.mark, selectedArea: g.selectedArea, won: g.won, maxWidth: maxWidth, ), ); } List puzzleNotes() => [ if (g.puzzle?.omittedRow != null) writing( 'Two totals have faded. Use the marked cells and area clues to recover the pattern.', size: 19, color: regionInk, ), if (g.puzzle?.footprintTrails.isNotEmpty ?? false) writing( 'Footprints: exactly two marked cells are lit, and they touch.', size: 19, color: regionInk, ), if (g.puzzle?.mirrorPairs.isNotEmpty ?? false) writing( 'Matching stars are mirrored: both cells match.', size: 19, color: regionInk, ), if (g.puzzle?.hiddenRow case final row?) writing( 'Row ${row + 1} and the diamond-marked cells together contain ${g.puzzle!.hiddenClueTotal} lights. Recover both missing totals.', size: 19, color: regionInk, ), if (g.puzzle?.lanternPairs.isNotEmpty ?? false) writing( 'Matching lanterns: exactly one of the two cells is lit.', size: 19, color: regionInk, ), if (g.mode == Mode.campaign) InkButton('Sound & atmosphere', soundSettings, size: 18), writing( g.won ? 'Already restored. Turn the leaf to revisit the memory.' : 'Tap: light → cross → clear. Mark every cell.', size: 18, color: muted, ), if (!g.won) InkButton(kIsWeb ? 'Hint' : 'Hint · rewarded ad', hint, size: 22), ]; /// The board stays in the viewport while supporting text scrolls separately. Widget fittedPuzzle({required List details}) => LayoutBuilder( builder: (context, constraints) { final grid = math.min( math.min(constraints.maxWidth, 350.0), constraints.maxHeight * .70, ); return Column( children: [ SizedBox( height: grid, child: board(maxWidth: grid), ), Expanded( child: SingleChildScrollView( key: const ValueKey('puzzle-details-scroll'), padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 4), child: column(details), ), ), ], ); }, ); /// Landscape puzzle leaf: the grid keeps the left column at its full height /// while the heading, area clues and notes sit beside it, so nothing has to /// be scrolled into view before the board can be played. Widget splitPuzzle({required List side}) => LayoutBuilder( builder: (context, c) { final width = math.min(c.maxWidth, 980.0), height = c.maxHeight.isFinite ? c.maxHeight : c.maxWidth, // Keep a readable column for the notes, then give the rest to the // grid, which stays a square no taller than the page. panel = math.min( math.min(280.0, math.max(200.0, width * .40)), width * .55, ), grid = math.min(math.min(height, width - panel - 18), 520.0); return Align( alignment: Alignment.center, child: SizedBox( width: width, height: height, child: Row( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ SizedBox( width: grid, child: Center(child: board(maxWidth: grid)), ), const SizedBox(width: 18), Expanded( child: SingleChildScrollView( key: const ValueKey('leaf-side-scroll'), padding: const EdgeInsets.fromLTRB(2, 8, 2, 8), child: column(side), ), ), ], ), ), ); }, ); Widget game() { List heading({bool compact = false}) => [ folio( g.mode == Mode.daily ? 'DAILY / ${DateFormat('d MMMM', Localizations.localeOf(context).languageCode).format(g.date)}' : g.mode == Mode.postcard ? 'POSTCARD / ${g.postcardIndex + 1} / PATTERN ${g.postcardSlot + 1} OF 3' : g.mode == Mode.campaign ? '${g.book.title.toUpperCase()} / ${g.campaignIndex + 1} OF ${g.book.levels.length}' : 'CLASSIC / ${g.difficulty.label} / LEVEL ${g.playingLevel}', ), writing( g.mode == Mode.campaign ? g.book.levels[g.campaignIndex].title : g.mode == Mode.postcard ? g.postcard.title : 'Find the light.', size: compact ? 27 : 32, ), writing( g.puzzle?.regions.isEmpty ?? true ? 'Match the totals. Let the pattern emerge.' : 'Compare rows, columns and overlapping areas.', size: compact ? 18 : 21, color: muted, ), ]; final actions = <({String label, VoidCallback run, bool primary})>[ if (g.won) ( label: g.mode == Mode.postcard ? (g.postcardSolved(g.postcardIndex) == 3 ? 'Read your postcard' : 'Next pattern →') : g.mode == Mode.daily ? (g.library == null ? 'Return to the notebook' : 'Back to the shelf') : g.mode == Mode.campaign ? 'Revisit the memory →' : 'Next puzzle →', run: g.mode == Mode.postcard ? nextPostcard : g.mode == Mode.daily ? back : g.mode == Mode.campaign ? () => g.reveal(g.campaignIndex) : nextPractice, primary: true, ), (label: 'How to play', run: rules, primary: false), ( label: g.mode == Mode.postcard ? 'Back to postcards' : g.mode != Mode.campaign && g.library != null ? 'Back to the shelf' : 'Back to notebook', run: g.mode == Mode.postcard ? g.showPostcards : g.mode == Mode.campaign ? g.contents : back, primary: false, ), ]; final clarity = writing('A moment of clarity.', size: 29); return Leaf( key: ValueKey('game-${g.key}'), onTurn: g.mode == Mode.campaign ? (d) => turnCampaign(d) : null, body: column([ ...heading(), puzzleBody(), if (g.won) clarity, for (final a in actions) action(a.label, a.run, primary: a.primary), ]), fittedBody: fittedPuzzle( details: [ areaPicker(), ...puzzleNotes(), ...heading(compact: true), if (g.won) clarity, for (final a in actions) action(a.label, a.run, primary: a.primary), ], ), // Landscape: the heading and notes sit beside the grid while the leaf's // actions stay in a compact bar that does not take room from the board. wideBody: Column( children: [ Expanded( child: splitPuzzle( side: [ ...heading(compact: true), areaPicker(), ...puzzleNotes(), if (g.won) writing('A moment of clarity.', size: 23), ], ), ), Padding( padding: const EdgeInsets.only(top: 6, bottom: 4), child: Row( children: [ for (var i = 0; i < actions.length; i++) ...[ if (i > 0) const SizedBox(width: 8), Expanded( child: InkButton( actions[i].label, actions[i].run, size: 20, primary: actions[i].primary, ), ), ], ], ), ), ], ), ); } Future hint() async { final requested = g.key; var granted = false; void give() async { if (granted || !mounted || g.key != requested || g.won || !(g.screen == Screen.game || g.screen == Screen.story && g.storyPage.type == StoryPageType.puzzle)) { return; } granted = true; final h = g.applyHint(); if (h == null) return; await message( 'Row ${h.cell ~/ g.puzzle!.size + 1}, column ${h.cell % g.puzzle!.size + 1}', '${CopyScope.text(context, h.explanation)}\n\n${CopyScope.text(context, h.value == 1 ? 'This cell is lit.' : 'This cell stays dark.')}', ); if (mounted && g.key == requested && (g.screen == Screen.game || g.screen == Screen.story && g.storyPage.type == StoryPageType.puzzle)) { g.check(); } } // Browser playtests have no mobile ad SDK or reward requirement. if (kIsWeb) { if (await confirm( 'A little nudge?', 'Reveal one cell with an explanation?', 'Show hint', no: 'Keep thinking', )) { give(); } return; } if (!await confirm( 'A little nudge?', 'Watch a rewarded ad for one explained hint.', 'Watch ad', no: 'Keep thinking', )) { return; } if (!await ads.hint(give)) { toast('No ad available. Please try again later.'); } } void nextPractice() { if (g.claimPracticeBreak()) { ads.between(() { if (mounted) unawaited(g.startPractice()); }); } else { unawaited(g.startPractice()); } } void nextPostcard() { if (g.postcardSolved(g.postcardIndex) == 3) { unawaited(readPostcard(g.postcardIndex, completedNow: true)); } else { g.startPostcard(g.postcardIndex); } } Widget discoveryArt(CampaignLevel level, {double height = 190}) { // Discovery images belong only to the leaf after the puzzle, even when // revisiting an earlier page with a completed save. if (!(g.screen == Screen.reveal || g.screen == Screen.story && g.storyPage.type == StoryPageType.memory)) { return const SizedBox.shrink(); } if (!g.recovered(g.book.levels.indexOf(level))) { return writing( 'The picture will appear once you restore the pattern.', size: 19, color: muted, ); } if (level.illustrationAsset case final asset?) { return Discovery( key: ValueKey('discovery-${g.campaignIndex}'), picture: level.picture, label: level.object, height: height, artwork: Image.asset( artworkAsset(asset), height: height, width: double.infinity, fit: BoxFit.contain, semanticLabel: 'Watercolour illustration: ${level.object}', errorBuilder: (_, _, _) => PixelPicture(level.picture, label: level.object, height: height), ), ); } return PixelPicture(level.picture, label: level.object, height: height); } Widget reveal() { final i = g.campaignIndex, l = g.book.levels[i]; return Leaf( key: ValueKey('reveal-$i'), onTurn: (d) => turnCampaign(d), body: column([ folio('${g.book.title.toUpperCase()} / LEAF ${i + 1}'), writing( g.recovered(i) ? 'Something found. Something remembered.' : 'A memory to read · your pattern can wait', size: 23, color: muted, ), writing(l.object, size: 35), discoveryArt(l), reading(l.after, size: 25), if (l.afterContinuation.isNotEmpty) reading(l.afterContinuation), if (g.book.tracks.containsKey(recordingId)) audio(), action( g.recovered(i) ? 'View the solved pattern' : 'Return to this pattern', () => g.startCampaign(i), ), gap(), writing( g.recovered(i) ? 'Kept safe, between these pages. — M.' : 'Your pattern is saved for another day.', size: 23, color: const Color(0xff70503b), ), divider(), if (i == g.book.levels.length - 1) ...[ folio( g.recoveredCount == g.book.levels.length ? 'THE END · YOUR WATCH HAS BEGUN' : 'THE LAST PAGE · COME BACK WHENEVER YOU LIKE', ), writing( g.recoveredCount == g.book.levels.length ? 'Every pattern restored. The daily puzzle will be here whenever you return.' : 'A light kept in these pages. Your unfinished patterns will be here whenever you return.', ), action('Return to the notebook', g.contents, primary: true), action('Today’s puzzle', () => g.startDaily(DateTime.now())), ] else action('Turn the page →', nextCampaign, primary: true), action('Back to notebook', g.contents), ]), ); } Future chooseDifficulty() async { await showDialog( context: context, builder: (c) => SimpleDialog( title: CopyText('Classic practice pace', style: hand(29)), children: [ for (final d in Difficulty.values) SimpleDialogOption( onPressed: () { g.selectDifficulty(d); Navigator.pop(c); }, child: CopyText( '${CopyScope.text(context, d.label)} — ${CopyScope.text(context, d.description)}', style: hand(23), ), ), ], ), ); } void rules() { final text = CopyScope.text( context, '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\nA, B and C are overlapping areas with their own totals. 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\nWatch a rewarded ad for each explained hint. Hints are optional, and your puzzle remains available if no ad can be shown. Streaks count consecutive daily completions on this device.', ); message( 'Find the light', kIsWeb ? '${text.substring(0, text.lastIndexOf('\n\n'))}\n\n${CopyScope.text(context, 'Hints are free in this browser playtest. Each hint reveals one cell and explains the deduction. Streaks count consecutive daily completions in this browser.')}' : text, close: 'Got it', ); } Future privacy() async { if (kIsWeb) { await message( 'Privacy & advertising', 'This browser playtest has no advertising. Progress, puzzle marks, bookmarks and settings are saved only in this browser. Clearing site data removes them. Progress does not sync between devices. Your web host may keep normal access logs.', close: 'Close', ); return; } if (!await ads.privacy()) { await message( 'Privacy & advertising', 'Game progress stays on this device. No account or game backend is used. Google advertising services may process device and ad interaction data when ads are available.\n\nNo advertising privacy options are currently required or available for your region.', close: 'Close', ); } } }