diff --git a/apps/library/books.zi b/apps/library/books.zi index a8e3d6ef1..3285ff453 100644 --- a/apps/library/books.zi +++ b/apps/library/books.zi @@ -1,37 +1,122 @@ -// The Library's books, each a list of chapters. +// Book content, stable text positions and the account record format. +#import "text_buffer" #import, file "tao_te_ching.zi"; BOOK_COUNT :: 1 +LIBRARY_PAGE_LIMIT :: 4096 +LIBRARY_ANNOTATION_LIMIT :: 128 + +LibraryPage :: struct { + chapter: s32 + start: s32 + end: s32 +} + +LibraryAnnotation :: struct { + start: s32 + end: s32 + highlighted: bool + note: string +} BookTitle :: (index: s32) -> string { unused index return TAO_TE_CHING_TITLE } +BookCover :: (index: s32) -> string { + unused index + return "assets/library/tao-te-ching.png" +} + BookAuthor :: (index: s32) -> string { unused index - return TAO_TE_CHING_AUTHOR + return "Lao Tzu" } -// Where the book's words come from. -BookNote :: (index: s32) -> string { - unused index - return TAO_TE_CHING_NOTE -} - -// The record that keeps the chapter a book is open at. +// Keep reading the released chapter record when no text position exists. BookRecord :: (index: s32) -> string { unused index return "tao-te-ching.chapter" } +BookPositionRecord :: (index: s32) -> string { + unused index + return "tao-te-ching.position" +} + +BookAnnotationsRecord :: (index: s32, chapter: s32) -> string { + unused index + value: Vec(u8) + BuilderPrint(*value, "tao-te-ching.annotations.%", chapter) + return BuilderFinish(value) +} + BookChapters :: (index: s32) -> s32 { unused index return TAO_TE_CHING_CHAPTERS } -// Chapter number's words, from 1. BookChapter :: (index: s32, number: s32) -> string { unused index return TaoTeChing(number) } + +// Decimal fields are bounded and separated by one non-digit byte. +ReadLibraryNumber :: (text: string, at: *s32) -> s32 { + value: s32 + digits: s32 + while at.* < text.count && text[at.*] >= #char "0" && text[at.*] <= #char "9" { + if digits >= 7 { return -1 } + value = value * 10 + cast(s32)text[at.*] - 48 + at.* += 1 + digits += 1 + } + if digits == 0 { return -1 } + if at.* < text.count { at.* += 1 } + return value +} + +LibraryPageFor :: (pages: []LibraryPage, chapter: s32, offset: s32) -> s32 { + found: s32 + for index: cast(s32)0..cast(s32)pages.count - 1 { + page := pages[index] + if page.chapter < chapter || (page.chapter == chapter && page.start <= offset) { + found = index + } + } + return found +} + +LibraryOverlaps :: (page: LibraryPage, annotation: LibraryAnnotation) -> bool { + return annotation.start < page.end && annotation.end > page.start +} + +// Length-prefixed notes preserve newlines and punctuation without an escape +// convention. Each chapter has a single atomic account record. +DecodeLibraryAnnotations :: (text: string, output: []LibraryAnnotation) -> s32 { + at: s32 + count: s32 + while at < text.count && count < output.count { + start := ReadLibraryNumber(text, *at) + end := ReadLibraryNumber(text, *at) + highlight := ReadLibraryNumber(text, *at) + length := ReadLibraryNumber(text, *at) + if start < 0 || end <= start || highlight < 0 || highlight > 1 || + length < 0 || length > 2048 || length > text.count - at { return 0 } + output[count] = LibraryAnnotation.{start, end, highlight == 1, text[at:at + length]} + at += length + count += 1 + } + if at != text.count { return 0 } + return count +} + +EncodeLibraryAnnotations :: (annotations: []LibraryAnnotation) -> string { + value: Vec(u8) + for annotation: annotations { + BuilderPrint(*value, "% % % %\n%", annotation.start, annotation.end, + ifx annotation.highlighted then 1 else 0, annotation.note.count, annotation.note) + } + return BuilderFinish(value) +} diff --git a/apps/library/library.zi b/apps/library/library.zi index a5b8e92b1..f13ffad95 100644 --- a/apps/library/library.zi +++ b/apps/library/library.zi @@ -1,6 +1,4 @@ -// Library: books to read slowly, a chapter at a time. Its first book is the -// Tao Te Ching. Books live in this bundle as text; the host only keeps the -// chapter each one is open at. +// Cover shelf and a paginated reader. Only account records leave this app. #import "session" #import "geometry" #import "vec" @@ -8,6 +6,13 @@ #import "text_props" #import "text_widget" #import "text_measure" +#import "text_align" +#import "image_props" +#import "image_widget" +#import "grid" +#import "grid_props" +#import "press_props" +#import "press_widget" #import "button_props" #import "button_widget" #import "control_props" @@ -17,9 +22,21 @@ #import "pointer_input" #import "swipe" #import "swipe_props" -#import "box_props" +#import "input_protocol" #import "drawing_props" +#import "box_props" #import "box_widget" +#import "spinbox_props" +#import "spinbox_widget" +#import "dropdown_props" +#import "dropdown_widget" +#import "toggle_props" +#import "toggle_widget" +#import "text_input_props" +#import "text_area_widget" +#import "widget_palette" +#import "icon" +#import "transition" #import, file "../../src/cells/app_presentation.zi"; #import "apps/node_types" #import, file "../../src/cells/module_types.zi"; @@ -33,28 +50,53 @@ ReadAppUiHost :: () -> AppUiFrame #foreign host_api; AppLocaleHost :: (key: string) -> string #foreign host_api; AppRecordHost :: (record: string) -> string #foreign host_api; SaveAppRecordHost :: (record: string, value: string) -> bool #foreign host_api; +AppKeyHost :: () -> s32 #foreign host_api; +AppFieldInputHost :: () -> TextFieldInput #foreign host_api; +CloseAppHost :: () -> bool #foreign host_api; +SmoothFramesHost :: (frames: s32) -> bool #foreign host_api; using TextWrap; using ButtonTone; using ButtonEmphasis; - -LIBRARY_SHELF :: 0 -LIBRARY_CONTENTS :: 1 -LIBRARY_CHAPTER :: 2 +using TextAlign; frame: AppUiFrame; -view: s32 = LIBRARY_SHELF; +reading: bool; book: s32; -chapter: s32 = 1; -// The view a chapter was opened from, where Back returns. -came_from: s32 = LIBRARY_SHELF; loaded_account: string; loaded: bool; -// Each view keeps its own place. shelf_scroll: s32; -contents_scroll: s32; -chapter_scroll: s32; -chapter_swipe: SwipeGesture; +pages: [LIBRARY_PAGE_LIMIT]LibraryPage; +page_count: s32; +page_index: s32; +anchor_chapter: s32 = 1; +anchor_offset: s32; +layout_width: s32; +layout_height: s32; +layout_scale: float32; +font_size: s32 = 21; +font_face: s32; +margin: s32 = 24; +line_gap: s32 = 8; +settings_dirty: bool; +position_dirty: bool; +save_failed: bool; +panel_open: bool; +panel_tab: s32; +panel_scroll: s32; +annotation_chapter: s32; +annotations: [LIBRARY_ANNOTATION_LIMIT]LibraryAnnotation; +annotation_count: s32; +annotation_index: s32 = -1; +annotation_dirty: bool; +note: [2049]u8; +note_state: TextAreaResult; +passage_state: TextAreaResult; +reader_swipe: SwipeGesture; +book_dark: bool; +opening_started: float64; +opening: bool; +opening_from: Rectangle; Scale :: (value: s32) -> s32 { return cast(s32)(cast(float32)value * frame.scale) @@ -64,217 +106,660 @@ Bounds :: (x: s32, y: s32, width: s32, height: s32) -> Rectangle { return Rectangle.{cast(float32)x, cast(float32)y, cast(float32)width, cast(float32)height} } -// The text of key with number in place of its %s. -Numbered :: (key: string, number: s32, buffer: []u8) -> string { - args: [1]FormatArg - args[0].number = number - unused FormatTemplate(AppLocaleHost(key), args[:], buffer[:]) - return TextUntilNul(buffer) +NumberText :: (value: s32) -> string { + text: Vec(u8) + BuilderPrint(*text, "%", value) + return BuilderFinish(text) } -ReadNumber :: (value: string) -> s32 { - if value.count == 0 || value.count > 4 { return 0 } - answer: s32 = 0 - for index: cast(s64)0..value.count - 1 { - if value[index] < cast(u8)48 || value[index] > cast(u8)57 { return 0 } - answer = answer * 10 + cast(s32)value[index] - 48 - } - return answer +RecordNumber :: (key: string, fallback: s32, minimum: s32, maximum: s32) -> s32 { + at: s32 + value := ReadLibraryNumber(AppRecordHost(key), *at) + return ifx value >= minimum && value <= maximum then value else fallback } -// The chapter a book is open at, or 0 before its first reading. -SavedChapter :: (index: s32) -> s32 { - saved := ReadNumber(AppRecordHost(BookRecord(index))) - return ifx saved >= 1 && saved <= BookChapters(index) then saved else 0 -} - -Open :: (index: s32, number: s32) { - if view != LIBRARY_CHAPTER { came_from = view } - book = index - chapter = number - chapter_scroll = 0 - view = LIBRARY_CHAPTER +SaveSettings :: () -> bool { + if !settings_dirty { return true } value: Vec(u8) - BuilderPrint(*value, "%", number) - unused SaveAppRecordHost(BookRecord(index), BuilderFinish(value)) + BuilderPrint(*value, "% % % %", font_size, font_face, margin, line_gap) + if !SaveAppRecordHost("reader.settings", BuilderFinish(value)) { return false } + if !SaveAppRecordHost("tao-te-ching.theme", ifx book_dark then "1" else "0") { return false } + settings_dirty = false + return true +} + +SavePosition :: () -> bool { + if !position_dirty { return true } + value: Vec(u8) + BuilderPrint(*value, "% %", anchor_chapter, anchor_offset) + if !SaveAppRecordHost(BookPositionRecord(book), BuilderFinish(value)) { return false } + position_dirty = false + return true +} + +SaveAnnotations :: () -> bool { + if !annotation_dirty { return true } + if annotation_index >= 0 { + value: Vec(u8) + BuilderPrint(*value, "%", TextUntilNul(note[:])) + annotations[annotation_index].note = BuilderFinish(value) + } + if !SaveAppRecordHost(BookAnnotationsRecord(book, annotation_chapter), + EncodeLibraryAnnotations(annotations[:annotation_count])) { return false } + annotation_dirty = false + return true +} + +SaveReader :: () -> bool { + notes_saved := SaveAnnotations() + settings_saved := SaveSettings() + position_saved := SavePosition() + save_failed = !notes_saved || !settings_saved || !position_saved + return !save_failed +} + +LoadSettings :: () { + font_size = 21 + font_face = 0 + margin = 24 + line_gap = 8 + book_dark = RecordNumber("tao-te-ching.theme", ifx frame.dark then 1 else 0, 0, 1) == 1 + text := AppRecordHost("reader.settings") + at: s32 + size := ReadLibraryNumber(text, *at) + face := ReadLibraryNumber(text, *at) + inset := ReadLibraryNumber(text, *at) + gap := ReadLibraryNumber(text, *at) + if size >= 14 && size <= 36 { font_size = size } + if face >= 0 && face <= 1 { font_face = face } + if inset >= 12 && inset <= 56 { margin = inset } + if gap >= 2 && gap <= 20 { line_gap = gap } +} + +ReadingBounds :: () -> Rectangle { + width := frame.width - Scale(margin * 2) + if width > Scale(680) { width = Scale(680) } + top := frame.top + Scale(16) + height := frame.height - frame.bottom - top - Scale(48) + return Bounds((frame.width - width) / 2, top, width, height) +} + +ReadingProps :: () -> TextProps { + return TextProps.{.bounds = ReadingBounds(), .font = Scale(font_size), + .typeface = ifx font_face == 1 then "assets/library/noto-sans.ttf" else "ui", + .line_gap = Scale(line_gap), .wrap = cast(TextWrap)TextWrapAuto} +} + +Reflow :: () { + bounds := ReadingBounds() + if page_count > 0 && layout_width == cast(s32)bounds.width && + layout_height == cast(s32)bounds.height && layout_scale == frame.scale { return } + // During a transient resize (for example a phone keyboard), keep the + // passage rather than saving a fabricated page with no room for a line. + if bounds.width < cast(float32)Scale(60) || bounds.height < cast(float32)Scale(font_size + line_gap) { return } + count: s32 + props := ReadingProps() + for chapter: cast(s32)1..BookChapters(book) { + props.text = BookChapter(book, chapter) + at: s32 + while at < props.text.count && count < LIBRARY_PAGE_LIMIT { + part := TextPage(frame.session, props, at) + if part.next <= at { return } + pages[count] = LibraryPage.{chapter, part.start, part.end} + count += 1 + at = part.next + } + } + page_count = count + page_index = LibraryPageFor(pages[:page_count], anchor_chapter, anchor_offset) + layout_width = cast(s32)bounds.width + layout_height = cast(s32)bounds.height + layout_scale = frame.scale +} + +LoadPageAnnotations :: () { + current := pages[page_index] + if annotation_chapter != current.chapter { + annotation_count = DecodeLibraryAnnotations(AppRecordHost(BookAnnotationsRecord(book, current.chapter)), annotations[:]) + annotation_chapter = current.chapter + } + annotation_index = -1 + for index: cast(s32)0..annotation_count - 1 { + if annotation_index < 0 && LibraryOverlaps(current, annotations[index]) { annotation_index = index } + } + note[0] = 0 + if annotation_index >= 0 { unused AppCopyText(annotations[annotation_index].note, note[:]) } + note_state = TextAreaResult.{} + passage_state = TextAreaResult.{} + if annotation_index >= 0 { + saved := annotations[annotation_index] + // Keep older page-wide notes, without selecting the entire page. + if saved.end - saved.start < current.end - current.start { + passage_state.anchor = ifx saved.start > current.start then saved.start - current.start else 0 + passage_state.cursor = ifx saved.end < current.end then saved.end - current.start else current.end - current.start + } + } +} + +OpenBook :: (index: s32) { + book = index + text := AppRecordHost(BookPositionRecord(book)) + at: s32 + anchor_chapter = ReadLibraryNumber(text, *at) + anchor_offset = ReadLibraryNumber(text, *at) + if anchor_chapter < 1 || anchor_chapter > BookChapters(book) { + anchor_chapter = RecordNumber(BookRecord(book), 1, 1, BookChapters(book)) + anchor_offset = 0 + } + if anchor_offset < 0 || anchor_offset >= BookChapter(book, anchor_chapter).count { anchor_offset = 0 } + page_count = 0 + annotation_chapter = 0 + panel_open = false + reading = true + opening = true + opening_started = frame.now + unused SmoothFramesHost(24) + reader_swipe = SwipeGesture.{} + Reflow() + if page_count > 0 { LoadPageAnnotations() } +} + +TurnPage :: (index: s32) { + if index < 0 || index >= page_count || !SaveReader() { return } + page_index = index + anchor_chapter = pages[index].chapter + anchor_offset = pages[index].start + position_dirty = true + unused SaveReader() + LoadPageAnnotations() } LibraryBack :: () -> bool { - if view == LIBRARY_CHAPTER { view = came_from; return true } - if view == LIBRARY_CONTENTS { view = LIBRARY_SHELF; return true } - return false + if !reading { return false } + if !SaveReader() { return true } + if panel_open { panel_open = false } + else { reading = false } + return true } -// A centred reading column, as wide as reads comfortably. -Column :: () -> Rectangle { - margin := Scale(20) - width := frame.width - margin * 2 - if width > Scale(640) { width = Scale(640) } - top := frame.top + Scale(12) - return Bounds((frame.width - width) / 2, top, width, frame.height - frame.bottom - top) +BookJacket :: (index: s32, cover: Rectangle, key: u64) { + Image(frame.session, ImageProps.{.key = key, .asset_path = BookCover(index), + .alt_text = BookTitle(index), .bounds = cover, + .fit = ImageFit.ImageFitStretch, .smooth = true}) + if cover.width < cast(float32)Scale(80) { return } + label_height := cast(s32)(cover.height * 0.30) + unused Box(frame.session, BoxProps.{.key = key + 1, + .bounds = Bounds(cast(s32)cover.x + Scale(4), cast(s32)cover.y + Scale(4), + cast(s32)cover.width - Scale(8), label_height), + .fill = Color.{244, 233, 204, 245}, .fill_bottom = Color.{244, 233, 204, 0}, + .has_fill_bottom = true}) + palette := ReaderPalette() + palette.text = cast(u32)0x40372bff + unused WidgetPaletteUse(frame.session, palette) + title_font := cast(s32)(cover.width * 0.105) + author_font := cast(s32)(cover.width * 0.075) + Text(frame.session, TextProps.{.key = key + 2, .text = BookTitle(index), .font = title_font, + .align = cast(TextAlign)TextAlignCenter, + .bounds = Bounds(cast(s32)cover.x + Scale(8), cast(s32)cover.y + Scale(12), + cast(s32)cover.width - Scale(16), title_font + Scale(4))}) + Text(frame.session, TextProps.{.key = key + 3, .text = BookAuthor(index), .font = author_font, + .align = cast(TextAlign)TextAlignCenter, + .bounds = Bounds(cast(s32)cover.x + Scale(8), cast(s32)cover.y + Scale(18) + title_font, + cast(s32)cover.width - Scale(16), author_font + Scale(4))}) + unused WidgetPaletteRestore(frame.session) } -Title :: (bounds: Rectangle, text: string, size: s32) -> s32 { - height := TextHeight(frame.session, TextProps.{.text = text, .font = size, .bounds = bounds, - .wrap = cast(TextWrap)TextWrapAuto}) - bounds.height = cast(float32)height - Text(frame.session, TextProps.{.text = text, .font = size, .bounds = bounds, - .wrap = cast(TextWrap)TextWrapAuto}) - return height -} - -ShelfNoteHeight :: (index: s32, width: s32) -> s32 { - return TextHeight(frame.session, TextProps.{.text = BookNote(index), .font = frame.font - Scale(2), - .bounds = Bounds(0, 0, width, 0), .wrap = cast(TextWrap)TextWrapAuto}) +OpeningView :: () { + progress := cast(float32)((frame.now - opening_started) / 0.32) + if progress >= 1.0 { + opening = false + return + } + unused SmoothFramesHost(2) + width := ReadingBounds().width + if width > cast(float32)Scale(260) { width = cast(float32)Scale(260) } + target := Rectangle.{(cast(float32)frame.width - width) / 2.0, + cast(float32)frame.top + cast(float32)Scale(24), width, width * 1.5} + lift := TransitionSmoothProgress(progress / 0.45) + cover := Rectangle.{opening_from.x + (target.x - opening_from.x) * lift, + opening_from.y + (target.y - opening_from.y) * lift, + opening_from.width + (target.width - opening_from.width) * lift, + opening_from.height + (target.height - opening_from.height) * lift} + turn := TransitionSmoothProgress((progress - 0.45) / 0.55) + cover.width *= 1.0 - turn + if cover.width > 1.0 { BookJacket(book, cover, 27800) } } ShelfView :: () { - column := Column() - height := Scale(64) - for index: cast(s32)0..BOOK_COUNT - 1 { - height += Scale(132) + ShelfNoteHeight(index, cast(s32)column.width) - } - scroll := Scroll(frame.session, ScrollProps.{.key = 27000, .bounds = column, - .content_height = height, .scroll_offset = shelf_scroll, .scale = frame.scale}) + area := Bounds(Scale(12), frame.top + Scale(12), frame.width - Scale(24), + frame.height - frame.bottom - frame.top - Scale(24)) + grid := MeasureGrid(GridProps.{.bounds = area, .min_item_width = Scale(132), + .max_columns = 5, .gap = Scale(28), .padding = Scale(20)}) + cover_width := grid.cell_width - Scale(8) + if cover_width > Scale(160) { cover_width = Scale(160) } + height := cover_width * 3 / 2 + row_height := height + Scale(72) + rows := GridRowCount(grid, BOOK_COUNT) + visible_rows := (cast(s32)area.height + row_height - 1) / row_height + if rows < visible_rows { rows = visible_rows } + content_height := rows * row_height + Scale(20) + unused Box(frame.session, BoxProps.{.key = 27900, .bounds = area, + .fill = Color.{73, 43, 28, 255}, .fill_bottom = Color.{111, 71, 44, 255}, + .has_fill_bottom = true}) + scroll := Scroll(frame.session, ScrollProps.{.key = 27000, .bounds = area, + .content_height = content_height, + .scroll_offset = shelf_scroll, .scale = frame.scale}) shelf_scroll = scroll.scroll_offset if !scroll.opened { return } defer { unused End(frame.session) } - x := cast(s32)scroll.content.x - y := cast(s32)scroll.content.y - width := cast(s32)scroll.content.width - y += Title(Bounds(x, y, width, 0), AppLocaleHost("app_name_library"), frame.font + Scale(8)) + Scale(20) - buffer: [128]u8 + grid.content.y = scroll.content.y + cast(float32)Scale(20) + // Recessed backs, a lit board top, and a thick wood edge make each row + // a shelf. Empty rows remain part of the bookcase as the library grows. + for row: cast(s32)0..rows - 1 { + x := cast(s32)scroll.content.x + y := cast(s32)scroll.content.y + row * row_height + width := cast(s32)scroll.content.width + board := y + height + Scale(20) + key := cast(u64)(28000 + row * 32) + unused Box(frame.session, BoxProps.{.key = key, + .bounds = Bounds(x + Scale(10), y, width - Scale(20), row_height), + .fill = Color.{57, 35, 25, 255}, .fill_bottom = Color.{126, 87, 55, 255}, + .has_fill_bottom = true}) + unused Box(frame.session, BoxProps.{.key = key + 1, + .bounds = Bounds(x + Scale(10), board - Scale(14), width - Scale(20), Scale(14)), + .fill = Color.{158, 110, 65, 255}, .fill_bottom = Color.{193, 143, 85, 255}, + .has_fill_bottom = true}) + unused Box(frame.session, BoxProps.{.key = key + 2, + .bounds = Bounds(x, board, width, Scale(22)), + .fill = Color.{163, 111, 63, 255}, .fill_bottom = Color.{108, 65, 36, 255}, + .has_fill_bottom = true}) + unused Box(frame.session, BoxProps.{.key = key + 3, + .bounds = Bounds(x, board, width, Scale(2)), .fill = Color.{217, 167, 104, 255}}) + unused Box(frame.session, BoxProps.{.key = key + 4, + .bounds = Bounds(x + Scale(10), board + Scale(22), width - Scale(20), Scale(18)), + .fill = Color.{25, 15, 10, 120}, .fill_bottom = Color.{25, 15, 10, 0}, + .has_fill_bottom = true}) + for grain: cast(s32)0..3 { + unused Box(frame.session, BoxProps.{.key = key + cast(u64)(5 + grain), + .bounds = Bounds(x + Scale(8 + grain * 13), board + Scale(5 + grain * 4), + width - Scale(40 + grain * 14), Scale(1)), + .fill = Color.{75, 43, 24, 65}}) + } + } for index: cast(s32)0..BOOK_COUNT - 1 { - Text(frame.session, TextProps.{.text = BookTitle(index), .font = frame.font + Scale(4), - .bounds = Bounds(x, y, width, Scale(30))}) - Text(frame.session, TextProps.{.text = BookAuthor(index), .font = frame.font - Scale(1), - .bounds = Bounds(x, y + Scale(30), width, Scale(22))}) - note := ShelfNoteHeight(index, width) - Text(frame.session, TextProps.{.text = BookNote(index), .font = frame.font - Scale(2), - .bounds = Bounds(x, y + Scale(56), width, note), .wrap = cast(TextWrap)TextWrapAuto}) - y += note + Scale(8) - saved := SavedChapter(index) - label := ifx saved > 0 then Numbered("library_continue", saved, buffer[:]) else AppLocaleHost("library_start") - half := (width - Scale(12)) / 2 - if Button(frame.session, ButtonProps.{.id = 27010 + index * 2, .bounds = Bounds(x, y + Scale(60), half, Scale(48)), - .label = label, .tone = cast(ButtonTone)ButtonToneAccent, - .emphasis = cast(ButtonEmphasis)ButtonEmphasisFilled}) != 0 { - Open(index, ifx saved > 0 then saved else 1) + cover := GridCellBounds(grid, index, row_height - grid.gap) + cover.width = cast(float32)cover_width + cover.height = cast(float32)height + x := cast(s32)cover.x + y := cast(s32)cover.y + key := cast(u64)(29000 + index * 16) + unused Box(frame.session, BoxProps.{.key = key, + .bounds = Bounds(x + Scale(6), y + Scale(8), cover_width + Scale(8), height), + .fill = Color.{20, 12, 8, 105}, .radius = cast(float32)Scale(3)}) + unused Box(frame.session, BoxProps.{.key = key + 1, + .bounds = Bounds(x + Scale(5), y + Scale(3), cover_width, height - Scale(3)), + .fill = Color.{221, 208, 171, 255}, .border = Color.{121, 101, 66, 255}}) + press := Press(frame.session, PressProps.{.key = cast(u64)(27010 + index), + .bounds = cover, .label = BookTitle(index), .now = frame.now}) + BookJacket(index, cover, key + 4) + unused Box(frame.session, BoxProps.{.key = key + 2, + .bounds = Bounds(x, y, Scale(5), height), .fill = Color.{18, 24, 17, 85}}) + unused Box(frame.session, BoxProps.{.key = key + 3, + .bounds = Bounds(x + Scale(6), y, Scale(1), height), .fill = Color.{255, 243, 192, 75}}) + if press.clicked { + opening_from = cover + OpenBook(index) } - if Button(frame.session, ButtonProps.{.id = 27011 + index * 2, - .bounds = Bounds(x + half + Scale(12), y + Scale(60), half, Scale(48)), - .label = AppLocaleHost("library_contents"), .tone = cast(ButtonTone)ButtonToneNeutral, - .emphasis = cast(ButtonEmphasis)ButtonEmphasisSoft}) != 0 { - book = index - contents_scroll = 0 - view = LIBRARY_CONTENTS - } - y += Scale(132) } } -// Every chapter's number, in rows, to open any of them. -ContentsView :: () { - column := Column() - width := cast(s32)column.width - size := Scale(56) - gap := Scale(8) - across := (width + gap) / (size + gap) - if across < 1 { across = 1 } - count := BookChapters(book) - rows := (count + across - 1) / across - height := Scale(72) + rows * (size + gap) - scroll := Scroll(frame.session, ScrollProps.{.key = 27100, .bounds = column, - .content_height = height, .scroll_offset = contents_scroll, .scale = frame.scale}) - contents_scroll = scroll.scroll_offset +EnsureAnnotation :: () -> bool { + if annotation_index >= 0 { return true } + if annotation_count >= LIBRARY_ANNOTATION_LIMIT { return false } + current := pages[page_index] + start := ifx passage_state.anchor < passage_state.cursor then passage_state.anchor else passage_state.cursor + end := ifx passage_state.anchor > passage_state.cursor then passage_state.anchor else passage_state.cursor + if end <= start { return false } + annotation_index = annotation_count + annotation_count += 1 + annotations[annotation_index] = LibraryAnnotation.{.start = current.start + start, .end = current.start + end} + return true +} + +AnnotationPanel :: (bounds: Rectangle) { + y := cast(s32)bounds.y + width := cast(s32)bounds.width + current := pages[page_index] + input := AppFieldInputHost() + Text(frame.session, TextProps.{.text = AppLocaleHost("library_select_passage"), .font = frame.font, + .bounds = Bounds(cast(s32)bounds.x, y, width, Scale(32))}) + y += Scale(40) + previous_start := ifx passage_state.anchor < passage_state.cursor then passage_state.anchor else passage_state.cursor + previous_end := ifx passage_state.anchor > passage_state.cursor then passage_state.anchor else passage_state.cursor + passage_state = TextArea(frame.session, TextAreaProps.{.key = 27619, .focus_id = 27619, + .bounds = Bounds(cast(s32)bounds.x, y, width, Scale(168)), + .value = BookChapter(book, current.chapter)[current.start:current.end], + .label = AppLocaleHost("library_select_passage"), .read_only = true, .wrap = true, + .cursor = passage_state.cursor, .anchor = passage_state.anchor, + .focused = passage_state.focused, .scroll_y = passage_state.scroll_y, + .selecting = passage_state.selecting, .scale = frame.scale, + .input = TextAreaInput.{.left = input.left, .right = input.right, + .home = input.home, .end = input.end, .shift = input.shift, + .select_all = input.select_all, .copy = input.copy, .now_seconds = frame.now}}) + start := ifx passage_state.anchor < passage_state.cursor then passage_state.anchor else passage_state.cursor + end := ifx passage_state.anchor > passage_state.cursor then passage_state.anchor else passage_state.cursor + if end > start && (start != previous_start || end != previous_end) && SaveAnnotations() { + annotation_index = -1 + for index: cast(s32)0..annotation_count - 1 { + if annotations[index].start == current.start + start && annotations[index].end == current.start + end { + annotation_index = index + } + } + note[0] = 0 + if annotation_index >= 0 { unused AppCopyText(annotations[annotation_index].note, note[:]) } + note_state = TextAreaResult.{} + } + y += Scale(184) + selected := end > start || annotation_index >= 0 + highlighted := annotation_index >= 0 && annotations[annotation_index].highlighted + Text(frame.session, TextProps.{.text = AppLocaleHost("library_highlight"), .font = frame.font, + .bounds = Bounds(cast(s32)bounds.x, y, width - Scale(72), Scale(48))}) + toggle := Toggle(frame.session, ToggleProps.{.key = 27620, + .bounds = Bounds(cast(s32)bounds.x + width - Scale(64), y, Scale(64), Scale(48)), + .label = AppLocaleHost("library_highlight"), .value = highlighted, .disabled = !selected}) + if toggle.changed && EnsureAnnotation() { + annotations[annotation_index].highlighted = toggle.value + annotation_dirty = true + unused SaveReader() + } + y += Scale(64) + edit := TextArea(frame.session, TextAreaProps.{.key = 27621, .focus_id = 27621, + .bounds = Bounds(cast(s32)bounds.x, y, width, Scale(160)), + .value = TextUntilNul(note[:]), .label = AppLocaleHost("library_note"), + .placeholder = AppLocaleHost("library_note"), .max_bytes = 2048, .max_codepoints = 2048, + .cursor = note_state.cursor, .anchor = note_state.anchor, + .scroll_y = note_state.scroll_y, .focused = note_state.focused, + .composition = note_state.composition, .wrap = true, .scale = frame.scale, .disabled = !selected, + .input = TextAreaInput.{.text = input.text, .paste_text = input.paste_text, + .composition_event = input.composition_event, .left = input.left, .right = input.right, + .home = input.home, .end = input.end, .shift = input.shift, + .backspace = input.backspace, .delete_forward = input.delete_forward, + .select_all = input.select_all, .copy = input.copy, .cut = input.cut, + .paste = input.paste, .enter = input.commit, .escape = input.escape, + .now_seconds = frame.now}}) + note_state = edit + if edit.edit.changed && EnsureAnnotation() { + if AppReplaceText(note[:], edit.edit.start, edit.edit.end, edit.edit.replacement) { + annotation_dirty = true + } + } + y += Scale(176) + // Reflow can put several older annotated passages on this page. Keep + // their notes visible as well as the editable first annotation. + for index: cast(s32)0..annotation_count - 1 { + if index != annotation_index && LibraryOverlaps(current, annotations[index]) && annotations[index].note != "" { + Text(frame.session, TextProps.{.text = annotations[index].note, .font = frame.font, + .bounds = Bounds(cast(s32)bounds.x, y, width, Scale(100))}) + y += Scale(112) + } + } +} + +FontPanel :: (bounds: Rectangle) { + x := cast(s32)bounds.x + y := cast(s32)bounds.y + width := cast(s32)bounds.width + Text(frame.session, TextProps.{.text = AppLocaleHost("library_font_size"), .font = frame.font, + .bounds = Bounds(x, y, width, Scale(28))}) + size := Spinbox(frame.session, SpinboxProps.{.key = 27630, + .bounds = Bounds(x, y + Scale(32), width, Scale(56)), .label = AppLocaleHost("library_font_size"), + .min = 14, .max = 36, .step = 1, .value = font_size, .value_text = NumberText(font_size)}) + if size.changed { + font_size = size.value + layout_width = 0 + settings_dirty = true + } + options: [2]DropdownOption + options[0].label = AppLocaleHost("library_font_system") + options[1].label = "Noto Sans" + Text(frame.session, TextProps.{.text = AppLocaleHost("library_typeface"), .font = frame.font, + .bounds = Bounds(x, y + Scale(112), width, Scale(28))}) + face := Dropdown(frame.session, DropdownProps.{.key = 27631, + .bounds = Bounds(x, y + Scale(144), width, Scale(48)), + .placeholder = AppLocaleHost("library_typeface"), .selected_index = font_face, + .scale = frame.scale}, options[:]) + if face.changed { + font_face = face.selected_index + layout_width = 0 + settings_dirty = true + } + unused SaveReader() +} + +LayoutPanel :: (bounds: Rectangle) { + x := cast(s32)bounds.x + y := cast(s32)bounds.y + width := cast(s32)bounds.width + Text(frame.session, TextProps.{.text = AppLocaleHost("library_margins"), .font = frame.font, + .bounds = Bounds(x, y, width, Scale(28))}) + Text(frame.session, TextProps.{.text = AppLocaleHost("library_line_spacing"), .font = frame.font, + .bounds = Bounds(x, y + Scale(112), width, Scale(28))}) + inset := Spinbox(frame.session, SpinboxProps.{.key = 27640, + .bounds = Bounds(x, y + Scale(32), width, Scale(56)), .label = AppLocaleHost("library_margins"), + .min = 12, .max = 56, .step = 4, .value = margin, .value_text = NumberText(margin)}) + gap := Spinbox(frame.session, SpinboxProps.{.key = 27641, + .bounds = Bounds(x, y + Scale(144), width, Scale(56)), .label = AppLocaleHost("library_line_spacing"), + .min = 2, .max = 20, .step = 2, .value = line_gap, .value_text = NumberText(line_gap)}) + if inset.changed || gap.changed { + margin = inset.value + line_gap = gap.value + layout_width = 0 + settings_dirty = true + } + unused SaveReader() +} + +ContentsPanel :: (bounds: Rectangle) { + grid := MeasureGrid(GridProps.{.bounds = bounds, .min_item_width = Scale(56), .gap = Scale(8)}) + for chapter: cast(s32)1..BookChapters(book) { + if Button(frame.session, ButtonProps.{.id = 27200 + chapter, + .bounds = GridCellBounds(grid, chapter - 1, Scale(48)), + .label = NumberText(chapter), .selected = chapter == pages[page_index].chapter, + .tone = cast(ButtonTone)ButtonToneNeutral, + .emphasis = cast(ButtonEmphasis)ButtonEmphasisSoft}) != 0 { + TurnPage(LibraryPageFor(pages[:page_count], chapter, 0)) + if !save_failed { panel_open = false } + } + } +} + +ReaderPalette :: () -> WidgetPalette { + return WidgetPalette.{ + .background = ifx book_dark then cast(u32)0x28231dff else cast(u32)0xf8f1e0ff, + .base = ifx book_dark then cast(u32)0x342e25ff else cast(u32)0xeee3ccff, + .text = ifx book_dark then cast(u32)0xe8dfccff else cast(u32)0x40372bff, + .selected = ifx book_dark then cast(u32)0xb49b70ff else cast(u32)0x89724eff, + .selected_text = ifx book_dark then cast(u32)0x211c16ff else cast(u32)0xfffbf1ff, + .border = ifx book_dark then cast(u32)0x655947ff else cast(u32)0xc9b993ff, + .danger = cast(u32)0xb54f45ff, .warning = cast(u32)0xb08b40ff, + .success = cast(u32)0x70835aff} +} + +ReaderToolbar :: () { + icons: [4]s32 = .[cast(s32)IconType.IconPencil, cast(s32)IconType.IconText, + cast(s32)IconType.IconGear, cast(s32)IconType.IconManual] + labels: [4]string = .["library_annotations", "library_font", "library_layout", "library_contents"] + size := Scale(44) + gap := Scale(4) + left := frame.width - Scale(12) - size * 5 - gap * 4 + for index: cast(s32)0..3 { + if Button(frame.session, ButtonProps.{.id = 27700 + index, + .bounds = Bounds(left + index * (size + gap), Scale(6), size, size), + .label = AppLocaleHost(labels[index]), .icon_type = icons[index], .icon_only = true, + .size = cast(ControlSize)ControlSize.ControlSizeLarge, + .selected = panel_open && panel_tab == index, + .tone = cast(ButtonTone)ButtonToneNeutral, + .emphasis = cast(ButtonEmphasis)ButtonEmphasisGhost}) != 0 && SaveReader() { + panel_open = !panel_open || panel_tab != index + panel_tab = index + panel_scroll = 0 + reader_swipe = SwipeGesture.{} + LoadPageAnnotations() + } + } + if Button(frame.session, ButtonProps.{.id = 27704, + .bounds = Bounds(left + 4 * (size + gap), Scale(6), size, size), + .label = AppLocaleHost(ifx book_dark then "theme_light" else "theme_dark"), + .icon_type = cast(s32)(ifx book_dark then IconType.IconSun else IconType.IconMoon), + .icon_only = true, .size = cast(ControlSize)ControlSize.ControlSizeLarge, + .tone = cast(ButtonTone)ButtonToneNeutral, + .emphasis = cast(ButtonEmphasis)ButtonEmphasisGhost}) != 0 { + book_dark = !book_dark + settings_dirty = true + unused SaveReader() + } +} + +ReaderPanel :: () { + bounds := ReadingBounds() + bounds.y = cast(float32)(frame.top + Scale(16)) + bounds.height = cast(float32)(frame.height - frame.bottom - cast(s32)bounds.y - Scale(48)) + Text(frame.session, TextProps.{.key = 27600, .text = AppLocaleHost( + ifx panel_tab == 0 then "library_annotations" else ifx panel_tab == 1 then "library_font" + else ifx panel_tab == 2 then "library_layout" else "library_contents"), + .font = frame.font, .bounds = bounds}) + if Button(frame.session, ButtonProps.{.id = 27601, + .bounds = Bounds(cast(s32)(bounds.x + bounds.width) - Scale(44), cast(s32)bounds.y - Scale(8), Scale(44), Scale(44)), + .label = AppLocaleHost("close_button"), .icon_type = cast(s32)IconType.IconCheck, + .icon_only = true, .size = cast(ControlSize)ControlSize.ControlSizeLarge, + .tone = cast(ButtonTone)ButtonToneNeutral, + .emphasis = cast(ButtonEmphasis)ButtonEmphasisGhost}) != 0 && SaveReader() { panel_open = false } + bounds.y += cast(float32)Scale(48) + bounds.height -= cast(float32)Scale(48) + content_height := ifx panel_tab == 0 then Scale(600) else Scale(420) + if panel_tab == 0 { + for index: cast(s32)0..annotation_count - 1 { + if index != annotation_index && LibraryOverlaps(pages[page_index], annotations[index]) && + annotations[index].note != "" { content_height += Scale(112) } + } + } + if panel_tab == 3 { + grid := MeasureGrid(GridProps.{.bounds = bounds, .min_item_width = Scale(56), .gap = Scale(8)}) + content_height = GridCellsHeight(grid, BookChapters(book), Scale(48)) + } + scroll := Scroll(frame.session, ScrollProps.{.key = cast(u64)(27602 + panel_tab), .bounds = bounds, + .content_height = content_height, .scroll_offset = panel_scroll, .scale = frame.scale}) + panel_scroll = scroll.scroll_offset if !scroll.opened { return } defer { unused End(frame.session) } - x := cast(s32)scroll.content.x - y := cast(s32)scroll.content.y - y += Title(Bounds(x, y, width, 0), BookTitle(book), frame.font + Scale(6)) + Scale(16) - saved := SavedChapter(book) - for number: cast(s32)1..count { - at := number - 1 - label: Vec(u8) - BuilderPrint(*label, "%", number) - if Button(frame.session, ButtonProps.{.id = 27200 + number, - .bounds = Bounds(x + (at % across) * (size + gap), y + (at / across) * (size + gap), size, size), - .label = BuilderFinish(label), .selected = number == saved, - .tone = ifx number == saved then cast(ButtonTone)ButtonToneAccent else cast(ButtonTone)ButtonToneNeutral, - .emphasis = cast(ButtonEmphasis)ButtonEmphasisSoft}) != 0 { - Open(book, number) - } - } + if panel_tab == 0 { AnnotationPanel(scroll.content) } + else if panel_tab == 1 { FontPanel(scroll.content) } + else if panel_tab == 2 { LayoutPanel(scroll.content) } + else { ContentsPanel(scroll.content) } } -// The chapter scrolls above its page buttons, which stay at the bottom. -ChapterView :: () { - paper := ifx frame.dark then Color.{40, 35, 29, 255} else Color.{248, 241, 224, 255} - unused Box(frame.session, BoxProps.{.key = cast(u64)27500, +ReaderView :: () { + unused WidgetPaletteUse(frame.session, ReaderPalette()) + paper := ifx book_dark then Color.{40, 35, 29, 255} else Color.{248, 241, 224, 255} + unused Box(frame.session, BoxProps.{.key = 27500, .bounds = Bounds(0, 0, frame.width, frame.height), .fill = paper}) - column := Column() - width := cast(s32)column.width - reading := frame.font + Scale(3) - buttons := Scale(48) - page := column - page.height -= cast(float32)(buttons + Scale(24)) - pointer := SamplePointer() - turn := Swipe(SwipeSpec.{.bounds = Bounds(0, frame.top, frame.width, cast(s32)(page.y + page.height) - frame.top), - .directions = cast(u32)SwipeDirection.SwipeHorizontal, - .min_distance = cast(float32)Scale(48), .axis_bias = 1.5, .max_duration = 0.8}, - chapter_swipe, SwipeFrame.{.pointer = Vector2.{pointer.x, pointer.y}, - .pressed = pointer.pressed, .down = pointer.down, .released = pointer.released, - .input_clear = true, .owner_clear = true, .now_seconds = frame.now, .scale = frame.scale}) - chapter_swipe = turn.gesture - if turn.direction == SwipeDirection.SwipeLeft && chapter < BookChapters(book) { - Open(book, chapter + 1) - } else if turn.direction == SwipeDirection.SwipeRight && chapter > 1 { - Open(book, chapter - 1) + if opening { + OpeningView() + unused WidgetPaletteUse(frame.session, ReaderPalette()) + if opening { return } } - words := BookChapter(book, chapter) - text_height := TextHeight(frame.session, TextProps.{.text = words, .font = reading, - .bounds = Bounds(0, 0, width, 0), .wrap = cast(TextWrap)TextWrapAuto}) - height := Scale(64) + text_height + Scale(24) - scroll := Scroll(frame.session, ScrollProps.{.key = 27300 + cast(u64)chapter, .bounds = page, - .content_height = height, .scroll_offset = chapter_scroll, .scale = frame.scale}) - chapter_scroll = scroll.scroll_offset - if scroll.opened { - x := cast(s32)scroll.content.x - y := cast(s32)scroll.content.y - buffer: [64]u8 - Text(frame.session, TextProps.{.text = Numbered("library_chapter", chapter, buffer[:]), - .font = frame.font - Scale(1), .bounds = Bounds(x, y, width, Scale(24))}) - y += Scale(64) - Text(frame.session, TextProps.{.text = words, .font = reading, .selectable = true, - .bounds = Bounds(x, y, width, text_height), .wrap = cast(TextWrap)TextWrapAuto}) - unused End(frame.session) + // Opening the keyboard inside the panel must not repaginate the book. + if !panel_open { + previous_width := layout_width + previous_height := layout_height + previous_scale := layout_scale + Reflow() + if page_count > 0 && (layout_width != previous_width || layout_height != previous_height || + layout_scale != previous_scale) { LoadPageAnnotations() } } - x := cast(s32)column.x - y := cast(s32)(column.y + column.height) - buttons - Scale(12) - half := (width - Scale(12)) / 2 - if Button(frame.session, ButtonProps.{.id = 27400, .bounds = Bounds(x, y, half, buttons), - .label = AppLocaleHost("library_previous"), .disabled = chapter <= 1, - .tone = cast(ButtonTone)ButtonToneNeutral, .emphasis = cast(ButtonEmphasis)ButtonEmphasisSoft}) != 0 { - Open(book, chapter - 1) + if page_count <= 0 { return } + if !panel_open && !opening { + pointer := SamplePointer() + swipe := Swipe(SwipeSpec.{.bounds = ReadingBounds(), + .directions = cast(u32)SwipeDirection.SwipeHorizontal, + .min_distance = cast(float32)Scale(48), .axis_bias = 1.5}, + reader_swipe, SwipeFrame.{.pointer = Vector2.{pointer.x, pointer.y}, + .pressed = pointer.pressed, .down = pointer.down, .released = pointer.released, + .input_clear = true, .owner_clear = true, .now_seconds = frame.now, .scale = frame.scale}) + reader_swipe = swipe.gesture + key := AppKeyHost() + if swipe.direction == SwipeDirection.SwipeLeft || key == KeyRight { TurnPage(page_index + 1) } + else if swipe.direction == SwipeDirection.SwipeRight || key == KeyLeft { TurnPage(page_index - 1) } } - if Button(frame.session, ButtonProps.{.id = 27401, .bounds = Bounds(x + half + Scale(12), y, half, buttons), - .label = AppLocaleHost("library_next"), .disabled = chapter >= BookChapters(book), - .tone = cast(ButtonTone)ButtonToneAccent, .emphasis = cast(ButtonEmphasis)ButtonEmphasisSoft}) != 0 { - Open(book, chapter + 1) + current := pages[page_index] + props := ReadingProps() + props.text = BookChapter(book, current.chapter)[current.start:current.end] + props.key = 27502 + // Emphasize only marked words; never paint a rectangle over the page. + marks: [LIBRARY_ANNOTATION_LIMIT]TextRange + mark_count: s32 + for annotation: annotations[:annotation_count] { + if !annotation.highlighted || !LibraryOverlaps(current, annotation) { continue } + start := ifx annotation.start > current.start then annotation.start - current.start else 0 + end := ifx annotation.end < current.end then annotation.end - current.start else current.end - current.start + place := mark_count + while place > 0 && marks[place - 1].start > start { + marks[place] = marks[place - 1] + place -= 1 + } + marks[place] = TextRange.{start, end} + mark_count += 1 + } + merged: s32 + for index: cast(s32)0..mark_count - 1 { + if merged > 0 && marks[index].start <= marks[merged - 1].end { + if marks[index].end > marks[merged - 1].end { marks[merged - 1].end = marks[index].end } + } else { + marks[merged] = marks[index] + merged += 1 + } + } + props.strong = marks[:merged] + if !panel_open { Text(frame.session, props) } + ReaderToolbar() + label: Vec(u8) + BuilderPrint(*label, "% / %", page_index + 1, page_count) + Text(frame.session, TextProps.{.key = 27511, .text = BuilderFinish(label), .font = frame.font - Scale(2), + .align = cast(TextAlign)TextAlignCenter, + .bounds = Bounds(0, frame.height - frame.bottom - Scale(40), frame.width, Scale(32))}) + if panel_open { ReaderPanel() } + unused WidgetPaletteUse(frame.session, ReaderPalette()) + if save_failed { + Text(frame.session, TextProps.{.text = AppLocaleHost("library_save_failed"), .font = frame.font, + .bounds = Bounds(Scale(16), frame.top + Scale(8), frame.width - Scale(216), Scale(48))}) } } LibraryView :: (message: AppMessage) -> AppMessage { frame = ReadAppUiHost() - // Another account starts on the shelf. + frame.top = Scale(56) if !loaded || loaded_account != message.account { loaded = true loaded_account = message.account - view = LIBRARY_SHELF + reading = false + panel_open = false + annotation_dirty = false + settings_dirty = false + position_dirty = false + save_failed = false + LoadSettings() } - if view == LIBRARY_CHAPTER { ChapterView() } - else if view == LIBRARY_CONTENTS { ContentsView() } + if reading { ReaderView() } else { ShelfView() } + if Button(frame.session, ButtonProps.{.id = 27710, + .bounds = Bounds(Scale(8), Scale(6), Scale(44), Scale(44)), + .label = AppLocaleHost("back_button"), .icon_type = cast(s32)IconType.IconLeft, + .icon_only = true, .size = cast(ControlSize)ControlSize.ControlSizeLarge, + .tone = cast(ButtonTone)ButtonToneNeutral, + .emphasis = cast(ButtonEmphasis)ButtonEmphasisGhost}) != 0 { + if !LibraryBack() { unused CloseAppHost() } + } + unused WidgetPaletteRestore(frame.session) message.succeeded = true return message } @@ -289,7 +774,7 @@ Main :: () -> s32 { if message.action == APP_BACK { message.succeeded = LibraryBack() } if message.action == APP_PRESENTATION { message.succeeded = true - message.screen = ifx view == LIBRARY_CHAPTER then APP_PRESENTATION_IMMERSIVE else 0 + message.screen = APP_PRESENTATION_OWN_HEADER | (ifx reading then APP_PRESENTATION_IMMERSIVE else 0) } WriteAppHost(message) return 0 diff --git a/apps/library/tao_te_ching.zi b/apps/library/tao_te_ching.zi index 134a3379f..88a853fea 100644 --- a/apps/library/tao_te_ching.zi +++ b/apps/library/tao_te_ching.zi @@ -1,10 +1,8 @@ -// The Tao Te Ching, a new English rendering made for Inner Breeze from J. H. +// The Tao Te Ching, a new English rendering made for Breeze from J. H. // McDonald's public-domain translation (1996), checked line by line against // James Legge's (1891) and the Chinese Wang Bi text. Each chapter is its own // text: a Ziran literal holds up to 4 KB. TAO_TE_CHING_TITLE :: "Tao Te Ching" -TAO_TE_CHING_AUTHOR :: "Lao Tzu" -TAO_TE_CHING_NOTE :: "A new English rendering, from J. H. McDonald’s public-domain translation, checked against James Legge’s and the Chinese text." TAO_TE_CHING_CHAPTERS :: 81 TaoTeChing :: (number: s32) -> string { diff --git a/apps/versions.json b/apps/versions.json index 5fdd96f1c..a533adf6b 100644 --- a/apps/versions.json +++ b/apps/versions.json @@ -1,5 +1,5 @@ { - "host_api": 28, + "host_api": 29, "oldest_host_api": 12, "package_format": "zx", "module_api": 2, @@ -74,7 +74,7 @@ "title": "Library", "version": "1.0.3", "sequence": 4, - "host_api": 26 + "host_api": 29 }, "radio": { "id": "inbe.radio", diff --git a/assets/fonts/subset/NotoSansJP-App-Regular.otf b/assets/fonts/subset/NotoSansJP-App-Regular.otf index 1c0a04d58..5ac83f23e 100644 Binary files a/assets/fonts/subset/NotoSansJP-App-Regular.otf and b/assets/fonts/subset/NotoSansJP-App-Regular.otf differ diff --git a/assets/fonts/subset/NotoSansKR-App-Regular.otf b/assets/fonts/subset/NotoSansKR-App-Regular.otf index 5e181b8fb..90f5873fd 100644 Binary files a/assets/fonts/subset/NotoSansKR-App-Regular.otf and b/assets/fonts/subset/NotoSansKR-App-Regular.otf differ diff --git a/assets/fonts/subset/NotoSansSC-App-Regular.otf b/assets/fonts/subset/NotoSansSC-App-Regular.otf index b1d29be73..6e84bd96f 100644 Binary files a/assets/fonts/subset/NotoSansSC-App-Regular.otf and b/assets/fonts/subset/NotoSansSC-App-Regular.otf differ diff --git a/assets/fonts/subset/NotoSansTC-App-Regular.otf b/assets/fonts/subset/NotoSansTC-App-Regular.otf index 3670fd062..da84a4bff 100644 Binary files a/assets/fonts/subset/NotoSansTC-App-Regular.otf and b/assets/fonts/subset/NotoSansTC-App-Regular.otf differ diff --git a/assets/library/font-license.txt b/assets/library/font-license.txt new file mode 100644 index 000000000..9651ea7d5 --- /dev/null +++ b/assets/library/font-license.txt @@ -0,0 +1,94 @@ +Copyright 2022 The Noto Project Authors (https://github.com/notofonts/) + +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/assets/library/noto-sans.ttf b/assets/library/noto-sans.ttf new file mode 100644 index 000000000..bd03c22c6 Binary files /dev/null and b/assets/library/noto-sans.ttf differ diff --git a/assets/library/tao-te-ching-prompt.txt b/assets/library/tao-te-ching-prompt.txt new file mode 100644 index 000000000..3844c909b --- /dev/null +++ b/assets/library/tao-te-ching-prompt.txt @@ -0,0 +1,5 @@ +Generated with the built-in image_gen tool. + +Use case: illustration-story. Asset type: portrait front cover artwork for Tao Te Ching, a clickable book in the calm Breeze reading app. Create a beautiful quiet literary book cover, full bleed flat front cover only, portrait aspect ratio 2:3. A graceful ink-wash mountain landscape with a winding river fading into luminous mist, a tiny warm sun, tranquil sage green, muted teal, warm ivory handmade paper and restrained gold accents. Sophisticated contemporary book design with a subtle linen/paper grain and a fine understated border, spacious and contemplative. Artwork should remain clear at thumbnail size. No words, no letters, no calligraphy, no author/title, no logos or watermark. No mockup scene, no perspective, no surrounding desk, no extra objects. + +Delivery asset: tao-te-ching.png, resized to 384 x 576, optimized PNG with 128 colors. diff --git a/assets/library/tao-te-ching.png b/assets/library/tao-te-ching.png new file mode 100644 index 000000000..d4bfccfb7 Binary files /dev/null and b/assets/library/tao-te-ching.png differ diff --git a/locales/cs.txt b/locales/cs.txt index 5e65b6d2e..e94ce4d9d 100644 --- a/locales/cs.txt +++ b/locales/cs.txt @@ -7237,30 +7237,10 @@ Až budeš mít dost mincí, kup si odměnu a užij si ji. Zasloužíš si ji! Knihovna --- -[library_start] -Začít číst ---- - -[library_continue] -Pokračovat kapitolou %d ---- - [library_contents] Obsah --- -[library_chapter] -Kapitola %d ---- - -[library_previous] -Předchozí kapitola ---- - -[library_next] -Další kapitola ---- - [exercise_workout] Sedmiminutový trénink --- @@ -7432,3 +7412,52 @@ Záporné hodnoty odečítají mince; 0 nedává žádné. [habit_change_coins] Mince: %s » %s --- + + +[library_annotations] +Poznámky +--- + +[library_font] +Písmo +--- + +[library_layout] +Rozvržení +--- + +[library_highlight] +Zvýraznit výběr +--- + +[library_note] +Poznámka k této pasáži +--- + +[library_font_size] +Velikost písma +--- + +[library_font_system] +Systémové písmo +--- + +[library_typeface] +Druh písma +--- + +[library_margins] +Okraje +--- + +[library_line_spacing] +Řádkování +--- + +[library_save_failed] +Uložení se nezdařilo. Zkuste to znovu. +--- + +[library_select_passage] +Vyberte pasáž pro poznámku +--- diff --git a/locales/de.txt b/locales/de.txt index 727a762a7..0379c1ef8 100644 --- a/locales/de.txt +++ b/locales/de.txt @@ -7231,30 +7231,10 @@ Sobald du genug Münzen hast, kauf dir eine Belohnung und genieße sie. Du hast Bibliothek --- -[library_start] -Lesen beginnen ---- - -[library_continue] -Weiter bei Kapitel %d ---- - [library_contents] Inhalt --- -[library_chapter] -Kapitel %d ---- - -[library_previous] -Vorheriges Kapitel ---- - -[library_next] -Nächstes Kapitel ---- - [exercise_workout] 7-Minuten-Workout --- @@ -7426,3 +7406,52 @@ Negative Werte ziehen Münzen ab; 0 vergibt keine. [habit_change_coins] Münzen: %s » %s --- + + +[library_annotations] +Anmerkungen +--- + +[library_font] +Schrift +--- + +[library_layout] +Seitenlayout +--- + +[library_highlight] +Auswahl hervorheben +--- + +[library_note] +Notiz zu dieser Textstelle +--- + +[library_font_size] +Schriftgröße +--- + +[library_font_system] +Systemschrift +--- + +[library_typeface] +Schriftart +--- + +[library_margins] +Seitenränder +--- + +[library_line_spacing] +Zeilenabstand +--- + +[library_save_failed] +Speichern fehlgeschlagen. Bitte erneut versuchen. +--- + +[library_select_passage] +Wähle eine Textstelle für eine Anmerkung +--- diff --git a/locales/en.txt b/locales/en.txt index 474007f16..0fd257abc 100644 --- a/locales/en.txt +++ b/locales/en.txt @@ -7255,30 +7255,10 @@ Once you have enough coins, buy a reward and enjoy it. You earned it! Library --- -[library_start] -Start reading ---- - -[library_continue] -Continue at chapter %d ---- - [library_contents] Contents --- -[library_chapter] -Chapter %d ---- - -[library_previous] -Previous chapter ---- - -[library_next] -Next chapter ---- - [exercise_workout] 7-Minute Workout --- @@ -7450,3 +7430,52 @@ Negative values deduct coins; 0 gives none. [habit_change_coins] Coins: %s » %s --- + + +[library_annotations] +Annotations +--- + +[library_font] +Font +--- + +[library_layout] +Layout +--- + +[library_highlight] +Highlight selection +--- + +[library_note] +Note on this passage +--- + +[library_font_size] +Font size +--- + +[library_font_system] +System font +--- + +[library_typeface] +Typeface +--- + +[library_margins] +Margins +--- + +[library_line_spacing] +Line spacing +--- + +[library_save_failed] +Could not save. Please try again. +--- + +[library_select_passage] +Select a passage to annotate +--- diff --git a/locales/es.txt b/locales/es.txt index 3c2947166..40eb1b5ab 100644 --- a/locales/es.txt +++ b/locales/es.txt @@ -7231,30 +7231,10 @@ Cuando tengas suficientes monedas, compra una recompensa y disfrútala. ¡Te la Biblioteca --- -[library_start] -Empezar a leer ---- - -[library_continue] -Seguir en el capítulo %d ---- - [library_contents] Índice --- -[library_chapter] -Capítulo %d ---- - -[library_previous] -Capítulo anterior ---- - -[library_next] -Capítulo siguiente ---- - [exercise_workout] Entrenamiento de 7 minutos --- @@ -7426,3 +7406,52 @@ Los valores negativos restan monedas; 0 no da ninguna. [habit_change_coins] Monedas: %s » %s --- + + +[library_annotations] +Anotaciones +--- + +[library_font] +Fuente +--- + +[library_layout] +Diseño +--- + +[library_highlight] +Resaltar selección +--- + +[library_note] +Nota sobre este pasaje +--- + +[library_font_size] +Tamaño de letra +--- + +[library_font_system] +Fuente del sistema +--- + +[library_typeface] +Tipo de letra +--- + +[library_margins] +Márgenes +--- + +[library_line_spacing] +Interlineado +--- + +[library_save_failed] +No se pudo guardar. Inténtalo de nuevo. +--- + +[library_select_passage] +Selecciona un pasaje para anotarlo +--- diff --git a/locales/fr.txt b/locales/fr.txt index 561ece93b..732c33e51 100644 --- a/locales/fr.txt +++ b/locales/fr.txt @@ -7219,30 +7219,10 @@ Quand tu as assez de pièces, achète une récompense et profites-en. Tu l'as bi Bibliothèque --- -[library_start] -Commencer la lecture ---- - -[library_continue] -Reprendre au chapitre %d ---- - [library_contents] Sommaire --- -[library_chapter] -Chapitre %d ---- - -[library_previous] -Chapitre précédent ---- - -[library_next] -Chapitre suivant ---- - [exercise_workout] Entraînement de 7 minutes --- @@ -7414,3 +7394,52 @@ Les valeurs négatives retirent des pièces ; 0 n’en donne aucune. [habit_change_coins] Pièces : %s » %s --- + + +[library_annotations] +Notes de lecture +--- + +[library_font] +Police +--- + +[library_layout] +Mise en page +--- + +[library_highlight] +Surligner la sélection +--- + +[library_note] +Note sur ce passage +--- + +[library_font_size] +Taille du texte +--- + +[library_font_system] +Police du système +--- + +[library_typeface] +Police de caractères +--- + +[library_margins] +Marges +--- + +[library_line_spacing] +Interligne +--- + +[library_save_failed] +Enregistrement impossible. Réessayez. +--- + +[library_select_passage] +Sélectionnez un passage à annoter +--- diff --git a/locales/id.txt b/locales/id.txt index e225dc507..90e93b3dd 100644 --- a/locales/id.txt +++ b/locales/id.txt @@ -7220,30 +7220,10 @@ Kalau koinmu sudah cukup, beli hadiah dan nikmatilah. Kamu pantas mendapatkannya Perpustakaan --- -[library_start] -Mulai membaca ---- - -[library_continue] -Lanjut di bab %d ---- - [library_contents] Daftar isi --- -[library_chapter] -Bab %d ---- - -[library_previous] -Bab sebelumnya ---- - -[library_next] -Bab berikutnya ---- - [exercise_workout] Latihan 7 Menit --- @@ -7415,3 +7395,52 @@ Nilai negatif mengurangi koin; 0 tidak memberi koin. [habit_change_coins] Koin: %s » %s --- + + +[library_annotations] +Catatan +--- + +[library_font] +Huruf +--- + +[library_layout] +Tata letak +--- + +[library_highlight] +Sorot pilihan +--- + +[library_note] +Catatan untuk bagian ini +--- + +[library_font_size] +Ukuran huruf +--- + +[library_font_system] +Huruf sistem +--- + +[library_typeface] +Jenis huruf +--- + +[library_margins] +Margin halaman +--- + +[library_line_spacing] +Jarak antarbaris +--- + +[library_save_failed] +Tidak dapat menyimpan. Silakan coba lagi. +--- + +[library_select_passage] +Pilih bagian teks untuk diberi catatan +--- diff --git a/locales/it.txt b/locales/it.txt index 3697dd5c9..bbc66b268 100644 --- a/locales/it.txt +++ b/locales/it.txt @@ -7220,30 +7220,10 @@ Quando hai abbastanza monete, compra un premio e goditelo. Te lo sei meritato! Biblioteca --- -[library_start] -Inizia a leggere ---- - -[library_continue] -Riprendi dal capitolo %d ---- - [library_contents] Indice --- -[library_chapter] -Capitolo %d ---- - -[library_previous] -Capitolo precedente ---- - -[library_next] -Capitolo successivo ---- - [exercise_workout] Allenamento di 7 minuti --- @@ -7415,3 +7395,52 @@ I valori negativi sottraggono monete; 0 non ne dà. [habit_change_coins] Monete: %s » %s --- + + +[library_annotations] +Annotazioni +--- + +[library_font] +Carattere +--- + +[library_layout] +Impaginazione +--- + +[library_highlight] +Evidenzia selezione +--- + +[library_note] +Nota su questo brano +--- + +[library_font_size] +Dimensione del testo +--- + +[library_font_system] +Carattere di sistema +--- + +[library_typeface] +Tipo di carattere +--- + +[library_margins] +Margini +--- + +[library_line_spacing] +Interlinea +--- + +[library_save_failed] +Impossibile salvare. Riprova. +--- + +[library_select_passage] +Seleziona un brano da annotare +--- diff --git a/locales/ja.txt b/locales/ja.txt index fbdfba817..814210f38 100644 --- a/locales/ja.txt +++ b/locales/ja.txt @@ -7216,30 +7216,10 @@ Inner Breeze がバージョン %s に更新されました。 ライブラリ --- -[library_start] -読み始める ---- - -[library_continue] -第%d章から続ける ---- - [library_contents] 目次 --- -[library_chapter] -第%d章 ---- - -[library_previous] -前の章 ---- - -[library_next] -次の章 ---- - [exercise_workout] 7分間ワークアウト --- @@ -7411,3 +7391,52 @@ Lumi や日記など、Inner Breeze 内のアプリを waozi.xyz から自動で [habit_change_coins] コイン:%s » %s --- + + +[library_annotations] +書き込み +--- + +[library_font] +文字 +--- + +[library_layout] +レイアウト +--- + +[library_highlight] +選択した文章を強調 +--- + +[library_note] +この文章へのメモ +--- + +[library_font_size] +文字サイズ +--- + +[library_font_system] +システムの書体 +--- + +[library_typeface] +書体 +--- + +[library_margins] +余白 +--- + +[library_line_spacing] +行間 +--- + +[library_save_failed] +保存できませんでした。もう一度お試しください。 +--- + +[library_select_passage] +メモを付ける文章を選択 +--- diff --git a/locales/ko.txt b/locales/ko.txt index ec40c4730..5e86273c5 100644 --- a/locales/ko.txt +++ b/locales/ko.txt @@ -7226,30 +7226,10 @@ Inner Breeze가 %s 버전으로 업데이트되었어요. 서재 --- -[library_start] -읽기 시작 ---- - -[library_continue] -%d장부터 계속 읽기 ---- - [library_contents] 목차 --- -[library_chapter] -%d장 ---- - -[library_previous] -이전 장 ---- - -[library_next] -다음 장 ---- - [exercise_workout] 7분 운동 --- @@ -7421,3 +7401,52 @@ Lumi, 일기 등 Inner Breeze 안의 앱을 waozi.xyz에서 자동으로 업데 [habit_change_coins] 코인: %s » %s --- + + +[library_annotations] +주석 +--- + +[library_font] +글꼴 +--- + +[library_layout] +쪽 구성 +--- + +[library_highlight] +선택한 구절 강조 +--- + +[library_note] +이 구절에 대한 메모 +--- + +[library_font_size] +글자 크기 +--- + +[library_font_system] +시스템 글꼴 +--- + +[library_typeface] +글꼴 종류 +--- + +[library_margins] +여백 +--- + +[library_line_spacing] +줄 간격 +--- + +[library_save_failed] +저장할 수 없습니다. 다시 시도해 주세요. +--- + +[library_select_passage] +주석을 달 구절을 선택하세요 +--- diff --git a/locales/pt.txt b/locales/pt.txt index a3618f457..346bc50b2 100644 --- a/locales/pt.txt +++ b/locales/pt.txt @@ -7229,30 +7229,10 @@ Quando tiver moedas suficientes, compre uma recompensa e aproveite. Você merece Biblioteca --- -[library_start] -Começar a ler ---- - -[library_continue] -Continuar no capítulo %d ---- - [library_contents] Sumário --- -[library_chapter] -Capítulo %d ---- - -[library_previous] -Capítulo anterior ---- - -[library_next] -Próximo capítulo ---- - [exercise_workout] Treino de 7 minutos --- @@ -7424,3 +7404,52 @@ Valores negativos descontam moedas; 0 não dá nenhuma. [habit_change_coins] Moedas: %s » %s --- + + +[library_annotations] +Anotações +--- + +[library_font] +Fonte +--- + +[library_layout] +Disposição +--- + +[library_highlight] +Destacar seleção +--- + +[library_note] +Nota sobre este trecho +--- + +[library_font_size] +Tamanho da fonte +--- + +[library_font_system] +Fonte do sistema +--- + +[library_typeface] +Tipo de letra +--- + +[library_margins] +Margens +--- + +[library_line_spacing] +Espaçamento entre linhas +--- + +[library_save_failed] +Não foi possível salvar. Tente novamente. +--- + +[library_select_passage] +Selecione um trecho para anotar +--- diff --git a/locales/ru.txt b/locales/ru.txt index dbb425226..d2fc47d01 100644 --- a/locales/ru.txt +++ b/locales/ru.txt @@ -7225,30 +7225,10 @@ Inner Breeze обновлён до версии %s. Библиотека --- -[library_start] -Начать чтение ---- - -[library_continue] -Продолжить с главы %d ---- - [library_contents] Содержание --- -[library_chapter] -Глава %d ---- - -[library_previous] -Предыдущая глава ---- - -[library_next] -Следующая глава ---- - [exercise_workout] 7-минутная тренировка --- @@ -7420,3 +7400,52 @@ Inner Breeze обновлён до версии %s. [habit_change_coins] Монеты: %s » %s --- + + +[library_annotations] +Заметки +--- + +[library_font] +Шрифт +--- + +[library_layout] +Оформление +--- + +[library_highlight] +Выделить выбранный текст +--- + +[library_note] +Заметка к этому отрывку +--- + +[library_font_size] +Размер шрифта +--- + +[library_font_system] +Системный шрифт +--- + +[library_typeface] +Гарнитура +--- + +[library_margins] +Поля +--- + +[library_line_spacing] +Межстрочный интервал +--- + +[library_save_failed] +Не удалось сохранить. Повторите попытку. +--- + +[library_select_passage] +Выберите отрывок для заметки +--- diff --git a/locales/zh.txt b/locales/zh.txt index 2856a2ddb..e33092f14 100644 --- a/locales/zh.txt +++ b/locales/zh.txt @@ -7231,30 +7231,10 @@ Inner Breeze 已更新至 %s 版本。 书库 --- -[library_start] -开始阅读 ---- - -[library_continue] -从第%d章继续 ---- - [library_contents] 目录 --- -[library_chapter] -第%d章 ---- - -[library_previous] -上一章 ---- - -[library_next] -下一章 ---- - [exercise_workout] 7分钟训练 --- @@ -7426,3 +7406,52 @@ Inner Breeze 已更新至 %s 版本。 [habit_change_coins] 金币:%s » %s --- + + +[library_annotations] +批注 +--- + +[library_font] +字体 +--- + +[library_layout] +排版 +--- + +[library_highlight] +突出显示所选文字 +--- + +[library_note] +此段文字的笔记 +--- + +[library_font_size] +字号 +--- + +[library_font_system] +系统字体 +--- + +[library_typeface] +字体类型 +--- + +[library_margins] +页边距 +--- + +[library_line_spacing] +行间距 +--- + +[library_save_failed] +无法保存,请重试。 +--- + +[library_select_passage] +选择要添加批注的段落 +--- diff --git a/mk/tests-cells.mk b/mk/tests-cells.mk index 1d30970c9..5e6b2a261 100644 --- a/mk/tests-cells.mk +++ b/mk/tests-cells.mk @@ -5,7 +5,7 @@ app-codec-check: python3 scripts/generate-app-codec.py --check .PHONY: cells-test -cells-test: cells $(ZIRAN_BUILD_DIR)/libziran.a $(LIBOQS_A) $(SQLITE_SRC) $(SQLITE_AMALGAMATION_H) +cells-test: library-reader-test cells $(ZIRAN_BUILD_DIR)/libziran.a $(LIBOQS_A) $(SQLITE_SRC) $(SQLITE_AMALGAMATION_H) sh tests/cells_zi_test.sh $(ZIRAN_BIN) $(LIBOQS_A) .PHONY: cells-platform-test cells-android-probe @@ -107,3 +107,7 @@ radio-android-test: radio-test: radio-app-test radio-native-test radio-web-test radio-android-test test: radio-app-test radio-native-test radio-web-test + +.PHONY: library-reader-test +library-reader-test: $(ZIRAN_BIN) + sh tests/library_reader_test.sh $(ZIRAN_BIN) diff --git a/src/app/return_bar.zi b/src/app/return_bar.zi index 0568b2020..d642290c1 100644 --- a/src/app/return_bar.zi +++ b/src/app/return_bar.zi @@ -37,6 +37,9 @@ app_return_bar_route :: (app: *InnerBreeze) -> s32 { if app.breathing.screen == ScreenProfile { return APP_NAV_ROUTE_NONE } + if app.breathing.screen == ScreenNodeApp && NodeAppOwnHeader(app.node_app_slot) { + return APP_NAV_ROUTE_NONE + } route := app_current_nav_route(app) apps := LauncherRoutes() if !RouteListContains(apps[:], cast(s32)apps.count, route) { diff --git a/src/cells/app_presentation.zi b/src/cells/app_presentation.zi index 09fe88ddd..bad7b6c88 100644 --- a/src/cells/app_presentation.zi +++ b/src/cells/app_presentation.zi @@ -1,5 +1,6 @@ -// Optional node/2 query. A package answers succeeded and sets screen to 1 -// while its current page needs the host navigation out of the way. Packages -// without this query keep their ordinary host layout. +// Optional node/2 query. A package answers succeeded with presentation flags +// in screen. Packages without this query keep their ordinary host layout. APP_PRESENTATION :: 4 APP_PRESENTATION_IMMERSIVE :: 1 +// The app draws its own return control and header inside its themed canvas. +APP_PRESENTATION_OWN_HEADER :: 2 diff --git a/src/cells/host_api.zi b/src/cells/host_api.zi index 96392d97d..44c13afa7 100644 --- a/src/cells/host_api.zi +++ b/src/cells/host_api.zi @@ -1,5 +1,5 @@ // Generated from apps/versions.json. This host runs packages built for host // interfaces from the oldest to the current one; module interfaces must match. -PackageHostAPI :: 28 +PackageHostAPI :: 29 PackageHostAPIOldest :: 12 PackageModuleAPI :: 2 diff --git a/src/cells/node_apps.zi b/src/cells/node_apps.zi index 09b1a6395..d8bccb743 100644 --- a/src/cells/node_apps.zi +++ b/src/cells/node_apps.zi @@ -700,6 +700,7 @@ NodeAppMediaGranted :: (app: string) -> bool { NodeAppCapability :: (name: string) -> bool { return name == "ReadAppHost" || name == "WriteAppHost" || name == "ReadAppUiHost" || name == "AppLocaleHost" || name == "AppRecordHost" || name == "SaveAppRecordHost" || + name == "AppKeyHost" || name == "AppFieldInputHost" || name == "CloseAppHost" || name == "AppFriendHost" || name == "AppSharedHost" || name == "AppSharedItemHost" || name == "AppInvitationHost" || name == "SendAppSharedHost" || name == "RefreshAppSharedHost" || name == "SmoothFramesHost" || name == "AudioStartHost" || @@ -1259,7 +1260,15 @@ NodeAppImmersive :: (slot: s32) -> bool { return false } message := NodeAppRunMessage(slot, AppMessage.{.action = APP_PRESENTATION}) - return message.succeeded && message.screen == APP_PRESENTATION_IMMERSIVE + return message.succeeded && (message.screen & APP_PRESENTATION_IMMERSIVE) != 0 +} + +NodeAppOwnHeader :: (slot: s32) -> bool { + if !NodeAppRunning(slot) || node_runners[slot].generic || node_runners[slot].nested != null { + return false + } + message := NodeAppRunMessage(slot, AppMessage.{.action = APP_PRESENTATION}) + return message.succeeded && (message.screen & APP_PRESENTATION_OWN_HEADER) != 0 } NodeAppAccepts :: (context: *void) -> bool { diff --git a/src/screens/node_app_screen.zi b/src/screens/node_app_screen.zi index 0de9218a4..084b79558 100644 --- a/src/screens/node_app_screen.zi +++ b/src/screens/node_app_screen.zi @@ -21,6 +21,8 @@ #import "layout" #import "layout_widget" #import "tree" +#import "tree_input" +#import "test_driver" #import, file "../platform/raylib_text_input.zi"; #import, file "../cells/node_apps.zi"; #import, file "../cells/node_app_runner.zi"; @@ -37,6 +39,8 @@ #import, file "../app/app_types.zi"; #import, file "../app/app.zi"; #import, file "../app/app_nav_state.zi"; +#import, file "../app/app_launcher_state.zi"; +#import, file "../app/app_modal_state.zi"; #import, file "../app/locale.zi"; #import, file "../app/metrics.zi"; #import, file "../app/text_buffers.zi"; @@ -104,6 +108,9 @@ NodeScreenFriend :: (app: *InnerBreeze, index: s32) -> AppPerson { return AppPerson.{.id = id, .name = NodeAppPersonName(alias, id, node_screen_friend_name[:])} } +node_screen_input_text: [1024]u8; +node_screen_input_codec: WidgetTextFieldInputCodec; + NodeScreenUiCall :: (context: *void, module: *u8, function: *u8, arguments: *HostValue, count: s32, result: *HostValue) -> s32 { app := cast(*InnerBreeze)context @@ -117,6 +124,31 @@ NodeScreenUiCall :: (context: *void, module: *u8, function: *u8, result.* = WidgetEncodeAppUiFrame(node_screen_frame, *node_screen_frame_codec) return 1 } + if name == "AppKeyHost" && count == 0 { + key := NodeAppKeyFor(NodePressedKey(), NodeRepeatedKey()) + if key == 0 && TestDriverActive() { + for candidate: cast(s32)32..348 { + if TestDriverKeyPressed(candidate) { + key = candidate + break + } + } + } + if key == 0 { key = KeyboardTake(app.ui.session) } + result.* = HostScalar("s32", key) + return 1 + } + if name == "CloseAppHost" && count == 0 { + app_block_current_click(app) + app_launcher_open(app) + result.* = HostScalar("bool", 1) + return 1 + } + if name == "AppFieldInputHost" && count == 0 { + input := SampleTextFieldInput(true, node_screen_input_text[:]) + result.* = WidgetEncodeTextFieldInput(input, *node_screen_input_codec) + return 1 + } if name == "AppLocaleHost" && count == 1 && HostScalarValid(arguments[0], "string", cast(s32)HostString) { key := NodeAppText(arguments[0]) diff --git a/tests/android_library_device.py b/tests/android_library_device.py new file mode 100644 index 000000000..79013f50b --- /dev/null +++ b/tests/android_library_device.py @@ -0,0 +1,288 @@ +#!/usr/bin/env python3 +"""Library on the shared USB Moto, through Kryon's private test-driver files. + +Run only after the release and render sessions have released the device. +The verification app's profile, driver directory and local bundles are renamed +aside and restored even when a case fails. Captures come from the USB Moto. +""" +import argparse +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +import re +import shlex +import sqlite3 +import subprocess +import time + +from library_reader_cases import LibraryReaderCases +from ui_driver import UiDriver, escape + +ROOT = Path(__file__).resolve().parents[1] +OUTPUT = ROOT / "backup/library/moto" +SERIAL = "ZE2223BQZT" +PACKAGE = "xyz.waozi.inbe.verification" +ACTIVITY = PACKAGE + "/xyz.waozi.inbe.MainActivity" +PROFILE = "files/inbe" +DRIVER = "files/kryon-test-driver" +EXTERNAL = "/sdcard/Android/data/" + PACKAGE + "/files" +TRANSFER = "/data/local/tmp/breeze-library-test" + + +class Device: + def __init__(self): + OUTPUT.mkdir(parents=True, exist_ok=True) + self.state_path = OUTPUT / "state.json" + self.state = json.loads(self.state_path.read_text()) if self.state_path.exists() else {} + assert self.adb("get-state").stdout.strip() == b"device" + assert self.shell("getprop", "ro.product.model") == "moto e6 play" + assert self.shell("getprop", "ro.build.version.sdk") == "28" + + def adb(self, *args, check=True, data=None, timeout=60): + return subprocess.run(["adb", "-s", SERIAL, *map(str, args)], input=data, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + timeout=timeout, check=check) + + def shell(self, *args, check=True): + return self.adb("shell", shlex.join(list(map(str, args))), check=check).stdout.decode().strip() + + def private(self, *args, check=True): + return self.shell("run-as", PACKAGE, *args, check=check) + + def exists(self, path): + command = "test -e " + shlex.quote(path) + return self.adb("shell", shlex.join(["run-as", PACKAGE, "sh", "-c", command]), + check=False).returncode == 0 + + def save(self): + pending = self.state_path.with_suffix(".tmp") + pending.write_text(json.dumps(self.state, indent=2) + "\n") + pending.replace(self.state_path) + + def foreground(self): + activities = self.shell("dumpsys", "activity", "activities") + return next((line.strip() for line in activities.splitlines() if "mResumedActivity:" in line), "") + + def owns_foreground(self): + current = self.foreground() + assert PACKAGE + "/" in current, "Verification app is not foreground: " + current + + def capture(self, name): + self.owns_foreground() + (OUTPUT / (name + ".png")).write_bytes(self.adb("exec-out", "screencap", "-p").stdout) + + def stop(self): + self.shell("am", "force-stop", PACKAGE) + + def start(self): + result = self.shell("am", "start", "-W", "-n", ACTIVITY, "--ez", "local_node_app", "true") + assert "Error:" not in result, result + self.owns_foreground() + + def put_private(self, source, destination): + self.shell("mkdir", "-p", TRANSFER) + remote = TRANSFER + "/" + source.name + self.adb("push", source, remote) + self.shell("chmod", "644", remote) + self.private("cp", remote, destination) + self.shell("rm", "-f", remote) + + def prepare(self, apk, bundle): + sdk = os.environ.get("ANDROID_HOME") or os.environ.get("ANDROID_SDK_ROOT") + if not sdk: + sdk = next(line.split("=", 1)[1] for line in + (ROOT / "droid/local.properties").read_text().splitlines() if line.startswith("sdk.dir=")) + aapt = sorted(Path(sdk).glob("build-tools/*/aapt"))[-1] + manifest = subprocess.check_output([str(aapt), "dump", "badging", str(apk)], text=True) + assert re.search(r"^package: name='([^']+)'", manifest, re.M)[1] == PACKAGE + assert "application-debuggable" in manifest, "Only the separate debug verification instance is allowed" + assert not self.state.get("isolated"), "Restore the previous Library test before starting another" + current = self.foreground() + assert " xyz.waozi.inbe/" not in current, "The owner's regular app is foreground" + for path in (PROFILE, DRIVER): + assert not self.exists(path + ".library-preserved"), "Preserved test data already exists: " + path + self.stop() + # Install before isolating data: package replacement may restore data + # or prepare the app's files, and must not touch the fresh test profile. + self.adb("install", "-r", "-t", apk, timeout=180) + self.state = dict(originating_chat="-1000000002", task="codex-projects-library-bookshelf", + time=datetime.now(timezone.utc).isoformat(), foreground_before=current, + apk_sha256=hashlib.sha256(apk.read_bytes()).hexdigest(), + library_sha256=hashlib.sha256(bundle.read_bytes()).hexdigest(), + isolated=True, preserved=[], external=[]) + self.save() + for path in (PROFILE, DRIVER): + if self.exists(path): + self.private("mv", path, path + ".library-preserved") + self.state["preserved"].append(path) + self.save() + self.private("mkdir", "-p", DRIVER, PROFILE) + self.private("touch", DRIVER + "/.library-test", PROFILE + "/.library-test") + self.private("mkdir", "-p", EXTERNAL) + names = self.private("ls", "-1", EXTERNAL).splitlines() + for name in names: + if name.endswith(".zx"): + assert re.fullmatch(r"[A-Za-z0-9_.-]+", name), "Unexpected local bundle name" + path = EXTERNAL + "/" + name + assert not self.exists(path + ".library-preserved") + self.private("mv", path, path + ".library-preserved") + self.state["external"].append(path) + self.save() + self.put_private(bundle, EXTERNAL + "/library.zx") + self.state["local_bundle_added"] = True + self.save() + self.start() + driver = AndroidDriver(self) + driver.tree() + self.stop() + self.private("touch", PROFILE + "/.library-test") + database = OUTPUT / "test-profile.db" + for suffix in ("", "-wal"): + result = self.adb("exec-out", "run-as", PACKAGE, "cat", PROFILE + "/inbe.db" + suffix, check=False) + local = Path(str(database) + suffix) + if result.returncode == 0: + local.write_bytes(result.stdout) + else: + local.unlink(missing_ok=True) + with sqlite3.connect(database) as db: + user = db.execute("SELECT id FROM users WHERE kind='local' LIMIT 1").fetchone()[0] + seeded = dict(language="en", language_system=0, language_setup_done=1, apps_setup_done=1, + tutorial_seen=1, habits_guide_seen=1, lumi_guides_seen=127, launcher_guide_seen=1, + package_updates_allowed=0, apps_last_update_check=1900000000, + node_apps_checked_at=int(time.time()), audio_enabled=0, sync_enabled=0, + node_app_slot_0="library", app_used_library=1) + for key, value in seeded.items(): + db.execute("INSERT INTO settings(user_id,key,value,updated_at) VALUES(?,?,?,1) " + "ON CONFLICT(user_id,key) DO UPDATE SET value=excluded.value", (user, key, str(value))) + db.commit() + standalone = OUTPUT / "seeded-profile.db" + with sqlite3.connect(standalone) as target: + db.backup(target) + self.put_private(standalone, PROFILE + "/inbe.db") + assert self.private("sha256sum", PROFILE + "/inbe.db").split()[0] == hashlib.sha256(standalone.read_bytes()).hexdigest() + self.private("rm", "-f", PROFILE + "/inbe.db-wal", PROFILE + "/inbe.db-shm") + self.start() + return AndroidDriver(self) + + def restore(self): + if not self.state.get("isolated"): + return + self.stop() + for path in (PROFILE, DRIVER): + if path in self.state.get("cleaned", []): + continue + if self.exists(path): + assert self.exists(path + "/.library-test"), "Refusing to remove unmarked data: " + path + self.private("rm", "-rf", path) + if path in self.state["preserved"]: + self.private("mv", path + ".library-preserved", path) + self.state.setdefault("cleaned", []).append(path) + self.save() + if self.state.get("local_bundle_added") and self.exists(EXTERNAL + "/library.zx"): + digest = self.private("sha256sum", EXTERNAL + "/library.zx").split()[0] + assert digest == self.state["library_sha256"], "Local Library bundle changed during the test" + self.private("rm", "-f", EXTERNAL + "/library.zx") + for path in list(self.state["external"]): + self.private("mv", path + ".library-preserved", path) + self.state["external"].remove(path) + self.save() + self.shell("rm", "-rf", TRANSFER) + self.state["isolated"] = False + self.state["restored"] = True + self.save() + + +class AndroidDriver(UiDriver): + """UiDriver's assertions and gestures, with Android's private file transport.""" + def __init__(self, phone): + self.phone = phone + super().__init__(OUTPUT / "driver") + + def reset(self): + self.phone.private("rm", "-f", DRIVER + "/command", DRIVER + "/reply", DRIVER + "/reply.tmp") + + def send(self, verb, timeout=30, **fields): + if verb in ("press", "pointer", "type", "key"): + self.phone.owns_foreground() + self.serial += 1 + parts = [str(self.serial), verb] + for name, value in fields.items(): + if value is not None: + parts.append(name + "=" + escape(int(value) if isinstance(value, bool) else value)) + local = self.directory / "command" + local.write_text("\t".join(parts) + "\n") + self.phone.private("rm", "-f", DRIVER + "/reply") + self.phone.put_private(local, DRIVER + "/command.tmp") + self.phone.private("mv", DRIVER + "/command.tmp", DRIVER + "/command") + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + result = self.phone.adb("exec-out", "run-as", PACKAGE, "cat", DRIVER + "/reply", check=False) + if result.returncode == 0: + try: + reply = json.loads(result.stdout) + except json.JSONDecodeError: + # The native driver can still be writing its response. + # Keep the pending serial until a complete JSON reply arrives. + time.sleep(.05) + continue + if reply.get("serial") == self.serial: + self.phone.private("rm", "-f", DRIVER + "/reply") + if verb == "tree": + self.last = reply + return reply + time.sleep(.05) + raise self._failure("Kryon Android driver did not answer: " + verb) + + +def chapter_text(number): + source = (ROOT / "apps/library/tao_te_ching.zi").read_text() + return re.search(rf"^TAO_{number} :: #string END\n(.*?)\nEND;$", source, re.M | re.S)[1] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("action", choices=("run", "restore")) + parser.add_argument("--apk", type=Path) + parser.add_argument("--bundle", type=Path, default=ROOT / "build/node-apps/library.zx") + args = parser.parse_args() + phone = Device() + if args.action == "restore": + phone.restore() + return + if args.apk is None: + parser.error("run requires --apk") + try: + driver = phone.prepare(args.apk.resolve(strict=True), args.bundle.resolve(strict=True)) + cases = LibraryReaderCases(driver, chapter_text, capture=phone.capture) + saved = cases.exercise() + # Also enter through Android's real touch path, independently of the + # shared widget test driver used for the detailed reader cases. + area = driver.wait(key=27502) + left = int(area["visible_x"] + area["visible_width"] * .12) + right = int(area["visible_x"] + area["visible_width"] * .88) + middle = int(area["visible_y"] + area["visible_height"] / 2) + before = cases.page_number() + phone.owns_foreground() + phone.shell("input", "swipe", right, middle, left, middle, 250) + cases.wait_page(before + 1) + phone.capture("reader-touch") + phone.shell("input", "swipe", left, middle, right, middle, 250) + cases.wait_page(before) + phone.stop() + phone.start() + driver.reset() + cases.resume(saved) + phone.state["result"] = "passed" + phone.state["cases"] = ["wooden bookshelf with cover title and author", "swipes and arrows", + "Android touch swipes", "inline icon tools", "contents", "font reflow", + "saved page", "selected passage and multiline note", "book theme", "cold restart"] + phone.save() + print("Moto Library: cover shelf, paging, contents, font reflow, resume and annotations passed through Kryon's driver") + finally: + phone.restore() + + +if __name__ == "__main__": + main() diff --git a/tests/library_reader_behavior.zi b/tests/library_reader_behavior.zi new file mode 100644 index 000000000..4824d5094 --- /dev/null +++ b/tests/library_reader_behavior.zi @@ -0,0 +1,28 @@ +// Stable anchors and annotation records use the real Library data model. +#import, file "../apps/library/books.zi"; + +#program_export +Check :: () -> s32 { + pages: [4]LibraryPage = .[LibraryPage.{1, 0, 50}, LibraryPage.{1, 51, 100}, + LibraryPage.{2, 0, 25}, LibraryPage.{2, 26, 80}] + if LibraryPageFor(pages[:], 1, 51) != 1 || LibraryPageFor(pages[:], 2, 40) != 3 { return 1 } + larger: [3]LibraryPage = .[LibraryPage.{1, 0, 25}, LibraryPage.{1, 26, 50}, LibraryPage.{1, 51, 100}] + if LibraryPageFor(larger[:], 1, 30) != 1 || LibraryPageFor(pages[:], 1, 30) != 0 { return 2 } + notes: [2]LibraryAnnotation = .[LibraryAnnotation.{12, 40, true, "Keep the quiet.\n水の道"}, + LibraryAnnotation.{60, 99, false, "A second note, with: 3 4 5\n"}] + saved := EncodeLibraryAnnotations(notes[:]) + restored: [LIBRARY_ANNOTATION_LIMIT]LibraryAnnotation + count := DecodeLibraryAnnotations(saved, restored[:]) + if count != 2 { return 3 } + for index: cast(s32)0..1 { + if restored[index].start != notes[index].start || restored[index].end != notes[index].end || + restored[index].highlighted != notes[index].highlighted || restored[index].note != notes[index].note { return 4 } + } + if !LibraryOverlaps(larger[0], restored[0]) || !LibraryOverlaps(larger[1], restored[0]) || + LibraryOverlaps(larger[2], restored[0]) { return 5 } + if DecodeLibraryAnnotations("12 40 1 99999\nmissing", restored[:]) != 0 || + DecodeLibraryAnnotations("-1 2 0 0\n", restored[:]) != 0 { return 6 } + at: s32 + if ReadLibraryNumber("214748364700", *at) != -1 { return 7 } + return 0 +} diff --git a/tests/library_reader_cases.py b/tests/library_reader_cases.py new file mode 100644 index 000000000..187c787b0 --- /dev/null +++ b/tests/library_reader_cases.py @@ -0,0 +1,189 @@ +"""The same Library interactions on desktop and Android, with optional captures.""" +import re +import time + + +class LibraryReaderCases: + def __init__(self, driver, chapter_text, log_text=lambda: "", capture=lambda name: None): + self.driver = driver + self.chapter_text = chapter_text + self.log_text = log_text + self.capture = capture + + def open_library(self): + self.driver.press(label="Library", role="button") + self.driver.wait_idle(frames=3) + downloads = self.driver.find(label="Download", role="button", visible=True) + if downloads: + self.driver.press(key=downloads[-1]["key"], role="button") + self.driver.wait(label="Open", role="button", timeout=60) + if self.driver.find(label="Open", role="button", visible=True): + self.driver.press(label="Open", role="button") + self.driver.wait(label="Tao Te Ching", role="button", timeout=60) + + def page_label(self): + self.driver.wait(key=27511) + labels = [label for label in self.driver.labels() if re.fullmatch(r"\d+ / \d+", label)] + assert len(labels) == 1, self.driver.text() + return labels[0] + + def page_number(self): + return int(self.page_label().split(" / ")[0]) + + def page_text(self): + return self.driver.wait(key=27502)["label"] + + def wait_page(self, number): + deadline = time.monotonic() + 20 + while self.page_number() != number: + assert time.monotonic() < deadline, (number, self.driver.text()) + time.sleep(.05) + + def open_tools(self, tab=None): + self.driver.press(label=tab or "Annotations", role="button") + assert not self.driver.find(role="modal"), "Reader tools opened a modal" + + def close_tools(self): + self.driver.press(label="Close", role="button") + self.driver.wait_idle(frames=3) + + def press_chapter(self, number): + for _ in range(14): + matches = self.driver.find(label=str(number), role="button", visible=True) + if matches: + self.driver.press(label=str(number), role="button") + return + self.driver.pointer(*self.driver.center(self.driver.wait(key=27605)), wheel=-3) + self.driver.release_pointer() + self.driver.wait_idle(frames=3) + raise AssertionError(("Chapter not visible", number, self.driver.text())) + + def exercise(self): + self.driver.press(label="Apps", role="button") + self.open_library() + self.driver.wait(label="Tao Te Ching", role="button") + self.driver.wait(label="Tao Te Ching", role="text") + self.driver.wait(label="Lao Tzu", role="text") + assert not self.driver.find(label="Library", role="title_bar"), "Library still has a title bar" + assert not self.driver.find(label="Start reading"), self.driver.text() + assert "the local bundle cannot run" not in self.log_text() + self.capture("shelf") + self.driver.press(label="Tao Te Ching", role="button") + self.capture("opening") + self.driver.wait_gone(key=27800) + first = self.page_text() + assert self.chapter_text(1).startswith(first), first + initial_total = int(self.page_label().split(" / ")[1]) + assert initial_total >= 81 + self.driver.wait_gone(label="Apps", role="button") + # Page gestures and desktop arrows use the same page index. + area = self.driver.wait(key=27502) + left = area["visible_x"] + area["visible_width"] * .12 + right = area["visible_x"] + area["visible_width"] * .88 + middle = area["visible_y"] + area["visible_height"] / 2 + self.driver.drag((right, middle), (left, middle)) + self.wait_page(2) + self.capture("reader") + self.driver.drag((left, middle), (right, middle)) + self.wait_page(1) + self.driver.key("right") + self.wait_page(2) + self.driver.key("left") + self.wait_page(1) + assert not self.driver.find(label="Next chapter"), self.driver.text() + theme_before = self.driver.wait(key=27704)["label"] + self.driver.press(key=27704, role="button") + theme_after = self.driver.wait(key=27704)["label"] + assert theme_after != theme_before, "Book theme did not change" + self.capture("reader-light" if theme_after == "Dark" else "reader-dark") + # Open contents inside the one reader panel; jump to a longer chapter. + self.open_tools("Contents") + self.press_chapter(39) + assert self.chapter_text(39).startswith(self.page_text()), self.page_text() + before = self.page_number() + self.driver.key("right") + self.wait_page(before + 1) + saved_page, saved_text = self.page_label(), self.page_text() + # Highlight and multiline note are stored by text range in account records. + self.page_text_snapshot = self.page_text() + self.open_tools("Annotations") + self.capture("tools") + self.driver.press(focus_id=27619, role="text_area") + self.driver.key("home") + start_cursor = self.driver.wait(focus_id=27619)["cursor"] + for _ in range(12): + self.driver.key("right", shift=True) + selection = self.driver.wait(focus_id=27619) + assert 0 < selection["cursor"] - start_cursor < len(self.page_text_snapshot) + self.driver.press(label="Highlight selection", role="toggle") + self.driver.press(focus_id=27621, role="text_area") + self.driver.type("A quiet passage.") + self.driver.key("enter") + self.driver.type("Remember the water.") + self.driver.wait(value="A quiet passage.\nRemember the water.", role="text_area") + self.capture("annotation") + self.close_tools() + self.capture("annotated-reader") + self.driver.press(label="Back", role="button") + self.driver.wait(label="Tao Te Ching", role="button") + self.driver.press(label="Tao Te Ching", role="button") + assert self.page_label() == saved_page and self.page_text() == saved_text + self.open_tools("Annotations") + self.driver.wait(value="A quiet passage.\nRemember the water.", role="text_area") + assert self.driver.wait(label="Highlight selection", role="toggle")["selected"] + self.close_tools() + # Font changes reflow from the saved text position; repeat changes give + # the same page count and never discard the anchored annotations. + self.open_tools("Font") + for _ in range(5): + self.driver.press(label="+", role="button") + self.close_tools() + large_total = int(self.page_label().split(" / ")[1]) + assert large_total > initial_total, (initial_total, large_total) + self.open_tools("Font") + for _ in range(5): + self.driver.press(label="-", role="button") + self.close_tools() + assert self.page_label() == saved_page and self.page_text() == saved_text + self.open_tools("Annotations") + self.driver.wait(value="A quiet passage.\nRemember the water.", role="text_area") + assert self.driver.wait(label="Highlight selection", role="toggle")["selected"] + self.close_tools() + self.open_tools("Font") + self.driver.press(key=27631) + self.driver.press(label="Noto Sans", role="selectable") + self.close_tools() + assert self.driver.wait(key=27502)["hidden_lines"] == 0 + self.open_tools("Font") + self.driver.press(key=27631) + self.driver.press(label="System font", role="selectable") + self.close_tools() + assert self.page_label() == saved_page and self.page_text() == saved_text + self.open_tools("Layout") + for _ in range(2): + self.driver.press(label="+", role="button", index=0) + self.driver.press(label="+", role="button", index=1) + self.close_tools() + assert self.driver.wait(key=27502)["hidden_lines"] == 0 + self.open_tools("Layout") + for _ in range(2): + self.driver.press(label="-", role="button", index=0) + self.driver.press(label="-", role="button", index=1) + self.close_tools() + assert self.page_label() == saved_page and self.page_text() == saved_text + return {"page": saved_page, "text": saved_text, "theme": theme_after} + + def resume(self, saved): + self.driver.press(label="Apps", role="button") + self.open_library() + self.driver.press(label="Tao Te Ching", role="button") + assert self.page_label() == saved["page"] and self.page_text() == saved["text"] + assert self.driver.wait(key=27704)["label"] == saved["theme"], "Book theme was lost after restart" + self.open_tools("Annotations") + self.driver.wait(value="A quiet passage.\nRemember the water.", role="text_area") + assert self.driver.wait(label="Highlight selection", role="toggle")["selected"] + self.close_tools() + self.driver.press(label="Back", role="button") + self.driver.wait(label="Tao Te Ching", role="button") + self.driver.press(label="Back", role="button") + self.driver.wait(label="Library", role="button") diff --git a/tests/library_reader_test.sh b/tests/library_reader_test.sh new file mode 100755 index 000000000..9f52b4b05 --- /dev/null +++ b/tests/library_reader_test.sh @@ -0,0 +1,26 @@ +#!/bin/sh +set -eu +root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +ziran=${1:-"$root/build/ziran-toolchain/bin/ziran"} +work=$root/build/library-reader-test +mkdir -p "$work" +# Source and saved IR must preserve Unicode note bytes and text anchors. +"$ziran" ir --root "$root/tests" --module-path "$root/build/packages/kryon/src/ui" \ + --module-path "$root/build/packages/ziran/std" -o "$work/ir" "$root/tests/library_reader_behavior.zi" +for mode in source saved; do + module=$root/tests/library_reader_behavior.zi + modules=$root/build/packages/kryon/src/ui + module_root=$root/tests + if [ "$mode" = saved ]; then + module=$work/ir/library_reader_behavior.zir + modules=$work/ir + module_root=$work/ir + fi + "$ziran" bundle --root "$module_root" --module-path "$modules" \ + --module-path "$root/build/packages/ziran/std" --entry library_reader_behavior:Check \ + -o "$work/$mode.zx" "$module" + result=$("$ziran" run "$work/$mode.zx") + test "$result" = 0 || { echo "Library reader $mode returned $result"; exit 1; } +done +cmp "$work/source.zx" "$work/saved.zx" +echo 'Library anchors survive reflow and annotation records preserve highlights, Unicode and multiline notes' diff --git a/tests/library_ui_test.py b/tests/library_ui_test.py index af8974be7..712bfe2b9 100644 --- a/tests/library_ui_test.py +++ b/tests/library_ui_test.py @@ -1,14 +1,7 @@ #!/usr/bin/env python3 -"""Library from More apps on a private display: the shelf starts the Tao Te -Ching at its first chapter, the chapter buttons turn pages, Back returns to -where the chapter was opened (the shelf or the contents), a long chapter -scrolls under page buttons that stay at the bottom, and after a restart the -shelf continues where reading stopped. - -The node's offer comes from a local package (INBE_NODE_APP_FILE), so nothing -is downloaded or published. Buttons and text are found in the app's widget -tree through Kryon's test driver. -""" +"""Exercise Library's actual package with a disposable profile and private Xvfb. +Book covers, gestures, reflow, resume and annotations use Kryon's widget tree. +Optional captures verify the private X server and the app window first.""" import os from pathlib import Path import re @@ -19,6 +12,7 @@ import tempfile import time from ui_driver import UiDriver +from library_reader_cases import LibraryReaderCases assert int(os.environ.get("DISPLAY", ":0").split(":")[-1].split(".")[0]) >= 300 ROOT = Path(__file__).resolve().parents[1] @@ -69,18 +63,35 @@ def launch(profile, name): def chapter_text(number): - """Chapter number's words, as the bundle's book source holds them.""" source = (ROOT / "apps/library/tao_te_ching.zi").read_text() return re.search(rf"^TAO_{number} :: #string END\n(.*?)\nEND;$", source, re.M | re.S)[1] -def first_line(number): - return chapter_text(number).splitlines()[0] - - -def shown(number): - driver.wait(label=f"Chapter {number}") - driver.wait(contains=first_line(number)) +def capture(name): + destination = os.environ.get("BREEZE_LIBRARY_CAPTURE") + if not destination: + return + if name == "opening": + driver.wait(key=27800, timeout=2) + time.sleep(.06) + display = os.environ["DISPLAY"].split(".")[0] + servers = [] + for entry in Path("/proc").iterdir(): + if not entry.name.isdigit(): + continue + try: + args = (entry / "cmdline").read_bytes().split(b"\0") + executable = (entry / "exe").resolve(strict=True) + if executable.name == "Xvfb" and display.encode() in args: + servers.append((entry.name, [arg.decode() for arg in args if arg])) + except (OSError, ValueError): + continue + assert len(servers) == 1, ("Private Xvfb source could not be verified", display, servers) + assert command("xdotool", "getwindowpid", window) == str(app.pid) + output = Path(destination) + output.mkdir(parents=True, exist_ok=True) + (output / "capture-source.txt").write_text(repr((display, servers, app.pid, window)) + "\n") + subprocess.run(["import", "-window", window, str(output / (name + ".png"))], check=True) with tempfile.TemporaryDirectory(prefix="inbe-library-") as directory: @@ -97,67 +108,14 @@ with tempfile.TemporaryDirectory(prefix="inbe-library-") as directory: db.execute("INSERT INTO settings(user_id,key,value,updated_at) VALUES(?,?,?,1) " "ON CONFLICT(user_id,key) DO UPDATE SET value=excluded.value", (user, key, str(value))) app, window = launch(profile, "reading") + cases = LibraryReaderCases(driver, chapter_text, lambda: (OUTPUT / "reading.log").read_text(), capture) try: - driver.press(label="Apps", role="button") - # More apps offers Library because the node (here, the local file) does. - driver.press(label="Library", role="button") - driver.wait(label="Tao Te Ching") - assert "the local bundle cannot run" not in (OUTPUT / "reading.log").read_text(), "new Library bundle was rejected and an older one downloaded" - driver.press(label="Start reading", role="button") - shown(1) - driver.wait_gone(label="Apps", role="button") - subprocess.run(["import", "-window", window, str(OUTPUT / f"reader-{WIDTH}.png")], check=True) - for start, finish, expected in [(WIDTH - 60, 60, 2), (60, WIDTH - 60, 1)]: - driver.pointer(start, HEIGHT / 2, down=True) - driver.pointer((start + finish) / 2, HEIGHT / 2, down=True) - driver.pointer(finish, HEIGHT / 2, down=True) - driver.pointer(finish, HEIGHT / 2) - driver.release_pointer() - shown(expected) - driver.press(label="Next chapter", role="button") - shown(2) - driver.press(label="Previous chapter", role="button") - shown(1) - driver.wait_idle(frames=3) - previous = driver.find(label="Previous chapter", role="button") - assert len(previous) == 1 and not previous[0]["enabled"], \ - ("the first chapter offers a previous one", previous) - # Back returns to the shelf the chapter was opened from. - driver.press(label="Back", role="button") - driver.wait(label="Continue at chapter 1", role="button") - driver.press(label="Contents", role="button") - driver.press(label="39", role="button") - shown(39) - # The chapter scrolls; its page buttons stay at the bottom. - driver.wait_idle(frames=3) - before = driver.find(label="Next chapter", role="button")[0] - assert before["visible"] and HEIGHT - 120 < before["visible_y"] + before["visible_height"] <= HEIGHT, \ - ("the page buttons sit at the bottom", before) - top = driver.find(label="Chapter 39")[0]["visible_y"] - driver.pointer(WIDTH / 2, HEIGHT / 2, wheel=-6) - driver.release_pointer() - driver.wait_idle(frames=10) - after = driver.find(label="Next chapter", role="button")[0] - moved = driver.find(label="Chapter 39") - assert not moved or not moved[0]["visible"] or moved[0]["visible_y"] < top, ("the chapter did not scroll", moved) - assert after["visible"] and after["visible_y"] == before["visible_y"], ("the page buttons scrolled", before, after) - # Back returns to the contents it was opened from. - driver.press(label="Back", role="button") - driver.press(label="3", role="button") - shown(3) - driver.press(label="Back", role="button") - driver.wait(label="39", role="button") - driver.press(label="Back", role="button") - driver.wait(label="Continue at chapter 3", role="button") + saved = cases.exercise() finally: stop(app) app, window = launch(profile, "continue") try: - driver.press(label="Apps", role="button") - driver.press(label="Library", role="button") - driver.press(label="Continue at chapter 3", role="button") - shown(3) + cases.resume(saved) finally: stop(app) -print("Library: start, turn pages both ways, Back to where a chapter opened, fixed page buttons, " - "open a chapter from the contents and continue after a restart passed") +print("Library bookshelf, swipe and arrow pages, contents, font reflow, resume and annotations persist after restart") diff --git a/tests/library_ui_test.sh b/tests/library_ui_test.sh index f7af4424f..91aeadf2e 100644 --- a/tests/library_ui_test.sh +++ b/tests/library_ui_test.sh @@ -6,6 +6,6 @@ root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) binary=${1:-"$root/build/bin/linux/breeze-linux-x86_64"} package=${2:-"$root/build/node-apps/library.zx"} env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS -u GDK_DISPLAY \ - -u SESSION_MANAGER YUE_DESKTOP_RECOVERY=0 SDL_AUDIODRIVER=dummy APP_NO_TRAY=1 \ + -u SESSION_MANAGER YUE_DESKTOP_RECOVERY=0 SDL_VIDEODRIVER=x11 LIBGL_ALWAYS_SOFTWARE=1 SDL_AUDIODRIVER=dummy APP_NO_TRAY=1 \ timeout 240s xvfb-run -a -n 311 -s '-noreset -screen 0 1280x900x24' \ python3 "$root/tests/library_ui_test.py" "$binary" "$package" diff --git a/tests/locale_keys_test.py b/tests/locale_keys_test.py index 72ba6d9f8..d60d5fe72 100644 --- a/tests/locale_keys_test.py +++ b/tests/locale_keys_test.py @@ -43,7 +43,7 @@ theme_sky theme_ocean theme_forest theme_sunset theme_lavender theme_cherry theme_dawn theme_sage theme_sepia theme_mono theme_mint theme_cobalt tutorial_step_intro tutorial_step_method tutorial_step_breathe tutorial_step_exhale_hold tutorial_step_inhale_hold -app_name_arcade app_name_chess app_name_photos +app_name_arcade app_name_chess app_name_photos app_name_library """.split() + ["sun_salutation_step_%d" % i for i in range(1, 13)]