diff --git a/crates/libbui/Cargo.toml b/crates/libbui/Cargo.toml index 3a31030..3e8a14d 100644 --- a/crates/libbui/Cargo.toml +++ b/crates/libbui/Cargo.toml @@ -12,6 +12,10 @@ keywords.workspace = true categories.workspace = true authors.workspace = true +[lib] +name = "libbui" +path = "src/lib.rs" + [[bin]] name = "libbui" path = "src/main.rs" @@ -20,5 +24,49 @@ path = "src/main.rs" libby = { workspace = true } libbui-core = { workspace = true } +tokio = { workspace = true } +tokio-util = { workspace = true } +futures-util = { workspace = true } +async-trait = { workspace = true } +reqwest = { workspace = true } +url = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +jiff = { workspace = true } +secrecy = { workspace = true } +thiserror = { workspace = true } +color-eyre = { workspace = true } +tracing = { workspace = true } +clap = { workspace = true } +clap_complete = "4.6" + +ratatui = { workspace = true } +crossterm = { workspace = true } +tui-input = { workspace = true } +unicode-width = { workspace = true } +unicode-segmentation = { workspace = true } + +# i18n: every user-visible string lives in locales//*.ftl +fluent-templates = "0.15.1" +sys-locale = "0.3.2" + +# fuzzy matching for the command palette (MPL-2.0, used unmodified) +nucleo-matcher = "0.3.1" + +# covers. `chafa-dyn` (a system library) is deliberately left out. +ratatui-image = { version = "=12.0.0-rc.3", default-features = false, features = ["crossterm"] } +image = { version = "0.25", default-features = false, features = ["jpeg", "png", "webp", "gif"] } + +# opening books, folders and libbyapp.com links with the system handler +terminal-colorsaurus = "1.0.3" +open = "5.4" + +[dev-dependencies] +insta = { workspace = true } +wiremock = { workspace = true } +pretty_assertions = { workspace = true } +tempfile = { workspace = true } +tokio = { workspace = true, features = ["test-util"] } + [lints] workspace = true diff --git a/crates/libbui/locales/en-US/app.ftl b/crates/libbui/locales/en-US/app.ftl new file mode 100644 index 0000000..8b0456c --- /dev/null +++ b/crates/libbui/locales/en-US/app.ftl @@ -0,0 +1,61 @@ +# Strings the app shell says itself: account changes, confirmations, +# downloads, the desktop, and errors. + +status-syncing = Syncing +status-sync-failed = Sync failed + +account-no-card = Choose a library card first. +account-card-switched = Now using { $library }. +account-borrowed = Borrowed “{ $title }”. +account-renewed = Renewed “{ $title }”. +account-returned = Returned “{ $title }”. +account-hold-placed = Placed a hold on “{ $title }”. +account-hold-cancelled = Cancelled the hold on “{ $title }”. +account-hold-resumed = Resumed the hold on “{ $title }”. +account-hold-suspended = + { $count -> + [one] Suspended the hold on “{ $title }” for { $count } day. + *[other] Suspended the hold on “{ $title }” for { $count } days. + } + +confirm-return-title = Return this loan? +confirm-return-body = “{ $title }” goes back to the library now. Files you have already downloaded stay on disk. +confirm-return-yes = Return +confirm-cancel-hold-title = Cancel this hold? +confirm-cancel-hold-body = You will lose your place in line for “{ $title }”. +confirm-cancel-hold-yes = Cancel hold +confirm-redownload-title = Download again? +confirm-redownload-body = “{ $title }” is already in your library folder. Downloading again keeps the existing file and adds a new one beside it. +confirm-redownload-yes = Download +confirm-quit-title = Quit while downloading? +confirm-quit-body = + { $count -> + [one] { $count } download is still running. It will pause and pick up where it left off next time. + *[other] { $count } downloads are still running. They will pause and pick up where they left off next time. + } +confirm-quit-yes = Quit + +download-queued = Queued “{ $title }”. +download-already-queued = “{ $title }” is already in the queue. +download-done = Downloaded “{ $title }”. +download-failed = Could not download “{ $title }”: { $reason } +download-libby-only = “{ $title }” can only be read or played in Libby. +download-not-on-loan = This title is no longer on loan. +download-persist-failed = Could not save the download queue: { $reason } + +system-opened-browser = Opened in your browser. +system-open-failed = Could not open it: { $reason } +system-missing-file = { $path } is no longer there. +system-copied = { $what } copied. +system-copy-failed = Could not copy: { $reason } + +error-unlinked = This device is no longer paired with Libby. +error-card-suspended = Your library has suspended this card. libbui has stopped using it; contact your library. +error-refused = Libby refused the request ({ $code }). +error-not-found = Libby could not find that. +error-rate-limited = Libby is asking us to slow down. Try again in a minute. +error-status = Libby answered with an error (HTTP { $status }). +error-unexpected = Libby sent a reply libbui does not understand. The details are in the log. +error-not-downloadable = This format can only be read or played in Libby. +error-timeout = Libby took too long to answer. Check your connection and try again. +error-network = Could not reach Libby. Check your connection and try again. diff --git a/crates/libbui/locales/en-US/common.ftl b/crates/libbui/locales/en-US/common.ftl new file mode 100644 index 0000000..abc295a --- /dev/null +++ b/crates/libbui/locales/en-US/common.ftl @@ -0,0 +1,63 @@ +### Strings shared by every screen. +### One file per area keeps translators (and parallel contributors) out of +### each other's way: common, keys, setup, shelf, search, detail, holds, +### downloads, settings, cli. + +app-name = libbui +app-tagline = Your library, in your terminal. + +## Navigation tabs +tab-shelf = Shelf +tab-search = Search +tab-holds = Holds +tab-downloads = Downloads + +## Media kinds +kind-ebook = Ebook +kind-audiobook = Audiobook +kind-magazine = Magazine +kind-other = Other + +## Time +time-days = { $count -> + [one] { $count } day + *[other] { $count } days +} +time-hours = { $count -> + [one] { $count } hour + *[other] { $count } hours +} +time-minutes = { $count -> + [one] { $count } minute + *[other] { $count } minutes +} +time-less-than-a-minute = less than a minute +time-left = { $span } left +time-ago = { $span } ago +time-expired = expired + +## States every pane can be in +state-loading = Loading… +state-empty = Nothing here yet. +state-error = Something went wrong +state-retry-hint = Press { $key } to try again. +state-offline = Can’t reach the library. Check your connection. + +## Confirmations +confirm-yes = Yes +confirm-no = No +confirm-cancel = Cancel + +## Terminal too small +too-small-title = A little more room, please +too-small-body = libbui needs at least { $cols }×{ $rows }. This window is { $have_cols }×{ $have_rows }. + +## Toast prefixes: never colour alone +toast-info = Note +toast-success = Done +toast-warning = Heads up +toast-error = Error + +## Help overlay +help-title = Keyboard shortcuts +help-scroll = { $first }–{ $last } of { $total } diff --git a/crates/libbui/locales/en-US/keys.ftl b/crates/libbui/locales/en-US/keys.ftl new file mode 100644 index 0000000..0bd60a8 --- /dev/null +++ b/crates/libbui/locales/en-US/keys.ftl @@ -0,0 +1,116 @@ +### Key binding groups, command descriptions (help overlay, command palette) +### and short labels (footer hints). `keymap.rs` has a test that fails when a +### bound command is missing either string. + +## Groups +keys-group-global = Everywhere +keys-group-list = Lists +keys-group-shelf = Shelf +keys-group-search = Search +keys-group-detail = Title details +keys-group-holds = Holds +keys-group-downloads = Downloads +keys-group-setup = Setup +keys-group-dialog = Dialogs + +## Descriptions: full sentences-ish, shown in help and the palette +cmd-quit = Quit libbui +cmd-back = Go back / close +cmd-help = Show keyboard shortcuts +cmd-palette = Open the command palette +cmd-go-shelf = Go to your shelf +cmd-go-search = Go to search +cmd-go-holds = Go to your holds +cmd-go-downloads = Go to downloads +cmd-next-tab = Next tab +cmd-prev-tab = Previous tab +cmd-next-pane = Next field +cmd-prev-pane = Previous field +cmd-refresh = Sync with the library +cmd-switch-card = Switch library card +cmd-settings = Open settings +cmd-suspend = Suspend to the shell +cmd-redraw = Redraw the screen +cmd-up = Move up +cmd-down = Move down +cmd-left = Move left +cmd-right = Move right +cmd-top = Jump to the top +cmd-bottom = Jump to the bottom +cmd-page-up = Page up +cmd-page-down = Page down +cmd-half-page-up = Half a page up +cmd-half-page-down = Half a page down +cmd-select = Open the selection +cmd-filter = Filter this list +cmd-sort = Change the sort order +cmd-borrow = Borrow this title +cmd-place-hold = Place a hold +cmd-return = Return this loan early +cmd-renew = Renew this loan +cmd-download = Download this loan +cmd-open-in-libby = Open in Libby (browser) +cmd-open-file = Open the downloaded file +cmd-copy-link = Copy a link to this title +cmd-focus-query = Edit the search +cmd-filters = Choose filters +cmd-toggle-available = Only show what’s available now +cmd-next-page = Load more results +cmd-cancel-hold = Cancel this hold +cmd-suspend-hold = Suspend or resume this hold +cmd-pause-resume = Pause or resume +cmd-cancel-download = Cancel this download +cmd-retry = Try again +cmd-clear-finished = Clear finished downloads +cmd-confirm = Confirm + +## Hints: one or two words, shown in the footer next to the key +hint-quit = quit +hint-back = back +hint-help = help +hint-palette = commands +hint-go-shelf = shelf +hint-go-search = search +hint-go-holds = holds +hint-go-downloads = downloads +hint-next-tab = next tab +hint-prev-tab = prev tab +hint-next-pane = next +hint-prev-pane = previous +hint-refresh = sync +hint-switch-card = card +hint-settings = settings +hint-suspend = suspend +hint-redraw = redraw +hint-up = up +hint-down = down +hint-left = left +hint-right = right +hint-top = top +hint-bottom = bottom +hint-page-up = page up +hint-page-down = page down +hint-half-page-up = half up +hint-half-page-down = half down +hint-select = open +hint-filter = filter +hint-sort = sort +hint-borrow = borrow +hint-place-hold = hold +hint-return = return +hint-renew = renew +hint-download = download +hint-open-in-libby = open in Libby +hint-open-file = open file +hint-copy-link = copy link +hint-focus-query = search +hint-filters = filters +hint-toggle-available = available +hint-next-page = more +hint-cancel-hold = cancel hold +hint-suspend-hold = suspend +hint-pause-resume = pause +hint-cancel-download = cancel +hint-retry = retry +hint-clear-finished = clear done +hint-confirm = confirm diff --git a/crates/libbui/src/api.rs b/crates/libbui/src/api.rs new file mode 100644 index 0000000..caed958 --- /dev/null +++ b/crates/libbui/src/api.rs @@ -0,0 +1,143 @@ +//! The seam between the interface and Libby. +//! +//! Screens never hold a [`libby::Client`]; they hold an [`Api`]. In the real +//! program that is the client. In tests it is a scripted fake, so every +//! screen can be driven end to end without a socket. + +use std::fmt::Debug; + +use async_trait::async_trait; +use libby::models::Card; +use libby::models::{CloneCode, Hold, LibraryMatch, Loan, Media, MediaKind, SearchPage, SyncState}; +use libby::{ + BorrowOptions, CardId, FormatId, Fulfillment, LibraryKey, Result, SearchQuery, TitleId, +}; +use url::Url; + +/// Everything the interface asks of Libby. +/// +/// Each method mirrors the [`libby::Client`] method of the same name; see +/// there for the wire behaviour and pacing guarantees. +#[async_trait] +pub trait Api: Send + Sync + Debug { + /// Whether this device has an identity that has been paired with an + /// account. `false` means the setup screen must run first. + fn is_linked(&self) -> bool; + + /// Fetches cards, loans and holds. + async fn sync(&self) -> Result; + + /// Pairs this device using a code generated in the Libby app. + async fn redeem_code(&self, code: &str) -> Result; + + /// Generates a code another device can use to pair with this account. + async fn clone_code(&self) -> Result; + + /// Finds libraries by name, city or postcode. + async fn find_libraries(&self, query: &str) -> Result>; + + /// Searches one library's catalogue. + async fn search(&self, library: &LibraryKey, query: &SearchQuery) -> Result; + + /// One title, with availability at `library`. + async fn library_media(&self, library: &LibraryKey, title: &TitleId) -> Result; + + /// Borrows a title. + async fn borrow( + &self, + card: &Card, + title: &TitleId, + kind: &MediaKind, + options: BorrowOptions, + ) -> Result; + + /// Renews a loan. + async fn renew(&self, card: &Card, loan: &Loan) -> Result; + + /// Returns a loan early. + async fn return_loan(&self, card: &CardId, title: &TitleId) -> Result<()>; + + /// Places a hold. + async fn place_hold(&self, card: &CardId, title: &TitleId) -> Result; + + /// Suspends a hold for `days` (0 resumes it). + async fn suspend_hold(&self, card: &CardId, title: &TitleId, days: u32) -> Result<()>; + + /// Cancels a hold. + async fn cancel_hold(&self, card: &CardId, title: &TitleId) -> Result<()>; + + /// Turns a loan into something that can be saved or opened. + async fn fulfill(&self, loan: &Loan, format: &FormatId) -> Result; + + /// Downloads a cover image. + async fn cover_bytes(&self, url: &Url) -> Result>; +} + +#[async_trait] +impl Api for libby::Client { + fn is_linked(&self) -> bool { + self.identity().is_some() + } + + async fn sync(&self) -> Result { + Self::sync(self).await + } + + async fn redeem_code(&self, code: &str) -> Result { + Self::redeem_code(self, code).await + } + + async fn clone_code(&self) -> Result { + Self::clone_code(self).await + } + + async fn find_libraries(&self, query: &str) -> Result> { + Self::find_libraries(self, query).await + } + + async fn search(&self, library: &LibraryKey, query: &SearchQuery) -> Result { + Self::search(self, library, query).await + } + + async fn library_media(&self, library: &LibraryKey, title: &TitleId) -> Result { + Self::library_media(self, library, title).await + } + + async fn borrow( + &self, + card: &Card, + title: &TitleId, + kind: &MediaKind, + options: BorrowOptions, + ) -> Result { + Self::borrow(self, card, title, kind, options).await + } + + async fn renew(&self, card: &Card, loan: &Loan) -> Result { + Self::renew(self, card, loan).await + } + + async fn return_loan(&self, card: &CardId, title: &TitleId) -> Result<()> { + Self::return_loan(self, card, title).await + } + + async fn place_hold(&self, card: &CardId, title: &TitleId) -> Result { + Self::place_hold(self, card, title).await + } + + async fn suspend_hold(&self, card: &CardId, title: &TitleId, days: u32) -> Result<()> { + Self::suspend_hold(self, card, title, days).await + } + + async fn cancel_hold(&self, card: &CardId, title: &TitleId) -> Result<()> { + Self::cancel_hold(self, card, title).await + } + + async fn fulfill(&self, loan: &Loan, format: &FormatId) -> Result { + Self::fulfill(self, loan, format).await + } + + async fn cover_bytes(&self, url: &Url) -> Result> { + Self::cover_bytes(self, url).await + } +} diff --git a/crates/libbui/src/app/chrome.rs b/crates/libbui/src/app/chrome.rs new file mode 100644 index 0000000..14598ad --- /dev/null +++ b/crates/libbui/src/app/chrome.rs @@ -0,0 +1,206 @@ +//! The frame around every screen: tabs on top, key hints below, toasts in +//! the corner, and a polite refusal when the window is too small. + +use ratatui::Frame; +use ratatui::layout::{Alignment, Constraint, Rect}; +use ratatui::text::{Line, Span}; +use ratatui::widgets::{Paragraph, Wrap}; + +use super::{MIN_SIZE, Shared, Tab}; +use crate::keymap::{Command, Context}; +use crate::t; +use crate::ui::hints::{Hint, HintBar}; +use crate::ui::text; +use crate::ui::toast::{ToastStack, Toasts}; + +/// Draws the header. Returns where each tab landed, for mouse clicks. +/// +/// `active` is `None` during setup, when there are no tabs to show. +pub(super) fn header( + frame: &mut Frame<'_>, + area: Rect, + shared: &Shared, + active: Option, +) -> Vec<(Tab, Rect)> { + let theme = &shared.theme; + let mut spans = vec![ + Span::raw(" "), + Span::styled(t!("app-name"), theme.accent), + Span::raw(" "), + ]; + let mut tab_areas = Vec::new(); + + if let Some(active) = active { + for tab in Tab::ALL { + let key = shared + .keymap + .primary(Context::Global, tab.command()) + .map(|chord| chord.to_string()); + let mut label = t!(tab.title_key()); + if let Some(badge) = badge(tab, shared) { + label = format!("{label} {badge}"); + } + let start = area.x + line_width(&spans); + if tab == active { + // Brackets as well as colour: the active tab must be + // findable without either. + spans.push(Span::styled("[", theme.accent)); + spans.push(Span::styled(label, theme.strong)); + spans.push(Span::styled("]", theme.accent)); + } else { + spans.push(Span::raw(" ")); + if let Some(key) = key { + spans.push(Span::styled(key, theme.key)); + spans.push(Span::raw(" ")); + } + spans.push(Span::styled(label, theme.muted)); + spans.push(Span::raw(" ")); + } + let end = area.x + line_width(&spans); + tab_areas.push((tab, Rect::new(start, area.y, end - start, 1))); + spans.push(Span::raw(" ")); + } + } + + let x = area.x + line_width(&spans); + let status = status(shared); + let left_width = usize::from(x - area.x); + let room = usize::from(area.width).saturating_sub(left_width + 1); + frame.render_widget(Line::from(spans), area); + if room > 0 { + let status = fit_status(status, room, shared); + frame.render_widget( + Paragraph::new(status).alignment(Alignment::Right), + Rect::new(area.x, area.y, area.width.saturating_sub(1), 1), + ); + } + tab_areas +} + +fn line_width(spans: &[Span<'_>]) -> u16 { + let width: usize = spans.iter().map(|span| text::width(&span.content)).sum(); + u16::try_from(width).unwrap_or(u16::MAX) +} + +/// The count shown beside a tab's name, when it says something useful. +fn badge(tab: Tab, shared: &Shared) -> Option { + let count = match tab { + Tab::Shelf => shared.account.loans().len(), + Tab::Holds => shared.account.holds().len(), + Tab::Downloads => shared.downloads.active_count(), + Tab::Search => 0, + }; + (count > 0).then(|| count.to_string()) +} + +/// The right-hand status: sync state and the active library. +fn status(shared: &Shared) -> Vec<(String, ratatui::style::Style)> { + let theme = &shared.theme; + let mut parts = Vec::new(); + if shared.account.syncing { + parts.push(( + format!("{} {}", shared.spinner(), t!("status-syncing")), + theme.info, + )); + } else if shared.account.error.is_some() { + parts.push(( + format!("{} {}", shared.symbols.warn, t!("status-sync-failed")), + theme.warning, + )); + } + if let Some(card) = shared.account.active() { + parts.push((card.library.name.clone(), theme.muted)); + } + parts +} + +fn fit_status( + parts: Vec<(String, ratatui::style::Style)>, + room: usize, + shared: &Shared, +) -> Line<'static> { + let separator = format!(" {} ", shared.symbols.dot); + let mut spans = Vec::new(); + let mut used = 0; + for (label, style) in parts { + let gap = if spans.is_empty() { + 0 + } else { + text::width(&separator) + }; + let available = room.saturating_sub(used + gap); + if available < 4 { + break; + } + let label = text::truncate(&label, available, shared.symbols.ellipsis); + if gap > 0 { + spans.push(Span::styled(separator.clone(), shared.theme.faint)); + } + used += gap + text::width(&label); + spans.push(Span::styled(label, style)); + } + Line::from(spans) +} + +/// Draws the key hints. +pub(super) fn footer( + frame: &mut Frame<'_>, + area: Rect, + shared: &Shared, + contexts: &[Context], + commands: &[Command], +) { + let hints: Vec = commands + .iter() + .filter_map(|command| { + let chord = contexts + .iter() + .find_map(|context| shared.keymap.primary_in(*context, *command))?; + Some(Hint { + key: chord.to_string(), + label: crate::i18n::lookup(&command.hint_key(), &[]), + }) + }) + .collect(); + let inner = Rect::new( + area.x.saturating_add(1), + area.y, + area.width.saturating_sub(2), + area.height, + ); + frame.render_widget(HintBar::new(&hints, &shared.theme, &shared.symbols), inner); +} + +/// Draws the toasts over the top-right of the body. +pub(super) fn toasts(frame: &mut Frame<'_>, body: Rect, shared: &Shared, toasts: &Toasts) { + let area = Rect::new(body.x, body.y, body.width.saturating_sub(1), body.height); + frame.render_widget( + ToastStack::new(toasts, &shared.theme, &shared.symbols), + area, + ); +} + +/// Replaces the whole interface when the terminal is too small to be useful. +pub(super) fn too_small(frame: &mut Frame<'_>, area: Rect, shared: &Shared) { + let lines = vec![ + Line::styled(t!("too-small-title"), shared.theme.strong), + Line::styled( + t!( + "too-small-body", + cols = MIN_SIZE.0, + rows = MIN_SIZE.1, + have_cols = area.width, + have_rows = area.height + ), + shared.theme.muted, + ), + ]; + let height = area.height.min(4); + let rect = area.centered(Constraint::Percentage(100), Constraint::Length(height)); + frame.render_widget( + Paragraph::new(lines) + .alignment(Alignment::Center) + .wrap(Wrap { trim: true }), + rect, + ); +} diff --git a/crates/libbui/src/app/errors.rs b/crates/libbui/src/app/errors.rs new file mode 100644 index 0000000..795fed4 --- /dev/null +++ b/crates/libbui/src/app/errors.rs @@ -0,0 +1,43 @@ +//! Turning errors into sentences a reader can act on. +//! +//! The libraries' `Display` text is written for logs. What reaches the +//! screen comes from here: localized, free of status codes where a plainer +//! sentence exists, and always saying what to do next when there is +//! something to do. + +use libby::Error; + +use crate::t; + +/// A short, localized description of `error`. +/// +/// The full error (with its source chain) belongs in the log; call sites +/// that have not logged it yet should. +#[must_use] +pub fn describe(error: &Error) -> String { + match error { + Error::Unlinked => t!("error-unlinked"), + Error::CardSuspended { .. } => t!("error-card-suspended"), + // Libby's own explanation is already written for patrons. + Error::Refused { explanation, .. } if !explanation.trim().is_empty() => { + libby::sanitize::sanitize_line(explanation) + } + Error::Refused { code, .. } => t!("error-refused", code = code.as_str()), + Error::NotFound { .. } => t!("error-not-found"), + Error::RateLimited { .. } => t!("error-rate-limited"), + Error::Status { status, .. } => t!("error-status", status = *status), + Error::Decode { .. } | Error::Malformed { .. } => t!("error-unexpected"), + Error::NotDownloadable { .. } => t!("error-not-downloadable"), + Error::InvalidInput(message) => libby::sanitize::sanitize_line(message), + Error::Network { source, .. } => { + if source.is_timeout() { + t!("error-timeout") + } else { + t!("error-network") + } + } + // `Error` is non-exhaustive: a variant added later still gets its + // own words rather than a shrug. + other => libby::sanitize::sanitize_line(&other.to_string()), + } +} diff --git a/crates/libbui/src/app/mod.rs b/crates/libbui/src/app/mod.rs new file mode 100644 index 0000000..36e4bec --- /dev/null +++ b/crates/libbui/src/app/mod.rs @@ -0,0 +1,1376 @@ +//! The application: one state, one `update`, one `render`. +//! +//! Everything that happens is an [`Action`]: a key press, a tick, a reply +//! from Libby, a download event. [`App::dispatch`] folds an action into the +//! state and returns the asynchronous work it started. The run loop (see +//! [`run`]) spawns that work and feeds the results back in as more actions; +//! the test harness awaits it inline instead. The app itself never awaits, +//! never sleeps and never touches the terminal, so it is fast and +//! deterministic. + +use std::collections::VecDeque; +use std::future::Future; +use std::path::PathBuf; +use std::pin::Pin; +use std::sync::Arc; +use std::time::Instant; + +use crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind}; +use jiff::Timestamp; +use libbui_core::download::{self, FileKind, JobId, JobSpec, JobState}; +use libby::models::{DownloadKind, Hold, Loan, Media, SyncState}; +use libby::{BorrowOptions, CardId, FormatId, TitleId}; +use ratatui::Frame; +use ratatui::layout::{Constraint, Layout, Position, Rect}; +use url::Url; + +use crate::keymap::{Command, Context}; +use crate::screens::{Modal, ModalFlow, Screen}; +use crate::screens::{detail, downloads, holds, search, setup, shelf}; +use crate::t; +use crate::tui::Event; +use crate::ui::toast::{Toast, Toasts}; + +mod chrome; +pub mod errors; +pub mod modals; +pub mod overlays; +mod run; +mod shared; + +pub use run::{Runtime, run}; +pub use shared::{Account, Busy, DownloadQueue, Downloads, Op, Services, Shared, System}; + +/// The smallest terminal the layouts are designed for. +pub const MIN_SIZE: (u16, u16) = (60, 16); + +/// How stale the account may get before regaining focus refreshes it. +const REFRESH_ON_FOCUS_AFTER: jiff::SignedDuration = jiff::SignedDuration::from_mins(10); + +/// Asynchronous work that ends in an [`Action`]. +pub type Task = Pin + Send + 'static>>; + +/// Everything that can happen. +#[derive(Debug)] +pub enum Action { + /// Terminal input. + Event(Event), + /// Time passed. + Tick { + /// Wall-clock time, for anything shown to the user. + now: Timestamp, + /// Monotonic time, for timers. + instant: Instant, + }, + /// A screen (or the palette) asks the app to do something. + Request(Request), + /// A request the user has already confirmed; runs without asking again. + Confirmed(Request), + /// Libby replied to an account operation. + Account(AccountEvent), + /// The download engine reported something. + Engine(download::Event), + /// A cover finished loading (`None`: it failed). + Cover { + /// Which cover. + url: Url, + /// The encoded image. + bytes: Option>, + }, + /// Run a command as if its key had been pressed (the palette does this). + Command(Command), + /// Show a notice. + Toast(Toast), + /// A reply for the shelf. + Shelf(shelf::Msg), + /// A reply for search. + Search(search::Msg), + /// A reply for the detail view. + Detail(detail::Msg), + /// A reply for holds. + Holds(holds::Msg), + /// A reply for downloads. + Downloads(downloads::Msg), + /// A reply for setup. + Setup(setup::Msg), + /// A reply for the open modal. + Modal(overlays::Msg), +} + +/// Something a screen asks the app to do on its behalf. +/// +/// Account changes are requests rather than screen-local work so that the +/// rules live in one place: confirmation before anything destructive, one +/// operation per title at a time, the same toast wording everywhere, and the +/// shared account updated before any screen redraws. +#[derive(Debug, Clone)] +pub enum Request { + /// Refresh cards, loans and holds. + Sync, + /// Borrow a title on the active card. + Borrow(Box), + /// Renew a loan. + Renew(Box), + /// Return a loan early (asks first). + Return(Box), + /// Place a hold on the active card. + PlaceHold(Box), + /// Cancel a hold (asks first). + CancelHold(Box), + /// Suspend a hold for `days`, or resume it with 0. + SuspendHold { + /// The hold. + hold: Box, + /// Days to suspend for; 0 resumes. + days: u32, + }, + /// Download a loan. With no `format`, the best downloadable one is + /// chosen: content files before ACSM tokens, EPUB before PDF. + Download { + /// The loan. + loan: Box, + /// A specific format, or the best available. + format: Option, + /// Catalogue details to enrich the metadata sidecar, when known. + media: Option>, + }, + /// Open a title in the Libby web app. + OpenInLibby(TitleId), + /// Open a URL in the browser. + OpenUrl(Url), + /// Open a file or folder. + OpenPath(PathBuf), + /// Copy text to the clipboard. + Copy { + /// The text. + text: String, + /// What it is, already localized, for the toast ("Link"). + what: String, + }, + /// Use another card for searching and borrowing. + SwitchCard(CardId), + /// Open the detail view. + ShowDetail(detail::Target), + /// Switch tab. + Go(Tab), + /// Open a modal. + Open(ModalBox), + /// Leave the program (asks first if downloads are running). + Quit, +} + +/// A boxed modal that can ride inside a (cloneable, debuggable) request. +#[derive(Debug, Clone)] +pub struct ModalBox(Arc>>>); + +impl ModalBox { + /// Wraps a modal. + #[must_use] + pub fn new(modal: impl Modal + Send + 'static) -> Self { + Self(Arc::new(std::sync::Mutex::new(Some(Box::new(modal))))) + } + + fn take(&self) -> Option> { + self.0.lock().ok()?.take() + } +} + +/// Libby's reply to an account operation. +#[derive(Debug)] +pub enum AccountEvent { + /// A sync finished. + Synced(libby::Result), + /// A borrow finished. + Borrowed { + /// The title. + title: TitleId, + /// Its name, for the toast. + name: String, + /// The new loan. + result: libby::Result, + }, + /// A renewal finished. + Renewed { + /// The title. + title: TitleId, + /// Its name, for the toast. + name: String, + /// The renewed loan. + result: libby::Result, + }, + /// A return finished. + Returned { + /// The title. + title: TitleId, + /// Its name, for the toast. + name: String, + /// Whether it worked. + result: libby::Result<()>, + }, + /// A hold was placed. + HoldPlaced { + /// The title. + title: TitleId, + /// Its name, for the toast. + name: String, + /// The new hold. + result: libby::Result, + }, + /// A hold was cancelled. + HoldCancelled { + /// The title. + title: TitleId, + /// Its name, for the toast. + name: String, + /// Whether it worked. + result: libby::Result<()>, + }, + /// A hold was suspended or resumed. + HoldSuspended { + /// The title. + title: TitleId, + /// Its name, for the toast. + name: String, + /// Days suspended for; 0 means resumed. + days: u32, + /// Whether it worked. + result: libby::Result<()>, + }, +} + +/// The top-level tabs. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Tab { + /// Loans. + Shelf, + /// The catalogue. + Search, + /// Holds. + Holds, + /// The download queue. + Downloads, +} + +impl Tab { + /// Every tab, in display order. + pub const ALL: [Self; 4] = [Self::Shelf, Self::Search, Self::Holds, Self::Downloads]; + + /// The Fluent key for the tab's label. + #[must_use] + pub const fn title_key(self) -> &'static str { + match self { + Self::Shelf => "tab-shelf", + Self::Search => "tab-search", + Self::Holds => "tab-holds", + Self::Downloads => "tab-downloads", + } + } + + /// The command that jumps to this tab. + #[must_use] + pub const fn command(self) -> Command { + match self { + Self::Shelf => Command::GoShelf, + Self::Search => Command::GoSearch, + Self::Holds => Command::GoHolds, + Self::Downloads => Command::GoDownloads, + } + } + + fn index(self) -> usize { + Self::ALL.iter().position(|tab| *tab == self).unwrap_or(0) + } + + fn offset(self, by: isize) -> Self { + let len = Self::ALL.len().cast_signed(); + let next = (self.index().cast_signed() + by).rem_euclid(len); + Self::ALL[next.cast_unsigned()] + } +} + +/// Work and follow-up actions produced while handling one action. +#[derive(Default)] +pub struct Outbox { + actions: VecDeque, + tasks: Vec, +} + +impl std::fmt::Debug for Outbox { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Outbox") + .field("actions", &self.actions) + .field("tasks", &self.tasks.len()) + .finish() + } +} + +/// What a screen can see and do while handling input. +#[derive(Debug)] +pub struct Ctx<'a> { + /// Shared, read-only state. + pub shared: &'a Shared, + /// Handles for starting work. + pub services: &'a Services, + out: &'a mut Outbox, +} + +impl Ctx<'_> { + /// Starts asynchronous work whose result comes back as an action. + /// + /// Screens should tag their requests (a sequence number in the `Msg`) + /// and ignore stale replies; work is not cancelled when the user moves + /// on. + pub fn spawn(&mut self, work: impl Future + Send + 'static) { + self.out.tasks.push(Box::pin(work)); + } + + /// Queues an action to be handled right after the current one. + pub fn send(&mut self, action: Action) { + self.out.actions.push_back(action); + } + + /// Asks the app to do something. + pub fn request(&mut self, request: Request) { + self.send(Action::Request(request)); + } + + /// Shows a notice. + pub fn toast(&mut self, toast: Toast) { + self.send(Action::Toast(toast)); + } + + /// Opens a modal over the current screen. + pub fn open(&mut self, modal: impl Modal + Send + 'static) { + self.request(Request::Open(ModalBox::new(modal))); + } +} + +/// What the run loop must do that the app cannot (it owns no terminal). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum LoopRequest { + /// Stop the process until the shell resumes it. + Suspend, + /// Clear and repaint everything. + Redraw, +} + +/// The whole interface. +pub struct App { + shared: Shared, + services: Services, + out: Outbox, + toasts: Toasts, + tab: Tab, + /// Whether the detail view covers the current tab. + detail_open: bool, + /// Whether the device still needs pairing. + needs_setup: bool, + modal: Option>, + shelf: shelf::Shelf, + search: search::Search, + detail: detail::Detail, + holds: holds::Holds, + downloads: downloads::Downloads, + setup: setup::Setup, + /// Where the body and the tabs were last drawn, for mouse hit-testing. + body_area: Rect, + tab_areas: Vec<(Tab, Rect)>, + last_instant: Instant, + quit: bool, + loop_request: Option, +} + +impl std::fmt::Debug for App { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("App") + .field("tab", &self.tab) + .field("detail_open", &self.detail_open) + .field("needs_setup", &self.needs_setup) + .field("modal", &self.modal) + .finish_non_exhaustive() + } +} + +/// Builds a [`Ctx`] from disjoint fields of the app, so a screen (another +/// field) can be borrowed mutably at the same time. +macro_rules! cx { + ($app:ident) => { + &mut Ctx { + shared: &$app.shared, + services: &$app.services, + out: &mut $app.out, + } + }; +} + +/// Runs `$body` with `$screen` bound to whichever screen is showing. +macro_rules! with_screen { + ($app:ident, |$screen:ident| $body:expr) => { + match $app.view() { + View::Setup => { + let $screen = &mut $app.setup; + $body + } + View::Detail => { + let $screen = &mut $app.detail; + $body + } + View::Tab(Tab::Shelf) => { + let $screen = &mut $app.shelf; + $body + } + View::Tab(Tab::Search) => { + let $screen = &mut $app.search; + $body + } + View::Tab(Tab::Holds) => { + let $screen = &mut $app.holds; + $body + } + View::Tab(Tab::Downloads) => { + let $screen = &mut $app.downloads; + $body + } + } + }; +} + +/// Which screen is on top. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +enum View { + Setup, + Detail, + Tab(Tab), +} + +impl App { + /// A new app. Call [`App::start`] to kick off the first sync. + #[must_use] + pub fn new(shared: Shared, services: Services) -> Self { + let needs_setup = !services.api.is_linked(); + Self { + shared, + services, + out: Outbox::default(), + toasts: Toasts::default(), + tab: Tab::Shelf, + detail_open: false, + needs_setup, + modal: None, + shelf: shelf::Shelf::default(), + search: search::Search::default(), + detail: detail::Detail::default(), + holds: holds::Holds::default(), + downloads: downloads::Downloads::default(), + setup: setup::Setup::default(), + body_area: Rect::default(), + tab_areas: Vec::new(), + last_instant: Instant::now(), + quit: false, + loop_request: None, + } + } + + /// Shows the first screen and starts the first sync (if paired). + pub fn start(&mut self) -> Vec { + if !self.needs_setup { + self.out.actions.push_back(Action::Request(Request::Sync)); + } + with_screen!(self, |screen| screen.on_show(cx!(self))); + self.drain() + } + + /// The shared state, for rendering helpers and tests. + #[must_use] + pub const fn shared(&self) -> &Shared { + &self.shared + } + + /// Mutable shared state, for the run loop's setup and tests. + pub const fn shared_mut(&mut self) -> &mut Shared { + &mut self.shared + } + + /// The tab that is (or is underneath what is) showing. + #[must_use] + pub const fn tab(&self) -> Tab { + self.tab + } + + /// Whether the user asked to leave. + #[must_use] + pub const fn should_quit(&self) -> bool { + self.quit + } + + /// Whether the app needs ticks at animation rate right now. + #[must_use] + pub fn is_animating(&self) -> bool { + self.shared.is_animating() || self.toasts.needs_tick() + } + + /// Takes the pending request for the run loop, if any. + pub const fn take_loop_request(&mut self) -> Option { + self.loop_request.take() + } + + /// The visible toasts, for tests. + pub fn toasts(&self) -> impl Iterator { + self.toasts.visible() + } + + /// Whether a modal is open, for tests. + #[must_use] + pub const fn has_modal(&self) -> bool { + self.modal.is_some() + } + + const fn view(&self) -> View { + if self.needs_setup { + View::Setup + } else if self.detail_open { + View::Detail + } else { + View::Tab(self.tab) + } + } + + /// Folds one action into the state. Returns the work it started. + pub fn dispatch(&mut self, action: Action) -> Vec { + self.out.actions.push_back(action); + self.drain() + } + + fn drain(&mut self) -> Vec { + while let Some(action) = self.out.actions.pop_front() { + self.update(action); + } + // Anything queued while nothing is ticking needs its clock started. + self.toasts.tick(self.last_instant); + std::mem::take(&mut self.out.tasks) + } + + fn update(&mut self, action: Action) { + match action { + Action::Event(event) => self.on_event(event), + Action::Tick { now, instant } => { + self.shared.now = now; + self.last_instant = instant; + if self.shared.is_animating() { + self.shared.frame = self.shared.frame.wrapping_add(1); + } + self.toasts.tick(instant); + } + Action::Request(request) => self.on_request(request, false), + Action::Confirmed(request) => self.on_request(request, true), + Action::Account(event) => self.on_account(event), + Action::Engine(event) => self.on_engine(event), + Action::Cover { url, bytes } => self.shared.covers.insert(&url, bytes), + Action::Command(command) => self.on_command(command), + Action::Toast(toast) => self.toasts.push(toast), + Action::Shelf(msg) => self.shelf.on_msg(msg, cx!(self)), + Action::Search(msg) => self.search.on_msg(msg, cx!(self)), + Action::Detail(msg) => self.detail.on_msg(msg, cx!(self)), + Action::Holds(msg) => self.holds.on_msg(msg, cx!(self)), + Action::Downloads(msg) => self.downloads.on_msg(msg, cx!(self)), + Action::Setup(msg) => self.setup.on_msg(msg, cx!(self)), + Action::Modal(msg) => { + if let Some(modal) = self.modal.as_mut() { + let flow = overlays::on_msg(modal.as_mut(), msg, cx!(self)); + self.apply_flow(flow); + } + } + } + } + + // ── Input ────────────────────────────────────────────────────────────── + + fn on_event(&mut self, event: Event) { + match event { + Event::Key(key) => self.on_key(key), + Event::Paste(text) => { + if let Some(modal) = self.modal.as_mut() { + modal.on_paste(&text, cx!(self)); + } else if with_screen!(self, |screen| screen.captures_text()) { + with_screen!(self, |screen| screen.on_paste(&text, cx!(self))); + } + } + Event::Mouse(mouse) => self.on_mouse(mouse), + Event::FocusGained => { + let stale = + self.shared.account.synced_at.is_some_and(|at| { + self.shared.now.duration_since(at) >= REFRESH_ON_FOCUS_AFTER + }); + if stale && !self.needs_setup { + self.on_request(Request::Sync, false); + } + } + Event::Resize(..) | Event::FocusLost => {} + } + } + + fn on_key(&mut self, key: KeyEvent) { + if let Some(modal) = self.modal.as_mut() { + // A modal sees every key first; what it declines goes through + // the keymap, except typing while it has a text field. + let flow = match modal.on_key(key, cx!(self)) { + Some(flow) => flow, + None if modal.captures_text() && is_text(key) => ModalFlow::Stay, + None => match self.shared.keymap.resolve(modal.contexts(), key) { + Some(command) => modal.on_command(command, cx!(self)), + None => ModalFlow::Stay, + }, + }; + self.apply_flow(flow); + return; + } + + let captures = with_screen!(self, |screen| screen.captures_text()); + if captures { + if with_screen!(self, |screen| screen.on_key(key, cx!(self))).is_yes() { + return; + } + if is_text(key) { + return; + } + } + let contexts = self.contexts(); + if let Some(command) = self.shared.keymap.resolve(&contexts, key) { + self.on_command(command); + } + } + + /// The keymap contexts for the visible screen, most specific first. + fn contexts(&self) -> [Context; 3] { + let screen = match self.view() { + View::Setup => self.setup.context(), + View::Detail => self.detail.context(), + View::Tab(Tab::Shelf) => self.shelf.context(), + View::Tab(Tab::Search) => self.search.context(), + View::Tab(Tab::Holds) => self.holds.context(), + View::Tab(Tab::Downloads) => self.downloads.context(), + }; + [screen, Context::List, Context::Global] + } + + fn on_command(&mut self, command: Command) { + if let Some(modal) = self.modal.as_mut() { + let flow = modal.on_command(command, cx!(self)); + self.apply_flow(flow); + return; + } + if with_screen!(self, |screen| screen.on_command(command, cx!(self))).is_yes() { + return; + } + match command { + Command::Quit => self.on_request(Request::Quit, false), + Command::Back => { + if self.detail_open { + self.detail_open = false; + with_screen!(self, |screen| screen.on_show(cx!(self))); + } else { + self.toasts.dismiss(); + } + } + Command::Help => { + self.modal = Some(Box::new(modals::HelpModal::new(self.contexts().to_vec()))); + } + Command::Palette => self.open_overlay(overlays::Which::Palette), + Command::SwitchCard => self.open_overlay(overlays::Which::Cards), + Command::Settings => self.open_overlay(overlays::Which::Settings), + Command::GoShelf => self.go(Tab::Shelf), + Command::GoSearch => self.go(Tab::Search), + Command::GoHolds => self.go(Tab::Holds), + Command::GoDownloads => self.go(Tab::Downloads), + Command::NextTab => self.go(self.tab.offset(1)), + Command::PrevTab => self.go(self.tab.offset(-1)), + Command::Refresh => self.on_request(Request::Sync, false), + Command::Suspend => self.loop_request = Some(LoopRequest::Suspend), + Command::Redraw => self.loop_request = Some(LoopRequest::Redraw), + _ => {} + } + } + + fn open_overlay(&mut self, which: overlays::Which) { + if self.needs_setup && which != overlays::Which::Settings { + return; + } + let contexts = self.contexts(); + if let Some(modal) = overlays::open(which, &contexts, cx!(self)) { + self.modal = Some(modal); + } + } + + fn apply_flow(&mut self, flow: ModalFlow) { + if flow == ModalFlow::Close { + self.modal = None; + } + } + + fn on_mouse(&mut self, mouse: MouseEvent) { + if !self.shared.config.mouse || self.modal.is_some() { + return; + } + let at = Position::new(mouse.column, mouse.row); + if matches!(mouse.kind, MouseEventKind::Down(MouseButton::Left)) + && !self.needs_setup + && let Some((tab, _)) = self.tab_areas.iter().find(|(_, area)| area.contains(at)) + { + let tab = *tab; + self.go(tab); + return; + } + if self.body_area.contains(at) { + with_screen!(self, |screen| screen.on_mouse(mouse, cx!(self))); + } + } + + fn go(&mut self, tab: Tab) { + if self.needs_setup { + return; + } + if self.tab == tab && !self.detail_open { + return; + } + self.tab = tab; + self.detail_open = false; + with_screen!(self, |screen| screen.on_show(cx!(self))); + } + + // ── Requests ─────────────────────────────────────────────────────────── + + #[allow(clippy::too_many_lines)] + fn on_request(&mut self, request: Request, confirmed: bool) { + match request { + Request::Sync => { + if self.shared.account.syncing { + return; + } + self.shared.account.syncing = true; + let api = Arc::clone(&self.services.api); + self.out.tasks.push(Box::pin(async move { + Action::Account(AccountEvent::Synced(api.sync().await)) + })); + } + Request::Borrow(media) => { + let Some(card) = self.shared.account.active().cloned() else { + self.toasts.push(Toast::warning(t!("account-no-card"))); + return; + }; + if !self.begin(Op::Borrow, &media.id) { + return; + } + let api = Arc::clone(&self.services.api); + self.out.tasks.push(Box::pin(async move { + let result = api + .borrow(&card, &media.id, &media.kind, BorrowOptions::default()) + .await; + Action::Account(AccountEvent::Borrowed { + title: media.id, + name: media.title, + result, + }) + })); + } + Request::Renew(loan) => { + let Some(card) = self.shared.account.card(&loan.card_id).cloned() else { + self.toasts.push(Toast::warning(t!("account-no-card"))); + return; + }; + if !self.begin(Op::Renew, &loan.title_id) { + return; + } + let api = Arc::clone(&self.services.api); + self.out.tasks.push(Box::pin(async move { + let result = api.renew(&card, &loan).await; + Action::Account(AccountEvent::Renewed { + title: loan.title_id, + name: loan.title, + result, + }) + })); + } + Request::Return(loan) => { + if !confirmed { + self.confirm( + t!("confirm-return-title"), + t!("confirm-return-body", title = loan.title.as_str()), + t!("confirm-return-yes"), + Request::Return(loan), + ); + return; + } + if !self.begin(Op::Return, &loan.title_id) { + return; + } + let api = Arc::clone(&self.services.api); + self.out.tasks.push(Box::pin(async move { + let result = api.return_loan(&loan.card_id, &loan.title_id).await; + Action::Account(AccountEvent::Returned { + title: loan.title_id, + name: loan.title, + result, + }) + })); + } + Request::PlaceHold(media) => { + let Some(card) = self.shared.account.active_card.clone() else { + self.toasts.push(Toast::warning(t!("account-no-card"))); + return; + }; + if !self.begin(Op::PlaceHold, &media.id) { + return; + } + let api = Arc::clone(&self.services.api); + self.out.tasks.push(Box::pin(async move { + let result = api.place_hold(&card, &media.id).await; + Action::Account(AccountEvent::HoldPlaced { + title: media.id, + name: media.title, + result, + }) + })); + } + Request::CancelHold(hold) => { + if !confirmed { + self.confirm( + t!("confirm-cancel-hold-title"), + t!("confirm-cancel-hold-body", title = hold.title.as_str()), + t!("confirm-cancel-hold-yes"), + Request::CancelHold(hold), + ); + return; + } + if !self.begin(Op::CancelHold, &hold.title_id) { + return; + } + let api = Arc::clone(&self.services.api); + self.out.tasks.push(Box::pin(async move { + let result = api.cancel_hold(&hold.card_id, &hold.title_id).await; + Action::Account(AccountEvent::HoldCancelled { + title: hold.title_id, + name: hold.title, + result, + }) + })); + } + Request::SuspendHold { hold, days } => { + if !self.begin(Op::SuspendHold, &hold.title_id) { + return; + } + let api = Arc::clone(&self.services.api); + self.out.tasks.push(Box::pin(async move { + let result = api.suspend_hold(&hold.card_id, &hold.title_id, days).await; + Action::Account(AccountEvent::HoldSuspended { + title: hold.title_id, + name: hold.title, + days, + result, + }) + })); + } + Request::Download { + loan, + format, + media, + } => self.download(*loan, format, media.as_deref(), confirmed), + Request::OpenInLibby(title) => { + let url = self.shared.account.library_key().map_or_else( + || libby::links::libby_share_url(&title), + |library| libby::links::libby_title_url(library, &title), + ); + self.open_url(url.as_str()); + } + Request::OpenUrl(url) => self.open_url(url.as_str()), + Request::OpenPath(path) => { + if let Err(message) = self.services.system.open_path(&path) { + self.toasts + .push(Toast::error(t!("system-open-failed", reason = message))); + } + } + Request::Copy { text, what } => match self.services.system.copy(&text) { + Ok(()) => self + .toasts + .push(Toast::success(t!("system-copied", what = what))), + Err(message) => self + .toasts + .push(Toast::error(t!("system-copy-failed", reason = message))), + }, + Request::SwitchCard(card) => { + if self.shared.account.card(&card).is_none() + || self.shared.account.active_card.as_ref() == Some(&card) + { + return; + } + self.shared.account.active_card = Some(card); + if let Some(active) = self.shared.account.active() { + self.toasts.push(Toast::info(t!( + "account-card-switched", + library = active.library.name.as_str() + ))); + } + self.notify_account(); + } + Request::ShowDetail(target) => { + if self.needs_setup { + return; + } + self.detail_open = true; + self.detail.open(target, cx!(self)); + self.detail.on_show(cx!(self)); + } + Request::Go(tab) => self.go(tab), + Request::Open(modal) => { + if let Some(modal) = modal.take() { + self.modal = Some(modal); + } + } + Request::Quit => { + let running = self.shared.downloads.active_count(); + if running > 0 && !confirmed { + self.confirm( + t!("confirm-quit-title"), + t!("confirm-quit-body", count = running), + t!("confirm-quit-yes"), + Request::Quit, + ); + return; + } + self.quit = true; + } + } + } + + /// Marks an operation as in flight. Returns `false` (and does nothing) + /// when the same operation is already running for that title. + fn begin(&mut self, op: Op, title: &TitleId) -> bool { + self.shared.busy.insert(Busy { + op, + title: title.clone(), + }) + } + + fn end(&mut self, op: Op, title: &TitleId) { + self.shared.busy.remove(&Busy { + op, + title: title.clone(), + }); + } + + fn confirm(&mut self, title: String, body: String, yes: String, request: Request) { + self.modal = Some(Box::new(modals::ConfirmModal::new( + title, body, yes, request, + ))); + } + + fn open_url(&mut self, url: &str) { + match self.services.system.open_url(url) { + Ok(()) => self.toasts.push(Toast::info(t!("system-opened-browser"))), + Err(message) => self + .toasts + .push(Toast::error(t!("system-open-failed", reason = message))), + } + } + + fn download( + &mut self, + loan: Loan, + format: Option, + media: Option<&Media>, + confirmed: bool, + ) { + let choices = loan.downloadable_formats(); + let chosen = match &format { + Some(wanted) => choices.iter().find(|(format, _)| &format.id == wanted), + None => choices.iter().min_by_key(|(_, kind)| preference(*kind)), + }; + let Some((chosen, kind)) = chosen.map(|(format, kind)| (format.id.clone(), *kind)) else { + self.toasts.push(Toast::warning(t!( + "download-libby-only", + title = loan.title.as_str() + ))); + return; + }; + if self.shared.downloads.is_pending(&loan.title_id) { + self.toasts.push(Toast::info(t!( + "download-already-queued", + title = loan.title.as_str() + ))); + return; + } + if self.shared.downloads.is_downloaded(&loan.title_id) && !confirmed { + self.confirm( + t!("confirm-redownload-title"), + t!("confirm-redownload-body", title = loan.title.as_str()), + t!("confirm-redownload-yes"), + Request::Download { + loan: Box::new(loan), + format: Some(chosen), + media: media.cloned().map(Box::new), + }, + ); + return; + } + let spec = job_spec(&loan, &chosen, kind, media); + self.toasts.push(Toast::info(t!( + "download-queued", + title = loan.title.as_str() + ))); + self.services.queue.enqueue(spec); + } + + // ── Replies ──────────────────────────────────────────────────────────── + + #[allow(clippy::too_many_lines)] + fn on_account(&mut self, event: AccountEvent) { + match event { + AccountEvent::Synced(Ok(state)) => { + let account = &mut self.shared.account; + account.syncing = false; + account.error = None; + account.synced_at = Some(self.shared.now); + let linked = state.is_linked(); + account.state = Some(state); + account.reconcile_active_card(self.shared.config.default_card.as_deref()); + let was_setup = self.needs_setup; + self.needs_setup = !linked; + self.notify_account(); + if was_setup != self.needs_setup { + with_screen!(self, |screen| screen.on_show(cx!(self))); + } + } + AccountEvent::Synced(Err(error)) => { + self.shared.account.syncing = false; + if error.needs_pairing() { + let was_setup = self.needs_setup; + self.needs_setup = true; + self.modal = None; + if !was_setup { + self.setup.on_show(cx!(self)); + } + return; + } + let message = errors::describe(&error); + // With something on screen already, a failed refresh is a + // notice; with nothing, the screens show it in place. + if self.shared.account.state.is_some() { + self.toasts.push(Toast::error(message.clone())); + } + self.shared.account.error = Some(message); + self.notify_account(); + } + AccountEvent::Borrowed { + title, + name, + result, + } => { + self.end(Op::Borrow, &title); + match result { + Ok(loan) => { + if let Some(state) = self.shared.account.state.as_mut() { + state.holds.retain(|hold| hold.title_id != title); + state.loans.retain(|known| known.title_id != title); + state.loans.push(loan); + } + self.toasts + .push(Toast::success(t!("account-borrowed", title = name))); + } + Err(error) => self.account_failed(&error), + } + self.notify_account(); + } + AccountEvent::Renewed { + title, + name, + result, + } => { + self.end(Op::Renew, &title); + match result { + Ok(loan) => { + if let Some(state) = self.shared.account.state.as_mut() { + match state.loans.iter_mut().find(|known| known.title_id == title) { + Some(known) => *known = loan, + None => state.loans.push(loan), + } + } + self.toasts + .push(Toast::success(t!("account-renewed", title = name))); + } + Err(error) => self.account_failed(&error), + } + self.notify_account(); + } + AccountEvent::Returned { + title, + name, + result, + } => { + self.end(Op::Return, &title); + match result { + Ok(()) => { + if let Some(state) = self.shared.account.state.as_mut() { + state.loans.retain(|loan| loan.title_id != title); + } + self.toasts + .push(Toast::success(t!("account-returned", title = name))); + } + Err(error) => self.account_failed(&error), + } + self.notify_account(); + } + AccountEvent::HoldPlaced { + title, + name, + result, + } => { + self.end(Op::PlaceHold, &title); + match result { + Ok(hold) => { + if let Some(state) = self.shared.account.state.as_mut() { + state.holds.retain(|known| known.title_id != title); + state.holds.push(hold); + } + self.toasts + .push(Toast::success(t!("account-hold-placed", title = name))); + } + Err(error) => self.account_failed(&error), + } + self.notify_account(); + } + AccountEvent::HoldCancelled { + title, + name, + result, + } => { + self.end(Op::CancelHold, &title); + match result { + Ok(()) => { + if let Some(state) = self.shared.account.state.as_mut() { + state.holds.retain(|hold| hold.title_id != title); + } + self.toasts + .push(Toast::success(t!("account-hold-cancelled", title = name))); + } + Err(error) => self.account_failed(&error), + } + self.notify_account(); + } + AccountEvent::HoldSuspended { + title, + name, + days, + result, + } => { + self.end(Op::SuspendHold, &title); + match result { + Ok(()) => { + let message = if days == 0 { + t!("account-hold-resumed", title = name) + } else { + t!("account-hold-suspended", title = name, count = days) + }; + self.toasts.push(Toast::success(message)); + // The reply carries no hold, and the new dates are + // the server's to decide: ask for them. + self.on_request(Request::Sync, false); + } + Err(error) => self.account_failed(&error), + } + self.notify_account(); + } + } + } + + fn account_failed(&mut self, error: &libby::Error) { + if error.needs_pairing() { + self.needs_setup = true; + self.modal = None; + self.setup.on_show(cx!(self)); + return; + } + self.toasts.push(Toast::error(errors::describe(error))); + } + + /// Tells every screen the account changed. + fn notify_account(&mut self) { + self.shelf.on_account(cx!(self)); + self.search.on_account(cx!(self)); + self.detail.on_account(cx!(self)); + self.holds.on_account(cx!(self)); + self.downloads.on_account(cx!(self)); + self.setup.on_account(cx!(self)); + } + + fn on_engine(&mut self, event: download::Event) { + match &event { + download::Event::Changed(job) => { + let before = self + .shared + .downloads + .jobs + .iter() + .find(|known| known.id() == job.id()) + .map(|known| known.state.name()); + if before != Some(job.state.name()) { + self.announce(job.id(), &job.spec.title, &job.state); + } + } + download::Event::PersistFailed { message } => { + self.toasts.push(Toast::warning(t!( + "download-persist-failed", + reason = message.as_str() + ))); + } + download::Event::Added(_) + | download::Event::Removed(_) + | download::Event::Progress(_) => {} + } + self.shared.downloads.apply(event); + self.downloads.on_queue(cx!(self)); + } + + fn announce(&mut self, _id: &JobId, title: &str, state: &JobState) { + // The downloads tab already shows every change; toasts are for + // people looking elsewhere. + if self.view() == View::Tab(Tab::Downloads) { + return; + } + match state { + JobState::Done { .. } => self + .toasts + .push(Toast::success(t!("download-done", title = title))), + JobState::Failed { message, .. } => self.toasts.push(Toast::error(t!( + "download-failed", + title = title, + reason = message.as_str() + ))), + _ => {} + } + } + + // ── Drawing ──────────────────────────────────────────────────────────── + + /// Draws everything. Returns the covers that were drawn but are not + /// loaded yet, as work to start. + pub fn render(&mut self, frame: &mut Frame<'_>) -> Vec { + let area = frame.area(); + if area.width < MIN_SIZE.0 || area.height < MIN_SIZE.1 { + chrome::too_small(frame, area, &self.shared); + return Vec::new(); + } + let [header, body, footer] = area.layout(&Layout::vertical([ + Constraint::Length(1), + Constraint::Fill(1), + Constraint::Length(1), + ])); + self.body_area = body; + self.tab_areas = chrome::header( + frame, + header, + &self.shared, + (!self.needs_setup).then_some(self.tab), + ); + with_screen!(self, |screen| screen.render(frame, body, &self.shared)); + + let commands = match self.modal.as_ref() { + Some(modal) => modal.hints(&self.shared), + None => { + let mut commands = with_screen!(self, |screen| screen.hints(&self.shared)); + commands.extend([Command::Help, Command::Quit]); + commands + } + }; + let contexts: Vec = match self.modal.as_ref() { + Some(modal) => modal.contexts().to_vec(), + None => self.contexts().to_vec(), + }; + chrome::footer(frame, footer, &self.shared, &contexts, &commands); + + if let Some(modal) = self.modal.as_mut() { + modal.render(frame, body, &self.shared); + } + chrome::toasts(frame, body, &self.shared, &self.toasts); + + self.shared + .covers + .take_wanted() + .into_iter() + .map(|url| { + let api = Arc::clone(&self.services.api); + let task: Task = Box::pin(async move { + let bytes = api.cover_bytes(&url).await.ok().map(Arc::from); + Action::Cover { url, bytes } + }); + task + }) + .collect() + } +} + +/// Whether `key` is ordinary typing (a character with no Ctrl or Alt). +fn is_text(key: KeyEvent) -> bool { + matches!(key.code, KeyCode::Char(_)) + && !key + .modifiers + .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) +} + +/// Lower is better: files anyone can read before files tied to Adobe, and +/// reflowable EPUB before fixed-layout PDF. +const fn preference(kind: DownloadKind) -> u8 { + match kind { + DownloadKind::EpubOpen => 0, + DownloadKind::PdfOpen => 1, + DownloadKind::EpubAcsm => 2, + DownloadKind::PdfAcsm => 3, + } +} + +fn job_spec(loan: &Loan, format: &FormatId, kind: DownloadKind, media: Option<&Media>) -> JobSpec { + let file_kind = match kind { + DownloadKind::EpubOpen => FileKind::Epub, + DownloadKind::PdfOpen => FileKind::Pdf, + DownloadKind::EpubAcsm | DownloadKind::PdfAcsm => FileKind::Acsm, + }; + let series = loan.detailed_series.as_ref(); + let cover_url = loan + .best_cover(600) + .and_then(|cover| Url::parse(&cover.href).ok()); + JobSpec { + id: JobId::generate(), + title_id: loan.title_id.as_str().to_owned(), + card_id: loan.card_id.as_str().to_owned(), + title: loan.title.clone(), + author: loan.first_creator_name.clone(), + series: series + .and_then(|series| series.series_name.clone()) + .or_else(|| loan.series.clone()), + series_index: series.and_then(|series| series.reading_order.clone()), + year: media + .and_then(|media| media.publish_date) + .map(|date| i32::from(date.to_zoned(jiff::tz::TimeZone::UTC).year())), + kind: file_kind, + format_id: format.as_str().to_owned(), + cover_url, + description: media.and_then(|media| media.description.clone()), + publisher: media + .and_then(|media| media.publisher.as_ref()) + .map(|publisher| publisher.name.clone()), + language: media + .and_then(|media| media.languages.first()) + .map(|language| language.id.clone()), + isbn: None, + subjects: media + .map(|media| { + media + .subjects + .iter() + .map(|subject| subject.name.clone()) + .collect() + }) + .unwrap_or_default(), + } +} + +#[cfg(test)] +mod tests; diff --git a/crates/libbui/src/app/modals.rs b/crates/libbui/src/app/modals.rs new file mode 100644 index 0000000..2e749e2 --- /dev/null +++ b/crates/libbui/src/app/modals.rs @@ -0,0 +1,207 @@ +//! The two modals the app itself needs: help, and "are you sure?". +//! +//! Richer overlays (the command palette, the card switcher, settings) live +//! in [`super::overlays`]. + +use ratatui::Frame; +use ratatui::layout::{Alignment, Constraint, Layout, Rect}; +use ratatui::text::{Line, Span}; +use ratatui::widgets::{Block, Clear, Padding, Paragraph}; + +use super::{Action, Ctx, Request, Shared}; +use crate::keymap::{Command, Context}; +use crate::screens::{Modal, ModalFlow}; +use crate::t; +use crate::ui::help::{Help, HelpState}; +use crate::ui::text; + +/// Every key that works right now, grouped by where it applies. +#[derive(Debug)] +pub struct HelpModal { + contexts: Vec, + state: HelpState, +} + +impl HelpModal { + /// Help for a screen whose keys resolve through `contexts`. + #[must_use] + pub fn new(contexts: Vec) -> Self { + Self { + contexts, + state: HelpState::default(), + } + } +} + +impl Modal for HelpModal { + fn contexts(&self) -> &'static [Context] { + // List for scrolling, Global so `?` and `q` close it again. + &[Context::Dialog, Context::List, Context::Global] + } + + fn on_command(&mut self, command: Command, _cx: &mut Ctx<'_>) -> ModalFlow { + match command { + Command::Up => self.state.scroll_by(-1), + Command::Down => self.state.scroll_by(1), + Command::HalfPageUp => self.state.scroll_by(-5), + Command::HalfPageDown => self.state.scroll_by(5), + Command::PageUp => self.state.scroll_by(-10), + Command::PageDown => self.state.scroll_by(10), + Command::Top => self.state.scroll = 0, + Command::Bottom => self.state.scroll = u16::MAX, + Command::Back | Command::Help | Command::Quit | Command::Confirm | Command::Select => { + return ModalFlow::Close; + } + _ => {} + } + ModalFlow::Stay + } + + fn hints(&self, _shared: &Shared) -> Vec { + vec![Command::Down, Command::Up, Command::Back] + } + + fn render(&mut self, frame: &mut Frame<'_>, area: Rect, shared: &Shared) { + Help::new(&shared.keymap, &shared.theme, &self.contexts).render( + area, + frame.buffer_mut(), + &mut self.state, + ); + } +} + +/// Asks before doing something that cannot be undone. +/// +/// The safe answer is focused first: Enter on a freshly opened dialog never +/// destroys anything. `y` always confirms and `n`/Esc always cancels, +/// whichever button is focused. +#[derive(Debug)] +pub struct ConfirmModal { + title: String, + body: String, + yes: String, + request: Request, + yes_focused: bool, +} + +impl ConfirmModal { + /// A dialog that sends `request` (as already confirmed) on "yes". + #[must_use] + pub const fn new(title: String, body: String, yes: String, request: Request) -> Self { + Self { + title, + body, + yes, + request, + yes_focused: false, + } + } + + fn accept(&self, cx: &mut Ctx<'_>) -> ModalFlow { + cx.send(Action::Confirmed(self.request.clone())); + ModalFlow::Close + } +} + +impl Modal for ConfirmModal { + fn on_command(&mut self, command: Command, cx: &mut Ctx<'_>) -> ModalFlow { + match command { + Command::Left | Command::Right | Command::NextPane | Command::PrevPane => { + self.yes_focused = !self.yes_focused; + ModalFlow::Stay + } + Command::Select => { + if self.yes_focused { + self.accept(cx) + } else { + ModalFlow::Close + } + } + Command::Confirm => self.accept(cx), + Command::Back | Command::Quit => ModalFlow::Close, + _ => ModalFlow::Stay, + } + } + + fn on_key(&mut self, key: crossterm::event::KeyEvent, cx: &mut Ctx<'_>) -> Option { + // Enter follows the focused button rather than always confirming. + (key.code == crossterm::event::KeyCode::Enter).then(|| { + if self.yes_focused { + self.accept(cx) + } else { + ModalFlow::Close + } + }) + } + + fn render(&mut self, frame: &mut Frame<'_>, area: Rect, shared: &Shared) { + let theme = &shared.theme; + let width = area.width.saturating_sub(4).min(56); + if width < 20 { + return; + } + let inner_width = usize::from(width - 6); + let body = text::wrap(&self.body, inner_width); + let height = u16::try_from(body.len() + 6) + .unwrap_or(u16::MAX) + .min(area.height); + let rect = area.centered(Constraint::Length(width), Constraint::Length(height)); + + let (border_style, border_type) = theme.pane_border(true); + let block = Block::bordered() + .border_type(border_type) + .border_style(border_style) + .title(Line::styled(format!(" {} ", self.title), theme.warning)) + .padding(Padding::new(2, 2, 1, 1)); + let inner = block.inner(rect); + frame.render_widget(Clear, rect); + frame.render_widget(block, rect); + + let [body_area, _, buttons_area] = inner.layout(&Layout::vertical([ + Constraint::Fill(1), + Constraint::Length(1), + Constraint::Length(1), + ])); + let lines: Vec> = body + .into_iter() + .map(|line| Line::styled(line, theme.text)) + .collect(); + frame.render_widget(Paragraph::new(lines), body_area); + + // Focus is shown with brackets and a cursor as well as colour. + let button = |label: &str, focused: bool, key: &str| -> Vec> { + let style = if focused { theme.selected } else { theme.text }; + let (open, close) = if focused { ("[ ", " ]") } else { (" ", " ") }; + vec![ + Span::styled(format!("{open}{label}{close}"), style), + Span::styled(format!(" {key}"), theme.key), + ] + }; + // The letter shortcuts are the last chord of each binding; Enter and + // Esc (the first) go without saying. + let shortcut = |command: Command| -> String { + shared + .keymap + .in_context(Context::Dialog) + .find(|binding| binding.command == command) + .and_then(|binding| binding.chords.last()) + .map(ToString::to_string) + .unwrap_or_default() + }; + let mut spans = button( + &t!("confirm-cancel"), + !self.yes_focused, + &shortcut(Command::Back), + ); + spans.push(Span::raw(" ")); + spans.extend(button( + &self.yes, + self.yes_focused, + &shortcut(Command::Confirm), + )); + frame.render_widget( + Paragraph::new(Line::from(spans)).alignment(Alignment::Center), + buttons_area, + ); + } +} diff --git a/crates/libbui/src/app/overlays.rs b/crates/libbui/src/app/overlays.rs new file mode 100644 index 0000000..054572d --- /dev/null +++ b/crates/libbui/src/app/overlays.rs @@ -0,0 +1,39 @@ +//! The richer overlays: command palette, card switcher, settings. +//! +//! Placeholder: the real overlays are still to be written. + +use super::Ctx; +use crate::keymap::Context; +use crate::screens::{Modal, ModalFlow}; + +/// Which overlay to open. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Which { + /// Fuzzy-search every command. + Palette, + /// Pick the card used for searching and borrowing. + Cards, + /// Change settings. + Settings, +} + +/// Replies to work an overlay started. +#[derive(Debug)] +pub enum Msg {} + +/// Builds an overlay. `contexts` are the focused screen's keymap contexts, +/// most specific first (the palette lists their commands). `None` when the +/// overlay has nothing to offer right now. +pub fn open( + _which: Which, + _contexts: &[Context], + _cx: &mut Ctx<'_>, +) -> Option> { + None +} + +/// Routes a reply to the open modal. Replies meant for an overlay that has +/// since closed (or been replaced) must be ignored. +pub fn on_msg(_modal: &mut dyn Modal, msg: Msg, _cx: &mut Ctx<'_>) -> ModalFlow { + match msg {} +} diff --git a/crates/libbui/src/app/run.rs b/crates/libbui/src/app/run.rs new file mode 100644 index 0000000..d5f5463 --- /dev/null +++ b/crates/libbui/src/app/run.rs @@ -0,0 +1,112 @@ +//! The run loop: the only place that waits. +//! +//! It owns the terminal and the channels, feeds everything that happens to +//! [`App::dispatch`], spawns the work that comes back, and redraws only when +//! something changed. While nothing animates the loop sleeps; a spinner or a +//! progress bar wakes it ten times a second, never more. + +use std::io; +use std::time::{Duration, Instant}; + +use jiff::Timestamp; +use libbui_core::download; +use tokio::sync::mpsc; + +use super::{Action, App, LoopRequest, Task}; +use crate::tui::Tui; + +/// How often the screen refreshes while something is animating. +const ANIMATION_TICK: Duration = Duration::from_millis(100); + +/// How often the clock advances otherwise, so "3 days left" stays true. +const IDLE_TICK: Duration = Duration::from_secs(30); + +/// What the loop needs besides the app. +#[derive(Debug)] +pub struct Runtime { + /// The terminal. + pub tui: Tui, + /// Events from the download engine. + pub engine: mpsc::UnboundedReceiver, +} + +/// Runs `app` until the user quits. +/// +/// # Errors +/// Terminal I/O failures. The terminal is restored when `runtime.tui` drops, +/// whether this returns `Ok` or not. +pub async fn run(app: &mut App, runtime: &mut Runtime) -> io::Result<()> { + let (tx, mut rx) = mpsc::unbounded_channel::(); + let spawn_all = |tasks: Vec| { + for task in tasks { + let tx = tx.clone(); + tokio::spawn(async move { + // The loop has gone away only when the app is quitting. + let _ = tx.send(task.await); + }); + } + }; + + let mut pending = app.dispatch(tick()); + pending.extend(app.start()); + spawn_all(pending); + let mut engine_open = true; + + loop { + let mut covers = Vec::new(); + runtime.tui.draw(|frame| covers = app.render(frame))?; + spawn_all(covers); + + let tick_every = if app.is_animating() { + ANIMATION_TICK + } else { + IDLE_TICK + }; + let first = tokio::select! { + event = runtime.tui.next_event() => match event { + Some(event) => Action::Event(event?), + // The input stream ended: the terminal is gone. + None => return Ok(()), + }, + Some(action) = rx.recv() => action, + event = runtime.engine.recv(), if engine_open => match event { + Some(event) => Action::Engine(event), + None => { + engine_open = false; + continue; + } + }, + () = tokio::time::sleep(tick_every) => tick(), + }; + + // Fold in everything else that is already waiting, so a burst of + // progress events or a pasted paragraph costs one redraw, not many. + let mut tasks = app.dispatch(first); + while let Ok(action) = rx.try_recv() { + tasks.extend(app.dispatch(action)); + } + while let Ok(event) = runtime.engine.try_recv() { + tasks.extend(app.dispatch(Action::Engine(event))); + } + spawn_all(tasks); + + match app.take_loop_request() { + Some(LoopRequest::Suspend) => { + runtime.tui.suspend()?; + spawn_all(app.dispatch(tick())); + } + Some(LoopRequest::Redraw) => runtime.tui.clear()?, + None => {} + } + if app.should_quit() { + return Ok(()); + } + } +} + +fn tick() -> Action { + Action::Tick { + now: Timestamp::now(), + instant: Instant::now(), + } +} diff --git a/crates/libbui/src/app/shared.rs b/crates/libbui/src/app/shared.rs new file mode 100644 index 0000000..a52ca3d --- /dev/null +++ b/crates/libbui/src/app/shared.rs @@ -0,0 +1,361 @@ +//! State every screen can read and only the app can write. +//! +//! Screens own what is theirs (a cursor, a query, a scroll offset). Anything +//! two screens must agree on lives here: the account, the download queue, the +//! look. Screens get `&Shared`; changes go through [`Request`]s so there is +//! exactly one place that talks to Libby about the account. +//! +//! [`Request`]: super::Request + +use std::collections::{BTreeSet, HashMap}; +use std::path::Path; +use std::sync::Arc; + +use jiff::Timestamp; +use libbui_core::config::Config; +use libbui_core::download::{Job, JobId, JobSpec, JobState, Progress}; +use libbui_core::library::LibraryEntry; +use libby::models::{Card, Hold, Loan, SyncState}; +use libby::{CardId, LibraryKey, TitleId}; + +use crate::api::Api; +use crate::keymap::Keymap; +use crate::theme::{Symbols, Theme}; +use crate::ui::cover::Covers; + +/// The read-only world handed to every screen. +#[derive(Debug)] +pub struct Shared { + /// The user's configuration. + pub config: Config, + /// Resolved colours and borders. + pub theme: Theme, + /// Resolved glyph set (Unicode or ASCII). + pub symbols: Symbols, + /// Resolved key bindings. + pub keymap: Keymap, + /// Cards, loans and holds. + pub account: Account, + /// The download queue and what is already on disk. + pub downloads: Downloads, + /// Cover images, loaded lazily as they are drawn. + pub covers: Covers, + /// Account operations in flight, for spinners and double-press guards. + pub busy: BTreeSet, + /// The current time. Screens must use this, never the system clock, so + /// renders are reproducible. + pub now: Timestamp, + /// Animation frame counter; advances on every tick while something moves. + pub frame: u64, +} + +impl Shared { + /// The current spinner glyph, or a static one under reduced motion. + #[must_use] + pub fn spinner(&self) -> &'static str { + let frames = self.symbols.spinner; + if self.config.reduced_motion || frames.is_empty() { + return self.symbols.ellipsis; + } + let index = usize::try_from(self.frame).unwrap_or(0) % frames.len(); + frames[index] + } + + /// Whether `op` is in flight for `title`. + #[must_use] + pub fn is_busy(&self, op: Op, title: &TitleId) -> bool { + self.busy.contains(&Busy { + op, + title: title.clone(), + }) + } + + /// Whether any account operation is in flight for `title`. + #[must_use] + pub fn is_title_busy(&self, title: &TitleId) -> bool { + self.busy.iter().any(|busy| &busy.title == title) + } + + /// Whether anything on screen is animating, i.e. the app must tick. + #[must_use] + pub fn is_animating(&self) -> bool { + self.account.syncing || !self.busy.is_empty() || self.downloads.has_in_flight() + } +} + +/// An account operation on one title. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum Op { + /// Borrowing. + Borrow, + /// Renewing a loan. + Renew, + /// Returning a loan. + Return, + /// Placing a hold. + PlaceHold, + /// Cancelling a hold. + CancelHold, + /// Suspending or resuming a hold. + SuspendHold, +} + +/// An operation in flight. +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Busy { + /// What is being done. + pub op: Op, + /// To which title. + pub title: TitleId, +} + +/// Cards, loans and holds, and how fresh they are. +#[derive(Debug, Default)] +pub struct Account { + /// The last successful sync; `None` before the first one lands. + pub state: Option, + /// Whether a sync is in flight. + pub syncing: bool, + /// Why the last sync failed, already localized. Cleared on success. + pub error: Option, + /// When `state` was fetched. + pub synced_at: Option, + /// The card used for searching and borrowing. + pub active_card: Option, +} + +impl Account { + /// Whether the first sync has not landed yet. + #[must_use] + pub const fn is_loading(&self) -> bool { + self.state.is_none() && self.syncing + } + + /// Every linked card. + #[must_use] + pub fn cards(&self) -> &[Card] { + self.state.as_ref().map_or(&[], |state| &state.cards) + } + + /// Every loan, across all cards, as synced. + #[must_use] + pub fn loans(&self) -> &[Loan] { + self.state.as_ref().map_or(&[], |state| &state.loans) + } + + /// Every hold, across all cards, as synced. + #[must_use] + pub fn holds(&self) -> &[Hold] { + self.state.as_ref().map_or(&[], |state| &state.holds) + } + + /// One card by id. + #[must_use] + pub fn card(&self, id: &CardId) -> Option<&Card> { + self.cards().iter().find(|card| &card.id == id) + } + + /// The card used for searching and borrowing. + #[must_use] + pub fn active(&self) -> Option<&Card> { + let id = self.active_card.as_ref()?; + self.card(id) + } + + /// The catalogue the active card searches. + #[must_use] + pub fn library_key(&self) -> Option<&LibraryKey> { + self.active()?.advantage_key.as_ref() + } + + /// The loan of `title`, on any card. + #[must_use] + pub fn loan(&self, title: &TitleId) -> Option<&Loan> { + self.loans().iter().find(|loan| &loan.title_id == title) + } + + /// The hold on `title`, on any card. + #[must_use] + pub fn hold(&self, title: &TitleId) -> Option<&Hold> { + self.holds().iter().find(|hold| &hold.title_id == title) + } + + /// Picks the active card after a sync: keep the current one if it still + /// exists, else the configured default, else the first. + pub(super) fn reconcile_active_card(&mut self, preferred: Option<&str>) { + let cards = self.cards(); + let still_there = self + .active_card + .as_ref() + .is_some_and(|id| cards.iter().any(|card| &card.id == id)); + if still_there { + return; + } + let configured = preferred.and_then(|wanted| { + cards.iter().find(|card| { + card.id.as_str() == wanted + || card + .advantage_key + .as_ref() + .is_some_and(|key| key.as_str() == wanted) + }) + }); + self.active_card = configured + .or_else(|| cards.first()) + .map(|card| card.id.clone()); + } +} + +/// The download queue as last reported by the engine, plus what earlier +/// sessions left on disk. +#[derive(Debug, Default)] +pub struct Downloads { + /// Jobs, oldest first. + pub jobs: Vec, + /// Latest progress sample per fetching job. + pub progress: HashMap, + /// Files finished in earlier sessions. + pub index: Vec, +} + +impl Downloads { + /// The most recent job for `title`, if any. + #[must_use] + pub fn job_for(&self, title: &TitleId) -> Option<&Job> { + self.jobs + .iter() + .rev() + .find(|job| job.spec.title_id == title.as_str()) + } + + /// Where `title` was saved, if it has been downloaded. + #[must_use] + pub fn path_for(&self, title: &TitleId) -> Option<&Path> { + let from_queue = self.jobs.iter().rev().find_map(|job| match &job.state { + JobState::Done { path, .. } if job.spec.title_id == title.as_str() => { + Some(path.as_path()) + } + _ => None, + }); + from_queue.or_else(|| { + self.index + .iter() + .rev() + .find(|entry| entry.title_id == title.as_str()) + .map(|entry| entry.path.as_path()) + }) + } + + /// Whether `title` has a finished download. + #[must_use] + pub fn is_downloaded(&self, title: &TitleId) -> bool { + self.path_for(title).is_some() + } + + /// Whether a job for `title` is queued, paused or running. + #[must_use] + pub fn is_pending(&self, title: &TitleId) -> bool { + self.job_for(title) + .is_some_and(|job| !job.state.is_terminal()) + } + + /// Whether any job is running right now. + #[must_use] + pub fn has_in_flight(&self) -> bool { + self.jobs.iter().any(|job| job.state.is_in_flight()) + } + + /// How many jobs are queued or running. + #[must_use] + pub fn active_count(&self) -> usize { + self.jobs + .iter() + .filter(|job| matches!(job.state, JobState::Queued) || job.state.is_in_flight()) + .count() + } + + /// How many jobs have failed and not been retried or cleared. + #[must_use] + pub fn failed_count(&self) -> usize { + self.jobs + .iter() + .filter(|job| matches!(job.state, JobState::Failed { .. })) + .count() + } + + /// Applies an engine event. + pub(super) fn apply(&mut self, event: libbui_core::download::Event) { + use libbui_core::download::Event; + match event { + Event::Added(job) | Event::Changed(job) => { + if !matches!(job.state, JobState::Fetching { .. }) { + self.progress.remove(job.id()); + } + match self.jobs.iter_mut().find(|known| known.id() == job.id()) { + Some(known) => *known = job, + None => self.jobs.push(job), + } + } + Event::Removed(job) => { + self.progress.remove(job.id()); + self.jobs.retain(|known| known.id() != job.id()); + } + Event::Progress(progress) => { + self.progress.insert(progress.id.clone(), progress); + } + // Surfaced as a toast by the app; nothing to store. + Event::PersistFailed { .. } => {} + } + } +} + +/// The download queue's controls. +/// +/// Fire-and-forget: outcomes come back as engine events, which is how the UI +/// learns about them whether a command came from here or from a retry timer. +pub trait DownloadQueue: Send + Sync + std::fmt::Debug { + /// Adds a job. + fn enqueue(&self, spec: JobSpec); + /// Pauses a queued or running job. + fn pause(&self, id: &JobId); + /// Resumes a paused job. + fn resume(&self, id: &JobId); + /// Cancels a job, discarding partial data. + fn cancel(&self, id: &JobId); + /// Re-queues a failed or cancelled job. + fn retry(&self, id: &JobId); + /// Removes a finished job from the list (the file stays). + fn remove(&self, id: &JobId); + /// Removes every finished job from the list. + fn clear_finished(&self); +} + +/// The outside world, minus Libby: browsers, file managers, the clipboard. +pub trait System: Send + Sync + std::fmt::Debug { + /// Opens a URL in the user's browser. + /// + /// # Errors + /// A message fit for a toast. + fn open_url(&self, url: &str) -> Result<(), String>; + /// Opens a file or folder with its default application. + /// + /// # Errors + /// A message fit for a toast. + fn open_path(&self, path: &Path) -> Result<(), String>; + /// Copies text to the clipboard. + /// + /// # Errors + /// A message fit for a toast. + fn copy(&self, text: &str) -> Result<(), String>; +} + +/// The handles screens use to start work. +#[derive(Debug, Clone)] +pub struct Services { + /// Libby. + pub api: Arc, + /// The download queue. + pub queue: Arc, + /// Browser, file manager, clipboard. + pub system: Arc, +} diff --git a/crates/libbui/src/app/tests.rs b/crates/libbui/src/app/tests.rs new file mode 100644 index 0000000..50b3b09 --- /dev/null +++ b/crates/libbui/src/app/tests.rs @@ -0,0 +1,191 @@ +//! The shell: tabs, help, confirmations, toasts, quitting. + +use std::time::Duration; + +use super::{Action, Request, Tab}; +use crate::keymap::Command; +use crate::testing::{Harness, done}; +use crate::ui::toast::Toast; + +#[tokio::test] +async fn starts_on_the_shelf_after_one_sync() { + let mut h = Harness::new().await; + assert_eq!(h.app.tab(), Tab::Shelf); + assert_eq!(h.api.calls(), ["sync"]); + assert_eq!(h.shared().account.loans().len(), 6); + let screen = h.screen(); + assert!(screen.contains("[Shelf"), "{screen}"); + assert!(screen.contains("Example Public Library"), "{screen}"); +} + +#[tokio::test] +async fn an_unpaired_device_does_not_talk_to_libby() { + let mut h = Harness::unlinked().await; + assert!(h.api.calls().is_empty()); + let screen = h.screen(); + assert!(!screen.contains("[Shelf"), "{screen}"); +} + +#[tokio::test] +async fn number_keys_and_tab_switch_tabs() { + let mut h = Harness::new().await; + h.press("3").await; + assert_eq!(h.app.tab(), Tab::Holds); + h.press("tab").await; + assert_eq!(h.app.tab(), Tab::Downloads); + h.press("tab").await; + assert_eq!(h.app.tab(), Tab::Shelf); + h.press("shift-tab").await; + assert_eq!(h.app.tab(), Tab::Downloads); + assert!(h.screen().contains("[Downloads")); +} + +#[tokio::test] +async fn help_opens_and_closes() { + let mut h = Harness::new().await; + h.press("?").await; + assert!(h.app.has_modal()); + assert!(h.screen().contains("Keyboard")); + h.press("esc").await; + assert!(!h.app.has_modal()); +} + +#[tokio::test] +async fn quit_is_immediate_when_idle() { + let mut h = Harness::new().await; + h.press("q").await; + assert!(h.app.should_quit()); +} + +#[tokio::test] +async fn quit_asks_first_while_downloading() { + let mut h = Harness::new().await; + h.job( + 0, + libbui_core::download::JobState::Fetching { + received: 10, + total: Some(100), + }, + ) + .await; + h.press("q").await; + assert!(!h.app.should_quit()); + assert!(h.screen().contains("Quit while downloading?")); + // The safe answer is focused: Enter keeps the app open. + h.press("enter").await; + assert!(!h.app.should_quit()); + assert!(!h.app.has_modal()); + h.press("q").await; + h.press("y").await; + assert!(h.app.should_quit()); +} + +#[tokio::test] +async fn returning_a_loan_is_confirmed_then_applied_without_another_sync() { + let mut h = Harness::new().await; + h.api.clear_calls(); + let loan = h.shared().account.loans()[0].clone(); + h.dispatch(Action::Request(Request::Return(Box::new(loan)))) + .await; + assert!( + h.api.calls().is_empty(), + "nothing is sent before confirming" + ); + assert!(h.screen().contains("Return this loan?")); + h.press("y").await; + assert_eq!(h.api.calls(), ["return_loan 10000001 1000001"]); + assert_eq!(h.shared().account.loans().len(), 5); + assert_eq!(h.toasts(), ["Returned “The Left Hand of Darkness”."]); +} + +#[tokio::test] +async fn a_failed_request_explains_itself_and_stays_until_dismissed() { + let mut h = Harness::new().await; + h.api.fail_next(libby::Error::RateLimited { + service: libby::Service::Sentry, + retry_after: None, + }); + h.command(Command::Refresh).await; + assert_eq!( + h.toasts(), + ["Libby is asking us to slow down. Try again in a minute."] + ); + h.advance(Duration::from_secs(60)).await; + assert_eq!(h.toasts().len(), 1, "errors do not time out"); + h.press("esc").await; + assert!(h.toasts().is_empty()); +} + +#[tokio::test] +async fn ordinary_toasts_expire() { + let mut h = Harness::new().await; + h.dispatch(Action::Toast(Toast::info("hello"))).await; + assert_eq!(h.toasts(), ["hello"]); + h.advance(Duration::from_secs(5)).await; + assert!(h.toasts().is_empty()); +} + +#[tokio::test] +async fn downloading_queues_the_open_epub_format() { + let mut h = Harness::new().await; + let loan = h.shared().account.loans()[0].clone(); + h.dispatch(Action::Request(Request::Download { + loan: Box::new(loan), + format: None, + media: None, + })) + .await; + assert_eq!(h.queue.calls(), ["enqueue 1000001 ebook-epub-open"]); +} + +#[tokio::test] +async fn a_libby_only_loan_is_never_queued() { + let mut h = Harness::new().await; + let loan = h.shared().account.loans()[1].clone(); + h.dispatch(Action::Request(Request::Download { + loan: Box::new(loan), + format: None, + media: None, + })) + .await; + assert!(h.queue.calls().is_empty()); + assert_eq!( + h.toasts(), + ["“Project Hail Mary” can only be read or played in Libby."] + ); +} + +#[tokio::test] +async fn a_finished_download_marks_the_title_and_says_so() { + let mut h = Harness::new().await; + h.job(0, done("/books/left-hand.epub", 1024)).await; + assert!( + h.shared() + .downloads + .is_downloaded(&libby::TitleId::new("1000001")) + ); + assert_eq!(h.toasts(), ["Downloaded “The Left Hand of Darkness”."]); +} + +#[tokio::test] +async fn a_small_terminal_says_so_instead_of_drawing_garbage() { + let mut h = Harness::new().await; + h.resize(40, 10).await; + let screen = h.screen(); + assert!(screen.contains("40"), "{screen}"); + assert!(!screen.contains("[Shelf"), "{screen}"); +} + +#[tokio::test] +async fn open_in_libby_uses_the_browser() { + let mut h = Harness::new().await; + let title = h.shared().account.loans()[0].title_id.clone(); + h.dispatch(Action::Request(Request::OpenInLibby(title))) + .await; + let calls = h.system.calls(); + assert_eq!(calls.len(), 1); + assert!( + calls[0].starts_with("open_url https://libbyapp.com/"), + "{calls:?}" + ); +} diff --git a/crates/libbui/src/cli.rs b/crates/libbui/src/cli.rs new file mode 100644 index 0000000..c99f683 --- /dev/null +++ b/crates/libbui/src/cli.rs @@ -0,0 +1,39 @@ +//! Command-line arguments. + +use std::path::PathBuf; + +use clap::Parser; + +/// Browse, borrow and download from your library, in the terminal. +#[derive(Debug, Clone, Parser)] +#[command(name = "libbui", version, about, long_about = None)] +pub struct Args { + /// Read configuration from this file instead of the default location. + #[arg(long, value_name = "FILE", env = "LIBBUI_CONFIG")] + pub config: Option, + + /// Colour theme: auto, dark, light, ansi, high-contrast or mono. + #[arg(long, value_name = "NAME", env = "LIBBUI_THEME")] + pub theme: Option, + + /// Interface language, as a BCP 47 tag such as en-US. + #[arg(long, value_name = "TAG", env = "LIBBUI_LANG")] + pub lang: Option, + + /// Draw with ASCII characters only. + #[arg(long)] + pub ascii: bool, + + /// Leave the mouse to the terminal (keeps native text selection). + #[arg(long)] + pub no_mouse: bool, + + /// Log filter, such as `info` or `libbui=debug,libby=trace`. + #[arg( + long, + value_name = "FILTER", + env = "LIBBUI_LOG", + default_value = "info" + )] + pub log: String, +} diff --git a/crates/libbui/src/i18n.rs b/crates/libbui/src/i18n.rs new file mode 100644 index 0000000..195ebaa --- /dev/null +++ b/crates/libbui/src/i18n.rs @@ -0,0 +1,165 @@ +//! The message catalog. +//! +//! Every string a person can read comes from a Fluent file under +//! `locales//`. Screens never hard-code English: they call [`t!`]. +//! +//! ```ignore +//! let title = t!("shelf-title"); +//! let left = t!("loan-days-left", days = 3); +//! ``` +//! +//! A missing key is a bug, and it is made loud rather than hidden: the lookup +//! renders the key itself in `⟦brackets⟧`, and `catalog_has_every_key_used` in +//! this crate's tests fails the build's test run. + +use std::borrow::Cow; +use std::collections::HashMap; +use std::sync::OnceLock; + +use fluent_templates::fluent_bundle::FluentValue; +use fluent_templates::{LanguageIdentifier, Loader, langid}; + +fluent_templates::static_loader! { + static LOCALES = { + locales: "./locales", + fallback_language: "en-US", + // Fluent wraps placeables in bidi isolation marks by default. They are + // invisible in a browser and a column-width hazard in a terminal grid. + customise: |bundle| bundle.set_use_isolating(false), + }; +} + +/// The language used when nothing better is known. +pub static FALLBACK: LanguageIdentifier = langid!("en-US"); + +static ACTIVE: OnceLock = OnceLock::new(); + +/// Fixes the UI language for the life of the process. +/// +/// `requested` is the user's explicit choice (flag or config); otherwise the +/// system locale is used, and `en-US` when that is unknown or untranslated. +/// Calling it twice is a no-op: the first choice wins. +pub fn init(requested: Option<&str>) { + let lang = requested + .map(str::to_owned) + .or_else(sys_locale::get_locale) + .and_then(|raw| raw.replace('_', "-").parse::().ok()) + .unwrap_or_else(|| FALLBACK.clone()); + let _ = ACTIVE.set(lang); +} + +/// The language in use. `en-US` until [`init`] is called (tests rely on this). +#[must_use] +pub fn active() -> &'static LanguageIdentifier { + ACTIVE.get().unwrap_or(&FALLBACK) +} + +/// A named argument for a message. +pub type Arg = (&'static str, FluentValue<'static>); + +/// Looks up `key` with `args`. Prefer the [`t!`] macro. +#[must_use] +pub fn lookup(key: &str, args: &[Arg]) -> String { + let found = if args.is_empty() { + LOCALES.try_lookup(active(), key) + } else { + let map: HashMap, FluentValue<'static>> = args + .iter() + .map(|(name, value)| (Cow::Borrowed(*name), value.clone())) + .collect(); + LOCALES.try_lookup_with_args(active(), key, &map) + }; + found.unwrap_or_else(|| { + tracing::error!(key, "missing translation"); + format!("⟦{key}⟧") + }) +} + +/// Whether `key` exists in the fallback catalog. +#[must_use] +pub fn has(key: &str) -> bool { + LOCALES.try_lookup(&FALLBACK, key).is_some() +} + +/// Converts a Rust value into a Fluent argument. Numbers stay numbers so +/// plural rules apply. +pub trait IntoArg { + /// The Fluent value for `self`. + fn into_arg(self) -> FluentValue<'static>; +} + +macro_rules! number_arg { + ($($ty:ty),*) => {$( + impl IntoArg for $ty { + fn into_arg(self) -> FluentValue<'static> { + FluentValue::from(self) + } + } + )*}; +} +number_arg!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize, f32, f64); + +impl IntoArg for String { + fn into_arg(self) -> FluentValue<'static> { + FluentValue::from(self) + } +} + +impl IntoArg for &str { + fn into_arg(self) -> FluentValue<'static> { + FluentValue::from(self.to_owned()) + } +} + +impl IntoArg for &String { + fn into_arg(self) -> FluentValue<'static> { + FluentValue::from(self.clone()) + } +} + +impl IntoArg for Cow<'_, str> { + fn into_arg(self) -> FluentValue<'static> { + FluentValue::from(self.into_owned()) + } +} + +/// Looks up a message from the catalog. +/// +/// `t!("key")` or `t!("key", name = value, …)`. Returns a `String`. +#[macro_export] +macro_rules! t { + ($key:expr) => { + $crate::i18n::lookup($key, &[]) + }; + ($key:expr, $($name:ident = $value:expr),+ $(,)?) => { + $crate::i18n::lookup( + $key, + &[$((stringify!($name), $crate::i18n::IntoArg::into_arg($value))),+], + ) + }; +} + +#[cfg(test)] +mod tests { + #[test] + fn plain_lookup() { + assert_eq!(t!("app-name"), "libbui"); + } + + #[test] + fn arguments_and_plurals() { + assert_eq!(t!("time-days", count = 1), "1 day"); + assert_eq!(t!("time-days", count = 3), "3 days"); + } + + #[test] + fn placeables_carry_no_isolation_marks() { + let rendered = t!("time-days", count = 3); + assert!(!rendered.contains('\u{2068}') && !rendered.contains('\u{2069}')); + } + + #[test] + fn a_missing_key_is_visible() { + assert_eq!(t!("no-such-key"), "⟦no-such-key⟧"); + } +} diff --git a/crates/libbui/src/keymap.rs b/crates/libbui/src/keymap.rs new file mode 100644 index 0000000..3d1646a --- /dev/null +++ b/crates/libbui/src/keymap.rs @@ -0,0 +1,922 @@ +//! One table of key bindings that drives everything. +//! +//! The dispatcher, the footer hints and the `?` help overlay all read the same +//! [`Keymap`], so they cannot drift apart: a key that works is a key that is +//! documented. Bindings are data, which is also what makes them rebindable +//! from `config.toml`. +//! +//! Keys resolve in a [`Context`]: the focused context is tried first, then +//! [`Context::Global`]. Text inputs swallow printable keys before the keymap +//! is consulted (see `App`), so `q` in a search box types a `q`. + +use std::collections::{BTreeMap, HashMap}; +use std::fmt; + +use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; + +/// Where a binding applies. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum Context { + /// Everywhere, unless the focused context claims the key first. + Global, + /// Any scrollable list or table. + List, + /// The shelf of loans. + Shelf, + /// Catalog search. + Search, + /// A title's detail pane. + Detail, + /// The holds list. + Holds, + /// The download queue. + Downloads, + /// The first-run pairing wizard. + Setup, + /// Any modal dialog. + Dialog, +} + +impl Context { + /// The Fluent key naming this group in the help overlay. + #[must_use] + pub const fn title_key(self) -> &'static str { + match self { + Self::Global => "keys-group-global", + Self::List => "keys-group-list", + Self::Shelf => "keys-group-shelf", + Self::Search => "keys-group-search", + Self::Detail => "keys-group-detail", + Self::Holds => "keys-group-holds", + Self::Downloads => "keys-group-downloads", + Self::Setup => "keys-group-setup", + Self::Dialog => "keys-group-dialog", + } + } +} + +/// Everything a key can ask for. +/// +/// Commands are intentions, not effects: `Command::Borrow` means "the user +/// pressed the borrow key here", and the focused screen decides what that +/// means for the selected title. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum Command { + // -- global + /// Leave libbui. + Quit, + /// Close the top-most layer: dialog, filter, detail, then nothing. + Back, + /// Toggle the help overlay. + Help, + /// Open the command palette. + Palette, + /// Go to the shelf. + GoShelf, + /// Go to search. + GoSearch, + /// Go to holds. + GoHolds, + /// Go to downloads. + GoDownloads, + /// Cycle to the next tab. + NextTab, + /// Cycle to the previous tab. + PrevTab, + /// Move focus to the next pane. + NextPane, + /// Move focus to the previous pane. + PrevPane, + /// Re-sync the account / reload the current view. + Refresh, + /// Switch library card. + SwitchCard, + /// Open settings. + Settings, + /// Suspend to the shell (Ctrl-Z). + Suspend, + /// Force a full redraw. + Redraw, + + // -- lists + /// Move the selection up one row. + Up, + /// Move the selection down one row. + Down, + /// Move left (previous column / collapse). + Left, + /// Move right (next column / expand). + Right, + /// Jump to the first row. + Top, + /// Jump to the last row. + Bottom, + /// Scroll up one page. + PageUp, + /// Scroll down one page. + PageDown, + /// Scroll up half a page. + HalfPageUp, + /// Scroll down half a page. + HalfPageDown, + /// Activate the selection. + Select, + /// Filter the current list as you type. + Filter, + /// Cycle the sort order. + Sort, + + // -- titles + /// Borrow the selected title. + Borrow, + /// Place a hold on the selected title. + PlaceHold, + /// Return the selected loan. + Return, + /// Renew the selected loan. + Renew, + /// Download the selected loan. + Download, + /// Open the selected title in Libby (browser). + OpenInLibby, + /// Open the downloaded file or its folder. + OpenFile, + /// Copy a share link for the selected title. + CopyLink, + + // -- search + /// Focus the search box. + FocusQuery, + /// Open the filters panel. + Filters, + /// Toggle "available now" only. + ToggleAvailable, + /// Load the next page of results. + NextPage, + + // -- holds + /// Cancel the selected hold. + CancelHold, + /// Suspend or resume the selected hold. + SuspendHold, + + // -- downloads + /// Pause or resume the selected download. + PauseResume, + /// Cancel the selected download. + CancelDownload, + /// Retry a failed download. + Retry, + /// Remove finished downloads from the list. + ClearFinished, + + // -- dialogs + /// Accept the dialog. + Confirm, +} + +impl Command { + /// The stable name used in `config.toml` (`[keymap]`) and the palette. + #[must_use] + pub const fn id(self) -> &'static str { + match self { + Self::Quit => "quit", + Self::Back => "back", + Self::Help => "help", + Self::Palette => "palette", + Self::GoShelf => "go-shelf", + Self::GoSearch => "go-search", + Self::GoHolds => "go-holds", + Self::GoDownloads => "go-downloads", + Self::NextTab => "next-tab", + Self::PrevTab => "prev-tab", + Self::NextPane => "next-pane", + Self::PrevPane => "prev-pane", + Self::Refresh => "refresh", + Self::SwitchCard => "switch-card", + Self::Settings => "settings", + Self::Suspend => "suspend", + Self::Redraw => "redraw", + Self::Up => "up", + Self::Down => "down", + Self::Left => "left", + Self::Right => "right", + Self::Top => "top", + Self::Bottom => "bottom", + Self::PageUp => "page-up", + Self::PageDown => "page-down", + Self::HalfPageUp => "half-page-up", + Self::HalfPageDown => "half-page-down", + Self::Select => "select", + Self::Filter => "filter", + Self::Sort => "sort", + Self::Borrow => "borrow", + Self::PlaceHold => "place-hold", + Self::Return => "return", + Self::Renew => "renew", + Self::Download => "download", + Self::OpenInLibby => "open-in-libby", + Self::OpenFile => "open-file", + Self::CopyLink => "copy-link", + Self::FocusQuery => "focus-query", + Self::Filters => "filters", + Self::ToggleAvailable => "toggle-available", + Self::NextPage => "next-page", + Self::CancelHold => "cancel-hold", + Self::SuspendHold => "suspend-hold", + Self::PauseResume => "pause-resume", + Self::CancelDownload => "cancel-download", + Self::Retry => "retry", + Self::ClearFinished => "clear-finished", + Self::Confirm => "confirm", + } + } + + /// The Fluent key describing this command (`cmd-`). + #[must_use] + pub fn description_key(self) -> String { + format!("cmd-{}", self.id()) + } + + /// The Fluent key for the short footer label (`hint-`). + #[must_use] + pub fn hint_key(self) -> String { + format!("hint-{}", self.id()) + } +} + +/// A key with its modifiers, normalised so lookups are exact. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct Chord { + /// The key. + pub code: KeyCode, + /// Ctrl/Alt (Shift is folded into the character for letters). + pub modifiers: KeyModifiers, +} + +impl Chord { + /// A plain key. + #[must_use] + pub const fn key(code: KeyCode) -> Self { + Self { + code, + modifiers: KeyModifiers::NONE, + } + } + + /// A plain character. + #[must_use] + pub const fn char(c: char) -> Self { + Self::key(KeyCode::Char(c)) + } + + /// Ctrl + a character. + #[must_use] + pub const fn ctrl(c: char) -> Self { + Self { + code: KeyCode::Char(c), + modifiers: KeyModifiers::CONTROL, + } + } + + /// Normalises a terminal key event. + /// + /// Terminals disagree about Shift: `G` may arrive as `Char('G')` with or + /// without the SHIFT flag, and Shift-Tab as `BackTab` with or without it. + /// Shift is dropped wherever the key code already says it. + #[must_use] + pub fn from_event(event: KeyEvent) -> Self { + let mut modifiers = event.modifiers & (KeyModifiers::CONTROL | KeyModifiers::ALT); + let code = match event.code { + KeyCode::Char(c) if event.modifiers.contains(KeyModifiers::SHIFT) => { + KeyCode::Char(c.to_uppercase().next().unwrap_or(c)) + } + KeyCode::Char(c) if modifiers.contains(KeyModifiers::CONTROL) => { + KeyCode::Char(c.to_ascii_lowercase()) + } + KeyCode::BackTab => KeyCode::BackTab, + other => { + if event.modifiers.contains(KeyModifiers::SHIFT) { + modifiers |= KeyModifiers::SHIFT; + } + other + } + }; + Self { code, modifiers } + } + + /// Parses the config spelling: `q`, `G`, `ctrl-p`, `alt-enter`, `shift-tab`, + /// `f5`, `space`, `pgdn`, `?`. + pub fn parse(raw: &str) -> Result { + let bad = || ParseChordError(raw.to_owned()); + let mut modifiers = KeyModifiers::NONE; + let mut rest = raw; + loop { + let lower = rest.to_ascii_lowercase(); + if let Some(tail) = strip_modifier(&lower, rest, "ctrl-") { + modifiers |= KeyModifiers::CONTROL; + rest = tail; + } else if let Some(tail) = strip_modifier(&lower, rest, "alt-") { + modifiers |= KeyModifiers::ALT; + rest = tail; + } else if let Some(tail) = strip_modifier(&lower, rest, "shift-") { + modifiers |= KeyModifiers::SHIFT; + rest = tail; + } else { + break; + } + } + let code = match rest.to_ascii_lowercase().as_str() { + "enter" | "return" => KeyCode::Enter, + "esc" | "escape" => KeyCode::Esc, + "tab" => KeyCode::Tab, + "backtab" => KeyCode::BackTab, + "space" => KeyCode::Char(' '), + "backspace" => KeyCode::Backspace, + "delete" | "del" => KeyCode::Delete, + "up" => KeyCode::Up, + "down" => KeyCode::Down, + "left" => KeyCode::Left, + "right" => KeyCode::Right, + "home" => KeyCode::Home, + "end" => KeyCode::End, + "pgup" | "pageup" => KeyCode::PageUp, + "pgdn" | "pagedown" => KeyCode::PageDown, + name if name.len() > 1 && name.starts_with('f') => { + let n: u8 = name[1..].parse().map_err(|_| bad())?; + if !(1..=12).contains(&n) { + return Err(bad()); + } + KeyCode::F(n) + } + _ => { + let mut chars = rest.chars(); + match (chars.next(), chars.next()) { + (Some(c), None) => KeyCode::Char(c), + _ => return Err(bad()), + } + } + }; + // Fold Shift into the key the same way `from_event` does. + let (code, modifiers) = match code { + KeyCode::Tab if modifiers.contains(KeyModifiers::SHIFT) => { + (KeyCode::BackTab, modifiers - KeyModifiers::SHIFT) + } + KeyCode::Char(c) if modifiers.contains(KeyModifiers::SHIFT) => ( + KeyCode::Char(c.to_uppercase().next().unwrap_or(c)), + modifiers - KeyModifiers::SHIFT, + ), + KeyCode::Char(c) if modifiers.contains(KeyModifiers::CONTROL) => { + (KeyCode::Char(c.to_ascii_lowercase()), modifiers) + } + other => (other, modifiers), + }; + Ok(Self { code, modifiers }) + } +} + +fn strip_modifier<'a>(lower: &str, original: &'a str, prefix: &str) -> Option<&'a str> { + // A lone "-"-suffixed word such as "ctrl-" must still leave a key behind. + (lower.starts_with(prefix) && original.len() > prefix.len()).then(|| &original[prefix.len()..]) +} + +/// A chord spelled the way people read it: `Ctrl-P`, `Enter`, `g`, `G`, `↑`. +impl fmt::Display for Chord { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + if self.modifiers.contains(KeyModifiers::CONTROL) { + f.write_str("Ctrl-")?; + } + if self.modifiers.contains(KeyModifiers::ALT) { + f.write_str("Alt-")?; + } + if self.modifiers.contains(KeyModifiers::SHIFT) { + f.write_str("Shift-")?; + } + match self.code { + KeyCode::Char(' ') => f.write_str("Space"), + KeyCode::Char(c) if self.modifiers.contains(KeyModifiers::CONTROL) => { + write!(f, "{}", c.to_ascii_uppercase()) + } + KeyCode::Char(c) => write!(f, "{c}"), + KeyCode::Enter => f.write_str("Enter"), + KeyCode::Esc => f.write_str("Esc"), + KeyCode::Tab => f.write_str("Tab"), + KeyCode::BackTab => f.write_str("Shift-Tab"), + KeyCode::Backspace => f.write_str("Backspace"), + KeyCode::Delete => f.write_str("Del"), + KeyCode::Up => f.write_str("↑"), + KeyCode::Down => f.write_str("↓"), + KeyCode::Left => f.write_str("←"), + KeyCode::Right => f.write_str("→"), + KeyCode::Home => f.write_str("Home"), + KeyCode::End => f.write_str("End"), + KeyCode::PageUp => f.write_str("PgUp"), + KeyCode::PageDown => f.write_str("PgDn"), + KeyCode::F(n) => write!(f, "F{n}"), + other => write!(f, "{other:?}"), + } + } +} + +/// A key spelling the keymap could not understand. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("unrecognised key {0:?} (examples: q, G, ctrl-p, shift-tab, f5, space, enter)")] +pub struct ParseChordError(pub String); + +/// A problem with the `[keymap]` section of the config. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum KeymapError { + /// The left-hand side is not `command` or `context.command`. + #[error("unknown command {0:?} in [keymap]")] + UnknownCommand(String), + /// The context prefix is not a known context. + #[error("unknown context {0:?} in [keymap]")] + UnknownContext(String), + /// The command exists but is not bound in that context by default, so + /// rebinding it there would do nothing. + #[error("{command:?} is not available in the {context:?} context")] + NotInContext { + /// The command id. + command: String, + /// The context name. + context: String, + }, + /// A key spelling was not understood. + #[error("[keymap] {command}: {source}")] + BadKey { + /// The command id. + command: String, + /// Why the key was rejected. + source: ParseChordError, + }, + /// Two commands in one context claim the same key. + #[error("{key} is bound to both {first:?} and {second:?} in the {context:?} context")] + Conflict { + /// The contested key. + key: String, + /// The context name. + context: String, + /// The first claimant. + first: String, + /// The second claimant. + second: String, + }, +} + +/// One row of the binding table. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Binding { + /// Where it applies. + pub context: Context, + /// What it does. + pub command: Command, + /// The keys that trigger it. The first is the one shown in hints. + pub chords: Vec, +} + +/// The resolved binding table. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Keymap { + bindings: Vec, + lookup: HashMap<(Context, Chord), Command>, +} + +impl Default for Keymap { + fn default() -> Self { + Self::build(default_bindings()).expect("the default keymap has no conflicts") + } +} + +impl Keymap { + fn build(bindings: Vec) -> Result { + let mut lookup = HashMap::new(); + for binding in &bindings { + for chord in &binding.chords { + if let Some(previous) = lookup.insert((binding.context, *chord), binding.command) + && previous != binding.command + { + return Err(KeymapError::Conflict { + key: chord.to_string(), + context: context_id(binding.context).to_owned(), + first: previous.id().to_owned(), + second: binding.command.id().to_owned(), + }); + } + } + } + Ok(Self { bindings, lookup }) + } + + /// The default keymap with the user's overrides applied. + /// + /// Keys are `command` (rebinds it in every context that has it) or + /// `context.command`; values replace that command's keys. An empty list + /// unbinds it. Anything unrecognised is an error, never ignored. + pub fn with_overrides(overrides: &BTreeMap>) -> Result { + let mut bindings = default_bindings(); + for (target, keys) in overrides { + let (context, command_id) = match target.split_once('.') { + Some((context, command)) => ( + Some( + parse_context(context) + .ok_or_else(|| KeymapError::UnknownContext(context.to_owned()))?, + ), + command, + ), + None => (None, target.as_str()), + }; + let chords = keys + .iter() + .map(|key| { + Chord::parse(key).map_err(|source| KeymapError::BadKey { + command: command_id.to_owned(), + source, + }) + }) + .collect::, _>>()?; + let mut matched = false; + let mut known = false; + for binding in &mut bindings { + if binding.command.id() != command_id { + continue; + } + known = true; + if context.is_none_or(|wanted| wanted == binding.context) { + binding.chords.clone_from(&chords); + matched = true; + } + } + if !known { + return Err(KeymapError::UnknownCommand(command_id.to_owned())); + } + if !matched { + return Err(KeymapError::NotInContext { + command: command_id.to_owned(), + context: context.map(context_id).unwrap_or_default().to_owned(), + }); + } + } + Self::build(bindings) + } + + /// Resolves a key event: the first context in `contexts` that binds it + /// wins. Pass the focused context(s) first and [`Context::Global`] last. + #[must_use] + pub fn resolve(&self, contexts: &[Context], event: KeyEvent) -> Option { + let chord = Chord::from_event(event); + contexts + .iter() + .find_map(|context| self.lookup.get(&(*context, chord)).copied()) + } + + /// The key shown for `command` in `context` (falling back to the list and + /// global contexts), if it is bound at all. + #[must_use] + pub fn primary(&self, context: Context, command: Command) -> Option { + [context, Context::List, Context::Global] + .into_iter() + .find_map(|ctx| { + self.bindings + .iter() + .find(|b| b.context == ctx && b.command == command) + .and_then(|b| b.chords.first().copied()) + }) + } + + /// The key shown for `command` in exactly `context`, with no fallback. + /// Use this when walking a context stack yourself. + #[must_use] + pub fn primary_in(&self, context: Context, command: Command) -> Option { + self.bindings + .iter() + .find(|b| b.context == context && b.command == command) + .and_then(|b| b.chords.first().copied()) + } + + /// Every binding in `context`, in table order, for the help overlay. + pub fn in_context(&self, context: Context) -> impl Iterator { + self.bindings + .iter() + .filter(move |binding| binding.context == context && !binding.chords.is_empty()) + } + + /// Every binding, for tests and the palette. + #[must_use] + pub fn bindings(&self) -> &[Binding] { + &self.bindings + } +} + +const CONTEXTS: [(Context, &str); 9] = [ + (Context::Global, "global"), + (Context::List, "list"), + (Context::Shelf, "shelf"), + (Context::Search, "search"), + (Context::Detail, "detail"), + (Context::Holds, "holds"), + (Context::Downloads, "downloads"), + (Context::Setup, "setup"), + (Context::Dialog, "dialog"), +]; + +/// Every context, in help-overlay order. +pub fn contexts() -> impl Iterator { + CONTEXTS.into_iter().map(|(context, _)| context) +} + +fn context_id(context: Context) -> &'static str { + CONTEXTS + .iter() + .find(|(candidate, _)| *candidate == context) + .map_or("global", |(_, id)| id) +} + +fn parse_context(raw: &str) -> Option { + CONTEXTS + .iter() + .find(|(_, id)| *id == raw) + .map(|(context, _)| *context) +} + +fn default_bindings() -> Vec { + use Command as C; + use Context as X; + use KeyCode as K; + + let key = Chord::key; + let ch = Chord::char; + let ctrl = Chord::ctrl; + let bind = |context, command, chords: &[Chord]| Binding { + context, + command, + chords: chords.to_vec(), + }; + + vec![ + // -- global + bind(X::Global, C::Help, &[ch('?'), key(K::F(1))]), + bind(X::Global, C::Palette, &[ctrl('p'), ch(':')]), + bind(X::Global, C::GoShelf, &[ch('1')]), + bind(X::Global, C::GoSearch, &[ch('2')]), + bind(X::Global, C::GoHolds, &[ch('3')]), + bind(X::Global, C::GoDownloads, &[ch('4')]), + bind(X::Global, C::NextTab, &[key(K::Tab)]), + bind(X::Global, C::PrevTab, &[key(K::BackTab)]), + bind(X::Global, C::Refresh, &[ctrl('r'), key(K::F(5))]), + bind(X::Global, C::SwitchCard, &[ch('c')]), + bind(X::Global, C::Settings, &[ch(',')]), + bind(X::Global, C::Back, &[key(K::Esc)]), + bind(X::Global, C::Quit, &[ch('q'), ctrl('c')]), + bind(X::Global, C::Suspend, &[ctrl('z')]), + bind(X::Global, C::Redraw, &[ctrl('l')]), + // -- any list + bind(X::List, C::Down, &[ch('j'), key(K::Down)]), + bind(X::List, C::Up, &[ch('k'), key(K::Up)]), + bind(X::List, C::Left, &[ch('h'), key(K::Left)]), + bind(X::List, C::Right, &[ch('l'), key(K::Right)]), + bind(X::List, C::Top, &[ch('g'), key(K::Home)]), + bind(X::List, C::Bottom, &[ch('G'), key(K::End)]), + bind(X::List, C::PageDown, &[key(K::PageDown), ctrl('f')]), + bind(X::List, C::PageUp, &[key(K::PageUp), ctrl('b')]), + bind(X::List, C::HalfPageDown, &[ctrl('d')]), + bind(X::List, C::HalfPageUp, &[ctrl('u')]), + bind(X::List, C::Select, &[key(K::Enter)]), + bind(X::List, C::Filter, &[ch('/')]), + bind(X::List, C::Sort, &[ch('s')]), + // -- shelf + bind(X::Shelf, C::Download, &[ch('d')]), + bind(X::Shelf, C::Renew, &[ch('r')]), + bind(X::Shelf, C::Return, &[ch('x')]), + bind(X::Shelf, C::OpenInLibby, &[ch('o')]), + bind(X::Shelf, C::OpenFile, &[ch('O')]), + bind(X::Shelf, C::CopyLink, &[ch('y')]), + // -- search + bind(X::Search, C::FocusQuery, &[ch('/'), ch('i')]), + bind(X::Search, C::Filters, &[ch('f')]), + bind(X::Search, C::ToggleAvailable, &[ch('a')]), + bind(X::Search, C::Borrow, &[ch('b')]), + bind(X::Search, C::PlaceHold, &[ch('H')]), + bind(X::Search, C::NextPage, &[ch('n')]), + bind(X::Search, C::OpenInLibby, &[ch('o')]), + bind(X::Search, C::CopyLink, &[ch('y')]), + // -- detail + bind(X::Detail, C::Borrow, &[ch('b')]), + bind(X::Detail, C::PlaceHold, &[ch('H')]), + bind(X::Detail, C::Download, &[ch('d')]), + bind(X::Detail, C::Renew, &[ch('r')]), + bind(X::Detail, C::Return, &[ch('x')]), + bind(X::Detail, C::OpenInLibby, &[ch('o')]), + bind(X::Detail, C::OpenFile, &[ch('O')]), + bind(X::Detail, C::CopyLink, &[ch('y')]), + // -- holds + bind(X::Holds, C::Borrow, &[ch('b')]), + bind(X::Holds, C::SuspendHold, &[ch('p')]), + bind(X::Holds, C::CancelHold, &[ch('x')]), + bind(X::Holds, C::OpenInLibby, &[ch('o')]), + // -- downloads + bind(X::Downloads, C::PauseResume, &[ch('p'), ch(' ')]), + bind(X::Downloads, C::CancelDownload, &[ch('x')]), + bind(X::Downloads, C::Retry, &[ch('r')]), + bind(X::Downloads, C::ClearFinished, &[ch('C')]), + bind(X::Downloads, C::OpenFile, &[ch('o'), key(K::Enter)]), + // -- setup + bind(X::Setup, C::Select, &[key(K::Enter)]), + bind(X::Setup, C::NextPane, &[key(K::Tab)]), + bind(X::Setup, C::PrevPane, &[key(K::BackTab)]), + bind(X::Setup, C::Refresh, &[ctrl('r')]), + // -- dialogs + bind(X::Dialog, C::Confirm, &[key(K::Enter), ch('y')]), + bind(X::Dialog, C::Back, &[key(K::Esc), ch('n')]), + bind( + X::Dialog, + C::Left, + &[ch('h'), key(K::Left), key(K::BackTab)], + ), + bind(X::Dialog, C::Right, &[ch('l'), key(K::Right), key(K::Tab)]), + bind(X::Dialog, C::Up, &[ch('k'), key(K::Up)]), + bind(X::Dialog, C::Down, &[ch('j'), key(K::Down)]), + ] +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use super::*; + + fn press(code: KeyCode, modifiers: KeyModifiers) -> KeyEvent { + KeyEvent::new(code, modifiers) + } + + #[test] + fn the_default_keymap_builds() { + let keymap = Keymap::default(); + assert!(!keymap.bindings().is_empty()); + } + + #[test] + fn the_focused_context_wins_over_global() { + let keymap = Keymap::default(); + let x = press(KeyCode::Char('x'), KeyModifiers::NONE); + assert_eq!( + keymap.resolve(&[Context::Shelf, Context::List, Context::Global], x), + Some(Command::Return) + ); + assert_eq!( + keymap.resolve(&[Context::Holds, Context::List, Context::Global], x), + Some(Command::CancelHold) + ); + assert_eq!(keymap.resolve(&[Context::Global], x), None); + } + + #[test] + fn shift_is_folded_into_the_character() { + let keymap = Keymap::default(); + let contexts = [Context::List, Context::Global]; + for event in [ + press(KeyCode::Char('G'), KeyModifiers::SHIFT), + press(KeyCode::Char('G'), KeyModifiers::NONE), + press(KeyCode::Char('g'), KeyModifiers::SHIFT), + ] { + assert_eq!(keymap.resolve(&contexts, event), Some(Command::Bottom)); + } + assert_eq!( + keymap.resolve(&contexts, press(KeyCode::BackTab, KeyModifiers::SHIFT)), + Some(Command::PrevTab) + ); + } + + #[test] + fn ctrl_c_always_quits() { + let keymap = Keymap::default(); + let event = press(KeyCode::Char('c'), KeyModifiers::CONTROL); + for context in contexts() { + assert_eq!( + keymap.resolve(&[context, Context::Global], event), + Some(Command::Quit), + "{context:?}" + ); + } + } + + #[test] + fn chords_parse_and_display() { + let cases = [ + ("q", "q"), + ("G", "G"), + ("shift-g", "G"), + ("ctrl-p", "Ctrl-P"), + ("Ctrl-P", "Ctrl-P"), + ("shift-tab", "Shift-Tab"), + ("alt-enter", "Alt-Enter"), + ("f5", "F5"), + ("space", "Space"), + ("pgdn", "PgDn"), + ("?", "?"), + ("-", "-"), + ]; + for (raw, shown) in cases { + assert_eq!(Chord::parse(raw).unwrap().to_string(), shown, "{raw}"); + } + for bad in ["", "ctrl-", "f13", "banana", "ctrl-shift-"] { + assert!(Chord::parse(bad).is_err(), "{bad:?} should not parse"); + } + } + + #[test] + fn a_parsed_chord_matches_the_event_it_describes() { + let chord = Chord::parse("ctrl-p").unwrap(); + let event = press(KeyCode::Char('p'), KeyModifiers::CONTROL); + assert_eq!(chord, Chord::from_event(event)); + } + + #[test] + fn overrides_rebind_and_unbind() { + let overrides = BTreeMap::from([ + ("quit".to_owned(), vec!["ctrl-q".to_owned()]), + ("shelf.return".to_owned(), vec![]), + ]); + let keymap = Keymap::with_overrides(&overrides).unwrap(); + let q = press(KeyCode::Char('q'), KeyModifiers::NONE); + let ctrl_q = press(KeyCode::Char('q'), KeyModifiers::CONTROL); + let x = press(KeyCode::Char('x'), KeyModifiers::NONE); + assert_eq!(keymap.resolve(&[Context::Global], q), None); + assert_eq!( + keymap.resolve(&[Context::Global], ctrl_q), + Some(Command::Quit) + ); + assert_eq!(keymap.resolve(&[Context::Shelf], x), None); + assert_eq!(keymap.primary(Context::Shelf, Command::Return), None); + } + + #[test] + fn bad_overrides_are_errors_not_shrugs() { + let with = |key: &str, value: &str| { + Keymap::with_overrides(&BTreeMap::from([(key.to_owned(), vec![value.to_owned()])])) + }; + assert!(matches!( + with("frobnicate", "x"), + Err(KeymapError::UnknownCommand(_)) + )); + assert!(matches!( + with("attic.quit", "x"), + Err(KeymapError::UnknownContext(_)) + )); + assert!(matches!( + with("holds.download", "x"), + Err(KeymapError::NotInContext { .. }) + )); + assert!(matches!( + with("quit", "banana"), + Err(KeymapError::BadKey { .. }) + )); + // `?` is already Help in the global context. + assert!(matches!( + with("quit", "?"), + Err(KeymapError::Conflict { .. }) + )); + } + + #[test] + fn every_command_and_context_is_documented() { + let keymap = Keymap::default(); + let mut missing = Vec::new(); + for (context, _) in CONTEXTS { + if !crate::i18n::has(context.title_key()) { + missing.push(context.title_key().to_owned()); + } + } + for binding in keymap.bindings() { + for key in [ + binding.command.description_key(), + binding.command.hint_key(), + ] { + if !crate::i18n::has(&key) { + missing.push(key); + } + } + } + missing.sort(); + missing.dedup(); + assert!( + missing.is_empty(), + "missing from locales/en-US/keys.ftl: {missing:#?}" + ); + } + + #[test] + fn command_ids_are_unique() { + let keymap = Keymap::default(); + let mut by_id: BTreeMap<&str, Command> = BTreeMap::new(); + for binding in keymap.bindings() { + if let Some(previous) = by_id.insert(binding.command.id(), binding.command) { + assert_eq!( + previous, + binding.command, + "duplicate id {}", + binding.command.id() + ); + } + } + } +} diff --git a/crates/libbui/src/lib.rs b/crates/libbui/src/lib.rs new file mode 100644 index 0000000..9bf21c0 --- /dev/null +++ b/crates/libbui/src/lib.rs @@ -0,0 +1,19 @@ +//! libbui: a terminal interface for Libby. +//! +//! The binary is a thin shell around this library so that everything, the +//! whole interface included, can be driven from tests. + +pub mod api; +pub mod app; +pub mod cli; +pub mod i18n; +pub mod keymap; +pub mod screens; +pub mod services; +pub mod startup; +pub mod theme; +pub mod tui; +pub mod ui; + +#[cfg(test)] +pub(crate) mod testing; diff --git a/crates/libbui/src/main.rs b/crates/libbui/src/main.rs index b07c574..0b97fe3 100644 --- a/crates/libbui/src/main.rs +++ b/crates/libbui/src/main.rs @@ -1,3 +1,11 @@ -//! libbui — a terminal UI for your Libby library. +//! The `libbui` binary. -fn main() {} +use clap::Parser; +use color_eyre::eyre::Result; +use libbui::cli::Args; + +#[tokio::main] +async fn main() -> Result<()> { + color_eyre::install()?; + libbui::startup::launch(Args::parse()).await +} diff --git a/crates/libbui/src/screens/detail.rs b/crates/libbui/src/screens/detail.rs new file mode 100644 index 0000000..a44e0d3 --- /dev/null +++ b/crates/libbui/src/screens/detail.rs @@ -0,0 +1,81 @@ +//! Everything about one title. +//! +//! Placeholder: the real screen is still to be written. + +use ratatui::Frame; +use ratatui::layout::Rect; +use ratatui::widgets::Paragraph; + +use crate::app::{Ctx, Shared}; +use crate::keymap::{Command, Context}; +use crate::screens::{Handled, Screen}; +use libby::TitleId; +use libby::models::{Hold, Loan, Media}; + +/// Replies to work this screen started. +#[derive(Debug)] +pub enum Msg {} + +/// What to show. +#[derive(Debug, Clone)] +pub enum Target { + /// A catalogue entry, already loaded (from search). + Media(Box), + /// A loan; the catalogue entry is fetched to fill in the rest. + Loan(Box), + /// A hold; the catalogue entry is fetched to fill in the rest. + Hold(Box), + /// Just an id; everything is fetched. + Title(TitleId), +} + +impl Target { + /// The title being shown. + #[must_use] + pub fn title_id(&self) -> &TitleId { + match self { + Self::Media(media) => &media.id, + Self::Loan(loan) => &loan.title_id, + Self::Hold(hold) => &hold.title_id, + Self::Title(id) => id, + } + } +} + +/// Everything about one title. +#[derive(Debug, Default)] +pub struct Detail {} + +impl Detail { + /// Points the view at `target` and starts loading what is missing. + pub fn open(&mut self, _target: Target, _cx: &mut Ctx<'_>) {} +} + +impl Screen for Detail { + type Msg = Msg; + + fn context(&self) -> Context { + Context::Detail + } + + fn on_command(&mut self, _command: Command, _cx: &mut Ctx<'_>) -> Handled { + Handled::No + } + + fn on_msg(&mut self, msg: Msg, _cx: &mut Ctx<'_>) { + match msg {} + } + + fn hints(&self, _shared: &Shared) -> Vec { + Vec::new() + } + + fn render(&mut self, frame: &mut Frame<'_>, area: Rect, shared: &Shared) { + frame.render_widget( + Paragraph::new("Detail") + .style(shared.theme.muted) + .centered(), + area, + ); + } +} diff --git a/crates/libbui/src/screens/downloads.rs b/crates/libbui/src/screens/downloads.rs new file mode 100644 index 0000000..58b426d --- /dev/null +++ b/crates/libbui/src/screens/downloads.rs @@ -0,0 +1,53 @@ +//! The download queue. +//! +//! Placeholder: the real screen is still to be written. + +use ratatui::Frame; +use ratatui::layout::Rect; +use ratatui::widgets::Paragraph; + +use crate::app::{Ctx, Shared}; +use crate::keymap::{Command, Context}; +use crate::screens::{Handled, Screen}; + +/// Replies to work this screen started. +#[derive(Debug)] +pub enum Msg {} + +/// The download queue. +#[derive(Debug, Default)] +pub struct Downloads {} + +impl Downloads { + /// The queue changed (a job was added, moved on, or removed). + pub fn on_queue(&mut self, _cx: &mut Ctx<'_>) {} +} + +impl Screen for Downloads { + type Msg = Msg; + + fn context(&self) -> Context { + Context::Downloads + } + + fn on_command(&mut self, _command: Command, _cx: &mut Ctx<'_>) -> Handled { + Handled::No + } + + fn on_msg(&mut self, msg: Msg, _cx: &mut Ctx<'_>) { + match msg {} + } + + fn hints(&self, _shared: &Shared) -> Vec { + Vec::new() + } + + fn render(&mut self, frame: &mut Frame<'_>, area: Rect, shared: &Shared) { + frame.render_widget( + Paragraph::new("Downloads") + .style(shared.theme.muted) + .centered(), + area, + ); + } +} diff --git a/crates/libbui/src/screens/holds.rs b/crates/libbui/src/screens/holds.rs new file mode 100644 index 0000000..f3164fd --- /dev/null +++ b/crates/libbui/src/screens/holds.rs @@ -0,0 +1,46 @@ +//! Your holds. +//! +//! Placeholder: the real screen is still to be written. + +use ratatui::Frame; +use ratatui::layout::Rect; +use ratatui::widgets::Paragraph; + +use crate::app::{Ctx, Shared}; +use crate::keymap::{Command, Context}; +use crate::screens::{Handled, Screen}; + +/// Replies to work this screen started. +#[derive(Debug)] +pub enum Msg {} + +/// Your holds. +#[derive(Debug, Default)] +pub struct Holds {} + +impl Screen for Holds { + type Msg = Msg; + + fn context(&self) -> Context { + Context::Holds + } + + fn on_command(&mut self, _command: Command, _cx: &mut Ctx<'_>) -> Handled { + Handled::No + } + + fn on_msg(&mut self, msg: Msg, _cx: &mut Ctx<'_>) { + match msg {} + } + + fn hints(&self, _shared: &Shared) -> Vec { + Vec::new() + } + + fn render(&mut self, frame: &mut Frame<'_>, area: Rect, shared: &Shared) { + frame.render_widget( + Paragraph::new("Holds").style(shared.theme.muted).centered(), + area, + ); + } +} diff --git a/crates/libbui/src/screens/mod.rs b/crates/libbui/src/screens/mod.rs new file mode 100644 index 0000000..627bd32 --- /dev/null +++ b/crates/libbui/src/screens/mod.rs @@ -0,0 +1,142 @@ +//! The screens, and the contract they share with the app. +//! +//! A screen is a small state machine: it turns commands and keys into state +//! changes and requests, turns replies (`Msg`) into more state, and draws +//! itself from its own state plus [`Shared`]. It never performs I/O itself; +//! it describes the work with [`Ctx::spawn`] or [`Ctx::request`] and the app +//! runs it. That is what makes every screen testable without a terminal or a +//! network. + +use crossterm::event::{KeyEvent, MouseEvent}; +use ratatui::Frame; +use ratatui::layout::Rect; + +use crate::app::{Ctx, Shared}; +use crate::keymap::{Command, Context}; + +pub mod detail; +pub mod downloads; +pub mod holds; +pub mod search; +pub mod setup; +pub mod shelf; + +/// Whether an input was used. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Handled { + /// The input was consumed; nothing else should see it. + Yes, + /// The input means nothing here; let the next layer try. + No, +} + +impl Handled { + /// Whether the input was consumed. + #[must_use] + pub const fn is_yes(self) -> bool { + matches!(self, Self::Yes) + } +} + +impl From for Handled { + fn from(handled: bool) -> Self { + if handled { Self::Yes } else { Self::No } + } +} + +/// One full-size view. +pub trait Screen { + /// Replies to work this screen started. + type Msg; + + /// The keymap context whose bindings apply here (tried before the shared + /// list and global contexts). + fn context(&self) -> Context; + + /// Whether a text field has focus. While true, keys go to + /// [`Screen::on_key`] first and plain characters never reach the keymap, + /// so typing `q` into a search box does not quit. + fn captures_text(&self) -> bool { + false + } + + /// The screen became visible. + fn on_show(&mut self, _cx: &mut Ctx<'_>) {} + + /// The account changed (a sync landed, a loan was added, the active card + /// switched). Clamp cursors, refresh derived rows. + fn on_account(&mut self, _cx: &mut Ctx<'_>) {} + + /// A bound command was pressed. + fn on_command(&mut self, command: Command, cx: &mut Ctx<'_>) -> Handled; + + /// A raw key, offered when [`Screen::captures_text`] is true. + fn on_key(&mut self, _key: KeyEvent, _cx: &mut Ctx<'_>) -> Handled { + Handled::No + } + + /// Bracketed paste, offered when [`Screen::captures_text`] is true. + fn on_paste(&mut self, _text: &str, _cx: &mut Ctx<'_>) -> Handled { + Handled::No + } + + /// A mouse event inside the screen's area (the last area passed to + /// [`Screen::render`]). + fn on_mouse(&mut self, _mouse: MouseEvent, _cx: &mut Ctx<'_>) -> Handled { + Handled::No + } + + /// A reply to work this screen started. + fn on_msg(&mut self, msg: Self::Msg, cx: &mut Ctx<'_>); + + /// The commands worth advertising in the footer right now, most + /// important first. Unbound ones are skipped automatically. + fn hints(&self, shared: &Shared) -> Vec; + + /// Draws the screen. `&mut self` so list and scroll state can be clamped + /// to the real size. + fn render(&mut self, frame: &mut Frame<'_>, area: Rect, shared: &Shared); +} + +/// What a modal wants after handling input. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ModalFlow { + /// Stay open. + Stay, + /// Close. + Close, +} + +/// A dialog drawn over the current screen that takes all input while open. +pub trait Modal: std::fmt::Debug { + /// The keymap contexts whose bindings apply, most specific first. + fn contexts(&self) -> &'static [Context] { + &[Context::Dialog] + } + + /// Whether a text field has focus (see [`Screen::captures_text`]). + fn captures_text(&self) -> bool { + false + } + + /// A bound command was pressed. Unhandled commands are dropped: nothing + /// underneath a modal reacts to input. + fn on_command(&mut self, command: Command, cx: &mut Ctx<'_>) -> ModalFlow; + + /// Every key, before the keymap sees it. Return `None` to let the + /// keymap have it (unless it is typing and [`Modal::captures_text`]). + fn on_key(&mut self, _key: KeyEvent, _cx: &mut Ctx<'_>) -> Option { + None + } + + /// Bracketed paste. + fn on_paste(&mut self, _text: &str, _cx: &mut Ctx<'_>) {} + + /// The commands worth advertising in the footer while open. + fn hints(&self, _shared: &Shared) -> Vec { + vec![Command::Confirm, Command::Back] + } + + /// Draws the modal over `area` (the whole body; centre yourself). + fn render(&mut self, frame: &mut Frame<'_>, area: Rect, shared: &Shared); +} diff --git a/crates/libbui/src/screens/search.rs b/crates/libbui/src/screens/search.rs new file mode 100644 index 0000000..89dc6c7 --- /dev/null +++ b/crates/libbui/src/screens/search.rs @@ -0,0 +1,48 @@ +//! The catalogue. +//! +//! Placeholder: the real screen is still to be written. + +use ratatui::Frame; +use ratatui::layout::Rect; +use ratatui::widgets::Paragraph; + +use crate::app::{Ctx, Shared}; +use crate::keymap::{Command, Context}; +use crate::screens::{Handled, Screen}; + +/// Replies to work this screen started. +#[derive(Debug)] +pub enum Msg {} + +/// The catalogue. +#[derive(Debug, Default)] +pub struct Search {} + +impl Screen for Search { + type Msg = Msg; + + fn context(&self) -> Context { + Context::Search + } + + fn on_command(&mut self, _command: Command, _cx: &mut Ctx<'_>) -> Handled { + Handled::No + } + + fn on_msg(&mut self, msg: Msg, _cx: &mut Ctx<'_>) { + match msg {} + } + + fn hints(&self, _shared: &Shared) -> Vec { + Vec::new() + } + + fn render(&mut self, frame: &mut Frame<'_>, area: Rect, shared: &Shared) { + frame.render_widget( + Paragraph::new("Search") + .style(shared.theme.muted) + .centered(), + area, + ); + } +} diff --git a/crates/libbui/src/screens/setup.rs b/crates/libbui/src/screens/setup.rs new file mode 100644 index 0000000..6bbaf14 --- /dev/null +++ b/crates/libbui/src/screens/setup.rs @@ -0,0 +1,46 @@ +//! Pairing this device with a Libby account. +//! +//! Placeholder: the real screen is still to be written. + +use ratatui::Frame; +use ratatui::layout::Rect; +use ratatui::widgets::Paragraph; + +use crate::app::{Ctx, Shared}; +use crate::keymap::{Command, Context}; +use crate::screens::{Handled, Screen}; + +/// Replies to work this screen started. +#[derive(Debug)] +pub enum Msg {} + +/// Pairing this device with a Libby account. +#[derive(Debug, Default)] +pub struct Setup {} + +impl Screen for Setup { + type Msg = Msg; + + fn context(&self) -> Context { + Context::Setup + } + + fn on_command(&mut self, _command: Command, _cx: &mut Ctx<'_>) -> Handled { + Handled::No + } + + fn on_msg(&mut self, msg: Msg, _cx: &mut Ctx<'_>) { + match msg {} + } + + fn hints(&self, _shared: &Shared) -> Vec { + Vec::new() + } + + fn render(&mut self, frame: &mut Frame<'_>, area: Rect, shared: &Shared) { + frame.render_widget( + Paragraph::new("Setup").style(shared.theme.muted).centered(), + area, + ); + } +} diff --git a/crates/libbui/src/screens/shelf.rs b/crates/libbui/src/screens/shelf.rs new file mode 100644 index 0000000..2518b5f --- /dev/null +++ b/crates/libbui/src/screens/shelf.rs @@ -0,0 +1,46 @@ +//! Your loans. +//! +//! Placeholder: the real screen is still to be written. + +use ratatui::Frame; +use ratatui::layout::Rect; +use ratatui::widgets::Paragraph; + +use crate::app::{Ctx, Shared}; +use crate::keymap::{Command, Context}; +use crate::screens::{Handled, Screen}; + +/// Replies to work this screen started. +#[derive(Debug)] +pub enum Msg {} + +/// Your loans. +#[derive(Debug, Default)] +pub struct Shelf {} + +impl Screen for Shelf { + type Msg = Msg; + + fn context(&self) -> Context { + Context::Shelf + } + + fn on_command(&mut self, _command: Command, _cx: &mut Ctx<'_>) -> Handled { + Handled::No + } + + fn on_msg(&mut self, msg: Msg, _cx: &mut Ctx<'_>) { + match msg {} + } + + fn hints(&self, _shared: &Shared) -> Vec { + Vec::new() + } + + fn render(&mut self, frame: &mut Frame<'_>, area: Rect, shared: &Shared) { + frame.render_widget( + Paragraph::new("Shelf").style(shared.theme.muted).centered(), + area, + ); + } +} diff --git a/crates/libbui/src/services.rs b/crates/libbui/src/services.rs new file mode 100644 index 0000000..1575653 --- /dev/null +++ b/crates/libbui/src/services.rs @@ -0,0 +1,251 @@ +//! The real implementations behind the app's service traits: the download +//! queue (the engine), the resolver the engine calls to turn a loan into a +//! file, and the desktop (browser, file manager, clipboard). + +use std::future::Future; +use std::io::Write; +use std::path::Path; +use std::sync::{Arc, Mutex}; + +use async_trait::async_trait; +use libbui_core::download::{ + EngineError, EngineHandle, JobId, JobSpec, ResolveError, Resolved, Resolver, +}; +use libby::models::Loan; +use libby::{CardId, FormatId, Fulfillment, TitleId}; + +use crate::api::Api; +use crate::app::{DownloadQueue, System, errors}; +use crate::t; + +/// The download engine, driven without waiting. +/// +/// The interface never blocks on the engine: each call is handed to the +/// runtime, and the outcome arrives as an engine event like every other +/// change to the queue. +#[derive(Debug, Clone)] +pub struct EngineQueue { + handle: EngineHandle, + runtime: tokio::runtime::Handle, +} + +impl EngineQueue { + /// Wraps an engine handle. Must be called within a Tokio runtime. + #[must_use] + pub fn new(handle: EngineHandle) -> Self { + Self { + handle, + runtime: tokio::runtime::Handle::current(), + } + } + + fn run(&self, what: &'static str, call: impl FnOnce(EngineHandle) -> F) + where + T: Send + 'static, + F: Future> + Send + 'static, + { + let work = call(self.handle.clone()); + self.runtime.spawn(async move { + if let Err(error) = work.await { + // The job may simply have finished or gone in the meantime; + // the queue on screen already reflects the truth. + tracing::warn!(%error, what, "download queue command failed"); + } + }); + } +} + +impl DownloadQueue for EngineQueue { + fn enqueue(&self, spec: JobSpec) { + self.run( + "enqueue", + |engine| async move { engine.enqueue(spec).await }, + ); + } + + fn pause(&self, id: &JobId) { + let id = id.clone(); + self.run("pause", |engine| async move { engine.pause(&id).await }); + } + + fn resume(&self, id: &JobId) { + let id = id.clone(); + self.run("resume", |engine| async move { engine.resume(&id).await }); + } + + fn cancel(&self, id: &JobId) { + let id = id.clone(); + self.run("cancel", |engine| async move { engine.cancel(&id).await }); + } + + fn retry(&self, id: &JobId) { + let id = id.clone(); + self.run("retry", |engine| async move { engine.retry(&id).await }); + } + + fn remove(&self, id: &JobId) { + let id = id.clone(); + self.run("remove", |engine| async move { engine.remove(&id).await }); + } + + fn clear_finished(&self) { + self.run("clear_finished", |engine| async move { + engine.clear_finished().await + }); + } +} + +/// Turns a queued job into a file by asking Libby to fulfil the loan. +/// +/// The engine only knows ids; fulfilment needs the loan itself. Loans are +/// remembered from the resolver's own last sync and refreshed only when a +/// job names a loan it has not seen, so a batch of downloads costs one sync, +/// not one each. +#[derive(Debug)] +pub struct LoanResolver { + api: Arc, + loans: Mutex>, +} + +impl LoanResolver { + /// A resolver over `api`. + #[must_use] + pub fn new(api: Arc) -> Self { + Self { + api, + loans: Mutex::new(Vec::new()), + } + } + + fn known(&self, title: &TitleId, card: &CardId) -> Option { + let loans = self.loans.lock().ok()?; + loans + .iter() + .find(|loan| &loan.title_id == title && &loan.card_id == card) + .cloned() + } + + async fn loan(&self, title: &TitleId, card: &CardId) -> Result { + if let Some(loan) = self.known(title, card) { + return Ok(loan); + } + let state = self.api.sync().await.map_err(|error| convert(&error))?; + if let Ok(mut loans) = self.loans.lock() { + *loans = state.loans; + } + self.known(title, card) + .ok_or_else(|| ResolveError::permanent(t!("download-not-on-loan"))) + } +} + +#[async_trait] +impl Resolver for LoanResolver { + async fn resolve(&self, spec: &JobSpec) -> Result { + let title = TitleId::new(spec.title_id.as_str()); + let card = CardId::new(spec.card_id.as_str()); + let format = FormatId::new(spec.format_id.as_str()); + let loan = self.loan(&title, &card).await?; + match self.api.fulfill(&loan, &format).await { + Ok(Fulfillment::Download { url, .. }) => Ok(Resolved::Url { + url, + expected_len: None, + }), + Ok(Fulfillment::Acsm { bytes, filename }) => Ok(Resolved::Bytes { + bytes, + filename: Some(filename), + }), + // A web reader or player, not a file. Nothing here will fetch + // what sits behind it. + Ok(Fulfillment::External { .. }) => { + Err(ResolveError::permanent(t!("error-not-downloadable"))) + } + Err(error) => { + if matches!(error, libby::Error::NotFound { .. }) { + // The loan was returned or expired since we last looked. + if let Ok(mut loans) = self.loans.lock() { + loans.clear(); + } + } + Err(convert(&error)) + } + } + } +} + +fn convert(error: &libby::Error) -> ResolveError { + let message = errors::describe(error); + if matches!(error, libby::Error::CardSuspended { .. }) { + ResolveError::fatal_for_card(message) + } else if error.is_retryable() { + ResolveError::retryable(message) + } else { + ResolveError::permanent(message) + } +} + +/// The user's desktop. +#[derive(Debug, Default, Clone, Copy)] +pub struct Desktop; + +impl System for Desktop { + fn open_url(&self, url: &str) -> Result<(), String> { + open::that_detached(url).map_err(|error| error.to_string()) + } + + fn open_path(&self, path: &Path) -> Result<(), String> { + if !path.exists() { + return Err(t!("system-missing-file", path = path.display().to_string())); + } + open::that_detached(path).map_err(|error| error.to_string()) + } + + /// Copies through the terminal (OSC 52), which works over SSH and inside + /// tmux/zellij where a desktop clipboard library cannot reach. + fn copy(&self, text: &str) -> Result<(), String> { + let sequence = format!("\x1b]52;c;{}\x1b\\", base64(text.as_bytes())); + let mut out = std::io::stdout().lock(); + out.write_all(sequence.as_bytes()) + .and_then(|()| out.flush()) + .map_err(|error| error.to_string()) + } +} + +/// Standard base64 with padding. Small enough not to be worth a dependency. +fn base64(bytes: &[u8]) -> String { + const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4); + for chunk in bytes.chunks(3) { + let b = [ + chunk[0], + chunk.get(1).copied().unwrap_or(0), + chunk.get(2).copied().unwrap_or(0), + ]; + let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]); + let sextet = |shift: u32| char::from(ALPHABET[((n >> shift) & 63) as usize]); + out.push(sextet(18)); + out.push(sextet(12)); + out.push(if chunk.len() > 1 { sextet(6) } else { '=' }); + out.push(if chunk.len() > 2 { sextet(0) } else { '=' }); + } + out +} + +#[cfg(test)] +mod tests { + use super::base64; + + #[test] + fn base64_matches_the_rfc_vectors() { + for (plain, encoded) in [ + ("", ""), + ("f", "Zg=="), + ("fo", "Zm8="), + ("foo", "Zm9v"), + ("foob", "Zm9vYg=="), + ("fooba", "Zm9vYmE="), + ("foobar", "Zm9vYmFy"), + ] { + assert_eq!(base64(plain.as_bytes()), encoded); + } + } +} diff --git a/crates/libbui/src/startup.rs b/crates/libbui/src/startup.rs new file mode 100644 index 0000000..73785ef --- /dev/null +++ b/crates/libbui/src/startup.rs @@ -0,0 +1,151 @@ +//! Wiring: turns arguments, files on disk and the terminal into a running +//! app, and puts everything back afterwards. + +use std::sync::Arc; +use std::time::Duration; + +use color_eyre::eyre::{Result, WrapErr, eyre}; +use jiff::Timestamp; +use libbui_core::config::Config; +use libbui_core::download::{self, Engine}; +use libbui_core::identity::{FileStore, SecretStore, StoredIdentity}; +use libbui_core::library::LibraryIndex; +use libbui_core::logging; +use libbui_core::paths::Paths; +use libby::{Client, ClientConfig, Identity}; + +use crate::api::Api; +use crate::app::{self, Account, App, Downloads, Runtime, Services, Shared}; +use crate::cli::Args; +use crate::keymap::Keymap; +use crate::services::{Desktop, EngineQueue, LoanResolver}; +use crate::theme::{ColorDepth, Symbols, Theme}; +use crate::tui::{Options, Tui}; +use crate::ui::cover::Covers; + +/// Runs the interface until the user quits. +/// +/// # Errors +/// Anything that prevents starting (unreadable configuration, an invalid key +/// binding, no terminal) or a terminal failure while running. +pub async fn launch(args: Args) -> Result<()> { + let paths = Paths::discover().wrap_err("could not work out where libbui keeps its files")?; + let _log = logging::init(&paths, &args.log).wrap_err("could not start logging")?; + tracing::info!(version = env!("CARGO_PKG_VERSION"), "starting"); + + let config_file = args.config.clone().unwrap_or_else(|| paths.config_file()); + let mut config = Config::load(&config_file) + .wrap_err_with(|| format!("could not read {}", config_file.display()))?; + if let Some(theme) = &args.theme { + config.theme.clone_from(theme); + } + config.ascii |= args.ascii; + config.mouse &= !args.no_mouse; + + crate::i18n::init(args.lang.as_deref()); + let keymap = Keymap::with_overrides(&config.keymap) + .wrap_err_with(|| format!("invalid [keymap] in {}", config_file.display()))?; + + // The account client, carrying the stored identity if there is one. + let store = Arc::new(FileStore::new(paths.identity_file())); + let client = Client::new(ClientConfig { + account_gap: Duration::from_millis(config.account_gap_ms), + ..ClientConfig::default() + }) + .map_err(|error| eyre!("could not set up the Libby client: {error}"))?; + if let Some(stored) = store + .load() + .wrap_err("could not read the saved Libby pairing")? + { + client.set_identity(Some(Identity::new(stored.token, stored.chip))); + } + let keeper = tokio::spawn(keep_identity(client.clone(), Arc::clone(&store))); + let api: Arc = Arc::new(client); + + // Downloads never carry the account token: a separate, bare client. + let content = reqwest::Client::builder() + .user_agent(concat!("libbui/", env!("CARGO_PKG_VERSION"))) + .build() + .wrap_err("could not set up the download client")?; + let settings = download::Settings::from_config(&config, &paths) + .wrap_err_with(|| format!("invalid [templates] in {}", config_file.display()))?; + let resolver = Arc::new(LoanResolver::new(Arc::clone(&api))); + let (engine, engine_events) = Engine::start(&paths, settings, resolver, content) + .wrap_err("could not start the download queue")?; + let downloads = Downloads { + jobs: engine + .snapshot() + .await + .wrap_err("could not read the download queue")?, + index: LibraryIndex::load(paths.library_index_file()) + .wrap_err("could not read the library index")? + .entries() + .to_vec(), + ..Downloads::default() + }; + + // The terminal's background has to be asked for before the interface + // takes over input. + let depth = ColorDepth::detect(|name| std::env::var(name).ok()); + let is_light = config.theme == "auto" + && depth == ColorDepth::TrueColor + && matches!( + terminal_colorsaurus::theme_mode(terminal_colorsaurus::QueryOptions::default()), + Ok(terminal_colorsaurus::ThemeMode::Light) + ); + + let shared = Shared { + theme: Theme::resolve(&config.theme, depth, is_light), + symbols: Symbols::pick(config.ascii).clone(), + keymap, + account: Account::default(), + downloads, + covers: Covers::new(false), + busy: std::collections::BTreeSet::new(), + now: Timestamp::now(), + frame: 0, + config, + }; + let services = Services { + api, + queue: Arc::new(EngineQueue::new(engine.clone())), + system: Arc::new(Desktop), + }; + let mouse = shared.config.mouse; + let mut app = App::new(shared, services); + + let tui = Tui::enter(Options { mouse }).wrap_err("could not take over the terminal")?; + let mut runtime = Runtime { + tui, + engine: engine_events, + }; + let outcome = app::run(&mut app, &mut runtime).await; + drop(runtime); + + // Pauses what is in flight and saves the queue. + if let Err(error) = engine.shutdown().await { + tracing::warn!(%error, "download queue did not shut down cleanly"); + } + keeper.abort(); + outcome.wrap_err("the terminal stopped responding") +} + +/// Saves the identity whenever it changes (pairing, token refresh) and +/// forgets it when the device is unlinked. +async fn keep_identity(client: Client, store: Arc) { + let mut changes = client.subscribe_identity(); + while changes.changed().await.is_ok() { + let identity = changes.borrow_and_update().clone(); + let result = match identity { + Some(identity) => store.save(&StoredIdentity { + token: identity.token().clone(), + chip: identity.chip().to_owned(), + saved_at: Timestamp::now(), + }), + None => store.clear(), + }; + if let Err(error) = result { + tracing::error!(%error, "could not save the Libby pairing"); + } + } +} diff --git a/crates/libbui/src/testing/fixtures/search-page-2.json b/crates/libbui/src/testing/fixtures/search-page-2.json new file mode 100644 index 0000000..d86c302 --- /dev/null +++ b/crates/libbui/src/testing/fixtures/search-page-2.json @@ -0,0 +1,1177 @@ +{ + "queryKeys": {}, + "facets": { + "availability": { + "name": "Availability", + "items": [ + { + "isApplied": true, + "totalItems": 90, + "totalItemsText": "90", + "id": "all-titles", + "name": "All titles" + }, + { + "isApplied": false, + "totalItemsText": "", + "id": "available-now", + "name": "Available now" + } + ] + }, + "mediaTypes": { + "name": "Media type", + "items": [ + { + "isApplied": true, + "totalItems": 90, + "totalItemsText": "90", + "id": "audiobook", + "name": "Audiobook" + } + ] + }, + "formats": { + "name": "Format", + "items": [ + { + "isApplied": false, + "totalItems": 90, + "totalItemsText": "90", + "id": "audiobook-overdrive", + "name": "OverDrive Listen audiobook" + }, + { + "isApplied": false, + "totalItems": 90, + "totalItemsText": "90", + "id": "audiobook-mp3", + "name": "MP3 audiobook" + } + ] + }, + "maturityLevels": { + "name": "Audience", + "items": [ + { + "isApplied": false, + "totalItems": 88, + "totalItemsText": "88", + "id": "generalcontent", + "name": "General adult" + }, + { + "isApplied": false, + "totalItems": 2, + "totalItemsText": "2", + "id": "juvenile", + "name": "Juvenile" + } + ] + }, + "subjects": { + "name": "Subject", + "items": [ + { + "isApplied": false, + "totalItems": 74, + "totalItemsText": "74", + "id": "26", + "name": "Fiction" + }, + { + "isApplied": false, + "totalItems": 54, + "totalItemsText": "54", + "id": "80", + "name": "Science Fiction" + }, + { + "isApplied": false, + "totalItems": 16, + "totalItemsText": "16", + "id": "49", + "name": "Literature" + } + ] + }, + "bisacCodes": { + "name": "Bisac code", + "items": [ + { + "isApplied": false, + "totalItems": 38, + "totalItemsText": "38", + "id": "FIC028030", + "name": "Fiction / Science Fiction / Space Opera" + }, + { + "isApplied": false, + "totalItems": 26, + "totalItemsText": "26", + "id": "FIC028010", + "name": "Fiction / Science Fiction / Action & Adventure" + }, + { + "isApplied": false, + "totalItems": 14, + "totalItemsText": "14", + "id": "FIC028000", + "name": "Fiction / Science Fiction / General" + } + ] + }, + "languages": { + "name": "Language", + "items": [ + { + "isApplied": false, + "totalItems": 66, + "totalItemsText": "66", + "id": "en", + "name": "English" + }, + { + "isApplied": false, + "totalItems": 23, + "totalItemsText": "23", + "id": "es", + "name": "Spanish; Castilian" + }, + { + "isApplied": false, + "totalItems": 1, + "totalItemsText": "1", + "id": "de", + "name": "German" + } + ] + }, + "boolean": { + "name": "Boolean properties", + "items": [ + { + "isApplied": false, + "totalItems": 90, + "totalItemsText": "90", + "id": "f", + "name": "Does not have audio synchronized text" + } + ] + }, + "addedDates": { + "name": "Date added", + "items": [ + { + "isApplied": false, + "totalItems": 4, + "totalItemsText": "4", + "id": "days-0-90", + "name": "Last 3 months" + }, + { + "isApplied": false, + "totalItems": 7, + "totalItemsText": "7", + "id": "days-0-180", + "name": "Last 6 months" + } + ] + }, + "atosLevels": { + "name": "ATOS Level", + "items": [ + { + "isApplied": false, + "totalItems": 2, + "totalItemsText": "2", + "id": "5-6", + "name": "5.0-6.0" + }, + { + "isApplied": false, + "totalItems": 3, + "totalItemsText": "3", + "id": "6-7", + "name": "6.0-7.0" + }, + { + "isApplied": false, + "totalItems": 3, + "totalItemsText": "3", + "id": "7-8", + "name": "7.0-8.0" + } + ] + }, + "lexileScores": { + "name": "Lexile Score", + "items": [ + { + "isApplied": false, + "totalItems": 2, + "totalItemsText": "2", + "id": "600-800", + "name": "600L - 800L" + }, + { + "isApplied": false, + "totalItems": 1, + "totalItemsText": "1", + "id": "800-1000", + "name": "800L - 1000L" + } + ] + }, + "interestLevels": { + "name": "Interest Level", + "items": [ + { + "isApplied": false, + "totalItems": 8, + "totalItemsText": "8", + "id": "upper-grades", + "name": "Upper Grades" + } + ] + }, + "gradeLevels": { + "name": "Text Difficulty", + "items": [ + { + "isApplied": false, + "totalItems": 2, + "totalItemsText": "2", + "id": "grade-4", + "name": "Grade 4" + }, + { + "isApplied": false, + "totalItems": 3, + "totalItemsText": "3", + "id": "grade-5", + "name": "Grade 5" + }, + { + "isApplied": false, + "totalItems": 3, + "totalItemsText": "3", + "id": "grade-6", + "name": "Grade 6" + } + ] + }, + "awards": { + "name": "Award", + "items": [ + { + "isApplied": false, + "totalItems": 1, + "totalItemsText": "1", + "id": "161", + "name": "Libby Award Nominee" + }, + { + "isApplied": false, + "totalItems": 1, + "totalItemsText": "1", + "id": "41", + "name": "Hugo Award Nominee" + }, + { + "isApplied": false, + "totalItems": 1, + "totalItemsText": "1", + "id": "62", + "name": "Listen Up Award" + } + ] + }, + "jurisdiction": { + "name": "Jurisdiction", + "items": [] + }, + "practiceArea": { + "name": "Practice Area", + "items": [] + }, + "classification": { + "name": "Classification", + "items": [] + }, + "audiobookDuration": { + "name": "Audiobook Duration", + "items": [ + { + "isApplied": false, + "totalItems": 2, + "totalItemsText": "2", + "id": "0-1", + "name": "0.0-1.0" + }, + { + "isApplied": false, + "totalItems": 3, + "totalItemsText": "3", + "id": "1-2", + "name": "1.0-2.0" + }, + { + "isApplied": false, + "totalItems": 1, + "totalItemsText": "1", + "id": "2-3", + "name": "2.0-3.0" + } + ] + }, + "freshStart": { + "name": "Fresh Start", + "items": [ + { + "isApplied": false, + "totalItems": 34, + "totalItemsText": "34", + "id": "standalone", + "name": "Standalone" + }, + { + "isApplied": false, + "totalItems": 9, + "totalItemsText": "9", + "id": "firstinseries", + "name": "FirstInSeries" + } + ] + }, + "appliedCount": 1 + }, + "sortOptions": [ + { + "isApplied": false, + "id": "mostpopular", + "name": "Popularity" + }, + { + "isApplied": true, + "id": "relevance", + "name": "Relevance" + }, + { + "isApplied": false, + "id": "releasedate", + "name": "Release date" + }, + { + "isApplied": false, + "id": "title", + "name": "Title" + }, + { + "isApplied": false, + "id": "author", + "name": "Author" + }, + { + "isApplied": false, + "id": "default", + "name": "Publish Date" + }, + { + "isApplied": false, + "id": "audiobookdurationasc", + "name": "Audiobook Duration, Ascending" + }, + { + "isApplied": false, + "id": "audiobookdurationdsc", + "name": "Audiobook Duration, Descending" + }, + { + "isApplied": false, + "id": "random", + "name": "Randomized" + }, + { + "isApplied": false, + "id": "newlyadded", + "name": "Date added" + }, + { + "isApplied": false, + "id": "lowcirculating", + "name": "Low circulating" + }, + { + "isApplied": false, + "id": "mostpopular-site", + "name": "Popularity (library)" + } + ], + "items": [ + { + "reserveId": "22222222-2222-3333-4444-000000000021", + "subjects": [ + { + "id": "26", + "name": "Fiction" + }, + { + "id": "80", + "name": "Science Fiction" + } + ], + "bisacCodes": [ + "FIC028010", + "FIC028030" + ], + "bisac": [ + { + "code": "FIC028010", + "description": "Fiction / Science Fiction / Action & Adventure" + }, + { + "code": "FIC028030", + "description": "Fiction / Science Fiction / Space Opera" + } + ], + "levels": [], + "creators": [ + { + "id": 21, + "name": "Frank Herbert", + "role": "Author", + "sortName": "Frank Herbert" + } + ], + "languages": [ + { + "id": "en", + "name": "English" + } + ], + "isBundledChild": false, + "ratings": { + "maturityLevel": { + "id": "generalcontent", + "name": "General content" + }, + "naughtyScore": { + "id": "GeneralContent", + "name": "General content" + } + }, + "constraints": { + "isDisneyEulaRequired": false + }, + "reviewCounts": { + "premium": 5, + "publisherSupplier": 0 + }, + "isAvailable": false, + "isPreReleaseTitle": false, + "estimatedReleaseDate": "2007-05-29T04:00:00Z", + "sample": { + "href": "https://samples.overdrive.com/?crid=d91b7033-fad9-49ce-a468-bb3b950fd5d5&.epub-sample.overdrive.com" + }, + "publisher": { + "id": "2166", + "name": "Macmillan Audio" + }, + "description": "

NOW A MAJOR MOTION PICTURE directed by Denis Villeneuve, starring Timothée Chalamet, Zendaya, Rebecca Ferguson, Javier Bardem, Josh Brolin, Austin Butler, Florence Pugh, Dave Bautista, Christoph…", + "availableCopies": 1, + "ownedCopies": 10, + "luckyDayAvailableCopies": 0, + "luckyDayOwnedCopies": 0, + "holdsCount": 1, + "holdsRatio": 0, + "estimatedWaitDays": 2, + "isFastlane": false, + "availabilityType": "normal", + "isRecommendableToLibrary": true, + "isOwned": true, + "isHoldable": true, + "isAdvantageFiltered": false, + "isRestricted": false, + "visitorEligible": false, + "juvenileEligible": false, + "youngAdultEligible": false, + "contentAccessLevels": 0, + "classifications": {}, + "type": { + "id": "ebook", + "name": "eBook" + }, + "covers": { + "cover150Wide": { + "href": "https://img1.od-cdn.com/ImageType-150/1493-1/{BBBBBBBB-0000-0000-0000-000000000021}Img.jpg", + "height": 200, + "width": 150, + "primaryColor": { + "hex": "#4C282A", + "rgb": { + "red": 76, + "green": 40, + "blue": 42 + } + }, + "isPlaceholderImage": false + }, + "cover300Wide": { + "href": "https://img1.od-cdn.com/ImageType-400/1493-1/{BBBBBBBB-0000-0000-0000-000000000021}Img.jpg", + "height": 400, + "width": 300, + "primaryColor": { + "hex": "#4C282C", + "rgb": { + "red": 76, + "green": 40, + "blue": 44 + } + }, + "isPlaceholderImage": false + }, + "cover510Wide": { + "href": "https://img2.od-cdn.com/ImageType-100/1493-1/{BBBBBBBB-0000-0000-0000-000000000021}Img.jpg", + "height": 680, + "width": 510, + "primaryColor": { + "hex": "#4C282C", + "rgb": { + "red": 76, + "green": 40, + "blue": 44 + } + }, + "isPlaceholderImage": false + } + }, + "id": "3000021", + "firstCreatorName": "Frank Herbert", + "firstCreatorId": 393911, + "firstCreatorSortName": "Frank Herbert", + "title": "Dune Chronicle 1", + "sortTitle": "Dune Chronicle 1", + "starRating": 4.2, + "starRatingCount": 3193, + "edition": "Unabridged", + "publishDate": "2007-05-29T00:00:00Z", + "publishDateText": "05/29/2007", + "dateContentReceivedUTC": "2015-07-29T04:00:00Z", + "formats": [ + { + "identifiers": [ + { + "type": "ISBN", + "value": "9780000000001" + } + ], + "rights": [], + "fileSize": 1543210, + "id": "ebook-overdrive", + "name": "OverDrive Read", + "fulfillmentType": "bifocal" + }, + { + "identifiers": [], + "rights": [], + "fileSize": 1543210, + "id": "ebook-epub-adobe", + "name": "EPUB eBook", + "fulfillmentType": "epub" + }, + { + "identifiers": [], + "rights": [], + "id": "ebook-kindle", + "name": "Kindle Book", + "fulfillmentType": "kindle" + } + ], + "publisherAccount": { + "accessId": 1493, + "id": "3606", + "name": "Macmillan Audio" + } + }, + { + "reserveId": "22222222-2222-3333-4444-000000000022", + "subjects": [ + { + "id": "26", + "name": "Fiction" + }, + { + "id": "80", + "name": "Science Fiction" + } + ], + "bisacCodes": [ + "FIC028010", + "FIC028030" + ], + "bisac": [ + { + "code": "FIC028010", + "description": "Fiction / Science Fiction / Action & Adventure" + }, + { + "code": "FIC028030", + "description": "Fiction / Science Fiction / Space Opera" + } + ], + "levels": [], + "creators": [ + { + "id": 22, + "name": "Frank Herbert", + "role": "Author", + "sortName": "Frank Herbert" + } + ], + "languages": [ + { + "id": "en", + "name": "English" + } + ], + "isBundledChild": false, + "ratings": { + "maturityLevel": { + "id": "generalcontent", + "name": "General content" + }, + "naughtyScore": { + "id": "GeneralContent", + "name": "General content" + } + }, + "constraints": { + "isDisneyEulaRequired": false + }, + "reviewCounts": { + "premium": 5, + "publisherSupplier": 0 + }, + "isAvailable": true, + "isPreReleaseTitle": false, + "estimatedReleaseDate": "2007-05-29T04:00:00Z", + "sample": { + "href": "https://samples.overdrive.com/?crid=d91b7033-fad9-49ce-a468-bb3b950fd5d5&.epub-sample.overdrive.com" + }, + "publisher": { + "id": "2166", + "name": "Macmillan Audio" + }, + "description": "

NOW A MAJOR MOTION PICTURE directed by Denis Villeneuve, starring Timothée Chalamet, Zendaya, Rebecca Ferguson, Javier Bardem, Josh Brolin, Austin Butler, Florence Pugh, Dave Bautista, Christoph…", + "availableCopies": 2, + "ownedCopies": 10, + "luckyDayAvailableCopies": 0, + "luckyDayOwnedCopies": 0, + "holdsCount": 2, + "holdsRatio": 0, + "estimatedWaitDays": 4, + "isFastlane": false, + "availabilityType": "normal", + "isRecommendableToLibrary": true, + "isOwned": true, + "isHoldable": true, + "isAdvantageFiltered": false, + "isRestricted": false, + "visitorEligible": false, + "juvenileEligible": false, + "youngAdultEligible": false, + "contentAccessLevels": 0, + "classifications": {}, + "type": { + "id": "ebook", + "name": "eBook" + }, + "covers": { + "cover150Wide": { + "href": "https://img1.od-cdn.com/ImageType-150/1493-1/{BBBBBBBB-0000-0000-0000-000000000022}Img.jpg", + "height": 200, + "width": 150, + "primaryColor": { + "hex": "#4C282A", + "rgb": { + "red": 76, + "green": 40, + "blue": 42 + } + }, + "isPlaceholderImage": false + }, + "cover300Wide": { + "href": "https://img1.od-cdn.com/ImageType-400/1493-1/{BBBBBBBB-0000-0000-0000-000000000022}Img.jpg", + "height": 400, + "width": 300, + "primaryColor": { + "hex": "#4C282C", + "rgb": { + "red": 76, + "green": 40, + "blue": 44 + } + }, + "isPlaceholderImage": false + }, + "cover510Wide": { + "href": "https://img2.od-cdn.com/ImageType-100/1493-1/{BBBBBBBB-0000-0000-0000-000000000022}Img.jpg", + "height": 680, + "width": 510, + "primaryColor": { + "hex": "#4C282C", + "rgb": { + "red": 76, + "green": 40, + "blue": 44 + } + }, + "isPlaceholderImage": false + } + }, + "id": "3000022", + "firstCreatorName": "Frank Herbert", + "firstCreatorId": 393911, + "firstCreatorSortName": "Frank Herbert", + "title": "Dune Chronicle 2", + "sortTitle": "Dune Chronicle 2", + "starRating": 4.2, + "starRatingCount": 3193, + "edition": "Unabridged", + "publishDate": "2007-05-29T00:00:00Z", + "publishDateText": "05/29/2007", + "dateContentReceivedUTC": "2015-07-29T04:00:00Z", + "formats": [ + { + "identifiers": [ + { + "type": "ISBN", + "value": "9780000000001" + } + ], + "rights": [], + "fileSize": 1543210, + "id": "ebook-overdrive", + "name": "OverDrive Read", + "fulfillmentType": "bifocal" + }, + { + "identifiers": [], + "rights": [], + "fileSize": 1543210, + "id": "ebook-epub-adobe", + "name": "EPUB eBook", + "fulfillmentType": "epub" + }, + { + "identifiers": [], + "rights": [], + "id": "ebook-kindle", + "name": "Kindle Book", + "fulfillmentType": "kindle" + } + ], + "publisherAccount": { + "accessId": 1493, + "id": "3606", + "name": "Macmillan Audio" + } + }, + { + "reserveId": "22222222-2222-3333-4444-000000000023", + "subjects": [ + { + "id": "26", + "name": "Fiction" + }, + { + "id": "80", + "name": "Science Fiction" + } + ], + "bisacCodes": [ + "FIC028010", + "FIC028030" + ], + "bisac": [ + { + "code": "FIC028010", + "description": "Fiction / Science Fiction / Action & Adventure" + }, + { + "code": "FIC028030", + "description": "Fiction / Science Fiction / Space Opera" + } + ], + "levels": [], + "creators": [ + { + "id": 23, + "name": "Frank Herbert", + "role": "Author", + "sortName": "Frank Herbert" + } + ], + "languages": [ + { + "id": "en", + "name": "English" + } + ], + "isBundledChild": false, + "ratings": { + "maturityLevel": { + "id": "generalcontent", + "name": "General content" + }, + "naughtyScore": { + "id": "GeneralContent", + "name": "General content" + } + }, + "constraints": { + "isDisneyEulaRequired": false + }, + "reviewCounts": { + "premium": 5, + "publisherSupplier": 0 + }, + "isAvailable": false, + "isPreReleaseTitle": false, + "estimatedReleaseDate": "2007-05-29T04:00:00Z", + "sample": { + "href": "https://samples.overdrive.com/?crid=d91b7033-fad9-49ce-a468-bb3b950fd5d5&.epub-sample.overdrive.com" + }, + "publisher": { + "id": "2166", + "name": "Macmillan Audio" + }, + "description": "

NOW A MAJOR MOTION PICTURE directed by Denis Villeneuve, starring Timothée Chalamet, Zendaya, Rebecca Ferguson, Javier Bardem, Josh Brolin, Austin Butler, Florence Pugh, Dave Bautista, Christoph…", + "availableCopies": 0, + "ownedCopies": 10, + "luckyDayAvailableCopies": 0, + "luckyDayOwnedCopies": 0, + "holdsCount": 3, + "holdsRatio": 0, + "estimatedWaitDays": 6, + "isFastlane": false, + "availabilityType": "normal", + "isRecommendableToLibrary": true, + "isOwned": true, + "isHoldable": true, + "isAdvantageFiltered": false, + "isRestricted": false, + "visitorEligible": false, + "juvenileEligible": false, + "youngAdultEligible": false, + "contentAccessLevels": 0, + "classifications": {}, + "type": { + "id": "ebook", + "name": "eBook" + }, + "covers": { + "cover150Wide": { + "href": "https://img1.od-cdn.com/ImageType-150/1493-1/{BBBBBBBB-0000-0000-0000-000000000023}Img.jpg", + "height": 200, + "width": 150, + "primaryColor": { + "hex": "#4C282A", + "rgb": { + "red": 76, + "green": 40, + "blue": 42 + } + }, + "isPlaceholderImage": false + }, + "cover300Wide": { + "href": "https://img1.od-cdn.com/ImageType-400/1493-1/{BBBBBBBB-0000-0000-0000-000000000023}Img.jpg", + "height": 400, + "width": 300, + "primaryColor": { + "hex": "#4C282C", + "rgb": { + "red": 76, + "green": 40, + "blue": 44 + } + }, + "isPlaceholderImage": false + }, + "cover510Wide": { + "href": "https://img2.od-cdn.com/ImageType-100/1493-1/{BBBBBBBB-0000-0000-0000-000000000023}Img.jpg", + "height": 680, + "width": 510, + "primaryColor": { + "hex": "#4C282C", + "rgb": { + "red": 76, + "green": 40, + "blue": 44 + } + }, + "isPlaceholderImage": false + } + }, + "id": "3000023", + "firstCreatorName": "Frank Herbert", + "firstCreatorId": 393911, + "firstCreatorSortName": "Frank Herbert", + "title": "Dune Chronicle 3", + "sortTitle": "Dune Chronicle 3", + "starRating": 4.2, + "starRatingCount": 3193, + "edition": "Unabridged", + "publishDate": "2007-05-29T00:00:00Z", + "publishDateText": "05/29/2007", + "dateContentReceivedUTC": "2015-07-29T04:00:00Z", + "formats": [ + { + "identifiers": [ + { + "type": "ISBN", + "value": "9780000000001" + } + ], + "rights": [], + "fileSize": 1543210, + "id": "ebook-overdrive", + "name": "OverDrive Read", + "fulfillmentType": "bifocal" + }, + { + "identifiers": [], + "rights": [], + "fileSize": 1543210, + "id": "ebook-epub-adobe", + "name": "EPUB eBook", + "fulfillmentType": "epub" + }, + { + "identifiers": [], + "rights": [], + "id": "ebook-kindle", + "name": "Kindle Book", + "fulfillmentType": "kindle" + } + ], + "publisherAccount": { + "accessId": 1493, + "id": "3606", + "name": "Macmillan Audio" + } + }, + { + "reserveId": "22222222-2222-3333-4444-000000000024", + "subjects": [ + { + "id": "26", + "name": "Fiction" + }, + { + "id": "80", + "name": "Science Fiction" + } + ], + "bisacCodes": [ + "FIC028010", + "FIC028030" + ], + "bisac": [ + { + "code": "FIC028010", + "description": "Fiction / Science Fiction / Action & Adventure" + }, + { + "code": "FIC028030", + "description": "Fiction / Science Fiction / Space Opera" + } + ], + "levels": [], + "creators": [ + { + "id": 24, + "name": "Frank Herbert", + "role": "Author", + "sortName": "Frank Herbert" + } + ], + "languages": [ + { + "id": "en", + "name": "English" + } + ], + "isBundledChild": false, + "ratings": { + "maturityLevel": { + "id": "generalcontent", + "name": "General content" + }, + "naughtyScore": { + "id": "GeneralContent", + "name": "General content" + } + }, + "constraints": { + "isDisneyEulaRequired": false + }, + "reviewCounts": { + "premium": 5, + "publisherSupplier": 0 + }, + "isAvailable": true, + "isPreReleaseTitle": false, + "estimatedReleaseDate": "2007-05-29T04:00:00Z", + "sample": { + "href": "https://samples.overdrive.com/?crid=d91b7033-fad9-49ce-a468-bb3b950fd5d5&.epub-sample.overdrive.com" + }, + "publisher": { + "id": "2166", + "name": "Macmillan Audio" + }, + "description": "

NOW A MAJOR MOTION PICTURE directed by Denis Villeneuve, starring Timothée Chalamet, Zendaya, Rebecca Ferguson, Javier Bardem, Josh Brolin, Austin Butler, Florence Pugh, Dave Bautista, Christoph…", + "availableCopies": 1, + "ownedCopies": 10, + "luckyDayAvailableCopies": 0, + "luckyDayOwnedCopies": 0, + "holdsCount": 4, + "holdsRatio": 0, + "estimatedWaitDays": 8, + "isFastlane": false, + "availabilityType": "normal", + "isRecommendableToLibrary": true, + "isOwned": true, + "isHoldable": true, + "isAdvantageFiltered": false, + "isRestricted": false, + "visitorEligible": false, + "juvenileEligible": false, + "youngAdultEligible": false, + "contentAccessLevels": 0, + "classifications": {}, + "type": { + "id": "ebook", + "name": "eBook" + }, + "covers": { + "cover150Wide": { + "href": "https://img1.od-cdn.com/ImageType-150/1493-1/{BBBBBBBB-0000-0000-0000-000000000024}Img.jpg", + "height": 200, + "width": 150, + "primaryColor": { + "hex": "#4C282A", + "rgb": { + "red": 76, + "green": 40, + "blue": 42 + } + }, + "isPlaceholderImage": false + }, + "cover300Wide": { + "href": "https://img1.od-cdn.com/ImageType-400/1493-1/{BBBBBBBB-0000-0000-0000-000000000024}Img.jpg", + "height": 400, + "width": 300, + "primaryColor": { + "hex": "#4C282C", + "rgb": { + "red": 76, + "green": 40, + "blue": 44 + } + }, + "isPlaceholderImage": false + }, + "cover510Wide": { + "href": "https://img2.od-cdn.com/ImageType-100/1493-1/{BBBBBBBB-0000-0000-0000-000000000024}Img.jpg", + "height": 680, + "width": 510, + "primaryColor": { + "hex": "#4C282C", + "rgb": { + "red": 76, + "green": 40, + "blue": 44 + } + }, + "isPlaceholderImage": false + } + }, + "id": "3000024", + "firstCreatorName": "Frank Herbert", + "firstCreatorId": 393911, + "firstCreatorSortName": "Frank Herbert", + "title": "Dune Chronicle 4", + "sortTitle": "Dune Chronicle 4", + "starRating": 4.2, + "starRatingCount": 3193, + "edition": "Unabridged", + "publishDate": "2007-05-29T00:00:00Z", + "publishDateText": "05/29/2007", + "dateContentReceivedUTC": "2015-07-29T04:00:00Z", + "formats": [ + { + "identifiers": [ + { + "type": "ISBN", + "value": "9780000000001" + } + ], + "rights": [], + "fileSize": 1543210, + "id": "ebook-overdrive", + "name": "OverDrive Read", + "fulfillmentType": "bifocal" + }, + { + "identifiers": [], + "rights": [], + "fileSize": 1543210, + "id": "ebook-epub-adobe", + "name": "EPUB eBook", + "fulfillmentType": "epub" + }, + { + "identifiers": [], + "rights": [], + "id": "ebook-kindle", + "name": "Kindle Book", + "fulfillmentType": "kindle" + } + ], + "publisherAccount": { + "accessId": 1493, + "id": "3606", + "name": "Macmillan Audio" + } + } + ], + "totalItems": 90, + "totalItemsText": "90", + "links": { + "self": { + "page": 2, + "pageText": "2" + }, + "first": { + "page": 1, + "pageText": "1" + }, + "last": { + "page": 45, + "pageText": "45" + }, + "prev": { + "page": 1, + "pageText": "1" + }, + "next": { + "page": 3, + "pageText": "3" + } + } +} \ No newline at end of file diff --git a/crates/libbui/src/testing/fixtures/search.json b/crates/libbui/src/testing/fixtures/search.json new file mode 100644 index 0000000..23aaa77 --- /dev/null +++ b/crates/libbui/src/testing/fixtures/search.json @@ -0,0 +1,1966 @@ +{ + "queryKeys": {}, + "facets": { + "availability": { + "name": "Availability", + "items": [ + { + "isApplied": true, + "totalItems": 90, + "totalItemsText": "90", + "id": "all-titles", + "name": "All titles" + }, + { + "isApplied": false, + "totalItemsText": "", + "id": "available-now", + "name": "Available now" + } + ] + }, + "mediaTypes": { + "name": "Media type", + "items": [ + { + "isApplied": true, + "totalItems": 90, + "totalItemsText": "90", + "id": "audiobook", + "name": "Audiobook" + } + ] + }, + "formats": { + "name": "Format", + "items": [ + { + "isApplied": false, + "totalItems": 90, + "totalItemsText": "90", + "id": "audiobook-overdrive", + "name": "OverDrive Listen audiobook" + }, + { + "isApplied": false, + "totalItems": 90, + "totalItemsText": "90", + "id": "audiobook-mp3", + "name": "MP3 audiobook" + } + ] + }, + "maturityLevels": { + "name": "Audience", + "items": [ + { + "isApplied": false, + "totalItems": 88, + "totalItemsText": "88", + "id": "generalcontent", + "name": "General adult" + }, + { + "isApplied": false, + "totalItems": 2, + "totalItemsText": "2", + "id": "juvenile", + "name": "Juvenile" + } + ] + }, + "subjects": { + "name": "Subject", + "items": [ + { + "isApplied": false, + "totalItems": 74, + "totalItemsText": "74", + "id": "26", + "name": "Fiction" + }, + { + "isApplied": false, + "totalItems": 54, + "totalItemsText": "54", + "id": "80", + "name": "Science Fiction" + }, + { + "isApplied": false, + "totalItems": 16, + "totalItemsText": "16", + "id": "49", + "name": "Literature" + } + ] + }, + "bisacCodes": { + "name": "Bisac code", + "items": [ + { + "isApplied": false, + "totalItems": 38, + "totalItemsText": "38", + "id": "FIC028030", + "name": "Fiction / Science Fiction / Space Opera" + }, + { + "isApplied": false, + "totalItems": 26, + "totalItemsText": "26", + "id": "FIC028010", + "name": "Fiction / Science Fiction / Action & Adventure" + }, + { + "isApplied": false, + "totalItems": 14, + "totalItemsText": "14", + "id": "FIC028000", + "name": "Fiction / Science Fiction / General" + } + ] + }, + "languages": { + "name": "Language", + "items": [ + { + "isApplied": false, + "totalItems": 66, + "totalItemsText": "66", + "id": "en", + "name": "English" + }, + { + "isApplied": false, + "totalItems": 23, + "totalItemsText": "23", + "id": "es", + "name": "Spanish; Castilian" + }, + { + "isApplied": false, + "totalItems": 1, + "totalItemsText": "1", + "id": "de", + "name": "German" + } + ] + }, + "boolean": { + "name": "Boolean properties", + "items": [ + { + "isApplied": false, + "totalItems": 90, + "totalItemsText": "90", + "id": "f", + "name": "Does not have audio synchronized text" + } + ] + }, + "addedDates": { + "name": "Date added", + "items": [ + { + "isApplied": false, + "totalItems": 4, + "totalItemsText": "4", + "id": "days-0-90", + "name": "Last 3 months" + }, + { + "isApplied": false, + "totalItems": 7, + "totalItemsText": "7", + "id": "days-0-180", + "name": "Last 6 months" + } + ] + }, + "atosLevels": { + "name": "ATOS Level", + "items": [ + { + "isApplied": false, + "totalItems": 2, + "totalItemsText": "2", + "id": "5-6", + "name": "5.0-6.0" + }, + { + "isApplied": false, + "totalItems": 3, + "totalItemsText": "3", + "id": "6-7", + "name": "6.0-7.0" + }, + { + "isApplied": false, + "totalItems": 3, + "totalItemsText": "3", + "id": "7-8", + "name": "7.0-8.0" + } + ] + }, + "lexileScores": { + "name": "Lexile Score", + "items": [ + { + "isApplied": false, + "totalItems": 2, + "totalItemsText": "2", + "id": "600-800", + "name": "600L - 800L" + }, + { + "isApplied": false, + "totalItems": 1, + "totalItemsText": "1", + "id": "800-1000", + "name": "800L - 1000L" + } + ] + }, + "interestLevels": { + "name": "Interest Level", + "items": [ + { + "isApplied": false, + "totalItems": 8, + "totalItemsText": "8", + "id": "upper-grades", + "name": "Upper Grades" + } + ] + }, + "gradeLevels": { + "name": "Text Difficulty", + "items": [ + { + "isApplied": false, + "totalItems": 2, + "totalItemsText": "2", + "id": "grade-4", + "name": "Grade 4" + }, + { + "isApplied": false, + "totalItems": 3, + "totalItemsText": "3", + "id": "grade-5", + "name": "Grade 5" + }, + { + "isApplied": false, + "totalItems": 3, + "totalItemsText": "3", + "id": "grade-6", + "name": "Grade 6" + } + ] + }, + "awards": { + "name": "Award", + "items": [ + { + "isApplied": false, + "totalItems": 1, + "totalItemsText": "1", + "id": "161", + "name": "Libby Award Nominee" + }, + { + "isApplied": false, + "totalItems": 1, + "totalItemsText": "1", + "id": "41", + "name": "Hugo Award Nominee" + }, + { + "isApplied": false, + "totalItems": 1, + "totalItemsText": "1", + "id": "62", + "name": "Listen Up Award" + } + ] + }, + "jurisdiction": { + "name": "Jurisdiction", + "items": [] + }, + "practiceArea": { + "name": "Practice Area", + "items": [] + }, + "classification": { + "name": "Classification", + "items": [] + }, + "audiobookDuration": { + "name": "Audiobook Duration", + "items": [ + { + "isApplied": false, + "totalItems": 2, + "totalItemsText": "2", + "id": "0-1", + "name": "0.0-1.0" + }, + { + "isApplied": false, + "totalItems": 3, + "totalItemsText": "3", + "id": "1-2", + "name": "1.0-2.0" + }, + { + "isApplied": false, + "totalItems": 1, + "totalItemsText": "1", + "id": "2-3", + "name": "2.0-3.0" + } + ] + }, + "freshStart": { + "name": "Fresh Start", + "items": [ + { + "isApplied": false, + "totalItems": 34, + "totalItemsText": "34", + "id": "standalone", + "name": "Standalone" + }, + { + "isApplied": false, + "totalItems": 9, + "totalItemsText": "9", + "id": "firstinseries", + "name": "FirstInSeries" + } + ] + }, + "appliedCount": 1 + }, + "sortOptions": [ + { + "isApplied": false, + "id": "mostpopular", + "name": "Popularity" + }, + { + "isApplied": true, + "id": "relevance", + "name": "Relevance" + }, + { + "isApplied": false, + "id": "releasedate", + "name": "Release date" + }, + { + "isApplied": false, + "id": "title", + "name": "Title" + }, + { + "isApplied": false, + "id": "author", + "name": "Author" + }, + { + "isApplied": false, + "id": "default", + "name": "Publish Date" + }, + { + "isApplied": false, + "id": "audiobookdurationasc", + "name": "Audiobook Duration, Ascending" + }, + { + "isApplied": false, + "id": "audiobookdurationdsc", + "name": "Audiobook Duration, Descending" + }, + { + "isApplied": false, + "id": "random", + "name": "Randomized" + }, + { + "isApplied": false, + "id": "newlyadded", + "name": "Date added" + }, + { + "isApplied": false, + "id": "lowcirculating", + "name": "Low circulating" + }, + { + "isApplied": false, + "id": "mostpopular-site", + "name": "Popularity (library)" + } + ], + "items": [ + { + "reserveId": "22222222-2222-3333-4444-000000000001", + "subjects": [ + { + "id": "26", + "name": "Fiction" + }, + { + "id": "80", + "name": "Science Fiction" + } + ], + "bisacCodes": [ + "FIC028010", + "FIC028030" + ], + "bisac": [ + { + "code": "FIC028010", + "description": "Fiction / Science Fiction / Action & Adventure" + }, + { + "code": "FIC028030", + "description": "Fiction / Science Fiction / Space Opera" + } + ], + "levels": [], + "creators": [ + { + "id": 1, + "name": "Frank Herbert", + "role": "Author", + "sortName": "Frank Herbert" + }, + { + "id": 901, + "name": "Ray Porter", + "role": "Narrator", + "sortName": "Porter, Ray" + } + ], + "languages": [ + { + "id": "en", + "name": "English" + } + ], + "isBundledChild": false, + "ratings": { + "maturityLevel": { + "id": "generalcontent", + "name": "General content" + }, + "naughtyScore": { + "id": "GeneralContent", + "name": "General content" + } + }, + "constraints": { + "isDisneyEulaRequired": false + }, + "reviewCounts": { + "premium": 5, + "publisherSupplier": 0 + }, + "isAvailable": true, + "isPreReleaseTitle": false, + "estimatedReleaseDate": "2007-05-29T04:00:00Z", + "sample": { + "href": "https://samples.overdrive.com/?crid=d91b7033-fad9-49ce-a468-bb3b950fd5d5&.epub-sample.overdrive.com" + }, + "publisher": { + "id": "2166", + "name": "Macmillan Audio" + }, + "description": "

Set on the desert planet Arrakis, Dune is the story of the boy Paul Atreides, heir to a noble family tasked with ruling an inhospitable world where the only thing of value is the “spice” melange.

A stunning blend of adventure and mysticism, environmentalism and politics.

", + "availableCopies": 1, + "ownedCopies": 268, + "luckyDayAvailableCopies": 0, + "luckyDayOwnedCopies": 0, + "holdsCount": 4, + "holdsRatio": 0, + "estimatedWaitDays": 1, + "isFastlane": false, + "availabilityType": "normal", + "isRecommendableToLibrary": true, + "isOwned": true, + "isHoldable": true, + "isAdvantageFiltered": false, + "isRestricted": false, + "visitorEligible": false, + "juvenileEligible": false, + "youngAdultEligible": false, + "contentAccessLevels": 0, + "classifications": {}, + "type": { + "id": "audiobook", + "name": "Audiobook" + }, + "covers": { + "cover150Wide": { + "href": "https://img1.od-cdn.com/ImageType-150/1493-1/{BBBBBBBB-0000-0000-0000-000000000001}Img.jpg", + "height": 200, + "width": 150, + "primaryColor": { + "hex": "#4C282A", + "rgb": { + "red": 76, + "green": 40, + "blue": 42 + } + }, + "isPlaceholderImage": false + }, + "cover300Wide": { + "href": "https://img1.od-cdn.com/ImageType-400/1493-1/{BBBBBBBB-0000-0000-0000-000000000001}Img.jpg", + "height": 400, + "width": 300, + "primaryColor": { + "hex": "#4C282C", + "rgb": { + "red": 76, + "green": 40, + "blue": 44 + } + }, + "isPlaceholderImage": false + }, + "cover510Wide": { + "href": "https://img2.od-cdn.com/ImageType-100/1493-1/{BBBBBBBB-0000-0000-0000-000000000001}Img.jpg", + "height": 680, + "width": 510, + "primaryColor": { + "hex": "#4C282C", + "rgb": { + "red": 76, + "green": 40, + "blue": 44 + } + }, + "isPlaceholderImage": false + } + }, + "id": "3000001", + "firstCreatorName": "Frank Herbert", + "firstCreatorId": 393911, + "firstCreatorSortName": "Frank Herbert", + "title": "Dune", + "sortTitle": "Dune", + "starRating": 4.2, + "starRatingCount": 3193, + "edition": "Unabridged", + "publishDate": "2007-05-29T00:00:00Z", + "publishDateText": "05/29/2007", + "dateContentReceivedUTC": "2015-07-29T04:00:00Z", + "formats": [ + { + "identifiers": [ + { + "type": "ISBN", + "value": "9781427201447" + } + ], + "rights": [], + "fileSize": 605814901, + "onSaleDateUtc": "2007-05-29T04:00:00+00:00", + "duration": "21:02:06", + "hasAudioSynchronizedText": false, + "isBundleParent": false, + "isbn": "9781427201447", + "bundledContent": [], + "sample": { + "href": "https://samples.overdrive.com/?crid=d91b7033-fad9-49ce-a468-bb3b950fd5d5&.epub-sample.overdrive.com" + }, + "fulfillmentType": "bifocal", + "id": "audiobook-overdrive", + "name": "OverDrive Listen audiobook" + }, + { + "identifiers": [ + { + "type": "ISBN", + "value": "9781427201447" + } + ], + "rights": [], + "fileSize": 605867780, + "onSaleDateUtc": "2007-05-29T04:00:00+00:00", + "partCount": 18, + "duration": "21:12:05", + "hasAudioSynchronizedText": false, + "isBundleParent": false, + "isbn": "9781427201447", + "bundledContent": [], + "sample": { + "href": "https://excerpts.cdn.overdrive.com/FormatType-425/1493-1/2308988-Dune.mp3" + }, + "fulfillmentType": "odm", + "id": "audiobook-mp3", + "name": "MP3 audiobook" + } + ], + "publisherAccount": { + "accessId": 1493, + "id": "3606", + "name": "Macmillan Audio" + }, + "series": "Dune", + "detailedSeries": { + "seriesId": 1, + "seriesName": "Dune", + "readingOrder": "1", + "rank": 1 + } + }, + { + "reserveId": "22222222-2222-3333-4444-000000000002", + "subjects": [ + { + "id": "26", + "name": "Fiction" + }, + { + "id": "80", + "name": "Science Fiction" + } + ], + "bisacCodes": [ + "FIC028010", + "FIC028030" + ], + "bisac": [ + { + "code": "FIC028010", + "description": "Fiction / Science Fiction / Action & Adventure" + }, + { + "code": "FIC028030", + "description": "Fiction / Science Fiction / Space Opera" + } + ], + "levels": [], + "creators": [ + { + "id": 2, + "name": "Frank Herbert", + "role": "Author", + "sortName": "Frank Herbert" + } + ], + "languages": [ + { + "id": "en", + "name": "English" + } + ], + "isBundledChild": false, + "ratings": { + "maturityLevel": { + "id": "generalcontent", + "name": "General content" + }, + "naughtyScore": { + "id": "GeneralContent", + "name": "General content" + } + }, + "constraints": { + "isDisneyEulaRequired": false + }, + "reviewCounts": { + "premium": 5, + "publisherSupplier": 0 + }, + "isAvailable": false, + "isPreReleaseTitle": false, + "estimatedReleaseDate": "2007-05-29T04:00:00Z", + "sample": { + "href": "https://samples.overdrive.com/?crid=d91b7033-fad9-49ce-a468-bb3b950fd5d5&.epub-sample.overdrive.com" + }, + "publisher": { + "id": "2166", + "name": "Macmillan Audio" + }, + "description": "

NOW A MAJOR MOTION PICTURE directed by Denis Villeneuve, starring Timothée Chalamet, Zendaya, Rebecca Ferguson, Javier Bardem, Josh Brolin, Austin Butler, Florence Pugh, Dave Bautista, Christoph…", + "availableCopies": 0, + "ownedCopies": 120, + "luckyDayAvailableCopies": 0, + "luckyDayOwnedCopies": 0, + "holdsCount": 310, + "holdsRatio": 2, + "estimatedWaitDays": 42, + "isFastlane": false, + "availabilityType": "normal", + "isRecommendableToLibrary": true, + "isOwned": true, + "isHoldable": true, + "isAdvantageFiltered": false, + "isRestricted": false, + "visitorEligible": false, + "juvenileEligible": false, + "youngAdultEligible": false, + "contentAccessLevels": 0, + "classifications": {}, + "type": { + "id": "ebook", + "name": "eBook" + }, + "covers": { + "cover150Wide": { + "href": "https://img1.od-cdn.com/ImageType-150/1493-1/{BBBBBBBB-0000-0000-0000-000000000002}Img.jpg", + "height": 200, + "width": 150, + "primaryColor": { + "hex": "#4C282A", + "rgb": { + "red": 76, + "green": 40, + "blue": 42 + } + }, + "isPlaceholderImage": false + }, + "cover300Wide": { + "href": "https://img1.od-cdn.com/ImageType-400/1493-1/{BBBBBBBB-0000-0000-0000-000000000002}Img.jpg", + "height": 400, + "width": 300, + "primaryColor": { + "hex": "#4C282C", + "rgb": { + "red": 76, + "green": 40, + "blue": 44 + } + }, + "isPlaceholderImage": false + }, + "cover510Wide": { + "href": "https://img2.od-cdn.com/ImageType-100/1493-1/{BBBBBBBB-0000-0000-0000-000000000002}Img.jpg", + "height": 680, + "width": 510, + "primaryColor": { + "hex": "#4C282C", + "rgb": { + "red": 76, + "green": 40, + "blue": 44 + } + }, + "isPlaceholderImage": false + } + }, + "id": "3000002", + "firstCreatorName": "Frank Herbert", + "firstCreatorId": 393911, + "firstCreatorSortName": "Frank Herbert", + "title": "Dune", + "sortTitle": "Dune", + "starRating": 4.2, + "starRatingCount": 3193, + "edition": "Unabridged", + "publishDate": "2007-05-29T00:00:00Z", + "publishDateText": "05/29/2007", + "dateContentReceivedUTC": "2015-07-29T04:00:00Z", + "formats": [ + { + "identifiers": [ + { + "type": "ISBN", + "value": "9780000000001" + } + ], + "rights": [], + "fileSize": 1543210, + "id": "ebook-overdrive", + "name": "OverDrive Read", + "fulfillmentType": "bifocal" + }, + { + "identifiers": [], + "rights": [], + "fileSize": 1543210, + "id": "ebook-epub-adobe", + "name": "EPUB eBook", + "fulfillmentType": "epub" + }, + { + "identifiers": [], + "rights": [], + "id": "ebook-kindle", + "name": "Kindle Book", + "fulfillmentType": "kindle" + } + ], + "publisherAccount": { + "accessId": 1493, + "id": "3606", + "name": "Macmillan Audio" + }, + "series": "Dune", + "detailedSeries": { + "seriesId": 2, + "seriesName": "Dune", + "readingOrder": "1", + "rank": 1 + } + }, + { + "reserveId": "22222222-2222-3333-4444-000000000003", + "subjects": [ + { + "id": "26", + "name": "Fiction" + }, + { + "id": "80", + "name": "Science Fiction" + } + ], + "bisacCodes": [ + "FIC028010", + "FIC028030" + ], + "bisac": [ + { + "code": "FIC028010", + "description": "Fiction / Science Fiction / Action & Adventure" + }, + { + "code": "FIC028030", + "description": "Fiction / Science Fiction / Space Opera" + } + ], + "levels": [], + "creators": [ + { + "id": 3, + "name": "Frank Herbert", + "role": "Author", + "sortName": "Frank Herbert" + } + ], + "languages": [ + { + "id": "en", + "name": "English" + } + ], + "isBundledChild": false, + "ratings": { + "maturityLevel": { + "id": "generalcontent", + "name": "General content" + }, + "naughtyScore": { + "id": "GeneralContent", + "name": "General content" + } + }, + "constraints": { + "isDisneyEulaRequired": false + }, + "reviewCounts": { + "premium": 5, + "publisherSupplier": 0 + }, + "isAvailable": true, + "isPreReleaseTitle": false, + "estimatedReleaseDate": "2007-05-29T04:00:00Z", + "sample": { + "href": "https://samples.overdrive.com/?crid=d91b7033-fad9-49ce-a468-bb3b950fd5d5&.epub-sample.overdrive.com" + }, + "publisher": { + "id": "2166", + "name": "Macmillan Audio" + }, + "description": "

NOW A MAJOR MOTION PICTURE directed by Denis Villeneuve, starring Timothée Chalamet, Zendaya, Rebecca Ferguson, Javier Bardem, Josh Brolin, Austin Butler, Florence Pugh, Dave Bautista, Christoph…", + "availableCopies": 3, + "ownedCopies": 40, + "luckyDayAvailableCopies": 0, + "luckyDayOwnedCopies": 0, + "holdsCount": 0, + "holdsRatio": 0, + "estimatedWaitDays": 0, + "isFastlane": false, + "availabilityType": "normal", + "isRecommendableToLibrary": true, + "isOwned": true, + "isHoldable": true, + "isAdvantageFiltered": false, + "isRestricted": false, + "visitorEligible": false, + "juvenileEligible": false, + "youngAdultEligible": false, + "contentAccessLevels": 0, + "classifications": {}, + "type": { + "id": "ebook", + "name": "eBook" + }, + "covers": { + "cover150Wide": { + "href": "https://img1.od-cdn.com/ImageType-150/1493-1/{BBBBBBBB-0000-0000-0000-000000000003}Img.jpg", + "height": 200, + "width": 150, + "primaryColor": { + "hex": "#4C282A", + "rgb": { + "red": 76, + "green": 40, + "blue": 42 + } + }, + "isPlaceholderImage": false + }, + "cover300Wide": { + "href": "https://img1.od-cdn.com/ImageType-400/1493-1/{BBBBBBBB-0000-0000-0000-000000000003}Img.jpg", + "height": 400, + "width": 300, + "primaryColor": { + "hex": "#4C282C", + "rgb": { + "red": 76, + "green": 40, + "blue": 44 + } + }, + "isPlaceholderImage": false + }, + "cover510Wide": { + "href": "https://img2.od-cdn.com/ImageType-100/1493-1/{BBBBBBBB-0000-0000-0000-000000000003}Img.jpg", + "height": 680, + "width": 510, + "primaryColor": { + "hex": "#4C282C", + "rgb": { + "red": 76, + "green": 40, + "blue": 44 + } + }, + "isPlaceholderImage": false + } + }, + "id": "3000003", + "firstCreatorName": "Frank Herbert", + "firstCreatorId": 393911, + "firstCreatorSortName": "Frank Herbert", + "title": "Dune Messiah", + "sortTitle": "Dune Messiah", + "starRating": 4.2, + "starRatingCount": 3193, + "edition": "Unabridged", + "publishDate": "2007-05-29T00:00:00Z", + "publishDateText": "05/29/2007", + "dateContentReceivedUTC": "2015-07-29T04:00:00Z", + "formats": [ + { + "identifiers": [ + { + "type": "ISBN", + "value": "9780000000001" + } + ], + "rights": [], + "fileSize": 1543210, + "id": "ebook-overdrive", + "name": "OverDrive Read", + "fulfillmentType": "bifocal" + }, + { + "identifiers": [], + "rights": [], + "fileSize": 1543210, + "id": "ebook-epub-adobe", + "name": "EPUB eBook", + "fulfillmentType": "epub" + }, + { + "identifiers": [], + "rights": [], + "id": "ebook-kindle", + "name": "Kindle Book", + "fulfillmentType": "kindle" + } + ], + "publisherAccount": { + "accessId": 1493, + "id": "3606", + "name": "Macmillan Audio" + }, + "series": "Dune", + "detailedSeries": { + "seriesId": 3, + "seriesName": "Dune", + "readingOrder": "2", + "rank": 2 + } + }, + { + "reserveId": "22222222-2222-3333-4444-000000000004", + "subjects": [ + { + "id": "26", + "name": "Fiction" + }, + { + "id": "80", + "name": "Science Fiction" + } + ], + "bisacCodes": [ + "FIC028010", + "FIC028030" + ], + "bisac": [ + { + "code": "FIC028010", + "description": "Fiction / Science Fiction / Action & Adventure" + }, + { + "code": "FIC028030", + "description": "Fiction / Science Fiction / Space Opera" + } + ], + "levels": [], + "creators": [ + { + "id": 4, + "name": "Frank Herbert", + "role": "Author", + "sortName": "Frank Herbert" + }, + { + "id": 904, + "name": "Ray Porter", + "role": "Narrator", + "sortName": "Porter, Ray" + } + ], + "languages": [ + { + "id": "en", + "name": "English" + } + ], + "isBundledChild": false, + "ratings": { + "maturityLevel": { + "id": "generalcontent", + "name": "General content" + }, + "naughtyScore": { + "id": "GeneralContent", + "name": "General content" + } + }, + "constraints": { + "isDisneyEulaRequired": false + }, + "reviewCounts": { + "premium": 5, + "publisherSupplier": 0 + }, + "isAvailable": false, + "isPreReleaseTitle": false, + "estimatedReleaseDate": "2007-05-29T04:00:00Z", + "sample": { + "href": "https://samples.overdrive.com/?crid=d91b7033-fad9-49ce-a468-bb3b950fd5d5&.epub-sample.overdrive.com" + }, + "publisher": { + "id": "2166", + "name": "Macmillan Audio" + }, + "description": "

NOW A MAJOR MOTION PICTURE directed by Denis Villeneuve, starring Timothée Chalamet, Zendaya, Rebecca Ferguson, Javier Bardem, Josh Brolin, Austin Butler, Florence Pugh, Dave Bautista, Christoph…", + "availableCopies": 0, + "ownedCopies": 12, + "luckyDayAvailableCopies": 0, + "luckyDayOwnedCopies": 0, + "holdsCount": 8, + "holdsRatio": 0, + "estimatedWaitDays": 14, + "isFastlane": false, + "availabilityType": "normal", + "isRecommendableToLibrary": true, + "isOwned": true, + "isHoldable": true, + "isAdvantageFiltered": false, + "isRestricted": false, + "visitorEligible": false, + "juvenileEligible": false, + "youngAdultEligible": false, + "contentAccessLevels": 0, + "classifications": {}, + "type": { + "id": "audiobook", + "name": "Audiobook" + }, + "covers": { + "cover150Wide": { + "href": "https://img1.od-cdn.com/ImageType-150/1493-1/{BBBBBBBB-0000-0000-0000-000000000004}Img.jpg", + "height": 200, + "width": 150, + "primaryColor": { + "hex": "#4C282A", + "rgb": { + "red": 76, + "green": 40, + "blue": 42 + } + }, + "isPlaceholderImage": false + }, + "cover300Wide": { + "href": "https://img1.od-cdn.com/ImageType-400/1493-1/{BBBBBBBB-0000-0000-0000-000000000004}Img.jpg", + "height": 400, + "width": 300, + "primaryColor": { + "hex": "#4C282C", + "rgb": { + "red": 76, + "green": 40, + "blue": 44 + } + }, + "isPlaceholderImage": false + }, + "cover510Wide": { + "href": "https://img2.od-cdn.com/ImageType-100/1493-1/{BBBBBBBB-0000-0000-0000-000000000004}Img.jpg", + "height": 680, + "width": 510, + "primaryColor": { + "hex": "#4C282C", + "rgb": { + "red": 76, + "green": 40, + "blue": 44 + } + }, + "isPlaceholderImage": false + } + }, + "id": "3000004", + "firstCreatorName": "Frank Herbert", + "firstCreatorId": 393911, + "firstCreatorSortName": "Frank Herbert", + "title": "Children of Dune", + "sortTitle": "Children of Dune", + "starRating": 4.2, + "starRatingCount": 3193, + "edition": "Unabridged", + "publishDate": "2007-05-29T00:00:00Z", + "publishDateText": "05/29/2007", + "dateContentReceivedUTC": "2015-07-29T04:00:00Z", + "formats": [ + { + "identifiers": [ + { + "type": "ISBN", + "value": "9781427201447" + } + ], + "rights": [], + "fileSize": 605814901, + "onSaleDateUtc": "2007-05-29T04:00:00+00:00", + "duration": "21:02:06", + "hasAudioSynchronizedText": false, + "isBundleParent": false, + "isbn": "9781427201447", + "bundledContent": [], + "sample": { + "href": "https://samples.overdrive.com/?crid=d91b7033-fad9-49ce-a468-bb3b950fd5d5&.epub-sample.overdrive.com" + }, + "fulfillmentType": "bifocal", + "id": "audiobook-overdrive", + "name": "OverDrive Listen audiobook" + }, + { + "identifiers": [ + { + "type": "ISBN", + "value": "9781427201447" + } + ], + "rights": [], + "fileSize": 605867780, + "onSaleDateUtc": "2007-05-29T04:00:00+00:00", + "partCount": 18, + "duration": "21:12:05", + "hasAudioSynchronizedText": false, + "isBundleParent": false, + "isbn": "9781427201447", + "bundledContent": [], + "sample": { + "href": "https://excerpts.cdn.overdrive.com/FormatType-425/1493-1/2308988-Dune.mp3" + }, + "fulfillmentType": "odm", + "id": "audiobook-mp3", + "name": "MP3 audiobook" + } + ], + "publisherAccount": { + "accessId": 1493, + "id": "3606", + "name": "Macmillan Audio" + }, + "series": "Dune", + "detailedSeries": { + "seriesId": 4, + "seriesName": "Dune", + "readingOrder": "3", + "rank": 3 + } + }, + { + "reserveId": "22222222-2222-3333-4444-000000000005", + "subjects": [ + { + "id": "26", + "name": "Fiction" + }, + { + "id": "80", + "name": "Science Fiction" + } + ], + "bisacCodes": [ + "FIC028010", + "FIC028030" + ], + "bisac": [ + { + "code": "FIC028010", + "description": "Fiction / Science Fiction / Action & Adventure" + }, + { + "code": "FIC028030", + "description": "Fiction / Science Fiction / Space Opera" + } + ], + "levels": [], + "creators": [ + { + "id": 5, + "name": "Brian Herbert", + "role": "Author", + "sortName": "Brian Herbert" + } + ], + "languages": [ + { + "id": "en", + "name": "English" + } + ], + "isBundledChild": false, + "ratings": { + "maturityLevel": { + "id": "generalcontent", + "name": "General content" + }, + "naughtyScore": { + "id": "GeneralContent", + "name": "General content" + } + }, + "constraints": { + "isDisneyEulaRequired": false + }, + "reviewCounts": { + "premium": 5, + "publisherSupplier": 0 + }, + "isAvailable": true, + "isPreReleaseTitle": false, + "estimatedReleaseDate": "2007-05-29T04:00:00Z", + "sample": { + "href": "https://samples.overdrive.com/?crid=d91b7033-fad9-49ce-a468-bb3b950fd5d5&.epub-sample.overdrive.com" + }, + "publisher": { + "id": "2166", + "name": "Macmillan Audio" + }, + "description": "

NOW A MAJOR MOTION PICTURE directed by Denis Villeneuve, starring Timothée Chalamet, Zendaya, Rebecca Ferguson, Javier Bardem, Josh Brolin, Austin Butler, Florence Pugh, Dave Bautista, Christoph…", + "availableCopies": 1, + "ownedCopies": 2, + "luckyDayAvailableCopies": 0, + "luckyDayOwnedCopies": 0, + "holdsCount": 0, + "holdsRatio": 0, + "estimatedWaitDays": 0, + "isFastlane": false, + "availabilityType": "normal", + "isRecommendableToLibrary": true, + "isOwned": true, + "isHoldable": true, + "isAdvantageFiltered": false, + "isRestricted": false, + "visitorEligible": false, + "juvenileEligible": false, + "youngAdultEligible": false, + "contentAccessLevels": 0, + "classifications": {}, + "type": { + "id": "ebook", + "name": "eBook" + }, + "covers": { + "cover150Wide": { + "href": "https://img1.od-cdn.com/ImageType-150/1493-1/{BBBBBBBB-0000-0000-0000-000000000005}Img.jpg", + "height": 200, + "width": 150, + "primaryColor": { + "hex": "#4C282A", + "rgb": { + "red": 76, + "green": 40, + "blue": 42 + } + }, + "isPlaceholderImage": false + }, + "cover300Wide": { + "href": "https://img1.od-cdn.com/ImageType-400/1493-1/{BBBBBBBB-0000-0000-0000-000000000005}Img.jpg", + "height": 400, + "width": 300, + "primaryColor": { + "hex": "#4C282C", + "rgb": { + "red": 76, + "green": 40, + "blue": 44 + } + }, + "isPlaceholderImage": false + }, + "cover510Wide": { + "href": "https://img2.od-cdn.com/ImageType-100/1493-1/{BBBBBBBB-0000-0000-0000-000000000005}Img.jpg", + "height": 680, + "width": 510, + "primaryColor": { + "hex": "#4C282C", + "rgb": { + "red": 76, + "green": 40, + "blue": 44 + } + }, + "isPlaceholderImage": false + } + }, + "id": "3000005", + "firstCreatorName": "Brian Herbert", + "firstCreatorId": 393911, + "firstCreatorSortName": "Brian Herbert", + "title": "The Road to Dune", + "sortTitle": "The Road to Dune", + "starRating": 3.4, + "starRatingCount": 3193, + "edition": "Unabridged", + "publishDate": "2007-05-29T00:00:00Z", + "publishDateText": "05/29/2007", + "dateContentReceivedUTC": "2015-07-29T04:00:00Z", + "formats": [ + { + "identifiers": [ + { + "type": "ISBN", + "value": "9780000000001" + } + ], + "rights": [], + "fileSize": 1543210, + "id": "ebook-overdrive", + "name": "OverDrive Read", + "fulfillmentType": "bifocal" + }, + { + "identifiers": [], + "rights": [], + "fileSize": 1543210, + "id": "ebook-epub-adobe", + "name": "EPUB eBook", + "fulfillmentType": "epub" + }, + { + "identifiers": [], + "rights": [], + "id": "ebook-kindle", + "name": "Kindle Book", + "fulfillmentType": "kindle" + } + ], + "publisherAccount": { + "accessId": 1493, + "id": "3606", + "name": "Macmillan Audio" + } + }, + { + "reserveId": "22222222-2222-3333-4444-000000000006", + "subjects": [ + { + "id": "26", + "name": "Fiction" + }, + { + "id": "80", + "name": "Science Fiction" + } + ], + "bisacCodes": [ + "FIC028010", + "FIC028030" + ], + "bisac": [ + { + "code": "FIC028010", + "description": "Fiction / Science Fiction / Action & Adventure" + }, + { + "code": "FIC028030", + "description": "Fiction / Science Fiction / Space Opera" + } + ], + "levels": [], + "creators": [ + { + "id": 6, + "name": "Frank Herbert", + "role": "Author", + "sortName": "Frank Herbert" + } + ], + "languages": [ + { + "id": "en", + "name": "English" + } + ], + "isBundledChild": false, + "ratings": { + "maturityLevel": { + "id": "generalcontent", + "name": "General content" + }, + "naughtyScore": { + "id": "GeneralContent", + "name": "General content" + } + }, + "constraints": { + "isDisneyEulaRequired": false + }, + "reviewCounts": { + "premium": 5, + "publisherSupplier": 0 + }, + "isAvailable": false, + "isPreReleaseTitle": false, + "estimatedReleaseDate": "2007-05-29T04:00:00Z", + "sample": { + "href": "https://samples.overdrive.com/?crid=d91b7033-fad9-49ce-a468-bb3b950fd5d5&.epub-sample.overdrive.com" + }, + "publisher": { + "id": "2166", + "name": "Macmillan Audio" + }, + "description": "

NOW A MAJOR MOTION PICTURE directed by Denis Villeneuve, starring Timothée Chalamet, Zendaya, Rebecca Ferguson, Javier Bardem, Josh Brolin, Austin Butler, Florence Pugh, Dave Bautista, Christoph…", + "availableCopies": 0, + "ownedCopies": 5, + "luckyDayAvailableCopies": 0, + "luckyDayOwnedCopies": 0, + "holdsCount": 61, + "holdsRatio": 12, + "estimatedWaitDays": 90, + "isFastlane": false, + "availabilityType": "normal", + "isRecommendableToLibrary": true, + "isOwned": true, + "isHoldable": true, + "isAdvantageFiltered": false, + "isRestricted": false, + "visitorEligible": false, + "juvenileEligible": false, + "youngAdultEligible": false, + "contentAccessLevels": 0, + "classifications": {}, + "type": { + "id": "ebook", + "name": "eBook" + }, + "covers": { + "cover150Wide": { + "href": "https://img1.od-cdn.com/ImageType-150/1493-1/{BBBBBBBB-0000-0000-0000-000000000006}Img.jpg", + "height": 200, + "width": 150, + "primaryColor": { + "hex": "#4C282A", + "rgb": { + "red": 76, + "green": 40, + "blue": 42 + } + }, + "isPlaceholderImage": false + }, + "cover300Wide": { + "href": "https://img1.od-cdn.com/ImageType-400/1493-1/{BBBBBBBB-0000-0000-0000-000000000006}Img.jpg", + "height": 400, + "width": 300, + "primaryColor": { + "hex": "#4C282C", + "rgb": { + "red": 76, + "green": 40, + "blue": 44 + } + }, + "isPlaceholderImage": false + }, + "cover510Wide": { + "href": "https://img2.od-cdn.com/ImageType-100/1493-1/{BBBBBBBB-0000-0000-0000-000000000006}Img.jpg", + "height": 680, + "width": 510, + "primaryColor": { + "hex": "#4C282C", + "rgb": { + "red": 76, + "green": 40, + "blue": 44 + } + }, + "isPlaceholderImage": false + } + }, + "id": "3000006", + "firstCreatorName": "Frank Herbert", + "firstCreatorId": 393911, + "firstCreatorSortName": "Frank Herbert", + "title": "Dune: The Graphic Novel, Book 1: A Faithful Adaptation of the Epic Science Fiction Masterpiece", + "sortTitle": "Dune: The Graphic Novel, Book 1: A Faithful Adaptation of the Epic Science Fiction Masterpiece", + "starRating": 4.2, + "starRatingCount": 3193, + "edition": "Unabridged", + "publishDate": "2007-05-29T00:00:00Z", + "publishDateText": "05/29/2007", + "dateContentReceivedUTC": "2015-07-29T04:00:00Z", + "formats": [ + { + "identifiers": [ + { + "type": "ISBN", + "value": "9780000000001" + } + ], + "rights": [], + "fileSize": 1543210, + "id": "ebook-overdrive", + "name": "OverDrive Read", + "fulfillmentType": "bifocal" + }, + { + "identifiers": [], + "rights": [], + "fileSize": 1543210, + "id": "ebook-epub-adobe", + "name": "EPUB eBook", + "fulfillmentType": "epub" + }, + { + "identifiers": [], + "rights": [], + "id": "ebook-kindle", + "name": "Kindle Book", + "fulfillmentType": "kindle" + } + ], + "publisherAccount": { + "accessId": 1493, + "id": "3606", + "name": "Macmillan Audio" + }, + "subtitle": "Deluxe Collector's Edition" + }, + { + "reserveId": "22222222-2222-3333-4444-000000000007", + "subjects": [ + { + "id": "26", + "name": "Fiction" + }, + { + "id": "80", + "name": "Science Fiction" + } + ], + "bisacCodes": [ + "FIC028010", + "FIC028030" + ], + "bisac": [ + { + "code": "FIC028010", + "description": "Fiction / Science Fiction / Action & Adventure" + }, + { + "code": "FIC028030", + "description": "Fiction / Science Fiction / Space Opera" + } + ], + "levels": [], + "creators": [ + { + "id": 7, + "name": "フランク・ハーバート", + "role": "Author", + "sortName": "フランク・ハーバート" + } + ], + "languages": [ + { + "id": "en", + "name": "English" + } + ], + "isBundledChild": false, + "ratings": { + "maturityLevel": { + "id": "generalcontent", + "name": "General content" + }, + "naughtyScore": { + "id": "GeneralContent", + "name": "General content" + } + }, + "constraints": { + "isDisneyEulaRequired": false + }, + "reviewCounts": { + "premium": 5, + "publisherSupplier": 0 + }, + "isAvailable": true, + "isPreReleaseTitle": false, + "estimatedReleaseDate": "2007-05-29T04:00:00Z", + "sample": { + "href": "https://samples.overdrive.com/?crid=d91b7033-fad9-49ce-a468-bb3b950fd5d5&.epub-sample.overdrive.com" + }, + "publisher": { + "id": "2166", + "name": "Macmillan Audio" + }, + "description": "

NOW A MAJOR MOTION PICTURE directed by Denis Villeneuve, starring Timothée Chalamet, Zendaya, Rebecca Ferguson, Javier Bardem, Josh Brolin, Austin Butler, Florence Pugh, Dave Bautista, Christoph…", + "availableCopies": 2, + "ownedCopies": 2, + "luckyDayAvailableCopies": 0, + "luckyDayOwnedCopies": 0, + "holdsCount": 0, + "holdsRatio": 0, + "estimatedWaitDays": 0, + "isFastlane": false, + "availabilityType": "normal", + "isRecommendableToLibrary": true, + "isOwned": true, + "isHoldable": true, + "isAdvantageFiltered": false, + "isRestricted": false, + "visitorEligible": false, + "juvenileEligible": false, + "youngAdultEligible": false, + "contentAccessLevels": 0, + "classifications": {}, + "type": { + "id": "ebook", + "name": "eBook" + }, + "covers": { + "cover150Wide": { + "href": "https://img1.od-cdn.com/ImageType-150/1493-1/{BBBBBBBB-0000-0000-0000-000000000007}Img.jpg", + "height": 200, + "width": 150, + "primaryColor": { + "hex": "#4C282A", + "rgb": { + "red": 76, + "green": 40, + "blue": 42 + } + }, + "isPlaceholderImage": false + }, + "cover300Wide": { + "href": "https://img1.od-cdn.com/ImageType-400/1493-1/{BBBBBBBB-0000-0000-0000-000000000007}Img.jpg", + "height": 400, + "width": 300, + "primaryColor": { + "hex": "#4C282C", + "rgb": { + "red": 76, + "green": 40, + "blue": 44 + } + }, + "isPlaceholderImage": false + }, + "cover510Wide": { + "href": "https://img2.od-cdn.com/ImageType-100/1493-1/{BBBBBBBB-0000-0000-0000-000000000007}Img.jpg", + "height": 680, + "width": 510, + "primaryColor": { + "hex": "#4C282C", + "rgb": { + "red": 76, + "green": 40, + "blue": 44 + } + }, + "isPlaceholderImage": false + } + }, + "id": "3000007", + "firstCreatorName": "フランク・ハーバート", + "firstCreatorId": 393911, + "firstCreatorSortName": "フランク・ハーバート", + "title": "沙丘", + "sortTitle": "沙丘", + "starRating": 0, + "starRatingCount": 3193, + "edition": "Unabridged", + "publishDate": "2007-05-29T00:00:00Z", + "publishDateText": "05/29/2007", + "dateContentReceivedUTC": "2015-07-29T04:00:00Z", + "formats": [ + { + "identifiers": [ + { + "type": "ISBN", + "value": "9780000000001" + } + ], + "rights": [], + "fileSize": 1543210, + "id": "ebook-overdrive", + "name": "OverDrive Read", + "fulfillmentType": "bifocal" + }, + { + "identifiers": [], + "rights": [], + "fileSize": 1543210, + "id": "ebook-epub-adobe", + "name": "EPUB eBook", + "fulfillmentType": "epub" + }, + { + "identifiers": [], + "rights": [], + "id": "ebook-kindle", + "name": "Kindle Book", + "fulfillmentType": "kindle" + } + ], + "publisherAccount": { + "accessId": 1493, + "id": "3606", + "name": "Macmillan Audio" + } + }, + { + "reserveId": "22222222-2222-3333-4444-000000000008", + "subjects": [ + { + "id": "26", + "name": "Fiction" + }, + { + "id": "80", + "name": "Science Fiction" + } + ], + "bisacCodes": [ + "FIC028010", + "FIC028030" + ], + "bisac": [ + { + "code": "FIC028010", + "description": "Fiction / Science Fiction / Action & Adventure" + }, + { + "code": "FIC028030", + "description": "Fiction / Science Fiction / Space Opera" + } + ], + "levels": [], + "creators": [ + { + "id": 8, + "name": "", + "role": "Author", + "sortName": "" + } + ], + "languages": [ + { + "id": "en", + "name": "English" + } + ], + "isBundledChild": false, + "ratings": { + "maturityLevel": { + "id": "generalcontent", + "name": "General content" + }, + "naughtyScore": { + "id": "GeneralContent", + "name": "General content" + } + }, + "constraints": { + "isDisneyEulaRequired": false + }, + "reviewCounts": { + "premium": 5, + "publisherSupplier": 0 + }, + "isAvailable": true, + "isPreReleaseTitle": false, + "estimatedReleaseDate": "2007-05-29T04:00:00Z", + "sample": { + "href": "https://samples.overdrive.com/?crid=d91b7033-fad9-49ce-a468-bb3b950fd5d5&.epub-sample.overdrive.com" + }, + "publisher": { + "id": "2166", + "name": "Macmillan Audio" + }, + "description": "

NOW A MAJOR MOTION PICTURE directed by Denis Villeneuve, starring Timothée Chalamet, Zendaya, Rebecca Ferguson, Javier Bardem, Josh Brolin, Austin Butler, Florence Pugh, Dave Bautista, Christoph…", + "availableCopies": 999, + "ownedCopies": 999, + "luckyDayAvailableCopies": 0, + "luckyDayOwnedCopies": 0, + "holdsCount": 0, + "holdsRatio": 0, + "estimatedWaitDays": 0, + "isFastlane": false, + "availabilityType": "normal", + "isRecommendableToLibrary": true, + "isOwned": true, + "isHoldable": false, + "isAdvantageFiltered": false, + "isRestricted": false, + "visitorEligible": false, + "juvenileEligible": false, + "youngAdultEligible": false, + "contentAccessLevels": 0, + "classifications": {}, + "type": { + "id": "magazine", + "name": "Magazine" + }, + "covers": { + "cover150Wide": { + "href": "https://img1.od-cdn.com/ImageType-150/1493-1/{BBBBBBBB-0000-0000-0000-000000000008}Img.jpg", + "height": 200, + "width": 150, + "primaryColor": { + "hex": "#4C282A", + "rgb": { + "red": 76, + "green": 40, + "blue": 42 + } + }, + "isPlaceholderImage": false + }, + "cover300Wide": { + "href": "https://img1.od-cdn.com/ImageType-400/1493-1/{BBBBBBBB-0000-0000-0000-000000000008}Img.jpg", + "height": 400, + "width": 300, + "primaryColor": { + "hex": "#4C282C", + "rgb": { + "red": 76, + "green": 40, + "blue": 44 + } + }, + "isPlaceholderImage": false + }, + "cover510Wide": { + "href": "https://img2.od-cdn.com/ImageType-100/1493-1/{BBBBBBBB-0000-0000-0000-000000000008}Img.jpg", + "height": 680, + "width": 510, + "primaryColor": { + "hex": "#4C282C", + "rgb": { + "red": 76, + "green": 40, + "blue": 44 + } + }, + "isPlaceholderImage": false + } + }, + "id": "3000008", + "firstCreatorName": "", + "firstCreatorId": 393911, + "firstCreatorSortName": "", + "title": "Sand Dunes Quarterly", + "sortTitle": "Sand Dunes Quarterly", + "starRating": 0, + "starRatingCount": 3193, + "edition": "Unabridged", + "publishDate": "2007-05-29T00:00:00Z", + "publishDateText": "05/29/2007", + "dateContentReceivedUTC": "2015-07-29T04:00:00Z", + "formats": [ + { + "identifiers": [], + "rights": [], + "id": "magazine-overdrive", + "name": "OverDrive Magazine" + } + ], + "publisherAccount": { + "accessId": 1493, + "id": "3606", + "name": "Macmillan Audio" + } + } + ], + "totalItems": 90, + "totalItemsText": "90", + "links": { + "self": { + "page": 1, + "pageText": "1" + }, + "first": { + "page": 1, + "pageText": "1" + }, + "last": { + "page": 45, + "pageText": "45" + }, + "next": { + "page": 2, + "pageText": "2" + } + } +} \ No newline at end of file diff --git a/crates/libbui/src/testing/fixtures/sync.json b/crates/libbui/src/testing/fixtures/sync.json new file mode 100644 index 0000000..385c269 --- /dev/null +++ b/crates/libbui/src/testing/fixtures/sync.json @@ -0,0 +1,549 @@ +{ + "result": "synchronized", + "cards": [ + { + "cardId": "10000001", + "cardName": "Example Public Library", + "advantageKey": "examplepl", + "emailAddress": "patron@example.invalid", + "library": { + "name": "Example Public Library", + "websiteId": "99" + }, + "lendingPeriods": { + "book": { + "preference": [ + 21, + "days" + ], + "options": [ + [ + 7, + "days" + ], + [ + 14, + "days" + ], + [ + 21, + "days" + ] + ] + }, + "audiobook": { + "preference": [ + 14, + "days" + ], + "options": [ + [ + 7, + "days" + ], + [ + 14, + "days" + ] + ] + } + }, + "limits": { + "loan": 10, + "hold": 15 + }, + "counts": { + "loan": 4, + "hold": 3 + } + }, + { + "cardId": "10000002", + "cardName": "River County Libraries", + "advantageKey": "rivercounty", + "emailAddress": "patron@example.invalid", + "library": { + "name": "River County Libraries", + "websiteId": "77" + }, + "lendingPeriods": { + "book": { + "preference": [ + 21, + "days" + ], + "options": [ + [ + 7, + "days" + ], + [ + 14, + "days" + ], + [ + 21, + "days" + ] + ] + }, + "audiobook": { + "preference": [ + 14, + "days" + ], + "options": [ + [ + 7, + "days" + ], + [ + 14, + "days" + ] + ] + } + }, + "limits": { + "loan": 5, + "hold": 5 + }, + "counts": { + "loan": 2, + "hold": 1 + } + } + ], + "loans": [ + { + "id": "1000001", + "reserveId": "11111111-2222-3333-4444-000000000001", + "cardId": "10000001", + "websiteId": "99", + "checkoutId": 900001, + "title": "The Left Hand of Darkness", + "sortTitle": "The Left Hand of Darkness", + "firstCreatorName": "Ursula K. Le Guin", + "type": { + "id": "ebook", + "name": "eBook" + }, + "covers": { + "cover150Wide": { + "href": "https://img1.od-cdn.com/ImageType-150/0000-1/{AAAAAAAA-0000-0000-0000-000000000001}Img150.jpg", + "width": 150, + "height": 200 + }, + "cover510Wide": { + "href": "https://img1.od-cdn.com/ImageType-400/0000-1/{AAAAAAAA-0000-0000-0000-000000000001}Img400.jpg", + "width": 510, + "height": 680 + } + }, + "formats": [ + { + "id": "ebook-overdrive", + "name": "OverDrive Read", + "identifiers": [], + "isLockedIn": false + }, + { + "id": "ebook-epub-open", + "name": "Open EPUB eBook", + "fulfillmentType": "epub", + "identifiers": [], + "isLockedIn": false + }, + { + "id": "ebook-kindle", + "name": "Kindle Book", + "fulfillmentType": "kindle", + "identifiers": [] + } + ], + "checkoutDate": "2026-11-01T15:04:05Z", + "expireDate": "2026-11-22T15:04:05Z", + "isReturnable": true, + "isFormatLockedIn": false, + "isLuckyDayCheckout": false, + "otherFormats": [], + "renewableOn": "2026-11-19T15:04:05Z", + "detailedSeries": { + "seriesId": 501, + "seriesName": "Hainish Cycle", + "readingOrder": "4", + "rank": 4 + }, + "series": "Hainish Cycle" + }, + { + "id": "1000002", + "reserveId": "11111111-2222-3333-4444-000000000002", + "cardId": "10000001", + "websiteId": "99", + "checkoutId": 900002, + "title": "Project Hail Mary", + "sortTitle": "Project Hail Mary", + "firstCreatorName": "Andy Weir", + "type": { + "id": "audiobook", + "name": "Audiobook" + }, + "covers": { + "cover150Wide": { + "href": "https://img1.od-cdn.com/ImageType-150/0000-1/{AAAAAAAA-0000-0000-0000-000000000002}Img150.jpg", + "width": 150, + "height": 200 + }, + "cover510Wide": { + "href": "https://img1.od-cdn.com/ImageType-400/0000-1/{AAAAAAAA-0000-0000-0000-000000000002}Img400.jpg", + "width": 510, + "height": 680 + } + }, + "formats": [ + { + "id": "audiobook-overdrive", + "name": "OverDrive Listen audiobook", + "identifiers": [], + "isLockedIn": false + }, + { + "id": "audiobook-mp3", + "name": "MP3 audiobook", + "identifiers": [], + "isLockedIn": false + } + ], + "checkoutDate": "2026-11-10T08:00:00Z", + "expireDate": "2026-11-24T08:00:00Z", + "isReturnable": true, + "isFormatLockedIn": false, + "isLuckyDayCheckout": false, + "otherFormats": [] + }, + { + "id": "1000003", + "reserveId": "11111111-2222-3333-4444-000000000003", + "cardId": "10000001", + "websiteId": "99", + "checkoutId": 900003, + "title": "A Psalm for the Wild-Built", + "sortTitle": "A Psalm for the Wild-Built", + "firstCreatorName": "Becky Chambers", + "type": { + "id": "ebook", + "name": "eBook" + }, + "covers": { + "cover150Wide": { + "href": "https://img1.od-cdn.com/ImageType-150/0000-1/{AAAAAAAA-0000-0000-0000-000000000003}Img150.jpg", + "width": 150, + "height": 200 + }, + "cover510Wide": { + "href": "https://img1.od-cdn.com/ImageType-400/0000-1/{AAAAAAAA-0000-0000-0000-000000000003}Img400.jpg", + "width": 510, + "height": 680 + } + }, + "formats": [ + { + "id": "ebook-overdrive", + "name": "OverDrive Read", + "identifiers": [], + "isLockedIn": false + }, + { + "id": "ebook-epub-adobe", + "name": "EPUB eBook", + "fulfillmentType": "epub", + "identifiers": [], + "isLockedIn": false + }, + { + "id": "ebook-kindle", + "name": "Kindle Book", + "fulfillmentType": "kindle", + "identifiers": [] + } + ], + "checkoutDate": "2026-10-26T09:30:00Z", + "expireDate": "2026-11-16T09:30:00Z", + "isReturnable": true, + "isFormatLockedIn": false, + "isLuckyDayCheckout": false, + "otherFormats": [], + "renewableOn": "2026-11-13T09:30:00Z" + }, + { + "id": "1000004", + "reserveId": "11111111-2222-3333-4444-000000000004", + "cardId": "10000001", + "websiteId": "99", + "checkoutId": 900004, + "title": "The New Yorker: Nov 9, 2026", + "sortTitle": "The New Yorker: Nov 9, 2026", + "firstCreatorName": "", + "type": { + "id": "magazine", + "name": "Magazine" + }, + "covers": { + "cover150Wide": { + "href": "https://img1.od-cdn.com/ImageType-150/0000-1/{AAAAAAAA-0000-0000-0000-000000000004}Img150.jpg", + "width": 150, + "height": 200 + }, + "cover510Wide": { + "href": "https://img1.od-cdn.com/ImageType-400/0000-1/{AAAAAAAA-0000-0000-0000-000000000004}Img400.jpg", + "width": 510, + "height": 680 + } + }, + "formats": [ + { + "id": "magazine-overdrive", + "name": "OverDrive Magazine", + "identifiers": [], + "isLockedIn": false + } + ], + "checkoutDate": "2026-11-09T00:00:00Z", + "expireDate": "2026-11-30T00:00:00Z", + "isReturnable": true, + "isFormatLockedIn": false, + "isLuckyDayCheckout": false, + "otherFormats": [] + }, + { + "id": "1000005", + "reserveId": "11111111-2222-3333-4444-000000000005", + "cardId": "10000002", + "websiteId": "77", + "checkoutId": 900005, + "title": "Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems", + "sortTitle": "Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems", + "firstCreatorName": "Martin Kleppmann", + "type": { + "id": "ebook", + "name": "eBook" + }, + "covers": { + "cover150Wide": { + "href": "https://img1.od-cdn.com/ImageType-150/0000-1/{AAAAAAAA-0000-0000-0000-000000000005}Img150.jpg", + "width": 150, + "height": 200 + }, + "cover510Wide": { + "href": "https://img1.od-cdn.com/ImageType-400/0000-1/{AAAAAAAA-0000-0000-0000-000000000005}Img400.jpg", + "width": 510, + "height": 680 + } + }, + "formats": [ + { + "id": "ebook-overdrive", + "name": "OverDrive Read", + "identifiers": [], + "isLockedIn": false + }, + { + "id": "ebook-pdf-open", + "name": "Open PDF eBook", + "fulfillmentType": "pdf", + "identifiers": [], + "isLockedIn": false + }, + { + "id": "ebook-epub-open", + "name": "Open EPUB eBook", + "fulfillmentType": "epub", + "identifiers": [], + "isLockedIn": false + } + ], + "checkoutDate": "2026-11-12T18:00:00Z", + "expireDate": "2026-11-26T18:00:00Z", + "isReturnable": true, + "isFormatLockedIn": false, + "isLuckyDayCheckout": true, + "otherFormats": [] + }, + { + "id": "1000006", + "reserveId": "11111111-2222-3333-4444-000000000006", + "cardId": "10000002", + "websiteId": "77", + "checkoutId": 900006, + "title": "三体", + "sortTitle": "三体", + "firstCreatorName": "刘慈欣", + "type": { + "id": "ebook", + "name": "eBook" + }, + "covers": { + "cover150Wide": { + "href": "https://img1.od-cdn.com/ImageType-150/0000-1/{AAAAAAAA-0000-0000-0000-000000000006}Img150.jpg", + "width": 150, + "height": 200 + }, + "cover510Wide": { + "href": "https://img1.od-cdn.com/ImageType-400/0000-1/{AAAAAAAA-0000-0000-0000-000000000006}Img400.jpg", + "width": 510, + "height": 680 + } + }, + "formats": [ + { + "id": "ebook-overdrive", + "name": "OverDrive Read", + "identifiers": [], + "isLockedIn": false + }, + { + "id": "ebook-epub-open", + "name": "Open EPUB eBook", + "fulfillmentType": "epub", + "identifiers": [], + "isLockedIn": false + } + ], + "checkoutDate": "2026-11-14T10:00:00Z", + "expireDate": "2026-12-05T10:00:00Z", + "isReturnable": true, + "isFormatLockedIn": false, + "isLuckyDayCheckout": false, + "otherFormats": [] + } + ], + "holds": [ + { + "id": "2000001", + "cardId": "10000001", + "websiteId": "99", + "title": "Piranesi", + "firstCreatorName": "Susanna Clarke", + "type": { + "id": "ebook", + "name": "eBook" + }, + "covers": { + "cover150Wide": { + "href": "https://img1.od-cdn.com/ImageType-150/0000-1/{AAAAAAAA-0000-0000-0000-000000000101}Img150.jpg", + "width": 150, + "height": 200 + }, + "cover510Wide": { + "href": "https://img1.od-cdn.com/ImageType-400/0000-1/{AAAAAAAA-0000-0000-0000-000000000101}Img400.jpg", + "width": 510, + "height": 680 + } + }, + "placedDate": "2026-10-01T12:00:00Z", + "isAvailable": true, + "holdListPosition": 1, + "estimatedWaitDays": 0, + "autoBorrow": false, + "suspensionFlag": false, + "ownedCopies": 3, + "holdsCount": 12, + "expireDate": "2026-11-18T12:00:00Z" + }, + { + "id": "2000002", + "cardId": "10000001", + "websiteId": "99", + "title": "The Ministry for the Future", + "firstCreatorName": "Kim Stanley Robinson", + "type": { + "id": "audiobook", + "name": "Audiobook" + }, + "covers": { + "cover150Wide": { + "href": "https://img1.od-cdn.com/ImageType-150/0000-1/{AAAAAAAA-0000-0000-0000-000000000102}Img150.jpg", + "width": 150, + "height": 200 + }, + "cover510Wide": { + "href": "https://img1.od-cdn.com/ImageType-400/0000-1/{AAAAAAAA-0000-0000-0000-000000000102}Img400.jpg", + "width": 510, + "height": 680 + } + }, + "placedDate": "2026-10-05T12:00:00Z", + "isAvailable": false, + "holdListPosition": 14, + "estimatedWaitDays": 60, + "autoBorrow": false, + "suspensionFlag": false, + "ownedCopies": 3, + "holdsCount": 42 + }, + { + "id": "2000003", + "cardId": "10000001", + "websiteId": "99", + "title": "Babel", + "firstCreatorName": "R. F. Kuang", + "type": { + "id": "ebook", + "name": "eBook" + }, + "covers": { + "cover150Wide": { + "href": "https://img1.od-cdn.com/ImageType-150/0000-1/{AAAAAAAA-0000-0000-0000-000000000103}Img150.jpg", + "width": 150, + "height": 200 + }, + "cover510Wide": { + "href": "https://img1.od-cdn.com/ImageType-400/0000-1/{AAAAAAAA-0000-0000-0000-000000000103}Img400.jpg", + "width": 510, + "height": 680 + } + }, + "placedDate": "2026-09-20T12:00:00Z", + "isAvailable": false, + "holdListPosition": 3, + "estimatedWaitDays": 21, + "autoBorrow": false, + "suspensionFlag": true, + "ownedCopies": 3, + "holdsCount": 12, + "suspensionEnd": "2026-12-01T00:00:00Z" + }, + { + "id": "2000004", + "cardId": "10000002", + "websiteId": "77", + "title": "Tomorrow, and Tomorrow, and Tomorrow", + "firstCreatorName": "Gabrielle Zevin", + "type": { + "id": "ebook", + "name": "eBook" + }, + "covers": { + "cover150Wide": { + "href": "https://img1.od-cdn.com/ImageType-150/0000-1/{AAAAAAAA-0000-0000-0000-000000000104}Img150.jpg", + "width": 150, + "height": 200 + }, + "cover510Wide": { + "href": "https://img1.od-cdn.com/ImageType-400/0000-1/{AAAAAAAA-0000-0000-0000-000000000104}Img400.jpg", + "width": 510, + "height": 680 + } + }, + "placedDate": "2026-11-01T12:00:00Z", + "isAvailable": false, + "holdListPosition": 128, + "estimatedWaitDays": 180, + "autoBorrow": false, + "suspensionFlag": false, + "ownedCopies": 6, + "holdsCount": 412 + } + ] +} \ No newline at end of file diff --git a/crates/libbui/src/testing/mod.rs b/crates/libbui/src/testing/mod.rs new file mode 100644 index 0000000..9da798a --- /dev/null +++ b/crates/libbui/src/testing/mod.rs @@ -0,0 +1,794 @@ +//! Driving the whole interface without a terminal, a network or a clock. +//! +//! ```ignore +//! let mut h = Harness::new().await; // paired, synced, on the shelf +//! h.press("2").await; // keys use the keymap's notation +//! h.type_text("dune").await; +//! h.press("enter").await; +//! insta::assert_snapshot!(h.screen()); +//! assert_eq!(h.api.calls(), ["sync", "search examplepl q=dune page=1"]); +//! ``` +//! +//! Everything asynchronous the app starts is awaited inline by +//! [`Harness::settle`] (which `press` and friends call), so tests are +//! deterministic: by the time a call returns, every reply has been folded +//! back into the state. + +#![allow( + dead_code, + reason = "a toolbox: not every helper has a caller at every moment" +)] + +use std::collections::{HashMap, VecDeque}; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, MutexGuard}; +use std::time::{Duration, Instant}; + +use async_trait::async_trait; +use crossterm::event::{KeyEvent, KeyEventKind, KeyEventState, MouseEvent}; +use jiff::Timestamp; +use libbui_core::config::Config; +use libbui_core::download::{self, Job, JobId, JobSpec, JobState}; +use libby::models::{ + Card, CloneCode, Hold, LibraryMatch, Loan, Media, MediaKind, SearchPage, SyncState, +}; +use libby::{BorrowOptions, CardId, FormatId, Fulfillment, LibraryKey, SearchQuery, TitleId}; +use ratatui::Terminal; +use ratatui::backend::TestBackend; +use url::Url; + +use crate::api::Api; +use crate::app::{Action, App, DownloadQueue, Services, Shared, System, Task}; +use crate::keymap::{Chord, Command, Keymap}; +use crate::theme::{ColorDepth, Symbols, Theme}; +use crate::tui::Event; +use crate::ui::cover::Covers; +use crate::ui::toast::Toast; + +/// The moment every test happens at. The fixtures' dates are relative to it: +/// one loan is due tomorrow, one hold is ready to borrow. +pub const NOW: &str = "2026-11-15T12:00:00Z"; + +/// Two cards, six loans (open EPUB, audiobook, ACSM-only, magazine, a very +/// long title, CJK), four holds (ready, waiting, suspended, far back). +pub const SYNC_JSON: &str = include_str!("fixtures/sync.json"); +/// Eight results for "dune", page 1 of 45. +pub const SEARCH_JSON: &str = include_str!("fixtures/search.json"); +/// Four more, page 2. +pub const SEARCH_PAGE_2_JSON: &str = include_str!("fixtures/search-page-2.json"); + +/// Parses a fixture, panicking with the reason if it no longer matches the +/// models (a test bug, never a runtime condition). +/// +/// # Panics +/// When `json` does not deserialize as `T`. +#[must_use] +pub fn fixture(json: &str) -> T { + match serde_json::from_str(json) { + Ok(value) => value, + Err(error) => panic!("fixture does not match the model: {error}"), + } +} + +/// The fixture account. +#[must_use] +pub fn sync_state() -> SyncState { + fixture(SYNC_JSON) +} + +/// The first page of fixture search results. +#[must_use] +pub fn search_page() -> SearchPage { + fixture(SEARCH_JSON) +} + +/// The test clock's "now". +/// +/// # Panics +/// Never: [`NOW`] is a valid timestamp. +#[must_use] +pub fn now() -> Timestamp { + match NOW.parse() { + Ok(now) => now, + Err(error) => panic!("NOW is not a timestamp: {error}"), + } +} + +// ── Fake API ─────────────────────────────────────────────────────────────── + +/// What the fake Libby knows and what it has been asked. +#[derive(Debug)] +pub struct FakeState { + /// Whether this device is paired. + pub linked: bool, + /// The account `sync` returns. Borrowing, returning and holds edit it. + pub account: SyncState, + /// Search results by page number. A missing page is an empty page. + pub pages: HashMap, + /// Catalogue entries by title, for the detail view. Search results are + /// added automatically. + pub media: HashMap, + /// What `find_libraries` returns. + pub libraries: Vec, + /// What `fulfill` returns, by format id. A missing format is refused. + pub fulfillments: HashMap, + /// The pairing code that `redeem_code` accepts. + pub valid_code: String, + /// Errors to return instead of answering, consumed in order, one per + /// call (any call). + pub failures: VecDeque, + /// Every call made, oldest first, in a compact readable form. + pub calls: Vec, +} + +impl Default for FakeState { + fn default() -> Self { + let first: SearchPage = fixture(SEARCH_JSON); + let second: SearchPage = fixture(SEARCH_PAGE_2_JSON); + let media = first + .items + .iter() + .chain(&second.items) + .map(|media| (media.id.clone(), media.clone())) + .collect(); + Self { + linked: true, + account: sync_state(), + pages: HashMap::from([(1, first), (2, second)]), + media, + libraries: Vec::new(), + fulfillments: HashMap::new(), + valid_code: "12345678".to_owned(), + failures: VecDeque::new(), + calls: Vec::new(), + } + } +} + +/// A scripted Libby. +#[derive(Debug, Default)] +pub struct FakeApi { + state: Mutex, +} + +impl FakeApi { + /// The state, for arranging and asserting. + /// + /// # Panics + /// When a previous holder of the lock panicked. + pub fn state(&self) -> MutexGuard<'_, FakeState> { + match self.state.lock() { + Ok(state) => state, + Err(error) => panic!("fake api state poisoned: {error}"), + } + } + + /// Every call so far. + #[must_use] + pub fn calls(&self) -> Vec { + self.state().calls.clone() + } + + /// Forgets the calls so far, so a test can assert on what follows. + pub fn clear_calls(&self) { + self.state().calls.clear(); + } + + /// Makes the next call (whatever it is) fail with `error`. + pub fn fail_next(&self, error: libby::Error) { + self.state().failures.push_back(error); + } + + /// Records the call; returns the scripted failure, if one is due. + fn begin(&self, call: String) -> libby::Result> { + let mut state = self.state(); + state.calls.push(call); + match state.failures.pop_front() { + Some(error) => Err(error), + None => Ok(state), + } + } +} + +fn not_found(what: &str) -> libby::Error { + libby::Error::NotFound { + what: what.to_owned(), + } +} + +#[async_trait] +impl Api for FakeApi { + fn is_linked(&self) -> bool { + self.state().linked + } + + async fn sync(&self) -> libby::Result { + let state = self.begin("sync".to_owned())?; + if state.linked { + Ok(state.account.clone()) + } else { + Err(libby::Error::Unlinked) + } + } + + async fn redeem_code(&self, code: &str) -> libby::Result { + let mut state = self.begin(format!("redeem_code {code}"))?; + if code == state.valid_code { + state.linked = true; + Ok(state.account.clone()) + } else { + Err(libby::Error::Refused { + code: "upstream_failure".to_owned(), + explanation: "That code is not valid. Check it and try again.".to_owned(), + }) + } + } + + async fn clone_code(&self) -> libby::Result { + drop(self.begin("clone_code".to_owned())?); + Ok(fixture(r#"{"code":"87654321","expiry":1794744060}"#)) + } + + async fn find_libraries(&self, query: &str) -> libby::Result> { + let state = self.begin(format!("find_libraries {query}"))?; + Ok(state.libraries.clone()) + } + + async fn search(&self, library: &LibraryKey, query: &SearchQuery) -> libby::Result { + let page = query.current_page(); + let params = query + .to_params()? + .into_iter() + .map(|(key, value)| format!("{key}={value}")) + .collect::>() + .join(" "); + let state = self.begin(format!("search {library} {params}"))?; + Ok(state.pages.get(&page).cloned().unwrap_or_else(|| { + let mut empty: SearchPage = fixture(SEARCH_JSON); + empty.items.clear(); + empty.total_items = 0; + empty + })) + } + + async fn library_media(&self, library: &LibraryKey, title: &TitleId) -> libby::Result { + let state = self.begin(format!("library_media {library} {title}"))?; + state + .media + .get(title) + .cloned() + .ok_or_else(|| not_found("title")) + } + + async fn borrow( + &self, + card: &Card, + title: &TitleId, + kind: &MediaKind, + _options: BorrowOptions, + ) -> libby::Result { + let mut state = self.begin(format!("borrow {} {title}", card.id))?; + // A loan shaped like a real one: start from a fixture loan and make + // it about this title. + let mut loan = state + .account + .loans + .first() + .cloned() + .unwrap_or_else(|| sync_state().loans.swap_remove(0)); + let media = state.media.get(title); + loan.title_id = title.clone(); + loan.card_id = card.id.clone(); + loan.kind = kind.clone(); + loan.title = media.map_or_else(|| format!("Title {title}"), |media| media.title.clone()); + loan.first_creator_name = media.and_then(|media| media.first_creator_name.clone()); + loan.series = None; + loan.detailed_series = None; + state.account.holds.retain(|hold| &hold.title_id != title); + state.account.loans.push(loan.clone()); + Ok(loan) + } + + async fn renew(&self, card: &Card, loan: &Loan) -> libby::Result { + let mut state = self.begin(format!("renew {} {}", card.id, loan.title_id))?; + let Some(known) = state + .account + .loans + .iter_mut() + .find(|known| known.title_id == loan.title_id) + else { + return Err(not_found("loan")); + }; + known.expire_date = known + .expire_date + .checked_add(jiff::SignedDuration::from_hours(24 * 14)) + .unwrap_or(known.expire_date); + known.renewable_on = None; + Ok(known.clone()) + } + + async fn return_loan(&self, card: &CardId, title: &TitleId) -> libby::Result<()> { + let mut state = self.begin(format!("return_loan {card} {title}"))?; + state.account.loans.retain(|loan| &loan.title_id != title); + Ok(()) + } + + async fn place_hold(&self, card: &CardId, title: &TitleId) -> libby::Result { + let mut state = self.begin(format!("place_hold {card} {title}"))?; + let mut hold = state + .account + .holds + .iter() + .find(|hold| !hold.is_available) + .cloned() + .unwrap_or_else(|| sync_state().holds.swap_remove(1)); + let media = state.media.get(title); + hold.title_id = title.clone(); + hold.card_id = card.clone(); + hold.title = media.map_or_else(|| format!("Title {title}"), |media| media.title.clone()); + hold.first_creator_name = media.and_then(|media| media.first_creator_name.clone()); + if let Some(media) = media { + hold.kind = media.kind.clone(); + } + state.account.holds.push(hold.clone()); + Ok(hold) + } + + async fn suspend_hold(&self, card: &CardId, title: &TitleId, days: u32) -> libby::Result<()> { + let mut state = self.begin(format!("suspend_hold {card} {title} {days}"))?; + match state + .account + .holds + .iter_mut() + .find(|hold| &hold.title_id == title) + { + Some(hold) => { + hold.suspension_flag = Some(days > 0); + Ok(()) + } + None => Err(not_found("hold")), + } + } + + async fn cancel_hold(&self, card: &CardId, title: &TitleId) -> libby::Result<()> { + let mut state = self.begin(format!("cancel_hold {card} {title}"))?; + state.account.holds.retain(|hold| &hold.title_id != title); + Ok(()) + } + + async fn fulfill(&self, loan: &Loan, format: &FormatId) -> libby::Result { + let state = self.begin(format!("fulfill {} {format}", loan.title_id))?; + state + .fulfillments + .get(format.as_str()) + .cloned() + .ok_or_else(|| libby::Error::NotDownloadable { + format: format.clone(), + }) + } + + async fn cover_bytes(&self, url: &Url) -> libby::Result> { + drop(self.begin(format!("cover_bytes {url}"))?); + Err(not_found("cover")) + } +} + +// ── Fake queue and desktop ───────────────────────────────────────────────── + +/// A download queue that only writes down what it was asked. +#[derive(Debug, Default)] +pub struct FakeQueue { + calls: Mutex>, + specs: Mutex>, +} + +impl FakeQueue { + fn record(&self, call: String) { + if let Ok(mut calls) = self.calls.lock() { + calls.push(call); + } + } + + /// Every call so far ("enqueue 1000001 ebook-epub-open", "pause "). + #[must_use] + pub fn calls(&self) -> Vec { + self.calls + .lock() + .map(|calls| calls.clone()) + .unwrap_or_default() + } + + /// Every spec enqueued so far. + #[must_use] + pub fn specs(&self) -> Vec { + self.specs + .lock() + .map(|specs| specs.clone()) + .unwrap_or_default() + } +} + +impl DownloadQueue for FakeQueue { + fn enqueue(&self, spec: JobSpec) { + self.record(format!("enqueue {} {}", spec.title_id, spec.format_id)); + if let Ok(mut specs) = self.specs.lock() { + specs.push(spec); + } + } + + fn pause(&self, id: &JobId) { + self.record(format!("pause {id}")); + } + + fn resume(&self, id: &JobId) { + self.record(format!("resume {id}")); + } + + fn cancel(&self, id: &JobId) { + self.record(format!("cancel {id}")); + } + + fn retry(&self, id: &JobId) { + self.record(format!("retry {id}")); + } + + fn remove(&self, id: &JobId) { + self.record(format!("remove {id}")); + } + + fn clear_finished(&self) { + self.record("clear_finished".to_owned()); + } +} + +/// A desktop that only writes down what it was asked. +#[derive(Debug, Default)] +pub struct FakeSystem { + calls: Mutex>, + /// When set, every call fails with this message. + pub fail_with: Mutex>, +} + +impl FakeSystem { + fn record(&self, call: String) -> Result<(), String> { + if let Ok(mut calls) = self.calls.lock() { + calls.push(call); + } + match self.fail_with.lock() { + Ok(failure) => failure.clone().map_or(Ok(()), Err), + Err(_) => Ok(()), + } + } + + /// Every call so far ("open_url https://…", "copy …"). + #[must_use] + pub fn calls(&self) -> Vec { + self.calls + .lock() + .map(|calls| calls.clone()) + .unwrap_or_default() + } +} + +impl System for FakeSystem { + fn open_url(&self, url: &str) -> Result<(), String> { + self.record(format!("open_url {url}")) + } + + fn open_path(&self, path: &Path) -> Result<(), String> { + self.record(format!("open_path {}", path.display())) + } + + fn copy(&self, text: &str) -> Result<(), String> { + self.record(format!("copy {text}")) + } +} + +// ── Harness ──────────────────────────────────────────────────────────────── + +/// The app, wired to fakes, with a virtual screen. +#[derive(Debug)] +pub struct Harness { + /// The app under test. + pub app: App, + /// The fake Libby. + pub api: Arc, + /// The fake download queue. + pub queue: Arc, + /// The fake desktop. + pub system: Arc, + terminal: Terminal, + now: Timestamp, + instant: Instant, +} + +impl Harness { + /// A paired device showing the shelf, synced, on a 100×30 screen. + pub async fn new() -> Self { + Self::with(|_| {}).await + } + + /// A device that has never been paired, showing setup. + pub async fn unlinked() -> Self { + Self::with(|state| state.linked = false).await + } + + /// Like [`Harness::new`], after `arrange` has edited the fake Libby. + pub async fn with(arrange: impl FnOnce(&mut FakeState)) -> Self { + Self::build(arrange, |_| {}, 100, 30).await + } + + /// Full control: arrange the fake Libby and the shared state (config, + /// theme, downloads), and pick the screen size. + /// + /// # Panics + /// When the virtual terminal cannot be created (it always can). + pub async fn build( + arrange: impl FnOnce(&mut FakeState), + configure: impl FnOnce(&mut Shared), + width: u16, + height: u16, + ) -> Self { + crate::i18n::init(Some("en-US")); + let api = Arc::new(FakeApi::default()); + arrange(&mut api.state()); + let queue = Arc::new(FakeQueue::default()); + let system = Arc::new(FakeSystem::default()); + let services = Services { + api: Arc::clone(&api) as Arc, + queue: Arc::clone(&queue) as Arc, + system: Arc::clone(&system) as Arc, + }; + let mut shared = Shared { + config: Config::default(), + theme: Theme::resolve("dark", ColorDepth::TrueColor, false), + symbols: Symbols::pick(false).clone(), + keymap: Keymap::default(), + account: crate::app::Account::default(), + downloads: crate::app::Downloads::default(), + covers: Covers::new(false), + busy: std::collections::BTreeSet::new(), + now: now(), + frame: 0, + }; + configure(&mut shared); + let terminal = match Terminal::new(TestBackend::new(width, height)) { + Ok(terminal) => terminal, + Err(error) => panic!("test terminal: {error}"), + }; + let mut harness = Self { + app: App::new(shared, services), + api, + queue, + system, + terminal, + now: now(), + instant: Instant::now(), + }; + let tasks = harness.app.start(); + harness.run(tasks).await; + harness + } + + /// Awaits `tasks` and everything they lead to. + async fn run(&mut self, tasks: Vec) { + let mut pending: VecDeque = tasks.into(); + while let Some(task) = pending.pop_front() { + let action = task.await; + pending.extend(self.app.dispatch(action)); + } + } + + /// Feeds one action through the app and awaits everything it starts. + pub async fn dispatch(&mut self, action: Action) { + let tasks = self.app.dispatch(action); + self.run(tasks).await; + } + + /// Feeds one action through the app but leaves the work it started + /// unfinished, to look at loading states. [`Harness::finish`] runs it. + #[must_use] + pub fn dispatch_pending(&mut self, action: Action) -> Vec { + self.app.dispatch(action) + } + + /// Completes work held back by [`Harness::dispatch_pending`]. + pub async fn finish(&mut self, tasks: Vec) { + self.run(tasks).await; + } + + /// Presses a key written in the keymap's notation: `j`, `enter`, `esc`, + /// `ctrl-p`, `shift-tab`, `G`, `space`, `f5`. + /// + /// # Panics + /// When `chord` is not valid notation. + pub async fn press(&mut self, chord: &str) { + self.dispatch(Action::Event(Event::Key(key(chord)))).await; + } + + /// Presses several keys in order. + pub async fn keys(&mut self, chords: &[&str]) { + for chord in chords { + self.press(chord).await; + } + } + + /// Like [`Harness::press`], leaving the work it started unfinished. + /// + /// # Panics + /// When `chord` is not valid notation. + #[must_use] + pub fn press_pending(&mut self, chord: &str) -> Vec { + self.dispatch_pending(Action::Event(Event::Key(key(chord)))) + } + + /// Types `text` one character at a time. + pub async fn type_text(&mut self, text: &str) { + for ch in text.chars() { + let event = KeyEvent::new( + crossterm::event::KeyCode::Char(ch), + crossterm::event::KeyModifiers::NONE, + ); + self.dispatch(Action::Event(Event::Key(event))).await; + } + } + + /// Pastes `text` (bracketed paste). + pub async fn paste(&mut self, text: &str) { + self.dispatch(Action::Event(Event::Paste(text.to_owned()))) + .await; + } + + /// Sends a mouse event. + pub async fn mouse(&mut self, event: MouseEvent) { + self.dispatch(Action::Event(Event::Mouse(event))).await; + } + + /// Runs a command directly, whatever it is bound to. + pub async fn command(&mut self, command: Command) { + self.dispatch(Action::Command(command)).await; + } + + /// Moves the clock forward and ticks. + pub async fn advance(&mut self, by: Duration) { + self.instant += by; + self.now = self.now.checked_add(by).unwrap_or(self.now); + let (now, instant) = (self.now, self.instant); + self.dispatch(Action::Tick { now, instant }).await; + } + + /// Delivers a download-engine event, as the engine would. + pub async fn engine(&mut self, event: download::Event) { + self.dispatch(Action::Engine(event)).await; + } + + /// Adds a job to the queue in `state`, as if the engine had reported it. + /// Returns the job for further events. + pub async fn job(&mut self, loan_index: usize, state: JobState) -> Job { + let loans = sync_state().loans; + let loan = &loans[loan_index % loans.len()]; + let id = match JobId::new(format!("job-{loan_index}")) { + Ok(id) => id, + Err(error) => panic!("job id: {error}"), + }; + let mut job = Job::new(JobSpec { + id, + title_id: loan.title_id.as_str().to_owned(), + card_id: loan.card_id.as_str().to_owned(), + title: loan.title.clone(), + author: loan.first_creator_name.clone(), + series: None, + series_index: None, + year: None, + kind: download::FileKind::Epub, + format_id: "ebook-epub-open".to_owned(), + cover_url: None, + description: None, + publisher: None, + language: None, + isbn: None, + subjects: Vec::new(), + }); + job.created_at = now(); + job.updated_at = now(); + self.engine(download::Event::Added(job.clone())).await; + if state != JobState::Queued { + job.state = state; + self.engine(download::Event::Changed(job.clone())).await; + } + job + } + + /// Resizes the virtual screen. + pub async fn resize(&mut self, width: u16, height: u16) { + self.terminal.backend_mut().resize(width, height); + self.dispatch(Action::Event(Event::Resize(width, height))) + .await; + } + + /// Draws a frame and returns it as text, one line per row, trailing + /// spaces trimmed. This is what snapshot tests compare. + /// + /// # Panics + /// When drawing fails (the test backend never does). + pub fn screen(&mut self) -> String { + let app = &mut self.app; + if let Err(error) = self.terminal.draw(|frame| { + // Covers are disabled in the harness: nothing to fetch. + drop(app.render(frame)); + }) { + panic!("draw failed: {error}"); + } + let buffer = self.terminal.backend().buffer(); + let width = usize::from(buffer.area.width); + let mut out = String::new(); + for row in buffer.content.chunks(width) { + let mut line = String::new(); + let mut skip = 0; + for cell in row { + // A wide character owns the cells after it; they hold + // filler that is not on screen. + if skip > 0 { + skip -= 1; + continue; + } + let symbol = cell.symbol(); + line.push_str(symbol); + skip = crate::ui::text::width(symbol).saturating_sub(1); + } + out.push_str(line.trim_end()); + out.push('\n'); + } + out + } + + /// The buffer of the last frame drawn by [`Harness::screen`], for + /// asserting on styles. + #[must_use] + pub fn buffer(&self) -> &ratatui::buffer::Buffer { + self.terminal.backend().buffer() + } + + /// The messages of the visible toasts, newest last. + #[must_use] + pub fn toasts(&self) -> Vec { + self.app + .toasts() + .map(|toast: &Toast| toast.message.clone()) + .collect() + } + + /// The shared state. + #[must_use] + pub const fn shared(&self) -> &Shared { + self.app.shared() + } +} + +/// A key press from the keymap's notation. +/// +/// # Panics +/// When `chord` is not valid notation. +#[must_use] +pub fn key(chord: &str) -> KeyEvent { + let chord = match Chord::parse(chord) { + Ok(chord) => chord, + Err(error) => panic!("bad key in test: {error}"), + }; + KeyEvent { + code: chord.code, + modifiers: chord.modifiers, + kind: KeyEventKind::Press, + state: KeyEventState::NONE, + } +} + +/// A finished job's state, for [`Harness::job`]. +#[must_use] +pub fn done(path: &str, bytes: u64) -> JobState { + JobState::Done { + path: PathBuf::from(path), + bytes, + sha256: "0".repeat(64), + } +} diff --git a/crates/libbui/src/theme.rs b/crates/libbui/src/theme.rs new file mode 100644 index 0000000..a552342 --- /dev/null +++ b/crates/libbui/src/theme.rs @@ -0,0 +1,641 @@ +//! Colours and glyphs. Every style in the UI comes from here. +//! +//! Screens ask for *roles* (`theme.accent`, `theme.danger`) and never name a +//! colour. Two rules hold for every theme: +//! +//! 1. **Never colour alone.** State is always carried by a glyph or a word as +//! well ([`Symbols`]); the `mono` theme proves it by having no colour. +//! 2. **Degrade, don't break.** Truecolour themes fall back to the 16 ANSI +//! colours when the terminal can't do better, and `NO_COLOR` selects `mono`. + +use ratatui::style::{Color, Modifier, Style}; +use ratatui::widgets::BorderType; + +/// How much colour the terminal can show. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ColorDepth { + /// `NO_COLOR` is set, or the output is not a colour terminal. + None, + /// The 16 ANSI colours, which follow the user's terminal palette. + Ansi16, + /// 24-bit colour. + TrueColor, +} + +impl ColorDepth { + /// Detects depth from the environment (`NO_COLOR`, `COLORTERM`, `TERM`). + /// + /// `lookup` is the environment accessor, injected so tests don't touch the + /// process environment. + #[must_use] + pub fn detect(lookup: impl Fn(&str) -> Option) -> Self { + // https://no-color.org: any non-empty value disables colour. + if lookup("NO_COLOR").is_some_and(|v| !v.is_empty()) { + return Self::None; + } + let term = lookup("TERM").unwrap_or_default(); + if term == "dumb" { + return Self::None; + } + let colorterm = lookup("COLORTERM").unwrap_or_default(); + if colorterm.contains("truecolor") || colorterm.contains("24bit") || term.contains("direct") + { + return Self::TrueColor; + } + Self::Ansi16 + } +} + +/// A named theme. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ThemeName { + /// Warm paper-and-ink dark theme (truecolour). + Dark, + /// The same palette for light terminals (truecolour). + Light, + /// Only the 16 ANSI colours: inherits the terminal's own palette. + Ansi, + /// Maximum contrast, bold focus, no dim text. + HighContrast, + /// No colour at all; structure comes from weight, reverse video and glyphs. + Mono, +} + +impl ThemeName { + /// Every theme, in the order the settings screen lists them. + pub const ALL: [Self; 5] = [ + Self::Dark, + Self::Light, + Self::Ansi, + Self::HighContrast, + Self::Mono, + ]; + + /// The name used in `config.toml` and `--theme`. + #[must_use] + pub const fn id(self) -> &'static str { + match self { + Self::Dark => "dark", + Self::Light => "light", + Self::Ansi => "ansi", + Self::HighContrast => "high-contrast", + Self::Mono => "mono", + } + } + + /// Parses a config/flag value. `"auto"` is handled by [`Theme::resolve`]. + #[must_use] + pub fn parse(raw: &str) -> Option { + Self::ALL.into_iter().find(|name| name.id() == raw) + } +} + +/// The styles for one theme, by role. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Theme { + /// Which theme this is. + pub name: ThemeName, + /// Body text. + pub text: Style, + /// Secondary text: labels, metadata, hints. + pub muted: Style, + /// Tertiary text and decorative rules. Never used for information. + pub faint: Style, + /// Titles and the thing being emphasised. + pub strong: Style, + /// Brand/interactive accent: active tab, focused border, key caps. + pub accent: Style, + /// The selected row in a focused list. + pub selected: Style, + /// The selected row in a list that does not have focus. + pub selected_inactive: Style, + /// Borders of unfocused panes. + pub border: Style, + /// Borders of the focused pane. + pub border_focused: Style, + /// Success / available. + pub success: Style, + /// Warning / expiring soon / waitlist. + pub warning: Style, + /// Error / destructive. + pub danger: Style, + /// Informational highlight. + pub info: Style, + /// Key caps in hints (`[q]`). + pub key: Style, + /// Characters matched by a fuzzy or search query. + pub matched: Style, + /// Filled part of gauges and progress bars. + pub gauge: Style, + /// Empty part of gauges and progress bars. + pub gauge_track: Style, + /// Per-kind accents so a shelf can be scanned by shape *and* hue. + pub ebook: Style, + /// See [`Theme::ebook`]. + pub audiobook: Style, + /// See [`Theme::ebook`]. + pub magazine: Style, + /// Border drawn around unfocused panes. + pub border_type: BorderType, + /// Border drawn around the focused pane. Differs in *shape* in themes + /// where colour can't carry focus. + pub border_type_focused: BorderType, +} + +impl Theme { + /// Picks a theme for a config/flag value and the terminal's capabilities. + /// + /// `requested` of `"auto"` (or anything unrecognised by [`ThemeName::parse`], + /// which the caller should have rejected earlier) follows the terminal: + /// `mono` without colour, `ansi` with 16 colours, and `dark`/`light` by + /// `is_light_background` with truecolour. An explicit truecolour theme on + /// a terminal that can't show it steps down rather than rendering wrong + /// colours. + #[must_use] + pub fn resolve(requested: &str, depth: ColorDepth, is_light_background: bool) -> Self { + let wanted = ThemeName::parse(requested); + let name = match (depth, wanted) { + (ColorDepth::None, _) => ThemeName::Mono, + (_, Some(ThemeName::Mono)) => ThemeName::Mono, + (ColorDepth::Ansi16, Some(ThemeName::HighContrast)) => ThemeName::HighContrast, + (ColorDepth::Ansi16, _) => ThemeName::Ansi, + (ColorDepth::TrueColor, Some(name)) => name, + (ColorDepth::TrueColor, None) if is_light_background => ThemeName::Light, + (ColorDepth::TrueColor, None) => ThemeName::Dark, + }; + Self::named(name) + } + + /// The theme called `name`. + #[must_use] + pub fn named(name: ThemeName) -> Self { + match name { + ThemeName::Dark => Self::dark(), + ThemeName::Light => Self::light(), + ThemeName::Ansi => Self::ansi(), + ThemeName::HighContrast => Self::high_contrast(), + ThemeName::Mono => Self::mono(), + } + } + + /// A reading-lamp palette: warm ink on a dark desk. + fn dark() -> Self { + let paper = Color::Rgb(0xe8, 0xe0, 0xd0); + let pencil = Color::Rgb(0xa3, 0x9a, 0x8a); + let smudge = Color::Rgb(0x6b, 0x64, 0x58); + let lamp = Color::Rgb(0xf2, 0xb7, 0x5c); + let moss = Color::Rgb(0x9c, 0xc8, 0x8a); + let rust = Color::Rgb(0xf0, 0x8a, 0x6e); + let sky = Color::Rgb(0x8c, 0xb8, 0xe0); + let plum = Color::Rgb(0xc9, 0xa0, 0xdc); + let shelf = Color::Rgb(0x3a, 0x33, 0x2b); + Self::from_palette( + ThemeName::Dark, + Palette { + text: paper, + muted: pencil, + faint: smudge, + accent: lamp, + success: moss, + warning: lamp, + danger: rust, + info: sky, + ebook: sky, + audiobook: plum, + magazine: moss, + selection_bg: shelf, + selection_fg: paper, + on_accent: Color::Rgb(0x1c, 0x18, 0x14), + }, + ) + } + + /// The same palette, re-inked for a light background. + fn light() -> Self { + let ink = Color::Rgb(0x2b, 0x26, 0x20); + let pencil = Color::Rgb(0x5f, 0x57, 0x4b); + let smudge = Color::Rgb(0x8f, 0x86, 0x78); + let amber = Color::Rgb(0x9a, 0x5b, 0x00); + let moss = Color::Rgb(0x2f, 0x6b, 0x2a); + let rust = Color::Rgb(0xa8, 0x32, 0x1c); + let sky = Color::Rgb(0x1f, 0x5a, 0x94); + let plum = Color::Rgb(0x7a, 0x3a, 0x96); + let wash = Color::Rgb(0xe9, 0xdf, 0xcc); + Self::from_palette( + ThemeName::Light, + Palette { + text: ink, + muted: pencil, + faint: smudge, + accent: amber, + success: moss, + warning: amber, + danger: rust, + info: sky, + ebook: sky, + audiobook: plum, + magazine: moss, + selection_bg: wash, + selection_fg: ink, + on_accent: Color::Rgb(0xff, 0xfb, 0xf2), + }, + ) + } + + fn from_palette(name: ThemeName, p: Palette) -> Self { + let fg = |color| Style::new().fg(color); + Self { + name, + text: fg(p.text), + muted: fg(p.muted), + faint: fg(p.faint), + strong: fg(p.text).add_modifier(Modifier::BOLD), + accent: fg(p.accent).add_modifier(Modifier::BOLD), + selected: Style::new() + .fg(p.on_accent) + .bg(p.accent) + .add_modifier(Modifier::BOLD), + selected_inactive: Style::new().fg(p.selection_fg).bg(p.selection_bg), + border: fg(p.faint), + border_focused: fg(p.accent), + success: fg(p.success), + warning: fg(p.warning), + danger: fg(p.danger).add_modifier(Modifier::BOLD), + info: fg(p.info), + key: fg(p.accent).add_modifier(Modifier::BOLD), + matched: fg(p.accent).add_modifier(Modifier::BOLD | Modifier::UNDERLINED), + gauge: fg(p.accent), + gauge_track: fg(p.faint), + ebook: fg(p.ebook), + audiobook: fg(p.audiobook), + magazine: fg(p.magazine), + border_type: BorderType::Rounded, + border_type_focused: BorderType::Rounded, + } + } + + /// Sixteen ANSI colours only, so the user's terminal palette shows through. + fn ansi() -> Self { + let fg = |color| Style::new().fg(color); + Self { + name: ThemeName::Ansi, + text: Style::new(), + muted: Style::new().add_modifier(Modifier::DIM), + faint: fg(Color::DarkGray), + strong: Style::new().add_modifier(Modifier::BOLD), + accent: fg(Color::Yellow).add_modifier(Modifier::BOLD), + selected: Style::new().add_modifier(Modifier::REVERSED | Modifier::BOLD), + selected_inactive: Style::new().add_modifier(Modifier::UNDERLINED), + border: fg(Color::DarkGray), + border_focused: fg(Color::Yellow), + success: fg(Color::Green), + warning: fg(Color::Yellow), + danger: fg(Color::Red).add_modifier(Modifier::BOLD), + info: fg(Color::Cyan), + key: fg(Color::Yellow).add_modifier(Modifier::BOLD), + matched: fg(Color::Yellow).add_modifier(Modifier::BOLD | Modifier::UNDERLINED), + gauge: fg(Color::Yellow), + gauge_track: fg(Color::DarkGray), + ebook: fg(Color::Cyan), + audiobook: fg(Color::Magenta), + magazine: fg(Color::Green), + border_type: BorderType::Rounded, + border_type_focused: BorderType::Rounded, + } + } + + /// Bright on default background, nothing dim, and focus shown by a heavy + /// border as well as colour. + fn high_contrast() -> Self { + let fg = |color| Style::new().fg(color).add_modifier(Modifier::BOLD); + Self { + name: ThemeName::HighContrast, + text: Style::new().fg(Color::White), + muted: Style::new().fg(Color::White), + faint: Style::new().fg(Color::Gray), + strong: fg(Color::White), + accent: fg(Color::LightYellow), + selected: Style::new() + .fg(Color::Black) + .bg(Color::LightYellow) + .add_modifier(Modifier::BOLD), + selected_inactive: Style::new() + .fg(Color::White) + .add_modifier(Modifier::UNDERLINED | Modifier::BOLD), + border: Style::new().fg(Color::Gray), + border_focused: fg(Color::LightYellow), + success: fg(Color::LightGreen), + warning: fg(Color::LightYellow), + danger: fg(Color::LightRed), + info: fg(Color::LightCyan), + key: fg(Color::LightYellow), + matched: Style::new() + .fg(Color::LightYellow) + .add_modifier(Modifier::BOLD | Modifier::UNDERLINED), + gauge: fg(Color::LightYellow), + gauge_track: Style::new().fg(Color::Gray), + ebook: fg(Color::LightCyan), + audiobook: fg(Color::LightMagenta), + magazine: fg(Color::LightGreen), + border_type: BorderType::Plain, + border_type_focused: BorderType::Thick, + } + } + + /// No colour. Weight, underline and reverse video carry everything. + fn mono() -> Self { + let plain = Style::new(); + let bold = plain.add_modifier(Modifier::BOLD); + Self { + name: ThemeName::Mono, + text: plain, + muted: plain, + faint: plain.add_modifier(Modifier::DIM), + strong: bold, + accent: bold, + selected: plain.add_modifier(Modifier::REVERSED | Modifier::BOLD), + selected_inactive: plain.add_modifier(Modifier::UNDERLINED), + border: plain.add_modifier(Modifier::DIM), + border_focused: bold, + success: plain, + warning: bold, + danger: bold, + info: plain, + key: bold, + matched: plain.add_modifier(Modifier::BOLD | Modifier::UNDERLINED), + gauge: bold, + gauge_track: plain.add_modifier(Modifier::DIM), + ebook: plain, + audiobook: plain, + magazine: plain, + border_type: BorderType::Plain, + border_type_focused: BorderType::Double, + } + } + + /// The border style and shape for a pane, by focus. + #[must_use] + pub fn pane_border(&self, focused: bool) -> (Style, BorderType) { + if focused { + (self.border_focused, self.border_type_focused) + } else { + (self.border, self.border_type) + } + } +} + +struct Palette { + text: Color, + muted: Color, + faint: Color, + accent: Color, + success: Color, + warning: Color, + danger: Color, + info: Color, + ebook: Color, + audiobook: Color, + magazine: Color, + selection_bg: Color, + selection_fg: Color, + on_accent: Color, +} + +/// The glyphs that carry state alongside colour. +/// +/// The Unicode set sticks to characters with unambiguous single-cell width in +/// common monospace fonts (no emoji, no Nerd Font glyphs). The ASCII set is +/// for terminals and fonts that can't be trusted with even that. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Symbols { + /// Marks the selected row. + pub cursor: &'static str, + /// Ebook. + pub ebook: &'static str, + /// Audiobook. + pub audiobook: &'static str, + /// Magazine. + pub magazine: &'static str, + /// Available now / success. + pub ok: &'static str, + /// Waitlist / warning. + pub warn: &'static str, + /// Failure. + pub error: &'static str, + /// Informational. + pub info: &'static str, + /// Downloaded to disk. + pub downloaded: &'static str, + /// In progress. + pub downloading: &'static str, + /// Paused. + pub paused: &'static str, + /// Waiting in a queue or on hold. + pub queued: &'static str, + /// Separator between inline facts. + pub dot: &'static str, + /// Text was cut short. + pub ellipsis: &'static str, + /// A filled star, for ratings. + pub star: &'static str, + /// An empty star. + pub star_empty: &'static str, + /// Filled gauge cell. + pub bar_full: &'static str, + /// Empty gauge cell. + pub bar_empty: &'static str, + /// Spinner frames, cycled while something loads. + pub spinner: &'static [&'static str], + /// Scrollbar thumb. + pub scroll_thumb: &'static str, + /// Scrollbar track. + pub scroll_track: &'static str, + /// Points at a submenu or the next step. + pub arrow: &'static str, + /// A checked box. + pub checked: &'static str, + /// An unchecked box. + pub unchecked: &'static str, +} + +impl Symbols { + /// Unicode glyphs. + pub const UNICODE: Self = Self { + cursor: "▌", + ebook: "▤", + audiobook: "♪", + magazine: "▥", + ok: "✓", + warn: "!", + error: "✗", + info: "i", + downloaded: "↓", + downloading: "⇣", + paused: "‖", + queued: "…", + dot: "·", + ellipsis: "…", + star: "★", + star_empty: "☆", + bar_full: "█", + bar_empty: "░", + spinner: &["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"], + scroll_thumb: "┃", + scroll_track: "│", + arrow: "›", + checked: "■", + unchecked: "□", + }; + + /// Seven-bit ASCII only. + pub const ASCII: Self = Self { + cursor: ">", + ebook: "B", + audiobook: "A", + magazine: "M", + ok: "+", + warn: "!", + error: "x", + info: "i", + downloaded: "v", + downloading: "~", + paused: "=", + queued: ".", + dot: "-", + ellipsis: "...", + star: "*", + star_empty: ".", + bar_full: "#", + bar_empty: "-", + spinner: &["|", "/", "-", "\\"], + scroll_thumb: "#", + scroll_track: "|", + arrow: ">", + checked: "[x]", + unchecked: "[ ]", + }; + + /// The set for the user's `ascii` preference. + #[must_use] + pub const fn pick(ascii: bool) -> &'static Self { + if ascii { &Self::ASCII } else { &Self::UNICODE } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn env(pairs: &'static [(&'static str, &'static str)]) -> impl Fn(&str) -> Option { + move |key| { + pairs + .iter() + .find(|(name, _)| *name == key) + .map(|(_, value)| (*value).to_owned()) + } + } + + #[test] + fn no_color_wins_over_everything() { + let depth = ColorDepth::detect(env(&[("NO_COLOR", "1"), ("COLORTERM", "truecolor")])); + assert_eq!(depth, ColorDepth::None); + assert_eq!(Theme::resolve("dark", depth, false).name, ThemeName::Mono); + } + + #[test] + fn an_empty_no_color_is_ignored() { + let depth = ColorDepth::detect(env(&[("NO_COLOR", ""), ("COLORTERM", "truecolor")])); + assert_eq!(depth, ColorDepth::TrueColor); + } + + #[test] + fn auto_follows_the_terminal() { + let auto = |depth, light| Theme::resolve("auto", depth, light).name; + assert_eq!(auto(ColorDepth::TrueColor, false), ThemeName::Dark); + assert_eq!(auto(ColorDepth::TrueColor, true), ThemeName::Light); + assert_eq!(auto(ColorDepth::Ansi16, false), ThemeName::Ansi); + assert_eq!(auto(ColorDepth::None, false), ThemeName::Mono); + } + + #[test] + fn truecolor_themes_step_down_on_a_16_colour_terminal() { + assert_eq!( + Theme::resolve("dark", ColorDepth::Ansi16, false).name, + ThemeName::Ansi + ); + } + + #[test] + fn mono_uses_no_colour_at_all() { + let theme = Theme::named(ThemeName::Mono); + for style in [ + theme.text, + theme.muted, + theme.accent, + theme.selected, + theme.danger, + theme.success, + theme.border_focused, + ] { + assert_eq!(style.fg, None); + assert_eq!(style.bg, None); + } + } + + #[test] + fn focus_is_never_carried_by_colour_alone() { + // Where the border colours can't differ, the border shape must. + for name in [ThemeName::Mono, ThemeName::HighContrast] { + let theme = Theme::named(name); + assert_ne!(theme.border_type, theme.border_type_focused, "{name:?}"); + } + // And selection is always more than a foreground colour. + for name in ThemeName::ALL { + let theme = Theme::named(name); + let selected = theme.selected; + assert!( + selected.bg.is_some() || selected.add_modifier.contains(Modifier::REVERSED), + "{name:?}" + ); + } + } + + #[test] + fn ascii_symbols_are_ascii() { + let s = &Symbols::ASCII; + let all = [ + s.cursor, + s.ebook, + s.audiobook, + s.magazine, + s.ok, + s.warn, + s.error, + s.info, + s.downloaded, + s.downloading, + s.paused, + s.queued, + s.dot, + s.ellipsis, + s.star, + s.star_empty, + s.bar_full, + s.bar_empty, + s.scroll_thumb, + s.scroll_track, + s.arrow, + s.checked, + s.unchecked, + ]; + assert!(all.iter().chain(s.spinner).all(|glyph| glyph.is_ascii())); + } + + #[test] + fn theme_ids_round_trip() { + for name in ThemeName::ALL { + assert_eq!(ThemeName::parse(name.id()), Some(name)); + } + assert_eq!(ThemeName::parse("auto"), None); + } +} diff --git a/crates/libbui/src/tui.rs b/crates/libbui/src/tui.rs new file mode 100644 index 0000000..3e90071 --- /dev/null +++ b/crates/libbui/src/tui.rs @@ -0,0 +1,230 @@ +//! Terminal ownership: entering and leaving the alternate screen, and the +//! stream of terminal events. +//! +//! The one invariant: **the user always gets their terminal back** — on a +//! clean exit, on an error, on a panic, and across Ctrl-Z. [`Tui`] is a guard; +//! dropping it restores the terminal, and [`Tui::enter`] installs a panic hook +//! that restores it before the panic message prints. + +use std::io::{self, Stdout, stdout}; + +use crossterm::event::{ + DisableBracketedPaste, DisableMouseCapture, EnableBracketedPaste, EnableMouseCapture, + Event as CrosstermEvent, EventStream, KeyEvent, KeyEventKind, MouseEvent, +}; +use crossterm::terminal::{ + BeginSynchronizedUpdate, EndSynchronizedUpdate, EnterAlternateScreen, LeaveAlternateScreen, + disable_raw_mode, enable_raw_mode, +}; +use crossterm::{cursor, execute, queue}; +use futures_util::StreamExt; +use ratatui::backend::CrosstermBackend; +use ratatui::{Frame, Terminal}; + +/// A terminal event the app cares about. +/// +/// Key *release* and *repeat* events (sent by terminals speaking the kitty +/// keyboard protocol, and by Windows) are dropped here so no screen can act +/// twice on one keystroke. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Event { + /// A key was pressed. + Key(KeyEvent), + /// The mouse did something (only when mouse capture is on). + Mouse(MouseEvent), + /// Text arrived as a bracketed paste: insert it, never interpret it as keys. + Paste(String), + /// The terminal is now this many columns × rows. + Resize(u16, u16), + /// The terminal window gained focus. + FocusGained, + /// The terminal window lost focus. + FocusLost, +} + +impl Event { + /// Converts a raw crossterm event, dropping the ones nothing should see. + #[must_use] + pub fn from_crossterm(event: CrosstermEvent) -> Option { + match event { + CrosstermEvent::Key(key) if key.kind == KeyEventKind::Press => Some(Self::Key(key)), + CrosstermEvent::Key(_) => None, + CrosstermEvent::Mouse(mouse) => Some(Self::Mouse(mouse)), + CrosstermEvent::Paste(text) => Some(Self::Paste(text)), + CrosstermEvent::Resize(cols, rows) => Some(Self::Resize(cols, rows)), + CrosstermEvent::FocusGained => Some(Self::FocusGained), + CrosstermEvent::FocusLost => Some(Self::FocusLost), + } + } +} + +/// What to switch on when entering the TUI. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Options { + /// Capture mouse clicks and scrolling. Off means the terminal keeps its + /// native text selection. + pub mouse: bool, +} + +/// The terminal, owned for the life of the UI. +#[derive(Debug)] +pub struct Tui { + terminal: Terminal>, + events: EventStream, + options: Options, +} + +impl Tui { + /// Takes over the terminal: raw mode, alternate screen, bracketed paste, + /// and mouse capture if asked for. + /// + /// Anything that must query the terminal over stdin/stdout (image protocol + /// detection, background colour) has to happen *before* this. + pub fn enter(options: Options) -> io::Result { + install_panic_hook(options); + enter_modes(options)?; + let terminal = Terminal::new(CrosstermBackend::new(stdout()))?; + Ok(Self { + terminal, + events: EventStream::new(), + options, + }) + } + + /// Draws one frame inside a synchronized update, so terminals that support + /// it never show a half-painted screen. + pub fn draw(&mut self, render: impl FnOnce(&mut Frame<'_>)) -> io::Result<()> { + queue!(stdout(), BeginSynchronizedUpdate)?; + let drawn = self.terminal.draw(render).map(|_| ()); + // Always close the update, even when drawing failed, or the terminal + // stays frozen. + let ended = execute!(stdout(), EndSynchronizedUpdate); + drawn.and(ended) + } + + /// The next terminal event. `None` means stdin closed: time to leave. + pub async fn next_event(&mut self) -> Option> { + loop { + match self.events.next().await? { + Ok(raw) => { + if let Some(event) = Event::from_crossterm(raw) { + return Some(Ok(event)); + } + } + Err(error) => return Some(Err(error)), + } + } + } + + /// Forgets what is on screen so the next draw repaints everything. + pub fn clear(&mut self) -> io::Result<()> { + self.terminal.clear() + } + + /// The current size as columns × rows. + pub fn size(&self) -> io::Result<(u16, u16)> { + let size = self.terminal.size()?; + Ok((size.width, size.height)) + } + + /// Hands the terminal back to the shell and stops the process (Ctrl-Z), + /// then takes the terminal over again when the shell resumes it. + #[cfg(unix)] + pub fn suspend(&mut self) -> io::Result<()> { + leave_modes(self.options)?; + // SIGTSTP stops this whole process; execution continues on the line + // after this one when the shell sends SIGCONT (`fg`). + let stopped = std::process::Command::new("kill") + .args(["-TSTP", &std::process::id().to_string()]) + .status(); + enter_modes(self.options)?; + self.terminal.clear()?; + stopped.map(|_| ()) + } + + /// Suspending is a Unix job-control idea; elsewhere it does nothing. + #[cfg(not(unix))] + pub fn suspend(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl Drop for Tui { + fn drop(&mut self) { + // Nothing useful can be done with an error while tearing down. + let _ = leave_modes(self.options); + } +} + +fn enter_modes(options: Options) -> io::Result<()> { + enable_raw_mode()?; + execute!( + stdout(), + EnterAlternateScreen, + EnableBracketedPaste, + cursor::Hide + )?; + if options.mouse { + execute!(stdout(), EnableMouseCapture)?; + } + Ok(()) +} + +fn leave_modes(options: Options) -> io::Result<()> { + // Attempt every step even if an earlier one fails: a half-restored + // terminal is worse than a reported error. + let mouse = if options.mouse { + execute!(stdout(), DisableMouseCapture) + } else { + Ok(()) + }; + let screen = execute!( + stdout(), + EndSynchronizedUpdate, + DisableBracketedPaste, + LeaveAlternateScreen, + cursor::Show + ); + let raw = disable_raw_mode(); + mouse.and(screen).and(raw) +} + +fn install_panic_hook(options: Options) { + let previous = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |info| { + let _ = leave_modes(options); + previous(info); + })); +} + +#[cfg(test)] +mod tests { + use crossterm::event::{KeyCode, KeyEventState, KeyModifiers}; + + use super::*; + + fn key(kind: KeyEventKind) -> CrosstermEvent { + CrosstermEvent::Key(KeyEvent { + code: KeyCode::Char('j'), + modifiers: KeyModifiers::NONE, + kind, + state: KeyEventState::NONE, + }) + } + + #[test] + fn only_key_presses_get_through() { + assert!(matches!( + Event::from_crossterm(key(KeyEventKind::Press)), + Some(Event::Key(_)) + )); + assert_eq!(Event::from_crossterm(key(KeyEventKind::Release)), None); + assert_eq!(Event::from_crossterm(key(KeyEventKind::Repeat)), None); + } + + #[test] + fn paste_arrives_whole() { + let pasted = Event::from_crossterm(CrosstermEvent::Paste("dune\nq".to_owned())); + assert_eq!(pasted, Some(Event::Paste("dune\nq".to_owned()))); + } +} diff --git a/crates/libbui/src/ui/cover.rs b/crates/libbui/src/ui/cover.rs new file mode 100644 index 0000000..77a0a65 --- /dev/null +++ b/crates/libbui/src/ui/cover.rs @@ -0,0 +1,210 @@ +//! Cover art, loaded lazily. +//! +//! A screen just draws a cover; it never asks for one to be fetched. Drawing +//! a URL the store has not seen records it as *wanted*, the app drains that +//! list after each frame and fetches, and the next frame after the bytes +//! arrive shows the picture. Until then (and forever, on terminals without +//! graphics or when the fetch fails) a placeholder with the media kind's +//! glyph stands in, so layouts never jump. + +use std::cell::RefCell; +use std::collections::HashMap; +use std::sync::Arc; + +use libby::models::MediaKind; +use ratatui::buffer::Buffer; +use ratatui::layout::{Alignment, Rect}; +use ratatui::style::Style; +use ratatui::text::Line; +use ratatui::widgets::{Block, Paragraph, Widget}; +use url::Url; + +use crate::theme::{Symbols, Theme}; + +/// At most this many covers are kept in memory; the oldest are forgotten +/// (they stay in the on-disk cache). +const MAX_ENTRIES: usize = 256; + +/// One cover's state. +#[derive(Debug, Clone)] +pub enum CoverState { + /// Asked for, not here yet. + Loading, + /// The encoded image bytes (JPEG, PNG, …). + Ready(Arc<[u8]>), + /// The fetch failed; a placeholder is shown and it is not retried. + Failed, +} + +#[derive(Debug, Default)] +struct Inner { + entries: HashMap, + /// Insertion order, for eviction. + order: Vec, + wanted: Vec, +} + +/// The in-memory cover store. +#[derive(Debug, Default)] +pub struct Covers { + inner: RefCell, + /// Whether to fetch covers at all (`images = "off"` disables it). + enabled: bool, +} + +impl Covers { + /// A store; `enabled = false` never fetches and always draws + /// placeholders. + #[must_use] + pub fn new(enabled: bool) -> Self { + Self { + inner: RefCell::default(), + enabled, + } + } + + /// The state of `url`, if it has been asked for. + #[must_use] + pub fn state(&self, url: &Url) -> Option { + self.inner.borrow().entries.get(url).cloned() + } + + /// The URLs drawn since the last call that still need fetching. + #[must_use] + pub fn take_wanted(&self) -> Vec { + std::mem::take(&mut self.inner.borrow_mut().wanted) + } + + /// Records a fetch result. + pub fn insert(&self, url: &Url, bytes: Option>) { + let state = bytes.map_or(CoverState::Failed, CoverState::Ready); + self.inner.borrow_mut().entries.insert(url.clone(), state); + } + + fn want(&self, url: &Url) { + if !self.enabled { + return; + } + let mut inner = self.inner.borrow_mut(); + if inner.entries.contains_key(url) { + return; + } + if inner.order.len() >= MAX_ENTRIES { + let oldest = inner.order.remove(0); + inner.entries.remove(&oldest); + } + inner.entries.insert(url.clone(), CoverState::Loading); + inner.order.push(url.clone()); + inner.wanted.push(url.clone()); + } + + /// Draws the cover at `url` into `area`, or a placeholder. + pub fn render( + &self, + area: Rect, + buf: &mut Buffer, + url: Option<&Url>, + kind: &MediaKind, + theme: &Theme, + symbols: &Symbols, + ) { + if area.is_empty() { + return; + } + if let Some(url) = url { + self.want(url); + } + placeholder(area, buf, kind, theme, symbols); + } +} + +/// The glyph and style for a media kind. +#[must_use] +pub fn kind_badge(kind: &MediaKind, theme: &Theme, symbols: &Symbols) -> (&'static str, Style) { + match kind { + MediaKind::Audiobook => (symbols.audiobook, theme.audiobook), + MediaKind::Magazine => (symbols.magazine, theme.magazine), + _ => (symbols.ebook, theme.ebook), + } +} + +fn placeholder(area: Rect, buf: &mut Buffer, kind: &MediaKind, theme: &Theme, symbols: &Symbols) { + let (glyph, style) = kind_badge(kind, theme, symbols); + let block = Block::bordered() + .border_type(theme.border_type) + .border_style(theme.faint); + let inner = block.inner(area); + block.render(area, buf); + if inner.is_empty() { + return; + } + let middle = Rect::new(inner.x, inner.y + inner.height / 2, inner.width, 1); + Paragraph::new(Line::styled(glyph, style)) + .alignment(Alignment::Center) + .render(middle, buf); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::theme::ThemeName; + + fn url(n: usize) -> Url { + Url::parse(&format!("https://img.example/{n}.jpg")).expect("valid url") + } + + fn draw(covers: &Covers, url: Option<&Url>) { + let area = Rect::new(0, 0, 8, 5); + let mut buf = Buffer::empty(area); + covers.render( + area, + &mut buf, + url, + &MediaKind::Ebook, + &Theme::named(ThemeName::Mono), + &Symbols::ASCII, + ); + } + + #[test] + fn drawing_a_cover_asks_for_it_once() { + let covers = Covers::new(true); + draw(&covers, Some(&url(1))); + draw(&covers, Some(&url(1))); + assert_eq!(covers.take_wanted(), [url(1)]); + assert!(covers.take_wanted().is_empty()); + assert!(matches!(covers.state(&url(1)), Some(CoverState::Loading))); + + covers.insert(&url(1), Some(Arc::from(&b"jpeg"[..]))); + draw(&covers, Some(&url(1))); + assert!(covers.take_wanted().is_empty()); + assert!(matches!(covers.state(&url(1)), Some(CoverState::Ready(_)))); + } + + #[test] + fn a_failed_cover_is_not_asked_for_again() { + let covers = Covers::new(true); + draw(&covers, Some(&url(1))); + let _ = covers.take_wanted(); + covers.insert(&url(1), None); + draw(&covers, Some(&url(1))); + assert!(covers.take_wanted().is_empty()); + } + + #[test] + fn disabled_covers_never_fetch() { + let covers = Covers::new(false); + draw(&covers, Some(&url(1))); + assert!(covers.take_wanted().is_empty()); + } + + #[test] + fn the_store_is_bounded() { + let covers = Covers::new(true); + for n in 0..=MAX_ENTRIES { + draw(&covers, Some(&url(n))); + } + assert!(covers.state(&url(0)).is_none()); + assert!(covers.state(&url(MAX_ENTRIES)).is_some()); + } +} diff --git a/crates/libbui/src/ui/help.rs b/crates/libbui/src/ui/help.rs new file mode 100644 index 0000000..bcf618a --- /dev/null +++ b/crates/libbui/src/ui/help.rs @@ -0,0 +1,216 @@ +//! The `?` overlay: every key that works here, grouped by where it works. +//! +//! It lists the focused screen's group first, then lists and global keys, and +//! is generated from the [`Keymap`], so it is always true. + +use ratatui::buffer::Buffer; +use ratatui::layout::{Constraint, Rect}; +use ratatui::text::{Line, Span}; +use ratatui::widgets::{Block, Clear, Padding, Paragraph, Widget}; + +use crate::i18n; +use crate::keymap::{Context, Keymap}; +use crate::theme::Theme; +use crate::ui::text; + +/// The help overlay's scroll position. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +pub struct HelpState { + /// First visible row. + pub scroll: u16, +} + +impl HelpState { + /// Scrolls by `delta` rows, clamped at the top. The bottom is clamped at + /// render time, when the content height is known. + pub fn scroll_by(&mut self, delta: i32) { + let next = i32::from(self.scroll).saturating_add(delta).max(0); + self.scroll = u16::try_from(next).unwrap_or(u16::MAX); + } +} + +/// The help overlay. +#[derive(Debug)] +pub struct Help<'a> { + keymap: &'a Keymap, + theme: &'a Theme, + /// The focused screen's contexts, most specific first. + contexts: &'a [Context], +} + +impl<'a> Help<'a> { + /// Help for a screen whose keys resolve through `contexts`. + #[must_use] + pub const fn new(keymap: &'a Keymap, theme: &'a Theme, contexts: &'a [Context]) -> Self { + Self { + keymap, + theme, + contexts, + } + } + + /// The overlay's rows: a heading per group, then `keys description`. + #[must_use] + pub fn lines(&self) -> Vec> { + let rows: Vec<(Context, Vec<(String, String)>)> = self + .contexts + .iter() + .map(|context| { + let bindings = self + .keymap + .in_context(*context) + .map(|binding| { + let keys = binding + .chords + .iter() + .map(ToString::to_string) + .collect::>() + .join(", "); + let what = i18n::lookup(&binding.command.description_key(), &[]); + (keys, what) + }) + .collect::>(); + (*context, bindings) + }) + .filter(|(_, bindings)| !bindings.is_empty()) + .collect(); + + let key_column = rows + .iter() + .flat_map(|(_, bindings)| bindings.iter().map(|(keys, _)| text::width(keys))) + .max() + .unwrap_or(0); + + let mut lines = Vec::new(); + for (context, bindings) in rows { + if !lines.is_empty() { + lines.push(Line::default()); + } + lines.push(Line::styled( + i18n::lookup(context.title_key(), &[]), + self.theme.strong, + )); + for (keys, what) in bindings { + let pad = " ".repeat(key_column - text::width(&keys) + 2); + lines.push(Line::from(vec![ + Span::raw(" "), + Span::styled(keys, self.theme.key), + Span::raw(pad), + Span::styled(what, self.theme.text), + ])); + } + } + lines + } + + /// Draws the overlay centred in `area`, clamping `state.scroll`. + pub fn render(&self, area: Rect, buf: &mut Buffer, state: &mut HelpState) { + let lines = self.lines(); + let content_width = lines.iter().map(Line::width).max().unwrap_or(0); + // Borders (2) + horizontal padding (2 each side). + let width = u16::try_from(content_width + 6).unwrap_or(u16::MAX); + let height = u16::try_from(lines.len() + 2).unwrap_or(u16::MAX); + let rect = area.centered( + Constraint::Length(width.min(area.width)), + Constraint::Length(height.min(area.height)), + ); + if rect.width < 12 || rect.height < 3 { + return; + } + let visible_rows = rect.height - 2; + let total_rows = u16::try_from(lines.len()).unwrap_or(u16::MAX); + let max_scroll = total_rows.saturating_sub(visible_rows); + state.scroll = state.scroll.min(max_scroll); + + let (border_style, border_type) = self.theme.pane_border(true); + let mut block = Block::bordered() + .border_type(border_type) + .border_style(border_style) + .title(Line::styled( + format!(" {} ", i18n::lookup("help-title", &[])), + self.theme.accent, + )) + .padding(Padding::horizontal(2)); + if max_scroll > 0 { + // Say there is more in words, not only with a scrollbar. + let more = i18n::lookup( + "help-scroll", + &[ + ("first", i18n::IntoArg::into_arg(state.scroll + 1)), + ( + "last", + i18n::IntoArg::into_arg((state.scroll + visible_rows).min(total_rows)), + ), + ("total", i18n::IntoArg::into_arg(total_rows)), + ], + ); + block = block.title_bottom(Line::styled(format!(" {more} "), self.theme.muted)); + } + Clear.render(rect, buf); + Paragraph::new(lines) + .block(block) + .scroll((state.scroll, 0)) + .render(rect, buf); + } +} + +#[cfg(test)] +mod tests { + use ratatui::buffer::Buffer; + + use super::*; + use crate::keymap::Command; + use crate::theme::ThemeName; + + #[test] + fn help_lists_what_the_keymap_binds() { + let keymap = Keymap::default(); + let theme = Theme::named(ThemeName::Mono); + let contexts = [Context::Shelf, Context::List, Context::Global]; + let lines: Vec = Help::new(&keymap, &theme, &contexts) + .lines() + .iter() + .map(ToString::to_string) + .collect(); + assert_eq!(lines[0], "Shelf"); + assert!(lines.iter().any(|l| l.contains("Download this loan"))); + assert!(lines.iter().any(|l| l == "Everywhere")); + // Other screens' keys are not listed. + assert!(!lines.iter().any(|l| l.contains("Cancel this hold"))); + // Both spellings of a command appear on one row. + let down = i18n::lookup(&Command::Down.description_key(), &[]); + assert!( + lines + .iter() + .any(|l| l.contains("j, ↓") && l.contains(&down)) + ); + } + + #[test] + fn scroll_is_clamped_to_the_content() { + let keymap = Keymap::default(); + let theme = Theme::named(ThemeName::Mono); + let contexts = [Context::Shelf, Context::List, Context::Global]; + let area = Rect::new(0, 0, 80, 12); + let mut buf = Buffer::empty(area); + let mut state = HelpState { scroll: 9000 }; + Help::new(&keymap, &theme, &contexts).render(area, &mut buf, &mut state); + assert!(state.scroll < 100); + assert!(state.scroll > 0); + } + + #[test] + fn a_tiny_terminal_does_not_panic() { + let keymap = Keymap::default(); + let theme = Theme::named(ThemeName::Mono); + for (w, h) in [(0, 0), (1, 1), (5, 2), (11, 40), (200, 2)] { + let area = Rect::new(0, 0, w, h); + let mut buf = Buffer::empty(area); + Help::new(&keymap, &theme, &[Context::Global]).render( + area, + &mut buf, + &mut HelpState::default(), + ); + } + } +} diff --git a/crates/libbui/src/ui/hints.rs b/crates/libbui/src/ui/hints.rs new file mode 100644 index 0000000..0420d66 --- /dev/null +++ b/crates/libbui/src/ui/hints.rs @@ -0,0 +1,148 @@ +//! The footer: the keys that matter right now. +//! +//! Hints are built from the same [`Keymap`] the dispatcher uses, so a rebound +//! key shows its new spelling and an unbound command simply disappears. When +//! the line is too narrow, hints are dropped from the end (callers list the +//! most important first) rather than cut mid-word. + +use ratatui::buffer::Buffer; +use ratatui::layout::Rect; +use ratatui::text::{Line, Span}; +use ratatui::widgets::Widget; + +use crate::i18n; +use crate::keymap::{Command, Context, Keymap}; +use crate::theme::{Symbols, Theme}; +use crate::ui::text; + +/// One hint: a key and what it does. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Hint { + /// The key, spelled for people (`Ctrl-P`). + pub key: String, + /// The short label (`commands`). + pub label: String, +} + +/// Resolves `commands` to hints in `context`, skipping any that are unbound. +#[must_use] +pub fn resolve(keymap: &Keymap, context: Context, commands: &[Command]) -> Vec { + commands + .iter() + .filter_map(|command| { + let chord = keymap.primary(context, *command)?; + Some(Hint { + key: chord.to_string(), + label: i18n::lookup(&command.hint_key(), &[]), + }) + }) + .collect() +} + +/// The footer line. +#[derive(Debug)] +pub struct HintBar<'a> { + hints: &'a [Hint], + theme: &'a Theme, + symbols: &'a Symbols, +} + +impl<'a> HintBar<'a> { + /// A footer showing `hints`, most important first. + #[must_use] + pub const fn new(hints: &'a [Hint], theme: &'a Theme, symbols: &'a Symbols) -> Self { + Self { + hints, + theme, + symbols, + } + } + + /// The hints that fit in `columns`, as one line. + #[must_use] + pub fn line(&self, columns: usize) -> Line<'a> { + let separator = format!(" {} ", self.symbols.dot); + let separator_width = text::width(&separator); + let mut spans = Vec::new(); + let mut used = 0; + for hint in self.hints { + let hint_width = text::width(&hint.key) + 1 + text::width(&hint.label); + let gap = if spans.is_empty() { 0 } else { separator_width }; + if used + gap + hint_width > columns { + break; + } + if gap > 0 { + spans.push(Span::styled(separator.clone(), self.theme.faint)); + } + spans.push(Span::styled(hint.key.as_str(), self.theme.key)); + spans.push(Span::raw(" ")); + spans.push(Span::styled(hint.label.as_str(), self.theme.muted)); + used += gap + hint_width; + } + Line::from(spans) + } +} + +impl Widget for HintBar<'_> { + fn render(self, area: Rect, buf: &mut Buffer) { + if area.is_empty() { + return; + } + self.line(usize::from(area.width)).render(area, buf); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::theme::ThemeName; + + fn rendered(hints: &[Hint], columns: usize) -> String { + let theme = Theme::named(ThemeName::Mono); + HintBar::new(hints, &theme, &Symbols::UNICODE) + .line(columns) + .to_string() + } + + #[test] + fn hints_come_from_the_keymap() { + let keymap = Keymap::default(); + let hints = resolve(&keymap, Context::Shelf, &[Command::Download, Command::Help]); + assert_eq!( + hints, + [ + Hint { + key: "d".into(), + label: "download".into() + }, + Hint { + key: "?".into(), + label: "help".into() + }, + ] + ); + } + + #[test] + fn unbound_commands_are_not_advertised() { + let overrides = [("shelf.download".to_owned(), Vec::new())].into(); + let keymap = Keymap::with_overrides(&overrides).expect("valid overrides"); + let hints = resolve(&keymap, Context::Shelf, &[Command::Download, Command::Help]); + assert_eq!(hints.len(), 1); + assert_eq!(hints[0].label, "help"); + } + + #[test] + fn hints_that_do_not_fit_are_dropped_whole() { + let keymap = Keymap::default(); + let hints = resolve( + &keymap, + Context::Shelf, + &[Command::Download, Command::Renew, Command::Help], + ); + assert_eq!(rendered(&hints, 80), "d download · r renew · ? help"); + assert_eq!(rendered(&hints, 22), "d download · r renew"); + assert_eq!(rendered(&hints, 12), "d download"); + assert_eq!(rendered(&hints, 5), ""); + } +} diff --git a/crates/libbui/src/ui/mod.rs b/crates/libbui/src/ui/mod.rs new file mode 100644 index 0000000..c9f051f --- /dev/null +++ b/crates/libbui/src/ui/mod.rs @@ -0,0 +1,9 @@ +//! Shared widgets and drawing helpers used by every screen. + +pub mod cover; +pub mod help; +pub mod hints; +pub mod placeholder; +pub mod text; +pub mod toast; +pub mod when; diff --git a/crates/libbui/src/ui/placeholder.rs b/crates/libbui/src/ui/placeholder.rs new file mode 100644 index 0000000..664e158 --- /dev/null +++ b/crates/libbui/src/ui/placeholder.rs @@ -0,0 +1,140 @@ +//! What a pane shows when it has no content: loading, nothing here, or an +//! error with a way out. Every screen uses the same three so they read the +//! same everywhere. + +use ratatui::buffer::Buffer; +use ratatui::layout::{Alignment, Constraint, Rect}; +use ratatui::text::Line; +use ratatui::widgets::{Paragraph, Widget, Wrap}; + +use crate::theme::{Symbols, Theme}; +use crate::ui::text; + +/// A centred message filling an otherwise empty pane. +#[derive(Debug, Clone)] +pub struct Placeholder<'a> { + icon: &'a str, + title: String, + body: Option, + title_style: ratatui::style::Style, + theme: &'a Theme, +} + +impl<'a> Placeholder<'a> { + /// Work in progress. `spinner` is the current frame + /// ([`crate::app::Shared::spinner`]). + #[must_use] + pub fn loading(title: impl Into, spinner: &'a str, theme: &'a Theme) -> Self { + Self { + icon: spinner, + title: title.into(), + body: None, + title_style: theme.muted, + theme, + } + } + + /// Nothing to show, and that is fine. + #[must_use] + pub fn empty(title: impl Into, theme: &'a Theme, symbols: &'a Symbols) -> Self { + Self { + icon: symbols.dot, + title: title.into(), + body: None, + title_style: theme.strong, + theme, + } + } + + /// Something went wrong. + #[must_use] + pub fn error(title: impl Into, theme: &'a Theme, symbols: &'a Symbols) -> Self { + Self { + icon: symbols.error, + title: title.into(), + body: None, + title_style: theme.danger, + theme, + } + } + + /// A second, quieter paragraph: what to do next. + #[must_use] + pub fn body(mut self, body: impl Into) -> Self { + self.body = Some(body.into()); + self + } +} + +impl Widget for Placeholder<'_> { + fn render(self, area: Rect, buf: &mut Buffer) { + if area.width < 4 || area.height == 0 { + return; + } + let columns = usize::from(area.width.saturating_sub(4)).min(56); + let mut lines = vec![Line::styled( + format!("{} {}", self.icon, self.title), + self.title_style, + )]; + if let Some(body) = &self.body { + lines.push(Line::raw("")); + lines.extend( + text::wrap(body, columns) + .into_iter() + .map(|row| Line::styled(row, self.theme.muted)), + ); + } + let height = u16::try_from(lines.len()).unwrap_or(u16::MAX); + let width = u16::try_from(columns).unwrap_or(u16::MAX); + let area = area.centered(Constraint::Length(width), Constraint::Length(height)); + Paragraph::new(lines) + .alignment(Alignment::Center) + .wrap(Wrap { trim: true }) + .render(area, buf); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::theme::ColorDepth; + + fn rendered(placeholder: Placeholder<'_>, width: u16, height: u16) -> String { + let area = Rect::new(0, 0, width, height); + let mut buf = Buffer::empty(area); + placeholder.render(area, &mut buf); + buf.content + .chunks(usize::from(width)) + .map(|row| { + row.iter() + .map(ratatui::buffer::Cell::symbol) + .collect::() + .trim_end() + .to_owned() + }) + .collect::>() + .join("\n") + } + + #[test] + fn centres_title_and_body() { + let theme = Theme::resolve("dark", ColorDepth::TrueColor, false); + let symbols = Symbols::pick(true); + let out = rendered( + Placeholder::empty("Nothing on loan", &theme, symbols).body("Press 2 to search."), + 40, + 5, + ); + let rows: Vec<&str> = out.lines().collect(); + assert!(rows[1].contains("Nothing on loan"), "{out}"); + assert!(rows[3].contains("Press 2 to search."), "{out}"); + assert!(rows[1].starts_with(" "), "{out}"); + } + + #[test] + fn draws_nothing_when_there_is_no_room() { + let theme = Theme::resolve("dark", ColorDepth::TrueColor, false); + let symbols = Symbols::pick(true); + assert_eq!(rendered(Placeholder::empty("x", &theme, symbols), 3, 1), ""); + } +} diff --git a/crates/libbui/src/ui/text.rs b/crates/libbui/src/ui/text.rs new file mode 100644 index 0000000..1042eb2 --- /dev/null +++ b/crates/libbui/src/ui/text.rs @@ -0,0 +1,186 @@ +//! Text that fits: width-aware truncation, padding and wrapping. +//! +//! Terminal columns are not characters. Everything here measures with +//! `unicode-width` and cuts on grapheme boundaries, so a CJK title or a +//! combining accent never splits a cell or overflows a column. + +use unicode_segmentation::UnicodeSegmentation; +use unicode_width::UnicodeWidthStr; + +/// The number of terminal columns `text` occupies. +#[must_use] +pub fn width(text: &str) -> usize { + UnicodeWidthStr::width(text) +} + +/// Cuts `text` to at most `max` columns, ending with `ellipsis` when anything +/// was removed. Returns the text unchanged when it already fits. +#[must_use] +pub fn truncate(text: &str, max: usize, ellipsis: &str) -> String { + if width(text) <= max { + return text.to_owned(); + } + let ellipsis_width = width(ellipsis); + if max <= ellipsis_width { + // No room for text *and* a marker: the marker alone, cut to fit. + return take_columns(ellipsis, max); + } + let mut out = take_columns(text, max - ellipsis_width); + // Don't leave "word …": the marker should touch the text. + out.truncate(out.trim_end().len()); + out.push_str(ellipsis); + out +} + +/// The longest prefix of `text` that fits in `max` columns. +fn take_columns(text: &str, max: usize) -> String { + let mut out = String::new(); + let mut used = 0; + for grapheme in text.graphemes(true) { + let w = width(grapheme); + if used + w > max { + break; + } + used += w; + out.push_str(grapheme); + } + out +} + +/// Pads `text` with spaces on the right to exactly `columns`, truncating if +/// it is too long. +#[must_use] +pub fn fit(text: &str, columns: usize, ellipsis: &str) -> String { + let mut out = truncate(text, columns, ellipsis); + let pad = columns.saturating_sub(width(&out)); + out.extend(std::iter::repeat_n(' ', pad)); + out +} + +/// Greedy word wrap to `columns`, breaking words longer than a line. +/// +/// Blank lines in the input are kept (paragraph breaks); runs of other +/// whitespace collapse to one space. +#[must_use] +pub fn wrap(text: &str, columns: usize) -> Vec { + if columns == 0 { + return Vec::new(); + } + let mut lines = Vec::new(); + for paragraph in text.split('\n') { + let mut line = String::new(); + let mut used = 0; + for word in paragraph.split_whitespace() { + let mut word = word; + loop { + let w = width(word); + let gap = usize::from(used > 0); + if used + gap + w <= columns { + if gap == 1 { + line.push(' '); + } + line.push_str(word); + used += gap + w; + break; + } + if used > 0 { + lines.push(std::mem::take(&mut line)); + used = 0; + continue; + } + // A single word wider than the line: hard-break it. + let head = take_columns(word, columns); + if head.is_empty() { + // A grapheme wider than the whole line; drop it rather + // than loop forever. + break; + } + word = &word[head.len()..]; + lines.push(head); + if word.is_empty() { + break; + } + } + } + lines.push(line); + } + while lines.last().is_some_and(String::is_empty) { + lines.pop(); + } + lines +} + +/// A byte count for people: `812 B`, `3.4 MB`. +#[must_use] +pub fn bytes(n: u64) -> String { + const UNITS: [&str; 5] = ["B", "KB", "MB", "GB", "TB"]; + if n < 1024 { + return format!("{n} B"); + } + #[allow(clippy::cast_precision_loss)] + let mut value = n as f64; + let mut unit = 0; + while value >= 1024.0 && unit < UNITS.len() - 1 { + value /= 1024.0; + unit += 1; + } + if value >= 100.0 { + format!("{value:.0} {}", UNITS[unit]) + } else { + format!("{value:.1} {}", UNITS[unit]) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn truncation_counts_columns_not_chars() { + assert_eq!(truncate("Dune", 10, "…"), "Dune"); + assert_eq!(truncate("Dune Messiah", 8, "…"), "Dune Me…"); + assert_eq!(truncate("Dune Messiah", 6, "…"), "Dune…"); + // Each CJK character is two columns wide. + assert_eq!(truncate("銀河鉄道の夜", 7, "…"), "銀河鉄…"); + assert_eq!(width(&truncate("銀河鉄道の夜", 7, "…")), 7); + assert_eq!(truncate("銀河鉄道の夜", 6, "…"), "銀河…"); + } + + #[test] + fn truncation_never_splits_a_grapheme() { + let accented = "e\u{301}e\u{301}e\u{301}"; // é é é as e + combining acute + assert_eq!(truncate(accented, 2, "…"), "e\u{301}…"); + } + + #[test] + fn truncation_survives_tiny_widths() { + assert_eq!(truncate("Dune", 0, "…"), ""); + assert_eq!(truncate("Dune", 1, "…"), "…"); + assert_eq!(truncate("Dune", 2, "..."), ".."); + } + + #[test] + fn fit_is_exact() { + assert_eq!(fit("ab", 4, "…"), "ab "); + assert_eq!(fit("abcdef", 4, "…"), "abc…"); + assert_eq!(width(&fit("銀河鉄道", 5, "…")), 5); + } + + #[test] + fn wrapping_keeps_paragraphs_and_breaks_long_words() { + assert_eq!(wrap("a bb ccc", 4), ["a bb", "ccc"]); + assert_eq!(wrap("one\n\ntwo", 10), ["one", "", "two"]); + assert_eq!(wrap("abcdefgh", 3), ["abc", "def", "gh"]); + assert_eq!(wrap(" spaced out ", 20), ["spaced out"]); + assert!(wrap("anything", 0).is_empty()); + } + + #[test] + fn byte_counts_read_naturally() { + assert_eq!(bytes(0), "0 B"); + assert_eq!(bytes(812), "812 B"); + assert_eq!(bytes(1536), "1.5 KB"); + assert_eq!(bytes(3_565_158), "3.4 MB"); + assert_eq!(bytes(250 * 1024 * 1024), "250 MB"); + } +} diff --git a/crates/libbui/src/ui/toast.rs b/crates/libbui/src/ui/toast.rs new file mode 100644 index 0000000..92e1e18 --- /dev/null +++ b/crates/libbui/src/ui/toast.rs @@ -0,0 +1,300 @@ +//! Toasts: brief, non-blocking notices in the corner. +//! +//! Good news fades by itself. Bad news stays until dismissed, because an +//! error that vanishes while you were looking elsewhere is an error you never +//! saw. At most [`MAX_VISIBLE`] show at once; older ones wait their turn. + +use std::collections::VecDeque; +use std::time::{Duration, Instant}; + +use ratatui::buffer::Buffer; +use ratatui::layout::Rect; +use ratatui::text::{Line, Span}; +use ratatui::widgets::{Block, Clear, Paragraph, Widget}; + +use crate::theme::{Symbols, Theme}; +use crate::ui::text; + +/// How many toasts are on screen at once. +pub const MAX_VISIBLE: usize = 3; + +/// How long a non-error toast stays. +pub const LIFETIME: Duration = Duration::from_secs(4); + +/// The widest a toast gets, in columns, borders included. +const MAX_WIDTH: u16 = 48; + +/// What kind of news a toast carries. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Level { + /// Neutral information. + Info, + /// Something worked. + Success, + /// Something needs attention but nothing failed. + Warning, + /// Something failed. Stays until dismissed. + Error, +} + +impl Level { + /// The Fluent key for the word shown beside the glyph. + #[must_use] + pub const fn label_key(self) -> &'static str { + match self { + Self::Info => "toast-info", + Self::Success => "toast-success", + Self::Warning => "toast-warning", + Self::Error => "toast-error", + } + } +} + +/// One notice. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Toast { + /// Its kind. + pub level: Level, + /// The message, already localized and sanitized. + pub message: String, +} + +impl Toast { + /// A toast of `level` saying `message`. + pub fn new(level: Level, message: impl Into) -> Self { + Self { + level, + message: message.into(), + } + } + + /// Neutral information. + pub fn info(message: impl Into) -> Self { + Self::new(Level::Info, message) + } + + /// Something worked. + pub fn success(message: impl Into) -> Self { + Self::new(Level::Success, message) + } + + /// Something needs attention. + pub fn warning(message: impl Into) -> Self { + Self::new(Level::Warning, message) + } + + /// Something failed. + pub fn error(message: impl Into) -> Self { + Self::new(Level::Error, message) + } +} + +#[derive(Debug)] +struct Entry { + toast: Toast, + /// When it first became visible; `None` while it waits in the queue. + shown_at: Option, +} + +/// The queue of toasts. +#[derive(Debug, Default)] +pub struct Toasts { + entries: VecDeque, +} + +impl Toasts { + /// Adds a toast. A repeat of the newest message is dropped, so a failing + /// retry loop can't fill the screen. + pub fn push(&mut self, toast: Toast) { + if self.entries.back().is_some_and(|last| last.toast == toast) { + return; + } + self.entries.push_back(Entry { + toast, + shown_at: None, + }); + } + + /// Whether nothing is showing or waiting. + #[must_use] + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + /// Whether a timer is running, i.e. the app must keep ticking. + #[must_use] + pub fn needs_tick(&self) -> bool { + self.entries + .iter() + .take(MAX_VISIBLE) + .any(|entry| entry.toast.level != Level::Error) + } + + /// Starts timers for newly visible toasts and expires old ones. Returns + /// whether anything changed (so the caller knows to redraw). + pub fn tick(&mut self, now: Instant) -> bool { + let before = self.entries.len(); + let mut index = 0; + self.entries.retain(|entry| { + let visible = index < MAX_VISIBLE; + index += 1; + let expired = visible + && entry.toast.level != Level::Error + && entry + .shown_at + .is_some_and(|shown| now.duration_since(shown) >= LIFETIME); + !expired + }); + let mut started = false; + for entry in self.entries.iter_mut().take(MAX_VISIBLE) { + if entry.shown_at.is_none() { + entry.shown_at = Some(now); + started = true; + } + } + started || self.entries.len() != before + } + + /// Dismisses the oldest visible toast. Returns whether there was one. + pub fn dismiss(&mut self) -> bool { + self.entries.pop_front().is_some() + } + + /// Dismisses everything. + pub fn clear(&mut self) { + self.entries.clear(); + } + + /// The toasts on screen, oldest first. + pub fn visible(&self) -> impl Iterator { + self.entries + .iter() + .take(MAX_VISIBLE) + .map(|entry| &entry.toast) + } + + /// Whether any visible toast is an error (it can be dismissed with Esc). + #[must_use] + pub fn has_sticky(&self) -> bool { + self.visible().any(|toast| toast.level == Level::Error) + } +} + +/// Draws the visible toasts stacked in the top-right corner of `area`. +#[derive(Debug)] +pub struct ToastStack<'a> { + toasts: &'a Toasts, + theme: &'a Theme, + symbols: &'a Symbols, +} + +impl<'a> ToastStack<'a> { + /// A stack over `toasts`. + #[must_use] + pub const fn new(toasts: &'a Toasts, theme: &'a Theme, symbols: &'a Symbols) -> Self { + Self { + toasts, + theme, + symbols, + } + } +} + +impl Widget for ToastStack<'_> { + fn render(self, area: Rect, buf: &mut Buffer) { + let width = MAX_WIDTH.min(area.width); + // Borders plus one column of padding each side. + let Some(inner_width) = width.checked_sub(4).filter(|w| *w >= 8) else { + return; + }; + let mut y = area.y; + for toast in self.toasts.visible() { + let (style, glyph) = match toast.level { + Level::Info => (self.theme.info, self.symbols.info), + Level::Success => (self.theme.success, self.symbols.ok), + Level::Warning => (self.theme.warning, self.symbols.warn), + Level::Error => (self.theme.danger, self.symbols.error), + }; + let label = crate::i18n::lookup(toast.level.label_key(), &[]); + let lines = text::wrap(&toast.message, usize::from(inner_width)); + let height = u16::try_from(lines.len()) + .unwrap_or(u16::MAX) + .saturating_add(2); + if y.saturating_add(height) > area.bottom() { + break; + } + let rect = Rect::new(area.right() - width, y, width, height); + let title = Line::from(vec![ + Span::raw(" "), + Span::styled(glyph, style), + Span::raw(" "), + Span::styled(label, style), + Span::raw(" "), + ]); + let block = Block::bordered() + .border_type(self.theme.border_type) + .border_style(style) + .title(title) + .padding(ratatui::widgets::Padding::horizontal(1)); + let body: Vec> = lines + .into_iter() + .map(|line| Line::styled(line, self.theme.text)) + .collect(); + Clear.render(rect, buf); + Paragraph::new(body).block(block).render(rect, buf); + y += height; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn good_news_expires_and_bad_news_stays() { + let start = Instant::now(); + let mut toasts = Toasts::default(); + toasts.push(Toast::success("Borrowed")); + toasts.push(Toast::error("Could not renew")); + assert!(toasts.tick(start)); + assert_eq!(toasts.visible().count(), 2); + + assert!(!toasts.tick(start + LIFETIME / 2)); + assert!(toasts.tick(start + LIFETIME)); + let left: Vec<_> = toasts.visible().collect(); + assert_eq!(left, [&Toast::error("Could not renew")]); + assert!(!toasts.needs_tick()); + + assert!(toasts.dismiss()); + assert!(toasts.is_empty()); + } + + #[test] + fn queued_toasts_start_their_clock_when_they_appear() { + let start = Instant::now(); + let mut toasts = Toasts::default(); + for n in 0..=MAX_VISIBLE { + toasts.push(Toast::info(format!("note {n}"))); + } + toasts.tick(start); + assert_eq!(toasts.visible().count(), MAX_VISIBLE); + + // The first three expire; the fourth only now becomes visible and + // gets its own full lifetime. + toasts.tick(start + LIFETIME); + assert_eq!(toasts.visible().count(), 1); + toasts.tick(start + LIFETIME + LIFETIME / 2); + assert_eq!(toasts.visible().count(), 1); + toasts.tick(start + LIFETIME * 2); + assert!(toasts.is_empty()); + } + + #[test] + fn an_immediate_repeat_is_dropped() { + let mut toasts = Toasts::default(); + toasts.push(Toast::error("offline")); + toasts.push(Toast::error("offline")); + assert_eq!(toasts.visible().count(), 1); + } +} diff --git a/crates/libbui/src/ui/when.rs b/crates/libbui/src/ui/when.rs new file mode 100644 index 0000000..863f3e8 --- /dev/null +++ b/crates/libbui/src/ui/when.rs @@ -0,0 +1,100 @@ +//! Durations and dates the way a person would say them. + +use std::time::Duration; + +use jiff::Timestamp; +use jiff::tz::TimeZone; + +use crate::t; + +const MINUTE: u64 = 60; +const HOUR: u64 = 60 * MINUTE; +const DAY: u64 = 24 * HOUR; + +/// A span in its largest sensible unit: "3 days", "5 hours", "12 minutes", +/// "less than a minute". Rounds down, so "1 day" never means 23 hours. +#[must_use] +pub fn span(duration: Duration) -> String { + let seconds = duration.as_secs(); + if seconds >= DAY { + t!("time-days", count = seconds / DAY) + } else if seconds >= HOUR { + t!("time-hours", count = seconds / HOUR) + } else if seconds >= MINUTE { + t!("time-minutes", count = seconds / MINUTE) + } else { + t!("time-less-than-a-minute") + } +} + +/// How long until `then`: "3 days left", or "expired" once it has passed. +#[must_use] +pub fn left(then: Timestamp, now: Timestamp) -> String { + match until(then, now) { + Some(duration) => t!("time-left", span = span(duration)), + None => t!("time-expired"), + } +} + +/// How long since `then`: "3 days ago". +#[must_use] +pub fn ago(then: Timestamp, now: Timestamp) -> String { + t!("time-ago", span = span(until(now, then).unwrap_or_default())) +} + +/// The time from `now` to `then`, or `None` when `then` is not in the future. +#[must_use] +pub fn until(then: Timestamp, now: Timestamp) -> Option { + Duration::try_from(then.duration_since(now)) + .ok() + .filter(|duration| !duration.is_zero()) +} + +/// A calendar date in the user's time zone, ISO 8601 (`2026-11-22`): the one +/// date format nobody misreads. +#[must_use] +pub fn date(when: Timestamp) -> String { + date_in(when, &TimeZone::system()) +} + +/// [`date`] in an explicit zone, for tests. +#[must_use] +pub fn date_in(when: Timestamp, zone: &TimeZone) -> String { + when.to_zoned(zone.clone()).date().to_string() +} + +#[cfg(test)] +mod tests { + use super::*; + + fn at(raw: &str) -> Timestamp { + raw.parse().expect("test timestamp") + } + + #[test] + fn spans_round_down_to_the_largest_unit() { + assert_eq!(span(Duration::from_secs(30)), "less than a minute"); + assert_eq!(span(Duration::from_secs(60)), "1 minute"); + assert_eq!(span(Duration::from_secs(59 * 60)), "59 minutes"); + assert_eq!(span(Duration::from_secs(23 * 3600 + 3599)), "23 hours"); + assert_eq!(span(Duration::from_secs(24 * 3600)), "1 day"); + assert_eq!(span(Duration::from_secs(7 * 24 * 3600 + 5)), "7 days"); + } + + #[test] + fn left_and_ago() { + let now = at("2026-11-15T12:00:00Z"); + assert_eq!(left(at("2026-11-22T15:04:05Z"), now), "7 days left"); + assert_eq!(left(at("2026-11-15T11:00:00Z"), now), "expired"); + assert_eq!(left(now, now), "expired"); + assert_eq!(ago(at("2026-11-13T12:00:00Z"), now), "2 days ago"); + } + + #[test] + fn dates_are_iso() { + assert_eq!( + date_in(at("2026-11-22T15:04:05Z"), &TimeZone::UTC), + "2026-11-22" + ); + } +}