Readium Kotlin Toolkit

repository·develop·Indexed 18 days ago

https://github.com/readium/kotlin-toolkit

A mobile toolkit for reading ebooks, audiobooks, and comics, providing core logic for parsing publications, navigating content, and handling DRM. It includes support for PDF rendering via Pdfium and PSPDFKit adapters, an OPDS 1.x and 2.0 feed parser, and specialized stylesheets for RTL and CJK content.

Tokens
41.8K
Snippets
122
Records
163
Agent score
58%

What's inside Readium Kotlin Toolkit

  1. Overview of the Readium Kotlin Toolkit modules

    develop

    The Readium Kotlin toolkit is a modular set of low-level tools for developing reading applications on Android and ChromeOS. It supports formats like EPUB, PDF, audiobooks, and comics.

    Note: The toolkit provides the engine and models, but you are responsible for building the User Interface (UI), managing the book database, and handling storage. The Test App in the repository serves as a reference implementation.

    Core Modules

    • readium-shared: Contains shared Publication models and utilities used across the toolkit.
    • readium-streamer: Responsible for parsing publication files (e.g., EPUB) into Publication objects.
    • readium-navigator: Handles the actual rendering of publication content.
      • readium-navigator-media-audio: Specialized for rendering audiobooks.
      • readium-navigator-media-tts: Specialized for text-to-speech rendering.

    Specialized Packages

    • readium-opds: Parses OPDS 1 and 2 catalog feeds.
    • readium-lcp: Handles downloading and decrypting LCP-protected publications.

    Third-party Adapters

    • readium-adapter-exoplayer: ExoPlayer adapter for AudioNavigator.
    • readium-adapter-pdfium: Pdfium adapter for the PDF Navigator.
    • readium-adapter-pspdfkit: PSPDFKit adapter for the PDF Navigator.
  2. Supported publication formats and features

    develop

    The Readium Kotlin toolkit supports various publication formats with varying levels of feature implementation.

    Formats

    • EPUB 2 & EPUB 3: Fully implemented.
    • PDF: Fully implemented.
    • Audiobooks: Readium Audiobook, Zipped Audiobook, and standalone audio files (MP3, AAC, etc.) are fully implemented.
    • Partially Implemented: Readium Web Publication, Readium Divina, and CBZ (Comic Book ZIP).
    • Planned/Other: DAISY (Planned), CBR (Not planned).

    Feature Matrix

    FeatureEPUB (reflow)EPUB (FXL)PDF
    Pagination
    Scrolling👀
    Right-to-left (RTL)
    Search in textual content👀
    Highlighting (Decoration API)👀
    Text-to-speech (TTS)👀
    Media overlays📆📆
  3. Understand the role of Readium JS (Kotlin) scripts

    develop

    Readium JS (Kotlin) consists of a set of JavaScript files that are utilized by the Kotlin EPUB navigator to handle core reading logic within the web view environment.

    Note: In the repository structure, this directory is prefixed with an underscore (_scripts) to prevent the Gradle build system from automatically embedding it as an asset during the build process. Developers looking to include these scripts in their own asset management pipeline should be aware of this naming convention.

  4. Observe playback changes using the playback flow

    develop

    You can monitor playback status by observing the navigator.playback flow property. This provides access to:

    • playWhenReady: A boolean indicating if the media is playing or will start once conditions (like buffering) are met.
    • state: The current playback status, which can be Ready, Ended, Buffering, or Error (or Failure in some implementations).
    • index: The index of the current navigator.readingOrder item being played.

    To determine if media is actively playing, check if playWhenReady is true AND state == Ready.

    navigator.playback
        .onEach { playback ->
            playPauseButton.toggle(playback.playWhenReady)
            
            val playingItem = navigator.readingOrder.items[playback.index]
    
            if (playback.state is MediaNavigator.State.Failure) {
                // Alert
            }
        }
        .launchIn(scope)
  5. Use AssetRetriever and PublicationOpener instead of Streamer

    develop

    In version 3.0.0, the Streamer object is deprecated. Use these specialized components instead:

    • AssetRetriever: Used to access the content of an asset (e.g., publication package, manifest, or LCP license) at a specific URL.
    • PublicationOpener: Uses a publication parser and content protections to create a Publication object from an Asset.
  6. Use AccessibilityMetadataDisplayGuide to simplify accessibility information

    develop

    The toolkit provides AccessibilityMetadataDisplayGuide to implement the W3C Accessibility Metadata Display Guide. This abstraction simplifies complex metadata into structured sections (fields) and statements that are easier to present to users.

    Key components include:

    • Fields: Logical sections of accessibility information (e.g., waysOfReading).
    • Statements: Specific claims within a field (e.g., whether visual adjustments are possible).
    • shouldDisplay: A property on a field that returns true if the field contains meaningful information to show.
    val guide = AccessibilityMetadataDisplayGuide(publication)
    
    when (guide.waysOfReading.visualAdjustments) {
        VisualAdjustments.MODIFIABLE -> {
            // The text and layout of the publication can be customized.
        }
        VisualAdjustments.UNMODIFIABLE -> {
            // The text and layout cannot be modified.
        }
        VisualAdjustments.UNKNOWN -> {
            // No metadata provided
        }
    }
  7. Extend AssetRetriever and PublicationParser

    develop

    You can customize how the toolkit handles files and formats by providing custom implementations or using composite patterns.

    Customizing Parsing

    • Use DefaultPublicationParser for standard behavior.
    • Use CompositePublicationParser to combine multiple parsers.
    • Implement your own PublicationParser for a fully custom resolution strategy.

    Customizing Asset Retrieval

    For advanced extensibility, use the AssetRetriever constructor that accepts:

    • ResourceFactory: Handles the URL schemes used to access content.
    • ArchiveOpener: Determines which archive types (ZIP, RAR, etc.) can be opened.
    • FormatSniffer: Identifies file formats recognized by the retriever.

    You can use the toolkit's built-in composite implementations (CompositeResourceFactory, CompositeArchiveOpener, and CompositeFormatSniffer) to easily add your own logic to the existing defaults.

  8. How Navigators work in the Readium Kotlin Toolkit

    develop

    A Navigator is the component responsible for rendering a publication's resources and providing APIs for content navigation.

    Key Mental Models:

    • UI Responsibility: Navigators do not provide a full user interface (like buttons or progress bars). They only provide the view that displays the content. Your application is responsible for building the surrounding UI (bookmarks, sliders, etc.).
    • Implementation Types: Navigators are categorized by how they present content:
      • Visual Navigators: Render content on screen (e.g., EpubNavigatorFragment). These are typically Android Fragments.
      • Media Navigators: Render audio or video (e.g., AudioNavigator). These are often 'chromeless', meaning they have no UI and you must build your own.
      • Specialized Navigators: Such as TtsNavigator (Text-to-Speech) or SelectableNavigator (for content selection).
    • Compatibility: Use publication.conformsTo() to determine which Navigator to instantiate based on the publication's profile.
    if (publication.conformsTo(Publication.Profile.EPUB)) {
        // Initialize an `EpubNavigatorFragment`.
    }
  9. How Publication, Link, and Locator models work

    develop

    The toolkit uses specific models to represent the structure and state of a book:

    Publication

    A Publication represents a single ebook, audiobook, or comic. It holds metadata (author, TOC), allows access to content (XHTML, audio), and provides services like text search.

    A Link object is a pointer (URL) to a resource or service with metadata like media type or title. Common Link collections within a Publication include:

    • readingOrder: Resources arranged in reading sequence.
    • resources: Secondary resources (images, fonts) needed for rendering.
    • tableOfContents: A tree of Link objects.
    • links: Additional resources like search web services.

    Locator

    A Locator represents a precise location within a resource. Unlike a Link, it is designed to be stored and shared, containing information like progression percentage, position, or textual context. Use Locator for:

    • Reporting current progression.
    • Saving bookmarks, highlights, and annotations.
    • Navigating search results.
  10. How Assets, Resources, and Containers work

    develop

    Readium uses a hierarchy of abstractions to manage data access:

    Asset

    An Asset represents a file or package. You obtain these via an AssetRetriever.

    • ContainerAsset: A package containing multiple resources (e.g., a ZIP archive).
    • ResourceAsset: A single resource (e.g., a JSON or PDF file). Use asset.format.conformsTo(Specification...) to check for capabilities like Lcp or Epub.

    Resource

    A Resource provides read access to a single file or archive entry. These are typically created by a ResourceFactory and support various protocols (local files, HTTP, Android Content Providers).

    Container

    A Container<Resource> provides read access to a collection of resources. Archives are usually opened via an ArchiveOpener (e.g., ZipArchiveOpener).