diff --git a/.claude/private/CLAUDE.md b/.claude/private/CLAUDE.md index d93ca30..2ddb784 100644 Binary files a/.claude/private/CLAUDE.md and b/.claude/private/CLAUDE.md differ diff --git a/apps/modusnote/assets/fonts/book/Inter-OFL.txt b/apps/modusnote/assets/fonts/book/Inter-OFL.txt new file mode 100644 index 0000000..21f6aff --- /dev/null +++ b/apps/modusnote/assets/fonts/book/Inter-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2020 The Inter Project Authors (https://github.com/rsms/inter) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/apps/modusnote/assets/fonts/book/Inter-Regular.ttf b/apps/modusnote/assets/fonts/book/Inter-Regular.ttf new file mode 100644 index 0000000..87eddd1 Binary files /dev/null and b/apps/modusnote/assets/fonts/book/Inter-Regular.ttf differ diff --git a/apps/modusnote/assets/fonts/book/Inter-SemiBold.ttf b/apps/modusnote/assets/fonts/book/Inter-SemiBold.ttf new file mode 100644 index 0000000..b503321 Binary files /dev/null and b/apps/modusnote/assets/fonts/book/Inter-SemiBold.ttf differ diff --git a/apps/modusnote/assets/fonts/book/PlusJakartaSans-Bold.ttf b/apps/modusnote/assets/fonts/book/PlusJakartaSans-Bold.ttf new file mode 100644 index 0000000..a461337 Binary files /dev/null and b/apps/modusnote/assets/fonts/book/PlusJakartaSans-Bold.ttf differ diff --git a/apps/modusnote/assets/fonts/book/PlusJakartaSans-OFL.txt b/apps/modusnote/assets/fonts/book/PlusJakartaSans-OFL.txt new file mode 100644 index 0000000..ea69b0c --- /dev/null +++ b/apps/modusnote/assets/fonts/book/PlusJakartaSans-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2020 The Plus Jakarta Sans Project Authors (https://github.com/tokotype/PlusJakartaSans) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +http://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/apps/modusnote/lib/bootstrap/home_native.dart b/apps/modusnote/lib/bootstrap/home_native.dart index d1e0a0f..f7a8356 100644 --- a/apps/modusnote/lib/bootstrap/home_native.dart +++ b/apps/modusnote/lib/bootstrap/home_native.dart @@ -32,6 +32,7 @@ import 'home.dart' show AppHome; import '../vault/vault_shelf_gate.dart'; import 'gallery_image_chooser.dart'; import 'local_reminder_scheduler.dart'; +import 'native_file_exchange.dart'; import 'vault_wiring.dart'; /// libsodium is built by the `sodium` package's build hook and loaded once @@ -153,6 +154,7 @@ VaultGate _gate({ }, passwordFrom: (bytes) => SodiumPasswordSecret.fromUtf8Bytes(sodium, bytes), catalog: SeedSchemas.catalog, + files: NativeFileExchange(), remindersFor: (l10n) => LocalReminderScheduler( channel: l10n.reminderChannel, description: l10n.reminderChannelDescription, diff --git a/apps/modusnote/lib/bootstrap/native_file_exchange.dart b/apps/modusnote/lib/bootstrap/native_file_exchange.dart new file mode 100644 index 0000000..5430e58 --- /dev/null +++ b/apps/modusnote/lib/bootstrap/native_file_exchange.dart @@ -0,0 +1,36 @@ +import 'dart:typed_data'; + +import 'package:file_picker/file_picker.dart'; + +import '../backup/file_exchange.dart'; + +/// Saves and picks through the system's own document dialogs (the +/// Storage Access Framework on Android, the document picker on iOS): the +/// person chooses where the file goes, and the bytes are written there +/// straight from memory. A picked file is copied by the system into the +/// app's cache to be read; the copy is removed as soon as it has been. +final class NativeFileExchange implements FileExchange { + @override + Future save(String name, String mimeType, Uint8List bytes) async { + await FilePicker.saveFile(fileName: name, bytes: bytes, mimeType: mimeType); + } + + @override + Future pick({ + required String accept, + required int maxBytes, + }) async { + try { + final picked = await FilePicker.pickFiles(); + if (picked.isEmpty) return null; + final file = picked.first; + final size = await file.length(); + if (size != null && size > maxBytes) throw const FileTooLargeException(); + final bytes = await file.readAsBytes(); + if (bytes.length > maxBytes) throw const FileTooLargeException(); + return bytes; + } finally { + await FilePicker.clearTemporaryFiles(); + } + } +} diff --git a/apps/modusnote/lib/cookbook/book_picture.dart b/apps/modusnote/lib/cookbook/book_picture.dart new file mode 100644 index 0000000..ffde414 --- /dev/null +++ b/apps/modusnote/lib/cookbook/book_picture.dart @@ -0,0 +1,59 @@ +import 'dart:ui' as ui; + +import 'package:flutter/foundation.dart'; +import 'package:image/image.dart' as img; + +/// The longest side of a recipe's opening photo in the book, and of the +/// other pictures: enough for a page printed at home, small enough that a +/// book of a thousand recipes fits in a phone's memory. +const bookPhotoSide = 987; +const bookPictureSide = 610; + +/// [picture] made again for a book: decoded by the platform, scaled down +/// to [side] at most, and written as a new JPEG from its pixels alone, so +/// nothing of the original file (place, camera, dates) survives. Null for +/// bytes that are not a picture. +Future bookPicture(Uint8List picture, {required int side}) async { + ui.Codec? codec; + ui.Image? image; + try { + final buffer = await ui.ImmutableBuffer.fromUint8List(picture); + codec = await ui.instantiateImageCodecWithSize( + buffer, + getTargetSize: (width, height) => switch (width >= height) { + _ when width <= side && height <= side => const ui.TargetImageSize(), + true => ui.TargetImageSize(width: side), + false => ui.TargetImageSize(height: side), + }, + ); + image = (await codec.getNextFrame()).image; + final rgba = await image.toByteData(format: ui.ImageByteFormat.rawRgba); + if (rgba == null) return null; + return await compute(_jpeg, ( + rgba.buffer.asUint8List(rgba.offsetInBytes, rgba.lengthInBytes), + image.width, + image.height, + )); + } on Object { + return null; + } finally { + image?.dispose(); + codec?.dispose(); + } +} + +Uint8List _jpeg((Uint8List, int, int) pixels) { + final (rgba, width, height) = pixels; + final decoded = img.Image.fromBytes( + width: width, + height: height, + bytes: rgba.buffer, + bytesOffset: rgba.offsetInBytes, + numChannels: 4, + ); + // A photo with see-through parts goes on the page's white. + final flat = img.Image(width: width, height: height); + img.fill(flat, color: img.ColorRgb8(255, 255, 255)); + img.compositeImage(flat, decoded); + return img.encodeJpg(flat, quality: 82); +} diff --git a/apps/modusnote/lib/cookbook/cookbook.dart b/apps/modusnote/lib/cookbook/cookbook.dart new file mode 100644 index 0000000..17eae77 --- /dev/null +++ b/apps/modusnote/lib/cookbook/cookbook.dart @@ -0,0 +1,180 @@ +import 'package:publishing/publishing.dart'; +import 'package:schema_dynamic_content/schema_dynamic_content.dart'; + +/// One recipe as the book prints it: the same page serv.pub would show +/// ([PageDocument] with the recipe layout, private links and ids already +/// gone), the files it shows, and its published address, if any. +final class CookbookRecipe { + CookbookRecipe({ + required this.entry, + required this.document, + required Map media, + this.page, + }) : media = Map.unmodifiable(media) { + if (document.recipe == null) { + throw ArgumentError.value(document, 'document', 'not a recipe page'); + } + } + + final EntryId entry; + final PageDocument document; + + /// Where each file the page shows comes from. + final Map media; + + /// The recipe's page on serv.pub: what a video's code points to. + final Uri? page; + + String get title => document.title; + PageRecipe get recipe => document.recipe!; +} + +/// The recipes filed directly in one category of the book. +final class CookbookChapter { + CookbookChapter({ + required List path, + required this.colours, + required List recipes, + }) : path = List.unmodifiable(path), + recipes = List.unmodifiable(recipes); + + /// The names from just under the book's own category down to this + /// one; empty for the recipes filed in the book's category itself. + final List path; + final CategoryColours colours; + final List recipes; + + /// The chapter's own name; empty for the book's category itself. + String get name => path.isEmpty ? '' : path.last; + + /// 0 for the book's category, 1 just under it, and so on. + int get depth => path.length; +} + +/// One line of the index of ingredients: a name and the recipes that use +/// it, in the order of the book. +final class CookbookIngredient { + CookbookIngredient(this.name, List recipes) + : recipes = List.unmodifiable(recipes); + + final String name; + final List recipes; +} + +/// A cookbook: the recipes of a category and of every category inside +/// it, a chapter per category in the order of the library, the recipes of +/// a chapter by title, and the ingredients in alphabetical order. Built on +/// the device from the vault, and so private until the person shares the +/// file. +final class Cookbook { + Cookbook._(this.title, this.palette, this.chapters, this.ingredients); + + /// The most recipes in one book. + static const maxRecipes = 2584; + + /// Collects the book of [root]. [compose] gives a note's page, null for + /// one that cannot be shown; [pageOf] its address on serv.pub. + factory Cookbook.collect({ + required CategoryTree tree, + required CategoryId root, + required Iterable entries, + required CategoryId? Function(EntryId id) categoryOf, + required CookbookRecipe? Function(DynamicEntry entry) compose, + required SitePalette palette, + }) { + final top = tree[root]; + if (top == null) { + throw ArgumentError.value(root, 'root', 'not in the tree'); + } + final inside = tree.subtree(root); + final filed = >{}; + var count = 0; + for (final entry in entries) { + if (entry.schemaId.name != Recipe.schema) continue; + final at = tree.resolve(categoryOf(entry.id)); + if (at == null || !inside.contains(at)) continue; + if (count++ == maxRecipes) throw const CookbookTooLargeException(); + filed.putIfAbsent(at, () => []).add(entry); + } + final order = [ + top, + for (final category in tree.ordered) + if (category.id != root && inside.contains(category.id)) category, + ]; + final chapters = []; + for (final category in order) { + final notes = filed[category.id]; + if (notes == null) continue; + final recipes = [for (final entry in notes) ?compose(entry)] + ..sort(_byTitle); + if (recipes.isEmpty) continue; + final path = tree.pathTo(category.id); + final below = path.indexWhere((c) => c.id == root); + chapters.add( + CookbookChapter( + path: [for (final c in path.skip(below + 1)) c.name.value], + colours: CategoryColours.of(palette, chapters.length), + recipes: recipes, + ), + ); + } + return Cookbook._( + top.name.value, + palette, + List.unmodifiable(chapters), + List.unmodifiable(_index(chapters)), + ); + } + + /// The name of the book's category. + final String title; + final SitePalette palette; + final List chapters; + final List ingredients; + + /// Every recipe, in the order of the book. + Iterable get recipes => + chapters.expand((chapter) => chapter.recipes); + + bool get isEmpty => chapters.isEmpty; + + /// The chapter [recipe] is in. + CookbookChapter chapterOf(CookbookRecipe recipe) => + chapters.firstWhere((c) => c.recipes.contains(recipe)); + + static int _byTitle(CookbookRecipe a, CookbookRecipe b) { + final folded = EntrySearch.fold(a.title) + .compareTo(EntrySearch.fold(b.title)); + if (folded != 0) return folded; + final exact = a.title.compareTo(b.title); + return exact != 0 ? exact : a.entry.value.compareTo(b.entry.value); + } + + /// Ingredients by their name without case, accents or repeated spaces: + /// «Farina 00» and «farina 00» are one line, named as first written. + static List _index(List chapters) { + final names = {}; + final uses = >{}; + for (final chapter in chapters) { + for (final recipe in chapter.recipes) { + for (final item in recipe.recipe.ingredients) { + final name = item.name.trim().replaceAll(RegExp(r'\s+'), ' '); + if (name.isEmpty) continue; + final key = EntrySearch.fold(name); + names.putIfAbsent(key, () => name); + final list = uses.putIfAbsent(key, () => []); + if (list.isEmpty || !identical(list.last, recipe)) list.add(recipe); + } + } + } + final keys = names.keys.toList()..sort(); + return [ + for (final key in keys) CookbookIngredient(names[key]!, uses[key]!), + ]; + } +} + +/// More recipes than [Cookbook.maxRecipes] in the category. +final class CookbookTooLargeException implements Exception { + const CookbookTooLargeException(); +} diff --git a/apps/modusnote/lib/cookbook/cookbook_epub.dart b/apps/modusnote/lib/cookbook/cookbook_epub.dart new file mode 100644 index 0000000..1b1add4 --- /dev/null +++ b/apps/modusnote/lib/cookbook/cookbook_epub.dart @@ -0,0 +1,512 @@ +import 'dart:convert'; +import 'dart:math'; +import 'dart:typed_data'; + +import 'package:publishing/publishing.dart'; + +import '../backup/zip_writer.dart'; +import '../notes/markdown/markdown_document.dart'; +import 'cookbook.dart'; +import 'cookbook_words.dart'; + +/// Writes a [Cookbook] as an EPUB 3 for e-readers (Kobo, Apple Books, +/// Google Play Books; a Kindle takes it through «Send to Kindle»): a +/// title page, the contents, a page per chapter and per recipe, and the +/// index of ingredients, all linked. The text reflows, so the layout is +/// left to the reader; the chapters keep their colours. Every word of the +/// person is escaped, and the Markdown is read by the notes' own reader, +/// so no markup of theirs reaches the file. No script, no font, no +/// address fetched. +final class CookbookEpub { + CookbookEpub({ + required this.book, + required this.words, + required this.pictures, + this.lang = 'it', + Random? random, + }) : _random = random ?? Random.secure(); + + final Cookbook book; + final CookbookWords words; + + /// The pictures the book shows, as JPEG or PNG; a picture not here is + /// left out. + final Map pictures; + final String lang; + final Random _random; + + /// The whole file. + Uint8List render({required DateTime at}) { + final zip = ZipWriter(at: at); + // First and stored: what tells a reader the archive is an EPUB. + zip.add('mimetype', ascii.encode('application/epub+zip')); + zip.add('META-INF/container.xml', utf8.encode(_container)); + final recipes = book.recipes.toList(); + final number = {for (final (i, r) in recipes.indexed) r: i}; + final files = {}; // path → media type + final spine = []; + final images = {}; + + String? imageOf(MediaId id) { + if (images[id] case final name?) return name; + final bytes = pictures[id]; + if (bytes == null) return null; + final type = _imageType(bytes); + if (type == null) return null; + final name = + 'images/p${images.length}.${type == 'image/png' ? 'png' : 'jpg'}'; + images[id] = name; + zip.add('EPUB/$name', bytes); + files[name] = type; + return name; + } + + void page(String name, String title, String body) { + zip.add('EPUB/$name', utf8.encode(_page(title, body))); + files[name] = 'application/xhtml+xml'; + spine.add(name); + } + + // The title page, with the first photo of the book. + String? cover; + for (final recipe in recipes) { + for (final p in recipe.recipe.cover) { + cover ??= imageOf(p.media); + } + } + page( + 'title.xhtml', + book.title, + '
' + '${cover == null ? '' : ''}' + '

${_e(book.title)}

' + '

${_e(words.recipeCount(recipes.length))}

' + '

${_e(words.madeWith)}

' + '
', + ); + + final chapters = book.chapters; + final separate = chapters.length > 1 || chapters.any((c) => c.depth > 0); + final nav = StringBuffer('
    '); + for (final (c, chapter) in chapters.indexed) { + final name = chapter.depth == 0 ? book.title : chapter.name; + final colour = 'c$c'; + if (separate) { + final file = 'chapter-$c.xhtml'; + page( + file, + name, + '
    ' + '${chapter.depth > 1 ? '

    ${_e(chapter.path.sublist(0, chapter.path.length - 1).join(' · '))}

    ' : ''}' + '

    ${_e(name)}

    ' + '

    ${_e(words.recipeCount(chapter.recipes.length))}

    ' + '
    ', + ); + nav.write('
  1. ${_e(name)}
      '); + } + for (final recipe in chapter.recipes) { + final file = _recipeFile(number[recipe]!); + page(file, recipe.title, _recipe(recipe, colour, imageOf)); + nav.write('
    1. ${_e(recipe.title)}
    2. '); + } + if (separate) nav.write('
  2. '); + } + if (book.ingredients.isNotEmpty) { + page('ingredients.xhtml', words.ingredientIndex, _index(number)); + nav.write( + '
  3. ${_e(words.ingredientIndex)}
  4. ', + ); + } + nav.write('
'); + zip.add( + 'EPUB/nav.xhtml', + utf8.encode( + _page( + words.contents, + '', + ), + ), + ); + zip.add('EPUB/style.css', utf8.encode(_style())); + zip.add( + 'EPUB/package.opf', + utf8.encode(_package(files, spine, images[_firstCover()], at)), + ); + return zip.finish(); + } + + MediaId? _firstCover() { + for (final recipe in book.recipes) { + for (final p in recipe.recipe.cover) { + if (pictures.containsKey(p.media)) return p.media; + } + } + return null; + } + + String _recipe( + CookbookRecipe entry, + String colour, + String? Function(MediaId) imageOf, + ) { + final recipe = entry.recipe; + final out = StringBuffer('
') + ..write('

${_e(entry.title)}

'); + final photos = [ + for (final p in recipe.cover) + if (imageOf(p.media) case final src?) (src, p.caption), + ]; + if (photos.isNotEmpty) out.write(_figure(photos.first, 'photo')); + if (recipe.description.isNotEmpty) { + out.write(_markdown(recipe.description, imageOf)); + } + final facts = [ + if (recipe.servings case final s?) ('', words.servings(s)), + ...words.times(recipe), + if (recipe.difficulty case final d?) + (words.difficulty, '${'●' * d}${'○' * (3 - d)}'), + if (recipe.methods.isNotEmpty) ('', recipe.methods.join(', ')), + ]; + if (facts.isNotEmpty) { + out.write('

'); + out.write( + facts + .map( + (f) => f.$1.isEmpty + ? '${_e(f.$2)}' + : '${_e(f.$1)} ${_e(f.$2)}', + ) + .join(' · '), + ); + out.write('

'); + } + if (recipe.ingredients.isNotEmpty) { + out.write('

${_e(words.ingredients)}

    '); + for (final item in recipe.ingredients) { + final q = words.quantity(item); + out.write('
  • '); + if (q.isNotEmpty) out.write('${_e(q)} '); + out.write(_e(item.name)); + if (item.link case final link? when _web(link) != null) { + out.write( + ' ${_e(_web(link)!.host)}', + ); + } + out.write('
  • '); + } + out.write('
'); + } + if (recipe.steps.isNotEmpty) { + out.write('

${_e(words.steps)}

    '); + for (final step in recipe.steps) { + out.write('
  1. ${_markdown(step.text, imageOf)}'); + final shown = [ + for (final p in step.pictures) + if (imageOf(p.media) case final src?) (src, p.caption), + ]; + for (final p in shown) { + out.write(_figure(p, 'step')); + } + if (step.video != null) { + out.write(switch (entry.page) { + final url? => + '

    ' + '${_e(words.watchVideo)}

    ', + null => '

    ${_e(words.videoInNote)}

    ', + }); + } + out.write('
  2. '); + } + out.write('
'); + } + for (final p in photos.skip(1)) { + out.write(_figure(p, 'photo')); + } + for (final block in entry.document.blocks) { + out.write(_block(block, imageOf)); + } + if (recipe.tags.isNotEmpty) { + out.write( + '

${_e(recipe.tags.map((t) => '#$t').join(' '))}

', + ); + } + out.write('
'); + return out.toString(); + } + + String _block(PageBlock block, String? Function(MediaId) imageOf) { + final label = '

${_e(block.label)}

'; + return switch (block) { + TextBlock(:final text) when !text.contains('\n') => + '

${_e(block.label)} ${_e(text)}

', + TextBlock(:final text) => '$label

${_e(text)}

', + MarkdownBlock(:final text) => '$label${_markdown(text, imageOf)}', + TagsBlock(:final items) => '$label

${_e(items.join(', '))}

', + ChecklistBlock(:final items) => + '$label
    ${[for (final i in items) '
  • ${i.done ? '☑' : '☐'} ${_e(i.text)}
  • '].join()}
', + LinksBlock(:final items) => + '$label', + ImageBlock(:final media, :final caption) => switch (imageOf(media)) { + final src? => '$label${_figure((src, caption), 'photo')}', + null => caption.isEmpty ? '' : '$label

${_e(caption)}

', + }, + AudioBlock() => '', + }; + } + + String _index(Map number) { + final out = StringBuffer('
') + ..write('

${_e(words.ingredientIndex)}

'); + for (final item in book.ingredients) { + out.write('
${_e(item.name)}
'); + out.write( + item.recipes + .map( + (r) => '${_e(r.title)}', + ) + .join(', '), + ); + out.write('
'); + } + out.write('
'); + return out.toString(); + } + + String _figure((String, String) picture, String kind) { + final (src, caption) = picture; + return '
${_a(caption)}' + '${caption.isEmpty ? '' : '
${_e(caption)}
'}' + '
'; + } + + // ---------------------------------------------------------- Markdown + + String _markdown(String source, String? Function(MediaId) imageOf) { + final out = StringBuffer(); + for (final block in MarkdownDocument.parse(source).blocks) { + _mdBlock(block, out, imageOf); + } + return out.toString(); + } + + void _mdBlock( + MdBlock block, + StringBuffer out, + String? Function(MediaId) imageOf, + ) { + switch (block) { + case MdHeading(:final level, :final inlines): + // Below the recipe's own h1 and its h2. + final h = (level + 2).clamp(3, 6); + out.write('${_inlines(inlines, imageOf)}'); + case MdParagraph(:final inlines): + out.write('

${_inlines(inlines, imageOf)}

'); + case MdList(:final ordered, :final start, :final items): + final tag = ordered ? 'ol' : 'ul'; + out.write(ordered && start != 1 ? '
    ' : '<$tag>'); + for (final item in items) { + out.write('
  1. '); + if (item.checked case final done?) out.write(done ? '☑ ' : '☐ '); + for (final inner in item.blocks) { + _mdBlock(inner, out, imageOf); + } + out.write('
  2. '); + } + out.write(''); + case MdQuote(:final blocks): + out.write('
    '); + for (final inner in blocks) { + _mdBlock(inner, out, imageOf); + } + out.write('
    '); + case MdCodeBlock(:final text): + out.write('
    ${_e(text)}
    '); + case MdRule(): + out.write('
    '); + } + } + + String _inlines( + List inlines, + String? Function(MediaId) imageOf, + ) => inlines.map((inline) { + return switch (inline) { + MdText(:final text) => _e(text), + MdCode(:final text) => '${_e(text)}', + MdStrong(:final children) => + '${_inlines(children, imageOf)}', + MdEmphasis(:final children) => '${_inlines(children, imageOf)}', + MdStrike(:final children) => '${_inlines(children, imageOf)}', + MdLink(:final children, :final url) => switch (_web(url)) { + final uri? => + '${_inlines(children, imageOf)}', + null => _inlines(children, imageOf), + }, + MdImage(:final alt, :final url) => switch (_picture(url, imageOf)) { + final src? => '${_a(alt)}', + null => _e(alt), + }, + }; + }).join(); + + String? _picture(String url, String? Function(MediaId) imageOf) { + if (!url.startsWith('image:')) return null; + try { + return imageOf(MediaId(url.substring(6))); + } on PublishingException { + return null; + } + } + + static Uri? _web(String url) => switch (Uri.tryParse(url)) { + final uri? + when (uri.isScheme('https') || uri.isScheme('http')) && + uri.host.isNotEmpty => + uri, + _ => null, + }; + + // ---------------------------------------------------------- the files + + static String _recipeFile(int index) => 'recipe-$index.xhtml'; + + String _page(String title, String body) => + '\n' + '\n' + '' + '${_e(title)}' + '' + '$body\n'; + + String _package( + Map files, + List spine, + String? cover, + DateTime at, + ) { + final id = _uuid(); + final modified = '${at.toUtc().toIso8601String().substring(0, 19)}Z'; + final items = StringBuffer( + '' + '', + ); + final ids = {}; + for (final (i, MapEntry(key: path, value: type)) in files.entries.indexed) { + final item = 'f$i'; + ids[path] = item; + items.write( + '', + ); + } + return '\n' + '' + '' + 'urn:uuid:$id' + '${_e(book.title)}' + '${_e(lang)}' + '$modified' + '' + '$items' + '${[for (final page in spine) ''].join()}' + '\n'; + } + + String _uuid() { + final b = List.generate(16, (_) => _random.nextInt(256)); + b[6] = (b[6] & 0x0F) | 0x40; + b[8] = (b[8] & 0x3F) | 0x80; + final hex = b.map((v) => v.toRadixString(16).padLeft(2, '0')).join(); + return '${hex.substring(0, 8)}-${hex.substring(8, 12)}-' + '${hex.substring(12, 16)}-${hex.substring(16, 20)}-${hex.substring(20)}'; + } + + /// The type of a picture by its first bytes; null for one an EPUB + /// reader need not show. + static String? _imageType(Uint8List b) { + if (b.length > 3 && b[0] == 0xFF && b[1] == 0xD8 && b[2] == 0xFF) { + return 'image/jpeg'; + } + if (b.length > 8 && + b[0] == 0x89 && + b[1] == 0x50 && + b[2] == 0x4E && + b[3] == 0x47) { + return 'image/png'; + } + return null; + } + + // The φ scale of the app, in em: half steps below and above the text. + static const _small = '.786em'; + static const _body = '1em'; + static const _h2 = '1.272em'; + static const _h1 = '2.618em'; + + String _style() { + String hex(Srgb c) => c.hex; + final p = book.palette; + final out = StringBuffer( + 'body{font-family:sans-serif;line-height:1.5;color:${hex(p.text)};}' + 'h1{font-size:$_h1;line-height:1.15;margin:0 0 .618em;color:${hex(p.accent)};}' + 'h2{font-size:$_h2;margin:1.618em 0 .618em;color:${hex(p.accent)};}' + 'h3,h4,h5,h6{font-size:$_body;margin:1em 0 .382em;}' + 'figure{margin:1em 0;}figure img{width:100%;height:auto;}' + 'figure.step img{width:61.8%;}' + 'figcaption{font-size:$_small;color:${hex(p.secondaryText)};}' + 'img.inline{max-width:61.8%;height:auto;display:block;margin:.618em 0;}' + '.facts,.fact{border-radius:.382em;padding:.382em .618em;}' + '.facts span,.fact span{font-size:$_small;color:${hex(p.secondaryText)};}' + 'ul.ingredients{list-style:none;padding:0;}ul.ingredients li{margin:.382em 0;}' + 'a.shop{font-size:$_small;}' + 'ol.steps li{margin:0 0 1em;}' + '.video{font-size:$_small;}' + '.tags,.made,.above{color:${hex(p.secondaryText)};font-size:$_small;}' + '.cover h1{font-size:$_h1;margin-top:1.618em;color:${hex(p.text)};}' + '.cover .count{color:${hex(p.accent)};}' + '.cover img.photo{width:100%;height:auto;}' + '.opener{padding:38.2% 1em 2em;}' + '.opener .count{font-size:$_h2;}' + 'dl dt{margin-top:.618em;}dl dd{margin:0 0 0 1.618em;}', + ); + for (final (c, chapter) in book.chapters.indexed) { + final accent = chapter.colours.accent.hex; + final tint = chapter.colours.tint.hex; + out.write( + '.c$c h1,.c$c h2,.c$c a{color:$accent;}' + '.c$c .facts,.c$c .fact{background:$tint;}' + '.opener.c$c{background:$tint;}', + ); + } + return out.toString(); + } + + static const _container = + '\n' + '' + '' + '\n'; + + /// [text] as XHTML text: the markup characters escaped, and the + /// characters XML 1.0 forbids dropped. + static String _e(String text) => text + .replaceAll(_forbidden, '') + .replaceAll('&', '&') + .replaceAll('<', '<') + .replaceAll('>', '>'); + + /// [text] inside a double-quoted attribute. + static String _a(String text) => _e(text).replaceAll('"', '"'); + + static final _forbidden = RegExp( + '[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F\\uFFFE\\uFFFF]', + ); +} diff --git a/apps/modusnote/lib/cookbook/cookbook_pages.dart b/apps/modusnote/lib/cookbook/cookbook_pages.dart new file mode 100644 index 0000000..7c0bb5c --- /dev/null +++ b/apps/modusnote/lib/cookbook/cookbook_pages.dart @@ -0,0 +1,89 @@ +import 'package:publishing/publishing.dart'; +import 'package:schema_dynamic_content/schema_dynamic_content.dart'; + +import '../notes/recipes/recipe_text.dart'; +import '../notes/schema_text.dart'; +import '../publishing/field_description.dart'; +import 'cookbook.dart'; + +/// Turns a recipe note into the page the book prints: every field the +/// note type lets one publish, pictures included, through the same +/// [PublicationPolicy] and [PageComposer] as serv.pub. Links to other +/// notes keep only their words unless that note is published, and no id +/// of the vault is left in the text. +final class CookbookPages { + CookbookPages({ + required this.schemas, + required this.texts, + required this.recipes, + required this.locale, + this.site, + }); + + final List schemas; + final SchemaText texts; + final RecipeText recipes; + + /// The language tag numbers and dates are written in. + final String locale; + + /// The device's site, for the addresses of the published recipes. + final SiteBook? site; + + var _next = 0; + + /// [entry]'s page; null for a note that is not a recipe or cannot be + /// shown. + CookbookRecipe? compose(DynamicEntry entry) { + final schema = _schemaOf(entry); + if (schema == null || schema.id.name != Recipe.schema) return null; + try { + final content = PublicationPolicy.compose( + entry: entry, + schema: schema, + fields: { + for (final field in PublicationPolicy.publishableFields(schema)) + field.key, + }, + published: site?.slugs ?? const {}, + ); + final media = { + for (final blob in [...content.images, ...content.videos]) + blob: _mediaId(), + }; + final document = PageComposer.compose( + content: content, + schema: schema, + media: media, + labelOf: (field) => texts.label(field.label), + describe: (field, value) => describeField(texts, locale, field, value), + listed: true, + ingredientLine: recipes.line, + recipeWords: RecipeWords(unit: recipes.unit, option: texts.option), + layout: PublicationLayout.recipe, + ); + final page = switch ((site, site?.pages[entry.id])) { + (final site?, final published?) => site.pageUrl(published.slug), + _ => null, + }; + return CookbookRecipe( + entry: entry.id, + document: document, + media: {for (final MapEntry(:key, :value) in media.entries) value: key}, + page: page, + ); + } on PublishingException { + return null; + } + } + + /// An id of the book's own, never one the site uses. + MediaId _mediaId() => MediaId('book${(_next++).toString().padLeft(18, '0')}'); + + SchemaDefinition? _schemaOf(DynamicEntry entry) { + for (final schema in schemas) { + if (schema.id == entry.schemaId) return schema; + } + return null; + } +} diff --git a/apps/modusnote/lib/cookbook/cookbook_pdf.dart b/apps/modusnote/lib/cookbook/cookbook_pdf.dart new file mode 100644 index 0000000..3332b67 --- /dev/null +++ b/apps/modusnote/lib/cookbook/cookbook_pdf.dart @@ -0,0 +1,979 @@ +import 'dart:math' as math; +import 'dart:typed_data'; + +import 'package:pdf/pdf.dart'; +import 'package:pdf/widgets.dart' as pw; +import 'package:publishing/publishing.dart'; + +import '../notes/markdown/markdown_document.dart'; +import 'cookbook.dart'; +import 'cookbook_words.dart'; + +/// The page a cookbook is printed on. +enum CookbookPage { + /// 144 × 233 mm, two Fibonacci numbers: the golden rectangle. + golden(144, 233), + a5(148, 210), + a4(210, 297); + + const CookbookPage(this.width, this.height); + + /// In millimetres. + final double width; + final double height; + + PdfPageFormat get format => + PdfPageFormat(width * PdfPageFormat.mm, height * PdfPageFormat.mm); +} + +/// The typefaces of the book, as TrueType files: Inter for the text, +/// Plus Jakarta Sans for the titles, as in the app. Only the letters the +/// book uses are written into the file. +final class CookbookFonts { + const CookbookFonts({ + required this.regular, + required this.semiBold, + required this.display, + this.fallback = const [], + }); + + final Uint8List regular; + final Uint8List semiBold; + final Uint8List display; + + /// For symbols the others lack. + final List fallback; +} + +/// Prints a [Cookbook] as a PDF laid out in φ like its page on serv.pub: +/// a cover, the contents, a chapter per category in its colour, each +/// recipe from a page of its own (opening photo in a golden rectangle, +/// ingredients in 38.2 % of the width and steps in the other 61.8 %), and +/// the index of ingredients at the end. The contents and the index link +/// to the recipes. A step's video cannot be printed: in its place a code +/// to its published page, or a line saying it is in the note. +final class CookbookPdf { + CookbookPdf({ + required this.book, + required this.words, + required this.fonts, + required this.pictures, + this.page = CookbookPage.golden, + this.lang = 'it', + }); + + final Cookbook book; + final CookbookWords words; + final CookbookFonts fonts; + + /// The pictures the book shows, as JPEG or PNG; a picture not here is + /// left out. + final Map pictures; + final CookbookPage page; + final String lang; + + static const _phi = 1.6180339887; + + /// The whole file. Laid out twice: the first time only to learn the + /// page each recipe starts on, for the contents and the index. + Future render() async { + final starts = {}; + await _document(starts, null).save(); + return _document({}, starts).save(); + } + + late final _regular = pw.Font.ttf(ByteData.sublistView(fonts.regular)); + late final _semiBold = pw.Font.ttf(ByteData.sublistView(fonts.semiBold)); + late final _display = pw.Font.ttf(ByteData.sublistView(fonts.display)); + late final _fallback = [ + for (final f in fonts.fallback) pw.Font.ttf(ByteData.sublistView(f)), + ]; + final _images = {}; + + // The type scale: the text, then one φ step (and half steps) either side. + double get _base => page == CookbookPage.a4 ? 11 : 9.5; + double get _small => _base / math.sqrt(_phi); + double get _h3 => _base * math.sqrt(_phi); + double get _h1 => _base * _phi * _phi; + double get _display1 => _base * _phi * _phi * _phi; + + // Space in steps of φ from the text size. + double get _s1 => _base / _phi / _phi; + double get _s2 => _base / _phi; + double get _s3 => _base; + double get _s4 => _base * _phi; + double get _s5 => _base * _phi * _phi; + + /// The margin: the page's width divided by φ⁵, and φ times more below. + pw.EdgeInsets get _margin { + final m = page.format.width / math.pow(_phi, 5); + return pw.EdgeInsets.fromLTRB(m, m, m, m * _phi); + } + + PdfColor _colour(Srgb c) => + PdfColor.fromInt(0xFF000000 | c.r << 16 | c.g << 8 | c.b); + + PdfColor get _text => _colour(book.palette.text); + PdfColor get _secondary => _colour(book.palette.secondaryText); + PdfColor get _background => _colour(book.palette.background); + PdfColor get _accent => _colour(book.palette.accent); + + pw.Document _document(Map found, Map? starts) { + final doc = pw.Document( + theme: + pw.ThemeData.withFont( + base: _regular, + bold: _semiBold, + italic: _regular, + boldItalic: _semiBold, + fontFallback: _fallback, + ).copyWith( + defaultTextStyle: pw.TextStyle( + font: _regular, + fontNormal: _regular, + fontBold: _semiBold, + fontItalic: _regular, + fontBoldItalic: _semiBold, + fontFallback: _fallback, + fontSize: _base, + color: _text, + lineSpacing: _base * (_phi - 1) * 0.5, + ), + ), + title: book.title, + creator: 'Modus Notes', + producer: 'Modus Notes', + compress: true, + ); + final recipes = book.recipes.toList(); + final number = {for (final (i, r) in recipes.indexed) r: i}; + String? numberOf(CookbookRecipe r) => + starts == null ? '000' : starts[number[r]!]?.toString(); + + doc.addPage(_cover(recipes)); + doc.addPage(_contents(number, numberOf)); + final chapters = book.chapters; + for (final chapter in chapters) { + if (chapters.length > 1 || chapter.depth > 0) { + doc.addPage(_opener(chapter)); + } + for (final recipe in chapter.recipes) { + doc.addPage(_recipe(chapter, recipe, number[recipe]!, found)); + } + } + if (book.ingredients.isNotEmpty) { + doc.addPage(_index(number, numberOf)); + } + return doc; + } + + pw.PageTheme _theme({PdfColor? ground}) => pw.PageTheme( + pageFormat: page.format, + margin: _margin, + buildBackground: ground == null + ? null + : (context) => pw.FullPage( + ignoreMargins: true, + child: pw.Container(color: ground), + ), + ); + + pw.Widget _footer(pw.Context context) => pw.Container( + alignment: pw.Alignment.center, + margin: pw.EdgeInsets.only(top: _s3), + child: pw.Text( + '${context.pageNumber}', + style: pw.TextStyle(fontSize: _small, color: _secondary), + ), + ); + + // ------------------------------------------------------------- cover + + pw.Page _cover(List recipes) { + MediaId? photo; + for (final recipe in recipes) { + for (final p in recipe.recipe.cover) { + if (_image(p.media) != null) { + photo = p.media; + break; + } + } + if (photo != null) break; + } + final width = page.format.width - _margin.horizontal; + return pw.Page( + pageTheme: _theme(ground: _background), + build: (context) => pw.Column( + crossAxisAlignment: pw.CrossAxisAlignment.start, + children: [ + if (photo != null) + pw.ClipRRect( + horizontalRadius: _s2, + verticalRadius: _s2, + child: pw.Image( + _image(photo)!, + width: width, + height: width / _phi, + fit: pw.BoxFit.cover, + ), + ), + pw.Spacer(), + pw.Container(width: _s5, height: _s1, color: _accent), + pw.SizedBox(height: _s4), + pw.Text( + book.title, + style: pw.TextStyle( + font: _display, + fontSize: _display1, + color: _text, + lineSpacing: 0, + ), + ), + pw.SizedBox(height: _s3), + pw.Text( + words.recipeCount(recipes.length), + style: pw.TextStyle(fontSize: _h3, color: _accent), + ), + pw.Spacer(flex: 1), + pw.Text( + words.madeWith, + style: pw.TextStyle(fontSize: _small, color: _secondary), + ), + ], + ), + ); + } + + // ---------------------------------------------------------- contents + + pw.MultiPage _contents( + Map number, + String? Function(CookbookRecipe) numberOf, + ) => pw.MultiPage( + pageTheme: _theme(), + maxPages: 1000, + footer: _footer, + build: (context) => [ + _heading(words.contents, _accent), + for (final chapter in book.chapters) ...[ + if (book.chapters.length > 1 || chapter.depth > 0) + pw.Padding( + padding: pw.EdgeInsets.only( + top: _s4, + bottom: _s2, + left: _s3 * math.max(0, chapter.depth - 1), + ), + child: pw.Text( + chapter.depth == 0 ? book.title : chapter.name, + style: pw.TextStyle( + font: _display, + fontSize: _h3, + color: _colour(chapter.colours.accent), + ), + ), + ), + for (final recipe in chapter.recipes) + pw.Link( + destination: _anchor(number[recipe]!), + child: pw.Padding( + padding: pw.EdgeInsets.only( + left: _s3 * math.max(0, chapter.depth - 1), + bottom: _s1, + ), + child: _leader(recipe.title, numberOf(recipe) ?? ''), + ), + ), + ], + ], + ); + + /// A line of the contents: the title, then its page at the right. + pw.Widget _leader(String title, String pageNumber) => pw.Row( + crossAxisAlignment: pw.CrossAxisAlignment.end, + children: [ + pw.Expanded(child: pw.Text(title, maxLines: 2)), + pw.SizedBox(width: _s3), + pw.SizedBox( + width: _s5, + child: pw.Text( + pageNumber, + textAlign: pw.TextAlign.right, + style: pw.TextStyle(color: _secondary), + ), + ), + ], + ); + + // ----------------------------------------------------------- chapter + + pw.Page _opener(CookbookChapter chapter) { + final accent = _colour(chapter.colours.accent); + final above = chapter.path.length > 1 + ? chapter.path.sublist(0, chapter.path.length - 1).join(' · ') + : book.title; + return pw.Page( + pageTheme: _theme(ground: _colour(chapter.colours.tint)), + build: (context) => pw.Column( + crossAxisAlignment: pw.CrossAxisAlignment.start, + children: [ + // The title sits at the golden section of the page. + pw.Spacer(flex: 382), + if (chapter.depth > 0) + pw.Text( + above, + style: pw.TextStyle(fontSize: _base, color: _secondary), + ), + pw.SizedBox(height: _s2), + pw.Text( + chapter.depth == 0 ? book.title : chapter.name, + style: pw.TextStyle( + font: _display, + fontSize: _display1, + color: accent, + lineSpacing: 0, + ), + ), + pw.SizedBox(height: _s3), + pw.Container(width: _s5, height: _s1, color: accent), + pw.SizedBox(height: _s3), + pw.Text( + words.recipeCount(chapter.recipes.length), + style: pw.TextStyle(fontSize: _h3, color: _text), + ), + pw.Spacer(flex: 618), + ], + ), + ); + } + + // ------------------------------------------------------------ recipe + + pw.MultiPage _recipe( + CookbookChapter chapter, + CookbookRecipe entry, + int index, + Map found, + ) { + final recipe = entry.recipe; + final accent = _colour(chapter.colours.accent); + final tint = _colour(chapter.colours.tint); + final width = page.format.width - _margin.horizontal; + final heading = chapter.depth == 0 ? book.title : chapter.name; + final photo = [ + for (final p in recipe.cover) + if (_image(p.media) != null) p, + ]; + return pw.MultiPage( + pageTheme: _theme(), + maxPages: 1000, + footer: _footer, + header: (context) { + // The first page of the recipe is where it starts. + found.putIfAbsent(index, () => context.pageNumber); + return pw.Container( + margin: pw.EdgeInsets.only(bottom: _s3), + child: pw.Text( + heading, + style: pw.TextStyle(fontSize: _small, color: accent), + ), + ); + }, + build: (context) => [ + pw.Anchor( + name: _anchor(index), + child: pw.Text( + entry.title, + style: pw.TextStyle( + font: _display, + fontSize: _h1, + color: accent, + lineSpacing: 0, + ), + ), + ), + pw.SizedBox(height: _s3), + if (photo.isNotEmpty) ...[ + pw.ClipRRect( + horizontalRadius: _s2, + verticalRadius: _s2, + child: pw.Image( + _image(photo.first.media)!, + width: width, + height: width / _phi, + fit: pw.BoxFit.cover, + ), + ), + if (photo.first.caption.isNotEmpty) _caption(photo.first.caption), + pw.SizedBox(height: _s3), + ], + if (recipe.description.isNotEmpty) ..._markdown(recipe.description), + ..._facts(recipe, accent, tint), + pw.SizedBox(height: _s4), + pw.Partitions( + children: [ + pw.Partition( + flex: 382, + child: pw.Padding( + padding: pw.EdgeInsets.only(right: _s4), + child: pw.Column( + crossAxisAlignment: pw.CrossAxisAlignment.start, + children: _ingredients(recipe, accent), + ), + ), + ), + pw.Partition( + flex: 618, + child: pw.Column( + crossAxisAlignment: pw.CrossAxisAlignment.start, + children: _steps(entry, accent, tint), + ), + ), + ], + ), + if (photo.length > 1) ...[ + pw.SizedBox(height: _s4), + _gallery(photo.skip(1).toList(), width), + ], + for (final block in entry.document.blocks) ..._block(block, accent), + if (recipe.tags.isNotEmpty) ...[ + pw.SizedBox(height: _s4), + pw.Text( + recipe.tags.map((t) => '#$t').join(' '), + style: pw.TextStyle(fontSize: _small, color: _secondary), + ), + ], + ], + ); + } + + /// Servings, times, methods and difficulty in one tinted box. + List _facts(PageRecipe recipe, PdfColor accent, PdfColor tint) { + final facts = <(String, String)>[ + if (recipe.servings case final servings?) ('', words.servings(servings)), + ...words.times(recipe), + if (recipe.difficulty case final d?) + (words.difficulty, '${'●' * d}${'○' * (3 - d)}'), + if (recipe.methods.isNotEmpty) ('', recipe.methods.join(', ')), + ]; + if (facts.isEmpty) return const []; + return [ + pw.SizedBox(height: _s3), + pw.Container( + padding: pw.EdgeInsets.symmetric(horizontal: _s3, vertical: _s2), + decoration: pw.BoxDecoration( + color: tint, + borderRadius: pw.BorderRadius.circular(_s2), + ), + child: pw.Wrap( + spacing: _s4, + runSpacing: _s1, + children: [ + for (final (label, value) in facts) + pw.RichText( + text: pw.TextSpan( + children: [ + if (label.isNotEmpty) + pw.TextSpan( + text: '$label ', + style: pw.TextStyle( + fontSize: _small, + color: _secondary, + ), + ), + pw.TextSpan( + text: value, + style: pw.TextStyle(fontWeight: pw.FontWeight.bold), + ), + ], + ), + ), + ], + ), + ), + ]; + } + + List _ingredients(PageRecipe recipe, PdfColor accent) { + if (recipe.ingredients.isEmpty) return [pw.SizedBox()]; + return [ + _subheading(words.ingredients, accent), + for (final item in recipe.ingredients) + pw.Padding( + padding: pw.EdgeInsets.only(bottom: _s2), + child: pw.RichText( + text: pw.TextSpan( + children: [ + if (words.quantity(item) case final q when q.isNotEmpty) + pw.TextSpan( + text: '$q ', + style: pw.TextStyle(fontWeight: pw.FontWeight.bold), + ), + pw.TextSpan(text: item.name), + if (item.link case final link?) + if (Uri.tryParse(link)?.host case final host?) + pw.TextSpan( + text: ' $host', + style: pw.TextStyle( + fontSize: _small, + color: accent, + decoration: pw.TextDecoration.underline, + ), + annotation: pw.AnnotationUrl(link), + ), + ], + ), + ), + ), + ]; + } + + List _steps(CookbookRecipe entry, PdfColor accent, PdfColor tint) { + final steps = entry.recipe.steps; + if (steps.isEmpty) return [pw.SizedBox()]; + final width = (page.format.width - _margin.horizontal) * 0.618 - _s1; + return [ + _subheading(words.steps, accent), + for (final (i, step) in steps.indexed) ...[ + ..._markdown( + step.text, + lead: pw.TextSpan( + text: '${i + 1} ', + style: pw.TextStyle(font: _display, fontSize: _h3, color: accent), + ), + ), + if (step.pictures.any((p) => _image(p.media) != null)) ...[ + _gallery(step.pictures, width), + pw.SizedBox(height: _s2), + ], + if (step.video != null) _video(entry, accent, tint), + pw.SizedBox(height: _s3), + ], + ]; + } + + pw.Widget _video(CookbookRecipe entry, PdfColor accent, PdfColor tint) { + final url = entry.page; + if (url == null) { + return pw.Padding( + padding: pw.EdgeInsets.only(bottom: _s2), + child: pw.Text( + words.videoInNote, + style: pw.TextStyle(fontSize: _small, color: _secondary), + ), + ); + } + final side = _s5 * _phi; + return pw.UrlLink( + destination: url.toString(), + child: pw.Container( + padding: pw.EdgeInsets.all(_s2), + decoration: pw.BoxDecoration( + color: tint, + borderRadius: pw.BorderRadius.circular(_s2), + ), + child: pw.Row( + mainAxisSize: pw.MainAxisSize.min, + children: [ + pw.Container( + color: _background, + padding: pw.EdgeInsets.all(_s1), + child: pw.BarcodeWidget( + data: url.toString(), + barcode: pw.Barcode.qrCode(), + width: side, + height: side, + drawText: false, + color: _text, + ), + ), + pw.SizedBox(width: _s3), + pw.SizedBox( + width: side * _phi, + child: pw.Text( + words.scanForVideo, + style: pw.TextStyle(fontSize: _small, color: accent), + ), + ), + ], + ), + ), + ); + } + + /// Pictures in rows of up to three golden rectangles. + pw.Widget _gallery(List shown, double width) { + final kept = [ + for (final p in shown) + if (_image(p.media) != null) p, + ]; + final across = math.min(3, kept.length); + final gap = _s2; + final side = (width - gap * (across - 1)) / across; + return pw.Wrap( + spacing: gap, + runSpacing: gap, + children: [ + for (final p in kept) + pw.SizedBox( + width: side, + child: pw.Column( + crossAxisAlignment: pw.CrossAxisAlignment.start, + children: [ + pw.ClipRRect( + horizontalRadius: _s1, + verticalRadius: _s1, + child: pw.Image( + _image(p.media)!, + width: side, + height: side / _phi, + fit: pw.BoxFit.cover, + ), + ), + if (p.caption.isNotEmpty) _caption(p.caption), + ], + ), + ), + ], + ); + } + + /// The other fields of the note, as serv.pub shows them after the steps. + List _block(PageBlock block, PdfColor accent) { + final body = switch (block) { + MarkdownBlock(:final text) => _markdown(text), + TextBlock(:final text) => [pw.Text(text)], + TagsBlock(:final items) => [pw.Text(items.join(', '))], + ChecklistBlock(:final items) => [ + for (final item in items) + pw.Text('${item.done ? '☑' : '☐'} ${item.text}'), + ], + LinksBlock(:final items) => [ + for (final link in items) + pw.UrlLink( + destination: link.url, + child: pw.Text( + link.title.isEmpty ? link.url : link.title, + style: pw.TextStyle( + color: accent, + decoration: pw.TextDecoration.underline, + ), + ), + ), + ], + ImageBlock(:final media, :final caption) => [ + if (_image(media) case final image?) + pw.Image( + image, + width: (page.format.width - _margin.horizontal) / _phi, + ), + if (caption.isNotEmpty) _caption(caption), + ], + AudioBlock() => const [], + }; + if (body.isEmpty) return const []; + final short = block is TextBlock && !block.text.contains('\n'); + if (short) { + return [ + pw.SizedBox(height: _s2), + pw.RichText( + text: pw.TextSpan( + children: [ + pw.TextSpan( + text: '${block.label} ', + style: pw.TextStyle(color: _secondary, fontSize: _small), + ), + pw.TextSpan( + text: block.text, + style: pw.TextStyle(fontWeight: pw.FontWeight.bold), + ), + ], + ), + ), + ]; + } + return [ + pw.SizedBox(height: _s4), + _subheading(block.label, accent), + ...body, + ]; + } + + // ------------------------------------------------------------- index + + pw.MultiPage _index( + Map number, + String? Function(CookbookRecipe) numberOf, + ) { + String? letter; + final lines = []; + for (final item in book.ingredients) { + final first = _initial(item.name); + if (first != letter) { + letter = first; + lines.add( + pw.Padding( + padding: pw.EdgeInsets.only(top: _s4, bottom: _s1), + child: pw.Text( + first, + style: pw.TextStyle( + font: _display, + fontSize: _h3, + color: _accent, + ), + ), + ), + ); + } + lines.add( + pw.Padding( + padding: pw.EdgeInsets.only(bottom: _s1), + child: pw.Row( + crossAxisAlignment: pw.CrossAxisAlignment.start, + children: [ + pw.Expanded(flex: 618, child: pw.Text(item.name)), + pw.SizedBox(width: _s3), + pw.Expanded( + flex: 382, + child: pw.Wrap( + spacing: _s2, + children: [ + for (final recipe in item.recipes) + pw.Link( + destination: _anchor(number[recipe]!), + child: pw.Text( + numberOf(recipe) ?? '', + style: pw.TextStyle(color: _secondary), + ), + ), + ], + ), + ), + ], + ), + ), + ); + } + return pw.MultiPage( + pageTheme: _theme(), + maxPages: 1000, + footer: _footer, + build: (context) => [_heading(words.ingredientIndex, _accent), ...lines], + ); + } + + static String _initial(String name) { + final runes = name.trim().runes; + if (runes.isEmpty) return '#'; + final first = String.fromCharCode(runes.first).toUpperCase(); + return RegExp(r'\p{L}', unicode: true).hasMatch(first) ? first : '#'; + } + + // ---------------------------------------------------------- the text + + pw.Widget _heading(String text, PdfColor colour) => pw.Padding( + padding: pw.EdgeInsets.only(bottom: _s4), + child: pw.Text( + text, + style: pw.TextStyle( + font: _display, + fontSize: _h1, + color: colour, + lineSpacing: 0, + ), + ), + ); + + pw.Widget _subheading(String text, PdfColor colour) => pw.Padding( + padding: pw.EdgeInsets.only(bottom: _s3), + child: pw.Text( + text, + style: pw.TextStyle(font: _display, fontSize: _h3, color: colour), + ), + ); + + pw.Widget _caption(String text) => pw.Padding( + padding: pw.EdgeInsets.only(top: _s1), + child: pw.Text( + text, + style: pw.TextStyle(fontSize: _small, color: _secondary), + ), + ); + + /// [source] read by the notes' own Markdown reader: no HTML, no address + /// fetched; a picture in the text is shown only when the book has it. + List _markdown(String source, {pw.InlineSpan? lead}) { + final blocks = MarkdownDocument.parse(source).blocks; + final out = []; + var first = true; + for (final block in blocks) { + out.addAll(_mdBlock(block, first ? lead : null, 0)); + first = false; + } + if (out.isEmpty && lead != null) { + out.add(pw.RichText(text: pw.TextSpan(children: [lead]))); + } + return out; + } + + List _mdBlock(MdBlock block, pw.InlineSpan? lead, int depth) { + final gap = pw.EdgeInsets.only(bottom: _s2, left: _s3 * depth); + pw.Widget paragraph(List inlines, pw.TextStyle? style) => + pw.Padding( + padding: gap, + child: pw.RichText( + text: pw.TextSpan( + style: style, + children: [?lead, ..._inlines(inlines, const pw.TextStyle())], + ), + ), + ); + switch (block) { + case MdHeading(:final level, :final inlines): + return [ + paragraph( + inlines, + pw.TextStyle( + font: _display, + fontSize: level <= 2 ? _h3 : _base, + color: _text, + ), + ), + ]; + case MdParagraph(:final inlines): + final pictures = [ + for (final inline in inlines) + if (inline case MdImage(:final url) when url.startsWith('image:')) + if (_mediaOf(url.substring(6)) case final id?) + if (_image(id) != null) id, + ]; + return [ + if (inlines.any((i) => i is! MdImage) || lead != null) + paragraph(inlines, null), + for (final id in pictures) + pw.Padding( + padding: gap, + child: pw.Image( + _image(id)!, + width: (page.format.width - _margin.horizontal) / _phi, + ), + ), + ]; + case MdList(:final ordered, :final start, :final items): + return [ + if (lead != null) pw.RichText(text: pw.TextSpan(children: [lead])), + for (final (i, item) in items.indexed) ...[ + for (final (j, inner) in item.blocks.indexed) + ..._mdBlock( + inner, + j == 0 + ? pw.TextSpan( + text: switch (item.checked) { + true => '☑ ', + false => '☐ ', + null => ordered ? '${start + i}. ' : '• ', + }, + style: pw.TextStyle(color: _secondary), + ) + : null, + depth + 1, + ), + ], + ]; + case MdQuote(:final blocks): + return [ + pw.Container( + margin: gap, + padding: pw.EdgeInsets.only(left: _s3), + decoration: pw.BoxDecoration( + border: pw.Border(left: pw.BorderSide(color: _accent, width: 2)), + ), + child: pw.Column( + crossAxisAlignment: pw.CrossAxisAlignment.start, + children: [ + for (final inner in blocks) ..._mdBlock(inner, null, 0), + ], + ), + ), + ]; + case MdCodeBlock(:final text): + return [ + pw.Padding( + padding: gap, + child: pw.Text(text, style: pw.TextStyle(color: _secondary)), + ), + ]; + case MdRule(): + return [pw.Divider(color: _secondary, thickness: 0.5)]; + } + } + + List _inlines(List inlines, pw.TextStyle style) => [ + for (final inline in inlines) + switch (inline) { + MdText(:final text) => pw.TextSpan(text: text, style: style), + MdCode(:final text) => pw.TextSpan( + text: text, + style: style.copyWith(color: _secondary), + ), + MdStrong(:final children) => pw.TextSpan( + children: _inlines( + children, + style.copyWith(fontWeight: pw.FontWeight.bold), + ), + ), + MdEmphasis(:final children) => pw.TextSpan( + children: _inlines(children, style.copyWith(color: _secondary)), + ), + MdStrike(:final children) => pw.TextSpan( + children: _inlines( + children, + style.copyWith(decoration: pw.TextDecoration.lineThrough), + ), + ), + MdLink(:final children, :final url) => switch (Uri.tryParse(url)) { + final uri? when uri.isScheme('https') || uri.isScheme('http') => + pw.TextSpan( + children: _inlines( + children, + style.copyWith( + color: _accent, + decoration: pw.TextDecoration.underline, + ), + ), + annotation: pw.AnnotationUrl(uri.toString()), + ), + _ => pw.TextSpan(children: _inlines(children, style)), + }, + // Shown under the paragraph, or by its words alone. + MdImage(:final alt, :final url) => + url.startsWith('image:') && + _mediaOf(url.substring(6)) != null && + _image(_mediaOf(url.substring(6))!) != null + ? const pw.TextSpan(text: '') + : pw.TextSpan( + text: alt, + style: style.copyWith(color: _secondary), + ), + }, + ]; + + MediaId? _mediaOf(String id) { + try { + return MediaId(id); + } on PublishingException { + return null; + } + } + + pw.ImageProvider? _image(MediaId id) => _images.putIfAbsent(id, () { + final bytes = pictures[id]; + if (bytes == null) return null; + try { + return pw.MemoryImage(bytes); + } on Object { + return null; + } + }); + + static String _anchor(int index) => 'recipe-$index'; +} diff --git a/apps/modusnote/lib/cookbook/cookbook_sheet.dart b/apps/modusnote/lib/cookbook/cookbook_sheet.dart new file mode 100644 index 0000000..198cb5b --- /dev/null +++ b/apps/modusnote/lib/cookbook/cookbook_sheet.dart @@ -0,0 +1,282 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:publishing/publishing.dart'; +import 'package:schema_dynamic_content/schema_dynamic_content.dart'; + +import '../backup/file_exchange.dart'; +import '../backup/markdown_export.dart'; +import '../l10n/generated/app_localizations.dart'; +import '../theme/golden_ratio.dart'; +import '../theme/modus_palette.dart'; +import '../vault/auto_lock.dart'; +import 'book_picture.dart'; +import 'cookbook.dart'; +import 'cookbook_epub.dart'; +import 'cookbook_pdf.dart'; +import 'cookbook_words.dart'; + +/// What exporting a cookbook needs from the open vault. +final class CookbookTools { + const CookbookTools({ + required this.files, + required this.collect, + required this.picture, + this.fonts = loadBookFonts, + }); + + final FileExchange files; + + /// The book of a category, in the person's language. + final Future Function(CategoryId root, AppLocalizations l10n) + collect; + + /// A picture of the vault as the book prints it, at most [side] pixels + /// on its longest side; null for a blob that is not a picture. + final Future Function(BlobId blob, int side) picture; + final Future Function() fonts; +} + +/// The book's typefaces, from the app's own files. +Future loadBookFonts() async { + Future read(String name) async { + final data = await rootBundle.load('assets/fonts/book/$name'); + return data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes); + } + + return CookbookFonts( + regular: await read('Inter-Regular.ttf'), + semiBold: await read('Inter-SemiBold.ttf'), + display: await read('PlusJakartaSans-Bold.ttf'), + ); +} + +enum CookbookFormat { pdf, epub } + +/// The sheet that makes a book of the recipes in [root] and its +/// categories: PDF (in three page sizes) or EPUB, with or without the +/// photos, after saying that the file will not be encrypted. +Future showCookbookSheet( + BuildContext context, { + required CategoryId root, + required String name, + required CookbookTools tools, +}) => showModalBottomSheet( + context: context, + showDragHandle: true, + isScrollControlled: true, + builder: (context) => _CookbookSheet(root: root, name: name, tools: tools), +); + +class _CookbookSheet extends StatefulWidget { + const _CookbookSheet({ + required this.root, + required this.name, + required this.tools, + }); + + final CategoryId root; + final String name; + final CookbookTools tools; + + @override + State<_CookbookSheet> createState() => _CookbookSheetState(); +} + +class _CookbookSheetState extends State<_CookbookSheet> { + var _format = CookbookFormat.pdf; + var _page = CookbookPage.golden; + var _pictures = true; + var _working = false; + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context); + final theme = Theme.of(context); + final palette = ModusPalette.of(context); + return SafeArea( + child: SingleChildScrollView( + padding: const EdgeInsets.only( + left: Spacing.l, + right: Spacing.l, + bottom: Spacing.l, + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + l10n.cookbookExportTitle(widget.name), + style: theme.textTheme.titleMedium, + ), + const SizedBox(height: Spacing.m), + Container( + padding: const EdgeInsets.all(Spacing.m), + decoration: BoxDecoration( + color: palette.surface, + borderRadius: BorderRadius.circular(Radii.card), + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon(Icons.lock_open, color: palette.muted), + const SizedBox(width: Spacing.m), + Expanded(child: Text(l10n.cookbookWarning)), + ], + ), + ), + const SizedBox(height: Spacing.l), + SegmentedButton( + key: const ValueKey('cookbook-format'), + segments: [ + ButtonSegment( + value: CookbookFormat.pdf, + icon: const Icon(Icons.print_outlined), + label: Text(l10n.cookbookPdf), + ), + ButtonSegment( + value: CookbookFormat.epub, + icon: const Icon(Icons.menu_book_outlined), + label: Text(l10n.cookbookEpub), + ), + ], + selected: {_format}, + onSelectionChanged: _working + ? null + : (chosen) => setState(() => _format = chosen.single), + ), + if (_format == CookbookFormat.pdf) ...[ + const SizedBox(height: Spacing.l), + Text(l10n.cookbookPageSize, style: theme.textTheme.labelLarge), + const SizedBox(height: Spacing.s), + SegmentedButton( + key: const ValueKey('cookbook-page'), + segments: [ + for (final page in CookbookPage.values) + ButtonSegment( + value: page, + label: Text(switch (page) { + CookbookPage.golden => l10n.cookbookGolden, + CookbookPage.a5 => 'A5', + CookbookPage.a4 => 'A4', + }), + ), + ], + selected: {_page}, + onSelectionChanged: _working + ? null + : (chosen) => setState(() => _page = chosen.single), + ), + ], + const SizedBox(height: Spacing.m), + SwitchListTile( + key: const ValueKey('cookbook-pictures'), + contentPadding: EdgeInsets.zero, + title: Text(l10n.cookbookPictures), + value: _pictures, + onChanged: _working + ? null + : (value) => setState(() => _pictures = value), + ), + const SizedBox(height: Spacing.m), + FilledButton.icon( + key: const ValueKey('cookbook-export'), + onPressed: _working ? null : _export, + icon: _working + ? const SizedBox.square( + dimension: Spacing.l, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.save_alt), + label: Text( + _working ? l10n.cookbookWorking : l10n.cookbookAction, + ), + ), + ], + ), + ), + ); + } + + Future _export() async { + final l10n = AppLocalizations.of(context); + final messenger = ScaffoldMessenger.of(context); + final navigator = Navigator.of(context); + final lang = Localizations.localeOf(context).languageCode; + final release = AutoLockScope.maybeOf(context)?.hold(); + setState(() => _working = true); + try { + final book = await widget.tools.collect(widget.root, l10n); + if (book.isEmpty) { + messenger.showSnackBar(SnackBar(content: Text(l10n.cookbookEmpty))); + return; + } + final pictures = _pictures + ? await _picturesOf(book) + : const {}; + final words = CookbookWords.of(l10n); + final stem = MarkdownExport.safeName(widget.name, fallback: 'ricette'); + final Uint8List bytes; + final String file; + final String type; + switch (_format) { + case CookbookFormat.pdf: + final fonts = await widget.tools.fonts(); + bytes = await compute( + _renderPdf, + CookbookPdf( + book: book, + words: words, + fonts: fonts, + pictures: pictures, + page: _page, + lang: lang, + ), + ); + file = '$stem.pdf'; + type = 'application/pdf'; + case CookbookFormat.epub: + bytes = CookbookEpub( + book: book, + words: words, + pictures: pictures, + lang: lang, + ).render(at: DateTime.now()); + file = '$stem.epub'; + type = 'application/epub+zip'; + } + await widget.tools.files.save(file, type, bytes); + navigator.pop(); + messenger.showSnackBar(SnackBar(content: Text(l10n.cookbookSaved))); + } on CookbookTooLargeException { + messenger.showSnackBar(SnackBar(content: Text(l10n.cookbookTooLarge))); + } on Object catch (error, stack) { + FlutterError.reportError( + FlutterErrorDetails(exception: error, stack: stack), + ); + messenger.showSnackBar(SnackBar(content: Text(l10n.cookbookFailed))); + } finally { + release?.call(); + if (mounted) setState(() => _working = false); + } + } + + /// Every picture the book shows, opened and made again one at a time: + /// the opening photos larger than the others. + Future> _picturesOf(Cookbook book) async { + final out = {}; + for (final recipe in book.recipes) { + final opening = {for (final p in recipe.recipe.cover) p.media}; + for (final MapEntry(key: id, value: blob) in recipe.media.entries) { + final side = opening.contains(id) ? bookPhotoSide : bookPictureSide; + if (await widget.tools.picture(blob, side) case final bytes?) { + out[id] = bytes; + } + } + } + return out; + } +} + +Future _renderPdf(CookbookPdf pdf) => pdf.render(); diff --git a/apps/modusnote/lib/cookbook/cookbook_words.dart b/apps/modusnote/lib/cookbook/cookbook_words.dart new file mode 100644 index 0000000..be3cfd9 --- /dev/null +++ b/apps/modusnote/lib/cookbook/cookbook_words.dart @@ -0,0 +1,122 @@ +import 'package:publishing/publishing.dart'; + +import '../l10n/generated/app_localizations.dart'; +import '../notes/recipes/recipe_text.dart'; + +/// The words a cookbook prints that are not the person's own. +final class CookbookWords { + const CookbookWords({ + required this.contents, + required this.ingredientIndex, + required this.ingredients, + required this.steps, + required this.prep, + required this.cook, + required this.rest, + required this.total, + required this.difficulty, + required this.scanForVideo, + required this.watchVideo, + required this.videoInNote, + required this.madeWith, + required this.recipeCount, + required this.servings, + required this.minutes, + required this.amount, + }); + + factory CookbookWords.of(AppLocalizations l10n) { + final text = RecipeText(l10n); + return CookbookWords( + contents: l10n.cookbookContents, + ingredientIndex: l10n.cookbookIngredientIndex, + ingredients: l10n.cookingIngredients, + steps: l10n.cookbookSteps, + prep: l10n.cookbookPrep, + cook: l10n.cookbookCook, + rest: l10n.cookbookRest, + total: l10n.cookbookTotal, + difficulty: l10n.cookbookDifficulty, + scanForVideo: l10n.cookbookScanForVideo, + watchVideo: l10n.cookbookWatchVideo, + videoInNote: l10n.cookbookVideoInNote, + madeWith: l10n.cookbookMadeWith, + recipeCount: l10n.cookbookRecipeCount, + servings: l10n.cookingServings, + minutes: text.minutes, + amount: text.amount, + ); + } + + /// Words a test can read. + static final plain = CookbookWords( + contents: 'Contents', + ingredientIndex: 'Index of ingredients', + ingredients: 'Ingredients', + steps: 'Method', + prep: 'Prep', + cook: 'Cook', + rest: 'Rest', + total: 'Total', + difficulty: 'Difficulty', + scanForVideo: 'Scan to watch the video', + watchVideo: 'Watch the video', + videoInNote: 'Video in the note', + madeWith: 'Made with Modus Notes', + recipeCount: (n) => n == 1 ? '1 recipe' : '$n recipes', + servings: (n) => n == 1 ? '1 serving' : '$n servings', + minutes: (m) => '$m min', + amount: (n) => '$n', + ); + + final String contents; + final String ingredientIndex; + final String ingredients; + final String steps; + final String prep; + final String cook; + final String rest; + final String total; + final String difficulty; + final String scanForVideo; + final String watchVideo; + final String videoInNote; + final String madeWith; + final String Function(int count) recipeCount; + final String Function(int count) servings; + final String Function(int minutes) minutes; + final String Function(num amount) amount; + + /// How much of [item]: «250 g», «2 cucchiai», «q.b.»; empty when the + /// recipe says nothing. + String quantity(RecipeIngredient item) { + final measured = switch ((item.amount, item.unit)) { + (final amount?, _?) => + '${this.amount(amount)} ${amount == 1 ? item.one : item.other}'.trim(), + (final amount?, null) => this.amount(amount), + _ => '', + }; + return [ + measured, + item.quantity.trim(), + ].where((part) => part.isNotEmpty).join(', '); + } + + /// The times of [recipe], each with its label, and their sum. + List<(String, String)> times(PageRecipe recipe) { + final parts = [ + (prep, recipe.prep), + (cook, recipe.cook), + (rest, recipe.rest), + ]; + final given = [ + for (final (label, value) in parts) + if (value != null && value > 0) (label, value), + ]; + return [ + for (final (label, value) in given) (label, minutes(value)), + if (given.length > 1) + (total, minutes(given.fold(0, (sum, part) => sum + part.$2))), + ]; + } +} diff --git a/apps/modusnote/lib/l10n/app_en.arb b/apps/modusnote/lib/l10n/app_en.arb index 1e168cd..77e0fa5 100644 --- a/apps/modusnote/lib/l10n/app_en.arb +++ b/apps/modusnote/lib/l10n/app_en.arb @@ -3037,5 +3037,123 @@ "stepTimerDone": "Time is up", "@stepTimerDone": { "description": "Shown when a step timer ends." + }, + "cookbookContents": "Contents", + "@cookbookContents": { + "description": "The heading of a cookbook's table of contents." + }, + "cookbookIngredientIndex": "Index of ingredients", + "@cookbookIngredientIndex": { + "description": "The heading of the index of ingredients at the end of a cookbook." + }, + "cookbookSteps": "Method", + "@cookbookSteps": { + "description": "The heading of a recipe's steps in a cookbook." + }, + "cookbookPrep": "Prep", + "@cookbookPrep": { + "description": "Label of the preparation time in a cookbook." + }, + "cookbookCook": "Cook", + "@cookbookCook": { + "description": "Label of the cooking time in a cookbook." + }, + "cookbookRest": "Rest", + "@cookbookRest": { + "description": "Label of the resting time in a cookbook." + }, + "cookbookTotal": "Total", + "@cookbookTotal": { + "description": "Label of the total time in a cookbook." + }, + "cookbookDifficulty": "Difficulty", + "@cookbookDifficulty": { + "description": "Label of a recipe's difficulty in a cookbook." + }, + "cookbookScanForVideo": "Scan the code to watch the video", + "@cookbookScanForVideo": { + "description": "Caption under the QR code of a step's video in a printed cookbook." + }, + "cookbookVideoInNote": "This step's video is in the note", + "@cookbookVideoInNote": { + "description": "Printed where a step has a video that is not published." + }, + "cookbookMadeWith": "Made with Modus Notes", + "@cookbookMadeWith": { + "description": "The line on a cookbook's cover." + }, + "cookbookExport": "Export the cookbook", + "@cookbookExport": { + "description": "Button that makes a book of the recipes in a category." + }, + "cookbookExportTitle": "Export «{name}» as a book", + "@cookbookExportTitle": { + "description": "Title of the cookbook export sheet.", + "placeholders": { + "name": { + "type": "String" + } + } + }, + "cookbookWarning": "The file is not encrypted: whoever gets it reads every recipe, photos included. It is made on this device, without going through the server.", + "@cookbookWarning": { + "description": "Warning before a cookbook export." + }, + "cookbookPdf": "PDF, to print", + "@cookbookPdf": { + "description": "Format choice." + }, + "cookbookEpub": "EPUB, for e-readers", + "@cookbookEpub": { + "description": "Format choice." + }, + "cookbookPageSize": "Page size", + "@cookbookPageSize": { + "description": "Label of the page size choice." + }, + "cookbookGolden": "Golden", + "@cookbookGolden": { + "description": "Page size of golden proportion, 144 × 233 mm." + }, + "cookbookAction": "Export", + "@cookbookAction": { + "description": "Button that makes the cookbook file." + }, + "cookbookWorking": "Making the book…", + "@cookbookWorking": { + "description": "Shown while the cookbook is made." + }, + "cookbookSaved": "Cookbook exported", + "@cookbookSaved": { + "description": "Shown when the file is saved." + }, + "cookbookEmpty": "There are no recipes in this category.", + "@cookbookEmpty": { + "description": "Shown when a category has no recipes to export." + }, + "cookbookTooLarge": "Too many recipes for one book: export a smaller category.", + "@cookbookTooLarge": { + "description": "Shown past the most recipes in a book." + }, + "cookbookFailed": "The book could not be made.", + "@cookbookFailed": { + "description": "Shown when the export fails." + }, + "cookbookPictures": "With the photos", + "@cookbookPictures": { + "description": "Switch that puts the photos in the book." + }, + "cookbookRecipeCount": "{count, plural, =1{1 recipe} other{{count} recipes}}", + "@cookbookRecipeCount": { + "description": "How many recipes a cookbook holds.", + "placeholders": { + "count": { + "type": "int" + } + } + }, + "cookbookWatchVideo": "Watch the video", + "@cookbookWatchVideo": { + "description": "Link to a step's video on its published page, in an ebook." } } diff --git a/apps/modusnote/lib/l10n/app_it.arb b/apps/modusnote/lib/l10n/app_it.arb index 7176ae5..72570e3 100644 --- a/apps/modusnote/lib/l10n/app_it.arb +++ b/apps/modusnote/lib/l10n/app_it.arb @@ -724,5 +724,32 @@ "stepTimerMinutes": "Minuti", "stepTimerStart": "Avvia", "stepTimerStop": "Ferma il timer", - "stepTimerDone": "Tempo scaduto" + "stepTimerDone": "Tempo scaduto", + "cookbookContents": "Indice", + "cookbookIngredientIndex": "Indice degli ingredienti", + "cookbookSteps": "Preparazione", + "cookbookPrep": "Preparazione", + "cookbookCook": "Cottura", + "cookbookRest": "Riposo", + "cookbookTotal": "Totale", + "cookbookDifficulty": "Difficoltà", + "cookbookScanForVideo": "Inquadra il codice per guardare il video", + "cookbookVideoInNote": "Il video di questa fase è nella nota", + "cookbookMadeWith": "Fatto con Modus Notes", + "cookbookExport": "Esporta il ricettario", + "cookbookExportTitle": "Esporta «{name}» come libro", + "cookbookWarning": "Il file non è cifrato: chi lo riceve legge tutte le ricette, con le foto. Viene creato su questo dispositivo, senza passare dal server.", + "cookbookPdf": "PDF, da stampare", + "cookbookEpub": "EPUB, per i lettori di ebook", + "cookbookPageSize": "Formato della pagina", + "cookbookGolden": "Aureo", + "cookbookAction": "Esporta", + "cookbookWorking": "Preparo il libro…", + "cookbookSaved": "Ricettario esportato", + "cookbookEmpty": "In questa categoria non ci sono ricette.", + "cookbookTooLarge": "Troppe ricette per un solo libro: esporta una categoria più piccola.", + "cookbookFailed": "Non sono riuscito a creare il libro.", + "cookbookPictures": "Con le foto", + "cookbookRecipeCount": "{count, plural, =1{1 ricetta} other{{count} ricette}}", + "cookbookWatchVideo": "Guarda il video" } diff --git a/apps/modusnote/lib/notes/note_library.dart b/apps/modusnote/lib/notes/note_library.dart index 3530d71..e23c759 100644 --- a/apps/modusnote/lib/notes/note_library.dart +++ b/apps/modusnote/lib/notes/note_library.dart @@ -45,6 +45,7 @@ class NoteLibraryScreen extends StatefulWidget { this.onPasskey, this.passkeyLabel, this.onBackup, + this.onCookbook, this.onNotices, this.journalSettings, this.noteTypes, @@ -77,6 +78,10 @@ class NoteLibraryScreen extends StatefulWidget { /// saved and picked. final VoidCallback? onBackup; + /// Makes a book of the recipes in a category and the ones inside it; + /// null where files cannot be saved. + final void Function(CategoryId category, String name)? onCookbook; + /// Opens the vault's notices, from the command palette; null where the /// vault has none (no server). final VoidCallback? onNotices; @@ -660,6 +665,15 @@ class _NoteLibraryScreenState extends State { tooltip: l10n.appearance, icon: const Icon(Icons.palette_outlined), ), + if ((widget.onCookbook, _selected) case (final onCookbook?, final at?) + when _holdsRecipes(at)) + IconButton( + key: const ValueKey('cookbook-export'), + onPressed: () => + onCookbook(at, widget.store.categories[at]?.name.value ?? ''), + tooltip: l10n.cookbookExport, + icon: const Icon(Icons.menu_book_outlined), + ), if (widget.onBackup case final onBackup?) IconButton( onPressed: onBackup, @@ -680,6 +694,17 @@ class _NoteLibraryScreenState extends State { ), ]; + /// Whether a recipe is filed in [category] or in one inside it. + bool _holdsRecipes(CategoryId category) { + final store = widget.store; + final inside = store.categories.subtree(category); + return store.entries.any( + (entry) => + entry.schemaId.name == Recipe.schema && + inside.contains(store.categoryOf(entry.id)), + ); + } + Widget _searchField(AppLocalizations l10n) => TextField( decoration: InputDecoration( hintText: l10n.searchHint, diff --git a/apps/modusnote/lib/publishing/field_description.dart b/apps/modusnote/lib/publishing/field_description.dart new file mode 100644 index 0000000..7efce6a --- /dev/null +++ b/apps/modusnote/lib/publishing/field_description.dart @@ -0,0 +1,37 @@ +import 'package:intl/intl.dart'; +import 'package:schema_dynamic_content/schema_dynamic_content.dart'; + +import '../notes/schema_text.dart'; + +/// [value] of [field] as a published page or a printed book shows it, in +/// [locale]; empty for a value they show in a block of its own. +String describeField( + SchemaText texts, + String locale, + FieldDefinition field, + FieldValue value, +) => switch (value) { + NumberValue(:final number) => NumberFormat.decimalPattern( + locale, + ).format(number), + DateValue(:final year, :final month, :final day) => DateFormat.yMMMMd( + locale, + ).format(DateTime(year, month, day)), + DateTimeValue(:final instant) => DateFormat.yMMMMd( + locale, + ).add_Hm().format(instant.toLocal()), + BooleanValue(value: final yes) => yes ? '✓' : '✗', + RatingValue(:final rating) => switch (field.type) { + RatingFieldType(:final max) => '${'★' * rating}${'☆' * (max - rating)}', + _ => '$rating', + }, + ChoiceValue(:final option) => texts.option(field, option), + ChoiceSetValue(:final options) => [ + for (final option in switch (field.type) { + ChoiceSetFieldType(options: final all) => all.where(options.contains), + _ => options, + }) + texts.option(field, option), + ].join(', '), + _ => '', +}; diff --git a/apps/modusnote/lib/publishing/publish_sheet.dart b/apps/modusnote/lib/publishing/publish_sheet.dart index be64391..5ffc472 100644 --- a/apps/modusnote/lib/publishing/publish_sheet.dart +++ b/apps/modusnote/lib/publishing/publish_sheet.dart @@ -1,6 +1,5 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; -import 'package:intl/intl.dart'; import 'package:publishing/publishing.dart'; import 'package:schema_dynamic_content/schema_dynamic_content.dart'; @@ -10,6 +9,7 @@ import '../notes/recipes/recipe_text.dart'; import '../notes/schema_text.dart'; import '../theme/golden_ratio.dart'; import '../theme/modus_palette.dart'; +import 'field_description.dart'; import 'site_settings_sheet.dart'; /// What the notes need to publish: the vault's [Publisher] and the way to @@ -228,7 +228,7 @@ class _PublishSheetState extends State { content: content, schema: widget.schema, labelOf: (field) => texts.label(field.label), - describe: (field, value) => _describe(texts, locale, field, value), + describe: (field, value) => describeField(texts, locale, field, value), ingredientLine: recipes.line, recipeWords: words, draft: !listed, @@ -257,37 +257,6 @@ class _PublishSheetState extends State { ); }); - static String _describe( - SchemaText texts, - String locale, - FieldDefinition field, - FieldValue value, - ) => switch (value) { - NumberValue(:final number) => NumberFormat.decimalPattern( - locale, - ).format(number), - DateValue(:final year, :final month, :final day) => DateFormat.yMMMMd( - locale, - ).format(DateTime(year, month, day)), - DateTimeValue(:final instant) => DateFormat.yMMMMd( - locale, - ).add_Hm().format(instant.toLocal()), - BooleanValue(value: final yes) => yes ? '✓' : '✗', - RatingValue(:final rating) => switch (field.type) { - RatingFieldType(:final max) => '${'★' * rating}${'☆' * (max - rating)}', - _ => '$rating', - }, - ChoiceValue(:final option) => texts.option(field, option), - ChoiceSetValue(:final options) => [ - for (final option in switch (field.type) { - ChoiceSetFieldType(options: final all) => all.where(options.contains), - _ => options, - }) - texts.option(field, option), - ].join(', '), - _ => '', - }; - @override Widget build(BuildContext context) { final l10n = AppLocalizations.of(context); diff --git a/apps/modusnote/lib/vault/vault_gate.dart b/apps/modusnote/lib/vault/vault_gate.dart index 8fec123..77afb7a 100644 --- a/apps/modusnote/lib/vault/vault_gate.dart +++ b/apps/modusnote/lib/vault/vault_gate.dart @@ -14,6 +14,10 @@ import '../attachments/note_images.dart'; import '../backup/backup_sheet.dart'; import '../backup/file_exchange.dart'; import '../backup/markdown_export.dart'; +import '../cookbook/book_picture.dart'; +import '../cookbook/cookbook.dart'; +import '../cookbook/cookbook_pages.dart'; +import '../cookbook/cookbook_sheet.dart'; import '../audio/note_playback.dart'; import '../audio/note_recorder.dart'; import '../appearance/appearance_scope.dart'; @@ -843,6 +847,59 @@ class _VaultGateState extends State with WidgetsBindingObserver { } } + /// Makes a book of the recipes in [category] of the open vault, after + /// the passphrase: the file is in clear. + Future _cookbook(CategoryId category, String name) async { + final files = widget.files; + if (files == null) return; + if (_stage case _Open(:final store, :final publishing)) { + if (!await _confirmed()) return; + if (!mounted) return; + final locale = Localizations.localeOf(context).toLanguageTag(); + await showCookbookSheet( + context, + root: category, + name: name, + tools: CookbookTools( + files: files, + collect: (root, l10n) async { + final site = await publishing?.publisher.book(); + return Cookbook.collect( + tree: store.categories, + root: root, + entries: store.entries, + categoryOf: store.categoryOf, + compose: CookbookPages( + schemas: widget.catalog.current, + texts: SchemaText(l10n), + recipes: RecipeText(l10n), + locale: locale, + site: site, + ).compose, + palette: SitePalette.of( + SiteTheme( + BaseTheme.fresco, + accentHue: site?.settings.theme.accentHue, + ), + ), + ); + }, + picture: (blob, side) async { + final image = store.imageOf(blob); + final images = store.images; + if (image == null || images == null) return null; + final original = await images.open(image); + try { + return await bookPicture(original, side: side); + } finally { + original.fillRange(0, original.length, 0); + } + }, + ), + ); + } + } + /// Sets up or turns off the passkey of the open vault. Future _passkeySettings() async { final keeper = widget.keeper; @@ -1028,6 +1085,7 @@ class _VaultGateState extends State with WidgetsBindingObserver { onNotices: notices == null ? null : _showNotices, onLock: _lock, onBackup: widget.files == null ? null : _backup, + onCookbook: widget.files == null ? null : _cookbook, onPasskey: widget.keeper.offersPasskeys ? _passkeySettings : null, passkeyLabel: widget.secondFactor.settings( AppLocalizations.of(context), diff --git a/apps/modusnote/pubspec.yaml b/apps/modusnote/pubspec.yaml index b6041a9..241ef3a 100644 --- a/apps/modusnote/pubspec.yaml +++ b/apps/modusnote/pubspec.yaml @@ -34,6 +34,9 @@ dependencies: flutter_local_notifications: 22.3.2 timezone: ^0.11.0 video_player: ^2.14.1 + pdf: ^3.13.1 + file_picker: ^13.3.1 + image: ^4.12.0 dev_dependencies: crypto: ^3.0.7 @@ -51,6 +54,8 @@ flutter: # they are plain assets: a font in `fonts:` is fetched at every start # of the web client. - assets/fonts/reading/ + # The cookbook's typefaces, loaded only to print one. + - assets/fonts/book/ fonts: - family: PlusJakartaSans fonts: diff --git a/apps/modusnote/test/backup/markdown_export_test.dart b/apps/modusnote/test/backup/markdown_export_test.dart index 65df79a..d007d17 100644 --- a/apps/modusnote/test/backup/markdown_export_test.dart +++ b/apps/modusnote/test/backup/markdown_export_test.dart @@ -23,14 +23,21 @@ DynamicEntry entry( Invalid(:final violations) => throw StateError('$violations'), }; -/// Reads back what [ZipWriter] wrote, checking every header and CRC. -Map unzip(Uint8List zip) { +/// Reads back what [ZipWriter] wrote, as text. +Map unzip(Uint8List zip) => { + for (final MapEntry(:key, :value) in unzipBytes(zip).entries) + key: utf8.decode(value), +}; + +/// Reads back what [ZipWriter] wrote, checking every header and CRC, in +/// the order of the archive. +Map unzipBytes(Uint8List zip) { final data = ByteData.sublistView(zip); final end = zip.length - 22; expect(data.getUint32(end, Endian.little), 0x06054b50); final count = data.getUint16(end + 10, Endian.little); var at = data.getUint32(end + 16, Endian.little); - final files = {}; + final files = {}; for (var i = 0; i < count; i++) { expect(data.getUint32(at, Endian.little), 0x02014b50); expect(data.getUint16(at + 8, Endian.little), 1 << 11, reason: 'UTF-8'); @@ -43,7 +50,7 @@ Map unzip(Uint8List zip) { final start = local + 30 + data.getUint16(local + 26, Endian.little); final body = zip.sublist(start, start + size); expect(ZipWriter.crc32(body), crc, reason: name); - files[name] = utf8.decode(body); + files[name] = body; at += 46 + nameLength; } return files; diff --git a/apps/modusnote/test/cookbook/cookbook_sheet_test.dart b/apps/modusnote/test/cookbook/cookbook_sheet_test.dart new file mode 100644 index 0000000..888bccd --- /dev/null +++ b/apps/modusnote/test/cookbook/cookbook_sheet_test.dart @@ -0,0 +1,149 @@ +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:modusnote/cookbook/cookbook.dart'; +import 'package:modusnote/cookbook/cookbook_pages.dart'; +import 'package:modusnote/cookbook/cookbook_sheet.dart'; +import 'package:modusnote/notes/recipes/recipe_text.dart'; +import 'package:modusnote/notes/schema_text.dart'; +import 'package:publishing/publishing.dart'; +import 'package:schema_dynamic_content/schema_dynamic_content.dart'; + +import '../backup/backup_sheet_test.dart' show FakeFiles; +import '../notes/harness.dart'; +import 'cookbook_test.dart' show fonts, jpeg, recipe; + +void main() { + final root = CategoryId('r' * 32); + final tree = CategoryTree([ + NoteCategory(id: root, name: CategoryName('Cucina sarda')), + ]); + final photo = BlobId('c' * 32); + final seadas = recipe('b', { + 'title': const TextValue('Seadas'), + 'photos': AttachmentsValue([ImageAttachment(photo)]), + 'ingredients': IngredientsValue([Ingredient('Miele', quantity: 'q.b.')]), + }); + + late FakeFiles files; + late List<(BlobId, int)> asked; + late List collected; + + CookbookTools tools({List? entries}) => CookbookTools( + files: files, + collect: (root, l10n) async { + collected.add(root); + return Cookbook.collect( + tree: tree, + root: root, + entries: entries ?? [seadas], + categoryOf: (_) => root, + compose: CookbookPages( + schemas: [SeedSchemas.recipeV1], + texts: SchemaText(l10n), + recipes: RecipeText(l10n), + locale: 'it', + ).compose, + palette: SitePalette.of(const SiteTheme(BaseTheme.fresco)), + ); + }, + picture: (blob, side) async { + asked.add((blob, side)); + return jpeg(60, 37, 200, 120, 40); + }, + fonts: () async => fonts(), + ); + + setUp(() { + files = FakeFiles(); + asked = []; + collected = []; + }); + + Future open(WidgetTester tester, CookbookTools tools) async { + await pumpApp( + tester, + Builder( + builder: (context) => Scaffold( + body: Center( + child: TextButton( + onPressed: () => showCookbookSheet( + context, + root: root, + name: 'Cucina sarda', + tools: tools, + ), + child: const Text('apri'), + ), + ), + ), + ), + ); + await tester.tap(find.text('apri')); + await tester.pumpAndSettle(); + } + + Future export(WidgetTester tester) async { + final button = find.byKey(const ValueKey('cookbook-export')); + await tester.ensureVisible(button); + await tester.tap(button); + // The work runs off the test's fake clock. + for (var i = 0; i < 50 && files.saved.isEmpty; i++) { + await tester.runAsync( + () => Future.delayed(const Duration(milliseconds: 100)), + ); + await tester.pump(); + } + await tester.pumpAndSettle(); + } + + testWidgets('warns that the file is in clear, then saves a PDF', ( + tester, + ) async { + await open(tester, tools()); + expect(find.textContaining('non è cifrato'), findsOneWidget); + expect(find.text('Aureo'), findsOneWidget); + + await export(tester); + + expect(collected, [root]); + expect(files.saved.keys.single, 'Cucina sarda.pdf'); + expect(String.fromCharCodes(files.saved.values.single.take(5)), '%PDF-'); + // The opening photo, at its own size. + expect(asked.single.$2, 987); + expect(find.text('Ricettario esportato'), findsOneWidget); + }); + + testWidgets('an EPUB, without the photos when asked', (tester) async { + await open(tester, tools()); + await tester.tap(find.text('EPUB, per i lettori di ebook')); + await tester.pumpAndSettle(); + expect(find.text('Aureo'), findsNothing); + await tester.tap(find.byKey(const ValueKey('cookbook-pictures'))); + await tester.pumpAndSettle(); + + await export(tester); + + expect(files.saved.keys.single, 'Cucina sarda.epub'); + final bytes = files.saved.values.single; + expect( + String.fromCharCodes(Uint8List.sublistView(bytes, 30, 38)), + 'mimetype', + ); + expect(asked, isEmpty); + }); + + testWidgets('a category without recipes says so and saves nothing', ( + tester, + ) async { + await open(tester, tools(entries: const [])); + await export(tester); + expect(collected, [root]); + expect( + find.text('In questa categoria non ci sono ricette.'), + findsOneWidget, + ); + expect(files.saved, isEmpty); + }); +} diff --git a/apps/modusnote/test/cookbook/cookbook_test.dart b/apps/modusnote/test/cookbook/cookbook_test.dart new file mode 100644 index 0000000..fa29192 --- /dev/null +++ b/apps/modusnote/test/cookbook/cookbook_test.dart @@ -0,0 +1,367 @@ +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; + +import '../backup/markdown_export_test.dart' show unzipBytes; + +import 'package:image/image.dart' as img; +import 'package:modusnote/cookbook/book_picture.dart'; +import 'package:modusnote/cookbook/cookbook.dart'; +import 'package:modusnote/cookbook/cookbook_epub.dart'; +import 'package:modusnote/cookbook/cookbook_pages.dart'; +import 'package:modusnote/cookbook/cookbook_pdf.dart'; +import 'package:modusnote/cookbook/cookbook_words.dart'; +import 'package:modusnote/l10n/generated/app_localizations_it.dart'; +import 'package:modusnote/notes/recipes/recipe_text.dart'; +import 'package:modusnote/notes/schema_text.dart'; +import 'package:publishing/publishing.dart'; +import 'package:schema_dynamic_content/schema_dynamic_content.dart'; + +DynamicEntry recipe(String id, Map attributes) => + switch (DynamicEntry.create( + schema: SeedSchemas.recipeV1, + id: EntryId(id.padRight(32, '0')), + attributes: { + for (final e in attributes.entries) FieldKey(e.key): e.value, + }, + at: DateTime.utc(2026, 11, 1, 9), + )) { + Valid(:final value) => value, + Invalid(:final violations) => throw StateError('$violations'), + }; + +/// A plain JPEG of [width] × [height] in one colour. +Uint8List jpeg(int width, int height, int r, int g, int b) { + final image = img.Image(width: width, height: height); + img.fill(image, color: img.ColorRgb8(r, g, b)); + return img.encodeJpg(image, quality: 80); +} + +final l10n = AppLocalizationsIt(); + +CookbookFonts fonts() { + Uint8List read(String name) => + File('assets/fonts/book/$name').readAsBytesSync(); + return CookbookFonts( + regular: read('Inter-Regular.ttf'), + semiBold: read('Inter-SemiBold.ttf'), + display: read('PlusJakartaSans-Bold.ttf'), + ); +} + +void main() { + final root = CategoryId('r' * 32); + final primi = CategoryId('p' * 32); + final dolci = CategoryId('d' * 32); + final elsewhere = CategoryId('x' * 32); + final tree = CategoryTree([ + NoteCategory(id: root, name: CategoryName('Cucina sarda')), + NoteCategory(id: primi, name: CategoryName('Primi'), parent: root), + NoteCategory(id: dolci, name: CategoryName('Dolci'), parent: root), + NoteCategory(id: elsewhere, name: CategoryName('Lavoro')), + ]); + final cover = BlobId('c' * 32); + final step = BlobId('s' * 32); + + final malloreddus = recipe('a', { + 'title': const TextValue('Malloreddus alla campidanese'), + 'description': const TextValue( + 'Gnocchetti di semola con **salsiccia** e zafferano.', + ), + 'photos': AttachmentsValue([ImageAttachment(cover, caption: 'Il piatto')]), + 'servings': NumberValue(4), + 'prep_time': NumberValue(30), + 'cook_time': NumberValue(40), + 'difficulty': const RatingValue(2), + 'methods': ChoiceSetValue({'stovetop'}), + 'ingredients': IngredientsValue([ + Ingredient('Malloreddus', amount: 400, unit: IngredientUnit.gram), + Ingredient('Salsiccia fresca', amount: 300, unit: IngredientUnit.gram), + Ingredient('Pecorino sardo', quantity: 'q.b.'), + Ingredient( + 'Zafferano', + amount: 1, + unit: IngredientUnit.pinch, + link: WebLink('https://example.org/zafferano'), + ), + ]), + 'steps': StepsValue([ + PreparationStep( + 'Rosola la salsiccia sbriciolata.', + pictures: [ImageAttachment(step, caption: 'Dorata')], + ), + PreparationStep( + 'Aggiungi il pomodoro e cuoci 40 minuti.', + video: BlobId('v' * 32), + ), + PreparationStep('Scola la pasta e condisci con il [sugo](note:abc).'), + ]), + 'tags': TagListValue({'domenica'}), + }); + final seadas = recipe('b', { + 'title': const TextValue('Seadas'), + 'ingredients': IngredientsValue([ + Ingredient('Pecorino sardo', amount: 200, unit: IngredientUnit.gram), + Ingredient('Miele', quantity: 'q.b.'), + ]), + 'steps': StepsValue([PreparationStep('Friggi e copri di miele.')]), + }); + final culurgiones = recipe('c', { + 'title': const TextValue('Culurgiones'), + 'ingredients': IngredientsValue([Ingredient('patate', amount: 1)]), + }); + final pane = recipe('d', {'title': const TextValue('Pane carasau')}); + final other = recipe('e', {'title': const TextValue('Fuori dal libro')}); + + final filed = { + malloreddus.id: primi, + culurgiones.id: primi, + seadas.id: dolci, + pane.id: root, + other.id: elsewhere, + }; + + Cookbook collect({SiteBook? site}) => Cookbook.collect( + tree: tree, + root: root, + entries: [malloreddus, seadas, culurgiones, pane, other], + categoryOf: (id) => filed[id], + compose: CookbookPages( + schemas: [SeedSchemas.recipeV1], + texts: SchemaText(l10n), + recipes: RecipeText(l10n), + locale: 'it', + site: site, + ).compose, + palette: SitePalette.of(const SiteTheme(BaseTheme.fresco)), + ); + + group('Cookbook', () { + test('a chapter per category, recipes by title, nothing from outside', () { + final book = collect(); + expect(book.title, 'Cucina sarda'); + expect( + [for (final c in book.chapters) c.path], + [ + [], + ['Dolci'], + ['Primi'], + ], + ); + expect( + [ + for (final c in book.chapters) [for (final r in c.recipes) r.title], + ], + [ + ['Pane carasau'], + ['Seadas'], + ['Culurgiones', 'Malloreddus alla campidanese'], + ], + ); + // Each chapter its colour, as on serv.pub. + final palette = SitePalette.of(const SiteTheme(BaseTheme.fresco)); + for (final (i, c) in book.chapters.indexed) { + expect(c.colours, CategoryColours.of(palette, i)); + } + }); + + test('the index merges ingredients written alike, in book order', () { + final book = collect(); + final index = { + for (final i in book.ingredients) + i.name: [for (final r in i.recipes) r.title], + }; + expect(index.keys, [ + 'Malloreddus', + 'Miele', + 'patate', + 'Pecorino sardo', + 'Salsiccia fresca', + 'Zafferano', + ]); + expect(index['Pecorino sardo'], [ + 'Seadas', + 'Malloreddus alla campidanese', + ]); + }); + + test('the page is the one serv.pub would show, without vault ids', () { + final book = collect(); + final page = book.recipes.last; + final r = page.recipe; + expect(r.description, contains('**salsiccia**')); + expect(r.cover.single.caption, 'Il piatto'); + expect(page.media[r.cover.single.media], cover); + expect(page.media[r.steps.first.pictures.single.media], step); + expect(r.steps[1].video, isNotNull); + expect(r.steps[2].text, isNot(contains('note:'))); + expect(page.page, isNull); + }); + + test('a published recipe brings its address, for the video code', () { + final site = SiteBook( + name: SiteName('ersilia'), + settings: SiteSettings(title: 'Ersilia', lang: 'it'), + pages: { + malloreddus.id: PublishedPage( + slug: PageSlug('malloreddus'), + title: 'Malloreddus', + listed: true, + media: const [], + at: DateTime.utc(2026, 11), + ), + }, + ); + final page = collect(site: site).recipes.last; + expect(page.page.toString(), endsWith('/ersilia/malloreddus')); + }); + + test('a category with too many recipes is refused', () { + final many = [ + for (var i = 0; i <= Cookbook.maxRecipes; i++) + recipe('m$i', {'title': TextValue('R$i')}), + ]; + expect( + () => Cookbook.collect( + tree: tree, + root: root, + entries: many, + categoryOf: (_) => root, + compose: (_) => null, + palette: SitePalette.of(const SiteTheme(BaseTheme.fresco)), + ), + throwsA(isA()), + ); + }); + }); + + group('CookbookPdf', () { + test('every page size gives a PDF with the pictures it has', () async { + final book = collect(); + final page = book.recipes.last; + final pictures = { + for (final MapEntry(:key, :value) in page.media.entries) + if (value == cover) + key: jpeg(800, 494, 200, 120, 40) + else if (value == step) + key: jpeg(320, 198, 90, 140, 60), + }; + for (final size in CookbookPage.values) { + final pdf = await CookbookPdf( + book: book, + words: CookbookWords.of(l10n), + fonts: fonts(), + pictures: pictures, + page: size, + ).render(); + expect(String.fromCharCodes(pdf.take(5)), '%PDF-'); + if (Platform.environment['COOKBOOK_OUT'] case final out?) { + File('$out/cookbook-${size.name}.pdf').writeAsBytesSync(pdf); + } + } + }); + }); + + group('CookbookEpub', () { + Map epub({String description = ''}) { + final book = collect(); + final page = book.recipes.last; + final pictures = { + for (final MapEntry(:key, :value) in page.media.entries) + if (value == cover) key: jpeg(80, 49, 200, 120, 40), + }; + final bytes = CookbookEpub( + book: book, + words: CookbookWords.of(l10n), + pictures: pictures, + ).render(at: DateTime.utc(2026, 11, 1, 12)); + if (Platform.environment['COOKBOOK_OUT'] case final out?) { + File('$out/cookbook.epub').writeAsBytesSync(bytes); + } + return unzipBytes(bytes); + } + + test('an EPUB 3: mimetype first, a page per recipe, the index', () { + final files = epub(); + expect(files.keys.first, 'mimetype'); + expect(String.fromCharCodes(files['mimetype']!), 'application/epub+zip'); + final opf = utf8.decode(files['EPUB/package.opf']!); + expect(opf, contains('Cucina sarda')); + expect(opf, contains('properties="cover-image"')); + expect( + files.keys.where((k) => k.startsWith('EPUB/recipe-')), + hasLength(4), + ); + final index = utf8.decode(files['EPUB/ingredients.xhtml']!); + expect(index, contains('
    Pecorino sardo
    ')); + final malloreddus = utf8.decode(files['EPUB/recipe-3.xhtml']!); + expect(malloreddus, contains('salsiccia')); + expect(malloreddus, contains(l10n.cookbookVideoInNote)); + expect(malloreddus, isNot(contains('note:'))); + }); + }); + + group('adversary', () { + test('markup of the person never becomes markup of the book', () { + final hostile = recipe('h', { + 'title': const TextValue(' & "co"'), + 'description': const TextValue( + '[clic](javascript:alert(1)) ' + '[ok](https://example.org/?a=1&b="2")', + ), + 'steps': StepsValue([ + PreparationStep('![x](https://tracker.example/pixel.png) Mescola.'), + ]), + }); + final book = Cookbook.collect( + tree: tree, + root: root, + entries: [hostile], + categoryOf: (_) => root, + compose: CookbookPages( + schemas: [SeedSchemas.recipeV1], + texts: SchemaText(l10n), + recipes: RecipeText(l10n), + locale: 'it', + ).compose, + palette: SitePalette.of(const SiteTheme(BaseTheme.fresco)), + ); + final files = unzipBytes( + CookbookEpub( + book: book, + words: CookbookWords.of(l10n), + pictures: const {}, + ).render(at: DateTime.utc(2026, 11)), + ); + final page = utf8.decode(files['EPUB/recipe-0.xhtml']!); + expect(page, isNot(contains('Cucina sarda')); + }); + + testWidgets('a picture keeps nothing of its file but the pixels', ( + tester, + ) async { + final original = img.Image(width: 40, height: 30); + img.fill(original, color: img.ColorRgb8(10, 120, 200)); + original.exif.imageIfd['Make'] = img.IfdValueAscii('SegretoCamera'); + final bytes = img.encodeJpg(original); + expect(String.fromCharCodes(bytes), contains('SegretoCamera')); + final clean = await tester.runAsync( + () => bookPicture(bytes, side: bookPictureSide), + ); + expect(clean, isNotNull); + expect(String.fromCharCodes(clean!), isNot(contains('SegretoCamera'))); + expect(String.fromCharCodes(clean), isNot(contains('Exif'))); + final back = img.decodeJpg(clean)!; + expect((back.width, back.height), (40, 30)); + }); + }); +} diff --git a/packages/publishing/lib/publishing.dart b/packages/publishing/lib/publishing.dart index 275cec1..814741c 100644 --- a/packages/publishing/lib/publishing.dart +++ b/packages/publishing/lib/publishing.dart @@ -10,6 +10,7 @@ library; export 'src/application/ports.dart'; export 'src/application/publisher.dart'; +export 'src/core/category_colours.dart'; export 'src/core/color.dart'; export 'src/core/golden.dart'; export 'src/core/layout.dart'; diff --git a/packages/publishing/lib/src/core/category_colours.dart b/packages/publishing/lib/src/core/category_colours.dart new file mode 100644 index 0000000..75a2472 --- /dev/null +++ b/packages/publishing/lib/src/core/category_colours.dart @@ -0,0 +1,108 @@ +import 'dart:math'; + +import 'package:meta/meta.dart'; + +import 'color.dart'; +import 'golden.dart'; +import 'site_palette.dart'; + +/// The colours of a cookbook's category, the same that serv.pub gives it +/// (`server/crates/publish/src/colour.rs`): the palette's accent turned by +/// the golden angle once more than the category before it, then moved in +/// lightness until it reads (4.5:1) on the background and the surface, and +/// a tint of the background leaning toward the same hue that keeps the +/// text at 7:1. A book printed from the app and the site it came from show +/// a category in one colour. +@immutable +final class CategoryColours { + const CategoryColours(this.accent, this.tint); + + /// The colours of the category that came [order]-th (from 0) under + /// [palette]. + factory CategoryColours.of(SitePalette palette, int order) { + final background = palette.background; + final surface = palette.surface; + final text = palette.text; + final base = Oklch.of(palette.accent); + final hue = (base.h + Golden.angle * order) % 360; + final chroma = max(base.c, 0.12); + final direction = palette.isDark ? 1.0 : -1.0; + Srgb? accent; + for (var step = 0; step <= 100; step++) { + final lightness = (base.l + direction * 0.01 * step).clamp(0.0, 1.0); + final colour = inGamut(lightness, chroma, hue); + if (colour.contrastWith(background) >= otherContrast && + colour.contrastWith(surface) >= otherContrast) { + accent = colour; + break; + } + } + final reads = accent ?? text; + final ground = Oklch.of(background).l; + final lean = palette.isDark ? 0.04 : -0.03; + var tint = background; + for (final c in const [0.035, 0.025, 0.015]) { + final t = inGamut((ground + lean).clamp(0.0, 1.0), c, hue); + if (text.contrastWith(t) >= textContrast && + reads.contrastWith(t) >= otherContrast) { + tint = t; + break; + } + } + return CategoryColours(reads, tint); + } + + /// Headings, numbers and links of the category. + final Srgb accent; + + /// Its bands and the ground of its boxes. + final Srgb tint; + + static const textContrast = 7.0; + static const otherContrast = 4.5; + + /// The colour at [l], [h] with the most chroma up to [c] that sRGB shows. + static Srgb inGamut(double l, double c, double h) { + var chroma = c; + while (true) { + final rgb = _linear(l, chroma, h); + if (rgb.every((v) => v >= -1e-4 && v <= 1 + 1e-4) || chroma <= 0) { + int channel(double v) { + final x = v.clamp(0.0, 1.0); + final encoded = x <= 0.0031308 + ? 12.92 * x + : 1.055 * pow(x, 1 / 2.4) - 0.055; + return (encoded * 255).round(); + } + + return Srgb.hex( + rgb.map((v) => channel(v).toRadixString(16).padLeft(2, '0')).join(), + ); + } + chroma -= 0.005; + } + } + + static List _linear(double l, double c, double h) { + final a = c * cos(h * pi / 180); + final b = c * sin(h * pi / 180); + final l1 = pow(l + 0.3963377774 * a + 0.2158037573 * b, 3).toDouble(); + final m1 = pow(l - 0.1055613458 * a - 0.0638541728 * b, 3).toDouble(); + final s1 = pow(l - 0.0894841775 * a - 1.2914855480 * b, 3).toDouble(); + return [ + 4.0767416621 * l1 - 3.3077115913 * m1 + 0.2309699292 * s1, + -1.2684380046 * l1 + 2.6097574011 * m1 - 0.3413193965 * s1, + -0.0041960863 * l1 - 0.7034186147 * m1 + 1.7076147010 * s1, + ]; + } + + @override + bool operator ==(Object other) => + other is CategoryColours && other.accent == accent && other.tint == tint; + + @override + int get hashCode => Object.hash(accent, tint); + + @override + String toString() => 'CategoryColours($accent, $tint)'; +} diff --git a/packages/publishing/test/category_colours_test.dart b/packages/publishing/test/category_colours_test.dart new file mode 100644 index 0000000..734b2df --- /dev/null +++ b/packages/publishing/test/category_colours_test.dart @@ -0,0 +1,57 @@ +import 'package:publishing/publishing.dart'; +import 'package:test/test.dart'; + +void main() { + final light = SitePalette.of(const SiteTheme(BaseTheme.fresco)); + final dark = SitePalette.of(const SiteTheme(BaseTheme.frescoDark)); + + test('the colours serv.pub gives the same categories', () { + // From `colour::category` on the two Fresco themes. + const expected = { + false: [ + ('#A9461B', '#FEE9E2'), + ('#117A6A', '#D6F7EF'), + ('#884B9E', '#F8E8FF'), + ('#7D6701', '#F6EED5'), + ('#0F7298', '#DEF2FC'), + ('#A93E58', '#FEE8EB'), + ], + true: [ + ('#E6905A', '#2D1A0F'), + ('#0AC1B9', '#072523'), + ('#D28BD1', '#281928'), + ('#B5AC43', '#22200B'), + ('#57B1F0', '#0F212E'), + ('#ED8688', '#2E1819'), + ], + }; + for (final MapEntry(key: isDark, value: rows) in expected.entries) { + final palette = isDark ? dark : light; + for (final (order, (accent, tint)) in rows.indexed) { + expect( + CategoryColours.of(palette, order), + CategoryColours(Srgb.hex(accent), Srgb.hex(tint)), + reason: '$isDark $order', + ); + } + } + }); + + test('every category reads, on both Frescos', () { + for (final palette in [light, dark]) { + for (var order = 0; order < 34; order++) { + final c = CategoryColours.of(palette, order); + expect( + c.accent.contrastWith(palette.background), + greaterThanOrEqualTo(4.5), + ); + expect( + c.accent.contrastWith(palette.surface), + greaterThanOrEqualTo(4.5), + ); + expect(c.accent.contrastWith(c.tint), greaterThanOrEqualTo(4.5)); + expect(palette.text.contrastWith(c.tint), greaterThanOrEqualTo(7)); + } + } + }); +} diff --git a/pubspec.lock b/pubspec.lock index 5c5ff64..7435652 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -17,6 +17,14 @@ packages: url: "https://pub.dev" source: hosted version: "13.3.0" + android_file_picker: + dependency: transitive + description: + name: android_file_picker + sha256: "03d3dd3cb578ab26b1e528aeea27bf6b976942f5a24e3da82d270369b8e161a8" + url: "https://pub.dev" + source: hosted + version: "2.1.2" archive: dependency: transitive description: @@ -41,6 +49,22 @@ packages: url: "https://pub.dev" source: hosted version: "2.13.1" + barcode: + dependency: transitive + description: + name: barcode + sha256: "7b6729c37e3b7f34233e2318d866e8c48ddb46c1f7ad01ff7bb2a8de1da2b9f4" + url: "https://pub.dev" + source: hosted + version: "2.2.9" + bidi: + dependency: transitive + description: + name: bidi + sha256: "77f475165e94b261745cf1032c751e2032b8ed92ccb2bf5716036db79320637d" + url: "https://pub.dev" + source: hosted + version: "2.0.13" boolean_selector: dependency: transitive description: @@ -161,6 +185,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.2.0" + ffi_leak_tracker: + dependency: transitive + description: + name: ffi_leak_tracker + sha256: "4093d4ef9ca06ffe2786e73bfb25e22aa92112b9bb4ec941f11e3e6b61489a97" + url: "https://pub.dev" + source: hosted + version: "0.1.2" file: dependency: transitive description: @@ -169,6 +201,46 @@ packages: url: "https://pub.dev" source: hosted version: "7.0.1" + file_picker: + dependency: transitive + description: + name: file_picker + sha256: "02f2945a7f29535c735f6b283c3c5553810566d3052d730429aec78fe9d06592" + url: "https://pub.dev" + source: hosted + version: "13.3.1" + file_picker_darwin: + dependency: transitive + description: + name: file_picker_darwin + sha256: b845af092ca7a3cff0e768029f835157d371a8341750f4158a7ad358143b0e54 + url: "https://pub.dev" + source: hosted + version: "2.4.1" + file_picker_linux: + dependency: transitive + description: + name: file_picker_linux + sha256: c6562fc7d426db2fb85ea66fe2627953d2709932df5584ceaacf0aa5e39cf4da + url: "https://pub.dev" + source: hosted + version: "2.0.2" + file_picker_platform_interface: + dependency: transitive + description: + name: file_picker_platform_interface + sha256: "336e7168306834a2b68e6168ed768e00d3fabeac23154d5793e277ca9f97cf20" + url: "https://pub.dev" + source: hosted + version: "4.2.0" + file_picker_web: + dependency: transitive + description: + name: file_picker_web + sha256: a2288008280aabe371aff029466b3405e60838e0a1d714767488c59b926c8b8c + url: "https://pub.dev" + source: hosted + version: "4.2.0" file_selector_linux: dependency: transitive description: @@ -357,6 +429,14 @@ packages: url: "https://pub.dev" source: hosted version: "4.1.2" + image: + dependency: transitive + description: + name: image + sha256: "89ed75b2f8231fe676808c5564f9590d728024ded7ac782a7ed8474f1c95b72a" + url: "https://pub.dev" + source: hosted + version: "4.12.0" image_picker: dependency: transitive description: @@ -581,6 +661,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.9.1" + path_parsing: + dependency: transitive + description: + name: path_parsing + sha256: "883402936929eac138ee0a45da5b0f2c80f89913e6dc3bf77eb65b84b409c6ca" + url: "https://pub.dev" + source: hosted + version: "1.1.0" path_provider: dependency: transitive description: @@ -629,6 +717,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.3.0" + pdf: + dependency: transitive + description: + name: pdf + sha256: "6e40827f370d196e97c6611724d923a3d86c431ce8e2ce1e59edd03a67a1a6e6" + url: "https://pub.dev" + source: hosted + version: "3.13.1" petitparser: dependency: transitive description: @@ -685,6 +781,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.2.1" + qr: + dependency: transitive + description: + name: qr + sha256: "2c0189dca64a3ab08dda7acd7911c89af2374f08eb4eaded3e8ef4609f3b9c8b" + url: "https://pub.dev" + source: hosted + version: "3.0.3" record: dependency: transitive description: @@ -1066,6 +1170,22 @@ packages: url: "https://pub.dev" source: hosted version: "1.2.1" + win32: + dependency: transitive + description: + name: win32 + sha256: a0b93865d5644f11cf6a8c3f6db909f1ec168958b5805f6cc684adea957cd63d + url: "https://pub.dev" + source: hosted + version: "6.4.0" + windows_file_picker: + dependency: transitive + description: + name: windows_file_picker + sha256: "18452aa293de3b6961c6d05b0e71b4be7bb90c67635abdd3aa5c4e75dd875072" + url: "https://pub.dev" + source: hosted + version: "2.0.1" xdg_directories: dependency: transitive description: