diff --git a/.github/workflows/extensions.yml b/.github/workflows/extensions.yml index a9141bf..eb73062 100644 --- a/.github/workflows/extensions.yml +++ b/.github/workflows/extensions.yml @@ -48,10 +48,13 @@ jobs: env: CROSS_COMPILE: ${{ github.workspace }}/toolchains/rockbox-arm/bin/arm-elf-eabi- run: | + pipx run ruff==0.12.12 check . + pipx run ruff==0.12.12 format --check themes tools tests make -j8 make check python3 tools/catalog.py preview python3 -m unittest discover -s tests + python3 -m unittest discover -s themes/tests - name: Select tagged package if: github.ref_type == 'tag' shell: bash diff --git a/.gitignore b/.gitignore index 539fdcf..fb4414a 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ -/build/ +build/ __pycache__/ +.ruff_cache/ .DS_Store +themes/dist/ +*.rvt diff --git a/Makefile b/Makefile index 32d96f0..13d3858 100644 --- a/Makefile +++ b/Makefile @@ -1,23 +1,38 @@ # SPDX-License-Identifier: GPL-3.0-only SDK ?= ../osos-lab/rvx-sdk OUT ?= build -extensions := balance crossfeed dsp night-shift playback-log +extensions := album-artists appearance balance clicker-modes crossfeed dsp equalizer \ + eu-volume-limit file-info homebrew iap-auth-bypass night-shift playback-log \ + playback-queue .PHONY: all $(extensions) -all: $(extensions) +all: $(extensions) $(OUT)/assets.json $(extensions): $(MAKE) -C extensions/$@ all SDK="$(abspath $(SDK))" OUT="$(abspath $(OUT))/.work/$@" @mkdir -p "$(OUT)/Extensions" cp "$(OUT)/.work/$@/$@.rvx" "$(OUT)/Extensions/$@.rvx" +# The bitmap assets of the core and every extension, for the theme tooling +# (themes/docs/catalog.md). +$(OUT)/assets.json: $(extensions) + cat "$(abspath $(SDK))/assets.json" > $@ + @for extension in $(extensions); do \ + $(PYTHON) "$(abspath $(SDK))/assets.py" extensions/$$extension/manifest.toml \ + "$(OUT)/Extensions/$$extension.rvx" >> $@ || exit 1; \ + done + .PHONY: check check: + $(PYTHON) extensions/album-artists/tests/run.py "$(abspath $(SDK))" + $(PYTHON) extensions/appearance/tests/run.py "$(abspath $(SDK))" $(PYTHON) extensions/balance/tests/run.py "$(abspath $(SDK))" $(PYTHON) extensions/crossfeed/tests/run.py "$(abspath $(SDK))" $(PYTHON) extensions/dsp/tests/run.py "$(abspath $(SDK))" + $(PYTHON) extensions/equalizer/tests/run.py "$(abspath $(SDK))" + $(PYTHON) extensions/file-info/tests/run.py "$(abspath $(SDK))" @mkdir -p "$(OUT)" - $(CC) $(TEST_FLAGS) extensions/night-shift/test.c -o "$(OUT)/test-night-shift" + $(CC) $(TEST_FLAGS) -Iextensions/shared extensions/night-shift/test.c -o "$(OUT)/test-night-shift" "$(OUT)/test-night-shift" $(CC) $(TEST_FLAGS) extensions/playback-log/test.c -o "$(OUT)/test-playback-log" "$(OUT)/test-playback-log" diff --git a/NOTICE b/NOTICE index 8f60e86..d463540 100644 --- a/NOTICE +++ b/NOTICE @@ -4,7 +4,28 @@ Balance, Crossfeed, DSP and the Night Shift scheduling and gamma code are from RevolaOS extensions, revision 36d197b180e55a304ea0468de4330c0d07fe715f. Night Shift derives from kayboll’s RepriseOS work. Playback Log derives from the work of brilliant-alien and lgreitis in osos-lab. Its Settings artwork is -from osos-lab commit 10485fa. The original RevolaOS notice follows. +from osos-lab commit 10485fa. Album Artists, File Info and Playback Queue are +from RevolaOS extensions, revision 900d5c4ea61e31834d85f9b62c353ce48e58419a, +and derive from the RepriseOS core: Album Artists by lgreitis, File Info by +lgreitis and paviro, Play Next and Play Last by lgreitis and brilliant-alien, +and Up Next by Alex Ball. Their Settings icons are Cupertino Icons glyphs +(MIT), see the LICENSE.cupertino-icons beside each. Equalizer, Clicker Modes, +iAP Auth Bypass and EU Volume Limit are from RevolaOS extensions, revision +509cd1630325a53495798541c170e72854bbb17e. Equalizer, Clicker Modes and iAP +Auth Bypass derive from the RepriseOS core: Custom EQ by lgreitis and paviro, +clicker modes by Alex Ball and lgreitis, iAP auth bypass by RaduTek; EU Volume +Limit is by paviro. Equalizer's Settings icon is the core's own settings-eq +art; the other three are Cupertino Icons glyphs (MIT), see the +LICENSE.cupertino-icons beside each. Homebrew is from RevolaOS extensions, +revision 509cd1630325a53495798541c170e72854bbb17e, and derives from the +RepriseOS core's homebrew patch by lgreitis; its catalog icon is a Cupertino +Icons glyph (MIT). Appearance is from RevolaOS extensions, revision +a32d616f5a06, and derives from the RepriseOS core's Dark Mode by lgreitis and +Alex Ball; its Settings icons are Cupertino Icons glyphs (MIT), see the +LICENSE.cupertino-icons beside them, and the Classic theme it carries is built +by the rvt compiler in themes/ (see themes/NOTICE). Night Shift's hosted row and +choice screen are from RevolaOS extensions, revision d04fa7d. The original +RevolaOS notice follows. RevolaOS Copyright (C) 2026 The RevolaOS Authors. GPL-3.0-only. diff --git a/README.md b/README.md index c7692aa..3148bb0 100644 --- a/README.md +++ b/README.md @@ -2,9 +2,18 @@ This repository hosts the source for these RepriseOS extensions and accepts proposals for the extension catalog. +- [Appearance](extensions/appearance/) adds Dark Mode with Auto, accent colours and themes from `/Reprise/Themes` that recolour the screens and replace the artwork. - [Balance](extensions/balance/) adjusts the volume of the left and right channels independently of the main volume. -- [Night Shift](extensions/night-shift/) warms the display manually or automatically from sunset to sunrise. +- [Night Shift](extensions/night-shift/) warms the display manually or automatically from sunset to sunrise; its row joins the Appearance menu when that extension runs. - [Playback Log](extensions/playback-log/) records listening history for scrobbling and optional detailed reports. +- [Album Artists](extensions/album-artists/) lists the library by Album Artist, with the Artist as the fallback. +- [File Info](extensions/file-info/) shows an item's tags and file properties from its context menu. +- [Playback Queue](extensions/playback-queue/) adds Play Next, Play Last and an Up Next screen to edit the queue. - [Crossfeed](extensions/crossfeed/) blends a little of each stereo channel into the other for headphone listening. It uses the included [DSP library](extensions/dsp/). +- [Equalizer](extensions/equalizer/) runs the EQ presets without distortion and adds a Custom preset with five bands. It uses the included [DSP library](extensions/dsp/). +- [Clicker Modes](extensions/clicker-modes/) lets Settings > Clicker choose the speaker, the headphones, both or off. +- [iAP Auth Bypass](extensions/iap-auth-bypass/) lets accessories use authentication-gated iAP commands without an Apple authentication chip. +- [EU Volume Limit](extensions/eu-volume-limit/) gives an EU iPod the volume behaviour of a non-EU one when its limit switch is off. +- [Homebrew](extensions/homebrew/) lists apps and games from `/Reprise/Apps` and `/Reprise/Games` under Extras and starts them without an Apple signature. To add your extension to the catalog, open a PR following the [submission guide](catalog/README.md). Later releases are picked up automatically. diff --git a/catalog/sources.toml b/catalog/sources.toml index 1e88372..ae6140d 100644 --- a/catalog/sources.toml +++ b/catalog/sources.toml @@ -8,6 +8,11 @@ repo = "RepriseOS/repriseos-extensions" path = "extensions/crossfeed" tag_prefix = "crossfeed/v" +[appearance] +repo = "RepriseOS/repriseos-extensions" +path = "extensions/appearance" +tag_prefix = "appearance/v" + [night-shift] repo = "RepriseOS/repriseos-extensions" path = "extensions/night-shift" @@ -22,3 +27,43 @@ tag_prefix = "playback-log/v" repo = "RepriseOS/repriseos-extensions" path = "extensions/dsp" tag_prefix = "dsp/v" + +[album-artists] +repo = "RepriseOS/repriseos-extensions" +path = "extensions/album-artists" +tag_prefix = "album-artists/v" + +[file-info] +repo = "RepriseOS/repriseos-extensions" +path = "extensions/file-info" +tag_prefix = "file-info/v" + +[playback-queue] +repo = "RepriseOS/repriseos-extensions" +path = "extensions/playback-queue" +tag_prefix = "playback-queue/v" + +[equalizer] +repo = "RepriseOS/repriseos-extensions" +path = "extensions/equalizer" +tag_prefix = "equalizer/v" + +[clicker-modes] +repo = "RepriseOS/repriseos-extensions" +path = "extensions/clicker-modes" +tag_prefix = "clicker-modes/v" + +[iap-auth-bypass] +repo = "RepriseOS/repriseos-extensions" +path = "extensions/iap-auth-bypass" +tag_prefix = "iap-auth-bypass/v" + +[eu-volume-limit] +repo = "RepriseOS/repriseos-extensions" +path = "extensions/eu-volume-limit" +tag_prefix = "eu-volume-limit/v" + +[homebrew] +repo = "RepriseOS/repriseos-extensions" +path = "extensions/homebrew" +tag_prefix = "homebrew/v" diff --git a/extensions/album-artists/Makefile b/extensions/album-artists/Makefile new file mode 100644 index 0000000..0266815 --- /dev/null +++ b/extensions/album-artists/Makefile @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: GPL-3.0-only +main_SOURCES := main.c fields.c browser.c +include $(SDK)/rv.mk diff --git a/extensions/album-artists/README.md b/extensions/album-artists/README.md new file mode 100644 index 0000000..9d340b6 --- /dev/null +++ b/extensions/album-artists/README.md @@ -0,0 +1,21 @@ +# Album Artists + +Partly adapted from the RepriseOS core's [Album Artists](https://github.com/RepriseOS/repriseos/blob/bfedd72/payload/album_artists.c) and its [index](https://github.com/RepriseOS/repriseos/blob/bfedd72/payload/album_artists_index.h), by lgreitis. + +Adds Album Artists after Artists in Music, and optionally to the main menu, listing the library by the iTunes Album Artist tag with the Artist as the fallback. Opening a group shows its albums with their artists as subtitles and their artwork, on the stock Artists and Albums screens. Settings > Music Menu and Main Menu show or hide the two rows. + +| | | +|---|---| +| Sort | the Sort Album Artist or Sort Artist tag when iTunes set one; otherwise the name, with Apple's rules for leading articles | +| Jump letters | from the Sort As text, "#" for digits and symbols | +| No artist | one "Unknown" group | + +Apple's importer discards the Album Artist, Sort Artist and Sort Album Artist tags, so the extension keeps them while the library loads. A song whose Album Artist is its Artist and that carries no Sort As tag is not kept: it lands in the same group either way. File Info shows an Album Artist row for the songs whose Album Artist differs from their Artist. + +On first start the two rows take over the Music Menu and Main Menu checkboxes of the Album Artists row that earlier RepriseOS releases built in. + +| | | +|---|---| +| Default | on | +| Memory | 20 bytes per song whose Album Artist differs from its Artist or that carries a Sort As tag, plus those strings in Apple's artist cache; up to twice that as the load finishes; the list's rows while the list is open and until Apple's selection and artwork cache let it go | +| Settings | the two menu visibility flags | diff --git a/extensions/album-artists/assets/LICENSE.cupertino-icons b/extensions/album-artists/assets/LICENSE.cupertino-icons new file mode 100644 index 0000000..581f84c --- /dev/null +++ b/extensions/album-artists/assets/LICENSE.cupertino-icons @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2016 Vladimir Kharlampidi + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/extensions/album-artists/assets/settings-album-artists.png b/extensions/album-artists/assets/settings-album-artists.png new file mode 100644 index 0000000..81097bb Binary files /dev/null and b/extensions/album-artists/assets/settings-album-artists.png differ diff --git a/extensions/album-artists/assets/settings-album-artists.svg b/extensions/album-artists/assets/settings-album-artists.svg new file mode 100644 index 0000000..484ca79 --- /dev/null +++ b/extensions/album-artists/assets/settings-album-artists.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/extensions/album-artists/browser.c b/extensions/album-artists/browser.c new file mode 100644 index 0000000..a5abadb --- /dev/null +++ b/extensions/album-artists/browser.c @@ -0,0 +1,928 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The Album Artists list reuses the stock Artists screen on a browser of the + * extension's own: a child of the shared music browser whose artist rows this + * file builds, grouped by the Album Artist of the fields table with the Artist + * as the fallback. Apple's readers of the rows, the artist filter, the album + * grouping and subtitle, the artwork source and the destructor are hooked and + * answer for the owned browsers only; every other browser goes to Apple. + * + * Up to four browsers share the registry; one context per slot remembers + * which are owned. Rows, tokens, jump table and the per-row artwork ids come + * from api->alloc and are freed here before Apple's own clear, which frees + * them with Heap_Free otherwise. + * + * Adapted from RepriseOS payload/album_artists.c and album_artists_index.h + * (bfedd72) by lgreitis. */ + +#include "browser.h" +#include "fields.h" +#include "shared.h" +#include "osos-2.0.5.h" +#include "rv_api.h" +#include "rv_media.h" +#include +#include + +/* An artist row of the browser's artists vector, Apple's layout. */ +struct group { + uint32_t token, display_token; + uint32_t *artwork; /* up to ARTWORK_IDS artwork ids */ + uint32_t artwork_count, albums; +}; + +_Static_assert(offsetof(struct group, artwork) == ArtistGroup_artwork, + "ArtistGroup layout"); +_Static_assert(sizeof(struct group) == ArtistGroup_bytes, "ArtistGroup layout"); +#define ARTWORK_IDS 10 + +/* An album row of the browser's albums vector, Apple's layout. */ +struct album { + uint32_t token, artist, display_artist, artwork, tracks, flags; +}; + +_Static_assert(sizeof(struct album) == AlbumGroup_bytes, "AlbumGroup layout"); + +/* One eligible track while the rows are built: its artist token, then the + * group it fell into, and its position in the list order. */ +struct track { + union { + uint32_t token; + uint32_t group_index; + }; + + uint32_t order; +}; + +struct context { + void *browser, *track_data; + void *model_reference; /* non-owning; the model's destructor clears the context */ +}; +static struct context contexts[4]; + +/* The artwork model the album source of an open list reads through, with a + * reference that keeps the owned model alive for as long as Apple's artwork + * cache holds the provider. */ +struct artwork_model { + uint8_t native[LibraryBrowser_bytes]; + void *owner_reference; +}; + +#define ARTWORK_MODEL_OWNERSHIP 0x80 /* ours; Apple's ownership values stay below */ +static void *artwork_model_reference; +static unsigned custom_artwork_providers; + +static const uint16_t unknown[] = {'U', 'n', 'k', 'n', 'o', 'w', 'n'}; + +static void *zalloc(uint32_t bytes) +{ + return api->alloc(self, bytes); +} + +static void release(void *block) +{ + if (block) + api->free(self, block); +} + +static struct context *context_for(void *browser) +{ + for (unsigned i = 0; i < 4; i++) + if (browser && contexts[i].browser == browser) + return &contexts[i]; + return NULL; +} + +static void *browser_of(void *model) +{ + return RV_FIELD(model, LibraryBrowser_browser, void *); +} + +static void *track_data_of(void *browser) +{ + return RV_FIELD(MediaBrowser_GetOwner(browser), MediaBrowser_track_data, void *); +} + +static void *artist_cache(void *track_data) +{ + return (uint8_t *)track_data + TrackData_artist_cache; +} + +static uint32_t token_view(void *track_data, uint32_t token, const uint16_t **text) +{ + uint32_t bytes = 0; + *text = NULL; + if (!token || StringCache_GetTokenView(artist_cache(track_data), token, + (void **)text, &bytes)) + return 0; + return bytes / 2; +} + +/* The group a record belongs to: its Album Artist, else its Artist. */ +static uint32_t resolved_artist_token(const void *record) +{ + const uint16_t *text; + void *track_data = RV_FIELD(record, 0, void *); + uint32_t token = fields_token(record); + if (token && token_view(track_data, token, &text)) + return token; + token = RV_FIELD(record, MediaRecord_artist, uint32_t); + return token && token_view(track_data, token, &text) ? token : 0; +} + +static uint32_t artist_name_view(void *track_data, uint32_t token, + const uint16_t **text) +{ + uint32_t units = token_view(track_data, token, text); + if (!units) { + *text = unknown; + units = sizeof unknown / sizeof *unknown; + } + return units; +} + +static int compare_artist_names(void *track_data, uint32_t a, uint32_t b) +{ + if (a == b) + return 0; + const uint16_t *left, *right; + uint32_t left_units = artist_name_view(track_data, a, &left); + uint32_t right_units = artist_name_view(track_data, b, &right); + return SongText_CompareUtf16(NULL, left, left_units, right, right_units); +} + +/* The text a group sorts by: its Sort As, else its name. */ +static uint32_t artist_sort_view(void *track_data, const void *record, + const uint16_t **text) +{ + uint32_t token = fields_token(record); + int has_album_artist = token && token_view(track_data, token, text); + uint32_t units = + token_view(track_data, fields_sort_token(record, has_album_artist), text); + if (units) + return units; + return artist_name_view(track_data, resolved_artist_token(record), text); +} + +/* Sorting of tracks, with the incoming order as the final tie-breaker. */ + +typedef int (*track_compare)(void *, const struct track *, const struct track *); + +static int compare_tracks(const struct track *a, const struct track *b, + track_compare compare, void *context) +{ + int result = compare(context, a, b); + return result ? result : (a->order > b->order) - (a->order < b->order); +} + +static void sift(struct track *tracks, uint32_t root, uint32_t count, + track_compare compare, void *context) +{ + while (root < count / 2) { + uint32_t child = root * 2 + 1; + if (child + 1 < count && + compare_tracks(&tracks[child], &tracks[child + 1], compare, context) < 0) + child++; + if (compare_tracks(&tracks[root], &tracks[child], compare, context) >= 0) + break; + struct track swap = tracks[root]; + tracks[root] = tracks[child]; + tracks[child] = swap; + root = child; + } +} + +static void sort_tracks(struct track *tracks, uint32_t count, track_compare compare, + void *context) +{ + for (uint32_t i = count / 2; i; i--) + sift(tracks, i - 1, count, compare, context); + for (uint32_t i = count; i > 1; i--) { + struct track swap = tracks[0]; + tracks[0] = tracks[i - 1]; + tracks[i - 1] = swap; + sift(tracks, 0, i - 1, compare, context); + } +} + +/* Puts rows into the order `order` lists them, in place. */ +static void reorder(struct group *rows, struct track *order, uint32_t count) +{ + for (uint32_t i = 0; i < count; i++) { + struct group saved = rows[i]; + uint32_t current = i; + while (order[current].group_index != i) { + uint32_t next = order[current].group_index; + rows[current] = rows[next]; + order[current].group_index = current; + current = next; + } + rows[current] = saved; + order[current].group_index = current; + } +} + +/* Apple's jump table: a count, then (letter, first index) pairs, then a + * (0, UINT32_MAX) end marker. */ +static int valid_jumps(const uint32_t *jump, uint32_t tracks) +{ + if (!jump || !jump[0] || jump[0] > tracks || jump[2] != 0) + return 0; + for (uint32_t i = 0; i < jump[0]; i++) + if (jump[i * 2 + 2] >= tracks || (i && jump[i * 2 + 2] <= jump[i * 2])) + return 0; + return 1; +} + +static uint16_t jump_letter(const uint32_t *jump, uint32_t index) +{ + uint32_t low = 0, high = jump[0]; + while (low + 1 < high) { + uint32_t middle = low + (high - low) / 2; + if (jump[middle * 2 + 2] <= index) + low = middle; + else + high = middle; + } + return (uint16_t)jump[low * 2 + 1]; +} + +static int compare_track_artists(void *track_data, const struct track *a, + const struct track *b) +{ + return compare_artist_names(track_data, a->token, b->token); +} + +/* Where the tracks come from: the list, through Apple's native Album Artist + * order when the import built one, else the album order, which keeps an + * album's tracks together so each album is one run. */ +struct source { + struct MediaList *list; + uint8_t *order; /* a MediaOrder, or NULL */ +}; + +static struct MediaEntry *source_entry(const struct source *source, uint32_t index) +{ + if (source->order) + return ((struct MediaEntry **)(source->order + MediaOrder_entries))[index]; + return MediaList_GetEntryByOrderIndex(source->list, MediaOrderMode_Album, 0, index); +} + +static const void *entry_record(const struct MediaEntry *entry) +{ + return RV_FIELD(entry, MediaEntry_song_record, const void *); +} + +struct group_sort { + void *track_data; + struct group *rows; + struct source source; +}; + +static int compare_group_order(void *opaque, const struct track *a, + const struct track *b) +{ + struct group_sort *sort = opaque; + if (sort->source.order) + return (a->order > b->order) - (a->order < b->order); + const uint16_t *left, *right; + uint32_t left_units = artist_sort_view( + sort->track_data, entry_record(source_entry(&sort->source, a->order)), &left); + uint32_t right_units = artist_sort_view( + sort->track_data, entry_record(source_entry(&sort->source, b->order)), &right); + int result = SongText_CompareUtf16(NULL, left, left_units, right, right_units); + return result ? result + : compare_artist_names(sort->track_data, + sort->rows[a->group_index].token, + sort->rows[b->group_index].token); +} + +static uint16_t artist_letter(void *track_data, const void *record) +{ + const uint16_t *text; + uint32_t units = artist_sort_view(track_data, record, &text); + while (units && *text <= ' ') { + text++; + units--; + } + if (!units) + return '#'; + for (uint16_t letter = 'A'; letter <= 'Z'; letter++) + if (!SongText_CompareUtf16(NULL, text, 1, &letter, 1)) + return letter; + return *text < 0x80 || (*text >= 0xd800 && *text <= 0xdfff) ? '#' : *text; +} + +static struct group *groups_of(void *browser) +{ + return RV_FIELD(browser, MediaBrowser_artists, struct group *); +} + +static uint32_t group_count(void *browser) +{ + return (uint32_t)(RV_FIELD(browser, MediaBrowser_artists + sizeof(void *), + struct group *) - + groups_of(browser)); +} + +/* Frees the rows and their arrays of an owned browser and leaves the words + * Apple's clear would free empty. */ +static void drop_rows(void *browser) +{ + struct group *rows = groups_of(browser); + uint32_t count = group_count(browser); + for (uint32_t i = 0; i < count; i++) + release(rows[i].artwork); + release(rows); + for (unsigned i = 0; i < 3; i++) + RV_FIELD(browser, MediaBrowser_artists + i * sizeof(void *), void *) = NULL; + release(RV_FIELD(browser, MediaBrowser_artist_tokens, void *)); + RV_FIELD(browser, MediaBrowser_artist_tokens, void *) = NULL; + release(RV_FIELD(browser, MediaBrowser_artist_jump, void *)); + RV_FIELD(browser, MediaBrowser_artist_jump, void *) = NULL; + RV_FIELD(browser, MediaBrowser_artist_count, uint32_t) = 0; +} + +static void clear_groups(void *browser) +{ + drop_rows(browser); + MediaBrowser_ClearArtists(browser); + MediaBrowser_ClearAlbums(browser); + MediaBrowser_ClearSongs(browser); + /* Apple's clear keeps the albums vector's capacity; an owned browser + * releases it too. */ + Heap_Free(RV_FIELD(browser, MediaBrowser_albums, void *)); + for (unsigned i = 0; i < 3; i++) + RV_FIELD(browser, MediaBrowser_albums + i * sizeof(void *), void *) = NULL; +} + +void browser_invalidate(void *track_data) +{ + for (unsigned i = 0; i < 4; i++) { + struct context *context = &contexts[i]; + if (!context->browser || context->track_data != track_data) + continue; + clear_groups(context->browser); + /* The TrackData's destruction has unlinked its lists already. */ + RV_FIELD(context->browser, MediaBrowser_list, void *) = NULL; + context->track_data = NULL; + } +} + +/* Building the rows */ + +static void build_group_rows(void *browser, void *track_data, struct track *tracks, + uint32_t used, struct group *rows, + const struct source *source) +{ + uint32_t group = 0, last_album = 0, previous_token = 0; + struct group *row = NULL; + void *owner = MediaBrowser_GetOwner(browser); + for (uint32_t i = 0; i < used; i++) { + struct track track = tracks[i]; + if (!i || compare_artist_names(track_data, previous_token, track.token)) { + row = &rows[group]; + *row = (struct group){track.token, 0, NULL, 0, 0}; + /* One representative per group, in the consumed track slots. */ + tracks[group] = (struct track){.group_index = group, .order = track.order}; + group++; + last_album = 0; + } + previous_token = track.token; + const void *record = entry_record(source_entry(source, track.order)); + uint32_t album = RV_FIELD(record, MediaRecord_album, uint32_t); + if (!album || album == last_album) + continue; + last_album = album; + row->albums++; + if (row->artwork_count == ARTWORK_IDS) + continue; + uint32_t artwork = MediaBrowser_GetRecordArtworkId(owner, (void *)record); + if (artwork && !row->artwork) + row->artwork = zalloc(ARTWORK_IDS * sizeof *row->artwork); + if (artwork && row->artwork) + row->artwork[row->artwork_count++] = artwork; + } +} + +static void build_group_jumps(void *track_data, const struct group *rows, + const struct track *tracks, uint32_t groups, + const uint32_t *native_jump, uint32_t *tokens, + uint32_t *jump, const struct source *source) +{ + jump[0] = 0; + for (uint32_t i = 0; i < groups; i++) { + tokens[i] = rows[tracks[i].group_index].token; + uint16_t letter = + native_jump + ? jump_letter(native_jump, tracks[i].order) + : artist_letter(track_data, + entry_record(source_entry(source, tracks[i].order))); + if (!jump[0] || (uint16_t)jump[jump[0] * 2 - 1] != letter) { + jump[jump[0] * 2 + 1] = letter; + jump[jump[0] * 2 + 2] = i; + jump[0]++; + } + } + jump[jump[0] * 2 + 1] = 0; + jump[jump[0] * 2 + 2] = UINT32_MAX; +} + +/* One track per artist and album run; its first track gives the artwork and + * the sort order. Counts when `tracks` is NULL. */ +static uint32_t collect_album_runs(void *browser, const struct source *source, + uint32_t count, struct track *tracks, + uint32_t capacity) +{ + uint32_t used = 0, previous_artist = 0, previous_album = 0; + for (uint32_t i = 0; i < count; i++) { + struct MediaEntry *entry = source_entry(source, i); + const void *record = entry ? entry_record(entry) : NULL; + if (!record || !MediaBrowser_EvaluateEntryFilters(browser, entry, NULL)) + continue; + uint32_t artist = resolved_artist_token(record); + uint32_t album = RV_FIELD(record, MediaRecord_album, uint32_t); + if (used && artist == previous_artist && album == previous_album) + continue; + if (tracks) { + if (used == capacity) + return 0; + tracks[used] = (struct track){.token = artist, .order = i}; + } + previous_artist = artist; + previous_album = album; + used++; + } + return used; +} + +static uint32_t build(void *browser) +{ + struct context *context = context_for(browser); + if (RV_FIELD(browser, MediaBrowser_artist_tokens, void *)) + return group_count(browser); + void *track_data = track_data_of(browser); + context->track_data = track_data; + struct MediaList *list = MediaBrowser_GetCurrentList(browser); + if (!track_data || !list || !RV_FIELD(list, MediaList_root, void *)) + return 0; + uint32_t count = RV_FIELD(RV_FIELD(list, MediaList_root, uint8_t *), + MediaEntry_tracks, uint16_t); + if (!count) + return 0; + /* Apple's Album Artist order exists only when the import built it; there + * is no comparator to rebuild it, so it is consumed when complete. */ + uint8_t *order = + RV_FIELD(list, MediaList_order_index + AlbumArtist_order_mode * sizeof(void *), + uint8_t *); + if (order && (RV_FIELD(order, MediaOrder_count, uint32_t) != count || + RV_FIELD(order, MediaOrder_capacity, uint32_t) < count)) + order = NULL; + const uint32_t *native_jump = + order ? RV_FIELD(list, + MediaList_jump_index + AlbumArtist_order_mode * sizeof(void *), + uint32_t *) + : NULL; + if (!valid_jumps(native_jump, count)) + native_jump = NULL; + TrackData_AcquireStringCaches(track_data); + struct source source = {list, order}; + uint32_t runs = collect_album_runs(browser, &source, count, NULL, 0); + struct track *tracks = runs ? zalloc(runs * sizeof *tracks) : NULL; + uint32_t used = + tracks ? collect_album_runs(browser, &source, count, tracks, runs) : 0; + uint32_t groups = 0; + struct group *rows = NULL; + uint32_t *tokens = NULL, *jump = NULL; + if (!used) + goto done; + sort_tracks(tracks, used, compare_track_artists, track_data); + for (uint32_t i = 0; i < used; i++) + if (!i || + compare_artist_names(track_data, tracks[i - 1].token, tracks[i].token)) + groups++; + rows = zalloc(groups * sizeof *rows); + tokens = zalloc(groups * sizeof *tokens); + jump = zalloc((groups * 2 + 3) * sizeof *jump); + if (!rows || !tokens || !jump) { + release(rows); + release(tokens); + release(jump); + groups = 0; + goto done; + } + build_group_rows(browser, track_data, tracks, used, rows, &source); + struct group_sort sort = {track_data, rows, source}; + sort_tracks(tracks, groups, compare_group_order, &sort); + build_group_jumps(track_data, rows, tracks, groups, native_jump, tokens, jump, + &source); + reorder(rows, tracks, groups); + drop_rows(browser); + RV_FIELD(browser, MediaBrowser_artists, struct group *) = rows; + RV_FIELD(browser, MediaBrowser_artists + sizeof(void *), struct group *) = + rows + groups; + RV_FIELD(browser, MediaBrowser_artists + 2 * sizeof(void *), struct group *) = + rows + groups; + RV_FIELD(browser, MediaBrowser_artist_tokens, uint32_t *) = tokens; + RV_FIELD(browser, MediaBrowser_artist_jump, uint32_t *) = jump; + RV_FIELD(browser, MediaBrowser_artist_count, uint32_t) = groups; +done: + TrackData_ReleaseStringCaches(track_data); + release(tracks); + return groups; +} + +/* Hooks */ + +/* MediaBrowser_BuildArtists on an owned browser builds here. The slot takes + * the model, the call sites the browser. */ +uint32_t build_artists(uint32_t browser, const void *next) +{ + if (!context_for(ptr(browser))) + return api->hook_next(next, browser, 0, 0, 0, 0, 0); + return build(ptr(browser)); +} + +uint32_t build_artists_slot(uint32_t model, const void *next) +{ + void *browser = browser_of(ptr(model)); + if (!context_for(browser)) + return api->hook_next(next, model, 0, 0, 0, 0, 0); + return build(browser); +} + +/* Apple's clear of an owned browser's rows: ours go first, so its Heap_Free + * sees nothing of them. */ +uint32_t clear_artists(uint32_t browser, const void *next) +{ + if (context_for(ptr(browser))) + drop_rows(ptr(browser)); + return api->hook_next(next, browser, 0, 0, 0, 0, 0); +} + +/* A group's name as a counted UTF-16 string of at most 255 units, Apple's + * status: 0, or -50 for an index outside the rows. */ +static int group_name(void *browser, int index, uint16_t *counted) +{ + counted[0] = 0; + if (index < 0 || (uint32_t)index >= group_count(browser)) + return -50; + void *track_data = track_data_of(browser); + TrackData_AcquireStringCaches(track_data); + const uint16_t *text; + uint32_t units = + artist_name_view(track_data, groups_of(browser)[index].token, &text); + if (units > 255) + units = 255; + if (units && text[units - 1] >= 0xd800 && text[units - 1] <= 0xdbff) + units--; + counted[0] = (uint16_t)units; + for (uint32_t i = 0; i < units; i++) + counted[i + 1] = text[i]; + TrackData_ReleaseStringCaches(track_data); + return 0; +} + +static int group_letter(void *browser, int index, uint16_t *counted) +{ + counted[0] = 0; + if (index < 0 || (uint32_t)index >= group_count(browser)) + return -50; + counted[0] = 1; + counted[1] = jump_letter( + RV_FIELD(browser, MediaBrowser_artist_jump, const uint32_t *), (uint32_t)index); + return 0; +} + +/* Whether the entry is outside the selected group, with the caches pinned by + * Apple's filter evaluation. */ +static int outside_selected_group(void *browser, const struct MediaEntry *entry) +{ + int index = RV_FIELD(browser, MediaBrowser_selected_artist, int); + if (index < 0) + return 0; + const void *record = entry_record(entry); + if ((uint32_t)index >= group_count(browser) || !record) + return 1; + return compare_artist_names(track_data_of(browser), groups_of(browser)[index].token, + resolved_artist_token(record)) != 0; +} + +/* The subtitle of an album row: its artist's name. */ +static void album_artist_subtitle(void *browser, int index, struct NativeString *out) +{ + struct album *begin = RV_FIELD(browser, MediaBrowser_albums, struct album *); + struct album *end = RV_FIELD(browser, MediaBrowser_albums_end, struct album *); + if (index < 0 || index >= end - begin) + return; + void *track_data = track_data_of(browser); + TrackData_AcquireStringCaches(track_data); + const uint16_t *text; + uint32_t units = artist_name_view(track_data, begin[index].artist, &text); + NativeString_AssignUtf16(out, text, (int)units); + TrackData_ReleaseStringCaches(track_data); +} + +uint32_t read_artist_name(uint32_t browser, uint32_t index, uint32_t out, + const void *next) +{ + if (!context_for(ptr(browser))) + return api->hook_next(next, browser, index, out, 0, 0, 0); + return (uint32_t)group_name(ptr(browser), (int)index, ptr(out)); +} + +uint32_t read_artist_jump_label(uint32_t browser, uint32_t index, uint32_t out, + const void *next) +{ + if (!context_for(ptr(browser))) + return api->hook_next(next, browser, index, out, 0, 0, 0); + return (uint32_t)group_letter(ptr(browser), (int)index, ptr(out)); +} + +/* The artist filter's compare in MediaBrowser_EvaluateEntryFilters: an owned + * browser matches the entry against the selected group instead of the artist + * text. Nonzero rejects the entry. */ +uint32_t artist_filter_compare(uint32_t browser, uint32_t left, uint32_t left_units, + uint32_t right, const void *next, uint32_t right_units, + uint32_t entry) +{ + if (!context_for(ptr(browser))) + return api->hook_next(next, 0, left, left_units, right, right_units, entry); + return (uint32_t)outside_selected_group(ptr(browser), ptr(entry)); +} + +/* MediaBrowser_BuildAlbums' accumulator, through the literal it loads: an + * owned browser groups its albums by the album token, with the resolved + * artist for the subtitle. ARM: AlbumGroupVector_Append ends in Apple's + * memcpy, which returns with mov pc, lr. */ +RV_ARM int album_group(void *browser, void *callback, uint32_t field_low, + uint32_t field_high, uint32_t index, struct MediaEntry *entry, + void *record, int first) +{ + if (!context_for(browser)) + return MediaBrowser_AccumulateAlbumGroup( + browser, callback, field_low, field_high, index, entry, record, first); + struct album *begin = RV_FIELD(browser, MediaBrowser_albums, struct album *); + struct album *end = RV_FIELD(browser, MediaBrowser_albums_end, struct album *); + if (first && begin != end) + return 0; + uint32_t album = RV_FIELD(record, MediaRecord_album, uint32_t); + if (!album) + return 1; + if (begin == end || end[-1].token != album) { + struct album row = { + album, + resolved_artist_token(record), + 0, + MediaBrowser_GetRecordArtworkId(MediaBrowser_GetOwner(browser), record), + 0, + ((RV_FIELD(record, MediaRecord_flags_15, uint8_t) & + MediaRecordFlags15_Compilation) + ? 1 + : 0) | + ((RV_FIELD(record, MediaRecord_flags_8f, uint8_t) & + MediaRecordFlags8F_PlaceholderAlbum) + ? 2 + : 0)}; + AlbumGroupVector_Append((uint8_t *)browser + MediaBrowser_albums, &row); + end = RV_FIELD(browser, MediaBrowser_albums_end, struct album *); + } + end[-1].tracks++; + return 1; +} + +uint32_t album_subtitle(uint32_t model, uint32_t index, uint32_t out, const void *next) +{ + void *browser = browser_of(ptr(model)); + if (!context_for(browser)) + return api->hook_next(next, model, index, out, 0, 0, 0); + album_artist_subtitle(browser, (int)index, ptr(out)); + return 0; +} + +/* Artwork: the album source of an owned list reads through a borrowed + * model of its own, so Apple's artwork cache can outlive the screen. */ + +static int release_artwork(void) +{ + if (custom_artwork_providers) { + void *session = ListArtworkSession_Get(); + if (session) { + void *previous = artwork_model_reference; + artwork_model_reference = NULL; + ArtworkSession_Stop(session); + ListArtworkSession_SetSource(session, AlbumArtwork_Selector); + artwork_model_reference = previous; + } + } + return !custom_artwork_providers; +} + +uint32_t select_artwork_source(uint32_t selection, uint32_t category, const void *next) +{ + void *reference = (uint8_t *)ptr(selection) + MediaListSelection_model; + void *model = LibraryModelRef_Get(reference); + int custom = + category == ArtworkCategory_Albums && model && context_for(browser_of(model)); + /* The provider and cache are made again even when both screens are album + * categories. */ + if (custom || custom_artwork_providers) + RV_FIELD(ptr(selection), MediaListSelection_artwork_category, uint8_t) = 0; + if (!custom) + release_artwork(); + void *previous = artwork_model_reference; + artwork_model_reference = custom ? reference : NULL; + uint32_t result = api->hook_next(next, selection, category, 0, 0, 0, 0); + artwork_model_reference = previous; + return result; +} + +/* ARM: Runtime_OperatorNew returns with mov pc, lr. */ +RV_ARM uint32_t create_artwork_provider(uint32_t kind, uint32_t selector, + const void *next) +{ + uint32_t provider = api->hook_next(next, kind, selector, 0, 0, 0, 0); + if (!provider || kind != ArtworkSource_SelectorKind || + selector != AlbumArtwork_Selector || !artwork_model_reference) + return provider; + void *owner = LibraryModelRef_Get(artwork_model_reference); + struct artwork_model *model = Runtime_OperatorNew(sizeof *model); + if (!model) + return provider; + LibraryBrowser_InitBorrowed(model, 2, browser_of(owner)); + model->owner_reference = NULL; + LibraryModelRef_Assign(&model->owner_reference, artwork_model_reference); + RV_FIELD(model, LibraryBrowser_ownership, uint8_t) = ARTWORK_MODEL_OWNERSHIP; + custom_artwork_providers++; + void *original = RV_FIELD(ptr(provider), AlbumArtworkProvider_model, void *); + RV_FIELD(ptr(provider), AlbumArtworkProvider_model, void *) = model; + typedef void (*destroy)(void *); + RV_METHOD(original, LibraryBrowser_delete_method, destroy)(original); + return provider; +} + +/* LibraryBrowser_Destroy: the artwork model gives its reference back; an + * owned model's browser drops its rows and context. Apple's body follows. */ +uint32_t destroy_model(uint32_t model, const void *next) +{ + if (RV_FIELD(ptr(model), LibraryBrowser_ownership, uint8_t) == + ARTWORK_MODEL_OWNERSHIP) { + if (custom_artwork_providers) + custom_artwork_providers--; + RV_FIELD(ptr(model), LibraryBrowser_ownership, uint8_t) = + LibraryBrowserOwnership_Borrowed; + LibraryModelRef_Release(&((struct artwork_model *)ptr(model))->owner_reference); + return api->hook_next(next, model, 0, 0, 0, 0, 0); + } + void *browser = browser_of(ptr(model)); + struct context *context = context_for(browser); + if (context && RV_FIELD(ptr(model), LibraryBrowser_ownership, uint8_t) == + LibraryBrowserOwnership_Child) { + if (context->track_data) + MediaBrowser_InvalidateEntryMatches(browser); + clear_groups(browser); + *context = (struct context){0}; + } + return api->hook_next(next, model, 0, 0, 0, 0, 0); +} + +/* Opening the list */ + +static int owns_model(void *model) +{ + struct context *context = model ? context_for(browser_of(model)) : NULL; + return context && context->model_reference && + LibraryModelRef_Get(&context->model_reference) == model; +} + +/* The selection may still hold an owned model after its screens closed; when + * it is the sole owner, a stock model takes its place so the registry slot + * and the rows go. */ +static void release_cached_selection(void) +{ + void *selection = MediaListSelection_GetInstance(); + void **reference = (void **)((uint8_t *)selection + MediaListSelection_model); + void *model = LibraryModelRef_Get(reference); + const uint32_t *block = *reference; + if (!owns_model(model) || + RV_FIELD(model, LibraryBrowser_ownership, uint8_t) != + LibraryBrowserOwnership_Child || + !block || block[LibraryModelRefBlock_count / 4] != 1) + return; + void *stock = LibraryBrowser_Create(0); + if (!stock) + return; + void *replacement = NULL; + LibraryModelRef_Init(&replacement, stock, 0); + MediaListSelection_SetList(selection, &replacement, 1, 0, 0); + LibraryModelRef_Release(&replacement); +} + +/* A model over a child browser of the shared music browser, in two free + * registry slots. */ +static void *create_model(void **reference) +{ + if (!release_artwork()) + return NULL; + void **registry = (void **)BrowserRegistry; + unsigned available = 0; + for (unsigned i = 0; i < 4; i++) + available += registry[i] == NULL; + if (available < 2) + return NULL; + void *model = LibraryBrowser_Create(0); + if (!model) + return NULL; + void *browser = NULL; + typedef void (*destroy)(void *); + if (MediaBrowser_CreateChild(browser_of(model), &browser) || !browser) { + RV_METHOD(model, LibraryBrowser_delete_method, destroy)(model); + return NULL; + } + RV_FIELD(model, LibraryBrowser_browser, void *) = browser; + RV_FIELD(model, LibraryBrowser_ownership, uint8_t) = LibraryBrowserOwnership_Child; + LibraryModelRef_Init(reference, model, 0); + return model; +} + +static void *acquire_model(void **reference) +{ + /* The selection or the artwork cache may keep the last model. */ + for (unsigned i = 0; i < 4; i++) + if (contexts[i].model_reference) { + LibraryModelRef_Assign(reference, &contexts[i].model_reference); + return LibraryModelRef_Get(reference); + } + void *model = create_model(reference); + if (!model) + return NULL; + void *browser = browser_of(model); + unsigned slot = RV_FIELD(browser, MediaBrowser_registry_slot, uint8_t); + contexts[slot] = (struct context){browser, track_data_of(browser), *reference}; + return model; +} + +/* The model's query as the stock Artists list configures it: reset, artist + * sort, the kinds the Music menu includes (the kind masks take GameMediaKind + * bits). */ +static void prepare_artists(void *model) +{ + typedef void (*reset)(void *); + typedef void (*configure)(void *, uint32_t, uint32_t); + RV_METHOD(model, LibraryBrowser_reset_method, reset)(model); + RV_METHOD(model, LibraryBrowser_artist_sort_method, reset)(model); + RV_METHOD(model, LibraryBrowser_kind_masks_method, + configure)(model, GameMediaKind_Music | GameMediaKind_MusicVideo, 0); +} + +void browser_open(const struct rv_context *ctx) +{ + void *reference = NULL; + /* The shared music browser's query, which a child browser starts from: + * music only, as the stock Artists row sets it. */ + if (!MusicMenu_ConfigureLibraryBrowser(ctx->controller, MediaKind_Music, 0, 1, + LibraryGrouping_Artists, LibrarySort_Artist, + 0)) + return; + void *model = acquire_model(&reference); + if (!model) + return; + if (!release_artwork()) + goto done; + prepare_artists(model); + if (!build(browser_of(model))) + goto done; + /* The stock Artists screen titles itself from the selection. */ + _Alignas(uint32_t) uint8_t storage[NativeString_bytes]; + struct NativeString *title = + NativeString_InitUtf8((struct NativeString *)storage, "Album Artists"); + MediaListSelection_SetTitle(MediaListSelection_GetInstance(), title); + NativeString_Destroy(title); + void *screen = UI_CreateScreenController( + UI_GetControllerRegistry(), RES_MediaLists_Artists_Screen, + RES_MediaLists_Artists_Screen_Default, Transition_ForegroundPush); + if (!screen) + goto done; + LibraryModelRef_Assign((uint8_t *)screen + MediaListController_model, &reference); + RV_FIELD(screen, MediaListController_created_model, uint8_t) = 0; + rv_controller_push(ctx->controller, screen); +done: + LibraryModelRef_Release(&reference); +} + +/* While the hooks are still bound: the artwork cache and the selection give + * back the models over owned browsers, so none outlives the module. */ +void browser_unload(void) +{ + release_artwork(); + release_cached_selection(); + for (unsigned i = 0; i < 4; i++) { + struct context *context = &contexts[i]; + if (!context->browser) + continue; + if (context->track_data) + MediaBrowser_InvalidateEntryMatches(context->browser); + clear_groups(context->browser); + *context = (struct context){0}; + } +} diff --git a/extensions/album-artists/browser.h b/extensions/album-artists/browser.h new file mode 100644 index 0000000..c9471b3 --- /dev/null +++ b/extensions/album-artists/browser.h @@ -0,0 +1,44 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The Album Artists list: a browser of the extension's own on the stock + * Artists screen, grouped by the fields table's Album Artist with the Artist + * as the fallback. */ + +#ifndef ALBUM_ARTISTS_BROWSER_H +#define ALBUM_ARTISTS_BROWSER_H +#include "rv_api.h" +#include + +/* Opens the list above the menu of `ctx`. */ +void browser_open(const struct rv_context *ctx); + +/* The fields table of `track_data` is going: the owned browsers drop their rows. */ +void browser_invalidate(void *track_data); + +/* On unload: the owned browsers drop their rows and contexts. */ +void browser_unload(void); + +/* The handlers main.c binds: MediaBrowser_BuildArtists through the model's + * slot and its two call sites, Apple's clear of the rows, the row readers, + * the artist filter compare, the album accumulator BuildAlbums loads from + * its literal, the album subtitle, the artwork source and provider, and + * LibraryBrowser_Destroy. */ +uint32_t build_artists_slot(uint32_t model, const void *next); +uint32_t build_artists(uint32_t browser, const void *next); +uint32_t clear_artists(uint32_t browser, const void *next); +uint32_t read_artist_name(uint32_t browser, uint32_t index, uint32_t out, + const void *next); +uint32_t read_artist_jump_label(uint32_t browser, uint32_t index, uint32_t out, + const void *next); +uint32_t artist_filter_compare(uint32_t browser, uint32_t left, uint32_t left_units, + uint32_t right, const void *next, uint32_t right_units, + uint32_t entry); +struct MediaEntry; +int album_group(void *browser, void *callback, uint32_t field_low, uint32_t field_high, + uint32_t index, struct MediaEntry *entry, void *record, int first); +uint32_t album_subtitle(uint32_t model, uint32_t index, uint32_t out, const void *next); +uint32_t select_artwork_source(uint32_t selection, uint32_t category, const void *next); +uint32_t create_artwork_provider(uint32_t kind, uint32_t selector, const void *next); +uint32_t destroy_model(uint32_t model, const void *next); + +#endif diff --git a/extensions/album-artists/fields.c b/extensions/album-artists/fields.c new file mode 100644 index 0000000..5170d81 --- /dev/null +++ b/extensions/album-artists/fields.c @@ -0,0 +1,290 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* Apple's importer discards the Album Artist (mhod 22), Sort Artist (23) and + * Sort Album Artist (29) strings. These hooks intern them in the TrackData's + * artist cache instead and keep one 20-byte row per song that needs one: a + * song whose Album Artist is its Artist and that carries no Sort As stores + * nothing, because the browser resolves a missing Album Artist to the Artist. + * While the import runs the rows collect in fixed chunks; when it ends they + * move into one exact-size block, each chunk freed as it is copied, and the + * block is heapsorted by persistent id for binary search. + * + * The mhods of one mhit are parsed before the next mhit begins, so one + * pending record collects a song's values and is flushed when another record + * arrives and when the dataset parse returns; by then the record's own Artist + * token is final. No token is ever released: a string the cache already holds + * comes back as the same token without a further reference, so one release by + * anyone frees it for every record that names it. The strings live as long as + * the TrackData, whose destruction drops them all. + * + * Based on RepriseOS payload/album_artist.c (bfedd72) by lgreitis. */ + +#include "fields.h" +#include "browser.h" +#include "shared.h" +#include "osos-2.0.5.h" +#include "rv_api.h" +#include + +enum { TOKEN, SORT_ALBUM_ARTIST, SORT_ARTIST, TOKENS }; + +#define CHUNK_ROWS 256 + +struct row { + uint32_t id_low, id_high; + uint32_t tokens[TOKENS]; +}; + +/* The rows of an import in progress, newest chunk first. */ +struct chunk { + struct chunk *next; + uint32_t count; + struct row rows[CHUNK_ROWS]; +}; + +static struct { + void *owner; /* the TrackData of the import, NULL before the first */ + void *cache; /* its artist string cache */ + struct chunk *chunks; + struct row *rows; /* the sorted table once sealed */ + uint32_t count; + uint8_t sealed; /* a later mhod only skips its bytes */ + + struct { + const void *record; + uint32_t tokens[TOKENS]; + } pending; +} table; + +static void drop_chunks(void) +{ + while (table.chunks) { + struct chunk *next = table.chunks->next; + api->free(self, table.chunks); + table.chunks = next; + } +} + +static void clear(void) +{ + if (table.owner) + browser_invalidate(table.owner); + drop_chunks(); + if (table.rows) + api->free(self, table.rows); + table.rows = NULL; + table.count = 0; + table.sealed = 0; + table.pending.record = NULL; + for (unsigned i = 0; i < TOKENS; i++) + table.pending.tokens[i] = 0; +} + +static const uint32_t *persistent_id(const void *record) +{ + return &RV_FIELD(record, TrackData_dbid, const uint32_t); +} + +static int before(const struct row *row, const uint32_t *id) +{ + return row->id_high < id[1] || (row->id_high == id[1] && row->id_low < id[0]); +} + +static void append(const void *record, const uint32_t *tokens) +{ + struct chunk *chunk = table.chunks; + if (!chunk || chunk->count == CHUNK_ROWS) { + chunk = api->alloc(self, sizeof *chunk); + if (!chunk) + return; + chunk->next = table.chunks; + table.chunks = chunk; + } + struct row *row = &chunk->rows[chunk->count++]; + table.count++; + const uint32_t *id = persistent_id(record); + row->id_low = id[0]; + row->id_high = id[1]; + for (unsigned i = 0; i < TOKENS; i++) + row->tokens[i] = tokens[i]; +} + +static void flush(void) +{ + const void *record = table.pending.record; + uint32_t *tokens = table.pending.tokens; + if (!record) + return; + table.pending.record = NULL; + /* Nothing to keep when the Album Artist is the Artist or empty and no + * Sort As came with it. */ + uint32_t token = tokens[TOKEN]; + int same = (!token || token == RV_FIELD(record, MediaRecord_artist, uint32_t)) && + !tokens[SORT_ALBUM_ARTIST] && !tokens[SORT_ARTIST]; + if (!same) + append(record, tokens); + for (unsigned i = 0; i < TOKENS; i++) + tokens[i] = 0; +} + +static void sift(struct row *rows, uint32_t root, uint32_t count) +{ + while (root < count / 2) { + uint32_t child = root * 2 + 1; + if (child + 1 < count && before(&rows[child], &rows[child + 1].id_low)) + child++; + if (!before(&rows[root], &rows[child].id_low)) + break; + struct row swap = rows[root]; + rows[root] = rows[child]; + rows[child] = swap; + root = child; + } +} + +/* The chunks into one exact-size block, heapsorted by persistent id in place. + * Without memory for the block the import's rows are dropped. */ +static void finish(void) +{ + uint32_t count = table.count; + struct row *rows = count ? api->alloc(self, count * sizeof *rows) : NULL; + uint32_t at = 0; + while (table.chunks) { + struct chunk *chunk = table.chunks; + if (rows) + for (uint32_t i = 0; i < chunk->count; i++) + rows[at++] = chunk->rows[i]; + table.chunks = chunk->next; + api->free(self, chunk); + } + table.rows = rows; + table.count = rows ? count : 0; + table.sealed = 1; + if (!rows) + return; + for (uint32_t i = count / 2; i; i--) + sift(rows, i - 1, count); + for (uint32_t i = count; i > 1; i--) { + struct row swap = rows[0]; + rows[0] = rows[i - 1]; + rows[i - 1] = swap; + sift(rows, 0, i - 1); + } +} + +void fields_import_begin(void *reader) +{ + clear(); + table.owner = RV_FIELD(reader, ITunesReader_owner, void *); + table.cache = (uint8_t *)table.owner + TrackData_artist_cache; +} + +void fields_import_end(int status) +{ + flush(); + if (status) + clear(); + else + finish(); +} + +int fields_import_mhod(void *reader, uint32_t body_bytes, void *record, + uint32_t mhod_type) +{ + /* Apple's skip treats a negative length as a seek back. */ + if (body_bytes > INT32_MAX) + return -0xd0; + if (!table.owner || table.sealed || body_bytes < 16) + return ITunesDB_SkipImportBytes(reader, (int32_t)body_bytes); + void *file = RV_FIELD(reader, ITunesReader_file, void *); + uint64_t start, end; + if (BufferedFile_GetPosition(file, &start)) + return ITunesDB_SkipImportBytes(reader, (int32_t)body_bytes); + /* Apple's own arguments for an artist string: UTF-16 in the file, the + * artist cache's glyph collection. */ + uint32_t token = 0; + int status = + ITunesDB_ImportCachedString(reader, 1, mhod_type, table.cache, &token, 1, 1); + int cursor = BufferedFile_GetPosition(file, &end); + if (cursor || end < start || end - start > body_bytes) + return cursor ? cursor : -0xd0; + /* The padding the decode left, also after a failed optional field. */ + int trailing = ITunesDB_SkipImportBytes( + reader, (int32_t)(body_bytes - (uint32_t)(end - start))); + if (trailing) + return trailing; + if (status) + token = 0; + if (table.pending.record != record) + flush(); + table.pending.record = record; + unsigned which = mhod_type == MHOD_SORT_ALBUM_ARTIST ? SORT_ALBUM_ARTIST + : mhod_type == MHOD_SORT_ARTIST ? SORT_ARTIST + : TOKEN; + table.pending.tokens[which] = token; + return 0; +} + +void fields_destroy(void *track_data) +{ + if (track_data == table.owner) { + clear(); + table.owner = table.cache = NULL; + } +} + +int fields_imported(void) +{ + return table.owner != NULL; +} + +static const struct row *lookup(const void *record) +{ + if (!record || !table.sealed || !table.count || + *(void *const *)record != table.owner) + return NULL; + const uint32_t *id = persistent_id(record); + uint32_t low = 0, high = table.count; + while (low < high) { + uint32_t middle = low + (high - low) / 2; + if (before(&table.rows[middle], id)) + low = middle + 1; + else + high = middle; + } + const struct row *row = &table.rows[low]; + return low < table.count && row->id_high == id[1] && row->id_low == id[0] ? row + : NULL; +} + +uint32_t fields_token(const void *record) +{ + const struct row *row = lookup(record); + return row ? row->tokens[TOKEN] : 0; +} + +uint32_t fields_sort_token(const void *record, int album_artist) +{ + const struct row *row = lookup(record); + return row ? row->tokens[album_artist ? SORT_ALBUM_ARTIST : SORT_ARTIST] : 0; +} + +uint32_t fields_read(const void *record, uint16_t *text, uint32_t max_units) +{ + uint32_t token = fields_token(record); + if (!token || token == RV_FIELD(record, MediaRecord_artist, uint32_t) || + !max_units || max_units > INT32_MAX / 2) + return 0; + uint32_t bytes = 0; + if (StringCache_ReadToken(table.cache, token, text, &bytes, max_units * 2)) + return 0; + uint32_t units = bytes / 2; + if (units && text[units - 1] >= 0xd800 && text[units - 1] <= 0xdbff) + units--; + return units; +} + +uint32_t fields_count(void) +{ + return table.count; +} diff --git a/extensions/album-artists/fields.h b/extensions/album-artists/fields.h new file mode 100644 index 0000000..140031f --- /dev/null +++ b/extensions/album-artists/fields.h @@ -0,0 +1,36 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The Album Artist, Sort Artist and Sort Album Artist of each song, kept by + * persistent id through the iTunesDB import. Tokens name strings in the + * TrackData's artist cache; 0 means absent. */ + +#ifndef ALBUM_ARTISTS_FIELDS_H +#define ALBUM_ARTISTS_FIELDS_H +#include + +/* The iTunesDB mhod types Apple discards. */ +enum { MHOD_ALBUM_ARTIST = 22, MHOD_SORT_ARTIST = 23, MHOD_SORT_ALBUM_ARTIST = 29 }; + +/* The import hooks: the parse of a track dataset begins and ends, and one of + * the mhod types Apple discards is reached with the record being filled. The + * mhod call returns Apple's status for the import loop. */ +void fields_import_begin(void *reader); +void fields_import_end(int status); +int fields_import_mhod(void *reader, uint32_t body_bytes, void *record, + uint32_t mhod_type); + +/* Apple destroys a TrackData's storage: the table of that TrackData goes. */ +void fields_destroy(void *track_data); + +/* Whether an import has run on the current TrackData since the module loaded. */ +int fields_imported(void); + +uint32_t fields_token(const void *record); +/* The Sort Album Artist when `album_artist` is set, else the Sort Artist. */ +uint32_t fields_sort_token(const void *record, int album_artist); +uint32_t fields_read(const void *record, uint16_t *text, uint32_t max_units); + +/* For the host tests. */ +uint32_t fields_count(void); + +#endif diff --git a/extensions/album-artists/listing.toml b/extensions/album-artists/listing.toml new file mode 100644 index 0000000..4ab9b1e --- /dev/null +++ b/extensions/album-artists/listing.toml @@ -0,0 +1,11 @@ +details = "Choose Album Artists in Music to browse the library by Album Artist, with the Artist as the fallback. Settings > Music Menu and Settings > Main Menu show or hide the row." + +icon = "assets/settings-album-artists.png" + +[[screenshots]] +file = "screenshots/list.png" +alt = "The Album Artists list: All Albums, then the album artists of the library." + +[[screenshots]] +file = "screenshots/albums.png" +alt = "An album artist's albums with their artwork and song counts." diff --git a/extensions/album-artists/main.c b/extensions/album-artists/main.c new file mode 100644 index 0000000..426f5ba --- /dev/null +++ b/extensions/album-artists/main.c @@ -0,0 +1,132 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* Album Artists: a row in Music and on the main menu that lists the library by + * Album Artist, falling back to Artist, on the stock Artists screen. The + * import hooks keep the Album Artist, Sort Artist and Sort Album Artist tags + * Apple discards (fields.c); the list is a browser of the extension's own + * (browser.c). + * + * Based on RepriseOS payload/album_artists.c (bfedd72) by lgreitis. */ + +#include "browser.h" +#include "fields.h" +#include "service.h" +#include "shared.h" +#include "../shared/menu_visibility.h" +#include "osos-2.0.5.h" +#include "rv_api.h" +#include "rv_menus.h" +#include "rv_sites.h" +#include "rv_ui.h" +#include + +const struct rv_api *api; +rv_extension_handle self; + +/* The reader of the dataset parse in progress, for the mhod hooks. */ +static void *importing; + +/* ITunesDB_ImportTrackDataset: the table of this TrackData is built here. */ +static uint32_t import_track_dataset(uint32_t reader, const void *next) +{ + fields_import_begin((void *)reader); + importing = (void *)reader; + uint32_t status = api->hook_next(next, reader, 0, 0, 0, 0, 0); + importing = NULL; + fields_import_end((int)status); + return status; +} + +/* The two discard calls of the mhod switch: (file or reader, bytes), with the + * record and the mhod type copied from Apple's registers. */ +static uint32_t discard_mhod(uint32_t target, uint32_t bytes, uint32_t record, + uint32_t type, const void *next) +{ + if (importing && (type == MHOD_ALBUM_ARTIST || type == MHOD_SORT_ARTIST || + type == MHOD_SORT_ALBUM_ARTIST)) + return (uint32_t)fields_import_mhod(importing, bytes, (void *)record, type); + return api->hook_next(next, target, bytes, record, type, 0, 0); +} + +static uint32_t destroy_storage(uint32_t track_data, const void *next) +{ + browser_invalidate((void *)track_data); + fields_destroy((void *)track_data); + return api->hook_next(next, track_data, 0, 0, 0, 0, 0); +} + +static void unload(void) +{ + browser_unload(); +} + +static const struct rv_hook hooks[] = { + RV_HOOK_FILTER(RV_SITE_ITunesDB_ImportTrackDataset_call, import_track_dataset), + RV_HOOK_FILTER(RV_SITE_ITunesDB_DiscardMhod_call, discard_mhod), + RV_HOOK_FILTER(RV_SITE_ITunesDB_SkipMhod_call, discard_mhod), + RV_HOOK_FILTER(RV_SITE_TrackData_DestroyStorage_call, destroy_storage), + RV_HOOK_FILTER(RV_SITE_LibraryBrowser_BuildArtists_slot, build_artists_slot), + RV_HOOK_FILTER(RV_SITE_MediaBrowser_BuildArtists_RefreshCounts_call, build_artists), + RV_HOOK_FILTER(RV_SITE_MediaBrowser_BuildArtists_SecondaryInit_call, build_artists), + RV_HOOK_FILTER(RV_SITE_MediaBrowser_ClearArtists_entry, clear_artists), + RV_HOOK_FILTER(RV_SITE_MediaBrowser_ReadArtistName_entry, read_artist_name), + RV_HOOK_FILTER(RV_SITE_MediaBrowser_ReadArtistJumpLabel_entry, + read_artist_jump_label), + RV_HOOK_FILTER(RV_SITE_MediaBrowser_ArtistFilterCompare_call, + artist_filter_compare), + RV_HOOK_POINTER(RV_SITE_AlbumGroup_literal, album_group), + RV_HOOK_FILTER(RV_SITE_AlbumSubtitle_slot, album_subtitle), + RV_HOOK_FILTER(RV_SITE_MediaListSelection_SelectArtworkSource_call, + select_artwork_source), + RV_HOOK_FILTER(RV_SITE_AlbumArtworkProvider_Create_call, create_artwork_provider), + RV_HOOK_FILTER(RV_SITE_LibraryBrowser_Destroy_entry, destroy_model), +}; + +static const struct rv_menu_entry entries[] = { + RV_MENU_ENTRY(RV_MENU_MUSIC, RV_MUSIC_ARTISTS, + RV_ROW_ACTION("Album Artists", browser_open), + .shown_by = KEY_IN_MUSIC), + RV_MENU_ENTRY(RV_MENU_MAIN, RV_MAIN_ARTISTS, + RV_ROW_ACTION("Album Artists", browser_open), .shown_by = KEY_IN_MAIN, + .preview = RV_PREVIEW_MUSIC), +}; + +static const struct rv_setting settings[] = { + RV_SETTING_BOOL(KEY_IN_MUSIC, "Album Artists in Music", 1), + RV_SETTING_BOOL(KEY_IN_MAIN, "Album Artists in Main Menu", 0), +}; + +static const struct album_artists_service service = {fields_read}; + +/* The old core's built-in Album Artists row in its menu visibility record. */ +#define OLD_MENU_KEY 0xdf951f53 + +static int first_load = 1; + +static void changed(uint16_t key) +{ + if (key == RV_SETTING_KEY_ALL) { + int import = first_load; + first_load = 0; + migrate_menu_visibility(api, self, import, OLD_MENU_KEY, KEY_IN_MUSIC, 1, + KEY_IN_MAIN, 0); + } +} + +static const struct rv_descriptor extension = { + .size = sizeof extension, + RV_HOOKS(hooks), + .unload = unload, + RV_SETTINGS(settings), + .setting_changed = changed, + RV_ENTRIES(entries), + .service = &service, +}; + +const struct rv_descriptor *rv_module_entry(const struct rv_api *core, + rv_extension_handle handle) +{ + api = core; + self = handle; + return &extension; +} diff --git a/extensions/album-artists/manifest.toml b/extensions/album-artists/manifest.toml new file mode 100644 index 0000000..7979545 --- /dev/null +++ b/extensions/album-artists/manifest.toml @@ -0,0 +1,16 @@ +id = "album-artists" +name = "Album Artists" +description = "Browse the library by Album Artist, falling back to Artist, from Music or the Main Menu." +version = "0.1.0" +author = "RepriseOS contributors" +license = "GPL-3.0-only" +api = "1.89" +stability = "beta" +category = "media" + +[libraries] +optional = ["reprise"] + +[[module]] +name = "main" +trigger = "always" diff --git a/extensions/album-artists/screenshots/albums.png b/extensions/album-artists/screenshots/albums.png new file mode 100644 index 0000000..b340477 Binary files /dev/null and b/extensions/album-artists/screenshots/albums.png differ diff --git a/extensions/album-artists/screenshots/list.png b/extensions/album-artists/screenshots/list.png new file mode 100644 index 0000000..b74540a Binary files /dev/null and b/extensions/album-artists/screenshots/list.png differ diff --git a/extensions/album-artists/service.h b/extensions/album-artists/service.h new file mode 100644 index 0000000..ab5286c --- /dev/null +++ b/extensions/album-artists/service.h @@ -0,0 +1,17 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* What Album Artists offers other extensions through api->extension_service. */ + +#ifndef ALBUM_ARTISTS_SERVICE_H +#define ALBUM_ARTISTS_SERVICE_H +#include + +#define ALBUM_ARTISTS_ID "album-artists" + +struct album_artists_service { + /* UTF-16 units of the record's Album Artist into `text`, when it differs + * from the record's Artist; 0 otherwise, or while no library is imported. */ + uint32_t (*read)(const void *record, uint16_t *text, uint32_t max_units); +}; + +#endif diff --git a/extensions/album-artists/shared.h b/extensions/album-artists/shared.h new file mode 100644 index 0000000..8ddf5ad --- /dev/null +++ b/extensions/album-artists/shared.h @@ -0,0 +1,22 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The core table and handle every file of the module calls through. */ + +#ifndef ALBUM_ARTISTS_SHARED_H +#define ALBUM_ARTISTS_SHARED_H +#include "rv_api.h" +#include + +#define KEY_IN_MUSIC 1 /* Settings > Music Menu and Main Menu flip these two */ +#define KEY_IN_MAIN 2 + +extern const struct rv_api *api; +extern rv_extension_handle self; + +/* A hook argument as the pointer it carries. */ +static inline void *ptr(uint32_t word) +{ + return (void *)(uintptr_t)word; +} + +#endif diff --git a/extensions/album-artists/tests/browser_contracts.c b/extensions/album-artists/tests/browser_contracts.c new file mode 100644 index 0000000..8c97cd4 --- /dev/null +++ b/extensions/album-artists/tests/browser_contracts.c @@ -0,0 +1,536 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ +#include +#include +#include +#include +#include "osos-2.0.5.h" +#include "rv_api.h" +#include "rv_media.h" + +/* Apple's row layouts hold pointers; the host's are wider, and the host + * compiler knows no ARM attribute. */ +#define _Static_assert(...) +#undef RV_ARM +#define RV_ARM +#include "../fields.h" +#include "../browser.c" + +/* The host doubles as the core: counted blocks from alloc and free. */ +static unsigned live_blocks; +static int fail_alloc; + +static void *host_alloc(rv_extension_handle s, uint32_t bytes) +{ + (void)s; + if (fail_alloc && ++fail_alloc == 4) + return NULL; + void *block = calloc(1, bytes); + assert(block); + live_blocks++; + return block; +} + +static void host_free(rv_extension_handle s, void *block) +{ + (void)s; + assert(live_blocks); + live_blocks--; + free(block); +} +static const struct rv_api host_api = {.alloc = host_alloc, .free = host_free}; +const struct rv_api *api = &host_api; +rv_extension_handle self; + +/* One owned browser over a TrackData, a list of six entries and their records. */ +static _Alignas(16) uint8_t browser[MediaBrowser_track_data + 8]; +static _Alignas(16) uint8_t owner[MediaBrowser_track_data + 8]; +static _Alignas(16) uint8_t track_data[TrackData_artist_cache + 0x58]; +static _Alignas(16) uint8_t list[MediaList_jump_index + 0x40 * 8]; +static _Alignas(16) uint8_t root[MediaEntry_size]; +static uint8_t *native_order; /* a MediaOrder, or NULL */ +static uint32_t *native_jump; +static unsigned pins; + +static _Alignas(16) uint8_t records[6][TrackData_dbid + 8]; + +/* What the fields table and the filter answer for each record. */ +static struct tags { + uint32_t album_artist, sort_artist, sort_album_artist; + int accepted; +} tags[6]; + +static struct tags *tags_of(const void *record) +{ + return &tags[((const uint8_t *)record - records[0]) / sizeof records[0]]; +} + +static _Alignas(16) uint8_t entries[6][MediaEntry_size]; +static const uint16_t *strings[] = { + u"", u"The Clash", u"The Cure", u"Alpha", u"Guest", u"Clash", + u"Cure", u"Zulu", u"Aardvark", u"The Zebra", u"Theatre", u"An Artist", +}; + +/* The fields table, as the test sets it per record. */ +uint32_t fields_token(const void *r) +{ + return tags_of(r)->album_artist; +} + +uint32_t fields_sort_token(const void *r, int album_artist) +{ + return album_artist ? tags_of(r)->sort_album_artist : tags_of(r)->sort_artist; +} + +void *MediaBrowser_GetOwner(void *b) +{ + assert(b == browser); + return owner; +} + +struct MediaList *MediaBrowser_GetCurrentList(void *b) +{ + assert(b == browser); + return (struct MediaList *)list; +} + +int MediaBrowser_EvaluateEntryFilters(void *b, struct MediaEntry *entry, + struct MediaList *override) +{ + assert(b == browser && !override); + return tags_of(RV_FIELD(entry, MediaEntry_song_record, void *))->accepted; +} + +uint32_t MediaBrowser_GetRecordArtworkId(void *o, void *record) +{ + assert(o == owner); + return RV_FIELD(record, MediaRecord_album, uint32_t) == 2 ? 0x200 : 0; +} + +static unsigned clears; + +void MediaBrowser_ClearArtists(void *b) +{ + assert(b == browser && !RV_FIELD(b, MediaBrowser_artists, void *) && + !RV_FIELD(b, MediaBrowser_artist_tokens, void *)); + clears++; +} + +void MediaBrowser_ClearAlbums(void *b) +{ + assert(b == browser); +} + +void MediaBrowser_ClearSongs(void *b) +{ + assert(b == browser); +} + +int MediaBrowser_InvalidateEntryMatches(void *b) +{ + assert(b == browser); + return 0; +} + +void Heap_Free(void *block) +{ + assert(!block); +} + +struct MediaEntry *MediaList_GetEntryByOrderIndex(struct MediaList *l, int mode, + uint32_t reverse, uint32_t index) +{ + assert((void *)l == list && mode == MediaOrderMode_Album && !reverse && index < 6); + return (struct MediaEntry *)entries[index]; +} + +int StringCache_GetTokenView(void *cache, uint32_t token, void **data, uint32_t *bytes) +{ + assert(cache == track_data + TrackData_artist_cache && pins); + assert(token < sizeof strings / sizeof *strings); + *data = (void *)strings[token]; + *bytes = 0; + while (strings[token][*bytes / 2]) + *bytes += 2; + return 0; +} + +void TrackData_AcquireStringCaches(void *t) +{ + assert(t == track_data); + pins++; +} + +void TrackData_ReleaseStringCaches(void *t) +{ + assert(t == track_data && pins); + pins--; +} + +/* Apple's compare: case-insensitive after leading blanks, as far as the + * grouping needs. */ +int SongText_CompareUtf16(void *collation, const uint16_t *a, uint32_t na, + const uint16_t *b, uint32_t nb) +{ + assert(!collation); + while (na && *a <= ' ') { + a++; + na--; + } + while (nb && *b <= ' ') { + b++; + nb--; + } + for (uint32_t i = 0; i < na && i < nb; i++) { + uint16_t x = a[i] | 32, y = b[i] | 32; + if (x != y) + return x < y ? -1 : 1; + } + return (na > nb) - (na < nb); +} + +static struct { + uint32_t units; + uint16_t text[64]; +} assigned; + +void NativeString_AssignUtf16(struct NativeString *s, const uint16_t *text, + int characters) +{ + (void)s; + assigned.units = (uint32_t)characters; + memcpy(assigned.text, text, (size_t)characters * 2); +} + +static _Alignas(16) uint8_t album_storage[8 * AlbumGroup_bytes]; + +void AlbumGroupVector_Append(void *vector, const void *row) +{ + assert(vector == browser + MediaBrowser_albums); + struct album *end = RV_FIELD(browser, MediaBrowser_albums_end, struct album *); + if (!end) { + RV_FIELD(browser, MediaBrowser_albums, void *) = album_storage; + end = (struct album *)album_storage; + } + memcpy(end, row, sizeof *end); + RV_FIELD(browser, MediaBrowser_albums_end, struct album *) = end + 1; +} + +int MediaBrowser_AccumulateAlbumGroup(void *b, void *c, uint32_t lo, uint32_t hi, + uint32_t i, struct MediaEntry *e, void *r, + int first) +{ + (void)b, (void)c, (void)lo, (void)hi, (void)i, (void)e, (void)r, (void)first; + abort(); +} + +/* Not reached by these tests: the open path and the artwork provider need the + * emulator. */ +void *LibraryBrowser_Create(uint32_t o) +{ + (void)o; + abort(); +} + +void *LibraryBrowser_InitBorrowed(void *m, uint8_t f, void *b) +{ + (void)m, (void)f, (void)b; + abort(); +} + +void *LibraryModelRef_Init(void *r, void *m, int s) +{ + (void)r, (void)m, (void)s; + abort(); +} + +void *LibraryModelRef_Assign(void *d, void *s) +{ + (void)d, (void)s; + abort(); +} + +void LibraryModelRef_Release(void *r) +{ + (void)r; + abort(); +} + +void *LibraryModelRef_Get(void *r) +{ + (void)r; + abort(); +} + +void *MediaListSelection_GetInstance(void) +{ + abort(); +} + +void *MediaListSelection_SetTitle(void *s, const struct NativeString *t) +{ + (void)s, (void)t; + abort(); +} + +struct NativeString *NativeString_InitUtf8(struct NativeString *s, const char *u) +{ + (void)s, (void)u; + abort(); +} + +struct NativeString *NativeString_Destroy(struct NativeString *s) +{ + (void)s; + abort(); +} + +void MediaListSelection_SetList(void *s, void *r, uint32_t c, uint32_t o, uint8_t e) +{ + (void)s, (void)r, (void)c, (void)o, (void)e; + abort(); +} + +void *ListArtworkSession_Get(void) +{ + abort(); +} + +void ArtworkSession_Stop(void *s) +{ + (void)s; + abort(); +} + +int ListArtworkSession_SetSource(void *s, unsigned sel) +{ + (void)s, (void)sel; + abort(); +} + +void *UI_GetControllerRegistry(void) +{ + abort(); +} + +void *UI_CreateScreenController(void *r, uint32_t s, uint32_t l, uint32_t t) +{ + (void)r, (void)s, (void)l, (void)t; + abort(); +} + +int MediaBrowser_CreateChild(void *o, void **out) +{ + (void)o, (void)out; + abort(); +} + +uint32_t MusicMenu_ConfigureLibraryBrowser(void *c, uint32_t i, uint32_t e, int r, + uint32_t g, uint32_t s, uint32_t o) +{ + (void)c, (void)i, (void)e, (void)r, (void)g, (void)s, (void)o; + abort(); +} + +void *Runtime_OperatorNew(uint32_t bytes) +{ + (void)bytes; + abort(); +} + +uint8_t BrowserRegistry[16]; + +static void reset_groups(void) +{ + drop_rows(browser); + assert(!pins && !live_blocks); +} + +static void expect_groups(const uint32_t *tokens, const char *letters, uint32_t count) +{ + assert(build(browser) == count); + assert(!pins && RV_FIELD(browser, MediaBrowser_artist_count, uint32_t) == count); + struct group *rows = groups_of(browser); + uint32_t *group_tokens = RV_FIELD(browser, MediaBrowser_artist_tokens, uint32_t *); + for (uint32_t i = 0; i < count; i++) { + assert(rows[i].token == tokens[i] && group_tokens[i] == tokens[i]); + uint16_t letter[2]; + assert(!group_letter(browser, (int)i, letter)); + assert(letter[0] == 1 && letter[1] == (uint16_t)letters[i]); + uint16_t name[256]; + assert(!group_name(browser, (int)i, name)); + assert(!memcmp(name + 1, strings[tokens[i]], name[0] * 2)); + } + uint16_t none[2]; + assert(group_name(browser, (int)count, none) == -50 && + group_letter(browser, -1, none) == -50); + /* Built rows are kept. */ + assert(build(browser) == count); + reset_groups(); +} + +static void check_album_runs(void) +{ + const struct source source = {(struct MediaList *)list, NULL}; + struct track tracks[6]; + const uint32_t albums[] = {1, 1, 2, 1, 3, 1}; + for (unsigned i = 0; i < 6; i++) + RV_FIELD(records[i], MediaRecord_album, uint32_t) = albums[i]; + tags[1].accepted = 0; + tags[2].accepted = 0; + pins++; + assert(collect_album_runs(browser, &source, 6, NULL, 0) == 3); + assert(collect_album_runs(browser, &source, 6, tracks, 3) == 3); + assert(tracks[0].order == 0 && tracks[1].order == 4 && tracks[2].order == 5); + tags[0].accepted = 0; + tags[1].accepted = 1; + assert(collect_album_runs(browser, &source, 6, tracks, 3) == 3); + assert(tracks[0].order == 1); + pins--; + assert(build(browser) == 1); + assert(groups_of(browser)->albums == 3); + reset_groups(); + for (unsigned i = 0; i < 6; i++) { + RV_FIELD(records[i], MediaRecord_album, uint32_t) = i + 1; + tags[i].accepted = 1; + } +} + +/* The selected group's filter and the album rows of a group. */ +static void check_group_albums(void) +{ + tags[0].album_artist = tags[4].album_artist = 1; + tags[1].album_artist = 2; + tags[2].album_artist = 3; + RV_FIELD(records[3], MediaRecord_artist, uint32_t) = 9; + tags[5].album_artist = 11; + RV_FIELD(records[0], MediaRecord_album, uint32_t) = + RV_FIELD(records[4], MediaRecord_album, uint32_t) = 5; + assert(build(browser) == 5); + pins++; /* Apple's filter evaluation and album build hold the caches */ + RV_FIELD(browser, MediaBrowser_selected_artist, int) = -1; + assert(!outside_selected_group(browser, (struct MediaEntry *)entries[0])); + RV_FIELD(browser, MediaBrowser_selected_artist, int) = + 3; /* The Clash, after the Sort As groups */ + assert(!outside_selected_group(browser, (struct MediaEntry *)entries[0])); + assert(!outside_selected_group(browser, (struct MediaEntry *)entries[4])); + assert(outside_selected_group(browser, (struct MediaEntry *)entries[1])); + RV_FIELD(browser, MediaBrowser_selected_artist, int) = 9; + assert(outside_selected_group(browser, (struct MediaEntry *)entries[0])); + /* Album rows: one per album token, counting tracks, the resolved artist + * as the subtitle, artwork from the first track. */ + assert(album_group(browser, NULL, 0, 0, 0, (struct MediaEntry *)entries[0], + records[0], 1) == 1); + assert(album_group(browser, NULL, 0, 0, 1, (struct MediaEntry *)entries[4], + records[4], 0) == 1); + assert(album_group(browser, NULL, 0, 0, 2, (struct MediaEntry *)entries[2], + records[2], 0) == 1); + RV_FIELD(records[1], MediaRecord_album, uint32_t) = 0; + assert(album_group(browser, NULL, 0, 0, 3, (struct MediaEntry *)entries[1], + records[1], 0) == 1); + RV_FIELD(records[1], MediaRecord_album, uint32_t) = 2; + assert(album_group(browser, NULL, 0, 0, 0, (struct MediaEntry *)entries[0], + records[0], 1) == 0); + struct album *rows = RV_FIELD(browser, MediaBrowser_albums, struct album *); + assert(RV_FIELD(browser, MediaBrowser_albums_end, struct album *) - rows == 2); + assert(rows[0].token == 5 && rows[0].artist == 1 && rows[0].tracks == 2 && + !rows[0].artwork); + assert(rows[1].token == 3 && rows[1].artist == 3 && rows[1].tracks == 1); + pins--; + album_artist_subtitle(browser, 0, NULL); + assert(assigned.units == 9 && !memcmp(assigned.text, u"The Clash", 18)); + album_artist_subtitle(browser, 5, NULL); + assert(assigned.units == 9); + RV_FIELD(browser, MediaBrowser_albums, void *) = NULL; + RV_FIELD(browser, MediaBrowser_albums_end, void *) = NULL; + RV_FIELD(records[0], MediaRecord_album, uint32_t) = 1; + RV_FIELD(records[4], MediaRecord_album, uint32_t) = 5; + reset_groups(); +} + +int main(void) +{ + contexts[0].browser = browser; + RV_FIELD(owner, MediaBrowser_track_data, void *) = track_data; + RV_FIELD(list, MediaList_root, void *) = root; + RV_FIELD(root, MediaEntry_tracks, uint16_t) = 6; + for (unsigned i = 0; i < 6; i++) { + RV_FIELD(entries[i], MediaEntry_song_record, void *) = records[i]; + RV_FIELD(records[i], 0, void *) = track_data; + tags[i].accepted = 1; + RV_FIELD(records[i], MediaRecord_artist, uint32_t) = 4; + RV_FIELD(records[i], MediaRecord_album, uint32_t) = i + 1; + } + check_album_runs(); + tags[0].album_artist = tags[4].album_artist = 1; + tags[1].album_artist = 2; + tags[2].album_artist = 3; + RV_FIELD(records[3], MediaRecord_artist, uint32_t) = 9; /* the Artist fallback */ + tags[5].album_artist = 11; + expect_groups((uint32_t[]){3, 11, 1, 2, 9}, "AATTT", 5); + strings[11] = u"An Aardvark"; + expect_groups((uint32_t[]){3, 11, 1, 2, 9}, "AATTT", 5); + strings[11] = u"A Zebra"; + expect_groups((uint32_t[]){11, 3, 1, 2, 9}, "AATTT", 5); + strings[11] = u"An Artist"; + + /* Sort As names come first, including a literal leading The. */ + tags[0].sort_album_artist = tags[1].sort_album_artist = 7; + tags[4].sort_album_artist = 8; + tags[3].sort_artist = 8; + tags[2].sort_album_artist = 9; + expect_groups((uint32_t[]){9, 11, 3, 1, 2}, "AATZZ", 5); + + /* Apple's own Album Artist order and jump table are consumed when complete. */ + native_order = calloc(1, MediaOrder_entries + 6 * sizeof(void *)); + RV_FIELD(native_order, MediaOrder_count, uint32_t) = 6; + RV_FIELD(native_order, MediaOrder_capacity, uint32_t) = 6; + const unsigned order[] = {3, 0, 2, 1, 4, 5}; + for (unsigned i = 0; i < 6; i++) + ((void **)(native_order + MediaOrder_entries))[i] = entries[order[i]]; + RV_FIELD(list, MediaList_order_index + AlbumArtist_order_mode * sizeof(void *), + void *) = native_order; + uint32_t jumps[] = {4, 0xbeef0000 | 'B', 0, 'C', 1, 'X', 2, 'Y', 3}; + native_jump = jumps; + RV_FIELD(list, MediaList_jump_index + AlbumArtist_order_mode * sizeof(void *), + void *) = native_jump; + expect_groups((uint32_t[]){9, 1, 3, 2, 11}, "BCXYY", 5); + tags[0].accepted = 0; + expect_groups((uint32_t[]){9, 3, 2, 1, 11}, "BXYYY", 5); + tags[0].accepted = 1; + /* A bad or missing jump table falls back to the Sort As letters in the + * native order; an incomplete order falls back to the sort. */ + jumps[2] = 1; + expect_groups((uint32_t[]){9, 1, 3, 2, 11}, "AZTZA", 5); + RV_FIELD(list, MediaList_jump_index + AlbumArtist_order_mode * sizeof(void *), + void *) = NULL; + expect_groups((uint32_t[]){9, 1, 3, 2, 11}, "AZTZA", 5); + RV_FIELD(native_order, MediaOrder_count, uint32_t) = 5; + expect_groups((uint32_t[]){9, 11, 3, 1, 2}, "AATZZ", 5); + RV_FIELD(list, MediaList_order_index + AlbumArtist_order_mode * sizeof(void *), + void *) = NULL; + free(native_order); + + /* No eligible track, then an allocation failure, leave no rows. */ + for (unsigned i = 0; i < 6; i++) + tags[i].accepted = 0; + expect_groups(NULL, "", 0); + for (unsigned i = 0; i < 6; i++) + tags[i].accepted = 1; + fail_alloc = 1; + assert(!build(browser) && !live_blocks && !pins); + fail_alloc = 0; + reset_groups(); + + check_group_albums(); + + /* Invalidation and the clear filter free the rows before Apple's clear. */ + assert(build(browser) == 5 && live_blocks); + contexts[0].track_data = track_data; + browser_invalidate(track_data); + assert(!live_blocks && clears == 1 && !contexts[0].track_data); + assert(build(browser) == 5); + drop_rows(browser); + MediaBrowser_ClearArtists(browser); + assert(!live_blocks && clears == 2); + return 0; +} diff --git a/extensions/album-artists/tests/contracts.c b/extensions/album-artists/tests/contracts.c new file mode 100644 index 0000000..36d801d --- /dev/null +++ b/extensions/album-artists/tests/contracts.c @@ -0,0 +1,329 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ +#include +#include +#include +#include +#include +#include "osos-2.0.5.h" +#include "rv_api.h" +#include "../fields.c" + +/* The host doubles as the core: counted blocks from alloc and free. */ +static size_t live_blocks, live_bytes, peak_bytes; +static int fail_alloc; + +union block { + max_align_t align; + size_t bytes; +}; + +static void *host_alloc(rv_extension_handle self, uint32_t bytes) +{ + (void)self; + if (fail_alloc) + return NULL; + union block *block = calloc(1, sizeof *block + bytes); + assert(block); + block->bytes = bytes; + live_blocks++; + live_bytes += bytes; + if (live_bytes > peak_bytes) + peak_bytes = live_bytes; + return block + 1; +} + +static void host_free(rv_extension_handle self, void *memory) +{ + (void)self; + union block *block = (union block *)memory - 1; + assert(live_blocks); + live_blocks--; + live_bytes -= block->bytes; + free(block); +} +static const struct rv_api host_api = {.alloc = host_alloc, .free = host_free}; +const struct rv_api *api = &host_api; +rv_extension_handle self; + +/* The artist cache: a string the cache holds comes back as its token with + * no further reference, so the table never releases one. */ +static struct { + const uint16_t *text; + uint32_t units; +} tokens[512]; + +static uint32_t token_count = 1; +static uint8_t track_data[TrackData_artist_cache + 0x58]; +static void *cache = track_data + TrackData_artist_cache; + +int StringCache_ReadToken(void *c, uint32_t token, void *out, uint32_t *bytes, + uint32_t maximum) +{ + assert(c == cache && token && token < token_count); + *bytes = tokens[token].units * 2 < maximum ? tokens[token].units * 2 : maximum; + memcpy(out, tokens[token].text, *bytes); + return 0; +} + +static uint32_t intern(const uint16_t *text, uint32_t units) +{ + for (uint32_t i = 1; i < token_count; i++) + if (tokens[i].units == units && !memcmp(tokens[i].text, text, units * 2)) + return i; + assert(token_count < sizeof tokens / sizeof tokens[0]); + tokens[token_count].text = text; + tokens[token_count].units = units; + return token_count++; +} + +/* The reader: a file cursor and the mhod body under it. */ +static struct { + uint64_t offset; + const uint16_t *text; + uint32_t units; + int decode_error, skip_error, position_error; +} file; + +static _Alignas(16) uint8_t reader[ITunesReader_owner + 8]; + +int ITunesDB_ImportCachedString(void *r, uint32_t encoding, uint32_t type, void *c, + uint32_t *token, uint32_t glyph_field, int collect) +{ + assert(r == reader && encoding == 1 && (type == 22 || type == 23 || type == 29) && + c == cache && glyph_field == 1 && collect == 1); + if (file.decode_error) { + file.offset += 8; + return file.decode_error; + } + file.offset += 16 + file.units * 2; + *token = file.units ? intern(file.text, file.units) : 0; + return 0; +} + +int ITunesDB_SkipImportBytes(void *r, int bytes) +{ + assert(r == reader); + if (file.skip_error) + return file.skip_error; + assert(bytes >= 0); + file.offset += (uint32_t)bytes; + return 0; +} + +int BufferedFile_GetPosition(void *f, uint64_t *position) +{ + assert(f == RV_FIELD(reader, ITunesReader_file, void *)); + if (file.position_error) + return file.position_error; + *position = file.offset; + return 0; +} + +static int invalidated; + +void browser_invalidate(void *owner) +{ + assert(owner == track_data); + invalidated++; +} + +/* Records: the owner word, the Artist token and the persistent id. */ +static uint8_t records[64][TrackData_dbid + 8]; + +static void *record(unsigned i, uint32_t artist, uint32_t id_low, uint32_t id_high) +{ + uint8_t *r = records[i]; + memset(r, 0, sizeof records[i]); + RV_FIELD(r, 0, void *) = track_data; + RV_FIELD(r, MediaRecord_artist, uint32_t) = artist; + RV_FIELD(r, TrackData_dbid, uint32_t) = id_low; + RV_FIELD(r, TrackData_dbid + 4, uint32_t) = id_high; + return r; +} + +#define U(...) ((const uint16_t[]){__VA_ARGS__}) +static const uint16_t artist_a[] = {'A', 'r', 't', 'i', 's', 't', ' ', 'A'}; +static const uint16_t various[] = {'V', 'a', 'r', 'i', 'o', 'u', 's'}; +static const uint16_t sort_x[] = {'X'}; + +/* One mhod of `type` with `text` for `record`, through the discard hook. */ +static int mhod(void *r, uint32_t type, const uint16_t *text, uint32_t units) +{ + file.text = text; + file.units = units; + uint64_t before = file.offset; + uint32_t body = 16 + units * 2 + 4; /* with retained padding */ + int status = fields_import_mhod(reader, body, r, type); + if (!status) + assert(file.offset == before + body); + return status; +} + +static void begin(void) +{ + RV_FIELD(reader, ITunesReader_file, void *) = &file; + RV_FIELD(reader, ITunesReader_owner, void *) = track_data; + memset(&file, 0, sizeof file); + fields_import_begin(reader); +} + +static void expect_text(const void *r, const uint16_t *text, uint32_t units) +{ + uint16_t out[64]; + uint32_t got = fields_read(r, out, 64); + assert(got == units && !memcmp(out, text, units * 2)); +} + +static void test_flush_rules(void) +{ + begin(); + uint32_t a = intern(artist_a, 8); /* the record's own Artist token */ + void *same = record(0, a, 1, 0); + void *differs = record(1, a, 2, 0); + void *sort_only = record(2, a, 3, 0); + void *same_sorted = record(3, a, 4, 0); + void *untagged = record(4, a, 5, 0); + void *no_artist = record(5, 0, 6, 0); + void *empty = record(6, a, 7, 0); + assert(!mhod(same, 22, artist_a, 8)); + assert(!mhod(empty, 22, various, 0)); /* an empty tag */ + assert(!mhod(differs, 22, various, 7)); + assert(!mhod(sort_only, 23, sort_x, 1)); + assert(!mhod(same_sorted, 22, artist_a, 8)); + assert(!mhod(same_sorted, 29, sort_x, 1)); + assert(!mhod(no_artist, 22, various, 7)); + /* The pending record flushes when another arrives, and once at the end. */ + assert(fields_count() == 3); + fields_import_end(0); + assert(fields_count() == 4 && fields_imported()); + /* Same-as-Artist stores nothing. */ + assert(!fields_token(same) && !fields_sort_token(same, 1) && + !fields_sort_token(same, 0)); + assert(fields_read(same, NULL, 0) == 0); + assert(fields_token(differs) && fields_token(differs) != a); + expect_text(differs, various, 7); + assert(!fields_token(sort_only) && fields_sort_token(sort_only, 0) && + !fields_sort_token(sort_only, 1)); + assert(fields_token(same_sorted) == a && fields_sort_token(same_sorted, 1)); + uint16_t text[8]; + assert(fields_read(same_sorted, text, 8) == 0); + assert(!fields_token(untagged) && !fields_token(empty)); + assert(fields_token(no_artist) == fields_token(differs)); + /* A record of another TrackData, or a stale one, answers nothing. */ + uint8_t other[TrackData_dbid + 8]; + memcpy(other, differs, sizeof other); + RV_FIELD(other, 0, void *) = other; + assert(!fields_token(other) && !fields_token(NULL)); + /* After the import a late mhod only skips. */ + uint32_t count = token_count; + assert(!mhod(untagged, 22, various, 7) && token_count == count && + !fields_token(untagged)); + /* The table is exact: 4 rows of 20 bytes, the import chunk gone. */ + assert(live_blocks == 1 && live_bytes == 4 * 20); + fields_destroy(track_data); + assert(!live_blocks && invalidated == 1 && !fields_imported()); + /* Destroying another TrackData's storage does nothing to the next table. */ + begin(); + fields_destroy(reader); + assert(fields_imported()); + fields_import_end(0); + assert(!live_blocks); + fields_destroy(track_data); +} + +static void test_sort_and_lookup(void) +{ + begin(); + /* Ids in both halves, out of order; more than one chunk's worth comes + * from the repeats below. */ + static const uint32_t ids[][2] = { + {5, 1}, {1, 0}, {0xffffffff, 0}, {2, 1}, {9, 9}, {4, 0}, + {3, 0}, {7, 2}, {8, 2}, {6, 2}, {1, 1}, {0, 1}, + {0xfffffffe, 0}, {11, 0}, {10, 0}, {12, 0}, {13, 0}, {14, 0}, + }; + + enum { N = sizeof ids / sizeof ids[0] }; + + for (unsigned i = 0; i < N; i++) + assert(!mhod(record(i, 0, ids[i][0], ids[i][1]), 22, various, 7)); + /* Chunk growth: 300 more ids fill a second chunk; the peak is the chunks + * plus the exact block while it is filled. */ + for (unsigned i = 0; i < 300; i++) + assert(!mhod(record(40 + i % 20, 0, 100 + i, 3), 22, various, 7)); + uint32_t total = N + 300; + fields_import_end(0); + assert(fields_count() == total && live_bytes == total * 20 && live_blocks == 1); + assert(peak_bytes <= total * 20 + 2 * (8 + 256 * 20) + 16); + uint32_t token = fields_token(records[0]); + for (unsigned i = 0; i < N; i++) + assert(fields_token(records[i]) == token); + assert(fields_token(record(59, 0, 399, 3)) == token && + !fields_token(record(59, 0, 400, 3))); + assert(!fields_token(record(60, 0, 5, 0)) && !fields_token(record(61, 0, 15, 0)) && + !fields_token(record(62, 0, 0, 0))); + fields_destroy(track_data); + assert(!live_blocks); +} + +static void test_failures(void) +{ + /* A failed import drops the table. */ + begin(); + assert(!mhod(record(0, 0, 1, 0), 22, various, 7)); + assert(!mhod(record(1, 0, 2, 0), 22, various, 7)); + fields_import_end(-1); + assert(!live_blocks && !fields_count()); + /* A body over INT32_MAX is refused; a short body, a cursor error, a decode + * past the body and a skip error all store nothing. */ + begin(); + void *r = record(0, 0, 1, 0); + assert(fields_import_mhod(reader, 0x80000000u, r, 22) == -0xd0); + assert(!fields_import_mhod(reader, 8, r, 22)); + file.position_error = -3; + assert(!mhod(r, 22, various, 7)); + file.position_error = 0; + file.text = various; + file.units = 7; + assert(fields_import_mhod(reader, 16, r, 22) == -0xd0); + file.skip_error = -4; + assert(fields_import_mhod(reader, 16 + 14 + 2, r, 22) == -4); + file.skip_error = 0; + /* A decode error keeps the row's slot empty but consumes the body. */ + file.decode_error = -5; + assert(!mhod(r, 22, various, 7)); + file.decode_error = 0; + fields_import_end(0); + assert(!fields_count() && !live_blocks); + fields_destroy(track_data); + /* Allocation failure drops the row; the table stays usable. Without + * memory for the final block the import's rows go. */ + begin(); + fail_alloc = 1; + assert(!mhod(record(0, 0, 1, 0), 22, various, 7)); + assert(!mhod(record(1, 0, 2, 0), 22, various, 7)); /* flushes record 0 */ + fail_alloc = 0; + assert(!mhod(record(2, 0, 3, 0), 22, various, 7)); + fields_import_end(0); + assert(fields_count() == 2 && fields_token(records[1]) && + fields_token(records[2]) && !fields_token(records[0])); + fields_destroy(track_data); + assert(!live_blocks); + begin(); + assert(!mhod(record(0, 0, 1, 0), 22, various, 7)); + assert(!mhod(record(1, 0, 2, 0), 22, various, 7)); + assert(!mhod(record(2, 0, 3, 0), 22, various, 7)); + fail_alloc = 1; + fields_import_end(0); + fail_alloc = 0; + assert(!fields_count() && !live_blocks && fields_imported()); + fields_destroy(track_data); +} + +int main(void) +{ + test_flush_rules(); + test_sort_and_lookup(); + test_failures(); + assert(!live_blocks); + return 0; +} diff --git a/extensions/album-artists/tests/run.py b/extensions/album-artists/tests/run.py new file mode 100644 index 0000000..1d85789 --- /dev/null +++ b/extensions/album-artists/tests/run.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +"""Run the table and browser tests with a staged SDK: python3 tests/run.py SDK.""" + +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +root = Path(__file__).resolve().parent +sdk = Path(sys.argv[1]).resolve() +with tempfile.TemporaryDirectory(prefix="album-artists-tests-") as name: + work = Path(name) + # Widen the pointer-bearing native layouts for the host; record offsets stay. + header = (sdk / "osos-2.0.5.h").read_text() + + def widen(match): + key, value = match.groups() + if key.startswith(("ITunesReader_", "MediaBrowser_", "MediaList_", "MediaEntry_", + "MediaOrder_", "TrackData_", "LibraryBrowser_", + "MediaListSelection_")): + return f"#define {key} {int(value, 16) * 2:#x}" + return match[0] + + (work / "osos-2.0.5.h").write_text( + re.sub(r"#define (\w+) (0x[0-9a-f]+)", widen, header) + ) + for header in ("rv_api.h", "rv_libc.h", "rv_media.h"): + (work / header).write_text((sdk / header).read_text()) + for source in ("contracts.c", "browser_contracts.c"): + executable = work / source[:-2] + subprocess.run( + [ + "cc", + "-std=c11", + "-Wall", + "-Wextra", + "-Werror", + "-g", + "-fsanitize=address,undefined", + "-I", + str(work), + str(root / source), + "-o", + str(executable), + ], + check=True, + ) + subprocess.run([str(executable)], check=True) +print("Album Artists contracts passed") diff --git a/extensions/appearance/Makefile b/extensions/appearance/Makefile new file mode 100644 index 0000000..ffab405 --- /dev/null +++ b/extensions/appearance/Makefile @@ -0,0 +1,29 @@ +# SPDX-License-Identifier: GPL-3.0-only +main_SOURCES := main.c look.c style.c render.c catalog.c crc.c tint.c selection_bar.c \ + menu_covers.c flat_cover.c latch.c theme.c theme_picker.c lz.c assets.c dark_mode.c \ + ../shared/schedule.c ../shared/sun.c +switch_SOURCES := switch.c pack.c derive.c stock.c +OUT ?= build +# The theme compiler and the Classic theme live in themes/ at the repository +# root: rvt.h and the bitmap catalog come from there, and the Classic dark +# artwork is compiled from there into build/classic.rvt, which stays under +# build/ whatever OUT is, where manifest.toml names it. +THEMES ?= ../../themes +RVT_DATA := $(THEMES)/rvt/data +CATALOG := $(RVT_DATA)/osos-2.0.5.json +CLASSIC := build/classic.rvt +EXTRA_CFLAGS := -I$(OUT) -I../shared -I$(RVT_DATA) +include $(SDK)/rv.mk + +$(OUT)/catalog.inc: $(CATALOG) tools/catalog_inc.py | $(OUT) + $(PYTHON) tools/catalog_inc.py $< $@ +$(OUT)/main/catalog.c.o: $(OUT)/catalog.inc + +$(CLASSIC): $(THEMES)/themes/classic/theme.toml \ + $(wildcard $(THEMES)/themes/classic/dark/apple/*) $(wildcard $(THEMES)/rvt/*.py) \ + $(wildcard $(RVT_DATA)/*) tools/catalog_inc.py + mkdir -p build + cd $(THEMES) && $(PYTHON) -m rvt compile themes/classic --allow-reserved --strict \ + --out $(abspath build)/classic-build >/dev/null + $(PYTHON) tools/catalog_inc.py $(CATALOG) --check build/classic-build/classic/classic.rvt + cp build/classic-build/classic/classic.rvt $@ diff --git a/extensions/appearance/README.md b/extensions/appearance/README.md new file mode 100644 index 0000000..0486282 --- /dev/null +++ b/extensions/appearance/README.md @@ -0,0 +1,48 @@ +# Appearance + +Derives from the core's former Dark Mode (payload/dark_mode.c, 01c89f6) by lgreitis and Alex Ball (alexballvideos-netizen). The Classic theme's dark background is the core's former themes/dark/background-dark-image.png by lgreitis. + +Adds Settings > Appearance, after Brightness, with five rows: + +| Row | Does | +|---|---| +| Theme | replaces colours and artwork | +| Accent | replaces the stock blue in the selection bar, the accent artwork and accent labels | +| Dark Mode | turns the look dark: Auto, On or Off | +| Menu Covers | shows the highlighted row's cover in the Main and Music menus; its Theme value follows the look, which is on for Classic | +| Now Playing Cover | draws the Now Playing cover tilted with its reflection, or flat; its Theme value follows the look, which is tilted for Classic | + +Other extensions can add rows to the menu after any of these (their ids are `theme`, `accent`, `dark-mode`, `menu-covers` and `now-playing-cover`); Night Shift's row follows Dark Mode. + +Themes are `.rvt` files in `/Reprise/Themes/`, built with the compiler in this repository's [themes directory](../../themes/README.md), which also holds the Classic theme. The Theme row lists Classic and up to 64 themes by name, rescanned each time it opens. A theme with the id `classic` is ignored. + +A theme may have a light appearance, a dark one or both. With only one, Dark Mode shows that one, its row value says which, and the pane says "Theme only supports dark mode" or "Theme only supports light mode". If the chosen theme's file is missing, Classic shows and Theme says "Theme unavailable"; the choice comes back with the file. + +A theme that cannot be read leaves the look unchanged. One that fails part way through is undone to the stock light look, and the row the action came from says so. If the stock artwork cannot be restored from `/Reprise/Firmware/reprise.bin`, the Appearance row disappears until the next boot. Presses queued during a switch cannot reverse it. Turning the extension off restores the stock artwork. + +## Auto + +Dark Mode's Auto follows sunset and sunrise in the city set under Settings > Date & Time > Time Zone, by the iPod's clock, checked once a minute: dark from the sunset minute to the sunrise minute. Without a time zone, Auto is light and says "Set a Time Zone". + +A theme with one appearance turns Dark Mode's Auto into the value it shows, as it does On and Off. + +## Colour roles + +| Role | Classic light | Classic dark | Draws | +|---|---|---|---| +| background | `#ffffff` | `#181818` | surfaces, the light greys of the stock screens | +| text | `#202020` | `#e8e8e8` | labels and the dark greys | +| accent_fill | `#236cc5` | `#00a1ff` | accent fills and the artwork that follows the accent | +| accent_text | `#3185d0` | `#00a1ff` | accent-coloured labels | +| on_accent | `#ffffff` | `#ffffff` | labels on the selection bar and on accent fills | +| selection | `#236cc5` | `#00a1ff` | the selection bar | +| cover_border | `#7e8183` | `#383838` | the Cover Flow border | +| icon_tint | `#3185d0` | `#00a1ff` | under a theme, extension icons and the artwork the theme tints with it | + +The accents are Blue, Teal, Green, Yellow, Orange, Red, Pink, Purple and Graphite. Theme Default keeps the look's own, and a theme may give each accent its own palette. A theme can replace extension bitmaps in Settings panes and canvases; the rest keep the extension's art. With `flat_icons`, Settings icons are drawn without their reflection. + +| | | +|---|---| +| Default | off | +| Memory | idle: the main module with the bitmap catalog and its state; Dark Mode on Auto: one timer; a look on: an index entry per bitmap the theme holds for extensions and the draw hook blocks; during a switch: the switch module; during a switch: one scratch block; the Theme list open: one entry per theme | +| Settings | theme id, Accent, Dark Mode, Menu Covers, Now Playing Cover, and `available`, the hidden bool that shows the Appearance row. The first load imports the core's former Dark Mode switch | diff --git a/extensions/appearance/assets.c b/extensions/appearance/assets.c new file mode 100644 index 0000000..41776f2 --- /dev/null +++ b/extensions/appearance/assets.c @@ -0,0 +1,142 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "assets.h" +#include "ext.h" +#include "look.h" +#include "osos-2.0.5.h" +#include "pixel.h" +#include "rv_libc.h" +#include "rv_theme.h" +#include "rvt.h" +#include "style.h" +#include "theme.h" +#include "tint.h" +#include + +static struct asset_entry + *live; /* the active look's index, which the provider answers from */ +static struct asset_entry + *pending; /* the next look's, under construction by a switch */ +static uint32_t live_count, pending_count; +static int providing; /* the core's provider is ours */ + +struct asset_entry *assets_reserve(uint32_t count) +{ + if (pending) + api->free(self, pending); + pending = count ? api->alloc(self, count * sizeof *pending) : NULL; + pending_count = pending ? count : 0; + return pending; +} + +void assets_commit(void) +{ + if (live) + api->free(self, live); + live = pending; + live_count = pending_count; + pending = NULL; + pending_count = 0; +} + +void assets_drop(void) +{ + assets_reserve(0); + assets_commit(); +} + +static const struct asset_entry *find(uint32_t owner, uint32_t asset) +{ + uint32_t low = 0, high = live_count; + while (low < high) { + uint32_t mid = low + (high - low) / 2; + const struct asset_entry *entry = live + mid; + if (entry->owner == owner && entry->asset == asset) + return entry; + if (asset_before(entry, owner, asset)) + low = mid + 1; + else + high = mid; + } + return NULL; +} + +/* The core's probe: how the look stores its bitmap for the asset, from the + * index. */ +static int replacement(uint32_t owner, uint32_t asset, struct rv_asset_stream *stream) +{ + const struct asset_entry *entry = find(owner, asset); + if (!entry) + return 0; + stream->codec = entry->kind == RVT_EXTENSION_BITMAP_LZ ? RV_ASSET_LZ : RV_ASSET_RAW; + stream->stored = entry->bytes; + stream->bytes = entry->decoded; + return 1; +} + +/* The core's read: the stored bitmap from the look's file. The core decodes + * and checks it; a read that fails returns 0 and the core decodes the + * extension's own bitmap instead. Nothing here binds or releases: the core + * is in the middle of a decode or a preload. */ +static int replacement_read(uint32_t owner, uint32_t asset, void *out, uint32_t stored) +{ + struct rv_file *file; + const struct asset_entry *entry = find(owner, asset); + if (!entry || stored != entry->bytes || !look_file_open(look_active(), &file)) + return 0; + int whole = api->file_seek(self, file, entry->offset) == RV_OK && + read_exact(file, out, stored); + api->file_close(self, file); + return whole; +} + +/* An extension's Settings icon as the core decodes it: the art in the upper + * rows of a 78 by 121 Mask8, its mirrored reflection below ICON_ART_ROWS. */ +enum { ICON_WIDTH = 78, ICON_HEIGHT = 121, ICON_STRIDE = 80, ICON_ART_ROWS = 79 }; + +static int menu_bitmap(const uint8_t *b, uint32_t bytes) +{ + return bytes == BMap_payload + ICON_STRIDE * ICON_HEIGHT && + le16(b + BMap_format) == BMapFormat_Mask8 && + le16(b + BMap_stride) == ICON_STRIDE && le16(b + BMap_depth) == 8 && + !le32(b + BMap_bounds) && !le32(b + BMap_bounds + 4) && + le32(b + BMap_bounds + 8) == ICON_HEIGHT && + le32(b + BMap_bounds + 12) == ICON_WIDTH && + le32(b + BMap_payload_bytes) == ICON_STRIDE * ICON_HEIGHT; +} + +/* A decoded bitmap, the look's replacement or the extension's own: a tinted + * replacement picture is painted in its role; under a flat-icon look a + * Settings icon loses its reflection. */ +static int adjust(uint32_t owner, uint32_t asset, void *bmap, uint32_t bytes) +{ + const struct asset_entry *entry = find(owner, asset); + if (entry && entry->tint != RVT_TINT_NONE && !menu_bitmap(bmap, bytes)) + return tint_bmap(bmap, bytes, + style_color((enum rvt_role)(entry->tint - RVT_TINT_ROLE))); + if (!(style_flags() & RVT_FLAG_FLAT_ICONS) || !menu_bitmap(bmap, bytes)) + return 0; + memset((uint8_t *)bmap + BMap_payload + ICON_ART_ROWS * ICON_STRIDE, 0, + (ICON_HEIGHT - ICON_ART_ROWS) * ICON_STRIDE); + return 1; +} + +static const struct rv_asset_provider provider = {replacement, replacement_read, + adjust}; + +int assets_bind(void) +{ + if (!live_count && !(style_flags() & RVT_FLAG_FLAT_ICONS)) { + assets_release(); + return 1; + } + providing = api->asset_set_provider(self, &provider) == RV_OK; + return providing; +} + +void assets_release(void) +{ + if (providing) + api->asset_set_provider(self, NULL); + providing = 0; +} diff --git a/extensions/appearance/assets.h b/extensions/appearance/assets.h new file mode 100644 index 0000000..490a24f --- /dev/null +++ b/extensions/appearance/assets.h @@ -0,0 +1,45 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* A theme's bitmaps for extensions: the pack's extension bitmap table as an + * index into the active look's file, and the asset provider that serves the + * core from it when it decodes an extension's bitmap, for a Settings pane or + * a canvas alike. The index is main's, since the provider answers while the + * switch module is unloaded; the switch module fills it through main_service. */ + +#ifndef ASSETS_H +#define ASSETS_H +#include "rv_api.h" +#include + +/* One bitmap of the look: where it is in the look's file, the bytes stored + * there (the whole BMap raw or as one lz stream), the bytes it decodes to and + * the tint word of the pack's table: RVT_TINT_NONE, or RVT_TINT_ROLE plus the + * role the provider paints the decoded picture in. */ +struct asset_entry { + uint32_t owner, asset, offset, bytes, decoded; + uint16_t kind; + uint8_t tint; +}; + +/* The index order: by owner, then asset. */ +static inline int asset_before(const struct asset_entry *a, uint32_t owner, + uint32_t asset) +{ + return a->owner < owner || (a->owner == owner && a->asset < asset); +} + +/* A switch builds the next index beside the active one, which answers until + * the switch succeeds: assets_reserve frees any index under construction and, + * for a count above 0, allocates one of `count` entries to fill in (owner, + * asset) order, NULL for no memory; assets_commit makes it the active one; + * assets_drop frees both. */ +struct asset_entry *assets_reserve(uint32_t count); +void assets_commit(void); +void assets_drop(void); +/* Holds the core's asset provider while the active index has entries or the + * look asks for flat icons, which also makes the core decode the bitmaps on + * screen again; releases it otherwise. 0 when the core refused. */ +int assets_bind(void); +void assets_release(void); + +#endif diff --git a/extensions/appearance/assets/LICENSE.cupertino-icons b/extensions/appearance/assets/LICENSE.cupertino-icons new file mode 100644 index 0000000..581f84c --- /dev/null +++ b/extensions/appearance/assets/LICENSE.cupertino-icons @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2016 Vladimir Kharlampidi + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/extensions/appearance/assets/render.py b/extensions/appearance/assets/render.py new file mode 100755 index 0000000..3674533 --- /dev/null +++ b/extensions/appearance/assets/render.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +"""Render the Settings pane icons: a Cupertino Icons glyph each, fitted into +the art box of the stock Settings icons on a 78 x 121 gray coverage mask, lit +from the top and mirrored in a fading reflection below. Drawing uses +ImageMagick's `magick`; the font (CupertinoIcons.ttf from the Flutter +`cupertino_icons` package, MIT, see LICENSE.cupertino-icons) is not in the +repository. + + python3 assets/render.py --font CupertinoIcons.ttf + python3 assets/render.py --font CupertinoIcons.ttf --check +""" + +import sys +from functools import partial +from pathlib import Path + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE.parents[1] / "shared")) +from settings_icon import ART_BOTTOM, ART_TOP, glyph, icon, main + +# Icon file stem, the glyph's code point in the font, and its reach: the +# longer side of the box the glyph is fitted into, centred on the art box. +ICONS = { + "settings-appearance": (0xF7E8, 52), # sparkles + "settings-theme": (0xF72F, 52), # paintbrush_fill + "settings-accent": (0xF665, 52), # eyedropper_full + "settings-moon": (0xF719, 52), # moon_fill + "settings-covers": (0xF809, 52), # square_lefthalf_fill + "settings-cover": (0xF758, 52), # perspective, mirrored to lean like the cover +} +MIRRORED = {"settings-cover"} + + +def render(out, work, font, code, reach, mirror): + icon(out, work, glyph(work, font, code, reach, mirror), ART_TOP, ART_BOTTOM) + + +if __name__ == "__main__": + main( + __doc__, + { + HERE / f"{stem}.png": partial( + render, code=code, reach=reach, mirror=stem in MIRRORED + ) + for stem, (code, reach) in ICONS.items() + }, + font=True, + ) diff --git a/extensions/appearance/assets/settings-accent.png b/extensions/appearance/assets/settings-accent.png new file mode 100644 index 0000000..675720a Binary files /dev/null and b/extensions/appearance/assets/settings-accent.png differ diff --git a/extensions/appearance/assets/settings-appearance.png b/extensions/appearance/assets/settings-appearance.png new file mode 100644 index 0000000..255ec3e Binary files /dev/null and b/extensions/appearance/assets/settings-appearance.png differ diff --git a/extensions/appearance/assets/settings-cover.png b/extensions/appearance/assets/settings-cover.png new file mode 100644 index 0000000..65fe22b Binary files /dev/null and b/extensions/appearance/assets/settings-cover.png differ diff --git a/extensions/appearance/assets/settings-covers.png b/extensions/appearance/assets/settings-covers.png new file mode 100644 index 0000000..72cd521 Binary files /dev/null and b/extensions/appearance/assets/settings-covers.png differ diff --git a/extensions/appearance/assets/settings-moon.png b/extensions/appearance/assets/settings-moon.png new file mode 100644 index 0000000..6de0cf1 Binary files /dev/null and b/extensions/appearance/assets/settings-moon.png differ diff --git a/extensions/appearance/assets/settings-theme.png b/extensions/appearance/assets/settings-theme.png new file mode 100644 index 0000000..ef93667 Binary files /dev/null and b/extensions/appearance/assets/settings-theme.png differ diff --git a/extensions/appearance/catalog.c b/extensions/appearance/catalog.c new file mode 100644 index 0000000..6e4c17e --- /dev/null +++ b/extensions/appearance/catalog.c @@ -0,0 +1,233 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "catalog.h" +#include "osos-2.0.5.h" +#include "pixel.h" + +struct contrast_text { + uint32_t first; + uint16_t count, index; +}; + +struct accent_art { + uint16_t index; + uint8_t role; +}; + +/* catalog_offsets[i] is bitmap i's offset from the bank base, word aligned, + * with the padding that follows it in the low two bits; the last entry ends + * the bank. */ +#include "catalog.inc" +_Static_assert(sizeof contrast_text / sizeof *contrast_text == CATALOG_CONTRAST_TEXTS, + "catalog.h names the contrast text count"); + +static uint32_t offset_of(uint32_t index) +{ + return catalog_offsets[index] & ~3u; +} + +uint32_t catalog_count(void) +{ + return CATALOG_COUNT; +} + +const uint8_t *catalog_fingerprint(void) +{ + return fingerprint; +} + +uint8_t *catalog_data(uint32_t index) +{ + return (uint8_t *)CATALOG_BASE + offset_of(index); +} + +uint32_t catalog_size(uint32_t index) +{ + return offset_of(index + 1) - offset_of(index) - (catalog_offsets[index] & 3u); +} + +uint32_t catalog_crc(uint32_t index) +{ + return catalog_crcs[index]; +} + +uint32_t catalog_file_offset(uint32_t index) +{ + return CATALOG_FILE_OFFSET + offset_of(index); +} + +/* A BMap: the header's format, stride, depth and bounds, then its data length + * word right before the data, which a bank bitmap holds at BMap_payload_bytes + * or one word later; then for paletted formats the colour count and the BGRA + * palette, then the rows. The bounds start at the origin. */ +int catalog_layout(uint32_t index, struct layout *b) +{ + if (index >= CATALOG_COUNT || index >= RVT_CATALOG_MAX) + return 0; + uint32_t size = catalog_size(index); + const uint8_t *p = catalog_data(index); + if (size < RVT_BMAP_HEADER_BYTES) + return 0; + b->start = le32(p + BMap_payload_bytes) == size - BMap_payload ? BMap_payload + : BMap_payload + 4; + if (size < b->start || le32(p + b->start - 4) != size - b->start) + return 0; + uint32_t format = le16(p + BMap_format); + b->mask = format == BMapFormat_Mask4 || format == BMapFormat_Mask8; + b->depth = format == BMapFormat_Mask4 ? 4 + : format == BMapFormat_Mask8 || format == BMapFormat_Indexed8 ? 8 + : format == BMapFormat_Indexed16 || format == BMapFormat_RGB565 ? 16 + : format == BMapFormat_BGRA8888 ? 32 + : 0; + b->stride = le16(p + BMap_stride); + b->height = le32(p + BMap_bounds + 8); + b->width = le32(p + BMap_bounds + 12); + b->colors = 0; + if (le32(p + BMap_bounds) || le32(p + BMap_bounds + 4)) + return 0; + if (!b->depth || le16(p + BMap_depth) != b->depth || !b->width || !b->height || + !b->stride || b->width > 0xffffu || b->height > 0xffffu || + b->width * b->depth > b->stride * 8) + return 0; + if (format == BMapFormat_Indexed8 || format == BMapFormat_Indexed16) { + if (size - b->start < 4) + return 0; + b->colors = le32(p + b->start); + b->start += 4; + if (!b->colors || b->colors > (1u << b->depth) || + b->colors > (size - b->start) / 4) + return 0; + } + b->pixels = b->start + b->colors * 4; + return b->pixels <= size && b->height * b->stride == size - b->pixels; +} + +/* The last answers: a screen draws the same few bitmaps again and again. */ +enum { RECENT = 8 }; + +static struct { + const uint8_t *pixels; + uint32_t index; +} recent[RECENT]; + +static unsigned recent_next; + +static int catalog_contains(const uint8_t *pixels) +{ + const uint8_t *base = (const uint8_t *)CATALOG_BASE; + return pixels >= base && pixels < base + CATALOG_BANK_BYTES; +} + +int catalog_from_pixels(const uint8_t *pixels, uint32_t *index) +{ + const uint8_t *base = (const uint8_t *)CATALOG_BASE; + if (!catalog_contains(pixels) || pixels < base + RVT_BMAP_HEADER_BYTES) + return 0; + for (unsigned i = 0; i < RECENT; i++) + if (recent[i].pixels == pixels) { + *index = recent[i].index; + return 1; + } + /* The header the pixels follow, found by bisection over the offsets. */ + uint32_t at = (uint32_t)(pixels - base) - RVT_BMAP_HEADER_BYTES, low = 0, + high = CATALOG_COUNT; + while (high - low > 1) { + uint32_t mid = (low + high) / 2; + if (offset_of(mid) <= at) + low = mid; + else + high = mid; + } + struct layout b; + if (offset_of(low) != at || !catalog_layout(low, &b)) + return 0; + recent[recent_next].pixels = pixels; + recent[recent_next].index = low; + recent_next = (recent_next + 1) % RECENT; + *index = low; + return 1; +} + +uint8_t *catalog_palette(uint32_t index, uint32_t *colors) +{ + struct layout b; + if (!catalog_layout(index, &b) || !b.colors) + return 0; + *colors = b.colors; + return catalog_data(index) + b.start; +} + +uint8_t *catalog_argb(uint32_t index, uint32_t *width, uint32_t *height, + uint32_t *stride) +{ + struct layout b; + if (!catalog_layout(index, &b) || b.depth != 32) + return 0; + *width = b.width; + *height = b.height; + *stride = b.stride; + return catalog_data(index) + b.pixels; +} + +int catalog_center_pixel(uint32_t index, uint8_t out[4]) +{ + struct layout b; + if (!catalog_layout(index, &b) || b.mask || (b.depth == 16 && !b.colors)) + return 0; + const uint8_t *data = catalog_data(index); + const uint8_t *row = data + b.pixels + ((b.height - 1) / 2) * b.stride; + const uint8_t *pixel; + if (b.colors) { + uint32_t column = (b.width - 1) / 2; + uint32_t entry = b.depth == 16 ? le16(row + column * 2) : row[column]; + if (entry >= b.colors) + return 0; + pixel = data + b.start + entry * 4; + } else { + pixel = row + ((b.width - 1) / 2) * 4; + } + if (!pixel[3]) + return 0; + out[0] = pixel[2]; + out[1] = pixel[1]; + out[2] = pixel[0]; + out[3] = 255; + return 1; +} + +uint32_t catalog_well_center(unsigned well) +{ + return well_centers[well < WELLS ? well : 0]; +} + +uint32_t catalog_field_center(void) +{ + return field_center; +} + +uint32_t catalog_calendar_cell(unsigned place) +{ + return calendar_cells[place < CALENDAR_CELLS ? place : 0]; +} + +int catalog_accent_art(uint32_t i, uint32_t *index, uint8_t *role) +{ + if (i >= sizeof accent_art / sizeof *accent_art) + return 0; + *index = accent_art[i].index; + *role = accent_art[i].role; + return 1; +} + +int catalog_contrast_text(uint32_t view) +{ + for (uint32_t i = 0; i < CATALOG_CONTRAST_TEXTS; i++) + if (view - contrast_text[i].first < contrast_text[i].count) + return (int)i; + return -1; +} + +uint32_t catalog_contrast_art(unsigned entry) +{ + return contrast_text[entry < CATALOG_CONTRAST_TEXTS ? entry : 0].index; +} diff --git a/extensions/appearance/catalog.h b/extensions/appearance/catalog.h new file mode 100644 index 0000000..3f8e63b --- /dev/null +++ b/extensions/appearance/catalog.h @@ -0,0 +1,91 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The firmware's bitmap bank: Apple's BMaps lie one after another in RAM, + * word aligned, in catalog order. The catalog (catalog.inc, generated from the + * themes directory's osos-2.0.5.json) gives each bitmap's offset in the bank + * and its stock checksum, and names the ones the extension treats specially. */ + +#ifndef CATALOG_H +#define CATALOG_H +#include "rvt.h" +#include + +#define BITMAP_WORDS (RVT_CATALOG_MAX / 32) + +/* Where a bitmap's bytes are: the palette or pixels start at `start`, the + * pixels at `pixels`; `colors` is the palette size, 0 without one; `mask` for + * the coverage formats the system colours while drawing. */ +struct layout { + uint32_t start, pixels, colors, stride, width, height, depth, mask; +}; + +static inline int same_layout(const struct layout *a, const struct layout *b) +{ + return a->start == b->start && a->pixels == b->pixels && a->colors == b->colors && + a->stride == b->stride && a->width == b->width && a->height == b->height && + a->depth == b->depth && a->mask == b->mask; +} + +uint32_t catalog_count(void); +const uint8_t *catalog_fingerprint(void); +uint8_t *catalog_data(uint32_t index); +uint32_t catalog_size(uint32_t index); +/* The low 16 bits of the stock bytes' CRC-32. */ +uint32_t catalog_crc(uint32_t index); +/* The offset of a bitmap's bytes in the firmware file. */ +uint32_t catalog_file_offset(uint32_t index); +/* 0 for an index past the catalog or a header that does not describe the + * bitmap's bytes. */ +int catalog_layout(uint32_t index, struct layout *b); +/* The catalog index of the bitmap whose pixel data starts at `pixels`. */ +int catalog_from_pixels(const uint8_t *pixels, uint32_t *index); +/* The resident BGRA palette of a paletted bitmap, or NULL. */ +uint8_t *catalog_palette(uint32_t index, uint32_t *colors); +/* The resident BGRA rows of an ARGB bitmap, or NULL. */ +uint8_t *catalog_argb(uint32_t index, uint32_t *width, uint32_t *height, + uint32_t *stride); +/* The opaque RGBA of the centre pixel of a paletted or ARGB bitmap; 0 for + * masks, RGB565, a bad layout or a clear pixel. */ +int catalog_center_pixel(uint32_t index, uint8_t out[4]); + +/* Option bar wells, which the keyboard and the option bars draw their labels + * on: white and black take the look, Now Playing's shuffle selector has its + * own colours, and its labels follow a theme or Classic dark. */ +enum { WELL_WHITE, WELL_BLACK, WELL_NOW_PLAYING, WELLS }; + +uint32_t catalog_well_center(unsigned well); +/* The Search input field's middle slice. */ +uint32_t catalog_field_center(void); + +/* Calendar day cells by what they show, then the page the weekday names sit + * on, which is no cell. */ +enum calendar_place { + CALENDAR_ACTIVE, + CALENDAR_INACTIVE, + CALENDAR_HILITE, + CALENDAR_CELLS, + CALENDAR_HEADER = CALENDAR_CELLS +}; + +/* The bitmap of a cell place, below CALENDAR_CELLS. */ +uint32_t catalog_calendar_cell(unsigned place); +/* Stock blue art that follows the accent: entry i's index and role; 0 past the end. */ +int catalog_accent_art(uint32_t i, uint32_t *index, uint8_t *role); +/* Labels drawn in a fixed colour over art: the entry (below + * CATALOG_CONTRAST_TEXTS) a view id belongs to, -1 for other views, and the + * art behind an entry. */ +#define CATALOG_CONTRAST_TEXTS 5 +int catalog_contrast_text(uint32_t view); +uint32_t catalog_contrast_art(unsigned entry); + +static inline int bit_test(const uint32_t *bits, uint32_t index) +{ + return (bits[index / 32] >> (index % 32)) & 1; +} + +static inline void bit_set(uint32_t *bits, uint32_t index) +{ + bits[index / 32] |= 1u << (index % 32); +} + +#endif diff --git a/extensions/appearance/crc.c b/extensions/appearance/crc.c new file mode 100644 index 0000000..dc8ce23 --- /dev/null +++ b/extensions/appearance/crc.c @@ -0,0 +1,21 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "crc.h" + +/* Polynomial 0xedb88320, four bits at a time. */ +static const uint32_t crc_nibbles[16] = { + 0x00000000u, 0x1db71064u, 0x3b6e20c8u, 0x26d930acu, 0x76dc4190u, 0x6b6b51f4u, + 0x4db26158u, 0x5005713cu, 0xedb88320u, 0xf00f9344u, 0xd6d6a3e8u, 0xcb61b38cu, + 0x9b64c2b0u, 0x86d3d2d4u, 0xa00ae278u, 0xbdbdf21cu, +}; + +uint32_t crc32_update(uint32_t crc, const void *data, uint32_t size) +{ + const uint8_t *p = data; + while (size--) { + crc ^= *p++; + crc = (crc >> 4) ^ crc_nibbles[crc & 15u]; + crc = (crc >> 4) ^ crc_nibbles[crc & 15u]; + } + return crc; +} diff --git a/extensions/appearance/crc.h b/extensions/appearance/crc.h new file mode 100644 index 0000000..0c2a3e9 --- /dev/null +++ b/extensions/appearance/crc.h @@ -0,0 +1,12 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#ifndef CRC_H +#define CRC_H +#include + +/* Reflected CRC-32 over an inverted seed: start from 0xffffffff, invert the + * result. The main module holds the one copy; the switch module calls it + * through main_service. */ +uint32_t crc32_update(uint32_t crc, const void *data, uint32_t size); + +#endif diff --git a/extensions/appearance/dark_mode.c b/extensions/appearance/dark_mode.c new file mode 100644 index 0000000..6e6807b --- /dev/null +++ b/extensions/appearance/dark_mode.c @@ -0,0 +1,40 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "dark_mode.h" +#include "look.h" +#include "schedule.h" +#include "style.h" + +const char *const dark_mode_labels[3] = {"Auto", "On", "Off"}; +static int choice = DARK_OFF; + +void dark_mode_set(int value) +{ + choice = value; +} + +int dark_mode_auto(void) +{ + return choice == DARK_AUTO; +} + +int dark_mode_wanted(void) +{ + struct schedule s; + if (choice != DARK_AUTO) + return choice == DARK_ON; + schedule_read(&s); + return schedule_night(&s); +} + +const char *dark_mode_caption(void) +{ + const char *problem = look_problem(PANE_DARK), *note = look_appearance_note(); + if (problem) + return problem; + if (note) + return note; + if (choice == DARK_AUTO) + return schedule_caption(); + return style_dark() ? "On" : "Off"; +} diff --git a/extensions/appearance/dark_mode.h b/extensions/appearance/dark_mode.h new file mode 100644 index 0000000..b7ea8f5 --- /dev/null +++ b/extensions/appearance/dark_mode.h @@ -0,0 +1,18 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#ifndef DARK_MODE_H +#define DARK_MODE_H + +/* Dark Mode: Auto from sunset to sunrise by the schedule, On or Off. The + * look on the screen is the switch's business; this is what the setting + * asks for. */ +enum { DARK_AUTO, DARK_ON, DARK_OFF }; + +extern const char *const dark_mode_labels[3]; +void dark_mode_set(int mode); +int dark_mode_auto(void); +/* Whether the setting asks for the dark appearance right now. */ +int dark_mode_wanted(void); +const char *dark_mode_caption(void); + +#endif diff --git a/extensions/appearance/derive.c b/extensions/appearance/derive.c new file mode 100644 index 0000000..d316bed --- /dev/null +++ b/extensions/appearance/derive.c @@ -0,0 +1,393 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "derive.h" +#include "pixel.h" +#include "rv_libc.h" +#include "switch.h" + +enum { ONE = 256, FULL = 255, GRAY_MAP = 256 }; + +static int luma(const uint8_t *bgra) +{ + return (77 * bgra[2] + 150 * bgra[1] + 29 * bgra[0]) >> 8; +} + +static int is_565(const struct layout *b) +{ + return b->depth == 16 && !b->colors && !b->mask; +} + +/* A BGRA entry or pixel as the RGBA word the tables are keyed by. */ +static uint32_t key_bgra(const uint8_t *p) +{ + return p[2] | (uint32_t)p[1] << 8 | (uint32_t)p[0] << 16 | (uint32_t)p[3] << 24; +} + +static uint32_t key_565(uint32_t w) +{ + uint8_t rgb[3]; + rgb565_unpack(w, rgb); + return rgb[0] | (uint32_t)rgb[1] << 8 | (uint32_t)rgb[2] << 16 | 0xff000000u; +} + +static uint32_t index_at(const struct layout *b, const uint8_t *rows, uint32_t x, + uint32_t y) +{ + const uint8_t *row = rows + y * b->stride; + return b->depth == 8 ? row[x] : le16(row + x * 2); +} + +static void set_index(const struct layout *b, uint8_t *rows, uint32_t x, uint32_t y, + uint32_t v) +{ + uint8_t *row = rows + y * b->stride; + if (b->depth == 8) { + row[x] = (uint8_t)v; + } else { + row[x * 2] = (uint8_t)v; + row[x * 2 + 1] = (uint8_t)(v >> 8); + } +} + +/* The pair whose `from` is `k`, or NULL. */ +static const uint8_t *lookup(const uint8_t *table, uint32_t count, uint32_t k) +{ + uint32_t low = 0, high = count; + while (low < high) { + uint32_t mid = (low + high) / 2, at = le32(table + mid * 8); + if (at == k) + return table + mid * 8 + 4; + if (at < k) + low = mid + 1; + else + high = mid; + } + return NULL; +} + +static int exact_565(const uint8_t *rgba) +{ + return !(rgba[0] & 7) && !(rgba[1] & 3) && !(rgba[2] & 7) && rgba[3] == 255; +} + +int derive_recolor(uint32_t asset, const struct layout *b, const uint8_t *table, + uint32_t count) +{ + uint8_t *data = main_module->catalog_data(asset); + if (b->mask || !count || count > RVT_RECOLOR_MAX) + return 0; + for (uint32_t i = 0; i < count; i++) { + const uint8_t *pair = table + i * 8; + if ((i && le32(pair) <= le32(pair - 8)) || le32(pair) == le32(pair + 4) || + (is_565(b) && !(exact_565(pair) && exact_565(pair + 4)))) + return 0; + } + if (b->colors) { + uint8_t *entry = data + b->start; + for (uint32_t i = 0; i < b->colors; i++, entry += 4) { + const uint8_t *to = lookup(table, count, key_bgra(entry)); + if (to) + entry[0] = to[2], entry[1] = to[1], entry[2] = to[0], entry[3] = to[3]; + } + return 1; + } + uint8_t *row = data + b->pixels; + for (uint32_t y = 0; y < b->height; y++, row += b->stride) + for (uint32_t x = 0; x < b->width; x++) { + if (is_565(b)) { + uint8_t *p = row + x * 2; + const uint8_t *to = lookup(table, count, key_565(le16(p))); + if (to) { + uint32_t w = rgb565_pack(to); + p[0] = (uint8_t)w, p[1] = (uint8_t)(w >> 8); + } + } else { + uint8_t *p = row + x * 4; + const uint8_t *to = lookup(table, count, key_bgra(p)); + if (to) + p[0] = to[2], p[1] = to[1], p[2] = to[0], p[3] = to[3]; + } + } + return 1; +} + +int derive_invert(uint32_t asset, const struct layout *b) +{ + uint8_t *data = main_module->catalog_data(asset); + if (b->mask) + return 0; + if (b->colors) { + uint8_t *entry = data + b->start; + for (uint32_t i = 0; i < b->colors; i++, entry += 4) + entry[0] ^= 255, entry[1] ^= 255, entry[2] ^= 255; + return 1; + } + uint8_t *row = data + b->pixels; + for (uint32_t y = 0; y < b->height; y++, row += b->stride) + for (uint32_t x = 0; x < b->width; x++) { + uint8_t *p = row + x * (b->depth / 8); + if (is_565(b)) + p[0] ^= 255, p[1] ^= 255; + else if (p[3]) + p[0] ^= 255, p[1] ^= 255, p[2] ^= 255; + } + return 1; +} + +/* Relight words: see enum rvt_relight. */ +enum { + DEAD = RVT_RELIGHT_T_ZERO, + K = RVT_RELIGHT_T_FULL, + BG_BASE = RVT_RELIGHT_BG_BASE, + BG_REF = RVT_RELIGHT_BG_REF, + BG_SLOPE = RVT_RELIGHT_BG_SLOPE, + BG_LO = RVT_RELIGHT_BG_LO, + BG_HI = RVT_RELIGHT_BG_HI, + ICON_BASE = RVT_RELIGHT_ICON_BASE, + ICON_LUMA = RVT_RELIGHT_ICON_LUMA, + ICON_ROW = RVT_RELIGHT_ICON_ROW, + ICON_LO = RVT_RELIGHT_ICON_LO, + ICON_HI = RVT_RELIGHT_ICON_HI, +}; + +/* The words a product can take without overflowing 32 bits: offsets and + * lumas are at most 255 in 8.8, rows below RVT_SCRATCH_PIXELS. */ +enum { + LEVEL_MAX = 255 * ONE, + BASE_MAX = 1024 * ONE, + SLOPE_MAX = 16 * ONE, +}; + +static int within(int32_t value, int32_t bound) +{ + return value >= -bound && value <= bound; +} + +static int relight_valid(const struct layout *b, const int32_t *p) +{ + int32_t levels = ((p[ICON_HI] + ONE / 2) >> 8) - (p[BG_LO] >> 8) + 1; + return b->colors && b->width * b->height <= RVT_SCRATCH_PIXELS && 0 <= p[DEAD] && + p[DEAD] < p[K] && p[K] <= LEVEL_MAX && within(p[BG_BASE], BASE_MAX) && + within(p[BG_REF], LEVEL_MAX) && within(p[BG_SLOPE], SLOPE_MAX) && + within(p[ICON_BASE], BASE_MAX) && within(p[ICON_LUMA], LEVEL_MAX) && + within(p[ICON_ROW], LEVEL_MAX) && 0 <= p[BG_LO] && p[BG_LO] <= p[BG_HI] && + p[BG_HI] <= p[ICON_LO] && p[ICON_LO] <= p[ICON_HI] && + p[ICON_HI] <= LEVEL_MAX && levels <= (int32_t)b->colors; +} + +static int32_t offset_from(const uint8_t *c, const uint8_t *bg) +{ + int32_t o = 0; + for (unsigned i = 0; i < 3; i++) { + int32_t d = c[i] > bg[i] ? c[i] - bg[i] : bg[i] - c[i]; + o = d > o ? d : o; + } + return o * ONE; +} + +int derive_relight(uint32_t asset, const struct layout *b, const int32_t *p, + uint8_t *scratch) +{ + uint8_t *data = main_module->catalog_data(asset), *palette = data + b->start; + uint8_t *rows = data + b->pixels; + uint32_t w = b->width, h = b->height; + uint8_t *t = scratch, *map = scratch + RVT_SCRATCH_PIXELS; + if (!relight_valid(b, p)) + return 0; + for (uint32_t y = 0; y < h; y++) + for (uint32_t x = 0; x < w; x++) + if (index_at(b, rows, x, y) >= b->colors) + return 0; + uint64_t range = reciprocal((uint32_t)(p[K] - p[DEAD])); + /* Coverage, then shadows: a partly covered pixel with no fully covered + * neighbour. Pruning in place is safe because only full pixels count as + * neighbours and pruning never creates one. */ + for (uint32_t y = 0; y < h; y++) { + const uint8_t *bg = palette + index_at(b, rows, 0, y) * 4; + for (uint32_t x = 0; x < w; x++) { + int32_t o = offset_from(palette + index_at(b, rows, x, y) * 4, bg); + t[y * w + x] = + (uint8_t)(o <= p[DEAD] ? 0 + : o >= p[K] ? FULL + : divide((uint32_t)(o - p[DEAD]) * FULL, range)); + } + } + for (uint32_t y = 0; y < h; y++) + for (uint32_t x = 0; x < w; x++) { + if (!t[y * w + x] || t[y * w + x] == FULL) + continue; + int solid = 0; + for (int dy = -1; dy <= 1; dy++) + for (int dx = -1; dx <= 1; dx++) { + int32_t nx = (int32_t)x + dx, ny = (int32_t)y + dy; + if ((dx || dy) && nx >= 0 && ny >= 0 && nx < (int32_t)w && + ny < (int32_t)h && t[ny * w + nx] == FULL) + solid = 1; + } + if (!solid) + t[y * w + x] = 0; + } + /* The grays overwrite the coverage in place; the palette is read here and + * rewritten only after this pass. */ + for (uint32_t y = 0; y < h; y++) { + const uint8_t *bg = palette + index_at(b, rows, 0, y) * 4; + int32_t bgd = p[BG_BASE] + (luma(bg) * ONE - p[BG_REF]) * p[BG_SLOPE] / ONE; + bgd = clamp(bgd, p[BG_LO], p[BG_HI]); + for (uint32_t x = 0; x < w; x++) { + const uint8_t *c = palette + index_at(b, rows, x, y) * 4; + int32_t icon = + p[ICON_BASE] + p[ICON_LUMA] * luma(c) + p[ICON_ROW] * (int32_t)y; + icon = clamp(icon, p[ICON_LO], p[ICON_HI]); + int32_t mixed = + bgd + (int32_t)divide((uint32_t)(icon - bgd) * t[y * w + x] + FULL / 2, + reciprocal(FULL)); + t[y * w + x] = (uint8_t)((mixed + ONE / 2) >> 8); + } + } + memset(map, 0, GRAY_MAP); + for (uint32_t i = 0; i < w * h; i++) + map[t[i]] = 1; + uint32_t n = 0; + for (uint32_t g = 0; g < GRAY_MAP; g++) + if (map[g]) { + if (n == b->colors) { + /* More grays than entries: a half-written bitmap, zeroed for the caller. */ + memset(data + b->start, 0, main_module->catalog_size(asset) - b->start); + return 0; + } + palette[n * 4] = palette[n * 4 + 1] = palette[n * 4 + 2] = (uint8_t)g; + palette[n * 4 + 3] = 255; + map[g] = (uint8_t)n++; + } + memset(palette + n * 4, 0, (b->colors - n) * 4); + for (uint32_t y = 0; y < h; y++) + for (uint32_t x = 0; x < w; x++) + set_index(b, rows, x, y, map[t[y * w + x]]); + return 1; +} + +/* The RGBA of a source pixel, whatever its format. */ +static void source_pixel(const struct layout *s, const uint8_t *data, uint32_t x, + uint32_t y, uint8_t rgba[4]) +{ + const uint8_t *p; + if (s->colors) { + p = data + s->start + index_at(s, data + s->pixels, x, y) * 4; + } else if (is_565(s)) { + rgb565_unpack(le16(data + s->pixels + y * s->stride + x * 2), rgba); + rgba[3] = 255; + return; + } else { + p = data + s->pixels + y * s->stride + x * 4; + } + rgba[0] = p[2], rgba[1] = p[1], rgba[2] = p[0], rgba[3] = p[3]; +} + +int derive_alias(uint32_t asset, const struct layout *b, uint32_t source) +{ + struct layout s; + uint8_t *data = main_module->catalog_data(asset); + if (source == asset || !main_module->catalog_layout(source, &s) || b->mask || + s.mask || b->width != s.width || b->height != s.height) + return 0; + const uint8_t *from = main_module->catalog_data(source); + if (same_layout(b, &s) && + main_module->catalog_size(asset) == main_module->catalog_size(source)) { + memcpy(data + b->start, from + s.start, + main_module->catalog_size(asset) - b->start); + return 1; + } + if (b->width * b->height > RVT_SCRATCH_PIXELS) + return 0; + if (s.colors) + for (uint32_t y = 0; y < s.height; y++) + for (uint32_t x = 0; x < s.width; x++) + if (index_at(&s, from + s.pixels, x, y) >= s.colors) + return 0; + uint8_t *palette = data + b->start, *rows = data + b->pixels; + uint32_t n = 0; + for (uint32_t y = 0; y < b->height; y++) + for (uint32_t x = 0; x < b->width; x++) { + uint8_t rgba[4]; + source_pixel(&s, from, x, y, rgba); + if (b->colors) { + uint8_t bgra[4] = {rgba[2], rgba[1], rgba[0], rgba[3]}; + uint32_t i = 0; + while (i < n && memcmp(palette + i * 4, bgra, 4)) + i++; + if (i == n) { + if (n == b->colors) { + /* Out of palette entries: a half-written bitmap, zeroed for the caller. */ + memset(data + b->start, 0, + main_module->catalog_size(asset) - b->start); + return 0; + } + memcpy(palette + n++ * 4, bgra, 4); + } + set_index(b, rows, x, y, i); + } else if (is_565(b)) { + uint32_t w = rgb565_pack(rgba); + uint8_t *p = rows + y * b->stride + x * 2; + p[0] = (uint8_t)w, p[1] = (uint8_t)(w >> 8); + } else { + uint8_t *p = rows + y * b->stride + x * 4; + p[0] = rgba[2], p[1] = rgba[1], p[2] = rgba[0], p[3] = rgba[3]; + } + } + if (b->colors) + memset(palette + n * 4, 0, (b->colors - n) * 4); + return 1; +} + +/* A coverage level of `full` with the solid floor applied: full from the + * floor up, the floor scaled to the level range. */ +static unsigned solid_level(unsigned level, unsigned full) +{ + return level * FULL >= RVT_SOLID_FLOOR * full ? full : level; +} + +/* One BGRA colour's alpha as tint coverage: as it is, scaled by how dark the + * colour is when the tint reads coverage from darkness, or made full from the + * floor up when it is solid. */ +static void coverage_of(uint8_t *bgra, int darkness, int solid) +{ + if (darkness) + bgra[3] = (uint8_t)div255((unsigned)bgra[3] * (unsigned)(255 - luma(bgra))); + if (solid) + bgra[3] = (uint8_t)solid_level(bgra[3], FULL); +} + +static void solid_mask(const struct layout *b, uint8_t *row) +{ + for (uint32_t y = 0; y < b->height; y++, row += b->stride) + for (uint32_t x = 0; x < b->width; x++) { + if (b->depth == 8) { + row[x] = (uint8_t)solid_level(row[x], FULL); + } else { + unsigned shift = x % 2 ? 0 : 4; + unsigned level = solid_level((row[x / 2] >> shift) & 15, 15); + row[x / 2] = (uint8_t)((row[x / 2] & ~(15u << shift)) | level << shift); + } + } +} + +int derive_coverage(uint32_t asset, const struct layout *b, int darkness, int solid) +{ + uint8_t *data = main_module->catalog_data(asset); + if (is_565(b) || (b->mask && (darkness || !solid))) + return 0; + if (b->mask) { + solid_mask(b, data + b->pixels); + return 1; + } + if (b->colors) { + for (uint32_t i = 0; i < b->colors; i++) + coverage_of(data + b->start + i * 4, darkness, solid); + return 1; + } + uint8_t *row = data + b->pixels; + for (uint32_t y = 0; y < b->height; y++, row += b->stride) + for (uint32_t x = 0; x < b->width; x++) + coverage_of(row + x * 4, darkness, solid); + return 1; +} diff --git a/extensions/appearance/derive.h b/extensions/appearance/derive.h new file mode 100644 index 0000000..3ff4ddd --- /dev/null +++ b/extensions/appearance/derive.h @@ -0,0 +1,35 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* Derived art: a bitmap computed in place from the stock bytes it holds, + * which pack_apply has made sure of first. Every function takes the bitmap's + * layout from catalog_layout and returns 0 when the record does not fit the + * bitmap, before writing anything. */ + +#ifndef DERIVE_H +#define DERIVE_H +#include "catalog.h" +#include + +/* `table` holds `count` pairs {from RGBA, to RGBA} ascending by `from` as a + * little-endian word; matching palette entries, ARGB pixels or RGB565 words + * take their `to`. */ +int derive_recolor(uint32_t asset, const struct layout *b, const uint8_t *table, + uint32_t count); +/* RGB inverted, alpha kept; not for masks. */ +int derive_invert(uint32_t asset, const struct layout *b); +/* The relight rule of rvt.h over a paletted bitmap; `scratch` is + * RVT_SCRATCH_BYTES. */ +int derive_relight(uint32_t asset, const struct layout *b, const int32_t *rule, + uint8_t *scratch); +/* The source's pixels as it holds them now: a byte copy for an equal layout, + * else re-encoded, for which the bitmap is at most RVT_SCRATCH_PIXELS; the + * same size, neither a mask, and a paletted bitmap needs room for the + * source's colours. */ +int derive_alias(uint32_t asset, const struct layout *b, uint32_t source); +/* A tinted bitmap without a record: its coverage as the tint paints it. On a + * paletted or ARGB bitmap the alpha, as it is or, with `darkness`, scaled to + * alpha x (255 - luma) / 255; with `solid` every level from RVT_SOLID_FLOOR + * up becomes full, on a mask's levels too. A mask takes `solid` only. */ +int derive_coverage(uint32_t asset, const struct layout *b, int darkness, int solid); + +#endif diff --git a/extensions/appearance/ext.h b/extensions/appearance/ext.h new file mode 100644 index 0000000..df83be1 --- /dev/null +++ b/extensions/appearance/ext.h @@ -0,0 +1,33 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#ifndef EXT_H +#define EXT_H +#include "rv_api.h" +#include + +/* The core's table and this extension's handle, set by each module's entry. */ +extern const struct rv_api *api; +extern rv_extension_handle self; + +/* The settings. KEY_AVAILABLE shows the Appearance row: on from load until a + * failed restore turns theming off for the session. */ +enum { + KEY_THEME = 1, /* string: the theme id, empty for Classic */ + KEY_DARK, /* choice: Auto, On, Off */ + KEY_ACCENT, /* choice */ + KEY_MENU_COVERS, /* choice: Theme, On, Off */ + KEY_AVAILABLE, /* bool without a row */ + KEY_NOW_PLAYING_COVER, /* choice: Theme, Tilted, Flat */ +}; + +/* The manual module that streams a switch, by its index in the manifest. */ +#define SWITCH_MODULE 1 + +/* Exactly `bytes` of `file` into `out`. */ +static inline int read_exact(struct rv_file *file, void *out, uint32_t bytes) +{ + uint32_t got = 0; + return api->file_read(self, file, out, bytes, &got) == RV_OK && got == bytes; +} + +#endif diff --git a/extensions/appearance/flat_cover.c b/extensions/appearance/flat_cover.c new file mode 100644 index 0000000..bb2f187 --- /dev/null +++ b/extensions/appearance/flat_cover.c @@ -0,0 +1,81 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* Now Playing draws its cover with GLES into a 320 by 240 RGB565 buffer: the + * tilted, reflected artwork, then smoothed lines along its edges. A flat look + * copies the artwork's pixels into the buffer instead, face on and unscaled + * where the stock cover starts, and skips the edge lines. The look asks for + * it with a flag; the Now Playing Cover setting can say otherwise. */ + +#include "flat_cover.h" +#include "ext.h" +#include "osos-2.0.5.h" +#include "rvt.h" +#include "style.h" +#include + +enum { + TARGET_WIDTH = 320, + ART_SIZE = 128, + ART_STRIDE = ART_SIZE * 2, + FLAT_X = 18, + FLAT_Y = 38 +}; + +const char *const now_playing_cover_labels[3] = {"Theme", "Tilted", "Flat"}; +static int cover_choice; /* the setting */ +static void * + drawing_view; /* the album art view inside its draw, where the renderer is called */ + +void flat_cover_set(int value) +{ + cover_choice = value; +} + +int flat_cover_flat(void) +{ + if (cover_choice == NP_COVER_THEME) + return style_flags() & RVT_FLAG_FLAT_NOW_PLAYING; + return cover_choice == NP_COVER_FLAT; +} + +uint32_t flat_cover_view_draw(uint32_t view, uint32_t argument, uint32_t clip, + const void *next) +{ + drawing_view = (void *)view; + uint32_t result = api->hook_next(next, view, argument, clip, 0, 0, 0); + drawing_view = NULL; + return result; +} + +/* The stock cover is a 128 by 128 RGB565 bitmap with packed rows; any other + * image keeps the stock drawing. */ +static int copyable(const uint8_t *image) +{ + const int32_t *bounds = (const int32_t *)(image + Bitmap_bounds); + return RV_FIELD(image, Bitmap_format, uint16_t) == BMapFormat_RGB565 && + RV_FIELD(image, Bitmap_stride, uint32_t) == ART_STRIDE && + bounds[2] - bounds[0] == ART_SIZE && bounds[3] - bounds[1] == ART_SIZE; +} + +uint32_t flat_cover_renderer_draw(uint32_t renderer, const void *next) +{ + if (!flat_cover_flat() || !drawing_view) + return api->hook_next(next, renderer, 0, 0, 0, 0, 0); + const uint8_t *image = GLAlbumArtView_GetImage(drawing_view); + void *buffer = NULL; + if (image) + GameGraphics_GetCurrentPixelBuffer(&buffer); + if (!image || !buffer || !copyable(image)) + return api->hook_next(next, renderer, 0, 0, 0, 0, 0); + const uint16_t *pixels = RV_FIELD(image, Bitmap_pixels, const uint16_t *); + uint16_t *target = (uint16_t *)buffer + FLAT_Y * TARGET_WIDTH + FLAT_X; + for (int row = 0; row < ART_SIZE; row++, target += TARGET_WIDTH) + for (int column = 0; column < ART_SIZE; column++) + target[column] = *pixels++; + return 0; +} + +uint32_t flat_cover_edge_lines(uint32_t buffer, const void *next) +{ + return flat_cover_flat() ? 0 : api->hook_next(next, buffer, 0, 0, 0, 0, 0); +} diff --git a/extensions/appearance/flat_cover.h b/extensions/appearance/flat_cover.h new file mode 100644 index 0000000..c91364e --- /dev/null +++ b/extensions/appearance/flat_cover.h @@ -0,0 +1,19 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#ifndef FLAT_COVER_H +#define FLAT_COVER_H +#include + +/* The Now Playing cover drawn face on. The setting is Theme (what the look + * says; stock tilts it), Tilted or Flat. */ +enum { NP_COVER_THEME, NP_COVER_TILTED, NP_COVER_FLAT }; + +extern const char *const now_playing_cover_labels[3]; +void flat_cover_set(int choice); +int flat_cover_flat(void); +uint32_t flat_cover_view_draw(uint32_t view, uint32_t argument, uint32_t clip, + const void *next); +uint32_t flat_cover_renderer_draw(uint32_t renderer, const void *next); +uint32_t flat_cover_edge_lines(uint32_t buffer, const void *next); + +#endif diff --git a/extensions/appearance/latch.c b/extensions/appearance/latch.c new file mode 100644 index 0000000..b136354 --- /dev/null +++ b/extensions/appearance/latch.c @@ -0,0 +1,53 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "latch.h" +#include "ext.h" +#include "rv_sites.h" +#include "rv_ui.h" + +static int loading, + latched; /* a switch runs; presses are held off and the watch is bound */ + +static uint32_t process_message(uint32_t wait, uint32_t quit, const void *next); +static const struct rv_hook watch = + RV_HOOK_FILTER(RV_SITE_UI_ProcessMessage_call, process_message); + +/* (wait, quit): one turn of the message loop; the result says a message was + * handled. The first idle turn after the switch opens the latch and ends the + * watch: a handler may unbind itself once hook_next has returned. */ +static uint32_t process_message(uint32_t wait, uint32_t quit, const void *next) +{ + uint32_t handled = api->hook_next(next, wait, quit, 0, 0, 0, 0); + if (!handled && !loading) { + latched = 0; + api->hook_unbind(self, &watch); + } + return handled; +} + +int latch_begin(void) +{ + if (latched) + return 0; + /* Without memory for the watch the switch runs unlatched. */ + latched = api->hook_bind(self, &watch) == RV_OK; + loading = 1; + return 1; +} + +void latch_finish(void) +{ + loading = 0; +} + +int latch_held(void) +{ + return latched; +} + +void latch_unload(void) +{ + if (latched) + api->hook_unbind(self, &watch); + loading = latched = 0; +} diff --git a/extensions/appearance/latch.h b/extensions/appearance/latch.h new file mode 100644 index 0000000..5ec0f7f --- /dev/null +++ b/extensions/appearance/latch.h @@ -0,0 +1,17 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#ifndef LATCH_H +#define LATCH_H + +/* A switch blocks the UI task while it streams, and the presses that queue + * meanwhile must not undo it: the first action latches and watches the + * message loop; the latch opens and the watch ends once the loop reports an + * empty queue after the switch is done. Nothing is bound while idle. */ +int latch_begin(void); +void latch_finish(void); +/* A switch's latch is still closed: another switch would be refused. */ +int latch_held(void); +/* Ends the watch, before the extension unloads. */ +void latch_unload(void); + +#endif diff --git a/extensions/appearance/listing.toml b/extensions/appearance/listing.toml new file mode 100644 index 0000000..804e147 --- /dev/null +++ b/extensions/appearance/listing.toml @@ -0,0 +1,9 @@ +details = "Settings > Appearance, after Brightness, holds Theme, Accent, Dark Mode (Auto, On or Off), Menu Covers and Now Playing Cover. Classic's dark look is derived from the stock artwork on the iPod; other themes are .rvt files in /Reprise/Themes, built with the compiler in the extensions repository. The first load imports the core's former Dark Mode switch." + +[[screenshots]] +file = "screenshots/appearance.png" +alt = "Settings > Appearance with the Theme, Accent, Dark Mode, Menu Covers and Now Playing Cover rows." + +[[screenshots]] +file = "screenshots/dark-mode.png" +alt = "The Settings menu in Classic dark: light text on a dark background with the blue accent." diff --git a/extensions/appearance/look.c b/extensions/appearance/look.c new file mode 100644 index 0000000..2536aa1 --- /dev/null +++ b/extensions/appearance/look.c @@ -0,0 +1,285 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "look.h" +#include "ext.h" +#include "osos-2.0.5.h" +#include "assets.h" +#include "dark_mode.h" +#include "latch.h" +#include "render.h" +#include "rv_libc.h" +#include "selection_bar.h" +#include "services.h" +#include "style.h" +#include "theme.h" +#include + +struct look_state look_state; +static int switcher_loaded; /* the switch module is held until finish releases it */ +static int busy; /* a switch is writing settings */ +static int theming_off; /* a restore failed: no theming until the next boot */ +static const char *problem; /* what the last switch could not do */ +static enum look_pane problem_at; /* the pane that shows it */ +static int + standing_in; /* Classic is on screen for a stored theme whose file is missing */ + +/* The canvas roles: the look's, with the secondary shades mixed from text + * toward the background as the stock greys are. */ +static rv_color canvas_roles[RV_COLOR_ROLE_COUNT]; + +const struct look *look_active(void) +{ + return &look_state.active; +} + +/* Whether the look has the other appearance to switch to. */ +static int look_dark_available(void) +{ + return !look_state.active.id[0] || look_state.active.appearances == + (RVT_APPEARANCE_LIGHT | RVT_APPEARANCE_DARK); +} + +const char *look_appearance_note(void) +{ + if (look_dark_available()) + return NULL; + return look_state.active.appearances == RVT_APPEARANCE_DARK + ? "Theme only supports dark mode" + : "Theme only supports light mode"; +} + +const char *look_problem(enum look_pane pane) +{ + return problem && problem_at == pane ? problem : NULL; +} + +int look_busy(void) +{ + return busy; +} + +int look_theming_off(void) +{ + return theming_off; +} + +void look_volume_changed(void) +{ + const struct look *active = &look_state.active; + look_state.stock_checked = 0; + if (active->id[0] && !theme_file_matches(active->id, active->header_crc)) { + assets_drop(); + assets_bind(); + } +} + +#define OPAQUE 0xff000000u + +static rv_color argb(const uint8_t *color) +{ + return OPAQUE | (uint32_t)color[0] << 16 | (uint32_t)color[1] << 8 | color[2]; +} + +static void apply_roles(void) +{ + uint8_t mixed[4], bar[3][4]; + const uint8_t *text = style_color(RVT_ROLE_TEXT), + *background = style_color(RVT_ROLE_BACKGROUND); + if (!style_not_stock()) { + api->ui_set_colors(self, NULL); + return; + } + canvas_roles[RV_COLOR_BACKGROUND] = argb(background); + canvas_roles[RV_COLOR_TEXT] = argb(text); + canvas_roles[RV_COLOR_HIGHLIGHT] = argb(style_color(RVT_ROLE_SELECTION)); + canvas_roles[RV_COLOR_HIGHLIGHT_TEXT] = argb(style_color(RVT_ROLE_ON_ACCENT)); + color_mix(mixed, text, background, 107); + canvas_roles[RV_COLOR_DIM] = argb(mixed); + color_mix(mixed, text, background, 66); + canvas_roles[RV_COLOR_PARAGRAPH] = argb(mixed); + canvas_roles[RV_COLOR_ACCENT_TEXT] = argb(style_color(RVT_ROLE_ACCENT_TEXT)); + /* The bar the lists get: the look's stops, or the stock ones when the + * stock bar stays. The RAM renderer draws no bottom line. */ + if (style_selection_bar(bar)) { + canvas_roles[RV_COLOR_BAR_TOP_LINE] = argb(bar[2]); + canvas_roles[RV_COLOR_BAR_START] = argb(bar[0]); + canvas_roles[RV_COLOR_BAR_END] = canvas_roles[RV_COLOR_BAR_BOTTOM_LINE] = + argb(bar[1]); + } else { + canvas_roles[RV_COLOR_BAR_TOP_LINE] = OPAQUE | SelectionBarColor_TopLine; + canvas_roles[RV_COLOR_BAR_START] = OPAQUE | SelectionBarColor_GradientStart; + canvas_roles[RV_COLOR_BAR_END] = OPAQUE | SelectionBarColor_GradientEnd; + canvas_roles[RV_COLOR_BAR_BOTTOM_LINE] = OPAQUE | SelectionBarColor_BottomLine; + } + api->ui_set_colors(self, canvas_roles); +} + +static uint32_t theme_setting(char id[RVT_ID_BYTES]) +{ + memset(id, 0, RVT_ID_BYTES); + return api->setting_read(self, KEY_THEME, id, RVT_ID_BYTES - 1); +} + +/* Writes the settings to say what is on the screen; `asked` is the appearance + * the action wanted. Auto stays while the screen shows what it asked for. */ +static void settings_write_back(int asked) +{ + char id[RVT_ID_BYTES]; + busy = 1; + theme_setting(id); + if (!standing_in && memcmp(id, look_state.active.id, RVT_ID_BYTES)) + api->setting_write(self, KEY_THEME, RV_SETTING_TYPE_STRING, + look_state.active.id, + (uint32_t)strlen(look_state.active.id)); + if (asked != look_state.active.dark) + api->setting_set_int(self, KEY_DARK, + look_state.active.dark ? DARK_ON : DARK_OFF); + if ((unsigned)api->setting_get_int(self, KEY_ACCENT) != look_state.active.accent) + api->setting_set_int(self, KEY_ACCENT, (int32_t)look_state.active.accent); + busy = 0; +} + +static const struct switch_service *switcher_load(void) +{ + switcher_loaded = api->module_load(self, SWITCH_MODULE) == RV_OK; + return switcher_loaded ? api->module_service(self, SWITCH_MODULE) : NULL; +} + +static void switcher_unload(void) +{ + if (switcher_loaded) + api->module_unload(self, SWITCH_MODULE); + switcher_loaded = 0; +} + +/* After a switch or an accent change, `accent` saying which: the settings, + * the canvas colours, the draw hooks, the cached drawings and the screens + * follow what is there; the switch module is let go. */ +static void finish(enum switch_result result, int asked, int accent, + enum look_pane pane) +{ + if (result != SWITCH_OK && !problem) + problem = result == SWITCH_RESTORE_FAILED ? "Could not restore artwork" + : accent ? "Could not change accent" + : result == SWITCH_RECOVERED ? "Could not apply theme" + : "Could not load theme"; + if (problem) + problem_at = pane; + if (result == SWITCH_RESTORE_FAILED) { + theming_off = 1; + busy = 1; + api->setting_set_int(self, KEY_AVAILABLE, 0); + busy = 0; + } + switcher_unload(); + settings_write_back(asked); + apply_roles(); + /* Binding again after an accent change makes the core decode the + * pictures on screen anew, so tinted extension bitmaps take the colour. */ + if (!assets_bind() && !accent && !problem) { + problem = "Artwork held by another extension"; + problem_at = PANE_THEME; + } + if (!render_bind(style_not_stock()) && !problem) { + problem = "Not enough memory"; + problem_at = pane; + } + selection_bar_apply(); + api->ui_refresh(self, "theme"); + api->ui_redraw(self); + latch_finish(); +} + +void look_switch(const char *id, int dark, unsigned accent, enum look_pane pane) +{ + struct look look; + struct pack_place pack = {0, 0}; + struct rv_file *file = NULL; + const struct switch_service *switcher; + enum switch_result result = SWITCH_LOAD_FAILED; + enum look_pane at = pane; + int asked = dark; + memset(&look, 0, sizeof look); + if (!latch_begin()) { + /* Presses queued behind a switch change nothing; the settings follow the screen. */ + settings_write_back(dark_mode_wanted()); + return; + } + problem = NULL; + standing_in = 0; + if (id[0]) { + enum theme_result opened = theme_open(id, dark, &file, &look, &pack); + if (opened == THEME_UNAVAILABLE) { + /* Classic in the same appearance and accent, the stored theme kept. */ + problem = "Theme unavailable"; + standing_in = 1; + id = ""; + } else { + if (opened == THEME_NOT_IN_APPEARANCE && + !memcmp(look.id, look_state.active.id, RVT_ID_BYTES) && + look.dark == look_state.active.dark && + accent == look_state.active.accent) { + /* The theme's one appearance is on the screen already: only + * the settings have to say so. */ + api->file_close(self, file); + finish(SWITCH_OK, asked, 0, pane); + return; + } + dark = look.dark; + } + } + look.dark = dark; + look.accent = accent; + if (!id[0] && dark && + (!look_file_open(&look, &file) || !look_pack_place(file, &look, &pack))) { + problem = "Could not load dark artwork"; + at = PANE_DARK; + } else if (!(switcher = switcher_load())) { + problem = "Not enough memory"; + } else { + result = switcher->apply(file, &look, &pack); + } + if (file) + api->file_close(self, file); + finish(result, asked, 0, at); +} + +void look_select(const char *id) +{ + look_switch(id, dark_mode_wanted(), + (unsigned)api->setting_get_int(self, KEY_ACCENT), PANE_THEME); +} + +void look_accent(unsigned accent) +{ + const struct switch_service *switcher; + if (accent == look_state.active.accent) + return; + int asked = dark_mode_wanted(); + if (!latch_begin()) { + settings_write_back(asked); + return; + } + problem = NULL; + if (!(switcher = switcher_load())) { + problem = "Not enough memory"; + finish(SWITCH_LOAD_FAILED, asked, 1, PANE_ACCENT); + return; + } + finish(switcher->accent(accent), asked, 1, PANE_ACCENT); +} + +void look_unload(void) +{ + const struct switch_service *switcher = switcher_load(); + if (switcher) + switcher->restore_all(); + switcher_unload(); + assets_release(); + assets_drop(); + latch_unload(); + render_bind(0); + selection_bar_restore(); + api->ui_set_colors(self, NULL); + api->ui_redraw(self); +} diff --git a/extensions/appearance/look.h b/extensions/appearance/look.h new file mode 100644 index 0000000..68bfae2 --- /dev/null +++ b/extensions/appearance/look.h @@ -0,0 +1,79 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* A look is what the screen shows: Classic or a theme, in the light or dark + * appearance, with an accent. Putting one on the screen loads the switch + * module, streams the artwork, applies the colours and writes the settings + * back to say what is there. */ + +#ifndef LOOK_H +#define LOOK_H +#include "catalog.h" +#include "rv_api.h" +#include + +struct look { + char id[RVT_ID_BYTES]; /* empty for Classic */ + char name[RVT_NAME_BYTES]; + uint32_t appearances; /* RVT_APPEARANCE_* bits the theme file has */ + int dark; + unsigned accent; + uint32_t header_crc; /* the header checksum word of the look's file */ +}; + +/* Where a look's pack is in its file: the pack header's offset and the + * pack's size, header included. */ +struct pack_place { + uint32_t offset, bytes; +}; + +enum switch_result { + SWITCH_OK, + SWITCH_LOAD_FAILED, /* the pack or the firmware file is unusable; nothing changed */ + SWITCH_RECOVERED, /* a write failed; the stock light look is back */ + SWITCH_RESTORE_FAILED /* and some bitmaps could not be restored: theming is off */ +}; + +/* What outlives a switch: the look on the screen, the bitmaps that differ + * from stock (the pack's replacements and the tinted accent art), which of + * those are the accent art, and whether the firmware file has been checked + * against the resident bank this session. */ +struct look_state { + struct look active; + uint32_t assets[BITMAP_WORDS]; + uint32_t accented[BITMAP_WORDS]; + int stock_checked; +}; + +extern struct look_state look_state; +const struct look *look_active(void); +/* For the Dark Mode pane of a theme with one appearance: which it has; NULL + * when both are there. */ +const char *look_appearance_note(void); + +/* The pane an action came from, which is where its failure is shown. */ +enum look_pane { PANE_THEME, PANE_DARK, PANE_ACCENT }; + +/* What the last switch could not do, or NULL; shown under `pane` only. */ +const char *look_problem(enum look_pane pane); + +/* Theme `id` ("" for Classic) in the current appearance and accent, from the + * picker. */ +void look_select(const char *id); +/* Theme `id`, or Classic in the `dark` or light appearance, with `accent`. + * A theme whose file is missing shows Classic and says so under Theme; the + * stored id stays, so the theme returns when its file does. */ +void look_switch(const char *id, int dark, unsigned accent, enum look_pane pane); +/* Another accent on the current look. */ +void look_accent(unsigned accent); +/* A switch is writing settings; their change callbacks are its own. */ +int look_busy(void); +/* A restore failed this session: theming stays off until the next boot. */ +int look_theming_off(void); +/* Disk mode may have replaced the firmware file and the theme file: the first + * is checked again next switch; the second is checked now, and when it is + * another file or gone, the index of its bitmaps for extensions goes. */ +void look_volume_changed(void); +/* Every bitmap back to stock and the stock colours, before the extension unloads. */ +void look_unload(void); + +#endif diff --git a/extensions/appearance/lz.c b/extensions/appearance/lz.c new file mode 100644 index 0000000..47c5ba2 --- /dev/null +++ b/extensions/appearance/lz.c @@ -0,0 +1,77 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "lz.h" +#include "crc.h" +#include "ext.h" +#include "rvt.h" + +struct lz_input { + struct rv_file *file; + uint32_t left; /* stream bytes still in the file */ + uint32_t have; /* bytes left in `chunk` */ + const uint8_t *next; /* the next of them */ + uint32_t crc; + uint8_t chunk[256]; +}; + +/* The next stream byte, -1 at the end or on a short read. */ +static int next_byte(struct lz_input *in) +{ + if (!in->have) { + uint32_t n = in->left < sizeof in->chunk ? in->left : sizeof in->chunk, got = 0; + if (!n || api->file_read(self, in->file, in->chunk, n, &got) != RV_OK || + got != n) + return -1; + in->crc = crc32_update(in->crc, in->chunk, n); + in->next = in->chunk; + in->have = n; + in->left -= n; + } + in->have--; + return *in->next++; +} + +static int decode(struct lz_input *in, uint8_t *out, uint32_t bytes) +{ + uint32_t done = 0; + while (done < bytes) { + int flags = next_byte(in); + if (flags < 0) + return 0; + for (uint32_t bit = 0; bit < 8 && done < bytes; bit++) { + int high = next_byte(in); + if (high < 0) + return 0; + if (!(flags >> bit & 1)) { + out[done++] = (uint8_t)high; + continue; + } + int low = next_byte(in); + uint32_t length = (uint32_t)(high >> 4) + RVT_LZ_MIN_MATCH; + uint32_t distance = + ((uint32_t)(high & 15) << 8 | (uint32_t)(low & 255)) + 1; + for (int more = high >> 4 == 15 ? 255 : 0; more == 255; + length += (uint32_t)more) + if ((more = next_byte(in)) < 0) + return 0; + if (low < 0 || distance > done || length > bytes - done) + return 0; + for (uint32_t end = done + length; done < end; done++) + out[done] = out[done - distance]; + } + } + return !in->have && !in->left; +} + +int lz_decode(struct rv_file *file, uint32_t stream_bytes, uint8_t *out, uint32_t bytes, + uint32_t *crc) +{ + struct lz_input in; + in.file = file; + in.left = stream_bytes; + in.have = 0; + in.crc = *crc; + int whole = decode(&in, out, bytes); + *crc = in.crc; + return whole; +} diff --git a/extensions/appearance/lz.h b/extensions/appearance/lz.h new file mode 100644 index 0000000..2ce1bb5 --- /dev/null +++ b/extensions/appearance/lz.h @@ -0,0 +1,20 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The RVT_LZ stream of a pixels record or an extension bitmap, read from the + * file in stack-sized pieces and decoded straight into its destination. In + * the main module, so the asset provider has it while the switch module is + * unloaded; the switch module calls it through main_service. */ + +#ifndef LZ_H +#define LZ_H +#include "rv_api.h" +#include + +/* Decodes the stream of `stream_bytes` at the file's position into exactly + * `bytes` of `out`, continuing *crc over every stream byte read: 0 when the + * stream ends early, a match reaches before the output, the output would + * overrun, or the stream does not end where the output is full. */ +int lz_decode(struct rv_file *file, uint32_t stream_bytes, uint8_t *out, uint32_t bytes, + uint32_t *crc); + +#endif diff --git a/extensions/appearance/main.c b/extensions/appearance/main.c new file mode 100644 index 0000000..893b785 --- /dev/null +++ b/extensions/appearance/main.c @@ -0,0 +1,309 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* Appearance: a Settings row after Brightness opening a menu of Theme, + * Accent, Dark Mode, Menu Covers and Now Playing Cover, whose rows other + * extensions anchor theirs on. A look is a theme file's pack or the Classic + * dark art from the `classic` asset streamed into the resident bitmaps, plus + * the colour roles the draw hooks map the stock screens to; the core's + * canvases follow through ui_set_colors. The settings hold the theme id, Dark + * Mode and the accent; whatever cannot be put on the screen is written back + * as what is. While Dark Mode is on Auto, a minute timer reads the schedule + * and it follows. + * + * This module is always loaded: the bitmap catalog, colour roles, draw hooks + * (bound only while the look is not stock light; the cover and menu cover + * hooks always), the index of the look's extension bitmaps and the provider + * that reads them when the core decodes one, the Theme list and the settings. + * Reading a theme file, deriving art and restoring stock bitmaps are in the + * switch module. */ + +#include "../shared/legacy.h" +#include "catalog.h" +#include "crc.h" +#include "dark_mode.h" +#include "ext.h" +#include "assets.h" +#include "flat_cover.h" +#include "latch.h" +#include "look.h" +#include "lz.h" +#include "menu_covers.h" +#include "rv_api.h" +#include "rv_libc.h" +#include "rv_menus.h" +#include "rv_sites.h" +#include "rv_ui.h" +#include "schedule.h" +#include "services.h" +#include "style.h" +#include "theme_picker.h" +#include "tint.h" +#include + +const struct rv_api *api; +rv_extension_handle self; + +static const struct rv_setting settings[] = { + RV_SETTING_CHOICE(KEY_DARK, "Dark Mode", DARK_OFF, dark_mode_labels), + RV_SETTING_CHOICE(KEY_ACCENT, "Accent", ACCENT_DEFAULT, accent_labels), + RV_SETTING_CHOICE(KEY_MENU_COVERS, "Menu Covers", COVERS_THEME, menu_covers_labels), + RV_SETTING_CHOICE(KEY_NOW_PLAYING_COVER, "Now Playing Cover", NP_COVER_THEME, + now_playing_cover_labels), + RV_SETTING_BOOL(KEY_AVAILABLE, "Appearance", 1), +}; + +static struct rv_timer *timer; /* the minute tick while Dark Mode is on Auto */ +static int zone_known; + +/* In Auto, the appearance the schedule asks for; a switch in progress, or + * one whose latch is still closed, keeps the setting and waits a minute. */ +static void dark_follow(const struct schedule *s) +{ + char id[RVT_ID_BYTES]; + int night = schedule_night(s); + if (!dark_mode_auto() || look_theming_off() || look_busy() || latch_held() || + night == look_active()->dark) + return; + memset(id, 0, sizeof id); + api->setting_read(self, KEY_THEME, id, sizeof id - 1); + look_switch(id, night, (unsigned)api->setting_get_int(self, KEY_ACCENT), PANE_DARK); +} + +static void tick(void *arg) +{ + (void)arg; + struct schedule s; + schedule_read(&s); + dark_follow(&s); + if (zone_known != (s.state != SCHEDULE_NO_ZONE)) { + zone_known = !zone_known; + api->ui_pane_refresh(self); + } +} + +/* The minute timer while Dark Mode is on Auto. At load the extension runs inside + * Apple's preferences load, before the browser holds the preferences object + * that names the time zone: a read that finds no zone is tried again from the + * event loop a second later, so the first screen already follows Auto. */ +static void watch(int on) +{ + struct schedule s; + if (on && !timer) { + timer = api->timer_start(self, 60 * 1000, 1, tick, NULL); + schedule_read(&s); + zone_known = s.state != SCHEDULE_NO_ZONE; + if (!zone_known) + api->timer_start(self, 1000, 0, tick, NULL); + } + if (!on) + rv_timer_cancel(api, self, &timer); +} + +/* The stored theme in appearance `dark` with `accent` is what the screen shows. */ +static int on_screen(const char *id, int dark, unsigned accent) +{ + const struct look *active = look_active(); + return !memcmp(id, active->id, RVT_ID_BYTES) && dark == active->dark && + accent == active->accent; +} + +/* The core's former Dark Mode switch, store record DARK = DRK1, comes in once on + * the first load as Dark Mode On; the write it makes is not a change of its own. */ +static int first_load = 1, importing; + +static void setting_changed(uint16_t key) +{ + char id[RVT_ID_BYTES]; + if (importing) + return; + if (key == RV_SETTING_KEY_ALL) { + importing = 1; + migrate_switch(api, self, first_load, KEY_DARK, 0x4b524144, 0x314b5244, DARK_ON, + DARK_OFF, RV_SETTING_TYPE_INT); + importing = 0; + first_load = 0; + } + if (key == RV_SETTING_KEY_ALL || key == KEY_DARK) + dark_mode_set(api->setting_get_int(self, KEY_DARK)); + watch(dark_mode_auto()); + if (look_busy()) + return; + int dark = dark_mode_wanted(); + unsigned accent = (unsigned)api->setting_get_int(self, KEY_ACCENT); + switch (key) { + case RV_SETTING_KEY_ALL: + /* At load, and after Reset All Settings emptied the store. */ + if (!api->setting_get_int(self, KEY_AVAILABLE) && !look_theming_off()) + api->setting_set_int(self, KEY_AVAILABLE, 1); + menu_covers_set(api->setting_get_int(self, KEY_MENU_COVERS)); + flat_cover_set(api->setting_get_int(self, KEY_NOW_PLAYING_COVER)); + memset(id, 0, sizeof id); + api->setting_read(self, KEY_THEME, id, sizeof id - 1); + if (!on_screen(id, dark, accent)) + look_switch(id, dark, accent, PANE_THEME); + break; + case KEY_DARK: + /* The stored theme, not the active one: while Classic stands in for a + * theme whose file was missing, the ids differ and the theme is tried again. */ + memset(id, 0, sizeof id); + api->setting_read(self, KEY_THEME, id, sizeof id - 1); + if (!on_screen(id, dark, accent)) + look_switch(id, dark, accent, PANE_DARK); + break; + case KEY_ACCENT: + look_accent(accent); + break; + case KEY_MENU_COVERS: + menu_covers_set(api->setting_get_int(self, KEY_MENU_COVERS)); + break; + case KEY_NOW_PLAYING_COVER: + flat_cover_set(api->setting_get_int(self, KEY_NOW_PLAYING_COVER)); + break; + default: + break; + } +} + +static const char *theme_caption(const struct rv_context *ctx) +{ + (void)ctx; + const struct look *active = look_active(); + const char *problem = look_problem(PANE_THEME); + return problem ? problem : active->id[0] ? active->name : "Classic"; +} + +static const char *dark_pane(const struct rv_context *ctx) +{ + (void)ctx; + return dark_mode_caption(); +} + +/* The row says Theme; the pane has room for the full phrase. */ +static const char *accent_caption(const struct rv_context *ctx) +{ + (void)ctx; + const char *problem = look_problem(PANE_ACCENT); + if (problem) + return problem; + return style_accent() == ACCENT_DEFAULT ? "Theme Default" + : accent_labels[style_accent()]; +} + +static const char *covers_caption(const struct rv_context *ctx) +{ + (void)ctx; + return menu_covers_enabled() ? "On" : "Off"; +} + +static const char *cover_caption(const struct rv_context *ctx) +{ + (void)ctx; + return flat_cover_flat() ? "Flat" : "Tilted"; +} + +/* The Appearance menu: each row with its own pane caption and icon, and an id + * other extensions anchor their rows on. */ +static const struct rv_row rows[] = { + RV_ROW_PUSH("Theme", "theme", .id = "theme"), + RV_ROW_SETTING("Accent", KEY_ACCENT, .id = "accent"), + RV_ROW_SETTING("Dark Mode", KEY_DARK, .id = "dark-mode"), + RV_ROW_SETTING("Menu Covers", KEY_MENU_COVERS, .id = "menu-covers"), + RV_ROW_SETTING("Now Playing Cover", KEY_NOW_PLAYING_COVER, + .id = "now-playing-cover"), +}; +static const struct rv_pane panes[] = { + {.caption_text = theme_caption, .bitmap = RV_BITMAP("settings-theme")}, + {.caption_text = accent_caption, .bitmap = RV_BITMAP("settings-accent")}, + {.caption_text = dark_pane, .bitmap = RV_BITMAP("settings-moon")}, + {.caption_text = covers_caption, .bitmap = RV_BITMAP("settings-covers")}, + {.caption_text = cover_caption, .bitmap = RV_BITMAP("settings-cover")}, +}; +/* The choice screens the rows open, declared for their pane icons; the + * screens the core makes from the settings have none. */ +static const struct rv_screen screens[] = { + RV_SCREEN_LIST_PANES("appearance", "Appearance", rows, panes), + THEME_PICKER_SCREEN, + RV_SCREEN_CHOICE("accent", "Accent", KEY_ACCENT, accent_labels, + .bitmap = RV_BITMAP("settings-accent")), + RV_SCREEN_CHOICE("dark-mode", "Dark Mode", KEY_DARK, dark_mode_labels, + .bitmap = RV_BITMAP("settings-moon")), + RV_SCREEN_CHOICE("menu-covers", "Menu Covers", KEY_MENU_COVERS, menu_covers_labels, + .bitmap = RV_BITMAP("settings-covers")), + RV_SCREEN_CHOICE("now-playing-cover", "Now Playing Cover", KEY_NOW_PLAYING_COVER, + now_playing_cover_labels, .bitmap = RV_BITMAP("settings-cover")), +}; + +static const struct rv_menu_entry entries[] = { + RV_MENU_ENTRY(RV_MENU_SETTINGS, RV_SETTINGS_BRIGHTNESS, + RV_ROW_PUSH("Appearance", "appearance"), + .pane = RV_PANE(.caption = "Make It Your Own", + .bitmap = RV_BITMAP("settings-appearance")), + .shown_by = KEY_AVAILABLE), +}; + +/* No arguments: disk mode has ended and the volume, firmware file included, + * is readable again. */ +static uint32_t disk_mode_exit(const void *next) +{ + look_volume_changed(); + return api->hook_next(next, 0, 0, 0, 0, 0, 0); +} + +/* The hooks bound in every look, the Menu Covers and Now Playing Cover hooks + * among them; the draw hooks are bound while a look is on. */ +static const struct rv_hook hooks[] = { + RV_HOOK_FILTER(RV_SITE_MediaArtworkProvider_GetSlotArtwork_entry, + menu_covers_query), + RV_HOOK_FILTER(RV_SITE_GLAlbumArtView_Draw_slot, flat_cover_view_draw), + RV_HOOK_FILTER(RV_SITE_AlbumArt_RendererDraw_call, flat_cover_renderer_draw), + RV_HOOK_FILTER(RV_SITE_AlbumArt_EdgeLines_call, flat_cover_edge_lines), + RV_HOOK_FILTER(RV_SITE_DiskModeExit_PopToMainScreen_call, disk_mode_exit), +}; + +/* The core stops the timer itself as the module unloads. */ +static void unload(void) +{ + timer = NULL; + look_unload(); +} + +static const struct main_service service = { + .state = &look_state, + .crc32_update = crc32_update, + .catalog_count = catalog_count, + .catalog_fingerprint = catalog_fingerprint, + .catalog_data = catalog_data, + .catalog_size = catalog_size, + .catalog_crc = catalog_crc, + .catalog_file_offset = catalog_file_offset, + .catalog_layout = catalog_layout, + .style_set = style_set, + .style_reset = style_reset, + .style_set_dark = style_set_dark, + .style_set_accent = style_set_accent, + .tint_refresh = tint_refresh, + .tint_accent_art = tint_accent_art, + .lz_decode = lz_decode, + .assets_reserve = assets_reserve, + .assets_commit = assets_commit, + .assets_drop = assets_drop, +}; + +static const struct rv_descriptor extension = { + .size = sizeof extension, + RV_HOOKS(hooks), + RV_SETTINGS(settings), + .unload = unload, + .setting_changed = setting_changed, + RV_SCREENS(screens), + RV_ENTRIES(entries), + .service = &service, +}; + +const struct rv_descriptor *rv_module_entry(const struct rv_api *core, + rv_extension_handle handle) +{ + api = core; + self = handle; + return &extension; +} diff --git a/extensions/appearance/manifest.toml b/extensions/appearance/manifest.toml new file mode 100644 index 0000000..01f9d7e --- /dev/null +++ b/extensions/appearance/manifest.toml @@ -0,0 +1,55 @@ +id = "appearance" +name = "Appearance" +description = "Dark Mode, Accent and themes that recolour the screens and replace the artwork." +version = "0.1.0" +author = "RepriseOS and RevolaOS contributors" +license = "GPL-3.0-only" +api = "1.89" +category = "system" +content = "Themes" + +[libraries] +optional = ["reprise"] + +[[module]] +name = "main" +trigger = "always" + +[[module]] +name = "switch" +trigger = "manual" + +[[asset]] +name = "settings-appearance" +file = "assets/settings-appearance.png" +pane = "icon" + +[[asset]] +name = "settings-theme" +file = "assets/settings-theme.png" +pane = "icon" + +[[asset]] +name = "settings-moon" +file = "assets/settings-moon.png" +pane = "icon" + +[[asset]] +name = "settings-accent" +file = "assets/settings-accent.png" +pane = "icon" + +[[asset]] +name = "settings-covers" +file = "assets/settings-covers.png" +pane = "icon" + +[[asset]] +name = "settings-cover" +file = "assets/settings-cover.png" +pane = "icon" + +[[asset]] +name = "classic" +file = "build/classic.rvt" +compress = false diff --git a/extensions/appearance/menu_covers.c b/extensions/appearance/menu_covers.c new file mode 100644 index 0000000..8f6e3b9 --- /dev/null +++ b/extensions/appearance/menu_covers.c @@ -0,0 +1,28 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "menu_covers.h" +#include "ext.h" +#include "rvt.h" +#include "style.h" + +const char *const menu_covers_labels[3] = {"Theme", "On", "Off"}; +static int choice; /* the setting */ + +void menu_covers_set(int value) +{ + choice = value; +} + +int menu_covers_enabled(void) +{ + if (choice == COVERS_THEME) + return !(style_flags() & RVT_FLAG_MENU_COVERS_OFF); + return choice == COVERS_ON; +} + +uint32_t menu_covers_query(uint32_t provider, uint32_t slot, const void *next) +{ + if (slot == 0 && !menu_covers_enabled()) + return 0; + return api->hook_next(next, provider, slot, 0, 0, 0, 0); +} diff --git a/extensions/appearance/menu_covers.h b/extensions/appearance/menu_covers.h new file mode 100644 index 0000000..5d82e16 --- /dev/null +++ b/extensions/appearance/menu_covers.h @@ -0,0 +1,18 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#ifndef MENU_COVERS_H +#define MENU_COVERS_H +#include "rv_api.h" + +/* Menu Covers: whether the Main and Music menus show the highlighted row's + * cover. The setting is Theme (what the look says; stock shows them), On or + * Off. */ +enum { COVERS_THEME, COVERS_ON, COVERS_OFF }; + +extern const char *const menu_covers_labels[3]; +void menu_covers_set(int choice); +int menu_covers_enabled(void); +/* (provider, slot): the artwork lookup the menus make; 0 hides the cover. */ +uint32_t menu_covers_query(uint32_t provider, uint32_t slot, const void *next); + +#endif diff --git a/extensions/appearance/pack.c b/extensions/appearance/pack.c new file mode 100644 index 0000000..9012418 --- /dev/null +++ b/extensions/appearance/pack.c @@ -0,0 +1,356 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "pack.h" +#include "derive.h" +#include "ext.h" +#include "pixel.h" +#include "rv_libc.h" +#include "stock.h" +#include "switch.h" + +static uint32_t checksum(uint32_t sum, const void *data, uint32_t size) +{ + return main_module->crc32_update(sum, data, size); +} + +static const uint8_t *tint_bytes(const struct pack *pack) +{ + return (const uint8_t *)pack->style + RVT_STYLE_TINTS; +} + +/* Opaque colours, known flags, and tint bytes that name a role on a bitmap + * the catalog has; checked before anything is written. */ +static int style_valid(const uint8_t *style, uint32_t catalog_count) +{ + const uint8_t *p = style + RVT_STYLE_COLORS; + for (unsigned i = 0; i < RVT_ROLES; i++) + if (p[i * 4 + 3] != 255) + return 0; + if (le32(style + RVT_STYLE_FLAGS) & + ~(uint32_t)(RVT_FLAG_FLAT_SELECTION | RVT_FLAG_MENU_COVERS_OFF | + RVT_FLAG_FLAT_NOW_PLAYING | RVT_FLAG_FLAT_ICONS)) + return 0; + p = style + RVT_STYLE_PALETTES; + for (unsigned i = 0; i < RVT_ACCENTS * RVT_ACCENT_SLOTS; i++) + if (p[i * 4 + 3] != 255) + return 0; + p = style + RVT_STYLE_TINTS; + for (unsigned i = 0; i < RVT_CATALOG_MAX; i++) { + unsigned coverage = p[i] & (RVT_TINT_DARKNESS | RVT_TINT_SOLID); + unsigned tint = p[i] & ~coverage; + if (coverage == (RVT_TINT_DARKNESS | RVT_TINT_SOLID) || + tint >= RVT_TINT_ROLE + RVT_ROLES || (coverage && tint == RVT_TINT_NONE) || + (p[i] && i >= catalog_count)) + return 0; + } + return 1; +} + +int pack_plain(const struct pack *pack) +{ + const uint8_t *tint = tint_bytes(pack); + if (le32((const uint8_t *)pack->style + RVT_STYLE_FLAGS)) + return 0; + for (unsigned i = 0; i < RVT_CATALOG_MAX; i++) + if (tint[i]) + return 0; + return 1; +} + +int pack_open(struct rv_file *file, uint32_t header_crc, const struct pack_place *place, + struct pack *pack) +{ + uint8_t pack_header[RVT_PACK_HEADER_BYTES]; + uint32_t crc; + memset(pack, 0, sizeof *pack); + if (api->file_seek(self, file, RVT_HEADER_CRC) != RV_OK || + !read_exact(file, &crc, sizeof crc) || crc != header_crc || + api->file_seek(self, file, place->offset) != RV_OK || + !read_exact(file, pack_header, sizeof pack_header)) + return 0; + pack->body = place->offset + RVT_PACK_HEADER_BYTES; + pack->body_bytes = le32(pack_header + RVT_PACK_BODY_BYTES); + pack->count = le32(pack_header + RVT_PACK_RECORDS); + pack->crc = le32(pack_header + RVT_PACK_CRC); + pack->extension_bitmaps = le32(pack_header + RVT_PACK_EXTENSION_BITMAPS); + if (pack->body_bytes != place->bytes - RVT_PACK_HEADER_BYTES || + pack->count > main_module->catalog_count() || + pack->extension_bitmaps > RVT_EXTENSION_BITMAPS_MAX || + !read_exact(file, pack->style, RVT_STYLE_BYTES) || + !style_valid((const uint8_t *)pack->style, main_module->catalog_count())) + return 0; + pack->file = file; + return 1; +} + +/* The payload bytes a kind allows for a bitmap. */ +static int record_valid(uint32_t asset, uint32_t kind, uint32_t size, uint32_t i, + uint32_t previous, struct layout *b) +{ + if ((i && asset <= previous) || !main_module->catalog_layout(asset, b)) + return 0; + switch (kind) { + case RVT_KIND_PIXELS: + return size == main_module->catalog_size(asset) - b->start; + case RVT_KIND_PIXELS_LZ: + return size > 0; + case RVT_KIND_RECOLOR: + return size >= 4 + 8 && (size - 4) % 8 == 0 && + (size - 4) / 8 <= RVT_RECOLOR_MAX; + case RVT_KIND_ALIAS: + return size == 4; + case RVT_KIND_INVERT: + return size == 0; + case RVT_KIND_RELIGHT: + return size == RVT_RELIGHT_BYTES; + } + return 0; +} + +/* Every pixel of a paletted bitmap names a palette entry; `data` starts at + * the palette. */ +static int indices_valid(const struct layout *b, const uint8_t *data) +{ + uint32_t colors = b->colors; + if (!colors || (b->depth == 8 && colors >= 256)) + return 1; + const uint8_t *row = data + b->pixels - b->start; + for (uint32_t y = 0; y < b->height; y++, row += b->stride) + for (uint32_t x = 0; x < b->width; x++) + if ((b->depth == 8 ? row[x] : le16(row + x * 2)) >= colors) + return 0; + return 1; +} + +/* One bit per tinted bitmap. A pixels record clears its bit; a derived record + * on a tinted bitmap is invalid; what remains is tinted stock art. */ +static void tint_pending(const uint8_t *tint, uint32_t *pending) +{ + memset(pending, 0, BITMAP_WORDS * 4); + for (uint32_t i = 0; i < RVT_CATALOG_MAX; i++) + if (tint[i]) + bit_set(pending, i); +} + +/* The bitmap holds its stock bytes: fetched when the active look changed it. */ +static int stock_ready(uint32_t asset, const struct layout *b, const uint32_t *current) +{ + return !bit_test(current, asset) || + stock_fetch(asset, main_module->catalog_data(asset) + b->start); +} + +struct alias { + uint16_t asset, source; +}; + +/* The stored bytes a kind allows for a bitmap of `decoded` bytes: the same, + * or an lz stream, which is at most a flag byte per eight literals longer. + * The decoded size holds at least a header and at most the cap. */ +static int bitmap_size_valid(uint32_t kind, uint32_t stored, uint32_t decoded) +{ + if (!stored || decoded <= RVT_BMAP_HEADER_BYTES || + decoded > RVT_EXTENSION_BITMAP_MAX_BYTES) + return 0; + if (kind == RVT_EXTENSION_BITMAP) + return stored == decoded; + return stored <= decoded + (decoded + 7) / 8; +} + +/* An extension bitmap's tint word: none, or a role without coverage bits. */ +static int tint_word_valid(uint32_t tint) +{ + return tint == RVT_TINT_NONE || + (tint >= RVT_TINT_ROLE && tint < RVT_TINT_ROLE + RVT_ROLES); +} + +/* Bytes the switch leaves in the file, read for the checksum only. */ +static int checksum_skip(struct rv_file *file, uint32_t bytes, uint32_t *sum) +{ + uint8_t chunk[256]; + while (bytes) { + uint32_t n = bytes < sizeof chunk ? bytes : sizeof chunk; + if (!read_exact(file, chunk, n)) + return 0; + *sum = checksum(*sum, chunk, n); + bytes -= n; + } + return 1; +} + +/* The extension bitmaps after the records into the index: each entry is + * checked and its payload's place kept; the payload is read into the checksum + * only and served as stored by the provider, since the core checks a bitmap + * once it has decoded it. */ +static int bitmaps_index(struct pack *pack, uint32_t *consumed, uint32_t *sum) +{ + struct asset_entry *entries = main_module->assets_reserve(pack->extension_bitmaps); + if (pack->extension_bitmaps && !entries) + return 0; + for (uint32_t i = 0; i < pack->extension_bitmaps; i++) { + uint32_t entry[RVT_EXTENSION_BITMAP_BYTES / 4], zero = 0; + if (pack->body_bytes - *consumed < sizeof entry || + !read_exact(pack->file, entry, sizeof entry)) + return 0; + *consumed += sizeof entry; + *sum = checksum(*sum, entry, sizeof entry); + uint32_t owner = entry[0], asset = entry[1], kind = entry[2], size = entry[3]; + uint32_t decoded = entry[4], tint = entry[5], padding = (0u - size) & 3u; + if ((i && !asset_before(entries + i - 1, owner, asset)) || + (kind != RVT_EXTENSION_BITMAP && kind != RVT_EXTENSION_BITMAP_LZ) || + !bitmap_size_valid(kind, size, decoded) || !tint_word_valid(tint) || + size > pack->body_bytes - *consumed || + padding > pack->body_bytes - *consumed - size) + return 0; + entries[i].owner = owner; + entries[i].asset = asset; + entries[i].offset = pack->body + *consumed; + entries[i].bytes = size; + entries[i].decoded = decoded; + entries[i].kind = (uint16_t)kind; + entries[i].tint = (uint8_t)tint; + if (!checksum_skip(pack->file, size, sum) || + (padding && (!read_exact(pack->file, &zero, padding) || zero))) + return 0; + *sum = checksum(*sum, &zero, padding); + *consumed += size + padding; + } + return 1; +} + +int pack_apply(struct pack *pack, uint32_t *written, const uint32_t *current) +{ + struct rv_file *file = pack->file; + uint32_t pending[BITMAP_WORDS], previous = 0; + uint32_t sum = checksum(0xffffffffu, pack->style, RVT_STYLE_BYTES); + uint32_t consumed = RVT_STYLE_BYTES; + struct alias aliases[RVT_ALIASES_MAX]; + uint32_t naliases = 0; + uint8_t *scratch = NULL; + int ok = 0; + tint_pending(tint_bytes(pack), pending); + for (uint32_t i = 0; i < pack->count; i++) { + uint32_t record[3], payload[RVT_RELIGHT_WORDS]; + struct layout b; + if (pack->body_bytes - consumed < sizeof record || + !read_exact(file, record, sizeof record)) + goto done; + consumed += sizeof record; + sum = checksum(sum, record, sizeof record); + uint32_t asset = record[0], kind = record[1], size = record[2]; + uint32_t padding = (0u - size) & 3u; + if (kind >= RVT_KINDS || size > pack->body_bytes - consumed || + padding > pack->body_bytes - consumed - size || + !record_valid(asset, kind, size, i, previous, &b)) + goto done; + previous = asset; + bit_set(written, asset); + uint8_t *data = main_module->catalog_data(asset) + b.start; + uint32_t bytes = main_module->catalog_size(asset) - b.start; + if (kind == RVT_KIND_PIXELS || kind == RVT_KIND_PIXELS_LZ) { + /* A resident bitmap must never index past its palette. */ + int whole; + if (kind == RVT_KIND_PIXELS) { + whole = read_exact(file, data, size); + sum = checksum(sum, data, size); + } else { + whole = main_module->lz_decode(file, size, data, bytes, &sum); + } + if (!whole || !indices_valid(&b, data)) { + memset(data, 0, bytes); + goto done; + } + pending[asset / 32] &= ~(1u << (asset % 32)); + } else { + if (bit_test(pending, asset) || + (!scratch && !(scratch = api->alloc(self, RVT_SCRATCH_BYTES)))) + goto done; + uint8_t *table = (uint8_t *)payload; + uint32_t pairs = 0; + if (kind == RVT_KIND_RECOLOR) { + /* The count, then the pairs into the scratch block, which holds + * RVT_RECOLOR_MAX of them and nothing else. */ + if (!read_exact(file, &pairs, 4) || pairs != (size - 4) / 8) + goto done; + sum = checksum(sum, &pairs, 4); + table = scratch; + size -= 4; + } + if (!read_exact(file, table, size)) + goto done; + sum = checksum(sum, table, size); + if (kind == RVT_KIND_RECOLOR) + size += 4; + if (kind == RVT_KIND_ALIAS) { + uint32_t source = payload[0]; + struct layout s; + if (naliases == RVT_ALIASES_MAX || source == asset || + !main_module->catalog_layout(source, &s) || + tint_bytes(pack)[source] || b.mask || s.mask || + b.width != s.width || b.height != s.height) + goto done; + aliases[naliases].asset = (uint16_t)asset; + aliases[naliases++].source = (uint16_t)source; + } else { + if (!stock_ready(asset, &b, current)) + goto done; + int derived = + kind == RVT_KIND_RECOLOR ? derive_recolor(asset, &b, scratch, pairs) + : kind == RVT_KIND_INVERT + ? derive_invert(asset, &b) + : derive_relight(asset, &b, (const int32_t *)payload, scratch); + if (!derived) + goto done; + } + } + uint32_t zero = 0; + if (padding && (!read_exact(file, &zero, padding) || zero)) + goto done; + sum = checksum(sum, &zero, padding); + consumed += size + padding; + } + if (!bitmaps_index(pack, &consumed, &sum) || consumed != pack->body_bytes || + ~sum != pack->crc) + goto done; + /* Aliases last, so every source is final; a source that is itself listed + * is a chain. A source the pack left alone must be stock, and the target + * starts from stock too, so its row padding is the same whatever the + * previous look left there. */ + for (uint32_t a = 0; a < naliases; a++) { + struct layout b, s; + for (uint32_t c = 0; c < naliases; c++) + if (aliases[c].asset == aliases[a].source) + goto done; + if (!main_module->catalog_layout(aliases[a].asset, &b) || + !main_module->catalog_layout(aliases[a].source, &s)) + goto done; + if (!bit_test(written, aliases[a].source) && + !stock_ready(aliases[a].source, &s, current)) + goto done; + if (!stock_ready(aliases[a].asset, &b, current) || + !derive_alias(aliases[a].asset, &b, aliases[a].source)) + goto done; + } + /* Tinted paletted and ARGB bitmaps without a record are tinted stock art: + * their coverage is prepared here. Masks are coloured while drawing and + * keep their stock levels unless the coverage is solid. */ + for (uint32_t i = 0; i < RVT_CATALOG_MAX; i++) { + struct layout b; + uint8_t tint = tint_bytes(pack)[i]; + if (!bit_test(pending, i)) + continue; + if (!main_module->catalog_layout(i, &b)) + goto done; + if (b.mask && !(tint & RVT_TINT_SOLID)) + continue; + bit_set(written, i); + if (!stock_ready(i, &b, current) || + !derive_coverage(i, &b, (tint & RVT_TINT_DARKNESS) != 0, + (tint & RVT_TINT_SOLID) != 0)) + goto done; + } + ok = 1; +done: + if (scratch) + api->free(self, scratch); + return ok; +} diff --git a/extensions/appearance/pack.h b/extensions/appearance/pack.h new file mode 100644 index 0000000..3ab106d --- /dev/null +++ b/extensions/appearance/pack.h @@ -0,0 +1,44 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* Reading one appearance pack of a theme file (rvt.h), streamed straight into + * the resident bitmaps. The file is an rv_file from content_open or + * asset_open whose header main has checked and placed the pack by. */ + +#ifndef PACK_H +#define PACK_H +#include "catalog.h" +#include "look.h" +#include "rv_api.h" +#include + +/* An open pack positioned at its first record, with its style prefix read; + * `body` is the file offset of its body, `extension_bitmaps` the count of + * the bitmaps for extensions after its records. */ +struct pack { + struct rv_file *file; + uint32_t body, body_bytes, count, crc, extension_bitmaps; + uint32_t style[RVT_STYLE_BYTES / 4]; +}; + +/* Opens the pack at `place`: the header's checksum word must still be + * `header_crc` (the file may have changed since main read it), then the pack + * header and the style prefix, which must be opaque and tint catalog bitmaps + * only. Nothing is written yet, so a failure leaves the look unchanged. */ +int pack_open(struct rv_file *file, uint32_t header_crc, const struct pack_place *place, + struct pack *pack); +/* Whether the pack's style asks for nothing but colours: no tints, no flags. */ +int pack_plain(const struct pack *pack); +/* Streams the records into the resident bitmaps: pixel records are read or + * decoded in place, derived records are computed from the stock bytes + * (fetched from the firmware file first when `current` says the active look + * changed the bitmap), aliases after every other record, and a tinted + * paletted or ARGB bitmap without a record gets its coverage prepared for + * tint_refresh. Each record's layout, payload and padding are checked, then + * the extension bitmaps go into the index main reserves for them (committed + * or dropped by the caller), then the body checksum. Every catalog bitmap it + * wrote is set in `written`, also on failure, when a half-written bitmap + * holds zeros or stock bytes. The caller has stock_open and the bitmaps are + * live, so this runs on the UI task and the caller redraws. */ +int pack_apply(struct pack *pack, uint32_t *written, const uint32_t *current); + +#endif diff --git a/extensions/appearance/pixel.h b/extensions/appearance/pixel.h new file mode 100644 index 0000000..e6f14be --- /dev/null +++ b/extensions/appearance/pixel.h @@ -0,0 +1,65 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* Little-endian words, clamping and RGB565 packing, shared by the file + * reader, the derivations and the draw hooks. */ + +#ifndef PIXEL_H +#define PIXEL_H +#include + +static inline uint32_t le16(const uint8_t *p) +{ + return p[0] | (uint32_t)p[1] << 8; +} + +static inline uint32_t le32(const uint8_t *p) +{ + return le16(p) | le16(p + 2) << 16; +} + +static inline int32_t clamp(int32_t value, int32_t low, int32_t high) +{ + return value < low ? low : value > high ? high : value; +} + +/* value / 255 exactly for value up to 65534, without a division. */ +static inline uint32_t div255(uint32_t value) +{ + return (value + 1 + (value >> 8)) >> 8; +} + +/* x / d for x below 2^24 and 0 < d below 2^16 as one multiply by the + * reciprocal, exact over that range (the divisor's 16 bits plus the + * dividend's 24 fit a 40-bit shift). Division by a constant folds at compile + * time; the relight rule computes its reciprocal once per bitmap. */ +static inline uint64_t reciprocal(uint32_t d) +{ + /* 2^40 / d from 2^32 = 0xffffffff + 1, in 32-bit steps. */ + uint32_t quotient = 0xffffffffu / d, remainder = 0xffffffffu % d + 1; + if (remainder == d) { + quotient++; + remainder = 0; + } + return ((uint64_t)quotient << 8) + (remainder << 8) / d + 1; +} + +static inline uint32_t divide(uint32_t x, uint64_t reciprocal_of_d) +{ + return (uint32_t)((x * reciprocal_of_d) >> 40); +} + +/* RGB565 words from and to RGB bytes. Unpacking widens by shifting, so a + * colour that is exactly 5-6-5 comes back unchanged. */ +static inline uint32_t rgb565_pack(const uint8_t *rgb) +{ + return (uint32_t)(rgb[0] >> 3) << 11 | (uint32_t)(rgb[1] >> 2) << 5 | rgb[2] >> 3; +} + +static inline void rgb565_unpack(uint32_t word, uint8_t rgb[3]) +{ + rgb[0] = (uint8_t)((word >> 11) << 3); + rgb[1] = (uint8_t)((word >> 5 & 63) << 2); + rgb[2] = (uint8_t)((word & 31) << 3); +} + +#endif diff --git a/extensions/appearance/render.c b/extensions/appearance/render.c new file mode 100644 index 0000000..dea34e0 --- /dev/null +++ b/extensions/appearance/render.c @@ -0,0 +1,402 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The stock screens draw in fixed colours, the light look's. Each draw passes + * one of the core's colour sites, where the colour says what is being drawn: + * light greys are surfaces, dark greys text, the stock blues accents, the + * white palette entry highlighted text. The handlers map each to its role and + * let the draw go on. The mapping is in functions of the colour and the + * view's id, which the hooks wrap. + * + * Derives from the core's former payload/dark_mode.c (01c89f6) by lgreitis and + * Alex Ball (alexballvideos-netizen). */ + +#include "render.h" +#include "catalog.h" +#include "ext.h" +#include "osos-2.0.5.h" +#include "pixel.h" +#include "rv_sites.h" +#include "rv_ui.h" +#include "style.h" +#include "tint.h" +#include + +/* Set while a view that keeps its light artwork fills its background, so + * the fill underneath stays stock too. */ +static int stock_fill; + +enum { + SURFACE_LIGHT_MIN = 0xb0, /* greys from here up are surfaces */ + TEXT_DARK_MAX = 0x80, /* greys to here are text */ + TEXT_WHITE_MIN = 0xf0, + TEXT_LIGHT_REFERENCE = + 0x20, /* the light look's text role; native black lies below it */ +}; + +/* Which of a bar view's own label colours a draw passes. */ +enum bar_slot { BAR_OTHER, BAR_LABEL, BAR_SELECTED }; + +/* The stock id of view id `id`: a picture pane copied from an Apple template + * gives its views new ids. */ +static uint32_t stock_id(uint32_t id) +{ + return RV_HAS(api, ui_stock_view) ? api->ui_stock_view(id) : id; +} + +static uint32_t view_id(uint32_t view) +{ + return stock_id(RV_FIELD(view, View_id, uint32_t)); +} + +static int same_rgb(const uint8_t *color, const uint8_t *other) +{ + return color[0] == other[0] && color[1] == other[1] && color[2] == other[2]; +} + +static int grey(const uint8_t *color) +{ + return color[0] == color[1] && color[1] == color[2]; +} + +static const uint8_t *recolor(const uint8_t *color, const uint8_t *target, uint8_t *out) +{ + out[0] = target[0]; + out[1] = target[1]; + out[2] = target[2]; + out[3] = color[3]; + return out; +} + +/* The role offset by the stock shade, so the stock gradations stay. */ +static const uint8_t *shade(const uint8_t *color, const uint8_t *target, int offset, + uint8_t *out) +{ + for (unsigned i = 0; i < 3; i++) + out[i] = (uint8_t)clamp(target[i] + offset, 0, 255); + out[3] = color[3]; + return out; +} + +/* Views whose labels keep their stock colour: they sit on their own art. */ +static int native_text(uint32_t view) +{ + switch (view) { + case RES_Alarms_PickDate_Preivew_NumericDay: + case RES_Settings_DateTime_NumericDay: + case RES_Settings_DateTime_Preivew_NumericDay: + return 1; + case RES_Search_Input_Text: + return !style_from_theme(); + default: + return 0; + } +} + +/* A label's colour in view `view`. White text on the stock blue-grey pane + * and on dark art takes the text role under a custom light background. */ +static const uint8_t *map_text(const uint8_t *color, uint32_t view, uint8_t *mapped) +{ + if (native_text(view)) + return color; + const uint8_t *text = style_color(RVT_ROLE_TEXT); + const uint8_t *field = + view == RES_Search_Input_Text ? tint_field_text_color() : NULL; + const uint8_t *art = tint_contrast_text_color(view); + if (art) + return recolor(color, art, mapped); + if (field && grey(color) && color[0] <= TEXT_DARK_MAX) + return recolor(color, field, mapped); + if (color == Palette_White) + return recolor(color, style_color(RVT_ROLE_ON_ACCENT), mapped); + if (same_rgb(color, style_stock_color(RVT_ROLE_ACCENT_FILL))) + return recolor(color, style_color(RVT_ROLE_ACCENT_FILL), mapped); + if (same_rgb(color, style_stock_color(RVT_ROLE_ACCENT_TEXT))) + return recolor(color, style_color(RVT_ROLE_ACCENT_TEXT), mapped); + if (grey(color) && color[0] <= TEXT_DARK_MAX) + return shade(color, text, + color_dark(text) ? color[0] - TEXT_LIGHT_REFERENCE + : -(color[0] / 2), + mapped); + if (grey(color) && color[0] >= TEXT_WHITE_MIN && style_from_theme() && + !color_dark(style_color(RVT_ROLE_BACKGROUND))) + return recolor(color, text, mapped); + return color; +} + +/* A fill's or clear's colour. */ +static const uint8_t *map_fill(const uint8_t *color, uint8_t *mapped) +{ + const uint8_t *background = style_color(RVT_ROLE_BACKGROUND); + if (stock_fill) + return color; + if (grey(color) && color[0] >= SURFACE_LIGHT_MIN) + /* Lighter stock greys become darker surfaces; a dark role inverts that. */ + return shade(color, background, + color_dark(background) ? (255 - color[0]) / 4 : color[0] - 255, + mapped); + if (same_rgb(color, style_stock_color(RVT_ROLE_COVER_BORDER))) + return recolor(color, style_color(RVT_ROLE_COVER_BORDER), mapped); + if (same_rgb(color, style_stock_color(RVT_ROLE_ACCENT_FILL))) + return recolor(color, style_color(RVT_ROLE_ACCENT_FILL), mapped); + return color; +} + +/* Views that keep their light artwork in every look, so their background + * fill must stay stock too. */ +static int stock_background(uint32_t view) +{ + switch (view) { + case RES_NowPlaying_White_Background_View: + case RES_NowPlaying_Idle_Template: + case RES_NowPlaying_ChapterArt_BackgroundImage_View: + case RES_RentalInfo_White_Background_View: + return 1; + default: + return 0; + } +} + +/* Accents alone keep the stock clears and blends. */ +static int background_themed(void) +{ + return style_dark() || style_from_theme(); +} + +/* A bar's label: the highlighted one sits on the selection-tinted thumb, so + * it takes the on-accent colour; the others follow whatever contrasts with + * the well art. The Now Playing thumb follows no accent, so without a theme + * its label keeps the stock colour. */ +static const uint8_t *map_bar_label(const uint8_t *color, enum bar_slot slot, + unsigned well, uint8_t *mapped) +{ + const uint8_t *derived; + if (slot == BAR_SELECTED && well == WELL_NOW_PLAYING && !style_from_theme()) + return color; + if (slot == BAR_SELECTED) + return recolor(color, style_color(RVT_ROLE_ON_ACCENT), mapped); + if (slot == BAR_LABEL && (derived = tint_well_letter_color(well))) + return recolor(color, derived, mapped); + return color; +} + +/* A calendar day number: the shown month's in black on the active cell, a + * neighbouring month's in grey, the selected day's in white. */ +static const uint8_t *map_calendar_day(const uint8_t *color, uint8_t *mapped) +{ + const uint8_t *themed; + uint8_t mixed[4]; + if (color[0] == 255 && grey(color)) + themed = style_from_theme() ? style_color(RVT_ROLE_ON_ACCENT) : NULL; + else + themed = tint_calendar_text_color( + color[0] ? CALENDAR_INACTIVE : CALENDAR_ACTIVE, mixed); + return themed ? recolor(color, themed, mapped) : color; +} + +/* (context, rgba, view): every label. */ +static uint32_t text_color(uint32_t context, uint32_t rgba, uint32_t view, + const void *next) +{ + uint8_t mapped[4]; + const uint8_t *color = map_text((const uint8_t *)rgba, view_id(view), mapped); + return api->hook_next(next, context, (uint32_t)color, view, 0, 0, 0); +} + +/* The colour a fill or clear onto `surface` uses. On a coverage mask the + * colour becomes coverage (255 minus its luminance): the white that clears a + * text bitmap must stay white, or the whole rectangle reads as covered. */ +static const uint8_t *fill_color(const void *surface, const uint8_t *color, + uint8_t *mapped) +{ + if ((RV_FIELD(surface, Surface_format, uint16_t) & ~BMapFormat_ByteSwapped) <= + BMapFormat_Mask8) + return color; + return map_fill(color, mapped); +} + +/* (surface, rect, rgba, mode, clip): every fill and clear. */ +static uint32_t fill_rect(uint32_t surface, uint32_t rect, uint32_t rgba, uint32_t mode, + const void *next, uint32_t clip) +{ + uint8_t mapped[4]; + const uint8_t *color = + fill_color((const void *)surface, (const uint8_t *)rgba, mapped); + return api->hook_next(next, surface, rect, (uint32_t)color, mode, clip, 0); +} + +/* The fill rule for the background of view `id`, returning the rule it + * replaces: a view drawn inside another's background gives it back. */ +static int enter_background(uint32_t id) +{ + int outer = stock_fill; + stock_fill = stock_background(id); + return outer; +} + +/* (context, rect, view): a view's background. */ +static uint32_t background_fill(uint32_t context, uint32_t rect, uint32_t view, + const void *next) +{ + int outer = enter_background(view_id(view)); + uint32_t result = api->hook_next(next, context, rect, view, 0, 0, 0); + stock_fill = outer; + return result; +} + +/* A channel as a 16.16 fraction of 255: c * 65536 / 255 is c * 257 plus one + * for c = 255. */ +static uint32_t fraction(uint8_t channel) +{ + return channel * 257u + ((channel + 1u) >> 8); +} + +/* (red, green, blue, alpha) in 16.16: the GLES clear behind Cover Flow and album art. */ +static uint32_t clear_color(uint32_t red, uint32_t green, uint32_t blue, uint32_t alpha, + const void *next) +{ + if (background_themed()) { + const uint8_t *background = style_color(RVT_ROLE_BACKGROUND); + red = fraction(background[0]); + green = fraction(background[1]); + blue = fraction(background[2]); + } + return api->hook_next(next, red, green, blue, alpha, 0, 0); +} + +/* (pixel, background, weight): the album art reflection fading to the background. */ +static uint32_t reflection_blend(uint32_t pixel, uint32_t background, uint32_t weight, + const void *next) +{ + if (background_themed()) + background = rgb565_pack(style_color(RVT_ROLE_BACKGROUND)); + return api->hook_next(next, pixel, background, weight, 0, 0, 0); +} + +/* (context, rgba, view): a bitmap view's mask colour. Tinted masks take their + * tint, or the on-accent colour while highlighted. */ +static uint32_t bitmap_color(uint32_t context, uint32_t rgba, uint32_t view, + const void *next) +{ + const uint8_t *tinted = tint_mask_color((const void *)view); + return api->hook_next(next, context, tinted ? (uint32_t)tinted : rgba, view, 0, 0, + 0); +} + +/* Which of the view's two label colour fields `color` is, by address. */ +static enum bar_slot bar_slot(uint32_t rgba, uint32_t view, uint32_t label, + uint32_t selected) +{ + return rgba == view + selected ? BAR_SELECTED + : rgba == view + label ? BAR_LABEL + : BAR_OTHER; +} + +/* (context, rgba, view): the keyboard's key letters, on black well slices. */ +static uint32_t keyboard_color(uint32_t context, uint32_t rgba, uint32_t view, + const void *next) +{ + uint8_t mapped[4]; + enum bar_slot slot = bar_slot(rgba, view, KeyboardView_letter_color, + KeyboardView_selected_letter_color); + const uint8_t *color = + map_bar_label((const uint8_t *)rgba, slot, WELL_BLACK, mapped); + return api->hook_next(next, context, (uint32_t)color, view, 0, 0, 0); +} + +/* (context, rgba, view): an option bar's segment labels. */ +static uint32_t option_bar_color(uint32_t context, uint32_t rgba, uint32_t view, + const void *next) +{ + uint8_t mapped[4]; + const uint8_t *color = (const uint8_t *)rgba; + unsigned well = RV_FIELD(view, OptionBarView_style, uint8_t); + if (well < WELLS) + color = map_bar_label(color, + bar_slot(rgba, view, OptionBarView_label_color, + OptionBarView_selected_label_color), + well, mapped); + return api->hook_next(next, context, (uint32_t)color, view, 0, 0, 0); +} + +/* (context, rgba): a calendar day number. */ +static uint32_t calendar_day_color(uint32_t context, uint32_t rgba, const void *next) +{ + uint8_t mapped[4]; + const uint8_t *color = map_calendar_day((const uint8_t *)rgba, mapped); + return api->hook_next(next, context, (uint32_t)color, 0, 0, 0, 0); +} + +/* (context, rgba): the calendar's weekday names. */ +static uint32_t calendar_header_color(uint32_t context, uint32_t rgba, const void *next) +{ + uint8_t mapped[4], mixed[4]; + const uint8_t *color = (const uint8_t *)rgba; + const uint8_t *themed = tint_calendar_text_color(CALENDAR_HEADER, mixed); + if (themed) + color = recolor(color, themed, mapped); + return api->hook_next(next, context, (uint32_t)color, 0, 0, 0, 0); +} + +/* (context, source, source_rect, rect, alpha, flags, view): a bitmap view's or + * a menu row icon's blit, with the view the site pushes. */ +static uint32_t view_blit(uint32_t context, uint32_t source, uint32_t source_rect, + uint32_t rect, const void *next, uint32_t alpha, + uint32_t flags, uint32_t view) +{ + tint_highlight_begin((const void *)view, (const void *)source); + uint32_t result = + api->hook_next7(next, context, source, source_rect, rect, alpha, flags, view); + tint_highlight_end(); + return result; +} + +/* The same for a calendar day cell's marker, with the cell pushed. */ +static uint32_t marker_blit(uint32_t context, uint32_t source, uint32_t source_rect, + uint32_t rect, const void *next, uint32_t alpha, + uint32_t flags, uint32_t cell) +{ + tint_marker_highlight_begin((const void *)cell, (const void *)source); + uint32_t result = + api->hook_next7(next, context, source, source_rect, rect, alpha, flags, cell); + tint_highlight_end(); + return result; +} + +static const struct rv_hook themed_hooks[] = { + RV_HOOK_FILTER(RV_SITE_TextView_DrawColor_call, text_color), + RV_HOOK_FILTER(RV_SITE_MarqueeTextView_DrawColor_call, text_color), + RV_HOOK_FILTER(RV_SITE_GraphicsContext_FillRect_call, fill_rect), + RV_HOOK_FILTER(RV_SITE_GraphicsContext_ClearRect_call, fill_rect), + RV_HOOK_FILTER(RV_SITE_View_BackgroundFill_call, background_fill), + RV_HOOK_FILTER(RV_SITE_CoverFlow_ClearColor_call, clear_color), + RV_HOOK_FILTER(RV_SITE_AlbumArt_ClearColor_call, clear_color), + RV_HOOK_FILTER(RV_SITE_ArtworkReflection_Blend_call, reflection_blend), + RV_HOOK_FILTER(RV_SITE_BitmapView_DrawColor_call, bitmap_color), + RV_HOOK_FILTER(RV_SITE_KeyboardView_DrawColor_call, keyboard_color), + RV_HOOK_FILTER(RV_SITE_OptionBarView_DrawColor_call, option_bar_color), + RV_HOOK_FILTER(RV_SITE_CalendarDayCell_DrawColor_call, calendar_day_color), + RV_HOOK_FILTER(RV_SITE_CalendarView_DrawColor_call, calendar_header_color), + RV_HOOK_FILTER(RV_SITE_BitmapView_Blit_call, view_blit), + RV_HOOK_FILTER(RV_SITE_BitmapView_TileBlit_call, view_blit), + RV_HOOK_FILTER(RV_SITE_MenuRowBitmapView_Blit_call, view_blit), + RV_HOOK_FILTER(RV_SITE_MenuRowBitmapView_TileBlit_call, view_blit), + RV_HOOK_FILTER(RV_SITE_CalendarDayCell_TopMarkerBlit_call, marker_blit), + RV_HOOK_FILTER(RV_SITE_CalendarDayCell_BottomMarkerBlit_call, marker_blit), +}; +#define THEMED_HOOKS RV_COUNT(themed_hooks) + +static unsigned bound; /* how many of themed_hooks are bound, from the first */ + +int render_bind(int on) +{ + if (on) { + while (bound < THEMED_HOOKS && + api->hook_bind(self, &themed_hooks[bound]) == RV_OK) + bound++; + if (bound == THEMED_HOOKS) + return 1; + } + while (bound) + api->hook_unbind(self, &themed_hooks[--bound]); + return !on; +} diff --git a/extensions/appearance/render.h b/extensions/appearance/render.h new file mode 100644 index 0000000..de7ff79 --- /dev/null +++ b/extensions/appearance/render.h @@ -0,0 +1,12 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#ifndef RENDER_H +#define RENDER_H + +/* The draw hooks: the colour sites that map the stock colours to the roles in + * force, the blits that colour highlighted tinted art and the flat cover. + * Bound while a look other than stock light is on, unbound otherwise, so + * the stock look draws without them; 1 when the hooks are as asked. */ +int render_bind(int on); + +#endif diff --git a/extensions/appearance/screenshots/appearance.png b/extensions/appearance/screenshots/appearance.png new file mode 100644 index 0000000..9007e08 Binary files /dev/null and b/extensions/appearance/screenshots/appearance.png differ diff --git a/extensions/appearance/screenshots/dark-mode.png b/extensions/appearance/screenshots/dark-mode.png new file mode 100644 index 0000000..6ff74da Binary files /dev/null and b/extensions/appearance/screenshots/dark-mode.png differ diff --git a/extensions/appearance/selection_bar.c b/extensions/appearance/selection_bar.c new file mode 100644 index 0000000..b209fbc --- /dev/null +++ b/extensions/appearance/selection_bar.c @@ -0,0 +1,79 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The selection bar's drawer has two renderers for its cached bitmap: the + * stock one blends fixed colours, the other a highlight line and a gradient + * from the RAM colour words, behind a branch the stock firmware never takes. + * The look's colours go into the RAM words, the branch is made unconditional + * and the cache's bounds cleared, so the next draw builds the bar from them; + * restore puts the stock words back and lets the branch fall through again. */ + +#include "selection_bar.h" +#include "ext.h" +#include "osos-2.0.5.h" +#include "rv_libc.h" +#include "rv_sites.h" +#include "rv_ui.h" +#include "style.h" + +static uint8_t stock_gradient[2][4], + stock_highlight[4]; /* the RAM words as the firmware had them */ +static int saved, custom; /* the stock words are kept; the branch is bound */ +/* `b` to the RAM-colour renderer, in place of the stock `beq` there. */ +static const struct rv_hook ram_colors = + RV_HOOK_WORD(RV_SITE_SelectionBar_StyleBranch_word, 0xea000138); + +static void redraw(void) +{ + int32_t *bounds = (int32_t *)(SelectionGradient_Bitmap + Bitmap_bounds); + for (unsigned i = 0; i < 4; i++) + bounds[i] = 0; +} + +/* The Now Playing status icons are drawn once and kept; the model redraws + * them when told their resources changed. */ +static void redraw_play_state(void) +{ + void *service = UI_FindServiceById(Service_NowPlaying); + if (!service) + return; + void *(*interface)(void *, uint32_t) = + RV_FIELD(RV_FIELD(service, 0, void **), Service_interface_method, void *); + void *model = interface(service, Interface_Model); + if (!model) + return; + Model_Notify(model, Resource_Draw, Property_PlayStateWhite); + Model_Notify(model, Resource_Draw, Property_PlayStateBlack); +} + +void selection_bar_apply(void) +{ + uint8_t colors[3][4]; + if (!saved) { + memcpy(stock_gradient, SelectionBar_RamGradient, sizeof stock_gradient); + memcpy(stock_highlight, SelectionBar_RamHighlight, sizeof stock_highlight); + saved = 1; + } + if (style_selection_bar(colors)) { + memcpy(SelectionBar_RamGradient[0], colors[0], 4); + memcpy(SelectionBar_RamGradient[1], colors[1], 4); + memcpy(SelectionBar_RamHighlight, colors[2], 4); + if (!custom) + custom = api->hook_bind(self, &ram_colors) == RV_OK; + redraw(); + } else { + selection_bar_restore(); + } + redraw_play_state(); +} + +void selection_bar_restore(void) +{ + if (saved) { + memcpy(SelectionBar_RamGradient, stock_gradient, sizeof stock_gradient); + memcpy(SelectionBar_RamHighlight, stock_highlight, sizeof stock_highlight); + } + if (custom) + api->hook_unbind(self, &ram_colors); + custom = 0; + redraw(); +} diff --git a/extensions/appearance/selection_bar.h b/extensions/appearance/selection_bar.h new file mode 100644 index 0000000..8cae45c --- /dev/null +++ b/extensions/appearance/selection_bar.h @@ -0,0 +1,13 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#ifndef SELECTION_BAR_H +#define SELECTION_BAR_H + +/* Gives the selection bar the look's colours while they differ from stock and + * has the cached drawings, the bar and the Now Playing status icons, drawn + * again; after every switch and accent change. Restore puts the stock colours + * back. */ +void selection_bar_apply(void); +void selection_bar_restore(void); + +#endif diff --git a/extensions/appearance/services.h b/extensions/appearance/services.h new file mode 100644 index 0000000..20634b3 --- /dev/null +++ b/extensions/appearance/services.h @@ -0,0 +1,56 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The tables the two modules call each other through (modules share no + * symbols). `main` publishes main_service for as long as the extension is + * loaded; `switch` publishes switch_service between main's module_load and + * module_unload of it. */ + +#ifndef SERVICES_H +#define SERVICES_H +#include "catalog.h" +#include "assets.h" +#include "look.h" +#include "rv_api.h" +#include "rvt.h" +#include + +struct main_service { + struct look_state *state; + uint32_t (*crc32_update)(uint32_t crc, const void *data, uint32_t size); + uint32_t (*catalog_count)(void); + const uint8_t *(*catalog_fingerprint)(void); + uint8_t *(*catalog_data)(uint32_t index); + uint32_t (*catalog_size)(uint32_t index); + uint32_t (*catalog_crc)(uint32_t index); + uint32_t (*catalog_file_offset)(uint32_t index); + int (*catalog_layout)(uint32_t index, struct layout *b); + void (*style_set)(const uint8_t *prefix); + void (*style_reset)(void); + void (*style_set_dark)(int dark); + void (*style_set_accent)(unsigned accent); + void (*tint_refresh)(void); + void (*tint_accent_art)(const uint32_t *skip, uint32_t *touched); + int (*lz_decode)(struct rv_file *file, uint32_t stream_bytes, uint8_t *out, + uint32_t bytes, uint32_t *crc); + struct asset_entry *(*assets_reserve)(uint32_t count); + void (*assets_commit)(void); + void (*assets_drop)(void); +}; + +struct switch_service { + /* Streams the pack at `pack` out of `file` (a theme file or the classic + * asset, its header checked by main and summed in look->header_crc; NULL + * for the stock light look) into the resident bitmaps, restores what the + * previous look changed and this one leaves alone, applies the colours + * and tints the stock accent art. A failure after the first write + * restores everything and returns to the stock light look. */ + enum switch_result (*apply)(struct rv_file *file, const struct look *look, + const struct pack_place *pack); + /* Another accent for the current look: the accent art is restored and + * tinted again; no pack is read. */ + enum switch_result (*accent)(unsigned accent); + /* Puts every bitmap back and forgets the look. */ + void (*restore_all)(void); +}; + +#endif diff --git a/extensions/appearance/stock.c b/extensions/appearance/stock.c new file mode 100644 index 0000000..8a5f3b0 --- /dev/null +++ b/extensions/appearance/stock.c @@ -0,0 +1,104 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "stock.h" +#include "ext.h" +#include "rv_libc.h" +#include "switch.h" +#include + +static struct rv_file *kept; /* the file while a switch holds it open */ + +static struct rv_file *open_firmware(void) +{ + struct rv_file *file; + return api->firmware_open(self, &file) == RV_OK ? file : NULL; +} + +static int read_at(struct rv_file *file, uint32_t offset, void *out, uint32_t bytes) +{ + return api->file_seek(self, file, offset) == RV_OK && read_exact(file, out, bytes); +} + +static int crc_matches(uint32_t crc, uint32_t index) +{ + return (uint16_t)~crc == main_module->catalog_crc(index); +} + +/* Read in pieces through the stack. */ +int stock_file_matches(void) +{ + struct rv_file *file = open_firmware(); + uint8_t piece[256]; + if (!file) + return 0; + uint32_t last = main_module->catalog_count() - 1, + left = main_module->catalog_size(last); + uint32_t crc = 0xffffffffu; + int ok = + api->file_seek(self, file, main_module->catalog_file_offset(last)) == RV_OK; + while (ok && left) { + uint32_t n = left < sizeof piece ? left : sizeof piece; + ok = read_exact(file, piece, n); + crc = main_module->crc32_update(crc, piece, n); + left -= n; + } + api->file_close(self, file); + return ok && crc_matches(crc, last); +} + +int stock_open(void) +{ + if (!kept) + kept = open_firmware(); + return kept != NULL; +} + +void stock_close(void) +{ + if (kept) + api->file_close(self, kept); + kept = NULL; +} + +static int fetch(struct rv_file *file, uint32_t index, uint8_t *dest) +{ + struct layout b; + if (!main_module->catalog_layout(index, &b)) + return 0; + const uint8_t *bitmap = main_module->catalog_data(index); + uint32_t size = main_module->catalog_size(index) - b.start; + uint32_t crc = main_module->crc32_update(0xffffffffu, bitmap, b.start); + if (!read_at(file, main_module->catalog_file_offset(index) + b.start, dest, size) || + !crc_matches(main_module->crc32_update(crc, dest, size), index)) { + memset(dest, 0, size); + return 0; + } + return 1; +} + +int stock_fetch(uint32_t index, uint8_t *dest) +{ + if (kept) + return fetch(kept, index, dest); + struct rv_file *file = open_firmware(); + if (!file) + return 0; + int ok = fetch(file, index, dest); + api->file_close(self, file); + return ok; +} + +int stock_restore(const uint32_t *bitmaps) +{ + int opened = !kept && stock_open(), ok = kept != NULL; + for (uint32_t i = 0; ok && i < main_module->catalog_count(); i++) + if (bit_test(bitmaps, i)) { + struct layout b; + if (!main_module->catalog_layout(i, &b) || + !fetch(kept, i, main_module->catalog_data(i) + b.start)) + ok = 0; + } + if (opened) + stock_close(); + return ok; +} diff --git a/extensions/appearance/stock.h b/extensions/appearance/stock.h new file mode 100644 index 0000000..f15e852 --- /dev/null +++ b/extensions/appearance/stock.h @@ -0,0 +1,29 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* Stock artwork comes back from the firmware file, + * /Reprise/Firmware/reprise.bin: Apple's image with the core appended, so + * every bitmap lies there at its catalog offset, unchanged. The file must be + * the image the iPod booted: it is checked once per session before a switch + * writes anything, so recovery is possible afterwards, and again after USB + * disk mode, which may have replaced it. */ + +#ifndef STOCK_H +#define STOCK_H +#include + +/* The file opens and its last bitmap carries the catalog's checksum, so it is + * the booted image. */ +int stock_file_matches(void); +/* Keeps the file open across one switch, so each fetch is a seek and a read; + * stock_fetch and stock_restore open it for themselves when it is not. */ +int stock_open(void); +void stock_close(void); +/* Reads one bitmap's bytes after its header into `dest` and checks them, with + * the resident header, against the stock checksum. 0 when they do not match; + * `dest` is then zero. */ +int stock_fetch(uint32_t index, uint8_t *dest); +/* stock_fetch of every bitmap set in `bitmaps` into its resident bitmap; 0 + * when one fails. */ +int stock_restore(const uint32_t *bitmaps); + +#endif diff --git a/extensions/appearance/style.c b/extensions/appearance/style.c new file mode 100644 index 0000000..9fb667b --- /dev/null +++ b/extensions/appearance/style.c @@ -0,0 +1,189 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "style.h" +#include "pixel.h" +#include "rv_libc.h" + +#define RGB(r, g, b) {r, g, b, 255} + +/* The stock look's roles, light then dark, in rvt_role order. The dark row's + * background, text, accent and border are the colours of the core's former Dark + * Mode, payload/dark_mode.c (147a6fb, 7ec554b), by lgreitis and Alex Ball + * (alexballvideos-netizen); the light row is Apple's. */ +static const uint8_t classic[2][RVT_ROLES][4] = { + {RGB(255, 255, 255), RGB(32, 32, 32), RGB(35, 108, 197), RGB(49, 133, 208), + RGB(255, 255, 255), RGB(35, 108, 197), RGB(126, 129, 131), RGB(49, 133, 208)}, + {RGB(24, 24, 24), RGB(232, 232, 232), RGB(0, 161, 255), RGB(0, 161, 255), + RGB(255, 255, 255), RGB(0, 161, 255), RGB(56, 56, 56), RGB(0, 161, 255)}, +}; + +/* The stock look's accents: fill and text, light then dark. Light colours keep + * 5:1 against white; dark fills keep 4.5:1 under white text and dark text 6:1 + * on the background. Blue is the stock colour itself. */ +static const uint8_t accents[RVT_ACCENTS][2][2][4] = { + {{RGB(35, 108, 197), RGB(49, 133, 208)}, {RGB(0, 161, 255), RGB(0, 161, 255)}}, + {{RGB(137, 68, 171), RGB(137, 68, 171)}, {RGB(150, 78, 188), RGB(218, 143, 255)}}, + {{RGB(196, 30, 86), RGB(196, 30, 86)}, {RGB(206, 38, 96), RGB(255, 100, 145)}}, + {{RGB(208, 32, 40), RGB(208, 32, 40)}, {RGB(212, 40, 48), RGB(255, 105, 97)}}, + {{RGB(184, 72, 0), RGB(184, 72, 0)}, {RGB(190, 76, 0), RGB(255, 159, 10)}}, + {{RGB(30, 128, 58), RGB(30, 128, 58)}, {RGB(32, 134, 62), RGB(48, 209, 88)}}, + {{RGB(0, 115, 120), RGB(0, 115, 120)}, {RGB(0, 120, 125), RGB(64, 210, 215)}}, + {{RGB(130, 101, 0), RGB(130, 101, 0)}, {RGB(132, 103, 0), RGB(255, 214, 10)}}, + {{RGB(92, 96, 102), RGB(92, 96, 102)}, {RGB(100, 104, 110), RGB(190, 194, 200)}}, +}; +#undef RGB + +const char *const accent_labels[ACCENTS] = { + "Theme", "Blue", "Teal", "Green", "Yellow", + "Orange", "Red", "Pink", "Purple", "Graphite", +}; + +/* The palette each listed accent is, in rvt_accent order. */ +static const uint8_t palette_of[ACCENTS - ACCENT_FIRST] = { + RVT_ACCENT_BLUE, RVT_ACCENT_TEAL, RVT_ACCENT_GREEN, + RVT_ACCENT_YELLOW, RVT_ACCENT_ORANGE, RVT_ACCENT_RED, + RVT_ACCENT_PINK, RVT_ACCENT_PURPLE, RVT_ACCENT_GRAPHITE, +}; + +/* Which palette slot of an accent replaces a role, plus one; 0 keeps the role. */ +static const uint8_t accent_slot[RVT_ROLES] = { + [RVT_ROLE_ACCENT_FILL] = RVT_SLOT_ACCENT_FILL + 1, + [RVT_ROLE_ACCENT_TEXT] = RVT_SLOT_ACCENT_TEXT + 1, + [RVT_ROLE_SELECTION] = RVT_SLOT_SELECTION + 1, + [RVT_ROLE_ON_ACCENT] = RVT_SLOT_ON_ACCENT + 1, + [RVT_ROLE_ICON_TINT] = RVT_SLOT_ICON_TINT + 1, +}; + +/* The pack's style prefix, tint roles packed two per byte. */ +static struct { + uint8_t colors[RVT_ROLES][4]; + uint32_t flags; + uint8_t accents[RVT_ACCENTS][RVT_ACCENT_SLOTS][4]; + uint8_t tint[RVT_CATALOG_MAX / 2]; +} pack; + +static int from_theme, dark; /* a pack's colours are in force; the dark appearance is */ +static unsigned accent; /* enum accent */ + +static unsigned palette(void) +{ + return palette_of[accent - ACCENT_FIRST]; +} + +void color_mix(uint8_t out[4], const uint8_t *from, const uint8_t *to, unsigned weight) +{ + for (unsigned i = 0; i < 3; i++) + out[i] = (uint8_t)div255(from[i] * (255 - weight) + to[i] * weight + 127); + out[3] = 255; +} + +const uint8_t *style_color(enum rvt_role role) +{ + if ((unsigned)role >= RVT_ROLES) + role = RVT_ROLE_TEXT; + if (from_theme) { + unsigned slot = accent_slot[role]; + return accent && slot ? pack.accents[palette()][slot - 1] : pack.colors[role]; + } + if (accent) { + const uint8_t (*preset)[4] = accents[palette()][dark]; + if (role == RVT_ROLE_ACCENT_FILL || role == RVT_ROLE_SELECTION) + return preset[0]; + if (role == RVT_ROLE_ACCENT_TEXT || role == RVT_ROLE_ICON_TINT) + return preset[1]; + } + return classic[dark][role]; +} + +const uint8_t *style_stock_color(enum rvt_role role) +{ + return classic[0][(unsigned)role < RVT_ROLES ? role : RVT_ROLE_TEXT]; +} + +void style_set(const uint8_t *prefix) +{ + const uint8_t *tint = prefix + RVT_STYLE_TINTS; + memcpy(pack.colors, prefix + RVT_STYLE_COLORS, sizeof pack.colors); + memcpy(&pack.flags, prefix + RVT_STYLE_FLAGS, sizeof pack.flags); + memcpy(pack.accents, prefix + RVT_STYLE_PALETTES, sizeof pack.accents); + for (unsigned i = 0; i < RVT_CATALOG_MAX; i += 2) + pack.tint[i / 2] = (uint8_t)((tint[i] & 15) | (tint[i + 1] << 4)); + from_theme = 1; +} + +void style_reset(void) +{ + from_theme = 0; +} + +int style_from_theme(void) +{ + return from_theme; +} + +void style_set_dark(int value) +{ + dark = !!value; +} + +int style_dark(void) +{ + return dark; +} + +void style_set_accent(unsigned value) +{ + accent = value < ACCENTS ? value : ACCENT_DEFAULT; +} + +unsigned style_accent(void) +{ + return accent; +} + +int style_not_stock(void) +{ + return dark || from_theme || style_accent_art_active(); +} + +unsigned style_flags(void) +{ + return from_theme ? pack.flags : 0; +} + +static unsigned tint_role(unsigned asset) +{ + if (!from_theme || asset >= RVT_CATALOG_MAX) + return RVT_TINT_NONE; + return (pack.tint[asset / 2] >> (asset % 2 * 4)) & 15; +} + +int style_tinted(unsigned asset) +{ + return tint_role(asset) != RVT_TINT_NONE; +} + +const uint8_t *style_tint_color(unsigned asset) +{ + return style_color((enum rvt_role)(tint_role(asset) - RVT_TINT_ROLE)); +} + +int style_accent_art_active(void) +{ + return from_theme || (accent && palette() != RVT_ACCENT_BLUE); +} + +/* The stock gradient's stops, lightened toward white by these / 255. */ +static const uint8_t bar_lift[3] = {64, 0, 140}; + +int style_selection_bar(uint8_t out[3][4]) +{ + static const uint8_t white[4] = {255, 255, 255, 255}; + int flat = style_flags() & RVT_FLAG_FLAT_SELECTION; + if (!flat && !style_accent_art_active()) + return 0; + const uint8_t *base = style_color(RVT_ROLE_SELECTION); + for (unsigned stop = 0; stop < 3; stop++) + color_mix(out[stop], base, white, flat ? 0 : bar_lift[stop]); + return 1; +} diff --git a/extensions/appearance/style.h b/extensions/appearance/style.h new file mode 100644 index 0000000..6aae069 --- /dev/null +++ b/extensions/appearance/style.h @@ -0,0 +1,62 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The colours in force: the roles of the stock look in light or dark, + * of a theme pack's style prefix, and of the accent chosen on top of either. + * Every colour is RGBA bytes, alpha 255. */ + +#ifndef STYLE_H +#define STYLE_H +#include "rvt.h" +#include + +/* The accent setting, in the order the list shows: Theme keeps the look's own + * accent colours, then the named accents. */ +enum accent { ACCENT_DEFAULT, ACCENT_FIRST, ACCENTS = ACCENT_FIRST + RVT_ACCENTS }; + +extern const char *const accent_labels[ACCENTS]; + +/* A role's colour under the current appearance and accent. */ +const uint8_t *style_color(enum rvt_role role); +/* A role's colour in the stock light look, which is what the stock screens + * draw in and the draw hooks recognise. */ +const uint8_t *style_stock_color(enum rvt_role role); +/* The style prefix of a theme pack (RVT_STYLE_BYTES) replaces the stock + * colours; reset returns to them. */ +void style_set(const uint8_t *prefix); +void style_reset(void); +int style_from_theme(void); +void style_set_dark(int dark); +int style_dark(void); +void style_set_accent(unsigned accent); +unsigned style_accent(void); +/* Anything but the stock light look with its own accent. */ +int style_not_stock(void); +/* RVT_FLAG_* of the pack, 0 for the stock look. */ +unsigned style_flags(void); +/* Whether a catalog bitmap is tinted, and the colour of the role it is + * tinted with; ask only for tinted ones. */ +int style_tinted(unsigned asset); +const uint8_t *style_tint_color(unsigned asset); +/* Whether stock accent artwork and the selection bar follow the colours: + * under a pack always, under the stock look for accents other than Blue. */ +int style_accent_art_active(void); +/* Gradient start, gradient end and top line of the selection bar; 0 keeps + * the stock bar. */ +int style_selection_bar(uint8_t out[3][4]); + +/* Weighted brightness scaled by 256 (black 0, white 255 * 256), and whether a + * colour reads as a dark surface. */ +static inline int color_brightness(const uint8_t *color) +{ + return 54 * color[0] + 183 * color[1] + 19 * color[2]; +} + +static inline int color_dark(const uint8_t *color) +{ + return color_brightness(color) < 128 * 256; +} + +/* Each channel of `from` moved toward `to` by weight / 255; `out` is opaque. */ +void color_mix(uint8_t out[4], const uint8_t *from, const uint8_t *to, unsigned weight); + +#endif diff --git a/extensions/appearance/switch.c b/extensions/appearance/switch.c new file mode 100644 index 0000000..481f21b --- /dev/null +++ b/extensions/appearance/switch.c @@ -0,0 +1,155 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The switch module: reads a theme file, derives artwork and restores stock + * bitmaps from the firmware file. Loaded for a switch, an accent change or + * unload. */ + +#include "switch.h" +#include "ext.h" +#include "pack.h" +#include "rv_libc.h" +#include "stock.h" +#include "style.h" + +const struct rv_api *api; +rv_extension_handle self; +const struct main_service *main_module; + +static int empty(const uint32_t *bits) +{ + for (unsigned i = 0; i < BITMAP_WORDS; i++) + if (bits[i]) + return 0; + return 1; +} + +static void accent_art_tint(struct look_state *s) +{ + memset(s->accented, 0, sizeof s->accented); + main_module->tint_accent_art(s->assets, s->accented); + for (unsigned i = 0; i < BITMAP_WORDS; i++) + s->assets[i] |= s->accented[i]; +} + +/* The firmware file is checked against the resident bank once per session. */ +static int stock_usable(struct look_state *s) +{ + if (!s->stock_checked) + s->stock_checked = stock_file_matches(); + return s->stock_checked; +} + +/* Artwork is half changed: restore every bitmap either look touched and go + * back to the stock light look. When that fails every bitmap of the attempt + * stays marked, restored or not, so the next switch reads them all again, + * and the firmware file is checked again before it. */ +static enum switch_result recover(struct look_state *s, const uint32_t *touched) +{ + uint32_t restore[BITMAP_WORDS]; + for (unsigned i = 0; i < BITMAP_WORDS; i++) + restore[i] = s->assets[i] | touched[i]; + int restored = stock_restore(restore); + memset(&s->active, 0, sizeof s->active); + if (restored) { + memset(s->assets, 0, sizeof s->assets); + memset(s->accented, 0, sizeof s->accented); + } else { + memcpy(s->assets, restore, sizeof s->assets); + s->stock_checked = 0; + } + main_module->assets_drop(); + main_module->style_reset(); + main_module->style_set_dark(0); + main_module->style_set_accent(ACCENT_DEFAULT); + main_module->tint_refresh(); + return restored ? SWITCH_RECOVERED : SWITCH_RESTORE_FAILED; +} + +static enum switch_result switch_apply(struct rv_file *file, const struct look *look, + const struct pack_place *place) +{ + struct look_state *s = main_module->state; + uint32_t target[BITMAP_WORDS], restore[BITMAP_WORDS]; + struct pack pack; + enum switch_result result; + memset(target, 0, sizeof target); + if (!stock_usable(s) || (file && !pack_open(file, look->header_crc, place, &pack))) + return SWITCH_LOAD_FAILED; + /* The Classic dark art carries colours the stock look already has. */ + if (file && !look->id[0] && !pack_plain(&pack)) + return SWITCH_LOAD_FAILED; + if (!stock_open()) + return SWITCH_LOAD_FAILED; + int applied = !file || pack_apply(&pack, target, s->assets); + if (!applied && empty(target)) { + /* Nothing changed: the look on the screen keeps its bitmaps. */ + main_module->assets_reserve(0); + stock_close(); + return SWITCH_LOAD_FAILED; + } + for (unsigned i = 0; i < BITMAP_WORDS; i++) + restore[i] = s->assets[i] & ~target[i]; + if (!applied || !stock_restore(restore)) { + result = recover(s, target); + stock_close(); + return result; + } + s->active = *look; + memcpy(s->assets, target, sizeof s->assets); + if (file) + main_module->assets_commit(); + else + main_module->assets_drop(); + if (look->id[0]) + main_module->style_set((const uint8_t *)pack.style); + else + main_module->style_reset(); + main_module->style_set_dark(look->dark); + main_module->style_set_accent(look->accent); + main_module->tint_refresh(); + accent_art_tint(s); + stock_close(); + return SWITCH_OK; +} + +static enum switch_result switch_accent(unsigned accent) +{ + struct look_state *s = main_module->state; + if (!stock_usable(s)) + return SWITCH_LOAD_FAILED; + s->active.accent = accent; + main_module->style_set_accent(accent); + main_module->tint_refresh(); + if (!stock_restore(s->accented)) + return recover(s, s->assets); + for (unsigned i = 0; i < BITMAP_WORDS; i++) + s->assets[i] &= ~s->accented[i]; + accent_art_tint(s); + return SWITCH_OK; +} + +static void switch_restore_all(void) +{ + struct look_state *s = main_module->state; + if (!empty(s->assets)) + stock_restore(s->assets); + memset(s->assets, 0, sizeof s->assets); + memset(s->accented, 0, sizeof s->accented); + memset(&s->active, 0, sizeof s->active); + main_module->assets_drop(); + main_module->style_reset(); +} + +static const struct switch_service service = {switch_apply, switch_accent, + switch_restore_all}; + +static const struct rv_descriptor module = {.size = sizeof module, .service = &service}; + +const struct rv_descriptor *rv_module_entry(const struct rv_api *core, + rv_extension_handle handle) +{ + api = core; + self = handle; + main_module = api->module_service(self, 0); + return &module; +} diff --git a/extensions/appearance/switch.h b/extensions/appearance/switch.h new file mode 100644 index 0000000..8e3291a --- /dev/null +++ b/extensions/appearance/switch.h @@ -0,0 +1,22 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The switch module: loaded by main for one switch, accent change or unload, + * it streams a pack into the resident bitmaps and restores stock artwork from + * the firmware file. Its files reach main's catalog, checksum, style and + * tint code through main's service table. + * + * A switch streams the pack's artwork straight into the firmware's resident + * bitmaps and restores what the previous look changed from the firmware + * file, reading only the bitmaps that need it and checking each against its + * stock checksum, so nothing is staged in memory. A failure part way through + * restores every bitmap either look touched and brings back the stock light + * look; when that restore fails too, theming is off for the session. */ + +#ifndef SWITCH_H +#define SWITCH_H +#include "services.h" + +/* main's table, fetched by the module's entry. */ +extern const struct main_service *main_module; + +#endif diff --git a/extensions/appearance/tests/catalog.inc b/extensions/appearance/tests/catalog.inc new file mode 100644 index 0000000..019627b --- /dev/null +++ b/extensions/appearance/tests/catalog.inc @@ -0,0 +1,23 @@ +/* Hand-written for the host tests, in the shape tools/catalog_inc.py writes: + * a six-bitmap catalog over a host array: a mask, two paletted bitmaps of one + * layout, an RGB565 one with padding after it, an ARGB one and a paletted one + * with a wider palette. The checksums are filled in once the bank is built. */ +#define CATALOG_COUNT 6 +#define CATALOG_BASE ((uintptr_t)host_bank) +#define CATALOG_FILE_OFFSET 0x1000u +#define CATALOG_BANK_BYTES sizeof host_bank +static const uint8_t fingerprint[RVT_FINGERPRINT_BYTES] = {1, 2, 3, 4, 5, 6, 7, 8}; +static const uint32_t catalog_offsets[CATALOG_COUNT + 1] = { + AT_MASK | PAD(MASK_BYTES), AT_PALETTED | PAD(PALETTED_BYTES), AT_RGB | PAD(RGB_BYTES), + AT_SECOND | PAD(PALETTED_BYTES), AT_ARGB | PAD(ARGB_BYTES), AT_WIDE | PAD(WIDE_BYTES), + BANK_END, +}; +static uint16_t catalog_crcs[CATALOG_COUNT]; +static const uint16_t well_centers[3] = {1, 1, 1}; +static const uint16_t field_center = 1; +static const uint16_t calendar_cells[3] = {1, 1, 1}; +static const struct contrast_text contrast_text[] = { + {RES_NowPlaying_StatusBar_Text_View, 1, 1}, {0x0dad0101u, 4, 1}, {0x0dad0201u, 4, 1}, + {0x0dad0301u, 3, 1}, {0x0dad0401u, 2, 1}, +}; +static const struct accent_art accent_art[] = {{5, RVT_ROLE_ACCENT_FILL}}; diff --git a/extensions/appearance/tests/contracts.c b/extensions/appearance/tests/contracts.c new file mode 100644 index 0000000..66a5dd9 --- /dev/null +++ b/extensions/appearance/tests/contracts.c @@ -0,0 +1,2871 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The extension's logic against a bitmap bank and a firmware file in host + * memory: what a theme file must look like to be accepted, that no record + * writes outside the bitmap it names, what each derived record kind computes, + * how a switch recovers, how the folder is listed, and which colour each + * stock draw is mapped to. */ + +#include +#include +#include +#include +#include + +/* A BMap: format, stride, depth half-words, zeros, height and width words, the + * data length, then the bytes. */ +#define HEADER 28 +#define MASK_BYTES (HEADER + 4 * 2) /* 4 wide, 2 high, 8-bit mask, stride 4 */ +#define PALETTED_BYTES (HEADER + 4 + 2 * 4 + 4 * 2) /* 2 colours, 4 by 2 at 8 bits */ +#define RGB_BYTES (HEADER + 2 * 3) /* 1 by 3 RGB565, stride 2: padded in the bank */ +#define ARGB_BYTES (HEADER + 16 * 2) /* 4 by 2 BGRA, stride 16 */ +#define WIDE_BYTES (HEADER + 4 + 4 * 4 + 4 * 2) /* 4 colours, 4 by 2 at 8 bits */ +#define ALIGNED(n) (((n) + 3) & ~3u) +#define PAD(n) (ALIGNED(n) - (n)) + +enum { + AT_MASK = 0, + AT_PALETTED = AT_MASK + ALIGNED(MASK_BYTES), + AT_RGB = AT_PALETTED + ALIGNED(PALETTED_BYTES), + AT_SECOND = AT_RGB + ALIGNED(RGB_BYTES), + AT_ARGB = AT_SECOND + ALIGNED(PALETTED_BYTES), + AT_WIDE = AT_ARGB + ALIGNED(ARGB_BYTES), + BANK_END = AT_WIDE + WIDE_BYTES, +}; + +enum { MASK = 0, PALETTED = 1, RGB = 2, SECOND = 3, ARGB = 4, WIDE = 5 }; + +static uint8_t host_bank[BANK_END]; +static uint8_t stock_bank[sizeof host_bank]; + +uint8_t Palette_White[4] = {255, 255, 255, 255}; + +/* The main module's sources, then the switch module's; switch.c defines + * `api`, `self` and `main_module`. */ +#include "../catalog.c" +#include "../crc.c" +#include "../flat_cover.c" +#include "../assets.c" +#include "../latch.c" +#include "../look.c" +#include "../lz.c" +#include "../render.c" +#include "../selection_bar.c" +#include "../style.c" +#include "../theme.c" +#include "../theme_picker.c" +#include "../tint.c" +#include "../derive.c" +#include "../pack.c" +#include "../stock.c" +#include "../switch.c" + +/* The schedule's Apple side: a clock and one time zone. */ +static uint8_t clock_now[DateTime_bytes]; +static int16_t clock_zone; +static uint8_t clock_dst; + +int RTC_ReadDateTime(struct DateTime *out) +{ + memcpy(out, clock_now, sizeof clock_now); + return 1; +} + +void RTC_GetZoneOffsets(int16_t *zone_minutes, uint8_t *dst_minutes) +{ + *zone_minutes = clock_zone; + *dst_minutes = clock_dst; +} + +static uint8_t host_zones[TimeZone_Count * TimeZone_bytes]; +#define TimeZones host_zones +static uint8_t host_preferences[PreferencesFile_time_zone_id + 4]; +static uint8_t host_browser[MediaBrowser_preferences + sizeof(void *)]; +static uint8_t host_app[App_browser + sizeof(void *)]; +void *App = host_app; +#include "../../shared/sun.c" +#include "../../shared/schedule.c" +#include "../dark_mode.c" + +/* The file under test: an rv_file is a cursor into a byte buffer. */ +struct rv_file { + const uint8_t *data; + uint32_t size, at; +}; + +/* The firmware file: the bank as built, at CATALOG_FILE_OFFSET, copied when + * it is opened. */ +static uint8_t firmware_image[CATALOG_FILE_OFFSET + BANK_END]; +static struct rv_file firmware_file; +static int firmware_open_now, firmware_missing, opens, closes; +static int corrupt_asset = -1; /* this asset's last byte reads back wrong */ + +static int firmware_open(rv_extension_handle s, struct rv_file **file) +{ + (void)s; + if (firmware_missing) + return RV_NOT_FOUND; + assert(!firmware_open_now); + memcpy(firmware_image + CATALOG_FILE_OFFSET, stock_bank, sizeof stock_bank); + if (corrupt_asset >= 0) + firmware_image[CATALOG_FILE_OFFSET + offset_of((uint32_t)corrupt_asset) + + catalog_size((uint32_t)corrupt_asset) - 1] ^= 1; + firmware_file = (struct rv_file){firmware_image, sizeof firmware_image, 0}; + firmware_open_now = 1; + opens++; + *file = &firmware_file; + return RV_OK; +} + +/* The selection bar's RAM words and cached bitmap, and the Now Playing + * service lookup, which finds nothing here. */ +uint8_t SelectionBar_RamGradient[2][4], SelectionBar_RamHighlight[4], + SelectionGradient_Bitmap[0xa8]; + +void *UI_FindServiceById(uint32_t service_id) +{ + (void)service_id; + return NULL; +} + +void Model_Notify(void *model, uint32_t type, uint32_t property) +{ + (void)model; + (void)type; + (void)property; + assert(0); +} + +/* The album art view and the GLES buffer behind the flat cover. */ +static uint8_t cover_image[0x100]; +static uint16_t render_target[320 * 240]; +static int cover_view; + +void *GLAlbumArtView_GetImage(void *view) +{ + assert(view == &cover_view); + return cover_image; +} + +void GameGraphics_GetCurrentPixelBuffer(void **out_pixels) +{ + *out_pixels = render_target; +} + +static int file_read(rv_extension_handle s, struct rv_file *f, void *out, + uint32_t bytes, uint32_t *got) +{ + (void)s; + uint32_t n = f->at >= f->size ? 0 + : f->at + bytes > f->size ? f->size - f->at + : bytes; + memcpy(out, f->data + f->at, n); + f->at += n; + *got = n; + return RV_OK; +} + +static int file_seek(rv_extension_handle s, struct rv_file *f, uint32_t offset) +{ + (void)s; + f->at = offset; + return RV_OK; +} + +static int allocations, alloc_fails; /* blocks out; the next alloc returns NULL */ + +static void *alloc(rv_extension_handle s, uint32_t bytes) +{ + (void)s; + if (alloc_fails) { + alloc_fails = 0; + return NULL; + } + allocations++; + return calloc(1, bytes); +} + +static void release(rv_extension_handle s, void *block) +{ + (void)s; + allocations--; + free(block); +} + +/* hook_next records what a handler passed on and returns `next_result`. */ +static uint32_t passed[7], next_result = 0x600d; + +static uint32_t hook_next(const void *next, uint32_t a, uint32_t b, uint32_t c, + uint32_t d, uint32_t e, uint32_t f) +{ + (void)next; + passed[0] = a, passed[1] = b, passed[2] = c, passed[3] = d, passed[4] = e, + passed[5] = f; + return next_result; +} + +static int binds, + bind_failures_at; /* hooks bound now; the bind that fails (1-based), 0 for none */ + +static int hook_bind(rv_extension_handle s, const struct rv_hook *hook) +{ + (void)s; + (void)hook; + if (bind_failures_at && binds + 1 == bind_failures_at) + return RV_NO_MEMORY; + binds++; + return RV_OK; +} + +static int hook_unbind(rv_extension_handle s, const struct rv_hook *hook) +{ + (void)s; + (void)hook; + assert(binds > 0); + binds--; + return RV_OK; +} + +/* A record to build into a pack: `payload` bytes of `kind`. */ +struct rec { + uint32_t asset, kind, size; + const uint8_t *payload; +}; + +/* The Themes folder: names the listing returns, and files opened by id. */ +static const char *const *folder; +static unsigned folder_count; +static const char *unreadable; /* an id whose file does not open */ + +struct built { + uint8_t bytes[32768]; + uint32_t size; +}; +static struct built opened_theme, classic_asset; +static struct rv_file opened_file, classic_file; +static int open_files; +static const struct built *provided; /* the file content_open returns for PROVIDED_ID */ +#define PROVIDED_ID "test" +static void build_theme(struct built *b, const char *id, const char *name); +static void build_file_at(struct built *b, const char *id, const char *name, + uint32_t header_bytes, const struct rec *light, + uint32_t nlight, const struct rec *dark, uint32_t ndark, + const uint8_t *tint, const uint8_t *prefix); + +static int content_open(rv_extension_handle s, const char *name, struct rv_file **file) +{ + (void)s; + char id[RVT_ID_BYTES] = {0}; + assert(!strncmp(name, "Themes/", 7)); + size_t n = strlen(name + 7); + assert(n > 4 && n - 4 < sizeof id && !strcmp(name + 7 + n - 4, ".rvt")); + memcpy(id, name + 7, n - 4); + if (unreadable && !strcmp(id, unreadable)) + return RV_NOT_FOUND; + assert(!open_files); + if (provided && !strcmp(id, PROVIDED_ID)) { + opened_file = (struct rv_file){provided->bytes, provided->size, 0}; + } else { + build_theme(&opened_theme, id, "Named"); + opened_file = (struct rv_file){opened_theme.bytes, opened_theme.size, 0}; + } + *file = &opened_file; + open_files++; + return RV_OK; +} + +static void file_close(rv_extension_handle s, struct rv_file *file) +{ + (void)s; + if (file == &firmware_file) { + assert(firmware_open_now); + firmware_open_now = 0; + closes++; + return; + } + assert((file == &opened_file || file == &classic_file) && open_files == 1); + open_files--; +} + +static int content_list(rv_extension_handle s, const char *name, + void (*each)(const char *entry, int is_folder, void *arg), + void *arg) +{ + (void)s; + assert(!strcmp(name, "Themes")); + each("Sub", 1, arg); + for (unsigned i = 0; i < folder_count; i++) + each(folder[i], 0, arg); + return RV_OK; +} + +/* The settings store: ints by key, and the theme id string. */ +static int32_t setting_ints[8]; +static char theme_id_setting[RVT_ID_BYTES]; + +static int32_t setting_get_int(rv_extension_handle s, uint16_t key) +{ + (void)s; + return setting_ints[key]; +} + +static int setting_set_int(rv_extension_handle s, uint16_t key, int32_t value) +{ + (void)s; + setting_ints[key] = value; + if (key == KEY_DARK) + dark_mode_set(value); + return RV_OK; +} + +static uint32_t setting_read(rv_extension_handle s, uint16_t key, void *out, + uint32_t capacity) +{ + (void)s; + assert(key == KEY_THEME); + uint32_t n = (uint32_t)strlen(theme_id_setting); + memcpy(out, theme_id_setting, n < capacity ? n : capacity); + return n; +} + +static int setting_write(rv_extension_handle s, uint16_t key, uint8_t type, + const void *data, uint32_t bytes) +{ + (void)s; + assert(key == KEY_THEME && type == RV_SETTING_TYPE_STRING && + bytes < sizeof theme_id_setting); + memset(theme_id_setting, 0, sizeof theme_id_setting); + memcpy(theme_id_setting, data, bytes); + return RV_OK; +} + +/* The switch module loads on request; the classic asset is a plain dark pack. */ +static int module_loaded, module_load_fails; + +static int module_load(rv_extension_handle s, uint32_t module) +{ + (void)s; + assert(module == SWITCH_MODULE); + if (module_load_fails) + return RV_NO_MEMORY; + module_loaded = 1; + return RV_OK; +} + +static void module_unload(rv_extension_handle s, uint32_t module) +{ + (void)s; + assert(module == SWITCH_MODULE); + module_loaded = 0; +} + +static int asset_open(rv_extension_handle s, const char *name, struct rv_file **file) +{ + (void)s; + assert(!strcmp(name, "classic")); + build_file_at(&classic_asset, "classic", "Classic", RVT_HEADER_BYTES, NULL, 0, NULL, + 0, NULL, NULL); + classic_file = (struct rv_file){classic_asset.bytes, classic_asset.size, 0}; + *file = &classic_file; + open_files++; + return RV_OK; +} + +static const rv_color *canvas_colors; +static int redraws; + +static int ui_set_colors(rv_extension_handle s, const rv_color *colors) +{ + (void)s; + canvas_colors = colors; + return RV_OK; +} + +static void ui_refresh(rv_extension_handle s, const char *screen) +{ + (void)s; + assert(!strcmp(screen, "theme")); +} + +static void ui_redraw(rv_extension_handle s) +{ + (void)s; + redraws++; +} +static const struct rv_asset_provider *core_provider; +static int provider_held; /* another extension has it */ + +static int asset_set_provider(rv_extension_handle s, const struct rv_asset_provider *p) +{ + (void)s; + if (provider_held) + return RV_ALREADY_BOUND; + core_provider = p; + return RV_OK; +} + +static const struct main_service host_service = { + .state = &look_state, + .crc32_update = crc32_update, + .catalog_count = catalog_count, + .catalog_fingerprint = catalog_fingerprint, + .catalog_data = catalog_data, + .catalog_size = catalog_size, + .catalog_crc = catalog_crc, + .catalog_file_offset = catalog_file_offset, + .catalog_layout = catalog_layout, + .style_set = style_set, + .style_reset = style_reset, + .style_set_dark = style_set_dark, + .style_set_accent = style_set_accent, + .tint_refresh = tint_refresh, + .tint_accent_art = tint_accent_art, + .lz_decode = lz_decode, + .assets_reserve = assets_reserve, + .assets_commit = assets_commit, + .assets_drop = assets_drop, +}; + +static const void *module_service(rv_extension_handle s, uint32_t module) +{ + (void)s; + if (module == SWITCH_MODULE) + return module_loaded ? (const void *)&service : NULL; + assert(module == 0); + return &host_service; +} + +static int timers; + +static struct rv_timer *timer_start(rv_extension_handle s, uint32_t ms, int repeat, + void (*callback)(void *arg), void *arg) +{ + (void)s, (void)ms, (void)repeat, (void)callback, (void)arg; + timers++; + return (struct rv_timer *)&timers; +} + +static void timer_stop(rv_extension_handle s, struct rv_timer *timer) +{ + (void)s, (void)timer; + timers--; +} + +static void ui_pane_refresh(rv_extension_handle s) +{ + (void)s; +} +static struct rv_api fake = { + .hook_bind = hook_bind, + .hook_unbind = hook_unbind, + .hook_next = hook_next, + .file_read = file_read, + .file_seek = file_seek, + .file_close = file_close, + .alloc = alloc, + .free = release, + .content_open = content_open, + .content_list = content_list, + .module_service = module_service, + .setting_get_int = setting_get_int, + .setting_set_int = setting_set_int, + .setting_read = setting_read, + .setting_write = setting_write, + .module_load = module_load, + .module_unload = module_unload, + .asset_open = asset_open, + .ui_set_colors = ui_set_colors, + .ui_refresh = ui_refresh, + .ui_redraw = ui_redraw, + .asset_set_provider = asset_set_provider, + .firmware_open = firmware_open, + .timer_start = timer_start, + .timer_stop = timer_stop, + .ui_pane_refresh = ui_pane_refresh, +}; + +static void put16(uint8_t *p, uint32_t v) +{ + p[0] = (uint8_t)v; + p[1] = (uint8_t)(v >> 8); +} + +static void put32(uint8_t *p, uint32_t v) +{ + put16(p, v); + put16(p + 2, v >> 16); +} + +static void bmap(uint8_t *p, uint32_t format, uint32_t stride, uint32_t depth, + uint32_t width, uint32_t height, uint32_t total) +{ + memset(p, 0, total); + put16(p, format); + put16(p + 4, stride); + put16(p + 6, depth); + put32(p + 16, height); + put32(p + 20, width); + put32(p + 24, total - HEADER); +} + +/* Palette entries are BGRA. Bitmap 1 is a light square with a darker icon + * pixel, as a relight expects; bitmap 3 is black and white; bitmap 5 holds + * the stock accent blue. */ +static const uint8_t LIGHT[4] = {247, 244, 240, 255}, ICON[4] = {216, 208, 200, 255}; +static const uint8_t BLACK[4] = {0, 0, 0, 255}, WHITE[4] = {255, 255, 255, 255}; +static const uint8_t BLUE[4] = {197, 108, 35, 255}, GREY[4] = {128, 128, 128, 255}; + +static void build_bank(void) +{ + uint8_t *p = host_bank; + bmap(p, 8, 4, 8, 4, 2, MASK_BYTES); + memcpy(p + HEADER, (uint8_t[]){0, 149, 150, 255, 1, 2, 3, 4}, 8); + p = host_bank + AT_PALETTED; + bmap(p, 0x64, 4, 8, 4, 2, PALETTED_BYTES); + put32(p + HEADER, 2); + memcpy(p + HEADER + 4, LIGHT, 4); + memcpy(p + HEADER + 8, ICON, 4); + memcpy(p + HEADER + 12, (uint8_t[]){0, 0, 1, 0, 0, 1, 1, 0}, 8); + p = host_bank + AT_RGB; + bmap(p, 0x565, 2, 16, 1, 3, RGB_BYTES); + p = host_bank + AT_SECOND; + bmap(p, 0x64, 4, 8, 4, 2, PALETTED_BYTES); + put32(p + HEADER, 2); + memcpy(p + HEADER + 4, BLACK, 4); + memcpy(p + HEADER + 8, WHITE, 4); + memcpy(p + HEADER + 12, (uint8_t[]){0, 1, 0, 1, 1, 0, 1, 0}, 8); + p = host_bank + AT_ARGB; + bmap(p, 0x1888, 16, 32, 4, 2, ARGB_BYTES); + for (unsigned i = 0; i < 8; i++) + memcpy(p + HEADER + i * 4, i % 3 ? WHITE : BLUE, 4); + p[HEADER + 7 * 4 + 3] = 0; /* one clear pixel */ + p = host_bank + AT_WIDE; + bmap(p, 0x64, 4, 8, 4, 2, WIDE_BYTES); + put32(p + HEADER, 4); + memcpy(p + HEADER + 4, BLUE, 4); + memcpy(p + HEADER + 8, GREY, 4); + memcpy(p + HEADER + 12, BLACK, 4); + memcpy(p + HEADER + 16, WHITE, 4); + memcpy(p + HEADER + 20, (uint8_t[]){0, 1, 2, 3, 3, 2, 1, 0}, 8); + memcpy(stock_bank, host_bank, sizeof host_bank); + for (uint32_t i = 0; i < CATALOG_COUNT; i++) + catalog_crcs[i] = + (uint16_t)~crc32_update(0xffffffffu, catalog_data(i), catalog_size(i)); +} + +static void reset_bank(void) +{ + memcpy(host_bank, stock_bank, sizeof host_bank); +} + +static int bank_is_stock(void) +{ + return !memcmp(host_bank, stock_bank, sizeof host_bank); +} + +static uint32_t crc(const void *data, uint32_t size) +{ + return ~crc32_update(0xffffffffu, data, size); +} + +/* An opaque style prefix with the stock light roles and no tints. */ +static void prefix_plain(uint8_t *p) +{ + memset(p, 0, RVT_STYLE_BYTES); + for (unsigned i = 0; i < RVT_ROLES; i++) + memcpy(p + RVT_STYLE_COLORS + i * 4, style_stock_color((enum rvt_role)i), 4); + for (unsigned i = 0; i < RVT_ACCENTS * RVT_ACCENT_SLOTS; i++) + p[RVT_STYLE_PALETTES + i * 4 + 3] = 255; +} + +/* Extension bitmaps appended to every pack written while `asset_table` is set. */ +struct asset_payload { + uint32_t owner, asset, kind, size, decoded; + const uint8_t *payload; + uint32_t tint; +}; +static const struct asset_payload *asset_table; +static uint32_t asset_table_count; + +/* Writes one pack at `pack`; returns the bytes written (header and body). */ +static uint32_t write_pack(uint8_t *pack, const struct rec *recs, uint32_t count, + const uint8_t *tint, const uint8_t *prefix) +{ + uint8_t *body = pack + RVT_PACK_HEADER_BYTES, *p = body; + if (prefix) + memcpy(p, prefix, RVT_STYLE_BYTES); + else + prefix_plain(p); + if (tint) + memcpy(p + RVT_STYLE_TINTS, tint, RVT_CATALOG_MAX); + p += RVT_STYLE_BYTES; + for (uint32_t i = 0; i < count; i++) { + put32(p, recs[i].asset); + put32(p + 4, recs[i].kind); + put32(p + 8, recs[i].size); + p += 12; + memcpy(p, recs[i].payload, recs[i].size); + memset(p + recs[i].size, 0, ALIGNED(recs[i].size) - recs[i].size); + p += ALIGNED(recs[i].size); + } + for (uint32_t i = 0; i < asset_table_count; i++) { + const struct asset_payload *a = asset_table + i; + put32(p, a->owner); + put32(p + 4, a->asset); + put32(p + 8, a->kind); + put32(p + 12, a->size); + put32(p + 16, a->decoded); + put32(p + 20, a->tint); + p += RVT_EXTENSION_BITMAP_BYTES; + memcpy(p, a->payload, a->size); + memset(p + a->size, 0, PAD(a->size)); + p += ALIGNED(a->size); + } + uint32_t body_bytes = (uint32_t)(p - body); + put32(pack + RVT_PACK_BODY_BYTES, body_bytes); + put32(pack + RVT_PACK_RECORDS, count); + put32(pack + RVT_PACK_CRC, crc(body, body_bytes)); + put32(pack + RVT_PACK_EXTENSION_BITMAPS, asset_table_count); + return RVT_PACK_HEADER_BYTES + body_bytes; +} + +/* Recomputes the dark pack's body checksum of a file built without a light + * pack, after a test edited the body. */ +static void resign_dark_pack(struct built *b) +{ + uint8_t *pack = b->bytes + RVT_HEADER_BYTES; + put32(pack + RVT_PACK_CRC, + crc(pack + RVT_PACK_HEADER_BYTES, le32(pack + RVT_PACK_BODY_BYTES))); +} + +static void sign_header(struct built *b) +{ + put32(b->bytes + RVT_HEADER_CRC, 0); + put32(b->bytes + RVT_HEADER_CRC, crc(b->bytes, RVT_HEADER_BYTES)); +} + +/* A theme file: a light pack when `light` is given, then the dark pack, with + * the packs starting at `header_bytes`. */ +static void build_file_at(struct built *b, const char *id, const char *name, + uint32_t header_bytes, const struct rec *light, + uint32_t nlight, const struct rec *dark, uint32_t ndark, + const uint8_t *tint, const uint8_t *prefix) +{ + uint8_t *h = b->bytes; + memset(b, 0, sizeof *b); + memcpy(h + RVT_HEADER_MAGIC, "RVT0", 4); + put16(h + RVT_HEADER_VERSION, RVT_VERSION); + put16(h + RVT_HEADER_HEADER_BYTES, header_bytes); + memcpy(h + RVT_HEADER_FINGERPRINT, fingerprint, RVT_FINGERPRINT_BYTES); + put32(h + RVT_HEADER_APPEARANCES, + RVT_APPEARANCE_DARK | (light ? RVT_APPEARANCE_LIGHT : 0)); + strcpy((char *)h + RVT_HEADER_ID, id); + strcpy((char *)h + RVT_HEADER_NAME, name); + uint32_t at = header_bytes; + if (light) { + uint32_t size = write_pack(h + at, light, nlight, NULL, prefix); + put32(h + RVT_HEADER_LIGHT_OFFSET, at); + put32(h + RVT_HEADER_LIGHT_BYTES, size); + at += size; + } + uint32_t size = write_pack(h + at, dark, ndark, tint, prefix); + put32(h + RVT_HEADER_DARK_OFFSET, at); + put32(h + RVT_HEADER_DARK_BYTES, size); + sign_header(b); + b->size = at + size; +} + +/* A theme file with the light pack only. */ +static void build_light_only(struct built *b, const char *id, const char *name) +{ + uint8_t *h = b->bytes; + memset(b, 0, sizeof *b); + memcpy(h + RVT_HEADER_MAGIC, "RVT0", 4); + put16(h + RVT_HEADER_VERSION, RVT_VERSION); + put16(h + RVT_HEADER_HEADER_BYTES, RVT_HEADER_BYTES); + memcpy(h + RVT_HEADER_FINGERPRINT, fingerprint, RVT_FINGERPRINT_BYTES); + put32(h + RVT_HEADER_APPEARANCES, RVT_APPEARANCE_LIGHT); + strcpy((char *)h + RVT_HEADER_ID, id); + strcpy((char *)h + RVT_HEADER_NAME, name); + uint32_t size = write_pack(h + RVT_HEADER_BYTES, NULL, 0, NULL, NULL); + put32(h + RVT_HEADER_LIGHT_OFFSET, RVT_HEADER_BYTES); + put32(h + RVT_HEADER_LIGHT_BYTES, size); + sign_header(b); + b->size = RVT_HEADER_BYTES + size; +} + +static void build_file(struct built *b, const struct rec *light, uint32_t nlight, + const struct rec *dark, uint32_t ndark, const uint8_t *tint) +{ + build_file_at(b, "test", "Test", RVT_HEADER_BYTES, light, nlight, dark, ndark, tint, + NULL); +} + +static void build(struct built *b, const struct rec *dark, uint32_t ndark, + const uint8_t *tint) +{ + build_file(b, NULL, 0, dark, ndark, tint); +} + +static void build_theme(struct built *b, const char *id, const char *name) +{ + build_file_at(b, id, name, RVT_HEADER_BYTES, NULL, 0, NULL, 0, NULL, NULL); +} + +static uint32_t record_at(uint32_t i) +{ + return RVT_HEADER_BYTES + RVT_PACK_HEADER_BYTES + RVT_STYLE_BYTES + i; +} + +static const uint32_t none[BITMAP_WORDS]; +static const struct look TEST_LOOK = {.id = "test", .dark = 1}; + +/* As main and the switch read a file: the header checked and the dark pack + * placed by main, opened and applied by the switch. */ +static int apply_from(struct built *b, uint32_t *assets, const uint32_t *current) +{ + struct rv_file file = {b->bytes, b->size, 0}; + struct look look = TEST_LOOK; + struct pack_place place; + struct pack pack; + memset(assets, 0, BITMAP_WORDS * 4); + stock_open(); + int ok = look_pack_place(&file, &look, &place) && + pack_open(&file, look.header_crc, &place, &pack) && + pack_apply(&pack, assets, current ? current : none); + stock_close(); + /* As the switch does with the index the pack filled. */ + if (ok) + assets_commit(); + else + assets_reserve(0); + assert(allocations == (live_count ? 1 : 0)); + return ok; +} + +/* A switch of `look` to the file `b`, placed as main places it. */ +static enum switch_result switch_to(struct built *b, struct look *look) +{ + struct rv_file file = {b->bytes, b->size, 0}; + struct pack_place place; + if (!look_pack_place(&file, look, &place)) + return SWITCH_LOAD_FAILED; + return switch_apply(&file, look, &place); +} + +static int apply(struct built *b, uint32_t *assets) +{ + return apply_from(b, assets, NULL); +} + +static struct rec pixels(uint32_t asset, const uint8_t *payload) +{ + struct layout l; + assert(catalog_layout(asset, &l)); + return (struct rec){asset, RVT_KIND_PIXELS, catalog_size(asset) - l.start, payload}; +} + +static uint32_t at_data(uint32_t asset) +{ + struct layout l; + assert(catalog_layout(asset, &l)); + return l.start; +} + +/* Relight vectors from the themes compiler's reference arithmetic + * (rvt/derive.py), pinned: a bitmap's bytes after the header in the WIDE or + * PALETTED layout, the rule, and what the iPod must produce. */ +static const uint8_t wide_plain_in[] = {4, 0, 0, 0, 230, 236, 240, 255, 70, 80, + 90, 255, 150, 160, 170, 255, 255, 255, 255, 255, + 0, 1, 2, 1, 0, 2, 3, 0}; +static const int32_t wide_plain_rule[RVT_RELIGHT_WORDS] = { + 768, 15360, 25600, 60416, 256, 25600, 25856, 26112, 0, 128, 26112, 26368}; +static const uint8_t wide_plain_out[] = { + 4, 0, 0, 0, 100, 100, 100, 255, 101, 101, 101, 255, 102, 102, + 102, 255, 103, 103, 103, 255, 0, 2, 2, 2, 0, 3, 1, 0}; +/* A partly covered pixel without a fully covered neighbour is pruned. */ +static const uint8_t wide_shadow_in[] = {4, 0, 0, 0, 250, 250, 250, 255, 0, 0, + 0, 255, 242, 242, 242, 255, 200, 200, 200, 255, + 0, 2, 0, 0, 0, 0, 0, 1}; +static const int32_t wide_shadow_rule[RVT_RELIGHT_WORDS] = { + 512, 10240, 40960, 64000, 256, 38400, 38656, 35840, 40, -256, 38912, 39168}; +static const uint8_t wide_shadow_out[] = {4, 0, 0, 0, 151, 151, 151, 255, 152, 152, + 152, 255, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 1}; +static const uint8_t paletted_two_in[] = {2, 0, 0, 0, 240, 244, 247, 255, 200, 208, + 216, 255, 0, 0, 1, 0, 0, 1, 1, 0}; +static const int32_t paletted_two_rule[RVT_RELIGHT_WORDS] = { + 768, 3584, 6400, 55296, 91, 6144, 6144, 101018, -300, -453, 6400, 6400}; +static const uint8_t paletted_two_out[] = {2, 0, 0, 0, 24, 24, 24, 255, 25, 25, + 25, 255, 0, 0, 1, 0, 0, 1, 1, 0}; + +static void expect_relight(uint32_t asset, const uint8_t *in, const int32_t *rule, + const uint8_t *out) +{ + struct built b; + uint32_t assets[BITMAP_WORDS], + at = (uint32_t)(catalog_data(asset) - host_bank) + HEADER; + uint32_t size = catalog_size(asset) - HEADER; + uint8_t kept[WIDE_BYTES]; + memcpy(kept, stock_bank + at, size); + memcpy(stock_bank + at, in, size); + reset_bank(); + catalog_crcs[asset] = + (uint16_t)~crc32_update(0xffffffffu, catalog_data(asset), catalog_size(asset)); + struct rec relight = {asset, RVT_KIND_RELIGHT, RVT_RELIGHT_BYTES, + (const uint8_t *)rule}; + build(&b, &relight, 1, NULL); + assert(apply(&b, assets) && !memcmp(catalog_data(asset) + HEADER, out, size)); + memcpy(stock_bank + at, kept, size); + reset_bank(); + catalog_crcs[asset] = + (uint16_t)~crc32_update(0xffffffffu, catalog_data(asset), catalog_size(asset)); +} + +static void reader_contracts(void) +{ + uint32_t assets[BITMAP_WORDS]; + struct built b; + struct look look; + struct pack_place place; + struct rv_file file, *opened; + char provided_id[RVT_ID_BYTES] = PROVIDED_ID; + + /* An empty pack is a valid theme, and the header reader sees its name. */ + build(&b, NULL, 0, NULL); + provided = &b; + assert(theme_open(provided_id, 1, &opened, &look, &place) == THEME_OK && + !strcmp(look.name, "Test") && look.appearances == RVT_APPEARANCE_DARK && + place.offset == RVT_HEADER_BYTES && + place.bytes == b.size - RVT_HEADER_BYTES); + file_close(NULL, opened); + provided = NULL; + assert(apply(&b, assets)); + + /* A record replaces exactly the bytes after the header, and after the + * colour count of a paletted bitmap; palette indices are checked. */ + uint8_t mask[4 * 2] = {1, 2, 3, 4, 5, 6, 7, 8}; + uint8_t paletted[2 * 4 + 4 * 2] = {9, 9, 9, 255, 8, 8, 8, 255, + 0, 1, 0, 1, 1, 0, 1, 0}; + struct rec two[2] = {pixels(MASK, mask), pixels(PALETTED, paletted)}; + build(&b, two, 2, NULL); + assert(apply(&b, assets) && bit_test(assets, 0) && bit_test(assets, 1) && + !bit_test(assets, 2)); + assert(!memcmp(catalog_data(MASK) + HEADER, mask, sizeof mask)); + assert(!memcmp(catalog_data(PALETTED) + HEADER + 4, paletted, sizeof paletted)); + paletted[8] = 2; /* an index past the two colours */ + build(&b, two, 2, NULL); + assert(!apply(&b, assets)); + assert(catalog_data(PALETTED)[HEADER + 4 + 8] == + 0); /* zeroed, never left half written */ + paletted[8] = 0; + reset_bank(); + + /* Records out of order, repeated, naming a size that is not the bitmap's + * or an unknown kind are refused. */ + struct rec reversed[2] = {pixels(PALETTED, paletted), pixels(MASK, mask)}; + build(&b, reversed, 2, NULL); + assert(!apply(&b, assets)); + build(&b, two, 2, NULL); + put32(b.bytes + record_at(8), sizeof mask + 4); + assert(!apply(&b, assets)); + struct rec unknown = {MASK, RVT_KINDS, sizeof mask, mask}; + build(&b, &unknown, 1, NULL); + assert(!apply(&b, assets)); + + /* The body checksum, the header checksum, the fingerprint and the magic + * each guard the file. */ + build(&b, two, 2, NULL); + b.bytes[b.size - 1] ^= 1; + assert(!apply(&b, assets)); + build(&b, two, 2, NULL); + b.bytes[RVT_HEADER_NAME] = 'U'; + file = (struct rv_file){b.bytes, b.size, 0}; + look = TEST_LOOK; + assert(!look_pack_place(&file, &look, &place)); + build(&b, two, 2, NULL); + b.bytes[RVT_HEADER_FINGERPRINT] ^= 1; + sign_header(&b); + assert(!apply(&b, assets)); + build(&b, two, 2, NULL); + b.bytes[RVT_HEADER_MAGIC] = 'X'; + sign_header(&b); + assert(!apply(&b, assets)); + /* Exactly the format version; another id than the file name's. */ + build(&b, two, 2, NULL); + put16(b.bytes + RVT_HEADER_VERSION, RVT_VERSION + 1); + sign_header(&b); + assert(!apply(&b, assets)); + put16(b.bytes + RVT_HEADER_VERSION, RVT_VERSION - 1); + sign_header(&b); + assert(!apply(&b, assets)); + build_file_at(&b, "other", "Test", RVT_HEADER_BYTES, NULL, 0, two, 2, NULL, NULL); + assert(!apply(&b, assets)); + reset_bank(); + + /* The packs start at the header's own size, a whole number of words: a + * pack before it is refused, one after a larger header is read; the + * switch sees the file main checked by its header checksum. */ + build(&b, two, 2, NULL); + put16(b.bytes + RVT_HEADER_HEADER_BYTES, RVT_HEADER_BYTES + 4); + sign_header(&b); + assert(!apply(&b, assets)); + build_file_at(&b, "test", "Test", RVT_HEADER_BYTES + 8, NULL, 0, two, 2, NULL, + NULL); + assert(apply(&b, assets) && + !memcmp(catalog_data(MASK) + HEADER, mask, sizeof mask)); + build_file_at(&b, "test", "Test", RVT_HEADER_BYTES - 4, NULL, 0, two, 2, NULL, + NULL); + assert(!apply(&b, assets)); + build_file_at(&b, "test", "Test", RVT_HEADER_BYTES + 2, NULL, 0, two, 2, NULL, + NULL); + assert(!apply(&b, assets)); + build(&b, two, 2, NULL); + file = (struct rv_file){b.bytes, b.size, 0}; + look = TEST_LOOK; + assert(look_pack_place(&file, &look, &place)); + { + struct pack pack; + assert(!pack_open(&file, look.header_crc ^ 1, &place, &pack)); + assert(pack_open(&file, look.header_crc, &place, &pack) && pack.count == 2); + } + reset_bank(); + + /* Ids and names: lower-case ASCII ids that are not the built-in's, + * printable UTF-8 names. */ + static const char *const good_ids[] = {"a", "example", "a-b_c9", + "0123456789012345678901234567890"}; + static const char *const bad_ids[] = { + "", "Example", "-a", "a b", "classic", "01234567890123456789012345678901"}; + char id[RVT_ID_BYTES]; + for (unsigned i = 0; i < sizeof good_ids / sizeof *good_ids; i++) { + memset(id, 0, sizeof id); + strcpy(id, good_ids[i]); + assert(id_valid(id)); + } + for (unsigned i = 0; i < sizeof bad_ids / sizeof *bad_ids; i++) { + memset(id, 0, sizeof id); + memcpy(id, bad_ids[i], + strlen(bad_ids[i]) < sizeof id ? strlen(bad_ids[i]) : sizeof id); + assert(!id_valid(id)); + } + uint8_t name[RVT_NAME_BYTES] = "Caf\xc3\xa9"; + assert(name_valid(name, sizeof name)); + name[5] = 1; /* a control character after the NUL is not zero padding */ + assert(!name_valid(name, sizeof name)); + name[5] = 0; + name[0] = 0x7f; + assert(!name_valid(name, sizeof name)); + name[0] = 0; + assert(!name_valid(name, sizeof name)); + memset(name, 'a', sizeof name); /* no NUL inside the field */ + assert(!name_valid(name, sizeof name)); + memcpy(name, "\xed\xa0\x80\0", 4); /* a surrogate */ + assert(!name_valid(name, sizeof name)); + + /* A style with a tint byte outside the roles or on a bitmap past the + * catalog, or a clear colour, is refused before anything is written. */ + uint8_t tint[RVT_CATALOG_MAX] = {0}; + tint[MASK] = RVT_TINT_ROLE + RVT_ROLES; + build(&b, NULL, 0, tint); + assert(!apply(&b, assets)); + tint[MASK] = 0; + tint[CATALOG_COUNT] = RVT_TINT_ROLE + RVT_ROLE_TEXT; + build(&b, NULL, 0, tint); + assert(!apply(&b, assets)); + tint[CATALOG_COUNT] = 0; + build(&b, NULL, 0, NULL); + b.bytes[RVT_HEADER_BYTES + RVT_PACK_HEADER_BYTES + RVT_STYLE_COLORS + 3] = 0; + assert(!apply(&b, assets)); + + /* A tinted mask needs no record. A tinted paletted asset without one is + * tinted stock art: with darkness coverage its alpha follows its luma. */ + tint[MASK] = RVT_TINT_ROLE + RVT_ROLE_TEXT; + build(&b, NULL, 0, tint); + assert(apply(&b, assets) && !bit_test(assets, MASK)); + tint[MASK] = 0; + tint[SECOND] = (RVT_TINT_ROLE + RVT_ROLE_ICON_TINT) | RVT_TINT_DARKNESS; + build(&b, NULL, 0, tint); + assert(apply(&b, assets) && bit_test(assets, SECOND)); + assert(catalog_data(SECOND)[at_data(SECOND) + 3] == 255 && + catalog_data(SECOND)[at_data(SECOND) + 7] == 0); + reset_bank(); + tint[SECOND] = RVT_TINT_ROLE + RVT_ROLE_ICON_TINT; + build(&b, NULL, 0, tint); + assert(apply(&b, assets) && + !memcmp(catalog_data(SECOND) + at_data(SECOND), BLACK, 4)); + tint[SECOND] = RVT_TINT_DARKNESS; /* darkness without a tint */ + build(&b, NULL, 0, tint); + assert(!apply(&b, assets)); + tint[SECOND] = 0; + + /* Solid coverage rewrites a mask's stock levels: full from the floor up, + * the rest kept; on a palette it rounds the alpha the same way. Both + * coverage bits together are invalid. */ + tint[MASK] = (RVT_TINT_ROLE + RVT_ROLE_TEXT) | RVT_TINT_SOLID; + build(&b, NULL, 0, tint); + assert(apply(&b, assets) && bit_test(assets, MASK)); + assert(!memcmp(catalog_data(MASK) + HEADER, + (uint8_t[]){0, 149, 255, 255, 1, 2, 3, 4}, 8)); + reset_bank(); + tint[MASK] = (RVT_TINT_ROLE + RVT_ROLE_TEXT) | RVT_TINT_SOLID | RVT_TINT_DARKNESS; + build(&b, NULL, 0, tint); + assert(!apply(&b, assets)); + tint[MASK] = 0; + tint[PALETTED] = (RVT_TINT_ROLE + RVT_ROLE_TEXT) | RVT_TINT_SOLID; + build(&b, NULL, 0, tint); + assert(apply(&b, assets) && bit_test(assets, PALETTED)); + assert(catalog_data(PALETTED)[at_data(PALETTED) + 3] == 255 && + catalog_data(PALETTED)[at_data(PALETTED) + 7] == 255); + reset_bank(); + tint[PALETTED] = 0; + + /* Recolour: a swap is two lookups against the stock colours, not a chain; + * RGB565 colours must be exact; ARGB pixels are keyed like palette + * entries, clear ones included; the count must match the payload and stay + * within RVT_RECOLOR_MAX. */ + uint8_t swap[4 + 16] = {2, 0, 0, 0, 0, 0, 0, 255, 255, 255, + 255, 255, 255, 255, 255, 255, 0, 0, 0, 255}; + struct rec recolor = {SECOND, RVT_KIND_RECOLOR, sizeof swap, swap}; + build(&b, &recolor, 1, NULL); + assert(apply(&b, assets) && bit_test(assets, SECOND)); + assert(!memcmp(catalog_data(SECOND) + at_data(SECOND), WHITE, 4) && + !memcmp(catalog_data(SECOND) + at_data(SECOND) + 4, BLACK, 4)); + reset_bank(); + uint8_t unsorted[4 + 16]; + memcpy(unsorted, swap, sizeof swap); + memcpy(unsorted + 4, swap + 12, 8); + memcpy(unsorted + 12, swap + 4, 8); + recolor.payload = unsorted; + build(&b, &recolor, 1, NULL); + assert(!apply(&b, assets)); + uint8_t rgb_pair[4 + 8] = {1, 0, 0, 0, 0, 0, 0, 255, 0x18, 0x20, 0x29, 255}; + struct rec rgb = {RGB, RVT_KIND_RECOLOR, sizeof rgb_pair, rgb_pair}; + build(&b, &rgb, 1, NULL); + assert(!apply(&b, assets)); + rgb_pair[8] = 0xf8, rgb_pair[9] = 0, rgb_pair[10] = 0; + build(&b, &rgb, 1, NULL); + assert(apply(&b, assets) && catalog_data(RGB)[HEADER] == 0 && + catalog_data(RGB)[HEADER + 1] == 0xf8 && + catalog_data(RGB)[HEADER + 5] == 0xf8); + reset_bank(); + struct rec recolor_mask = {MASK, RVT_KIND_RECOLOR, sizeof swap, swap}; + build(&b, &recolor_mask, 1, NULL); + assert(!apply(&b, assets)); + uint8_t blue_to_red[4 + 8] = {1, 0, 0, 0, 35, 108, 197, 255, 200, 0, 0, 255}; + struct rec recolor_argb = {ARGB, RVT_KIND_RECOLOR, sizeof blue_to_red, blue_to_red}; + build(&b, &recolor_argb, 1, NULL); + assert(apply(&b, assets)); + assert(!memcmp(catalog_data(ARGB) + HEADER, (uint8_t[]){0, 0, 200, 255}, 4) && + !memcmp(catalog_data(ARGB) + HEADER + 4, WHITE, 4) && + !memcmp(catalog_data(ARGB) + HEADER + 12, (uint8_t[]){0, 0, 200, 255}, 4)); + reset_bank(); + static uint8_t many[4 + (RVT_RECOLOR_MAX + 1) * 8]; + put32(many, RVT_RECOLOR_MAX + 1); + for (uint32_t i = 0; i <= RVT_RECOLOR_MAX; i++) { + put32(many + 4 + i * 8, i); + put32(many + 8 + i * 8, i + 0x1000000u); + } + struct rec too_many = {ARGB, RVT_KIND_RECOLOR, sizeof many, many}; + build(&b, &too_many, 1, NULL); + assert(!apply(&b, assets)); + put32(many, RVT_RECOLOR_MAX); + struct rec miscounted = {ARGB, RVT_KIND_RECOLOR, sizeof many, many}; + build(&b, &miscounted, 1, NULL); + assert(!apply(&b, assets)); /* pairs != (size - 4) / 8 */ + uint8_t wrapped[4 + 16]; + memcpy(wrapped, swap, sizeof swap); + put32(wrapped, + 2 + (1u << 29)); /* a count whose times eight wraps to the payload size */ + struct rec wrapped_count = {SECOND, RVT_KIND_RECOLOR, sizeof wrapped, wrapped}; + build(&b, &wrapped_count, 1, NULL); + assert(!apply(&b, assets)); + struct rec max_pairs = {ARGB, RVT_KIND_RECOLOR, sizeof many - 8, many}; + build(&b, &max_pairs, 1, NULL); + assert(apply(&b, assets)); /* a shared map may name colours the bitmap lacks */ + reset_bank(); + + /* Invert keeps alpha, also on ARGB and RGB565; a mask cannot be inverted. */ + struct rec invert = {SECOND, RVT_KIND_INVERT, 0, NULL}; + build(&b, &invert, 1, NULL); + assert(apply(&b, assets) && + !memcmp(catalog_data(SECOND) + at_data(SECOND), WHITE, 4)); + reset_bank(); + struct rec invert_argb = {ARGB, RVT_KIND_INVERT, 0, NULL}; + build(&b, &invert_argb, 1, NULL); + assert(apply(&b, assets)); + assert(!memcmp(catalog_data(ARGB) + HEADER, (uint8_t[]){58, 147, 220, 255}, 4) && + !memcmp(catalog_data(ARGB) + HEADER + 4, (uint8_t[]){0, 0, 0, 255}, 4) && + !memcmp(catalog_data(ARGB) + HEADER + 28, (uint8_t[]){255, 255, 255, 0}, 4)); + reset_bank(); + uint8_t rgb_stock[6]; + memcpy(rgb_stock, stock_bank + AT_RGB + HEADER, 6); + memcpy(catalog_data(RGB) + HEADER, (uint8_t[]){0x00, 0xf8, 0xe0, 0x07, 0x1f, 0x00}, + 6); + memcpy(stock_bank + AT_RGB + HEADER, catalog_data(RGB) + HEADER, 6); + catalog_crcs[RGB] = + (uint16_t)~crc32_update(0xffffffffu, catalog_data(RGB), catalog_size(RGB)); + struct rec invert_rgb = {RGB, RVT_KIND_INVERT, 0, NULL}; + build(&b, &invert_rgb, 1, NULL); + assert(apply(&b, assets)); + assert(!memcmp(catalog_data(RGB) + HEADER, + (uint8_t[]){0xff, 0x07, 0x1f, 0xf8, 0xe0, 0xff}, 6)); + memcpy(stock_bank + AT_RGB + HEADER, rgb_stock, 6); + reset_bank(); + catalog_crcs[RGB] = + (uint16_t)~crc32_update(0xffffffffu, catalog_data(RGB), catalog_size(RGB)); + struct rec invert_mask = {MASK, RVT_KIND_INVERT, 0, NULL}; + build(&b, &invert_mask, 1, NULL); + assert(!apply(&b, assets)); + + /* Relight: the background rows take bg gray, the icon pixel icon gray, and + * the palette is rebuilt in ascending order; a rule the palette cannot + * hold, or with words outside their bounds, is refused. */ + int32_t rule[RVT_RELIGHT_WORDS] = { + 3 * 256, 14 * 256, 25 * 256, 216 * 256, 91, 24 * 256, + 24 * 256, 101018, -300, -453, 25 * 256, 25 * 256, + }; + struct rec relight = {PALETTED, RVT_KIND_RELIGHT, sizeof rule, + (const uint8_t *)rule}; + build(&b, &relight, 1, NULL); + assert(apply(&b, assets) && bit_test(assets, PALETTED)); + assert(catalog_data(PALETTED)[at_data(PALETTED)] == 24 && + catalog_data(PALETTED)[at_data(PALETTED) + 4] == 25); + assert(!memcmp(catalog_data(PALETTED) + HEADER + 12, + (uint8_t[]){0, 0, 1, 0, 0, 1, 1, 0}, 8)); + reset_bank(); + rule[RVT_RELIGHT_ICON_HI] = 26 * 256; + build(&b, &relight, 1, NULL); + assert(!apply(&b, assets)); + rule[RVT_RELIGHT_ICON_HI] = 25 * 256; + + static const struct { + unsigned word; + int32_t value; + } out_of_bounds[] = { + {RVT_RELIGHT_T_ZERO, -1}, {RVT_RELIGHT_T_FULL, 256 * 256}, + {RVT_RELIGHT_BG_BASE, 1025 * 256}, {RVT_RELIGHT_BG_REF, -256 * 256}, + {RVT_RELIGHT_BG_SLOPE, 17 * 256}, {RVT_RELIGHT_ICON_BASE, -1025 * 256}, + {RVT_RELIGHT_ICON_LUMA, 256 * 256}, {RVT_RELIGHT_ICON_ROW, -256 * 256}, + }; + + for (unsigned i = 0; i < sizeof out_of_bounds / sizeof *out_of_bounds; i++) { + int32_t kept = rule[out_of_bounds[i].word]; + rule[out_of_bounds[i].word] = out_of_bounds[i].value; + build(&b, &relight, 1, NULL); + assert(!apply(&b, assets)); + rule[out_of_bounds[i].word] = kept; + } + struct rec relight_rgb = {RGB, RVT_KIND_RELIGHT, sizeof rule, + (const uint8_t *)rule}; + build(&b, &relight_rgb, 1, NULL); + assert(!apply(&b, assets)); + expect_relight(WIDE, wide_plain_in, wide_plain_rule, wide_plain_out); + expect_relight(WIDE, wide_shadow_in, wide_shadow_rule, wide_shadow_out); + expect_relight(PALETTED, paletted_two_in, paletted_two_rule, paletted_two_out); + /* Shadow pruning: a partly covered pixel with no fully covered neighbour + * becomes background. Bitmap 5's third colour is black, far past k; the + * shade at (1, 0), offset 8 from the row's background, has no full + * neighbour and is dropped; the same shade at (3, 0) touches the black + * pixel at (3, 1) and stays a mid gray. */ + uint8_t *wide = catalog_data(WIDE) + at_data(WIDE), wide_stock[24]; + memcpy(wide_stock, wide, 24); + memcpy(wide, LIGHT, 4); + memcpy(wide + 4, (uint8_t[]){239, 236, 232, 255}, 4); + memcpy(wide + 8, BLACK, 4); + memcpy(wide + 12, LIGHT, 4); + memcpy(wide + 16, (uint8_t[]){0, 1, 0, 1, 0, 0, 0, 2}, 8); + memcpy(stock_bank + AT_WIDE + at_data(WIDE), wide, 24); + catalog_crcs[WIDE] = + (uint16_t)~crc32_update(0xffffffffu, catalog_data(WIDE), catalog_size(WIDE)); + int32_t wide_rule[RVT_RELIGHT_WORDS] = { + 3 * 256, 14 * 256, 25 * 256, 216 * 256, 91, 24 * 256, + 24 * 256, 27 * 256, 0, 0, 27 * 256, 27 * 256, + }; + struct rec relight_wide = {WIDE, RVT_KIND_RELIGHT, sizeof wide_rule, + (const uint8_t *)wide_rule}; + build(&b, &relight_wide, 1, NULL); + assert(apply(&b, assets)); + { + const uint8_t *rows = catalog_data(WIDE) + at_data(WIDE) + 16; + const uint8_t *palette = catalog_data(WIDE) + at_data(WIDE); + assert(palette[rows[1] * 4] == 24); /* pruned to the background gray */ + assert(palette[rows[7] * 4] == 27); /* the black pixel, fully covered */ + assert(palette[rows[3] * 4] == 25); /* kept and blended */ + assert(!memcmp( + palette, + (uint8_t[]){24, 24, 24, 255, 25, 25, 25, 255, 27, 27, 27, 255, 0, 0, 0, 0}, + 16)); + } + memcpy(stock_bank + AT_WIDE + at_data(WIDE), wide_stock, 24); + reset_bank(); + catalog_crcs[WIDE] = + (uint16_t)~crc32_update(0xffffffffu, catalog_data(WIDE), catalog_size(WIDE)); + + /* Alias: applied after the other records, so a source with a higher index + * is final; a chain, a self alias, a different size and a tinted source + * are refused; a source of another layout is re-encoded when the palette + * has room. */ + uint32_t three = SECOND; + struct rec alias_up[2] = {{PALETTED, RVT_KIND_ALIAS, 4, (const uint8_t *)&three}, + invert}; + build(&b, alias_up, 2, NULL); + assert(apply(&b, assets) && !memcmp(catalog_data(PALETTED) + at_data(PALETTED), + catalog_data(SECOND) + at_data(SECOND), + PALETTED_BYTES - HEADER - 4)); + assert(!memcmp(catalog_data(PALETTED) + at_data(PALETTED), WHITE, 4)); + reset_bank(); + uint32_t one = PALETTED; + struct rec chain[2] = {{PALETTED, RVT_KIND_ALIAS, 4, (const uint8_t *)&three}, + {SECOND, RVT_KIND_ALIAS, 4, (const uint8_t *)&one}}; + build(&b, chain, 2, NULL); + assert(!apply(&b, assets)); + struct rec self_alias = {PALETTED, RVT_KIND_ALIAS, 4, (const uint8_t *)&one}; + build(&b, &self_alias, 1, NULL); + assert(!apply(&b, assets)); + uint32_t two_ = RGB; + struct rec wrong_size = {PALETTED, RVT_KIND_ALIAS, 4, (const uint8_t *)&two_}; + build(&b, &wrong_size, 1, NULL); + assert(!apply(&b, assets)); + tint[SECOND] = RVT_TINT_ROLE + RVT_ROLE_ICON_TINT; + build(&b, alias_up, 1, tint); + assert(!apply(&b, assets)); + tint[SECOND] = 0; + uint32_t four = ARGB, five = WIDE; + struct rec argb_into_wide = {WIDE, RVT_KIND_ALIAS, 4, (const uint8_t *)&four}; + build(&b, &argb_into_wide, 1, NULL); + assert(apply(&b, assets)); /* blue, white and clear white: three of four entries */ + assert( + !memcmp(catalog_data(WIDE) + at_data(WIDE), BLUE, 4) && + !memcmp(catalog_data(WIDE) + at_data(WIDE) + 4, WHITE, 4) && + !memcmp(catalog_data(WIDE) + at_data(WIDE) + 8, (uint8_t[]){255, 255, 255, 0}, + 4) && + !memcmp(catalog_data(WIDE) + at_data(WIDE) + 12, (uint8_t[]){0, 0, 0, 0}, 4) && + !memcmp(catalog_data(WIDE) + at_data(WIDE) + 16, + (uint8_t[]){0, 1, 1, 0, 1, 1, 0, 2}, 8)); + reset_bank(); + struct rec wide_into_argb = {ARGB, RVT_KIND_ALIAS, 4, (const uint8_t *)&five}; + build(&b, &wide_into_argb, 1, NULL); + assert(apply(&b, assets)); + assert(!memcmp(catalog_data(ARGB) + HEADER, BLUE, 4) && + !memcmp(catalog_data(ARGB) + HEADER + 4, GREY, 4) && + !memcmp(catalog_data(ARGB) + HEADER + 28, BLUE, 4)); + reset_bank(); + struct rec wide_into_paletted = {PALETTED, RVT_KIND_ALIAS, 4, + (const uint8_t *)&five}; + build(&b, &wide_into_paletted, 1, NULL); + assert(!apply(&b, assets)); /* four colours into two entries */ + assert(catalog_data(PALETTED)[at_data(PALETTED)] == 0); + reset_bank(); + + /* A derived record on a bitmap the active look changed fetches stock first; + * one the look left alone is derived in place. */ + uint32_t current[BITMAP_WORDS] = {0}; + bit_set(current, SECOND); + memset(catalog_data(SECOND) + at_data(SECOND), 0x55, 8); + opens = 0; + build(&b, &invert, 1, NULL); + assert(apply_from(&b, assets, current) && opens == 1); + assert(!memcmp(catalog_data(SECOND) + at_data(SECOND), WHITE, 4)); + reset_bank(); + memset(current, 0, sizeof current); + + /* A tint on a derived record is refused. */ + tint[SECOND] = RVT_TINT_ROLE + RVT_ROLE_ICON_TINT; + build(&b, &invert, 1, tint); + assert(!apply(&b, assets)); + tint[SECOND] = 0; + + /* Compressed pixels decode straight into the bitmap: a literal group, + * then a match; a long match extends its length; the stream must end + * where the bitmap is full and must not end before. */ + static const uint8_t lz_paletted[14] = {0x00, 9, 9, 9, 255, 8, 8, + 8, 255, 0x04, 0, 1, 0x30, 0x01}; + struct rec lz = {PALETTED, RVT_KIND_PIXELS_LZ, sizeof lz_paletted, lz_paletted}; + build(&b, &lz, 1, NULL); + assert(apply(&b, assets) && bit_test(assets, PALETTED)); + assert(!memcmp(catalog_data(PALETTED) + at_data(PALETTED), + (uint8_t[]){9, 9, 9, 255, 8, 8, 8, 255, 0, 1, 0, 1, 0, 1, 0, 1}, + 16)); + reset_bank(); + static const uint8_t lz_zeros[5] = {0x02, 0, 0xf0, 0x00, 0x0d}; + struct rec lz_argb = {ARGB, RVT_KIND_PIXELS_LZ, sizeof lz_zeros, lz_zeros}; + build(&b, &lz_argb, 1, NULL); + assert(apply(&b, assets)); + for (unsigned i = 0; i < 32; i++) + assert(catalog_data(ARGB)[HEADER + i] == 0); + reset_bank(); + struct rec lz_short = {PALETTED, RVT_KIND_PIXELS_LZ, sizeof lz_paletted - 1, + lz_paletted}; + build(&b, &lz_short, 1, NULL); + assert(!apply(&b, assets) && catalog_data(PALETTED)[at_data(PALETTED)] == 0); + reset_bank(); + static uint8_t lz_long[15]; + memcpy(lz_long, lz_paletted, 14); + struct rec lz_trailing = {PALETTED, RVT_KIND_PIXELS_LZ, sizeof lz_long, lz_long}; + build(&b, &lz_trailing, 1, NULL); + assert(!apply(&b, assets) && catalog_data(PALETTED)[at_data(PALETTED)] == 0); + reset_bank(); + static const uint8_t lz_backwards[3] = {0x01, 0x00, 0x05}; + struct rec lz_before = {PALETTED, RVT_KIND_PIXELS_LZ, sizeof lz_backwards, + lz_backwards}; + build(&b, &lz_before, 1, NULL); + assert(!apply(&b, assets)); + static const uint8_t lz_overrun[4] = {0x02, 0, 0xf0, + 0x00}; /* 18 more bytes than the 16 */ + struct rec lz_over = {PALETTED, RVT_KIND_PIXELS_LZ, sizeof lz_overrun, lz_overrun}; + build(&b, &lz_over, 1, NULL); + assert(!apply(&b, assets)); + struct rec lz_empty = {PALETTED, RVT_KIND_PIXELS_LZ, 0, lz_paletted}; + build(&b, &lz_empty, 1, NULL); + assert(!apply(&b, assets)); + reset_bank(); + /* A paletted record's indices are checked after decoding. */ + static const uint8_t lz_bad_index[14] = {0x00, 9, 9, 9, 255, 8, 8, + 8, 255, 0x04, 0, 2, 0x30, 0x01}; + struct rec lz_bad = {PALETTED, RVT_KIND_PIXELS_LZ, sizeof lz_bad_index, + lz_bad_index}; + build(&b, &lz_bad, 1, NULL); + assert(!apply(&b, assets) && catalog_data(PALETTED)[at_data(PALETTED)] == 0); + reset_bank(); + + /* A truncated file fails on the record it cuts; what it wrote before + * stays marked for the switch to restore. */ + build(&b, two, 2, NULL); + b.size -= 8; + assert(!apply(&b, assets) && bit_test(assets, MASK) && bit_test(assets, PALETTED)); + assert(!memcmp(catalog_data(MASK) + HEADER, mask, sizeof mask)); + assert(catalog_data(PALETTED)[at_data(PALETTED)] == 0); + reset_bank(); + + /* The CRC-32 vector. */ + assert(crc("123456789", 9) == 0xcbf43926u); +} + +/* The switch module over the host firmware file: what a switch leaves in the + * bank, in the state and in the style, and how it comes back from damage. */ +static void switch_contracts(void) +{ + struct built b; + struct look theme = { + .id = "test", .name = "Test", .appearances = RVT_APPEARANCE_DARK, .dark = 1}; + struct look stock = {0}; + uint8_t mask[4 * 2] = {1, 2, 3, 4, 5, 6, 7, 8}; + uint8_t paletted[2 * 4 + 4 * 2] = {9, 9, 9, 255, 8, 8, 8, 255, + 0, 1, 0, 1, 1, 0, 1, 0}; + struct rec two[2] = {pixels(MASK, mask), pixels(PALETTED, paletted)}; + memset(&look_state, 0, sizeof look_state); + style_reset(); + style_set_dark(0); + style_set_accent(ACCENT_DEFAULT); + + /* A theme goes on and comes off; the firmware file is checked once. */ + build(&b, two, 2, NULL); + opens = closes = 0; + assert(switch_to(&b, &theme) == SWITCH_OK); + assert(opens == 2 && closes == 2 && + look_state.stock_checked); /* the check, then the switch */ + assert(!strcmp(look_state.active.id, "test") && look_state.active.dark && + style_from_theme() && style_dark()); + assert(bit_test(look_state.assets, MASK) && bit_test(look_state.assets, PALETTED)); + /* Under a theme the stock accent art follows the theme's accent fill. */ + assert(bit_test(look_state.assets, WIDE) && bit_test(look_state.accented, WIDE)); + assert( + !memcmp(catalog_data(WIDE) + at_data(WIDE), (uint8_t[]){197, 108, 35, 255}, 4)); + assert(!memcmp(catalog_data(MASK) + HEADER, mask, sizeof mask)); + assert(switch_apply(NULL, &stock, NULL) == SWITCH_OK && opens == 3); + assert(bank_is_stock() && !look_state.active.id[0] && !style_from_theme() && + !style_dark()); + for (unsigned i = 0; i < BITMAP_WORDS; i++) + assert(!look_state.assets[i] && !look_state.accented[i]); + + /* Without the firmware file nothing changes. */ + firmware_missing = 1; + look_state.stock_checked = 0; + assert(switch_to(&b, &theme) == SWITCH_LOAD_FAILED && bank_is_stock() && + !look_state.stock_checked); + firmware_missing = 0; + assert(switch_to(&b, &theme) == SWITCH_OK); + + /* A pack that fails part way: the stock light look comes back and every + * touched bitmap is restored. */ + paletted[8] = 2; + memcpy(mask, (uint8_t[]){8, 7, 6, 5, 4, 3, 2, 1}, 8); + two[0] = pixels(MASK, mask); + build(&b, two, 2, NULL); + assert(switch_to(&b, &theme) == SWITCH_RECOVERED); + assert(bank_is_stock() && !look_state.active.id[0] && !style_from_theme() && + !style_dark() && style_accent() == ACCENT_DEFAULT && !firmware_open_now); + for (unsigned i = 0; i < BITMAP_WORDS; i++) + assert(!look_state.assets[i]); + paletted[8] = 0; + + /* When the firmware file cannot restore a bitmap, theming is off: the + * attempt's bitmaps stay marked and the file is checked again next time. */ + build(&b, two, 2, NULL); + assert(switch_to(&b, &theme) == SWITCH_OK); + corrupt_asset = MASK; + assert(switch_apply(NULL, &stock, NULL) == SWITCH_RESTORE_FAILED); + assert(bit_test(look_state.assets, MASK) && bit_test(look_state.assets, PALETTED) && + !look_state.stock_checked && !look_state.active.id[0] && + !style_from_theme()); + assert(catalog_data(MASK)[HEADER] == 0); /* zeroed by the failed fetch */ + corrupt_asset = -1; + assert(switch_apply(NULL, &stock, NULL) == SWITCH_OK && bank_is_stock() && + look_state.stock_checked); + + /* Theme to theme: the second pack applies, then a bitmap only the first + * touched cannot be restored; the recovery cannot restore it either, so + * theming is off with both packs' bitmaps marked. */ + struct built second; + build(&b, two, 2, NULL); + assert(switch_to(&b, &theme) == SWITCH_OK); + build(&second, two + 1, 1, NULL); + corrupt_asset = MASK; + assert(switch_to(&second, &theme) == SWITCH_RESTORE_FAILED); + assert(bit_test(look_state.assets, MASK) && bit_test(look_state.assets, PALETTED) && + !look_state.stock_checked && !look_state.active.id[0] && + !style_from_theme()); + corrupt_asset = -1; + assert(switch_apply(NULL, &stock, NULL) == SWITCH_OK && bank_is_stock() && + look_state.stock_checked); + + /* Classic dark: a pack with colours only; one with a tint or a flag is refused. */ + struct look dark = {.dark = 1}; + build(&b, two, 2, NULL); + assert(switch_to(&b, &dark) == SWITCH_OK && !style_from_theme() && style_dark()); + assert(!memcmp(catalog_data(MASK) + HEADER, mask, sizeof mask)); + uint8_t tint[RVT_CATALOG_MAX] = {0}; + tint[MASK] = RVT_TINT_ROLE + RVT_ROLE_ICON_TINT; + build(&b, NULL, 0, tint); + assert(switch_to(&b, &dark) == SWITCH_LOAD_FAILED); + build(&b, NULL, 0, NULL); + put32(b.bytes + RVT_HEADER_BYTES + RVT_PACK_HEADER_BYTES + RVT_STYLE_FLAGS, + RVT_FLAG_FLAT_SELECTION); + resign_dark_pack(&b); + assert(switch_to(&b, &dark) == SWITCH_LOAD_FAILED); + assert(!memcmp(catalog_data(MASK) + HEADER, mask, + sizeof mask)); /* the dark look stays */ + assert(switch_apply(NULL, &stock, NULL) == SWITCH_OK && bank_is_stock()); + + /* An accent on Classic recolours the stock accent art from stock pixels + * and restores it exactly; Blue and Theme Default leave it alone. */ + struct look pink = {.accent = ACCENT_FIRST + 6}; + assert(!strcmp(accent_labels[pink.accent], "Pink")); + assert(switch_apply(NULL, &pink, NULL) == SWITCH_OK && + bit_test(look_state.assets, WIDE) && bit_test(look_state.accented, WIDE)); + const uint8_t *fill = style_color(RVT_ROLE_ACCENT_FILL); + assert(fill[0] == 196 && fill[1] == 30 && fill[2] == 86); + assert( + !memcmp(catalog_data(WIDE) + at_data(WIDE), (uint8_t[]){86, 30, 196, 255}, 4)); + assert( + !memcmp(catalog_data(WIDE) + at_data(WIDE) + 4, GREY, 4)); /* grey stays grey */ + assert(switch_accent(ACCENT_FIRST + 2) == SWITCH_OK); /* Green, from stock again */ + assert( + !memcmp(catalog_data(WIDE) + at_data(WIDE), (uint8_t[]){58, 128, 30, 255}, 4)); + assert(switch_accent(ACCENT_FIRST) == SWITCH_OK && bank_is_stock() && + !bit_test(look_state.assets, WIDE)); + assert(switch_accent(ACCENT_DEFAULT) == SWITCH_OK && bank_is_stock()); + /* A failed restore during an accent change recovers like a switch. */ + assert(switch_accent(pink.accent) == SWITCH_OK); + corrupt_asset = WIDE; + assert(switch_accent(ACCENT_FIRST + 2) == SWITCH_RESTORE_FAILED && + !look_state.stock_checked && style_accent() == ACCENT_DEFAULT && + bit_test(look_state.assets, WIDE)); + corrupt_asset = -1; + assert(switch_apply(NULL, &stock, NULL) == SWITCH_OK && bank_is_stock()); + + /* A pack that replaces the accent art keeps its own art under any accent. */ + uint8_t wide_art[4 * 4 + 8] = {1, 1, 1, 255, 2, 2, 2, 255, 3, 3, 3, 255, + 4, 4, 4, 255, 0, 1, 2, 3, 0, 1, 2, 3}; + struct rec own = pixels(WIDE, wide_art); + build(&b, &own, 1, NULL); + theme.accent = pink.accent; + assert(switch_to(&b, &theme) == SWITCH_OK && !bit_test(look_state.accented, WIDE)); + assert(!memcmp(catalog_data(WIDE) + at_data(WIDE), wide_art, sizeof wide_art)); + assert(switch_accent(ACCENT_FIRST + 2) == SWITCH_OK && + !memcmp(catalog_data(WIDE) + at_data(WIDE), wide_art, sizeof wide_art)); + theme.accent = 0; + + /* Unload puts everything back. */ + switch_restore_all(); + assert(bank_is_stock() && !look_state.active.id[0] && !style_from_theme()); + for (unsigned i = 0; i < BITMAP_WORDS; i++) + assert(!look_state.assets[i]); + assert(!firmware_open_now && !allocations); +} + +/* A theme's bitmaps for extensions: the table after a pack's records goes + * into the index, checked entry by entry; the provider serves the core from + * the index and the theme file; the index goes when the look does. */ +#define OWNER_A 0x1000u +#define OWNER_B 0x2000u +/* A Settings icon: 78 by 121 Mask8, stride 80. */ +#define MENU_STRIDE 80 +#define MENU_ROWS (MENU_STRIDE * 121) +#define MENU_BMAP_BYTES (HEADER + MENU_ROWS) +#define LZ_BOUND(n) ((n) + ((n) + 7) / 8) +static uint8_t menu_a[MENU_BMAP_BYTES], menu_b[MENU_BMAP_BYTES]; +/* menu_lz: the header and a 0xab as 29 literals (four flag bytes), then one + * match of 9,679 bytes from one byte back: 15 + 3, extended by 37 bytes of + * 255 and one of 226. */ +static uint8_t menu_lz[4 + HEADER + 1 + 2 + 38]; +/* A canvas bitmap: 4 by 2 Indexed8 with two colours, raw and as literals. */ +static uint8_t small[PALETTED_BYTES], small_lz[LZ_BOUND(PALETTED_BYTES)]; + +/* `n` bytes as an lz stream of literals: a flag byte per eight. */ +static uint32_t lz_literals(uint8_t *out, const uint8_t *in, uint32_t n) +{ + uint32_t written = 0; + for (uint32_t i = 0; i < n; i++) { + if (i % 8 == 0) + out[written++] = 0; + out[written++] = in[i]; + } + return written; +} + +static void asset_payloads(void) +{ + bmap(menu_a, BMapFormat_Mask8, MENU_STRIDE, 8, 78, 121, sizeof menu_a); + bmap(menu_b, BMapFormat_Mask8, MENU_STRIDE, 8, 78, 121, sizeof menu_b); + for (uint32_t i = HEADER; i < sizeof menu_a; i++) { + menu_a[i] = (uint8_t)(i * 7); + menu_b[i] = (uint8_t)(i * 3 + 1); + } + uint8_t *lz = menu_lz; + for (uint32_t group = 0; group < 3; group++) { + *lz++ = 0; + memcpy(lz, menu_a + 8 * group, 8); + lz += 8; + } + *lz++ = 0x20; /* four header literals, the 0xab, then the match */ + memcpy(lz, menu_a + 24, 4); + lz += 4; + *lz++ = 0xab; + *lz++ = 0xf0; + *lz++ = 0x00; + memset(lz, 255, 37); + lz[37] = 226; + assert(lz + 38 == menu_lz + sizeof menu_lz); + bmap(small, BMapFormat_Indexed8, 4, 8, 4, 2, sizeof small); + put32(small + HEADER, 2); + memcpy(small + HEADER + 4, LIGHT, 4); + memcpy(small + HEADER + 8, ICON, 4); + for (uint32_t i = 0; i < 8; i++) + small[HEADER + 12 + i] = (uint8_t)(i & 1); + assert(lz_literals(small_lz, small, sizeof small) == sizeof small_lz); +} + +static void with_assets(const struct asset_payload *table, uint32_t count, + struct built *b) +{ + asset_table = table; + asset_table_count = count; + build(b, NULL, 0, NULL); + asset_table = NULL; + asset_table_count = 0; +} + +static void prefix_custom(uint8_t *p, const uint8_t roles[RVT_ROLES][3], uint32_t flags, + unsigned palette, const uint8_t accent[RVT_ACCENT_SLOTS][3]); + +/* 1 when the probe answers the asset with exactly this stream. */ +static int probe(uint32_t owner, uint32_t asset, uint8_t codec, uint32_t stored, + uint32_t bytes) +{ + struct rv_asset_stream stream = {0xff, 0, 0}; + return replacement(owner, asset, &stream) && stream.codec == codec && + stream.stored == stored && stream.bytes == bytes; +} + +/* The core's read of a probed stream: 1 when the provider copied `stored` + * bytes of the asset into `block`; the block is the caller's. */ +static int read_stored(uint32_t owner, uint32_t asset, uint8_t *block, uint32_t stored) +{ + memset(block, 0x5a, stored); + return replacement_read(owner, asset, block, stored); +} + +static void assets_contracts(void) +{ + static uint8_t block[MENU_BMAP_BYTES], zeros[MENU_BMAP_BYTES]; + uint32_t assets[BITMAP_WORDS]; + struct built b; + asset_payloads(); + const struct asset_payload four[4] = { + {OWNER_A, 5, RVT_EXTENSION_BITMAP, sizeof menu_a, MENU_BMAP_BYTES, menu_a, 0}, + {OWNER_A, 9, RVT_EXTENSION_BITMAP_LZ, sizeof menu_lz, MENU_BMAP_BYTES, menu_lz, + 0}, + {OWNER_B, 1, RVT_EXTENSION_BITMAP, sizeof small, PALETTED_BYTES, small, 0}, + {OWNER_B, 2, RVT_EXTENSION_BITMAP_LZ, sizeof small_lz, PALETTED_BYTES, small_lz, + 0}, + }; + + /* A good table: one entry per asset, in order, each payload's offset in + * the file, the stored bytes, the decoded bytes and the kind. */ + with_assets(four, 4, &b); + assert(apply(&b, assets) && live_count == 4 && allocations == 1); + for (unsigned i = 0; i < 4; i++) { + assert(live[i].owner == four[i].owner && live[i].asset == four[i].asset); + assert(live[i].kind == four[i].kind && live[i].bytes == four[i].size); + assert(live[i].decoded == four[i].decoded); + assert(!memcmp(b.bytes + live[i].offset, four[i].payload, four[i].size)); + } + assert(live[0].offset == RVT_HEADER_BYTES + RVT_PACK_HEADER_BYTES + + RVT_STYLE_BYTES + RVT_EXTENSION_BITMAP_BYTES); + + /* Refused, the index that was on staying: out of order or repeated keys; + * a kind that is not a bitmap; a decoded size that is no more than a + * header or over the cap; a raw payload of another size than decoded; an + * empty lz stream or one over the literal bound; padding that is not + * zero; a count the body does not hold, one that leaves a table unread, + * and a table past the limit. The bitmap itself is the core's to check + * once decoded. */ + struct asset_payload bad[4]; + memcpy(bad, four, sizeof bad); + bad[0] = four[1], bad[1] = four[0]; + with_assets(bad, 4, &b); + assert(!apply(&b, assets) && live_count == 4); + memcpy(bad, four, sizeof bad); + bad[1].asset = 5; + with_assets(bad, 4, &b); + assert(!apply(&b, assets)); + memcpy(bad, four, sizeof bad); + bad[2].owner = OWNER_A, bad[2].asset = 2; + with_assets(bad, 4, &b); + assert(!apply(&b, assets)); + memcpy(bad, four, sizeof bad); + bad[0].kind = RVT_EXTENSION_KINDS; + with_assets(bad, 4, &b); + assert(!apply(&b, assets)); + bad[0].kind = 0; + with_assets(bad, 4, &b); + assert(!apply(&b, assets)); + memcpy(bad, four, sizeof bad); + bad[2].size = bad[2].decoded = HEADER; /* a header without rows */ + with_assets(bad, 4, &b); + assert(!apply(&b, assets)); + memcpy(bad, four, sizeof bad); + bad[2].size = sizeof small - 1; /* a raw payload of another size */ + with_assets(bad, 4, &b); + assert(!apply(&b, assets)); + bad[2].size = sizeof small, bad[2].decoded = PALETTED_BYTES + 4; + with_assets(bad, 4, &b); + assert(!apply(&b, assets)); + memcpy(bad, four, sizeof bad); + bad[1].decoded = RVT_EXTENSION_BITMAP_MAX_BYTES + 1; /* over the cap */ + with_assets(bad, 4, &b); + assert(!apply(&b, assets)); + bad[1].decoded = RVT_EXTENSION_BITMAP_MAX_BYTES; /* at it: the core decides */ + with_assets(bad, 4, &b); + assert(apply(&b, assets) && live_count == 4); + /* A tint word names a role without coverage bits; the index keeps it. */ + memcpy(bad, four, sizeof bad); + bad[2].tint = RVT_TINT_ROLE + RVT_ROLE_TEXT; + with_assets(bad, 4, &b); + assert(apply(&b, assets) && live[2].tint == RVT_TINT_ROLE + RVT_ROLE_TEXT && + !live[3].tint); + bad[2].tint = RVT_TINT_ROLE + RVT_ROLES; + with_assets(bad, 4, &b); + assert(!apply(&b, assets)); + bad[2].tint = RVT_TINT_ROLE + RVT_ROLE_TEXT | RVT_TINT_DARKNESS; + with_assets(bad, 4, &b); + assert(!apply(&b, assets)); + bad[2].tint = RVT_TINT_ROLE + RVT_ROLE_TEXT | RVT_TINT_SOLID; + with_assets(bad, 4, &b); + assert(!apply(&b, assets)); + memcpy(bad, four, sizeof bad); + bad[1].size = 0; + with_assets(bad, 4, &b); + assert(!apply(&b, assets)); + static uint8_t overlong[LZ_BOUND(MENU_BMAP_BYTES) + 1]; + bad[1].size = sizeof overlong, bad[1].payload = overlong; + with_assets(bad, 4, &b); + assert(!apply(&b, assets)); + bad[1].size = sizeof overlong - 1; + with_assets(bad, 4, &b); + assert(apply(&b, assets) && live_count == 4); /* parsed; the core decides */ + memcpy(bad, four, sizeof bad); + static uint8_t small_overlong[sizeof small_lz + 1]; + memcpy(small_overlong, small_lz, sizeof small_lz); + bad[3].size = sizeof small_overlong, bad[3].payload = small_overlong; + with_assets(bad, 4, &b); + assert(!apply(&b, assets)); + with_assets(four, 4, &b); + b.bytes[b.size - 1] ^= 1; + assert(!apply(&b, assets)); /* the checksum covers the table */ + with_assets(four, 4, &b); + b.bytes[live[1].offset + sizeof menu_lz] = 1; /* padding after the lz stream */ + resign_dark_pack(&b); + assert(!apply(&b, assets)); + with_assets(four, 4, &b); + put32(b.bytes + RVT_HEADER_BYTES + RVT_PACK_EXTENSION_BITMAPS, 5); + assert(!apply(&b, assets)); + put32(b.bytes + RVT_HEADER_BYTES + RVT_PACK_EXTENSION_BITMAPS, 3); + assert(!apply(&b, assets)); + static struct asset_payload many[RVT_EXTENSION_BITMAPS_MAX + 1]; + for (uint32_t i = 0; i < RVT_EXTENSION_BITMAPS_MAX + 1; i++) + many[i] = (struct asset_payload){ + OWNER_A, i, RVT_EXTENSION_BITMAP_LZ, sizeof menu_lz, MENU_BMAP_BYTES, + menu_lz, 0}; + with_assets(many, RVT_EXTENSION_BITMAPS_MAX + 1, &b); + assert(!apply(&b, assets)); + with_assets(many, RVT_EXTENSION_BITMAPS_MAX, &b); + assert(apply(&b, assets) && live_count == RVT_EXTENSION_BITMAPS_MAX); + /* A pack without a table leaves no index. */ + build(&b, NULL, 0, NULL); + assert(apply(&b, assets) && !live_count && !allocations); + + /* The probe answers how a listed asset is stored, nothing for any other; + * the read copies exactly the stored bytes and nothing for another size. */ + with_assets(four, 4, &b); + assert(apply(&b, assets)); + provided = &b; + memcpy(look_state.active.id, PROVIDED_ID, sizeof PROVIDED_ID); + assert(probe(OWNER_A, 5, RV_ASSET_RAW, sizeof menu_a, MENU_BMAP_BYTES)); + assert(probe(OWNER_A, 9, RV_ASSET_LZ, sizeof menu_lz, MENU_BMAP_BYTES)); + assert(probe(OWNER_B, 1, RV_ASSET_RAW, sizeof small, PALETTED_BYTES)); + assert(probe(OWNER_B, 2, RV_ASSET_LZ, sizeof small_lz, PALETTED_BYTES)); + struct rv_asset_stream none; + assert(!replacement(OWNER_A, 7, &none) && !replacement(OWNER_A, 4, &none)); + assert(!replacement(OWNER_B, 3, &none) && !replacement(0, 5, &none)); + assert(read_stored(OWNER_A, 5, block, sizeof menu_a) && + !memcmp(block, menu_a, sizeof menu_a)); + assert(read_stored(OWNER_A, 9, block, sizeof menu_lz) && + !memcmp(block, menu_lz, sizeof menu_lz)); + assert(read_stored(OWNER_B, 1, block, sizeof small) && + !memcmp(block, small, sizeof small)); + assert(read_stored(OWNER_B, 2, block, sizeof small_lz) && + !memcmp(block, small_lz, sizeof small_lz)); + assert(!read_stored(OWNER_A, 7, block, MENU_BMAP_BYTES)); + assert(!read_stored(OWNER_A, 5, block, sizeof menu_a - 1)); + assert(!read_stored(OWNER_B, 1, block, sizeof menu_a)); + assert(!open_files && allocations == 1); + /* A file that no longer holds the bytes: cut inside a raw payload or an + * lz stream. The read says 0 and holds nothing. */ + b.size = live[0].offset + 100; + assert(!read_stored(OWNER_A, 5, block, sizeof menu_a)); + b.size = live[1].offset + 10; + assert(!read_stored(OWNER_A, 9, block, sizeof menu_lz)); + assert(!open_files && allocations == 1); + with_assets(four, 4, &b); + assert(apply(&b, assets)); + /* A theme file that is gone. */ + provided = NULL; + unreadable = PROVIDED_ID; + assert(probe(OWNER_A, 5, RV_ASSET_RAW, sizeof menu_a, MENU_BMAP_BYTES)); + assert(!read_stored(OWNER_A, 5, block, sizeof menu_a) && !open_files); + unreadable = NULL; + provided = &b; + /* Classic dark serves its bitmaps from the classic asset; Classic light + * has no file. */ + memset(look_state.active.id, 0, sizeof look_state.active.id); + look_state.active.dark = 1; + assert(!read_stored(OWNER_A, 5, block, sizeof menu_a) && + !open_files); /* the asset here holds none */ + look_state.active.dark = 0; + assert(!read_stored(OWNER_A, 5, block, sizeof menu_a) && !open_files); + memcpy(look_state.active.id, PROVIDED_ID, sizeof PROVIDED_ID); + + /* The extension's own bitmap is left alone, until a flat-icon look: then + * a Settings icon loses the rows under its art, and nothing else changes. */ + memcpy(block, menu_a, sizeof block); + assert(!adjust(OWNER_A, 7, block, MENU_BMAP_BYTES) && + !memcmp(block, menu_a, sizeof block)); + uint8_t prefix[RVT_STYLE_BYTES]; + static const uint8_t roles[RVT_ROLES][3] = {{0}}; + prefix_custom(prefix, roles, RVT_FLAG_FLAT_ICONS, 0, NULL); + style_set(prefix); + assert(adjust(OWNER_A, 7, block, MENU_BMAP_BYTES)); + assert(!memcmp(block, menu_a, HEADER + 79 * MENU_STRIDE) && + !memcmp(block + HEADER + 79 * MENU_STRIDE, zeros, (121 - 79) * MENU_STRIDE)); + memcpy(block, small, sizeof small); + assert(!adjust(OWNER_B, 1, block, PALETTED_BYTES) && + !memcmp(block, small, sizeof small)); + memcpy(block, menu_a, sizeof block); + put16(block, BMapFormat_Indexed8); + assert(!adjust(OWNER_A, 7, block, MENU_BMAP_BYTES)); + put16(block, BMapFormat_Mask8); + assert(!adjust(OWNER_A, 7, block, MENU_BMAP_BYTES - 1)); + put32(block + 20, 80); + assert(!adjust(OWNER_A, 7, block, MENU_BMAP_BYTES)); + assert(!memcmp(block + HEADER, menu_a + HEADER, MENU_ROWS)); + style_reset(); + + /* A tinted replacement: the decoded picture's palette entries take the + * role's colour and keep their alpha; a Settings icon under a tint word + * is left to the core, which draws it in the icon tint anyway. */ + struct asset_payload tinted[4]; + memcpy(tinted, four, sizeof tinted); + tinted[2].tint = RVT_TINT_ROLE + RVT_ROLE_TEXT; + tinted[0].tint = RVT_TINT_ROLE + RVT_ROLE_TEXT; + with_assets(tinted, 4, &b); + assert(apply(&b, assets)); + static const uint8_t text_role[RVT_ROLES][3] = { + [RVT_ROLE_TEXT] = {0x12, 0x34, 0x56}}; + prefix_custom(prefix, text_role, 0, 0, NULL); + style_set(prefix); + memcpy(block, small, sizeof small); + assert(adjust(OWNER_B, 1, block, PALETTED_BYTES)); + static const uint8_t painted_light[4] = {0x56, 0x34, 0x12, 255}; + assert(!memcmp(block + HEADER + 4, painted_light, 4) && + block[HEADER + 11] == ICON[3] && + !memcmp(block + HEADER + 8, "\x56\x34\x12", 3) && + !memcmp(block + HEADER + 12, small + HEADER + 12, 8)); + memcpy(block, small, sizeof small); + assert(!adjust(OWNER_B, 2, block, PALETTED_BYTES) && + !memcmp(block, small, sizeof small)); + memcpy(block, menu_a, sizeof block); + assert(!adjust(OWNER_A, 5, block, MENU_BMAP_BYTES) && + !memcmp(block, menu_a, sizeof block)); + /* BGRA rows: covered pixels are painted, clear ones stay. */ + static uint8_t argb[HEADER + 16 * 2]; + bmap(argb, BMapFormat_BGRA8888, 16, 32, 4, 2, sizeof argb); + for (uint32_t i = 0; i < 8; i++) + memcpy(argb + HEADER + i * 4, i & 1 ? "\x01\x02\x03\x80" : "\x09\x09\x09\x00", + 4); + assert(tint_bmap(argb, sizeof argb, style_color(RVT_ROLE_TEXT))); + for (uint32_t i = 0; i < 8; i++) + assert(!memcmp(argb + HEADER + i * 4, + i & 1 ? "\x56\x34\x12\x80" : "\x09\x09\x09\x00", 4)); + put16(argb, BMapFormat_RGB565); + assert(!tint_bmap(argb, sizeof argb, style_color(RVT_ROLE_TEXT))); + style_reset(); + with_assets(four, 4, &b); + assert(apply(&b, assets)); + + /* The end of disk mode checks the theme file's header: the same file + * keeps the index, another under the id or none ends it. */ + look_state.active.header_crc = le32(b.bytes + RVT_HEADER_CRC); + look_volume_changed(); + assert(probe(OWNER_A, 5, RV_ASSET_RAW, sizeof menu_a, MENU_BMAP_BYTES) && + live_count == 4); + struct built swapped; + asset_table = four, asset_table_count = 4; + build_file_at(&swapped, PROVIDED_ID, "Other", RVT_HEADER_BYTES, NULL, 0, NULL, 0, + NULL, NULL); + asset_table = NULL, asset_table_count = 0; + provided = &swapped; + look_volume_changed(); + assert(!replacement(OWNER_A, 5, &none)); + assert(!live_count && !allocations && !open_files); + assert(apply(&b, assets) && live_count == 4); + unreadable = PROVIDED_ID; + look_volume_changed(); + assert(!live_count && !allocations && !open_files); + unreadable = NULL; + provided = &b; + + /* The switch: a look with bitmaps holds the index; the stock look, a + * recovered switch and unload free it; a switch that fails before it + * changes anything keeps the index of the look that stays. */ + struct look theme = { + .id = "test", .name = "Test", .appearances = RVT_APPEARANCE_DARK, .dark = 1}; + struct look stock = {0}; + with_assets(four, 4, &b); + assert(switch_to(&b, &theme) == SWITCH_OK && live_count == 4 && allocations == 1); + assert(switch_apply(NULL, &stock, NULL) == SWITCH_OK && !live_count && + !allocations); + assert(switch_to(&b, &theme) == SWITCH_OK && live_count == 4); + struct built failing; + memcpy(bad, four, sizeof bad); + bad[0].kind = RVT_EXTENSION_KINDS; /* no records: a bad table alone */ + with_assets(bad, 4, &failing); + assert(switch_to(&failing, &theme) == SWITCH_LOAD_FAILED && live_count == 4 && + allocations == 1); + uint8_t paletted[2 * 4 + 4 * 2] = {9, 9, 9, 255, 8, 8, 8, 255, + 0, 1, 0, 2, 1, 0, 1, 0}; + struct rec broken = pixels(PALETTED, paletted); + asset_table = four, asset_table_count = 4; + build(&failing, &broken, 1, NULL); + asset_table = NULL, asset_table_count = 0; + assert(switch_to(&failing, &theme) == SWITCH_RECOVERED && !live_count && + !allocations); + assert(switch_to(&b, &theme) == SWITCH_OK && live_count == 4); + switch_restore_all(); + assert(!live_count && !allocations && bank_is_stock()); + provided = NULL; + memset(&look_state.active, 0, sizeof look_state.active); +} + +static void scan_contracts(void) +{ + static const char *const names[] = {"zeta.rvt", "ALPHA.RVT", "Mid.Rvt", + "notes.txt", "BAD~1.RVT", "classic.rvt", + "alpha.rvt", "broken.rvt", "-dash.rvt"}; + struct theme_entry entries[64]; + int overflow = 1; + folder = names; + folder_count = sizeof names / sizeof *names; + unreadable = "broken"; + /* Counted: zeta, ALPHA, Mid, alpha, broken; listed in order without the + * duplicate and the file that does not open. */ + assert(theme_count() == 5); + uint32_t n = theme_scan(entries, 64, &overflow); + assert(n == 3 && !overflow); + assert(!strcmp(entries[0].id, "alpha") && !strcmp(entries[1].id, "mid") && + !strcmp(entries[2].id, "zeta")); + assert(!strcmp(entries[0].name, "Named")); + + /* More files than the list holds: the first in order are kept and the + * overflow reported; a smaller capacity caps the same way. */ + static char many_names[70][16]; + static const char *many[70]; + for (unsigned i = 0; i < 70; i++) { + snprintf(many_names[i], sizeof many_names[i], "t%02u.rvt", 69 - i); + many[i] = many_names[i]; + } + folder = many; + folder_count = 70; + unreadable = NULL; + assert(theme_count() == 70); + n = theme_scan(entries, 64, &overflow); + assert(n == 64 && overflow && !strcmp(entries[0].id, "t00") && + !strcmp(entries[63].id, "t63")); + n = theme_scan(entries, 3, &overflow); + assert(n == 3 && overflow && !strcmp(entries[2].id, "t02")); + + /* Opening a theme: by id, in the appearance asked for or the one it has; + * the reserved id and a missing file are unavailable. */ + struct rv_file *file; + struct look look; + struct pack_place place; + char id[RVT_ID_BYTES] = "t05"; + assert(theme_open(id, 1, &file, &look, &place) == THEME_OK && look.dark && file); + file_close(NULL, file); + assert(theme_open(id, 0, &file, &look, &place) == THEME_NOT_IN_APPEARANCE && + look.dark && file); + assert(!strcmp(look.id, "t05") && look.appearances == RVT_APPEARANCE_DARK); + assert(place.offset == RVT_HEADER_BYTES && + place.bytes == opened_theme.size - RVT_HEADER_BYTES); + file_close(NULL, file); + strcpy(id, "classic"); + assert(theme_open(id, 1, &file, &look, &place) == THEME_UNAVAILABLE && !file); + strcpy(id, "broken"); + unreadable = "broken"; + assert(theme_open(id, 1, &file, &look, &place) == THEME_UNAVAILABLE && !file); + assert(!open_files); +} + +/* A style prefix with the given role colours (RGB), flags and one accent palette. */ +static void prefix_custom(uint8_t *p, const uint8_t roles[RVT_ROLES][3], uint32_t flags, + unsigned palette, const uint8_t accent[RVT_ACCENT_SLOTS][3]) +{ + prefix_plain(p); + for (unsigned i = 0; i < RVT_ROLES; i++) + memcpy(p + RVT_STYLE_COLORS + i * 4, roles[i], 3); + put32(p + RVT_STYLE_FLAGS, flags); + if (accent) + for (unsigned i = 0; i < RVT_ACCENT_SLOTS; i++) + memcpy(p + RVT_STYLE_PALETTES + (palette * RVT_ACCENT_SLOTS + i) * 4, + accent[i], 3); +} + +static void expect_text(const uint8_t *color, uint32_t view, uint8_t r, uint8_t g, + uint8_t b) +{ + uint8_t mapped[4]; + const uint8_t *out = map_text(color, view, mapped); + assert(out[0] == r && out[1] == g && out[2] == b && out[3] == color[3]); +} + +static void expect_fill(const uint8_t *color, uint8_t r, uint8_t g, uint8_t b) +{ + uint8_t mapped[4]; + const uint8_t *out = map_fill(color, mapped); + assert(out[0] == r && out[1] == g && out[2] == b && out[3] == color[3]); +} + +static void expect_background(uint32_t r, uint32_t g, uint32_t b, uint32_t rgb565) +{ + assert(clear_color(0x10000, 0x10000, 0x10000, 0x4321, NULL) == 0x600d); + assert(passed[0] == r && passed[1] == g && passed[2] == b && passed[3] == 0x4321); + assert(reflection_blend(0xabcd, 0xffff, 0x8000, NULL) == 0x600d); + assert(passed[0] == 0xabcd && passed[1] == rgb565 && passed[2] == 0x8000); +} + +static void expect_bar(const uint8_t *color, enum bar_slot slot, unsigned well, + uint8_t r, uint8_t g, uint8_t b) +{ + uint8_t mapped[4]; + const uint8_t *out = map_bar_label(color, slot, well, mapped); + assert(out[0] == r && out[1] == g && out[2] == b && out[3] == color[3]); +} + +static void expect_day(const uint8_t *color, uint8_t r, uint8_t g, uint8_t b) +{ + uint8_t mapped[4]; + const uint8_t *out = map_calendar_day(color, mapped); + assert(out[0] == r && out[1] == g && out[2] == b && out[3] == color[3]); +} + +static const uint8_t white[] = {255, 255, 255, 173}, + light_gray[] = {0xee, 0xee, 0xee, 9}, + pale_gray[] = {0xb0, 0xb0, 0xb0, 10}, + below_gray[] = {0xaf, 0xaf, 0xaf, 11}, + cover_border[] = {0x7e, 0x81, 0x83, 127}, + accent_fill[] = {0x23, 0x6c, 0xc5, 91}, + accent_text[] = {0x31, 0x85, 0xd0, 77}, black[] = {0, 0, 0, 123}, + dim_text[] = {0x80, 0x80, 0x80, 5}, + light_text[] = {0x81, 0x81, 0x81, 6}, + inactive_day[] = {0x66, 0x66, 0x66, 255}; + +enum { ORDINARY_VIEW = 0x0dad0001 }; + +#define DARK16(c) ((uint32_t)(c) * 0x10000 / 255) + +/* Classic with Theme Default or Blue is exact in both appearances. */ +static void classic_mapping(void) +{ + for (unsigned a = ACCENT_DEFAULT; a <= ACCENT_FIRST; a++) { + style_set_accent(a); + for (int dark = 0; dark < 2; dark++) { + style_set_dark(dark); + for (unsigned c = 0; c < 256; c++) { + const uint8_t native_gray[] = {(uint8_t)c, (uint8_t)c, (uint8_t)c, 33}; + uint8_t fill_shade = + (uint8_t)(dark && c >= 0xb0 ? 0x18 + (255 - c) / 4 : c); + uint8_t text_shade = (uint8_t)(dark && c <= 0x80 ? 0xe8 - c / 2 : c); + expect_fill(native_gray, fill_shade, fill_shade, fill_shade); + expect_text(native_gray, ORDINARY_VIEW, text_shade, text_shade, + text_shade); + } + expect_text(Palette_White, ORDINARY_VIEW, 255, 255, 255); + expect_text(white, ORDINARY_VIEW, 255, 255, 255); + if (dark) { + expect_fill(cover_border, 0x38, 0x38, 0x38); + expect_fill(accent_fill, 0, 161, 255); + expect_text(accent_fill, ORDINARY_VIEW, 0, 161, 255); + expect_text(accent_text, ORDINARY_VIEW, 0, 161, 255); + expect_background(DARK16(0x18), DARK16(0x18), DARK16(0x18), 0x18c3); + } else { + expect_fill(cover_border, 0x7e, 0x81, 0x83); + expect_fill(accent_fill, 0x23, 0x6c, 0xc5); + expect_text(accent_fill, ORDINARY_VIEW, 0x23, 0x6c, 0xc5); + expect_text(accent_text, ORDINARY_VIEW, 0x31, 0x85, 0xd0); + expect_background(0x10000, 0x10000, 0x10000, 0xffff); + } + } + } + style_set_dark(0); + style_set_accent(ACCENT_DEFAULT); +} + +enum { COPIED_DAY = 0x0dad8001 }; + +static uint32_t ui_stock_view(uint32_t view) +{ + return view == COPIED_DAY ? RES_Alarms_PickDate_Preivew_NumericDay : view; +} + +/* The day number of a copied Calendars pane keeps its stock black in dark + * mode, as the stock pane's does; a core without ui_stock_view leaves the id. */ +static void copied_view_text(void) +{ + style_set_dark(1); + expect_text(black, RES_Alarms_PickDate_Preivew_NumericDay, 0, 0, 0); + assert(stock_id(COPIED_DAY) == COPIED_DAY); + fake.size = sizeof fake; + fake.ui_stock_view = ui_stock_view; + assert(stock_id(COPIED_DAY) == RES_Alarms_PickDate_Preivew_NumericDay); + assert(stock_id(ORDINARY_VIEW) == ORDINARY_VIEW); + expect_text(black, stock_id(COPIED_DAY), 0, 0, 0); + fake.size = 0; + fake.ui_stock_view = NULL; + style_set_dark(0); +} + +static void accent_mapping(void) +{ + /* Purple recolours accents but leaves Classic light surfaces and text alone. */ + style_set_accent(ACCENT_FIRST + 7); + assert(!strcmp(accent_labels[ACCENT_FIRST + 7], "Purple")); + style_set_dark(0); + expect_fill(white, 255, 255, 255); + expect_fill(light_gray, 0xee, 0xee, 0xee); + expect_fill(cover_border, 0x7e, 0x81, 0x83); + expect_text(black, ORDINARY_VIEW, 0, 0, 0); + expect_text(dim_text, ORDINARY_VIEW, 0x80, 0x80, 0x80); + expect_text(Palette_White, ORDINARY_VIEW, 255, 255, 255); + expect_fill(accent_fill, 137, 68, 171); + expect_text(accent_fill, ORDINARY_VIEW, 137, 68, 171); + expect_text(accent_text, ORDINARY_VIEW, 137, 68, 171); + expect_background(0x10000, 0x10000, 0x10000, 0xffff); + style_set_dark(1); + expect_fill(white, 0x18, 0x18, 0x18); + expect_fill(accent_fill, 150, 78, 188); + expect_text(accent_fill, ORDINARY_VIEW, 150, 78, 188); + expect_text(accent_text, ORDINARY_VIEW, 218, 143, 255); + expect_background(DARK16(0x18), DARK16(0x18), DARK16(0x18), 0x18c3); + /* Native-colour views keep their colours under every accent. */ + expect_text(accent_text, RES_Search_Input_Text, 0x31, 0x85, 0xd0); + expect_text(black, RES_Search_Input_Text, 0, 0, 0); + + /* Pink, Red, Orange, Green: the accent text presets, light and dark. */ + static const struct { + const char *label; + uint8_t light[3], dark[3]; + } presets[] = { + {"Pink", {196, 30, 86}, {255, 100, 145}}, + {"Red", {208, 32, 40}, {255, 105, 97}}, + {"Orange", {184, 72, 0}, {255, 159, 10}}, + {"Green", {30, 128, 58}, {48, 209, 88}}, + }; + + for (unsigned i = 0; i < 4; i++) { + unsigned a = ACCENT_FIRST; + while (strcmp(accent_labels[a], presets[i].label)) + a++; + style_set_accent(a); + style_set_dark(0); + expect_text(accent_text, ORDINARY_VIEW, presets[i].light[0], + presets[i].light[1], presets[i].light[2]); + style_set_dark(1); + expect_text(accent_text, ORDINARY_VIEW, presets[i].dark[0], presets[i].dark[1], + presets[i].dark[2]); + } + /* An accent past the list is Theme Default. */ + style_set_accent(ACCENTS); + assert(style_accent() == ACCENT_DEFAULT); + style_set_dark(0); +} + +static void theme_mapping(void) +{ + uint8_t prefix[RVT_STYLE_BYTES]; + static const uint8_t sepia[RVT_ROLES][3] = { + [RVT_ROLE_BACKGROUND] = {250, 240, 220}, + [RVT_ROLE_TEXT] = {60, 40, 20}, + [RVT_ROLE_ACCENT_FILL] = {160, 80, 30}, + [RVT_ROLE_ACCENT_TEXT] = {140, 70, 20}, + [RVT_ROLE_ON_ACCENT] = {20, 10, 0}, + [RVT_ROLE_SELECTION] = {160, 80, 30}, + [RVT_ROLE_COVER_BORDER] = {120, 100, 80}, + }; + static const uint8_t orange[RVT_ACCENT_SLOTS][3] = { + [RVT_SLOT_ACCENT_FILL] = {190, 76, 0}, [RVT_SLOT_ACCENT_TEXT] = {255, 159, 10}, + [RVT_SLOT_SELECTION] = {190, 76, 0}, [RVT_SLOT_ON_ACCENT] = {255, 255, 255}, + [RVT_SLOT_ICON_TINT] = {255, 159, 10}, + }; + prefix_custom(prefix, sepia, RVT_FLAG_FLAT_NOW_PLAYING, RVT_ACCENT_ORANGE, orange); + style_set(prefix); + tint_refresh(); + /* A theme's colours hold in both appearances. */ + for (int dark = 0; dark < 2; dark++) { + style_set_dark(dark); + expect_fill(white, 250, 240, 220); + expect_fill(light_gray, 250 - 17, 240 - 17, 220 - 17); + expect_fill(pale_gray, 250 - 79, 240 - 79, 220 - 79); + expect_fill(below_gray, 0xaf, 0xaf, 0xaf); + expect_fill(cover_border, 120, 100, 80); + expect_fill(accent_fill, 160, 80, 30); + expect_text(black, ORDINARY_VIEW, 60 - 32, 40 - 32, 0); + expect_text(dim_text, ORDINARY_VIEW, 60 + 96, 40 + 96, 20 + 96); + expect_text(light_text, ORDINARY_VIEW, 0x81, 0x81, 0x81); + expect_text(accent_fill, ORDINARY_VIEW, 160, 80, 30); + expect_text(accent_text, ORDINARY_VIEW, 140, 70, 20); + /* Selected-row text follows on_accent by pointer; other white text + * takes the text role on this light background. */ + expect_text(Palette_White, ORDINARY_VIEW, 20, 10, 0); + expect_text(white, ORDINARY_VIEW, 60, 40, 20); + expect_text(light_gray, ORDINARY_VIEW, 0xee, 0xee, 0xee); + expect_background(DARK16(250), DARK16(240), DARK16(220), + (31u << 11) | (60u << 5) | 27u); + /* Retained-light views stay unmapped. */ + expect_text(black, RES_Settings_DateTime_NumericDay, 0, 0, 0); + expect_text(Palette_White, RES_Settings_DateTime_NumericDay, 255, 255, 255); + assert(stock_background(RES_NowPlaying_White_Background_View) && + !stock_background(ORDINARY_VIEW)); + /* A view drawn inside another's background fill gives the outer + * rule back. */ + int outer = enter_background(RES_NowPlaying_White_Background_View); + assert(!outer && stock_fill); + int inner = enter_background(ORDINARY_VIEW); + assert(inner && !stock_fill); + stock_fill = inner; + assert(stock_fill); + stock_fill = outer; + assert(!stock_fill); + /* A fill onto a coverage mask keeps its colour: white clears a text + * bitmap; onto a pixel surface it is mapped. */ + static uint8_t surface[0x20]; + uint8_t mapped[4]; + *(uint16_t *)(surface + Surface_format) = + BMapFormat_Mask8 | BMapFormat_ByteSwapped; + assert(fill_color(surface, white, mapped) == white); + *(uint16_t *)(surface + Surface_format) = BMapFormat_Mask4; + assert(fill_color(surface, white, mapped) == white); + *(uint16_t *)(surface + Surface_format) = BMapFormat_RGB565; + assert(fill_color(surface, white, mapped) == mapped && mapped[0] == 250); + *(uint16_t *)(surface + Surface_format) = BMapFormat_Indexed8; + assert(fill_color(surface, white, mapped) == mapped); + } + /* Accents on a theme use its authored palette, icon tint included. */ + unsigned a = ACCENT_FIRST; + while (strcmp(accent_labels[a], "Orange")) + a++; + style_set_accent(a); + expect_fill(accent_fill, 190, 76, 0); + expect_text(accent_text, ORDINARY_VIEW, 255, 159, 10); + expect_fill(white, 250, 240, 220); + assert(style_color(RVT_ROLE_ICON_TINT)[0] == 255 && + style_color(RVT_ROLE_ICON_TINT)[1] == 159); + style_set_accent(ACCENT_DEFAULT); + expect_fill(accent_fill, 160, 80, 30); + assert(!style_color(RVT_ROLE_ICON_TINT)[0]); /* the prefix's own, zero here */ + + /* A dark theme inverts the stock shades and clamps the channels. */ + static const uint8_t night[RVT_ROLES][3] = { + [RVT_ROLE_BACKGROUND] = {250, 10, 40}, + [RVT_ROLE_TEXT] = {255, 250, 100}, + [RVT_ROLE_ACCENT_FILL] = {160, 80, 30}, + [RVT_ROLE_ACCENT_TEXT] = {140, 70, 20}, + [RVT_ROLE_ON_ACCENT] = {20, 10, 0}, + [RVT_ROLE_SELECTION] = {160, 80, 30}, + [RVT_ROLE_COVER_BORDER] = {120, 100, 80}, + }; + prefix_custom(prefix, night, 0, 0, NULL); + style_set(prefix); + tint_refresh(); + style_set_dark(0); + expect_fill(white, 250, 10, 40); + expect_fill(pale_gray, 255, 10 + 19, 40 + 19); + expect_text(black, ORDINARY_VIEW, 255, 250, 100); + expect_text(dim_text, ORDINARY_VIEW, 255 - 64, 250 - 64, 100 - 64); + expect_text(white, ORDINARY_VIEW, 255, 255, + 255); /* a dark background keeps white */ + expect_background(DARK16(250), DARK16(10), DARK16(40), + (31u << 11) | (2u << 5) | 5u); + style_reset(); + style_set_dark(0); + expect_fill(white, 255, 255, 255); +} + +/* Bar labels: the highlighted one takes on_accent whenever anything is + * themed; the others take the colour derived from the well art under a + * theme. Without a theme the Now Playing bar keeps its highlighted label, + * and its others follow the well under Dark. */ +static void bar_mapping(void) +{ + static const uint8_t native[] = {255, 255, 255, 201}; + static const uint8_t blue[] = {10, 120, 210, 255}, gray[] = {60, 60, 60, 255}; + uint8_t prefix[RVT_STYLE_BYTES]; + style_reset(); + style_set_dark(0); + style_set_accent(ACCENT_FIRST + + 7); /* Purple on Classic: white on_accent, stock wells */ + tint_refresh(); + expect_bar(native, BAR_SELECTED, WELL_BLACK, 255, 255, 255); + expect_bar(native, BAR_LABEL, WELL_BLACK, 255, 255, 255); + expect_bar(native, BAR_OTHER, WELL_WHITE, 255, 255, 255); + assert(!tint_well_letter_color(WELL_BLACK)); + expect_bar(blue, BAR_SELECTED, WELL_NOW_PLAYING, 10, 120, 210); + expect_bar(gray, BAR_LABEL, WELL_NOW_PLAYING, 60, 60, 60); + /* Bitmap 1's centre is light, so the dark background role. */ + style_set_dark(1); + tint_refresh(); + const uint8_t *background = style_color(RVT_ROLE_BACKGROUND); + expect_bar(gray, BAR_LABEL, WELL_NOW_PLAYING, background[0], background[1], + background[2]); + expect_bar(blue, BAR_SELECTED, WELL_NOW_PLAYING, 10, 120, 210); + assert(!tint_well_letter_color(WELL_WHITE) && !tint_well_letter_color(WELL_BLACK)); + style_set_dark(0); + tint_refresh(); + style_set_accent(ACCENT_DEFAULT); + /* Under a theme the wells' letters contrast with the well art: bitmap 1's + * centre is the light colour, so the dark text role. */ + static const uint8_t sepia[RVT_ROLES][3] = { + [RVT_ROLE_BACKGROUND] = {250, 240, 220}, + [RVT_ROLE_TEXT] = {60, 40, 20}, + [RVT_ROLE_ACCENT_FILL] = {160, 80, 30}, + [RVT_ROLE_ACCENT_TEXT] = {140, 70, 20}, + [RVT_ROLE_ON_ACCENT] = {20, 10, 0}, + [RVT_ROLE_SELECTION] = {160, 80, 30}, + [RVT_ROLE_COVER_BORDER] = {120, 100, 80}, + }; + prefix_custom(prefix, sepia, 0, 0, NULL); + style_set(prefix); + tint_refresh(); + for (unsigned well = 0; well < WELLS; well++) { + expect_bar(native, BAR_SELECTED, well, 20, 10, 0); + expect_bar(native, BAR_LABEL, well, 60, 40, 20); + expect_bar(native, BAR_OTHER, well, 255, 255, 255); + } + assert(!tint_well_letter_color(WELLS)); + /* The Search field text follows the field art the same way; the caret's + * accent blue takes accent_text like any other text. */ + expect_text(black, RES_Search_Input_Text, 60, 40, 20); + expect_text(dim_text, RES_Search_Input_Text, 60, 40, 20); + expect_text(accent_text, RES_Search_Input_Text, 140, 70, 20); + /* Labels over listed art take the contrast colour, also over the + * white-text mapping; other views do not. */ + static const uint8_t status[] = {0xd3, 0xd3, 0xd3, 255}; + expect_text(status, RES_NowPlaying_StatusBar_Text_View, 60, 40, 20); + expect_text(white, RES_NowPlaying_StatusBar_Text_View, 60, 40, 20); + expect_text(status, ORDINARY_VIEW, 0xd3, 0xd3, 0xd3); + /* Clear art keeps the stock colour. */ + uint8_t *center = catalog_data(PALETTED) + at_data(PALETTED) + 3; + *center = 0; + tint_refresh(); + assert(!tint_field_text_color() && !tint_well_letter_color(WELL_WHITE) && + !tint_contrast_text_color(RES_NowPlaying_StatusBar_Text_View)); + expect_text(status, RES_NowPlaying_StatusBar_Text_View, 0xd3, 0xd3, 0xd3); + expect_text(dim_text, RES_Search_Input_Text, 60 + 96, 40 + 96, 20 + 96); + *center = 255; + tint_refresh(); + /* Calendar days: the shown month's on the active cell's contrast colour, + * a neighbouring month's mixed halfway toward the cell, weekday names + * halfway toward the page, the selected day in on_accent. */ + uint8_t out[4], half[4]; + expect_day(black, 60, 40, 20); + static const uint8_t light_rgba[4] = {240, 244, 247, + 255}; /* LIGHT, read out of BGRA */ + color_mix(half, style_color(RVT_ROLE_TEXT), light_rgba, 128); + expect_day(inactive_day, half[0], half[1], half[2]); + color_mix(half, style_color(RVT_ROLE_TEXT), style_color(RVT_ROLE_BACKGROUND), 128); + assert(tint_calendar_text_color(CALENDAR_HEADER, out) == out && + !memcmp(out, half, 4)); + assert(!tint_calendar_text_color(CALENDAR_HILITE, out)); + expect_day(white, 20, 10, 0); + /* Classic keeps every native colour. */ + style_reset(); + expect_day(black, 0, 0, 0); + expect_day(white, 255, 255, 255); + assert(!tint_calendar_text_color(CALENDAR_HEADER, out) && !tint_field_text_color()); + expect_text(black, RES_Search_Input_Text, 0, 0, 0); +} + +/* Tinted art: a highlighted view draws a tinted paletted bitmap in on_accent + * and puts the tint back; tinted ARGB art keeps its tint; masks are coloured + * while drawing; an unknown bitmap takes the icon tint role under a theme. */ +static void tint_contracts(void) +{ + uint8_t prefix[RVT_STYLE_BYTES], tint[RVT_CATALOG_MAX] = {0}; + static const uint8_t roles[RVT_ROLES][3] = { + [RVT_ROLE_BACKGROUND] = {1, 2, 3}, [RVT_ROLE_TEXT] = {4, 5, 6}, + [RVT_ROLE_ACCENT_FILL] = {7, 8, 9}, [RVT_ROLE_ACCENT_TEXT] = {40, 50, 60}, + [RVT_ROLE_ON_ACCENT] = {88, 0, 0}, [RVT_ROLE_SELECTION] = {11, 12, 13}, + [RVT_ROLE_COVER_BORDER] = {14, 15, 16}, [RVT_ROLE_ICON_TINT] = {10, 20, 30}, + }; + tint[MASK] = RVT_TINT_ROLE + RVT_ROLE_ICON_TINT; + tint[SECOND] = RVT_TINT_ROLE + RVT_ROLE_ICON_TINT; + tint[ARGB] = RVT_TINT_ROLE + RVT_ROLE_SELECTION; + tint[WIDE] = RVT_TINT_ROLE + RVT_ROLE_TEXT; + prefix_custom(prefix, roles, 0, 0, NULL); + memcpy(prefix + RVT_STYLE_TINTS, tint, RVT_CATALOG_MAX); + style_set(prefix); + tint_refresh(); + assert(!memcmp(catalog_data(SECOND) + at_data(SECOND), (uint8_t[]){30, 20, 10, 255}, + 4)); + assert(!memcmp(catalog_data(ARGB) + HEADER, (uint8_t[]){13, 12, 11, 255}, 4) && + catalog_data(ARGB)[HEADER + 31] == 0); + /* Views and contexts as the hooks see them. */ + static uint8_t view[0x200], context[0x40], bitmap[0x20], foreign[0x20], + other_context[0x40]; + const uint8_t *pixels = catalog_data(SECOND) + HEADER; + memcpy(bitmap + Bitmap_pixels, &pixels, sizeof pixels); + uint8_t *bitmap_p = bitmap; + memcpy(context + GraphicsContext_bitmap, &bitmap_p, sizeof bitmap_p); + uint8_t *context_p = context; + memcpy(view + BitmapView_context, &context_p, sizeof context_p); + assert(tint_mask_color(view)[0] == 10); + *(uint32_t *)(view + View_flags) = ViewFlags_Highlighted; + assert(tint_mask_color(view)[0] == 88); + tint_highlight_begin(view, context); + assert(catalog_data(SECOND)[at_data(SECOND) + 2] == 88 && + catalog_data(SECOND)[at_data(SECOND) + 6] == 88); + tint_highlight_end(); + assert(catalog_data(SECOND)[at_data(SECOND) + 2] == 10); + /* A blit inside the two halves of another: the first asset stays the + * highlighted one and the second keeps its tint. */ + static uint8_t wide_bitmap[0x20], wide_context[0x40]; + const uint8_t *wide_pixels = catalog_data(WIDE) + HEADER; + memcpy(wide_bitmap + Bitmap_pixels, &wide_pixels, sizeof wide_pixels); + uint8_t *wide_bitmap_p = wide_bitmap; + memcpy(wide_context + GraphicsContext_bitmap, &wide_bitmap_p, sizeof wide_bitmap_p); + uint8_t wide_tinted[4]; + memcpy(wide_tinted, catalog_data(WIDE) + at_data(WIDE), 4); + tint_highlight_begin(view, context); + tint_highlight_begin(view, wide_context); + assert(highlighted == SECOND + 1 && + !memcmp(catalog_data(WIDE) + at_data(WIDE), wide_tinted, 4)); + tint_highlight_end(); + assert(catalog_data(SECOND)[at_data(SECOND) + 2] == 10 && !highlighted); + tint_highlight_begin(view, wide_context); + assert(highlighted == WIDE + 1 && catalog_data(WIDE)[at_data(WIDE) + 2] == 88); + tint_highlight_end(); + assert(!memcmp(catalog_data(WIDE) + at_data(WIDE), wide_tinted, 4)); + /* A pointer into a bitmap's middle and a bitmap outside the bank are no + * catalog bitmap: an extension's own icon, drawn in the icon tint role. */ + pixels = catalog_data(SECOND) + HEADER + 4; + memcpy(bitmap + Bitmap_pixels, &pixels, sizeof pixels); + assert(tint_mask_color(view)[0] == 88); + pixels = foreign; + memcpy(bitmap + Bitmap_pixels, &pixels, sizeof pixels); + assert(tint_mask_color(view)[0] == 88); + *(uint32_t *)(view + View_flags) = 0; + assert(tint_mask_color(view)[0] == 10); + pixels = catalog_data(PALETTED) + HEADER; + memcpy(bitmap + Bitmap_pixels, &pixels, sizeof pixels); + assert(!tint_mask_color(view)); + /* ARGB art is not rewritten for a highlight. */ + pixels = catalog_data(ARGB) + HEADER; + memcpy(bitmap + Bitmap_pixels, &pixels, sizeof pixels); + *(uint32_t *)(view + View_flags) = ViewFlags_Highlighted; + tint_highlight_begin(view, context); + assert(catalog_data(ARGB)[HEADER + 2] == 11); + tint_highlight_end(); + /* A calendar marker turns on_accent over the selected day's cell art only. */ + static uint8_t cell[0x200]; + pixels = catalog_data(SECOND) + HEADER; + memcpy(bitmap + Bitmap_pixels, &pixels, sizeof pixels); + memcpy(cell + CalendarDayCell_art, &context_p, sizeof context_p); + const uint8_t *hilite = catalog_data(PALETTED) + HEADER; + static uint8_t hilite_bitmap[0x20]; + memcpy(hilite_bitmap + Bitmap_pixels, &hilite, sizeof hilite); + uint8_t *hilite_p = hilite_bitmap; + memcpy(other_context + GraphicsContext_bitmap, &hilite_p, sizeof hilite_p); + uint8_t *other_p = other_context; + memcpy(cell + CalendarDayCell_art, &other_p, sizeof other_p); + tint_marker_highlight_begin(cell, context); + assert(catalog_data(SECOND)[at_data(SECOND) + 2] == 88); + tint_highlight_end(); + memcpy(cell + CalendarDayCell_art, &context_p, sizeof context_p); + tint_marker_highlight_begin(cell, context); + assert(catalog_data(SECOND)[at_data(SECOND) + 2] == 10); + tint_highlight_end(); + style_reset(); + assert(!tint_mask_color(view)); + reset_bank(); +} + +/* A flat look copies only a 128 by 128 RGB565 image with packed rows into the + * colour buffer and skips the edge lines; any other image, or a look without + * the flag under Theme, keeps the stock drawing. The copy itself needs the 32-bit Bitmap + * layout (the pixel pointer and the stride overlap on a 64-bit host), so the + * emulator covers it. */ +static void cover_contracts(void) +{ + uint8_t prefix[RVT_STYLE_BYTES]; + static const uint8_t roles[RVT_ROLES][3] = {{0}}; + int32_t bounds[4] = {0, 0, 128, 128}; + memcpy(cover_image + Bitmap_bounds, bounds, sizeof bounds); + *(uint16_t *)(cover_image + Bitmap_format) = BMapFormat_RGB565; + *(uint32_t *)(cover_image + Bitmap_stride) = 256; + assert(copyable(cover_image)); + *(uint32_t *)(cover_image + Bitmap_stride) = 512; + assert(!copyable(cover_image)); + *(uint32_t *)(cover_image + Bitmap_stride) = 256; + *(uint16_t *)(cover_image + Bitmap_format) = BMapFormat_BGRA8888; + assert(!copyable(cover_image)); + *(uint16_t *)(cover_image + Bitmap_format) = BMapFormat_RGB565; + bounds[2] = 100; + memcpy(cover_image + Bitmap_bounds, bounds, sizeof bounds); + assert(!copyable(cover_image)); + prefix_custom(prefix, roles, RVT_FLAG_FLAT_NOW_PLAYING, 0, NULL); + style_set(prefix); + assert(flat_cover_edge_lines(2, NULL) == 0); + drawing_view = + &cover_view; /* inside the view's draw, but the image is not copyable */ + assert(flat_cover_renderer_draw(1, NULL) == 0x600d && passed[0] == 1); + drawing_view = NULL; + assert(flat_cover_renderer_draw(1, NULL) == 0x600d); + style_reset(); + assert(flat_cover_renderer_draw(1, NULL) == 0x600d && + flat_cover_edge_lines(2, NULL) == 0x600d); + /* The setting over the look: Tilted keeps the stock draw under a flat + * theme, Flat copies under stock, Theme follows the flag again. */ + flat_cover_set(NP_COVER_FLAT); + assert(flat_cover_flat() && flat_cover_edge_lines(2, NULL) == 0); + style_set(prefix); + flat_cover_set(NP_COVER_TILTED); + assert(!flat_cover_flat() && flat_cover_edge_lines(2, NULL) == 0x600d); + flat_cover_set(NP_COVER_THEME); + assert(flat_cover_flat()); + style_reset(); + assert(!flat_cover_flat()); +} + +/* The latch: the first action binds the watch and holds presses off until + * the message loop runs dry after the switch, which also ends the watch; a + * watch still bound goes at unload; without memory for the watch the switch + * runs unlatched. */ +static void latch_contracts(void) +{ + int before = binds; + assert(latch_begin() && binds == before + 1 && !latch_begin()); + next_result = 0; + assert(process_message(1, 0, NULL) == 0 && binds == before + 1 && + latched); /* still loading */ + latch_finish(); + next_result = 0x600d; + assert(process_message(1, 0, NULL) == 0x600d && latched); /* a message handled */ + next_result = 0; + assert(process_message(1, 0, NULL) == 0 && !latched && binds == before); + assert(latch_begin() && latched && binds == before + 1); + latch_finish(); + latch_unload(); + assert(binds == before && !latched); + bind_failures_at = binds + 1; + assert(latch_begin() && binds == before && !latched); + bind_failures_at = 0; + latch_finish(); + latch_unload(); + next_result = 0x600d; +} + +/* The Theme list: Classic, the folder's themes in order, the active theme + * kept in order when the list is full, and a last row for the overflow or + * the trouble. */ +static void picker_contracts(void) +{ + static char many_names[70][16]; + static const char *many[70]; + const char *detail = (const char *)1; + for (unsigned i = 0; i < 70; i++) { + snprintf(many_names[i], sizeof many_names[i], "t%02u.rvt", i); + many[i] = many_names[i]; + } + folder = many; + folder_count = 70; + unreadable = NULL; + provided = NULL; + memset(&look_state.active, 0, sizeof look_state.active); + strcpy(look_state.active.id, "t99"); + strcpy(look_state.active.name, "Last"); + assert(theme_picker_rows(NULL) == 1 + 64 + 1 && allocations == 1 && count == 64); + assert(!strcmp(theme_picker_row(NULL, 0, &detail), "Classic") && !detail); + assert(!strcmp(theme_picker_row(NULL, 1, &detail), "Named") && + !strcmp(entries[0].id, "t00")); + assert(!strcmp(entries[62].id, "t62") && !strcmp(entries[63].id, "t99")); + assert(!strcmp(theme_picker_row(NULL, 64, &detail), "Last")); + assert(!strcmp(theme_picker_row(NULL, 65, &detail), "Showing 64 themes")); + assert(theme_picker_initial(NULL) == 64 && !theme_picker_select(NULL, 65) && + !module_loaded); + theme_picker_closed(NULL); + assert(!allocations && !count && !overflow && !scanned); + /* Sorting inside the list: inserted in place, the last entry dropped. */ + strcpy(look_state.active.id, "t005"); + assert(theme_picker_rows(NULL) == 66 && !strcmp(entries[1].id, "t005") && + !strcmp(entries[2].id, "t01")); + assert(!strcmp(entries[63].id, "t62") && theme_picker_initial(NULL) == 2); + theme_picker_closed(NULL); + /* Listed already: nothing moves. */ + strcpy(look_state.active.id, "t10"); + assert(theme_picker_rows(NULL) == 66 && !strcmp(entries[10].id, "t10") && + !strcmp(entries[63].id, "t63")); + assert(theme_picker_initial(NULL) == 11); + theme_picker_closed(NULL); + /* Room for every theme: the active one is among them or it is Classic's turn. */ + folder_count = 5; + strcpy(look_state.active.id, "zzz"); + assert(theme_picker_rows(NULL) == 6 && theme_picker_initial(NULL) == 0); + theme_picker_closed(NULL); + strcpy(look_state.active.id, "t03"); + assert(theme_picker_rows(NULL) == 6 && theme_picker_initial(NULL) == 4); + theme_picker_closed(NULL); + /* An empty folder lists Classic alone; no memory for the list says so. */ + folder_count = 0; + assert(theme_picker_rows(NULL) == 1 && !allocations); + theme_picker_closed(NULL); + folder_count = 5; + alloc_fails = 1; + assert(theme_picker_rows(NULL) == 2 && + !strcmp(theme_picker_row(NULL, 1, &detail), "Not enough memory")); + theme_picker_closed(NULL); + assert(!allocations); + folder_count = 0; + memset(&look_state.active, 0, sizeof look_state.active); +} + +/* The draw hooks bind while a look is on; a bind that fails leaves none bound. */ +static void bind_contracts(void) +{ + assert(render_bind(1) && binds == (int)THEMED_HOOKS); + assert(render_bind(1) && binds == (int)THEMED_HOOKS); + assert(render_bind(0) && binds == 0); + bind_failures_at = 5; + assert(!render_bind(1) && binds == 0); + bind_failures_at = 0; + assert(render_bind(0) && binds == 0); +} + +/* The whole of a switch from main's side: a saved theme whose file is gone + * falls back to Classic in the saved appearance, the settings keep the + * appearance and drop the id, the draw hooks and the latch bind, and unload + * puts everything back. */ +static void look_contracts(void) +{ + char id[RVT_ID_BYTES] = "example"; + memset(&look_state, 0, sizeof look_state); + style_reset(); + style_set_dark(0); + style_set_accent(ACCENT_DEFAULT); + strcpy(theme_id_setting, "example"); + setting_set_int(NULL, KEY_DARK, DARK_ON); + setting_ints[KEY_ACCENT] = ACCENT_DEFAULT; + setting_ints[KEY_AVAILABLE] = 1; + folder_count = 0; + unreadable = "example"; + redraws = 0; + look_switch(id, 1, ACCENT_DEFAULT, PANE_THEME); + assert(!look_state.active.id[0] && look_state.active.dark && style_dark() && + !style_from_theme()); + assert(setting_ints[KEY_DARK] == DARK_ON && !strcmp(theme_id_setting, "example") && + setting_ints[KEY_AVAILABLE] == 1); + assert(!strcmp(look_problem(PANE_THEME), "Theme unavailable") && + !look_problem(PANE_DARK)); + assert(look_dark_available() && + binds == (int)THEMED_HOOKS + 1); /* the draw hooks and the latch */ + assert(canvas_colors && redraws == 1 && !module_loaded && !open_files && + !look_theming_off()); + /* A second press while the latch holds changes nothing. */ + look_switch(id, 0, ACCENT_DEFAULT, PANE_DARK); + assert(look_state.active.dark && setting_ints[KEY_DARK] == DARK_ON && redraws == 1); + /* An accent change keeps the stored theme too; choosing Classic drops it. */ + latch_unload(); + look_accent(ACCENT_FIRST); + assert(!strcmp(theme_id_setting, "example") && style_accent() == ACCENT_FIRST); + latch_unload(); + look_switch("", 1, ACCENT_DEFAULT, PANE_THEME); + assert(!theme_id_setting[0] && !look_problem(PANE_THEME)); + latch_unload(); + look_unload(); + assert(bank_is_stock() && binds == 0 && !canvas_colors && !look_state.active.dark); + + /* A theme with one appearance is shown in it whatever Dark Mode asked: + * the row's value and the stored setting say which, the pane says what + * the theme lacks, and a refused toggle leaves them so. */ + struct built light_only, dark_only; + build_light_only(&light_only, PROVIDED_ID, "Day"); + build_file_at(&dark_only, PROVIDED_ID, "Night", RVT_HEADER_BYTES, NULL, 0, NULL, 0, + NULL, NULL); + provided = &light_only; + unreadable = NULL; + memset(id, 0, sizeof id); /* ids are zero-padded */ + strcpy(id, PROVIDED_ID); + look_switch(id, 1, ACCENT_DEFAULT, PANE_THEME); + assert(!strcmp(look_state.active.id, PROVIDED_ID) && !look_state.active.dark && + !style_dark()); + assert(setting_ints[KEY_DARK] == DARK_OFF && !look_dark_available() && + !look_problem(PANE_DARK) && !look_problem(PANE_THEME) && + !strcmp(look_appearance_note(), "Theme only supports light mode")); + latch_unload(); + setting_set_int(NULL, KEY_DARK, + DARK_ON); /* the press, as the store sees it first */ + look_switch(id, 1, ACCENT_DEFAULT, PANE_DARK); + assert(!look_state.active.dark && setting_ints[KEY_DARK] == DARK_OFF && + !look_problem(PANE_DARK) && + !strcmp(look_appearance_note(), "Theme only supports light mode") && + !open_files); + latch_unload(); + provided = &dark_only; + look_switch(id, 0, ACCENT_DEFAULT, PANE_THEME); + assert(look_state.active.dark && style_dark() && + setting_ints[KEY_DARK] == DARK_ON && + !strcmp(look_appearance_note(), "Theme only supports dark mode")); + latch_unload(); + setting_set_int(NULL, KEY_DARK, DARK_OFF); + look_switch(id, 0, ACCENT_DEFAULT, PANE_DARK); + assert(look_state.active.dark && setting_ints[KEY_DARK] == DARK_ON && + !look_problem(PANE_DARK) && + !strcmp(look_appearance_note(), "Theme only supports dark mode")); + latch_unload(); + look_switch("", 1, ACCENT_DEFAULT, PANE_THEME); + assert(!look_appearance_note() && look_dark_available()); + latch_unload(); + look_unload(); + provided = NULL; + + /* A theme with bitmaps for extensions, or one asking for flat icons, + * holds the core's asset provider; Classic and unload release it and free + * the index; the end of disk mode keeps both until another file turns up + * under the id; a provider another extension holds is said under Theme. */ + struct built with, flat, swapped; + const struct asset_payload one = { + OWNER_A, 5, RVT_EXTENSION_BITMAP, sizeof menu_a, MENU_BMAP_BYTES, menu_a, 0}; + with_assets(&one, 1, &with); + provided = &with; + unreadable = NULL; + strcpy(id, PROVIDED_ID); + look_switch(id, 1, ACCENT_DEFAULT, PANE_THEME); + assert(!strcmp(look_state.active.id, PROVIDED_ID) && core_provider == &provider && + live_count == 1); + assert(look_state.active.header_crc == le32(with.bytes + RVT_HEADER_CRC) && + !look_problem(PANE_THEME)); + latch_unload(); /* the message queue empties between presses */ + look_accent(ACCENT_FIRST); + assert(core_provider == &provider && live_count == 1); + latch_unload(); + look_switch("", 1, ACCENT_DEFAULT, PANE_THEME); + assert(!core_provider && !live_count && !allocations); + latch_unload(); + look_switch(id, 1, ACCENT_DEFAULT, PANE_THEME); + assert(core_provider == &provider); + latch_unload(); + look_volume_changed(); + assert(core_provider == &provider && live_count == 1 && !look_state.stock_checked); + build_file_at(&swapped, PROVIDED_ID, "Other", RVT_HEADER_BYTES, NULL, 0, NULL, 0, + NULL, NULL); + provided = &swapped; + look_volume_changed(); + assert(!core_provider && !live_count && !allocations && !open_files); + uint8_t prefix[RVT_STYLE_BYTES]; + static const uint8_t roles[RVT_ROLES][3] = {{0}}; + prefix_custom(prefix, roles, RVT_FLAG_FLAT_ICONS, 0, NULL); + build_file_at(&flat, PROVIDED_ID, "Flat", RVT_HEADER_BYTES, NULL, 0, NULL, 0, NULL, + prefix); + provided = ♭ + look_switch(id, 1, ACCENT_DEFAULT, PANE_THEME); + assert(core_provider == &provider && !live_count); + latch_unload(); + provided = &swapped; /* flat icons stay bound without an index */ + look_volume_changed(); + assert(core_provider == &provider && !live_count); + provided = ♭ + look_switch("", 1, ACCENT_DEFAULT, PANE_THEME); + assert(!core_provider); + latch_unload(); + provider_held = 1; + provided = &with; + look_switch(id, 1, ACCENT_DEFAULT, PANE_THEME); + assert(!strcmp(look_problem(PANE_THEME), "Artwork held by another extension") && + live_count == 1); + assert(!core_provider); + provider_held = 0; + look_unload(); + assert(!core_provider && !live_count && !allocations && bank_is_stock()); + provided = NULL; +} + +/* Sunrise and sunset against NOAA's formula in double precision, in UTC. */ +/* The schedule: night from the sunset minute to the sunrise minute, by the + * clock in the time zone's city; the polar states; no zone is day. */ +static void schedule_contracts(void) +{ + struct schedule s; + /* Without a known zone: day, and the caption asks for one. */ + schedule_read(&s); + assert(s.state == SCHEDULE_NO_ZONE && !schedule_night(&s)); + assert(!strcmp(schedule_caption(), "Set a Time Zone")); + /* Berlin, 21 June: sunset 21:33 CEST, sunrise 04:43 (NOAA, within 3 minutes). */ + put16(host_zones + 90 * TimeZone_bytes + TimeZone_zone_id, 0x1234); + memcpy(host_app + App_browser, &(uint8_t *){host_browser}, sizeof(void *)); + memcpy(host_browser + MediaBrowser_preferences, &(uint8_t *){host_preferences}, + sizeof(void *)); + put16(host_preferences + PreferencesFile_time_zone_id, 0x1234); + clock_now[DateTime_hour] = 21, clock_now[DateTime_minute] = 0; + clock_now[DateTime_day] = 21, clock_now[DateTime_month] = 6; + put16(clock_now + DateTime_year, 2026); + clock_zone = 60, clock_dst = 60; + schedule_read(&s); + assert(s.state == SCHEDULE_RISES && s.now == 21 * 60 && !schedule_night(&s)); + assert(abs(s.set - (21 * 60 + 33)) <= 3 && abs(s.rise - (4 * 60 + 43)) <= 3); + clock_now[DateTime_hour] = (uint8_t)(s.set / 60), + clock_now[DateTime_minute] = (uint8_t)(s.set % 60); + schedule_read(&s); + assert(schedule_night(&s)); /* the sunset minute itself */ + clock_now[DateTime_minute]--; + schedule_read(&s); + assert(!schedule_night(&s)); + clock_now[DateTime_hour] = (uint8_t)(s.rise / 60), + clock_now[DateTime_minute] = (uint8_t)(s.rise % 60); + schedule_read(&s); + assert(!schedule_night(&s)); /* the sunrise minute is day */ + clock_now[DateTime_minute]--; + schedule_read(&s); + assert(schedule_night(&s)); + assert(!strcmp(schedule_caption(), "Sunset to Sunrise")); + /* No city in Apple's zones lies beyond a polar circle, so the polar states + * are checked on their own. */ + s.state = SCHEDULE_NEVER_RISES; + assert(schedule_night(&s)); + s.state = SCHEDULE_NEVER_SETS; + assert(!schedule_night(&s)); + /* No such zone: day, and the caption asks for one. */ + put16(host_preferences + PreferencesFile_time_zone_id, 0x7777); + schedule_read(&s); + assert(s.state == SCHEDULE_NO_ZONE && !schedule_night(&s)); + assert(!strcmp(schedule_caption(), "Set a Time Zone")); + put16(host_preferences + PreferencesFile_time_zone_id, 0x1234); + clock_now[DateTime_hour] = 23, clock_now[DateTime_minute] = 0; +} + +/* Dark Mode: On and Off ask for themselves, Auto asks for the schedule's + * night; a switch that shows what Auto asked for keeps Auto, one that cannot + * writes the appearance on the screen. */ +static void dark_mode_contracts(void) +{ + struct built light_only; + char id[RVT_ID_BYTES]; + setting_set_int(NULL, KEY_DARK, DARK_ON); + assert(dark_mode_wanted() && !dark_mode_auto()); + setting_set_int(NULL, KEY_DARK, DARK_OFF); + assert(!dark_mode_wanted()); + setting_set_int(NULL, KEY_DARK, DARK_AUTO); + assert(dark_mode_auto() && dark_mode_wanted()); /* Berlin, 23:00 */ + clock_now[DateTime_hour] = 13; + assert(!dark_mode_wanted()); + clock_now[DateTime_hour] = 23; + + memset(&look_state, 0, sizeof look_state); + style_reset(); + style_set_dark(0); + theme_id_setting[0] = 0; + unreadable = NULL; + redraws = 0; + look_switch("", dark_mode_wanted(), ACCENT_DEFAULT, PANE_DARK); + assert(look_state.active.dark && setting_ints[KEY_DARK] == DARK_AUTO); + assert(!strcmp(dark_mode_caption(), "Sunset to Sunrise")); + latch_unload(); + /* A light-only theme at night: the screen stays light and the setting says Off. */ + build_light_only(&light_only, PROVIDED_ID, "Day"); + provided = &light_only; + memset(id, 0, sizeof id); + strcpy(id, PROVIDED_ID); + look_switch(id, dark_mode_wanted(), ACCENT_DEFAULT, PANE_THEME); + assert(!look_state.active.dark && setting_ints[KEY_DARK] == DARK_OFF && + !dark_mode_auto()); + assert(!strcmp(dark_mode_caption(), "Theme only supports light mode")); + latch_unload(); + look_switch("", 0, ACCENT_DEFAULT, PANE_THEME); + assert(!strcmp(dark_mode_caption(), "Off")); + latch_unload(); + look_unload(); + provided = NULL; +} + +int main(void) +{ + rv_module_entry(&fake, NULL); + assert(main_module == &host_service); + build_bank(); + + reader_contracts(); + puts("PASS: theme file reader"); + switch_contracts(); + puts("PASS: switch and recovery"); + assets_contracts(); + puts("PASS: bitmaps for extensions"); + scan_contracts(); + puts("PASS: theme folder"); + classic_mapping(); + copied_view_text(); + accent_mapping(); + theme_mapping(); + bar_mapping(); + puts("PASS: colour mapping"); + tint_contracts(); + cover_contracts(); + latch_contracts(); + picker_contracts(); + bind_contracts(); + puts("PASS: tinted art, flat cover, latch, theme list, hook binding"); + look_contracts(); + puts("PASS: look fallback and unload"); + schedule_contracts(); + dark_mode_contracts(); + puts("PASS: schedule, Dark Mode"); + return 0; +} diff --git a/extensions/appearance/tests/run.py b/extensions/appearance/tests/run.py new file mode 100755 index 0000000..b0f63c1 --- /dev/null +++ b/extensions/appearance/tests/run.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +"""Run the appearance contracts with a staged SDK: python3 tests/run.py SDK. + +The extension's logic is built natively, both modules in one program, over a +bitmap bank and a firmware file in host memory. Hook handlers carry pointers in +uint32_t by the ARM convention, so the host build allows the narrowing casts and +reads Apple's struct fields unaligned.""" + +import subprocess +import sys +import tempfile +from pathlib import Path + +root = Path(__file__).resolve().parent +sdk = Path(sys.argv[1]).resolve() +with tempfile.TemporaryDirectory(prefix="appearance-tests-") as name: + work = Path(name) + for header in ("rv_api.h", "rv_libc.h", "rv_ui.h", "rv_theme.h", "rv_sites.h", "osos-2.0.5.h"): + (work / header).write_text((sdk / header).read_text()) + executable = work / "contracts" + subprocess.run( + [ + "cc", + "-std=c11", + "-Wall", + "-Wextra", + "-Werror", + "-Wno-int-to-pointer-cast", + "-Wno-pointer-to-int-cast", + "-g", + "-fsanitize=address,undefined", + "-fno-sanitize=alignment", + "-I", + str(root), + "-I", + str(work), + "-I", + str(root.parent), + "-I", + str(root.parents[1] / "shared"), + "-I", + str(root.parents[2] / "themes" / "rvt" / "data"), + str(root / "contracts.c"), + "-o", + str(executable), + ], + check=True, + ) + subprocess.run([str(executable)], check=True) +print("Appearance contracts passed") diff --git a/extensions/appearance/theme.c b/extensions/appearance/theme.c new file mode 100644 index 0000000..2d6d704 --- /dev/null +++ b/extensions/appearance/theme.c @@ -0,0 +1,279 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "theme.h" +#include "crc.h" +#include "ext.h" +#include "pixel.h" +#include "rv_libc.h" +#include + +#define FOLDER "Themes" +#define SUFFIX ".rvt" +/* The id of the built-in theme, which is the asset's name; a file of that + * name in the folder is ignored. */ +#define RESERVED_ID "classic" + +static int id_valid(const char *id) +{ + uint32_t n = 0; + for (; n < RVT_ID_BYTES && id[n]; n++) { + char c = id[n]; + if (!((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || + (n && (c == '_' || c == '-')))) + return 0; + } + if (!n || n > RVT_ID_BYTES - 1) + return 0; + for (; n < RVT_ID_BYTES; n++) + if (id[n]) + return 0; + return !!memcmp(id, RESERVED_ID, sizeof RESERVED_ID); +} + +/* Printable UTF-8 up to the first NUL, zeros after it. */ +static int name_valid(const uint8_t *text, uint32_t size) +{ + uint32_t at = 0; + if (!text[0]) + return 0; + while (at < size && text[at]) { + uint32_t cp = text[at++], tails = 0, minimum = 0; + if (cp >= 0xc2 && cp <= 0xdf) + cp &= 31, tails = 1, minimum = 0x80; + else if (cp >= 0xe0 && cp <= 0xef) + cp &= 15, tails = 2, minimum = 0x800; + else if (cp >= 0xf0 && cp <= 0xf4) + cp &= 7, tails = 3, minimum = 0x10000; + else if (cp >= 0x80) + return 0; + if (tails > size - at) + return 0; + while (tails--) { + uint32_t c = text[at++]; + if ((c & 0xc0) != 0x80) + return 0; + cp = cp << 6 | (c & 63); + } + if (cp < minimum || cp > 0x10ffff || (cp >= 0xd800 && cp <= 0xdfff) || + cp < 32 || cp == 127) + return 0; + } + if (at == size) + return 0; + for (; at < size; at++) + if (text[at]) + return 0; + return 1; +} + +/* The header (RVT_HEADER_BYTES) with its fields checked: magic, version, + * header size, checksum, fingerprint, appearances and name. The id is the + * caller's to compare. */ +static int header_read(struct rv_file *file, uint8_t *header) +{ + uint32_t got = 0; + if (api->file_seek(self, file, 0) != RV_OK || + api->file_read(self, file, header, RVT_HEADER_BYTES, &got) != RV_OK || + got != RVT_HEADER_BYTES) + return 0; + uint8_t zero[4] = {0}; + uint32_t computed = crc32_update(0xffffffffu, header, RVT_HEADER_CRC); + computed = crc32_update(computed, zero, 4); + computed = ~crc32_update(computed, header + RVT_HEADER_ID, + RVT_HEADER_BYTES - RVT_HEADER_ID); + uint32_t mask = le32(header + RVT_HEADER_APPEARANCES); + uint32_t header_bytes = le16(header + RVT_HEADER_HEADER_BYTES); + return le32(header + RVT_HEADER_MAGIC) == RVT_MAGIC && + le16(header + RVT_HEADER_VERSION) == RVT_VERSION && + header_bytes >= RVT_HEADER_BYTES && header_bytes % 4 == 0 && + computed == le32(header + RVT_HEADER_CRC) && + !memcmp(header + RVT_HEADER_FINGERPRINT, catalog_fingerprint(), + RVT_FINGERPRINT_BYTES) && + mask && !(mask & ~(uint32_t)(RVT_APPEARANCE_LIGHT | RVT_APPEARANCE_DARK)) && + name_valid(header + RVT_HEADER_NAME, RVT_NAME_BYTES); +} + +/* The light or dark pack's place from a checked header: 0 when the header + * has no such pack, puts it before its own end or off a word, or sizes it + * below a pack header and style prefix. */ +static int pack_place(const uint8_t *header, int dark, struct pack_place *pack) +{ + uint32_t at = dark ? RVT_HEADER_DARK_OFFSET : RVT_HEADER_LIGHT_OFFSET; + uint32_t offset = le32(header + at), bytes = le32(header + at + 4); + if (!offset || bytes < RVT_PACK_HEADER_BYTES + RVT_STYLE_BYTES || offset % 4 || + offset < le16(header + RVT_HEADER_HEADER_BYTES) || bytes > 0xffffffffu - offset) + return 0; + pack->offset = offset; + pack->bytes = bytes; + return 1; +} + +/* A checked header of theme `id` into `look`, or 0 for another id. */ +static int header_look(const uint8_t *header, const char *id, struct look *look) +{ + if (memcmp(header + RVT_HEADER_ID, id, RVT_ID_BYTES)) + return 0; + memset(look, 0, sizeof *look); + memcpy(look->id, header + RVT_HEADER_ID, RVT_ID_BYTES); + memcpy(look->name, header + RVT_HEADER_NAME, RVT_NAME_BYTES); + look->appearances = le32(header + RVT_HEADER_APPEARANCES); + look->header_crc = le32(header + RVT_HEADER_CRC); + return 1; +} + +static char lower(char c) +{ + return c >= 'A' && c <= 'Z' ? (char)(c + ('a' - 'A')) : c; +} + +/* The id a file name stands for: its stem in lower case, since FAT may return + * short names in capitals; 0 for another suffix or a stem that is no id. */ +static int stem_id(const char *entry, char id[RVT_ID_BYTES]) +{ + uint32_t n = 0; + while (entry[n]) + n++; + if (n < sizeof SUFFIX || n - (sizeof SUFFIX - 1) > RVT_ID_BYTES - 1) + return 0; + for (uint32_t i = 0; i < sizeof SUFFIX - 1; i++) + if (lower(entry[n - (sizeof SUFFIX - 1) + i]) != SUFFIX[i]) + return 0; + n -= sizeof SUFFIX - 1; + memset(id, 0, RVT_ID_BYTES); + for (uint32_t i = 0; i < n; i++) + id[i] = lower(entry[i]); + return id_valid(id); +} + +static void path_of(const char *id, char *path) +{ + memcpy(path, FOLDER "/", sizeof FOLDER); + uint32_t n = sizeof FOLDER; + while (*id) + path[n++] = *id++; + memcpy(path + n, SUFFIX, sizeof SUFFIX); +} + +static int theme_file_open(const char *id, struct rv_file **file) +{ + char path[sizeof FOLDER + RVT_ID_BYTES + sizeof SUFFIX]; + path_of(id, path); + return api->content_open(self, path, file) == RV_OK; +} + +int look_file_open(const struct look *look, struct rv_file **file) +{ + if (look->id[0]) + return theme_file_open(look->id, file); + return look->dark && api->asset_open(self, RESERVED_ID, file) == RV_OK; +} + +int look_pack_place(struct rv_file *file, struct look *look, struct pack_place *pack) +{ + uint8_t header[RVT_HEADER_BYTES]; + if (!header_read(file, header) || + (look->id[0] && memcmp(header + RVT_HEADER_ID, look->id, RVT_ID_BYTES))) + return 0; + look->header_crc = le32(header + RVT_HEADER_CRC); + return pack_place(header, look->dark, pack); +} + +int theme_file_matches(const char *id, uint32_t crc) +{ + uint8_t header[RVT_HEADER_BYTES]; + struct rv_file *file; + if (!theme_file_open(id, &file)) + return 0; + int same = header_read(file, header) && le32(header + RVT_HEADER_CRC) == crc; + api->file_close(self, file); + return same; +} + +static void count_entry(const char *entry, int is_folder, void *arg) +{ + char id[RVT_ID_BYTES]; + if (!is_folder && stem_id(entry, id)) + ++*(uint32_t *)arg; +} + +uint32_t theme_count(void) +{ + uint32_t n = 0; + api->content_list(self, FOLDER, count_entry, &n); + return n; +} + +struct scan { + struct theme_entry *out; + uint32_t capacity, count; + int overflow; +}; + +/* Collects ids in order while the folder is listed; files are opened after. */ +static void collect(const char *entry, int is_folder, void *arg) +{ + struct scan *s = arg; + char id[RVT_ID_BYTES]; + if (is_folder || !stem_id(entry, id)) + return; + uint32_t at = s->count; + while (at && memcmp(s->out[at - 1].id, id, RVT_ID_BYTES) > 0) + at--; + if (at && !memcmp(s->out[at - 1].id, id, RVT_ID_BYTES)) + return; + if (s->count == s->capacity) { + s->overflow = 1; + if (at == s->capacity) + return; + s->count--; + } + memmove(s->out + at + 1, s->out + at, (s->count - at) * sizeof *s->out); + memcpy(s->out[at].id, id, RVT_ID_BYTES); + s->count++; +} + +uint32_t theme_scan(struct theme_entry *out, uint32_t capacity, int *overflow) +{ + struct scan s = {out, capacity, 0, 0}; + struct look look; + struct rv_file *file; + uint8_t header[RVT_HEADER_BYTES]; + api->content_list(self, FOLDER, collect, &s); + uint32_t kept = 0; + for (uint32_t i = 0; i < s.count; i++) { + if (!theme_file_open(out[i].id, &file)) + continue; + int ok = header_read(file, header) && header_look(header, out[i].id, &look); + api->file_close(self, file); + if (!ok) + continue; + memcpy(out[kept].id, look.id, RVT_ID_BYTES); + memcpy(out[kept].name, look.name, RVT_NAME_BYTES); + kept++; + } + *overflow = s.overflow; + return kept; +} + +enum theme_result theme_open(const char *id, int dark, struct rv_file **file, + struct look *look, struct pack_place *pack) +{ + uint8_t header[RVT_HEADER_BYTES]; + enum theme_result result = THEME_OK; + *file = NULL; + if (!id_valid(id) || !theme_file_open(id, file)) + return THEME_UNAVAILABLE; + if (header_read(*file, header) && header_look(header, id, look)) { + if (!(look->appearances & + (dark ? RVT_APPEARANCE_DARK : RVT_APPEARANCE_LIGHT))) { + dark = !dark; + result = THEME_NOT_IN_APPEARANCE; + } + look->dark = dark; + if (pack_place(header, dark, pack)) + return result; + } + api->file_close(self, *file); + *file = NULL; + return THEME_UNAVAILABLE; +} diff --git a/extensions/appearance/theme.h b/extensions/appearance/theme.h new file mode 100644 index 0000000..8ac4a43 --- /dev/null +++ b/extensions/appearance/theme.h @@ -0,0 +1,46 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* Theme files a listener copies to /Reprise/Themes/: .rvt, named after + * the id inside, and the `classic` asset, a theme file with the Classic dark + * pack. This reads and checks their headers; the switch module reads the + * packs where the header places them. */ + +#ifndef THEME_H +#define THEME_H +#include "look.h" +#include "rv_api.h" +#include + +struct theme_entry { + char id[RVT_ID_BYTES]; + char name[RVT_NAME_BYTES]; +}; + +/* How many files in the folder are named like a theme, before any is opened. */ +uint32_t theme_count(void); +/* The readable themes sorted by id, at most `capacity`; *overflow says more + * were named like one. */ +uint32_t theme_scan(struct theme_entry *out, uint32_t capacity, int *overflow); + +enum theme_result { + THEME_OK, + THEME_UNAVAILABLE, /* no such file, or not a theme of that id */ + THEME_NOT_IN_APPEARANCE /* opened, but has only the other appearance */ +}; +/* Opens theme `id` and fills `look` from its header, with `look->dark` the + * appearance asked for, or the only one the theme has, and `pack` where that + * appearance's pack is. The file is the caller's to close unless the theme is + * unavailable. */ +enum theme_result theme_open(const char *id, int dark, struct rv_file **file, + struct look *look, struct pack_place *pack); +/* Opens the file a look's pack is in without reading it: a theme's by id, + * Classic dark's the `classic` asset. 0 for Classic light, which has none. */ +int look_file_open(const struct look *look, struct rv_file **file); +/* Checks the header of `file`, opened for `look` (its id when it has one), + * sets look->header_crc and places the pack of look->dark; 0 when the file is + * no theme of that id or lacks the pack. */ +int look_pack_place(struct rv_file *file, struct look *look, struct pack_place *pack); +/* Whether theme `id`'s file is still the one whose header checksum is `crc`. */ +int theme_file_matches(const char *id, uint32_t crc); + +#endif diff --git a/extensions/appearance/theme_picker.c b/extensions/appearance/theme_picker.c new file mode 100644 index 0000000..8179bb3 --- /dev/null +++ b/extensions/appearance/theme_picker.c @@ -0,0 +1,120 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* Settings > Theme: a list of Classic and the themes in /Reprise/Themes/, + * scanned when the screen opens into a block sized by a count of the folder + * and freed when it closes. More than THEMES entries end in a row saying so. */ + +#include "theme_picker.h" +#include "ext.h" +#include "look.h" +#include "rv_libc.h" +#include "theme.h" +#include + +#define THEMES 64 +#define STRINGIFY_(n) #n +#define STRINGIFY(n) STRINGIFY_(n) + +static struct theme_entry *entries; /* the scanned themes while the screen is open */ +static uint32_t count; /* themes in the list */ +static int overflow; /* the folder held more themes than the list shows */ +static int scanned; /* the folder was read since the screen opened */ +static const char *problem; /* the picker's own trouble: no memory for the list */ + +/* The active theme stays listed when the sorted list is full: in order, in + * place of the last entry when it sorts after every other. */ +static void insert_active(uint32_t capacity) +{ + const struct look *active = look_active(); + uint32_t at = 0; + while (at < count && memcmp(entries[at].id, active->id, RVT_ID_BYTES) < 0) + at++; + if (at < count && !memcmp(entries[at].id, active->id, RVT_ID_BYTES)) + return; + if (count == capacity) { + if (at == count) + at--; + else + memmove(entries + at + 1, entries + at, (count - 1 - at) * sizeof *entries); + } else { + memmove(entries + at + 1, entries + at, (count - at) * sizeof *entries); + count++; + } + memcpy(entries[at].id, active->id, RVT_ID_BYTES); + memcpy(entries[at].name, active->name, RVT_NAME_BYTES); +} + +/* The list is scanned the first time the screen asks for it, which is while + * it is built, before `opened`. */ +static void scan(void) +{ + if (scanned) + return; + scanned = 1; + uint32_t capacity = theme_count(); + if (!capacity) + return; + if (capacity > THEMES) + capacity = THEMES; + entries = api->alloc(self, capacity * sizeof *entries); + if (!entries) { + problem = "Not enough memory"; + return; + } + count = theme_scan(entries, capacity, &overflow); + if (overflow && count && look_active()->id[0]) + insert_active(capacity); +} + +void theme_picker_closed(const struct rv_context *ctx) +{ + (void)ctx; + if (entries) + api->free(self, entries); + entries = NULL; + problem = NULL; + count = overflow = scanned = 0; +} + +static const char *trouble(void) +{ + return problem ? problem : look_problem(PANE_THEME); +} + +uint32_t theme_picker_rows(const struct rv_context *ctx) +{ + (void)ctx; + scan(); + return 1 + count + (overflow || trouble()); +} + +const char *theme_picker_row(const struct rv_context *ctx, uint32_t index, + const char **detail) +{ + (void)ctx; + *detail = NULL; + if (index == 0) + return "Classic"; + if (index <= count) + return entries[index - 1].name; + return trouble() ? trouble() : "Showing " STRINGIFY(THEMES) " themes"; +} + +int theme_picker_select(const struct rv_context *ctx, uint32_t index) +{ + (void)ctx; + if (index > count) + return 0; + look_select(index ? entries[index - 1].id : ""); + return 0; +} + +uint32_t theme_picker_initial(const struct rv_context *ctx) +{ + (void)ctx; + const struct look *active = look_active(); + for (uint32_t i = 0; i < count; i++) + if (!memcmp(entries[i].id, active->id, RVT_ID_BYTES)) + return i + 1; + return 0; +} diff --git a/extensions/appearance/theme_picker.h b/extensions/appearance/theme_picker.h new file mode 100644 index 0000000..4a7fd9d --- /dev/null +++ b/extensions/appearance/theme_picker.h @@ -0,0 +1,22 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#ifndef THEME_PICKER_H +#define THEME_PICKER_H +#include "rv_api.h" +#include "rv_ui.h" + +/* The Theme screen: Classic, then the themes in the folder. */ +uint32_t theme_picker_rows(const struct rv_context *ctx); +const char *theme_picker_row(const struct rv_context *ctx, uint32_t index, + const char **detail); +int theme_picker_select(const struct rv_context *ctx, uint32_t index); +uint32_t theme_picker_initial(const struct rv_context *ctx); +void theme_picker_closed(const struct rv_context *ctx); +#define THEME_PICKER_SCREEN \ + RV_SCREEN_DYNAMIC_LIST("theme", "Theme", theme_picker_rows, theme_picker_row, \ + .dynamic.select = theme_picker_select, \ + .dynamic.initial = theme_picker_initial, \ + .closed = theme_picker_closed, \ + .bitmap = RV_BITMAP("settings-theme")) + +#endif diff --git a/extensions/appearance/tint.c b/extensions/appearance/tint.c new file mode 100644 index 0000000..f9df187 --- /dev/null +++ b/extensions/appearance/tint.c @@ -0,0 +1,306 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "tint.h" +#include "catalog.h" +#include "osos-2.0.5.h" +#include "pixel.h" +#include "rv_api.h" +#include "rv_libc.h" +#include "style.h" +#include + +/* One past the index of the bitmap whose palette holds the on-accent colour + * between the two halves of one blit; 0 when none. */ +static uint32_t highlighted; + +/* The label colours that contrast with the artwork, picked once per switch: + * the wells, the Search field, the contrast texts, then the calendar's + * active cell, inactive cell and page; alpha 0 where the stock colour stays. */ +enum { + CONTRAST_WELL, + CONTRAST_FIELD = WELLS, + CONTRAST_TEXT, + CONTRAST_CALENDAR = CONTRAST_TEXT + CATALOG_CONTRAST_TEXTS, + CONTRASTS = CONTRAST_CALENDAR + 3 +}; + +static uint8_t contrast[CONTRASTS][4]; + +typedef void (*pixel_fn)(uint8_t *bgra, const uint8_t *color); + +/* Palette entries and ARGB pixels are BGRA; coverage stays in the alpha byte. + * Every palette entry is visited; clear ARGB pixels keep their bytes so stock + * art still compares exactly. */ +static void each_entry(uint8_t *entry, uint32_t colors, pixel_fn fn, + const uint8_t *color) +{ + for (; colors--; entry += 4) + fn(entry, color); +} + +static void each_pixel(uint32_t index, pixel_fn fn, const uint8_t *color) +{ + uint32_t colors, width, height, stride; + uint8_t *entry = catalog_palette(index, &colors); + if (entry) { + each_entry(entry, colors, fn, color); + return; + } + uint8_t *row = catalog_argb(index, &width, &height, &stride); + if (!row) + return; + for (; height--; row += stride) + for (uint8_t *p = row, *end = row + width * 4; p < end; p += 4) + if (p[3]) + fn(p, color); +} + +static void paint(uint8_t *bgra, const uint8_t *color) +{ + bgra[0] = color[2]; + bgra[1] = color[1]; + bgra[2] = color[0]; +} + +enum { + GRAY_CHROMA = + 24, /* below this (max minus min channel) a pixel is grey: letters, gloss, shadows */ + FULL_CHROMA = 96, /* from here on a pixel is fully recoloured; between, blended */ + BRIGHTNESS_MAX = 255 * 256, + /* Stock accent art is shaded around the stock accent fill, (35, 108, 197). */ + STOCK_ACCENT_BRIGHTNESS = 54 * 35 + 183 * 108 + 19 * 197, +}; + +/* Moves `color` toward white or black by how much brighter or darker the stock + * pixel is than the stock blue, so that blue becomes `color` exactly and the + * art keeps its gradients. */ +static void colorize(uint8_t *bgra, const uint8_t *color) +{ + static const uint8_t white[4] = {255, 255, 255, 255}, black[4] = {0, 0, 0, 255}; + uint8_t stock[4] = {bgra[2], bgra[1], bgra[0], 255}, shaded[4]; + int high = stock[0], low = stock[0]; + for (unsigned i = 1; i < 3; i++) { + high = stock[i] > high ? stock[i] : high; + low = stock[i] < low ? stock[i] : low; + } + int chroma = high - low; + if (chroma < GRAY_CHROMA) + return; + int brightness = color_brightness(stock); + if (brightness >= STOCK_ACCENT_BRIGHTNESS) + color_mix(shaded, color, white, + divide((unsigned)(brightness - STOCK_ACCENT_BRIGHTNESS) * 255, + reciprocal(BRIGHTNESS_MAX - STOCK_ACCENT_BRIGHTNESS))); + else + color_mix(shaded, color, black, + divide((unsigned)(STOCK_ACCENT_BRIGHTNESS - brightness) * 255, + reciprocal(STOCK_ACCENT_BRIGHTNESS))); + unsigned weight = chroma >= FULL_CHROMA + ? 255 + : divide((unsigned)(chroma - GRAY_CHROMA) * 255, + reciprocal(FULL_CHROMA - GRAY_CHROMA)); + color_mix(shaded, stock, shaded, weight); + paint(bgra, shaded); +} + +int tint_bmap(void *bmap, uint32_t bytes, const uint8_t *color) +{ + uint8_t *b = bmap; + uint32_t format = le16(b + BMap_format), stride = le16(b + BMap_stride); + const uint8_t *bounds = b + BMap_bounds; + uint32_t height = le32(bounds + 8) - le32(bounds), + width = le32(bounds + 12) - le32(bounds + 4); + uint8_t *rows = b + BMap_payload; + if (bytes < BMap_payload || le32(b + BMap_payload_bytes) > bytes - BMap_payload) + return 0; + if (format == BMapFormat_Indexed8) { + uint32_t colors = le32(rows); + if (le32(b + BMap_payload_bytes) < 4 + colors * 4) + return 0; + each_entry(rows + 4, colors, paint, color); + return 1; + } + if (format != BMapFormat_BGRA8888 || le16(b + BMap_depth) != 32 || + width * 4 > stride || height * stride > le32(b + BMap_payload_bytes)) + return 0; + for (; height--; rows += stride) + for (uint8_t *p = rows, *end = rows + width * 4; p < end; p += 4) + if (p[3]) + paint(p, color); + return 1; +} + +/* The pixel data of a bitmap context's bitmap, or NULL. */ +static const uint8_t *context_pixels(const void *context) +{ + const uint8_t *bitmap = + context ? RV_FIELD(context, GraphicsContext_bitmap, const uint8_t *) : NULL; + return bitmap ? RV_FIELD(bitmap, Bitmap_pixels, const uint8_t *) : NULL; +} + +const uint8_t *tint_mask_color(const void *view) +{ + uint32_t index; + const uint8_t *pixels = + context_pixels(RV_FIELD(view, BitmapView_context, const void *)); + const uint8_t *color = NULL; + if (!pixels || !style_from_theme()) + return NULL; + if (!catalog_from_pixels(pixels, &index)) + color = style_color(RVT_ROLE_ICON_TINT); + else if (style_tinted(index)) + color = style_tint_color(index); + if (color && (RV_FIELD(view, View_flags, uint32_t) & ViewFlags_Highlighted)) + return style_color(RVT_ROLE_ON_ACCENT); + return color; +} + +/* A tinted paletted bitmap: its palette takes the on-accent colour until the + * end call. ARGB art would need every pixel rewritten twice per blit. A blit + * inside another's two halves leaves the first one's bitmap the highlighted + * one. */ +static void highlight(const void *context) +{ + uint32_t index, colors; + uint8_t *entry; + const uint8_t *pixels = context_pixels(context); + if (highlighted || !pixels || !catalog_from_pixels(pixels, &index) || + !style_tinted(index) || !(entry = catalog_palette(index, &colors))) + return; + each_entry(entry, colors, paint, style_color(RVT_ROLE_ON_ACCENT)); + highlighted = index + 1; +} + +void tint_highlight_begin(const void *view, const void *context) +{ + if (style_from_theme() && + (RV_FIELD(view, View_flags, uint32_t) & ViewFlags_Highlighted)) + highlight(context); +} + +void tint_marker_highlight_begin(const void *cell, const void *context) +{ + uint32_t index; + const uint8_t *art = + context_pixels(RV_FIELD(cell, CalendarDayCell_art, const void *)); + if (style_from_theme() && art && catalog_from_pixels(art, &index) && + index == catalog_calendar_cell(CALENDAR_HILITE)) + highlight(context); +} + +void tint_highlight_end(void) +{ + if (!highlighted) + return; + each_pixel(highlighted - 1, paint, style_tint_color(highlighted - 1)); + highlighted = 0; +} + +/* The text or background role, whichever differs more in brightness from `art`. */ +static const uint8_t *contrast_with(const uint8_t *art) +{ + const uint8_t *text = style_color(RVT_ROLE_TEXT), + *background = style_color(RVT_ROLE_BACKGROUND); + int reference = color_brightness(art); + int text_gap = color_brightness(text) - reference; + int background_gap = color_brightness(background) - reference; + if (text_gap < 0) + text_gap = -text_gap; + if (background_gap < 0) + background_gap = -background_gap; + return text_gap >= background_gap ? text : background; +} + +/* Entry `slot` of `contrast`: the role against the centre pixel of `index`, + * or nothing when the art is clear. */ +static void pick_contrast(unsigned slot, uint32_t index) +{ + uint8_t art[4]; + if (catalog_center_pixel(index, art)) + memcpy(contrast[slot], contrast_with(art), 4); + else + memset(contrast[slot], 0, 4); +} + +static void pick_contrasts(void) +{ + uint8_t art[4]; + const uint8_t *background = style_color(RVT_ROLE_BACKGROUND); + for (unsigned well = 0; well < WELLS; well++) + pick_contrast(CONTRAST_WELL + well, catalog_well_center(well)); + pick_contrast(CONTRAST_FIELD, catalog_field_center()); + for (unsigned entry = 0; entry < CATALOG_CONTRAST_TEXTS; entry++) + pick_contrast(CONTRAST_TEXT + entry, catalog_contrast_art(entry)); + /* A clear cell counts as the page: the role that contrasts with the + * background, mixed halfway toward it for days of other months. */ + for (unsigned place = CALENDAR_ACTIVE; place <= CALENDAR_INACTIVE; place++) { + const uint8_t *behind = + catalog_center_pixel(catalog_calendar_cell(place), art) ? art : background; + const uint8_t *color = contrast_with(behind); + if (place == CALENDAR_ACTIVE) + memcpy(contrast[CONTRAST_CALENDAR + place], color, 4); + else + color_mix(contrast[CONTRAST_CALENDAR + place], color, behind, 128); + } + color_mix(contrast[CONTRAST_CALENDAR + 2], contrast_with(background), background, + 128); +} + +void tint_refresh(void) +{ + if (style_from_theme()) + for (uint32_t i = 0; i < RVT_CATALOG_MAX; i++) + if (style_tinted(i)) + each_pixel(i, paint, style_tint_color(i)); + pick_contrasts(); +} + +void tint_accent_art(const uint32_t *skip, uint32_t *touched) +{ + uint32_t index; + uint8_t role; + if (!style_accent_art_active()) + return; + for (uint32_t i = 0; catalog_accent_art(i, &index, &role); i++) { + if (index >= RVT_CATALOG_MAX || bit_test(skip, index)) + continue; + each_pixel(index, colorize, style_color((enum rvt_role)role)); + bit_set(touched, index); + } +} + +static const uint8_t *picked(unsigned slot) +{ + return style_from_theme() && contrast[slot][3] ? contrast[slot] : NULL; +} + +const uint8_t *tint_well_letter_color(unsigned well) +{ + /* Classic dark repaints the Now Playing well. */ + if (well == WELL_NOW_PLAYING && style_dark() && contrast[CONTRAST_WELL + well][3]) + return contrast[CONTRAST_WELL + well]; + return well < WELLS ? picked(CONTRAST_WELL + well) : NULL; +} + +const uint8_t *tint_field_text_color(void) +{ + return picked(CONTRAST_FIELD); +} + +const uint8_t *tint_contrast_text_color(uint32_t view) +{ + int entry = style_from_theme() ? catalog_contrast_text(view) : -1; + return entry < 0 ? NULL : picked(CONTRAST_TEXT + (unsigned)entry); +} + +const uint8_t *tint_calendar_text_color(unsigned place, uint8_t out[4]) +{ + unsigned slot = place == CALENDAR_HEADER ? 2 : place; + if (place == CALENDAR_HILITE || place > CALENDAR_HEADER || + !picked(CONTRAST_CALENDAR + slot)) + return NULL; + if (place == CALENDAR_ACTIVE) + return contrast[CONTRAST_CALENDAR]; + memcpy(out, contrast[CONTRAST_CALENDAR + slot], 4); + return out; +} diff --git a/extensions/appearance/tint.h b/extensions/appearance/tint.h new file mode 100644 index 0000000..6ff1c40 --- /dev/null +++ b/extensions/appearance/tint.h @@ -0,0 +1,49 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* Colouring bitmaps in place and picking label colours against artwork. */ + +#ifndef TINT_H +#define TINT_H +#include + +/* The colour a bitmap view draws its mask in: its tint colour when the bitmap + * is a tinted catalog bitmap, the icon tint role when it is no catalog bitmap + * at all (an extension's menu icon) under a theme, the on-accent colour while + * the view is highlighted, NULL to keep the stock colour. */ +const uint8_t *tint_mask_color(const void *view); +/* Around one blit of a bitmap context by a view, or of a calendar day cell's + * marker: a tinted paletted asset in a highlighted view, or on the selected + * day, draws with the on-accent colour, put back by the end call. Tinted ARGB + * art keeps its tint while highlighted. */ +void tint_highlight_begin(const void *view, const void *context); +void tint_marker_highlight_begin(const void *cell, const void *context); +void tint_highlight_end(void); +/* Paints a decoded extension picture, a whole BMap of `bytes`, in `color`: + * the entries of an Indexed8 palette or the covered pixels of BGRA8888 rows, + * keeping their alpha. 0 for any other format. */ +int tint_bmap(void *bmap, uint32_t bytes, const uint8_t *color); +/* Rewrites the palettes of tinted paletted bitmaps and the pixels of tinted + * ARGB bitmaps with their tint colour, and picks the label colours that + * contrast with the artwork; after a switch or accent change, once the pack's + * records are applied. */ +void tint_refresh(void); +/* Tints the stock accent artwork with its role, skipping bitmaps set in + * `skip` (replaced by the pack), and sets each one it touched in `touched`. + * Expects stock pixels. */ +void tint_accent_art(const uint32_t *skip, uint32_t *touched); +/* The colour for labels on an option bar well (catalog.h WELL_*): the text or + * background role, whichever contrasts more with the well's centre art; NULL + * keeps the stock colour (no pack, or clear art). The Now Playing well has one + * under Dark without a pack too. */ +const uint8_t *tint_well_letter_color(unsigned well); +/* The same for the text typed into the Search field. */ +const uint8_t *tint_field_text_color(void); +/* The same for a stock label drawn in a fixed colour over art, by view id. */ +const uint8_t *tint_contrast_text_color(uint32_t view); +/* Calendar labels (catalog.h calendar_place): a day of the shown month on the + * active cell, of another month on the inactive cell (mixed halfway toward + * it), a weekday name on the page; `out` holds a mixed result. NULL keeps the + * stock colour. */ +const uint8_t *tint_calendar_text_color(unsigned place, uint8_t out[4]); + +#endif diff --git a/extensions/appearance/tools/catalog_inc.py b/extensions/appearance/tools/catalog_inc.py new file mode 100755 index 0000000..e453a45 --- /dev/null +++ b/extensions/appearance/tools/catalog_inc.py @@ -0,0 +1,161 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +"""Write catalog.inc from the Apple bitmap catalog, themes/rvt/data/osos-2.0.5.json: +the bank's base and file offset, each bitmap's offset in the bank +with its padding in the low two bits, the low 16 bits of each stock checksum, +the catalog fingerprint, and the indices of the assets the extension treats +specially. + + python3 tools/catalog_inc.py ../../themes/rvt/data/osos-2.0.5.json build/catalog.inc + python3 tools/catalog_inc.py ../../themes/rvt/data/osos-2.0.5.json --check build/classic.rvt + +The second form checks that a theme file carries the catalog's fingerprint. +""" + +import json +import sys +from pathlib import Path + +# Stock blue artwork and the role it is recoloured with. Blue that marks content +# (capacity legends, playlist kinds) is not listed. +ACCENT_ART = { + "RVT_ROLE_SELECTION": ( + "OptionBar_White_Thumb_LeftCap_Image", + "OptionBar_White_Thumb_Center_Image", + "OptionBar_White_Thumb_RightCap_Image", + "OptionBar_Black_Thumb_LeftCap_Image", + "OptionBar_Black_Thumb_Center_Image", + "OptionBar_Black_Thumb_RightCap_Image", + "System_ActiveButtonLeftCap_Image", + "System_ActiveButtonRightCap_Image", + "System_ActiveButtonFill_Image", + "DateTimePicker_Selection", + "Alarms_Timer_Time_Panel_Focus", + "Settings_DateTime_Capsule_Hilite", + "Calendar_Hilite_Cell", + "LockScreen_TumblerFocus_Image", + "Settings_MainMenu_CheckmarkWhite_Image", + ), + "RVT_ROLE_ACCENT_FILL": ( + "NowPlaying_ProgressBar_Active_Fill_Image", + "NowPlaying_ProgressBar_Scrub_Image", + "Genius_Slider_Endcap_Image", + "Genius_Slider_Fill_Image", + "Podcasts_new_item_Image", + "Podcasts_new_item_video_Image", + "NowPlaying_Blue_Dot_Image", + "NowPlaying_Blue_Star_Image", + "NowPlaying_Large_Blue_Star_Image", + "StatusBarWhite_PlayStatus_Image", + "NowPlaying_White_Play_Image", + "NowPlaying_White_Pause_Image", + "NowPlaying_White_FF_Image", + "NowPlaying_White_Rew_Image", + "Radio_Preset_Image", + "Radio_Signal_Indicator_Light_Image", + ), +} +RECOLORABLE_FORMATS = (0x64, 0x65, 0x1888) + +# Stock labels drawn in a fixed colour over art a theme may replace, by the +# first view of a run of consecutive ids, the run's length and the asset behind +# them: they take the text or background role, whichever contrasts more with +# that art. +CONTRAST_TEXT = ( + ("RES_NowPlaying_StatusBar_Text_View", 1, "NowPlaying_StatusBar_Image"), + ("RES_LockScreen_TumblerDigit0_View", 4, "LockScreen_TumblerBgnd_Image"), + ("RES_VolumeLimitLockScreen_TumblerDigit0_View", 4, "LockScreen_TumblerBgnd_Image"), + ("RES_DateTimePicker_Value1", 3, "DateTimePicker_Well"), + ("RES_CoverFlow_Backside_AlbumTitle_Text", 2, "CoverFlow_Backside_Top_Image"), +) +WELLS = ( + "OptionBar_White_Well_Center_Image", + "OptionBar_Black_Well_Center_Image", + "OptionBar_NowPlaying_Well_Center_Image", +) +FIELD = "System_Input_Field_Middle_Image" +CELLS = ("Calendar_Active_Cell", "Calendar_Inactive_Cell", "Calendar_Hilite_Cell") +FINGERPRINT_AT = 8 +FINGERPRINT_BYTES = 8 + + +def check(catalog, rvt): + stored = bytes.fromhex(catalog["fingerprint"]) + found = rvt.read_bytes()[FINGERPRINT_AT : FINGERPRINT_AT + FINGERPRINT_BYTES] + if found != stored: + raise SystemExit(f"{rvt} was compiled against another catalog") + + +def write(catalog, out): + bitmaps = sorted(catalog["bitmaps"], key=lambda b: b["address"]) + index = {b["name"]: i for i, b in enumerate(bitmaps)} + if len(index) != len(bitmaps): + raise SystemExit("catalog names are not unique") + base = bitmaps[0]["address"] + if base % 4 or bitmaps[0]["offset"] % 4: + raise SystemExit("the bank does not start on a word") + at = base + offsets = [] + for b in bitmaps: + if b["address"] != at: + raise SystemExit(f"{b['name']} does not follow the previous bitmap") + padding = -b["bytes"] & 3 + offsets.append(at - base | padding) + at += b["bytes"] + padding + offsets.append(at - base) + for name in ACCENT_ART["RVT_ROLE_SELECTION"] + ACCENT_ART["RVT_ROLE_ACCENT_FILL"]: + if bitmaps[index[name]]["format"] not in RECOLORABLE_FORMATS: + raise SystemExit(f"{name} is not paletted or ARGB") + digest = bytes.fromhex(catalog["fingerprint"]) + lines = [ + "/* Generated by tools/catalog_inc.py from osos-2.0.5.json; do not edit. */", + f"#define CATALOG_COUNT {len(bitmaps)}", + f"#define CATALOG_BASE {base:#x}u /* first bitmap in RAM */", + f"#define CATALOG_FILE_OFFSET {bitmaps[0]['offset']:#x}u" + " /* the same in the firmware file */", + f"#define CATALOG_BANK_BYTES {at - base}u", + "static const uint8_t fingerprint[RVT_FINGERPRINT_BYTES] = {" + + ", ".join(f"{b:#04x}" for b in digest) + + "};", + "static const uint32_t catalog_offsets[CATALOG_COUNT + 1] = {", + *(f" {o}u," for o in offsets), + "};", + "static const uint16_t catalog_crcs[CATALOG_COUNT] = {", + *(f" {b['crc32'] & 0xFFFF:#06x}," for b in bitmaps), + "};", + "static const uint16_t well_centers[3] = {" + + ", ".join(str(index[n]) for n in WELLS) + + "};", + f"static const uint16_t field_center = {index[FIELD]};", + "static const uint16_t calendar_cells[3] = {" + + ", ".join(str(index[n]) for n in CELLS) + + "};", + "static const struct contrast_text contrast_text[] = {", + *( + f" {{{first}, {count}, {index[name]}}}," + for first, count, name in CONTRAST_TEXT + ), + "};", + "static const struct accent_art accent_art[] = {", + *( + f" {{{index[name]}, {role}}}," + for role, names in ACCENT_ART.items() + for name in names + ), + "};", + "", + ] + out.parent.mkdir(parents=True, exist_ok=True) + out.write_text("\n".join(lines)) + + +def main(): + catalog = json.loads(Path(sys.argv[1]).read_text()) + if sys.argv[2] == "--check": + check(catalog, Path(sys.argv[3])) + else: + write(catalog, Path(sys.argv[2])) + + +if __name__ == "__main__": + main() diff --git a/extensions/balance/manifest.toml b/extensions/balance/manifest.toml index 2e4aa37..635b3c2 100644 --- a/extensions/balance/manifest.toml +++ b/extensions/balance/manifest.toml @@ -1,10 +1,10 @@ id = "balance" name = "Balance" description = "Shift the sound towards the left or right ear in decibel steps, or play one ear only." -version = "0.1.0" +version = "0.1.1" author = "RevolaOS" license = "GPL-3.0-only" -api = "1.78" +api = "1.89" stability = "beta" category = "effects" diff --git a/extensions/clicker-modes/Makefile b/extensions/clicker-modes/Makefile new file mode 100644 index 0000000..cb973a7 --- /dev/null +++ b/extensions/clicker-modes/Makefile @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: GPL-3.0-only +main_SOURCES := main.c +include $(SDK)/rv.mk diff --git a/extensions/clicker-modes/README.md b/extensions/clicker-modes/README.md new file mode 100644 index 0000000..4938c9d --- /dev/null +++ b/extensions/clicker-modes/README.md @@ -0,0 +1,13 @@ +# Clicker Modes + +Based on the RepriseOS core's [clicker modes](https://github.com/RepriseOS/repriseos/blob/b9b1c62/payload/clicker.c), by Alex Ball and lgreitis. + +Settings > Clicker cycles Off, Speaker, Headphones and Both instead of Off and On. Apple's click engine already handles all four values; the extension adds the missing two to the row and labels them correctly. Every mode except Off shows Apple's On picture. + +Without the extension, a saved Speaker or Headphones still routes the click, but the stock row swaps their labels ("Speaker" for Headphones), picks the picture by the speaker alone, and Select goes to Both. + +| | | +|---|---| +| Default | on | +| Memory | image only | +| Settings | none; the mode is Apple's preference | diff --git a/extensions/clicker-modes/assets/LICENSE.cupertino-icons b/extensions/clicker-modes/assets/LICENSE.cupertino-icons new file mode 100644 index 0000000..581f84c --- /dev/null +++ b/extensions/clicker-modes/assets/LICENSE.cupertino-icons @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2016 Vladimir Kharlampidi + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/extensions/clicker-modes/assets/settings-clicker-modes.png b/extensions/clicker-modes/assets/settings-clicker-modes.png new file mode 100644 index 0000000..5a650aa Binary files /dev/null and b/extensions/clicker-modes/assets/settings-clicker-modes.png differ diff --git a/extensions/clicker-modes/assets/settings-clicker-modes.svg b/extensions/clicker-modes/assets/settings-clicker-modes.svg new file mode 100644 index 0000000..d15817c --- /dev/null +++ b/extensions/clicker-modes/assets/settings-clicker-modes.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/extensions/clicker-modes/listing.toml b/extensions/clicker-modes/listing.toml new file mode 100644 index 0000000..4b745f3 --- /dev/null +++ b/extensions/clicker-modes/listing.toml @@ -0,0 +1,7 @@ +details = "Open Settings > Clicker and press Select to cycle Off, Speaker, Headphones and Both." + +icon = "assets/settings-clicker-modes.png" + +[[screenshots]] +file = "screenshots/settings.png" +alt = "Settings > Clicker set to Headphones, with the Headphones description in the preview pane." diff --git a/extensions/clicker-modes/main.c b/extensions/clicker-modes/main.c new file mode 100644 index 0000000..4c67e89 --- /dev/null +++ b/extensions/clicker-modes/main.c @@ -0,0 +1,126 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* Clicker Modes. Settings > Clicker cycles Off, Speaker, Headphones and Both + * instead of Off and On. Apple's click engine already routes all four values + * of its Clicker preference; only the Settings row offers two of them, and its + * labels for Speaker and Headphones are swapped. + * + * Adapted from RepriseOS payload/clicker.c (565dfe0, d48e7c4, c997a51) by + * Alex Ball (alexballvideos-netizen) and lgreitis. */ + +#include "osos-2.0.5.h" +#include "rv_api.h" +#include "rv_libc.h" +#include "rv_sites.h" +#include "rv_ui.h" + +static const struct rv_api *api; + +static uint32_t clicker_get(void *preferences) +{ + typedef uint32_t (*get_fn)(void *, uint32_t, uint32_t); + return RV_METHOD(preferences, Preferences_get_method, + get_fn)(preferences, Preference_Clicker, Service_Preferences); +} + +static void clicker_set(void *preferences, uint32_t value) +{ + typedef void (*set_fn)(void *, uint32_t, uint32_t, uint32_t); + RV_METHOD(preferences, Preferences_set_method, + set_fn)(preferences, Preference_Clicker, Service_Preferences, value); +} + +static void notify(void *model, uint32_t property) +{ + typedef void (*notify_fn)(void *, uint32_t, uint32_t); + RV_METHOD(model, Model_notify_method, notify_fn)(model, Notify_All, property); +} + +static uint32_t on_action(uint32_t controller, uint32_t name, uint32_t argument, + const void *next) +{ + void *preferences = PreferencesService_Get(); + if (!preferences || !name || strcmp((const char *)name, "ToggleSetting_Clicker")) + return api->hook_next(next, controller, name, argument, 0, 0, 0); + if (argument == ActionSupportQuery) + return 1; + uint32_t value; + switch (clicker_get(preferences)) { + case Clicker_Off: + value = Clicker_Speaker; + break; + case Clicker_Speaker: + value = Clicker_Headphones; + break; + case Clicker_Headphones: + value = Clicker_Both; + break; + default: + value = Clicker_Off; + break; + } + clicker_set(preferences, value); + void *model = *(void **)(controller + ScreenController_settings_model); + notify(model, SettingsProperty_ClickerValue); + notify(model, SettingsProperty_ClickerDescription); + notify(model, SettingsProperty_ClickerImage); + return 1; +} + +static uint32_t on_property(uint32_t model, uint32_t type, uint32_t property, + uint32_t out, const void *next) +{ + int image = property == SettingsProperty_ClickerImage && type == Resource_BMap; + int row = property == SettingsProperty_ClickerValue; + void *preferences = PreferencesService_Get(); + if (!preferences || + (!image && !((row || property == SettingsProperty_ClickerDescription) && + type == Property_String))) + return api->hook_next(next, model, type, property, out, 0, 0); + uint32_t value = clicker_get(preferences); + void *service = UI_GetResourceService(); + if (image) { + /* Apple's picks the picture by the speaker bit alone. */ + *(uintptr_t *)out = (uintptr_t)ResourceService_GetBitmap( + service, value == Clicker_Off ? RES_Settings_ClickerOff_Image + : RES_Settings_ClickerOn_Image); + return 1; + } + uint32_t id; + switch (value) { + case Clicker_Off: + id = row ? RES_Settings_Off_String : RES_Settings_ClickerOff_Description; + break; + case Clicker_Speaker: + id = + row ? RES_Settings_Speaker_String : RES_Settings_ClickerSpeaker_Description; + break; + case Clicker_Headphones: + id = row ? RES_Settings_Headphones_String + : RES_Settings_ClickerHeadphones_Description; + break; + default: + id = row ? RES_Settings_Both_String : RES_Settings_ClickerBoth_Description; + break; + } + *(uintptr_t *)out = (uintptr_t)ResourceService_GetString(service, id); + return 1; +} + +static const struct rv_hook hooks[] = { + RV_HOOK_FILTER(RV_SITE_Settings_Action_slot, on_action), + RV_HOOK_FILTER(RV_SITE_Settings_Property_slot, on_property), +}; + +static const struct rv_descriptor extension = { + .size = sizeof extension, + RV_HOOKS(hooks), +}; + +const struct rv_descriptor *rv_module_entry(const struct rv_api *core, + rv_extension_handle handle) +{ + (void)handle; + api = core; + return &extension; +} diff --git a/extensions/clicker-modes/manifest.toml b/extensions/clicker-modes/manifest.toml new file mode 100644 index 0000000..42eac75 --- /dev/null +++ b/extensions/clicker-modes/manifest.toml @@ -0,0 +1,13 @@ +id = "clicker-modes" +name = "Clicker Modes" +description = "Choose where the click wheel sound plays: the iPod's speaker, headphones, both or off." +version = "0.1.0" +author = "RepriseOS contributors" +license = "GPL-3.0-only" +api = "1.89" +stability = "beta" +category = "system" + +[[module]] +name = "main" +trigger = "always" diff --git a/extensions/clicker-modes/screenshots/settings.png b/extensions/clicker-modes/screenshots/settings.png new file mode 100644 index 0000000..069c011 Binary files /dev/null and b/extensions/clicker-modes/screenshots/settings.png differ diff --git a/extensions/crossfeed/manifest.toml b/extensions/crossfeed/manifest.toml index 1109dc6..1449cb3 100644 --- a/extensions/crossfeed/manifest.toml +++ b/extensions/crossfeed/manifest.toml @@ -1,14 +1,17 @@ id = "crossfeed" name = "Crossfeed" description = "Blends a little of each channel into the other so hard-panned stereo is easier on headphones. A simple mode or a custom filter." -version = "0.1.0" +version = "0.1.1" author = "RevolaOS" note = "Ported from Rockbox" license = "GPL-3.0-only" -api = "1.78" +api = "1.89" stability = "beta" category = "effects" -requires = ["dsp"] + +[libraries] +required = ["dsp"] +optional = ["reprise"] [[module]] name = "main" diff --git a/extensions/crossfeed/tests/run.py b/extensions/crossfeed/tests/run.py index 00bc001..b586883 100644 --- a/extensions/crossfeed/tests/run.py +++ b/extensions/crossfeed/tests/run.py @@ -275,7 +275,7 @@ def simple_response(hz): h = simple_response(hz) for amplitude, expected in ( (max(abs(r) for _, r in out), abs(h)), - (max(abs(l) for l, _ in out), abs(1 - h)), + (max(abs(left) for left, _ in out), abs(1 - h)), ): got = 20 * math.log10(amplitude / 20000) assert abs(got - 20 * math.log10(expected)) < 0.1, (hz, got, expected) diff --git a/extensions/dsp/manifest.toml b/extensions/dsp/manifest.toml index c1657c3..14b074b 100644 --- a/extensions/dsp/manifest.toml +++ b/extensions/dsp/manifest.toml @@ -1,11 +1,11 @@ id = "dsp" name = "DSP" description = "Signal processing the audio effects share: the look-ahead limiter, filter designs, the biquad cascade and the maths behind them." -version = "0.1.0" +version = "0.1.1" author = "RevolaOS" note = "Partly adapted from RepriseOS" license = "GPL-3.0-only" -api = "1.74" +api = "1.89" stability = "beta" category = "library" exports = [ diff --git a/extensions/dsp/rv_dsp.h b/extensions/dsp/rv_dsp.h index 5ae8a22..d63b241 100644 --- a/extensions/dsp/rv_dsp.h +++ b/extensions/dsp/rv_dsp.h @@ -1,7 +1,7 @@ /* SPDX-License-Identifier: GPL-3.0-only */ /* What the dsp library exports, and the state its limiter and fade run on. - * An effect lists `requires = ["dsp"]` in its manifest; rv.mk finds the + * An effect lists dsp under `[libraries] required`; rv.mk finds the * library and the core fills in the addresses when it loads. No * RV_MODULE_CALL here: a call into a library is a long call. */ diff --git a/extensions/equalizer/Makefile b/extensions/equalizer/Makefile new file mode 100644 index 0000000..5370c73 --- /dev/null +++ b/extensions/equalizer/Makefile @@ -0,0 +1,4 @@ +# SPDX-License-Identifier: GPL-3.0-only +main_SOURCES := main.c engine.c presets.c +editor_SOURCES := editor.c +include $(SDK)/rv.mk diff --git a/extensions/equalizer/README.md b/extensions/equalizer/README.md new file mode 100644 index 0000000..0ce7f30 --- /dev/null +++ b/extensions/equalizer/README.md @@ -0,0 +1,25 @@ +# Equalizer + +Partly adapted from the RepriseOS core's [Custom EQ](https://github.com/RepriseOS/repriseos/blob/b9b1c62/payload/custom_eq.c), [EQ audio path](https://github.com/RepriseOS/repriseos/blob/b9b1c62/payload/eq_audio.c), [EQ canvas](https://github.com/RepriseOS/repriseos/blob/b9b1c62/payload/eq_canvas.c) and [filter design](https://github.com/RepriseOS/repriseos/blob/b9b1c62/payload/eq_coefficients.c), by lgreitis and paviro. + +Apple's EQ rounds each of its three filter stages to 16 bits, so boosting presets distort loud passages. Equalizer runs the same presets through its own filter chain with 42 dB of headroom between stages, and lowers each preset by its peak gain. A look-ahead limiter at the end catches the peaks the precut misses and delays the output by about 0.7 ms. Off and Flat pass audio through untouched. + +The EQ list gains a Custom preset after Apple's. While Custom is selected, Settings shows an Edit EQ row to shape it. The wheel picks a band, Select steps into its parameters and then edits one, Menu goes back. Holding Select resets the highlighted band or parameter. Changes apply immediately. Moving the Hold switch shows the response curve, precut included. Like Flat, Custom is not replaced by a track's own EQ setting. Each of the five bands has: + +| Parameter | Range | Default | +|---|---|---| +| Type | off, peaking, low shelf, high shelf | low shelf, peaking, high shelf, off, off | +| Frequency | 20 Hz to 20 kHz | 60 Hz, 1 kHz, 8 kHz, 250 Hz, 4 kHz | +| Q | 0.3 to 4.0 | 0.7 | +| Gain | -12 to +12 dB | 0 dB | +| Precut, for the whole preset | automatic (the chain's peak gain) or fixed down to -10 dB | automatic | + +Enabled during playback, it takes over at the next track or preset change. Disabling it with Custom selected sets the EQ to Off. + +On first start the extension imports the Custom EQ values the earlier core kept in its settings store (the CEQ record) and shows the Edit EQ row when Custom was the selected preset. Custom EQ values that exist only in the pre-store CFWEQ file start from the defaults. + +| | | +|---|---| +| Default | on | +| Memory | image only | +| Settings | the Custom preset and whether the Edit EQ row shows | diff --git a/extensions/equalizer/assets/settings-eq.png b/extensions/equalizer/assets/settings-eq.png new file mode 100644 index 0000000..20644d3 Binary files /dev/null and b/extensions/equalizer/assets/settings-eq.png differ diff --git a/extensions/equalizer/assets/settings-eq.svg b/extensions/equalizer/assets/settings-eq.svg new file mode 100644 index 0000000..3508b93 --- /dev/null +++ b/extensions/equalizer/assets/settings-eq.svg @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/extensions/equalizer/editor.c b/extensions/equalizer/editor.c new file mode 100644 index 0000000..3af747f --- /dev/null +++ b/extensions/equalizer/editor.c @@ -0,0 +1,322 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The Custom EQ editor: five gain bars over a row of the selected band's + * parameters. The wheel picks a band; Select moves into the parameters and + * then into editing one, holding Select puts what is highlighted back to its + * default, Menu steps back out. Every change plays at once through the link + * main passed as the screen's argument. The hold switch shows the response + * curve of what plays. + * + * Adapted from RepriseOS payload/eq_canvas.c (d640115, 93f6a45) by lgreitis. */ + +#include "rv_canvas.h" +#include "rv_libc.h" +#include "rv_ui.h" +#include "shared.h" + +static const struct rv_api *api; +static rv_extension_handle self; + +enum { DEPTH_BAND, DEPTH_PARAMETER, DEPTH_EDIT, DEPTHS }; + +/* Wheel order follows reading order: Type | Precut, then Gain | Frequency | Q. */ +enum { PARAM_TYPE, PARAM_PRECUT, PARAM_GAIN, PARAM_FREQUENCY, PARAM_Q, PARAM_COUNT }; + +static const uint8_t parameters[PARAM_COUNT] = {EQ_TYPE, EQ_PRECUT, EQ_GAIN, + EQ_FREQUENCY, EQ_Q}; +static const char *const titles[PARAM_COUNT] = {"Type", "Precut", "Gain", "Frequency", + "Q"}; +static const char *const types[] = {"Off", "Peaking", "Low shelf", "High shelf"}; + +enum { + BAND_LEFT = 42, + BAND_WIDTH = 54, + BAND_TOP = 18, + BAND_BOTTOM = 108, + BAND_ZERO = (BAND_TOP + BAND_BOTTOM) / 2, + INLINE_TOP = 141, /* Type | Precut, title left and value right */ + INLINE_HEIGHT = 27, + INLINE_COUNT = PARAM_GAIN, + CELL_TOP = INLINE_TOP + INLINE_HEIGHT + + 1, /* the cells run to the bottom of the canvas */ + RESPONSE_POINTS = 261, + RESPONSE_TOP = 36, + RESPONSE_BOTTOM = 180, + RESPONSE_ZERO = (RESPONSE_TOP + RESPONSE_BOTTOM) / 2, + TICK_TOP = 192, + TICK_HEIGHT = 22, +}; + +static struct { + struct rv_editor input; + int band, parameter, response, dirty; + int16_t curve[RESPONSE_POINTS]; + /* The response from +extent at the top to -extent at the bottom, tenths + * of a decibel, doubled until the curve fits. */ + struct rv_plot plot; + unsigned int precut; +} editor; + +static const struct eq_link *link(const struct rv_context *ctx) +{ + return ctx->arg; +} + +static unsigned int slot(int band, int parameter) +{ + return eq_slot((unsigned int)band, parameters[parameter]); +} + +static unsigned int choice(const struct rv_context *ctx, int band, int parameter) +{ + return link(ctx)->values[slot(band, parameter)]; +} + +static void save(const struct rv_context *ctx) +{ + if (editor.dirty) + link(ctx)->save(); + editor.dirty = 0; +} + +enum { LABEL_BYTES = 12 }; + +static const char *label(int parameter, unsigned int choice, char out[LABEL_BYTES]) +{ + switch (parameter) { + case PARAM_TYPE: + return types[choice]; + case PARAM_PRECUT: + if (choice == EQ_PRECUT_AUTO) + return "Auto"; + rv_format_tenths(out, LABEL_BYTES, eq_precut_tenths(choice), 0, " dB"); + return out; + case PARAM_GAIN: + rv_format_tenths(out, LABEL_BYTES, eq_gain_tenths(choice), 1, " dB"); + return out; + case PARAM_FREQUENCY: + rv_format_hz(out, LABEL_BYTES, eq_frequencies[choice]); + return out; + default: + rv_format_tenths(out, LABEL_BYTES, eq_q_tenths(choice), 0, ""); + return out; + } +} + +static void compute_response(const struct rv_context *ctx) +{ + int extent = 60; + editor.precut = link(ctx)->response(editor.curve, RESPONSE_POINTS); + for (unsigned int i = 0; i < RESPONSE_POINTS; i++) + while (editor.curve[i] < -extent || editor.curve[i] > extent) + extent *= 2; + editor.plot = (struct rv_plot){.left = 44, + .top = RESPONSE_TOP, + .bottom = RESPONSE_BOTTOM, + .points = RESPONSE_POINTS, + .top_value = (int16_t)extent, + .bottom_value = (int16_t)-extent}; +} + +static void draw_response(const struct rv_context *ctx, const struct rv_canvas *c) +{ + static const char *const tick_labels[] = {"20", "200", "2k", "20k Hz"}; + char value[LABEL_BYTES], high[8], low[8]; + const char *scale[] = {high, "0", low}; + unsigned int precut = choice(ctx, 0, PARAM_PRECUT); + const char *title = "Precut"; + rv_canvas_header(c, "EQ response", NULL, 0); + /* With Auto, the attenuation the engine found. */ + if (precut == EQ_PRECUT_AUTO) { + title = "Auto precut"; + precut = editor.precut + 1; + } + label(PARAM_PRECUT, precut, value); + int right = c->width - 8; + int value_width = c->gfx->measure(RV_FONT_TEXT, value); + int title_width = c->gfx->measure(RV_FONT_TEXT, title); + rv_canvas_text(c, right - value_width - 6 - title_width, 3, title_width, 24, title, + 0, RV_ALIGN_LEFT, RV_CANVAS_MUTED); + rv_canvas_text(c, right - value_width, 3, value_width, 24, value, 0, RV_ALIGN_RIGHT, + RV_CANVAS_TEXT); + rv_format(high, sizeof high, "+%u", (unsigned int)editor.plot.top_value / 10); + rv_format(low, sizeof low, "-%u", (unsigned int)editor.plot.top_value / 10); + rv_plot_ticks(c, &editor.plot, tick_labels, 4, TICK_TOP, TICK_HEIGHT); + rv_plot_grid(c, &editor.plot, scale, 3); + rv_canvas_rect(c, editor.plot.left, RESPONSE_ZERO, RESPONSE_POINTS, 1, + RV_CANVAS_ZERO); + rv_plot_curve(c, &editor.plot, editor.curve, 1, RV_CANVAS_ACCENT); +} + +static void draw_bands(const struct rv_context *ctx, const struct rv_canvas *c) +{ + rv_canvas_rect(c, BAND_LEFT, BAND_TOP, BAND_WIDTH * EQ_BANDS, 1, RV_CANVAS_GRID); + rv_canvas_rect(c, BAND_LEFT, BAND_BOTTOM, BAND_WIDTH * EQ_BANDS, 1, RV_CANVAS_GRID); + rv_canvas_rect(c, BAND_LEFT + 2 + editor.band * BAND_WIDTH, 4, BAND_WIDTH - 4, + INLINE_TOP - 7, RV_CANVAS_SELECTION); + rv_canvas_rect(c, BAND_LEFT, BAND_ZERO, BAND_WIDTH * EQ_BANDS, 1, RV_CANVAS_ZERO); + rv_canvas_text(c, 2, BAND_TOP - 9, 34, 18, "+12", 0, RV_ALIGN_CENTER, + RV_CANVAS_MUTED); + rv_canvas_text(c, 2, BAND_ZERO - 9, 34, 18, "0", 0, RV_ALIGN_CENTER, + RV_CANVAS_MUTED); + rv_canvas_text(c, 2, BAND_BOTTOM - 9, 34, 18, "-12", 0, RV_ALIGN_CENTER, + RV_CANVAS_MUTED); + for (int band = 0; band < EQ_BANDS; band++) { + char frequency[LABEL_BYTES]; + int x = BAND_LEFT + BAND_WIDTH / 2 + band * BAND_WIDTH; + int y = BAND_ZERO - eq_gain_tenths(choice(ctx, band, PARAM_GAIN)) * + (BAND_BOTTOM - BAND_ZERO) / 120; + int selected = band == editor.band; + int off = choice(ctx, band, PARAM_TYPE) == EQ_OFF; + uint8_t color = off ? RV_CANVAS_BORDER + : selected ? RV_CANVAS_ACCENT + : RV_CANVAS_INACTIVE; + rv_canvas_rect(c, x - 8, BAND_TOP, 16, BAND_BOTTOM - BAND_TOP, RV_CANVAS_TRACK); + rv_canvas_rect(c, x - 16, BAND_ZERO, 32, 1, RV_CANVAS_ZERO); + int top = y < BAND_ZERO ? y : BAND_ZERO; + int height = y < BAND_ZERO ? BAND_ZERO - y : y - BAND_ZERO; + if (height) + rv_canvas_rect(c, x - 8, top, 16, height, color); + rv_canvas_rect(c, x - 12, y - 3, 24, 6, color); + rv_canvas_text( + c, x - 25, INLINE_TOP - 25, 50, 22, + off ? "Off" + : label(PARAM_FREQUENCY, choice(ctx, band, PARAM_FREQUENCY), frequency), + 0, RV_ALIGN_CENTER, selected ? RV_CANVAS_ACCENT : RV_CANVAS_MUTED); + } +} + +static void draw_parameters(const struct rv_context *ctx, const struct rv_canvas *c) +{ + char text[PARAM_COUNT][LABEL_BYTES]; + const char *values[PARAM_COUNT]; + uint8_t states[PARAM_COUNT]; + for (int parameter = 0; parameter < PARAM_COUNT; parameter++) { + int active = editor.input.depth != DEPTH_BAND && parameter == editor.parameter; + values[parameter] = + label(parameter, choice(ctx, editor.band, parameter), text[parameter]); + states[parameter] = !active ? RV_CELL_IDLE + : editor.input.depth == DEPTH_EDIT ? RV_CELL_EDITING + : RV_CELL_SELECTED; + } + rv_canvas_fields(c, INLINE_TOP, INLINE_HEIGHT, titles, values, states, + INLINE_COUNT); + rv_canvas_cells(c, CELL_TOP, c->height - CELL_TOP, titles + INLINE_COUNT, + values + INLINE_COUNT, states + INLINE_COUNT, + PARAM_COUNT - INLINE_COUNT); +} + +static void draw(const struct rv_context *ctx, const struct rv_gfx *g, int width, + int height) +{ + struct rv_canvas c; + rv_canvas_begin(&c, g, width, height); + if (editor.response) { + draw_response(ctx, &c); + return; + } + draw_bands(ctx, &c); + draw_parameters(ctx, &c); +} + +static void wheel(const struct rv_context *ctx, int delta) +{ + if (editor.input.depth == DEPTH_BAND) { + editor.band = rv_clamp(editor.band + delta, 0, EQ_BANDS - 1); + } else if (editor.input.depth == DEPTH_PARAMETER) { + editor.parameter = rv_clamp(editor.parameter + delta, 0, PARAM_COUNT - 1); + } else { + unsigned int at = slot(editor.band, editor.parameter); + int previous = link(ctx)->values[at]; + int value = + rv_clamp(previous + delta, 0, eq_choices[parameters[editor.parameter]] - 1); + if (value != previous) { + link(ctx)->change(at, (unsigned int)value); + editor.dirty = 1; + } + } +} + +/* A held Select puts what is highlighted back to its default: a band with its + * four parameters, or at the parameter levels the one parameter, Precut + * included. One publish. */ +static void reset(const struct rv_context *ctx) +{ + uint8_t trial[EQ_VALUES]; + unsigned int first, count; + if (editor.input.depth == DEPTH_BAND) { + first = eq_slot((unsigned int)editor.band, EQ_TYPE); + count = EQ_PARAMETERS - 1; + } else { + first = slot(editor.band, editor.parameter); + count = 1; + } + if (!memcmp(link(ctx)->values + first, link(ctx)->defaults + first, count)) + return; + memcpy(trial, link(ctx)->values, EQ_VALUES); + memcpy(trial + first, link(ctx)->defaults + first, count); + link(ctx)->set(trial); + editor.dirty = 1; +} + +static int input(const struct rv_context *ctx, const struct rv_input *input) +{ + if (input->kind == RV_INPUT_HOLD) { + editor.response = input->delta; + if (editor.response) { + save(ctx); + compute_response(ctx); + } + } else if (editor.response) { + return 1; + } else { + switch (rv_editor_input(&editor.input, input)) { + case RV_EDITOR_IGNORED: + return 0; + case RV_EDITOR_CONSUMED: + return 1; + case RV_EDITOR_WHEEL: + wheel(ctx, input->delta); + break; + case RV_EDITOR_RESET: + reset(ctx); + break; + default: + save(ctx); + break; + } + } + api->ui_invalidate(self); + return 1; +} + +static void opened(const struct rv_context *ctx) +{ + (void)ctx; + memset(&editor, 0, sizeof editor); + editor.input.depths = DEPTHS; +} + +static void closed(const struct rv_context *ctx) +{ + save(ctx); +} + +static const struct rv_screen screens[] = { + RV_SCREEN_CANVAS("editor", "Custom EQ", draw, input, + .transition = RV_TRANSITION_FROM_PANE, .opened = opened, + .closed = closed), +}; + +static const struct rv_descriptor module = { + .size = sizeof module, + RV_SCREENS(screens), +}; + +const struct rv_descriptor *rv_module_entry(const struct rv_api *core, + rv_extension_handle handle) +{ + api = core; + self = handle; + return &module; +} diff --git a/extensions/equalizer/engine.c b/extensions/equalizer/engine.c new file mode 100644 index 0000000..839f961 --- /dev/null +++ b/extensions/equalizer/engine.c @@ -0,0 +1,269 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* What the EQ plays. Apple's loader still fills its three stages for its own + * presets; the engine copies them, cuts the first by the cascade's peak so a + * boost has room, and runs them through the dsp library's cascade. The Custom + * preset is five stages Apple's loader never sees. Apple's records keep what + * Apple wrote. + * + * Load and reset arrive on the task that changed the setting or prepared a + * track, process on the PCM output pump task. Only the pump task touches the + * stages that play. The others leave it a set of coefficients with interrupts + * masked, and it takes the set over once it sees the generation move. + * + * Adapted from RepriseOS payload/eq_audio.c (93f6a45) by lgreitis. */ + +#include "engine.h" +#include "osos-2.0.5.h" +#include "rv_dsp.h" +#include "rv_libc.h" + +/* The saved band types are the library's filter types. */ +_Static_assert((int)EQ_OFF == RV_DSP_FLAT && (int)EQ_PEAKING == RV_DSP_PEAKING && + (int)EQ_LOW_SHELF == RV_DSP_LOW_SHELF && + (int)EQ_HIGH_SHELF == RV_DSP_HIGH_SHELF, + "band types"); + +enum { + NATIVE_STAGES = 3, + PRECUT_LIMIT = 100, + UNITY = 1 << 24, +}; + +static const struct rv_api *api; + +/* The Custom preset at 44.1 and 48 kHz, each stage b0, b1, b2, a1, a2, and the + * precut inside its first stage. */ +static int32_t custom[2][EQ_BANDS][5]; +static uint8_t custom_precut[2]; + +/* The set left for the pump task, and what the last load found. */ +struct eq_set { + int32_t coefficients[EQ_BANDS][5]; + uint8_t count; + uint8_t fade; /* blend from what plays instead of switching */ + uint8_t dry; /* the pump task may not have run since the last set: start from dry */ +}; +static struct eq_set next; +static struct rv_handoff handoff; +static struct ThreeBandEQ *volatile owner; /* NULL until the first load */ +static uint8_t plays_custom, custom_bank; +static volatile uint8_t rest_pending; +/* Apple runs the EQ only while its record is enabled; until the next set that + * plays, what the pump task holds is stale. 1 before the first load. */ +static uint8_t stopped = 1; + +/* The precut of the last Apple preset loaded: tenths of a decibel, the preset + * from bit 8 and the rate's bank in bit 16. Preset 0 has no stages, so 0 is + * no entry. */ +static uint32_t native_precut; + +/* Pump task only. The limiter runs while a stage does; a flat set passes the + * audio through, and a change between the two fades its delay in or out. */ +static struct rv_dsp_stage playing[EQ_BANDS], fading[EQ_BANDS]; +static struct rv_fade fade; +static struct rv_limiter limiter; + +void eq_engine_start(const struct rv_api *core) +{ + api = core; +} + +static int supported(unsigned int rate) +{ + return rate == 44100 || rate == 48000; +} + +static unsigned int precut_for(const int32_t (*set)[5], unsigned int count, + unsigned int rate) +{ + int peak = rv_dsp_peak(set, count, rate); + return peak <= 0 ? 0 : peak > PRECUT_LIMIT ? PRECUT_LIMIT : (unsigned int)peak; +} + +/* Interrupts masked. */ +static void leave(const int32_t (*set)[5], unsigned int count, unsigned int blend) +{ + for (unsigned int i = 0; i < count; i++) + for (unsigned int c = 0; c < 5; c++) + next.coefficients[i][c] = set[i][c]; + next.count = (uint8_t)count; + next.fade = (uint8_t)blend; + next.dry = stopped; + handoff.generation++; +} + +int eq_publish(const uint8_t values[EQ_VALUES]) +{ + int32_t banks[2][EQ_BANDS][5]; + unsigned int precut[2]; + for (unsigned int bank = 0; bank < 2; bank++) { + unsigned int rate = bank ? 48000 : 44100; + int automatic = values[EQ_PRECUT] == EQ_PRECUT_AUTO; + precut[bank] = + automatic ? 0 : (unsigned int)-eq_precut_tenths(values[EQ_PRECUT]); + for (unsigned int band = 0; band < EQ_BANDS; band++) { + const uint8_t *v = values + band * (EQ_PARAMETERS - 1); + if (!rv_dsp_biquad( + banks[bank][band], v[EQ_TYPE], eq_frequencies[v[EQ_FREQUENCY]], + (unsigned int)eq_q_tenths(v[EQ_Q]), eq_gain_tenths(v[EQ_GAIN]), + band ? 0 : precut[bank], rate)) + return 0; + } + if (automatic) { + precut[bank] = precut_for(banks[bank], EQ_BANDS, rate); + rv_dsp_attenuate(banks[bank][0], precut[bank]); + } + } + uint32_t state = api->irq_save(); + memcpy(custom, banks, sizeof custom); + custom_precut[0] = (uint8_t)precut[0]; + custom_precut[1] = (uint8_t)precut[1]; + if (plays_custom) + leave(custom[custom_bank], EQ_BANDS, 1); + api->irq_restore(state); + return 1; +} + +unsigned int eq_custom_response(int16_t *tenths, unsigned int points) +{ + unsigned int bank = custom_bank; + rv_dsp_response(custom[bank], EQ_BANDS, bank ? 48000 : 44100, tenths, points); + return custom_precut[bank]; +} + +/* Works out what `eq` plays after a load and leaves it for the pump task. */ +static void prepare(struct ThreeBandEQ *eq) +{ + int32_t set[NATIVE_STAGES][5]; + unsigned int count = 0, rate = RV_FIELD(eq, ThreeBandEQ_sample_rate, uint32_t); + unsigned int preset = RV_FIELD(eq, ThreeBandEQ_preset, uint32_t), + bank = rate == 48000; + if (preset == EQ_CUSTOM_PRESET) { + RV_FIELD(eq, ThreeBandEQ_enabled, uint8_t) = (uint8_t)supported(rate); + count = supported(rate) ? EQ_BANDS : 0; + } else if (RV_FIELD(eq, ThreeBandEQ_enabled, uint8_t)) { + for (unsigned int i = 0; i < NATIVE_STAGES; i++) { + uint8_t *stage = + &RV_FIELD(eq, ThreeBandEQ_stages + i * EQStage_bytes, uint8_t); + if (RV_FIELD(stage, EQStage_bypass, uint8_t)) + continue; + set[count][0] = RV_FIELD(stage, EQStage_b0, int32_t); + set[count][1] = RV_FIELD(stage, EQStage_b1, int32_t); + set[count][2] = RV_FIELD(stage, EQStage_b2, int32_t); + set[count][3] = RV_FIELD(stage, EQStage_a1, int32_t); + set[count][4] = RV_FIELD(stage, EQStage_a2, int32_t); + count++; + } + uint32_t key = preset << 8 | bank << 16, cached = native_precut; + if (count && (cached & ~0xffu) != key) { + cached = key | precut_for(set, count, rate); + native_precut = cached; + } + if (count) + rv_dsp_attenuate(set[0], cached & 0xff); + } + uint32_t state = api->irq_save(); + owner = eq; + plays_custom = preset == EQ_CUSTOM_PRESET && count; + custom_bank = (uint8_t)bank; + leave(plays_custom ? custom[bank] : set, count, 0); + stopped = !RV_FIELD(eq, ThreeBandEQ_enabled, uint8_t); + api->irq_restore(state); +} + +void eq_load(struct ThreeBandEQ *eq, const void *next_hook) +{ + (void)next_hook; + /* Apple's loader has no row for the Custom preset. */ + if (RV_FIELD(eq, ThreeBandEQ_preset, uint32_t) != EQ_CUSTOM_PRESET) + EQ_LoadPresetCoefficients(eq); + prepare(eq); +} + +void eq_reset(struct ThreeBandEQ *eq, const void *next_hook) +{ + (void)next_hook; + EQ_ResetAllBiquadStates(eq); + rest_pending = 1; +} + +static int running(const struct rv_dsp_stage *stages) +{ + for (unsigned int i = 0; i < EQ_BANDS; i++) + if (!stages[i].bypass) + return 1; + return 0; +} + +/* Takes over the set a load or publish left. A set left meanwhile moves the + * generation again, and the next call takes that one. Between a flat set and + * one that runs the limiter's delay fades in or out, whether the set asks for + * a fade or not; after the EQ was off the old state is treated as flat. */ +static void take(void) +{ + struct eq_set set; + memcpy(fading, playing, sizeof fading); + rv_handoff_take(&handoff, &set, &next, sizeof set); + if (set.dry) + for (unsigned int i = 0; i < EQ_BANDS; i++) + fading[i].bypass = 1; + for (unsigned int i = 0; i < EQ_BANDS; i++) { + const int32_t *c = set.coefficients[i]; + rv_dsp_stage_set(&playing[i], c); + playing[i].bypass = + i >= set.count || (c[0] == UNITY && !(c[1] | c[2] | c[3] | c[4])); + } + rv_dsp_cascade_rest(playing, EQ_BANDS); + int was = running(fading), now = running(playing); + if (now && !was) + rv_limiter_rest(&limiter); + if (was != now) + rv_fade_start(&fade, now ? RV_LIMITER_FRAMES : 0); + else if (set.fade) + rv_fade_start(&fade, 0); + else + fade.remaining = 0; +} + +static int cascade(void *stages, const int16_t *in, int32_t *out, uint32_t frames) +{ + if (!running(stages)) + return 0; + rv_dsp_cascade_run(stages, EQ_BANDS, in, out, frames); + return 1; +} + +void eq_process(struct ThreeBandEQ *eq, int16_t *samples, uint32_t frames, + int16_t **output, const void *next_hook, uint32_t *output_frames) +{ + (void)next_hook; + /* Bound while a preset plays: Apple's stages as they are until the next load. */ + if (owner != eq) { + EQ_ProcessThreeBiquadsInPlace(eq, samples, frames, output, output_frames); + return; + } + *output = samples; + *output_frames = frames; + if (rv_handoff_pending(&handoff) && !rv_fade_switching(&fade)) + take(); + if (rest_pending) { + rest_pending = 0; + rv_dsp_cascade_rest(playing, EQ_BANDS); + /* A load resets right after it, so a fade of the delay stays. */ + if (running(playing) == running(fading)) + fade.remaining = 0; + } + rv_fade_run_limited(&fade, &limiter, cascade, playing, fading, samples, frames); +} + +void eq_engine_stop(void) +{ + struct ThreeBandEQ *eq = owner; + uint32_t state = api->irq_save(); + if (eq && RV_FIELD(eq, ThreeBandEQ_preset, uint32_t) == EQ_CUSTOM_PRESET) { + RV_FIELD(eq, ThreeBandEQ_enabled, uint8_t) = 0; + RV_FIELD(eq, ThreeBandEQ_preset, uint32_t) = 0; + } + api->irq_restore(state); +} diff --git a/extensions/equalizer/engine.h b/extensions/equalizer/engine.h new file mode 100644 index 0000000..bfd2144 --- /dev/null +++ b/extensions/equalizer/engine.h @@ -0,0 +1,33 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The audio path of the main module. */ + +#ifndef EQUALIZER_ENGINE_H +#define EQUALIZER_ENGINE_H +#include "shared.h" + +struct rv_api; +struct ThreeBandEQ; + +/* The Custom preset is the DSP preset and the EQ menu row after Apple's last. */ +#define EQ_CUSTOM_PRESET EQ_PresetCount + +void eq_engine_start(const struct rv_api *core); +/* Before the hooks are unbound: turns the EQ off if it plays the Custom preset, + * which Apple's own code cannot. */ +void eq_engine_stop(void); + +/* Makes `values` the Custom preset, crossfading when it plays. 0, and nothing + * changes, when a band has no stable filter. UI task. */ +int eq_publish(const uint8_t values[EQ_VALUES]); +/* struct eq_link's response, of the Custom preset. UI task. */ +unsigned int eq_custom_response(int16_t *tenths, unsigned int points); + +/* Hook handlers: load and reset on the task that changed the setting or + * prepared a track, process on the PCM output pump task. */ +void eq_load(struct ThreeBandEQ *eq, const void *next_hook); +void eq_reset(struct ThreeBandEQ *eq, const void *next_hook); +void eq_process(struct ThreeBandEQ *eq, int16_t *samples, uint32_t frames, + int16_t **output, const void *next_hook, uint32_t *output_frames); + +#endif diff --git a/extensions/equalizer/listing.toml b/extensions/equalizer/listing.toml new file mode 100644 index 0000000..c94fc75 --- /dev/null +++ b/extensions/equalizer/listing.toml @@ -0,0 +1,5 @@ +details = "Choose Custom at the end of Settings > EQ, then open Settings > Edit EQ to shape its five bands. Every preset runs through the extension's own filter chain, which keeps loud passages from distorting." + +[[screenshots]] +file = "screenshots/editor.png" +alt = "The Custom EQ editor, opened from Settings > Edit EQ: the response curve above the five bands and their parameters." diff --git a/extensions/equalizer/main.c b/extensions/equalizer/main.c new file mode 100644 index 0000000..c99fb92 --- /dev/null +++ b/extensions/equalizer/main.c @@ -0,0 +1,229 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* Equalizer: Apple's EQ presets through a cascade with headroom, and a Custom + * preset of five bands shaped in the editor screen. + * + * The count patches and the band defaults are adapted from RepriseOS + * payload/patches/patches.c and payload/custom_eq.ui (8fc840d) by lgreitis. */ + +#include "engine.h" +#include "presets.h" +#include "../reprise/reprise.h" +#include "osos-2.0.5.h" +#include "rv_libc.h" +#include "rv_menus.h" +#include "rv_sites.h" +#include "rv_ui.h" + +static const struct rv_api *api; +static rv_extension_handle self; + +/* The Custom preset that plays. */ +static uint8_t values[EQ_VALUES]; + +/* A low shelf at 60 Hz, a peak at 1 kHz and a high shelf at 8 kHz, all flat; + * two bands off at 250 Hz and 4 kHz. */ +static const uint8_t defaults[EQ_VALUES] = { + EQ_PRECUT_AUTO, + EQ_LOW_SHELF, + 5, + 4, + 24, + EQ_PEAKING, + 18, + 4, + 24, + EQ_HIGH_SHELF, + 27, + 4, + 24, + EQ_OFF, + 12, + 4, + 24, + EQ_OFF, + 24, + 4, + 24, +}; + +static int valid(const uint8_t *v) +{ + if (v[EQ_PRECUT] >= eq_choices[EQ_PRECUT]) + return 0; + for (unsigned int band = 0; band < EQ_BANDS; band++) + for (unsigned int parameter = EQ_TYPE; parameter < EQ_PARAMETERS; parameter++) + if (v[eq_slot(band, parameter)] >= eq_choices[parameter]) + return 0; + return 1; +} + +/* Plays what the store holds, the defaults when it holds nothing usable. */ +static void load(void) +{ + uint8_t stored[EQ_VALUES]; + const uint8_t *wanted = defaults; + if (api->setting_read(self, KEY_VALUES, stored, sizeof stored) == sizeof stored && + valid(stored)) + wanted = stored; + if (!memcmp(values, wanted, EQ_VALUES)) + return; + memcpy(values, wanted, EQ_VALUES); + if (!eq_publish(values)) { + memcpy(values, defaults, EQ_VALUES); + eq_publish(values); + } +} + +static void set(const uint8_t *choices) +{ + if (eq_publish(choices)) + memcpy(values, choices, EQ_VALUES); +} + +static void change(unsigned int slot, unsigned int choice) +{ + uint8_t trial[EQ_VALUES]; + memcpy(trial, values, EQ_VALUES); + trial[slot] = (uint8_t)choice; + set(trial); +} + +static void save(void) +{ + api->setting_write(self, KEY_VALUES, RV_SETTING_TYPE_BLOB, values, EQ_VALUES); +} + +static const struct eq_link link = {values, defaults, change, + set, save, eq_custom_response}; + +/* The Custom EQ record of the earlier core: the EQ_VALUES choices as words in + * the slot order of shared.h, then a layout word from the Auto precut on. */ +enum { LEGACY_KEY = 0x20514543 /* "CEQ " */, LEGACY_LAYOUT_AUTO_PRECUT = 1 }; + +/* Only the first start imports the old core's Custom EQ record. Whatever it + * holds, KEY_VALUES is written, so a later boot cannot import it; on a core + * without the reprise library nothing is imported. The row flag takes its + * first value from Apple's EQ preference: Custom was the preset selected + * when that is the row after Apple's last. */ +static void import_legacy(void) +{ + uint8_t stored[EQ_VALUES]; + if (reprise_legacy_preference && + api->setting_read(self, KEY_VALUES, stored, sizeof stored) != sizeof stored) { + uint32_t record[EQ_VALUES + 1]; + uint32_t bytes = (reprise_legacy_preference)(LEGACY_KEY, record, sizeof record); + int usable = bytes == sizeof record || bytes == sizeof record - 4; + /* Auto took precut choice 0; earlier layouts start at 0 dB. */ + if (usable && + (bytes < sizeof record || record[EQ_VALUES] < LEGACY_LAYOUT_AUTO_PRECUT)) { + usable = record[EQ_PRECUT] < eq_choices[EQ_PRECUT] - 1u; + record[EQ_PRECUT]++; + } + for (unsigned int i = 0; usable && i < EQ_VALUES; i++) { + usable = record[i] <= 0xff; + stored[i] = (uint8_t)record[i]; + } + api->setting_write(self, KEY_VALUES, RV_SETTING_TYPE_BLOB, + usable && valid(stored) ? stored : defaults, EQ_VALUES); + } + int32_t shown; + void *preferences = PreferencesService_Get(); + if (preferences && api->setting_read(self, KEY_CUSTOM_SHOWN, &shown, + sizeof shown) != sizeof shown) { + typedef uint32_t (*get_fn)(void *, uint32_t, uint32_t); + shown = RV_METHOD(preferences, Preferences_get_method, + get_fn)(preferences, Preference_EQMenuIndex, + Service_Preferences) == EQ_PresetCount; + api->setting_write(self, KEY_CUSTOM_SHOWN, RV_SETTING_TYPE_BOOL, &shown, + sizeof shown); + } +} + +static void open_editor(const struct rv_context *ctx) +{ + (void)ctx; + api->ui_push(self, "editor", (void *)&link); +} + +/* The Settings row shows while Custom plays. The stored flag carries over a + * boot: MediaPlayer_GetInstance builds the player on first use, too early while + * extensions load, and the preset it then takes is the one stored anyway. */ +static uint32_t eq_apply(uintptr_t player, uint32_t settings_id, const void *next) +{ + uint32_t result = api->hook_next(next, player, settings_id, 0, 0, 0, 0); + int custom = MediaPlayer_GetEQSettingsId((void *)player) == EQ_CUSTOM_SETTINGS_ID; + if (api->setting_get_int(self, KEY_CUSTOM_SHOWN) != custom) + api->setting_set_int(self, KEY_CUSTOM_SHOWN, custom); + return result; +} + +static void setting_changed(uint16_t key) +{ + if (key == KEY_VALUES || key == RV_SETTING_KEY_ALL) + load(); +} + +static void unload(void) +{ + /* Apple's code has no row for Custom once the tables are its own again. */ + if (MediaPlayer_GetEQSettingsId(MediaPlayer_GetInstance()) == EQ_CUSTOM_SETTINGS_ID) + SettingsModel_SelectEQMenuIndex(SettingsModel_GetInstance(), 0); + eq_engine_stop(); +} + +/* Bound in this order: the engine before anything can ask for the Custom + * preset, the tables before the counts that reach into them, the id map last. */ +static const struct rv_hook hooks[] = { + RV_HOOK_REPLACE(RV_SITE_EQ_Process_slot, eq_process), + RV_HOOK_REPLACE(RV_SITE_EQ_Reset_slot, eq_reset), + RV_HOOK_REPLACE(RV_SITE_EQ_SetPreset_Load_call, eq_load), + RV_HOOK_REPLACE(RV_SITE_EQ_SetRate_Load_call, eq_load), + RV_HOOK_WORD(RV_SITE_EQ_DspCount_word, 0xe3510018), /* cmp r1, #EQ_ROWS */ + RV_HOOK_POINTER(RV_SITE_EQ_MenuIds_literal, eq_preset_ids), + RV_HOOK_POINTER(RV_SITE_EQ_SettingsIds_literal, eq_preset_ids), + RV_HOOK_POINTER(RV_SITE_EQ_PreviewTable_literal, eq_preset_rows), + RV_HOOK_POINTER(RV_SITE_EQ_NameTable_literal, eq_preset_rows), + RV_HOOK_POINTER(RV_SITE_EQ_ResourceTable_literal, eq_preset_rows), + RV_HOOK_WORD(RV_SITE_EQ_PreviewCount_word, 0xe3510018), /* cmp r1, #EQ_ROWS */ + RV_HOOK_WORD(RV_SITE_EQ_NameCount_word, 0xe3510018), /* cmp r1, #EQ_ROWS */ + RV_HOOK_WORD(RV_SITE_EQ_SettingsCount_word, 0xe3520018), /* cmp r2, #EQ_ROWS */ + RV_HOOK_WORD(RV_SITE_EQ_ProviderCount_word, 0xe3a00018), /* mov r0, #EQ_ROWS */ + RV_HOOK_WORD(RV_SITE_EQ_ResourceCount_word, 0xe3550018), /* cmp r5, #EQ_ROWS */ + RV_HOOK_REPLACE(RV_SITE_EQ_TrackPreset_call, eq_track_preset), + RV_HOOK_REPLACE(RV_SITE_EQ_SettingsIdToDspPreset_entry, eq_map_preset), + RV_HOOK_FILTER(RV_SITE_EQ_ApplySettingsId_slot, eq_apply), +}; + +static const struct rv_setting settings[] = { + RV_SETTING_BOOL(KEY_CUSTOM_SHOWN, NULL, 0), +}; + +static const struct rv_menu_entry entries[] = { + RV_MENU_ENTRY(RV_MENU_SETTINGS, RV_SETTINGS_EQ, + RV_ROW_ACTION("Edit EQ", open_editor), + .pane = RV_PANE(.caption = "Adjust Your Sound", + .bitmap = RV_BITMAP("settings-eq")), + .shown_by = KEY_CUSTOM_SHOWN), +}; + +static const struct rv_descriptor extension = { + .size = sizeof extension, + RV_HOOKS(hooks), + RV_SETTINGS(settings), + .unload = unload, + .setting_changed = setting_changed, + RV_ENTRIES(entries), +}; + +const struct rv_descriptor *rv_module_entry(const struct rv_api *core, + rv_extension_handle handle) +{ + api = core; + self = handle; + eq_engine_start(core); + eq_presets_start(api->string_resource(self, "Custom")); + import_legacy(); + load(); + return &extension; +} diff --git a/extensions/equalizer/manifest.toml b/extensions/equalizer/manifest.toml new file mode 100644 index 0000000..a797dfc --- /dev/null +++ b/extensions/equalizer/manifest.toml @@ -0,0 +1,27 @@ +id = "equalizer" +name = "Equalizer" +description = "Stop the EQ presets from distorting, and add a Custom preset with five bands you shape yourself." +version = "0.1.0" +author = "RepriseOS contributors" +license = "GPL-3.0-only" +api = "1.89" +stability = "beta" +category = "effects" + +[libraries] +required = ["dsp"] +optional = ["reprise"] + +[[module]] +name = "main" +trigger = "always" + +[[module]] +name = "editor" +trigger = "screen" +screens = ["editor"] + +[[asset]] +name = "settings-eq" +file = "assets/settings-eq.png" +pane = "icon" diff --git a/extensions/equalizer/presets.c b/extensions/equalizer/presets.c new file mode 100644 index 0000000..9df6f6e --- /dev/null +++ b/extensions/equalizer/presets.c @@ -0,0 +1,50 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* Apple keeps the EQ presets in two tables of EQ_PresetCount rows: the settings + * ids and the name and preview resource ids. Six count words and five literals + * in the image give their length and address; the extension points them at + * copies one row longer, and maps the Custom settings id to the DSP preset + * after Apple's last, which the engine plays. + * + * Adapted from RepriseOS payload/custom_eq.c and payload/custom_eq.S (8fc840d) by + * lgreitis. */ + +#include "presets.h" +#include "engine.h" +#include "rv_api.h" +#include "rv_libc.h" + +uint32_t eq_preset_ids[EQ_ROWS]; +uint32_t eq_preset_rows[EQ_ROWS * EQPreset_bytes / sizeof(uint32_t)]; + +void eq_presets_start(uint32_t name) +{ + uint8_t *custom = (uint8_t *)eq_preset_rows + EQ_PresetCount * EQPreset_bytes; + memcpy(eq_preset_ids, EQ_PresetIds, EQ_PresetCount * sizeof(uint32_t)); + memcpy(eq_preset_rows, EQ_Presets, EQ_PresetCount * EQPreset_bytes); + eq_preset_ids[EQ_PresetCount] = EQ_CUSTOM_SETTINGS_ID; + /* Off and Flat share a preview: the flat line. */ + RV_FIELD(custom, EQPreset_preview, uint32_t) = + RV_FIELD(EQ_Presets, EQPreset_preview, uint32_t); + RV_FIELD(custom, EQPreset_name, uint32_t) = name; +} + +uint32_t eq_map_preset(uint32_t settings_id, const void *next) +{ + (void)next; + /* Apple's ids and Custom's are consecutive, as the presets they map to. */ + uint32_t n = settings_id - EQ_SettingsId_First; + return n < EQ_PresetCount ? n + 1 : 0; +} + +uint32_t eq_track_preset(struct MediaItem *item, struct MediaTrack *track, + const void *next) +{ + (void)track; + (void)next; + /* A track's own preset replaces the player's unless that is Flat; Custom + * holds as well. */ + if (MediaPlayer_GetEQSettingsId(MediaPlayer_GetInstance()) == EQ_CUSTOM_SETTINGS_ID) + return 0; + return MediaItem_GetEQSettingsId(item); +} diff --git a/extensions/equalizer/presets.h b/extensions/equalizer/presets.h new file mode 100644 index 0000000..74042ce --- /dev/null +++ b/extensions/equalizer/presets.h @@ -0,0 +1,26 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The Custom preset's row in Apple's EQ tables. */ + +#ifndef EQUALIZER_PRESETS_H +#define EQUALIZER_PRESETS_H +#include "osos-2.0.5.h" + +/* The settings id of the Custom preset, after Apple's last. */ +#define EQ_CUSTOM_SETTINGS_ID (EQ_SettingsId_Last + 1) +/* The rows of the EQ list with Custom. */ +#define EQ_ROWS (EQ_PresetCount + 1) + +/* Copies of Apple's two tables with the Custom row appended, for the literal + * sites. eq_presets_start fills them, naming the row by the string resource + * `name`; before that they are zero. */ +extern uint32_t eq_preset_ids[EQ_ROWS]; +extern uint32_t eq_preset_rows[EQ_ROWS * EQPreset_bytes / sizeof(uint32_t)]; +void eq_presets_start(uint32_t name); + +/* Hook handlers. */ +uint32_t eq_map_preset(uint32_t settings_id, const void *next); +uint32_t eq_track_preset(struct MediaItem *item, struct MediaTrack *track, + const void *next); + +#endif diff --git a/extensions/equalizer/screenshots/editor.png b/extensions/equalizer/screenshots/editor.png new file mode 100644 index 0000000..89be125 Binary files /dev/null and b/extensions/equalizer/screenshots/editor.png differ diff --git a/extensions/equalizer/shared.h b/extensions/equalizer/shared.h new file mode 100644 index 0000000..588639f --- /dev/null +++ b/extensions/equalizer/shared.h @@ -0,0 +1,82 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* What the two modules of Equalizer agree on. + * + * The parameter choices and the band type enum are adapted from RepriseOS + * payload/custom_eq.ui and payload/eq_coefficients.h (8fc840d) by lgreitis. */ + +#ifndef EQUALIZER_SHARED_H +#define EQUALIZER_SHARED_H +#include + +enum { EQ_BANDS = 5 }; + +enum eq_type { EQ_OFF, EQ_PEAKING, EQ_LOW_SHELF, EQ_HIGH_SHELF }; + +/* The Custom preset is EQ_VALUES choices, one byte each: the precut, then each + * band's type, frequency, Q and gain. The order and the choices are the saved + * format. */ +enum { + EQ_PRECUT, /* 0 is Auto, then 0.0 to -10.0 dB in tenths */ + EQ_TYPE, /* enum eq_type */ + EQ_FREQUENCY, /* an index into eq_frequencies */ + EQ_Q, /* 0.3 to 4.0 in tenths */ + EQ_GAIN, /* -12.0 to +12.0 dB in halves */ + EQ_PARAMETERS, + EQ_VALUES = 1 + EQ_BANDS * (EQ_PARAMETERS - 1), +}; + +#define KEY_VALUES 1 /* blob: the EQ_VALUES choices */ +#define KEY_CUSTOM_SHOWN \ + 2 /* bool: Custom is the preset that plays; shows the Settings row */ + +enum { EQ_PRECUT_AUTO = 0 }; + +static const uint8_t eq_choices[EQ_PARAMETERS] = {102, 4, 32, 38, 49}; + +static const uint16_t eq_frequencies[] = { + 20, 25, 31, 40, 50, 60, 70, 80, 100, 125, 160, + 200, 250, 315, 400, 500, 630, 800, 1000, 1250, 1600, 2000, + 2500, 3150, 4000, 5000, 6300, 8000, 10000, 12500, 16000, 20000, +}; + +/* Where a band's parameter is among the choices; the precut has no band. */ +static inline unsigned int eq_slot(unsigned int band, unsigned int parameter) +{ + return parameter == EQ_PRECUT ? 0 : parameter + band * (EQ_PARAMETERS - 1); +} + +/* Choices as tenths: of a decibel for precut (below zero) and gain, of one for Q. */ +static inline int eq_precut_tenths(unsigned int choice) +{ + return 1 - (int)choice; +} + +static inline int eq_q_tenths(unsigned int choice) +{ + return 3 + (int)choice; +} + +static inline int eq_gain_tenths(unsigned int choice) +{ + return (int)choice * 5 - 120; +} + +/* What main passes the editor screen as its argument. The editor module links + * none of the filter code; it calls main's. */ +struct eq_link { + const uint8_t *values; /* the EQ_VALUES choices that play */ + const uint8_t *defaults; /* the choices a reset returns to */ + /* Plays one choice changed. Nothing changes when a band then has no stable + * filter. */ + void (*change)(unsigned int slot, unsigned int choice); + /* Plays a whole set of choices, under the same rule. */ + void (*set)(const uint8_t *choices); + void (*save)(void); /* stores the choices */ + /* What plays, at `points` frequencies from 20 Hz to 20 kHz evenly spaced in + * octaves, in tenths of a decibel. Returns the precut applied, in tenths + * of a decibel. */ + unsigned int (*response)(int16_t *tenths, unsigned int points); +}; + +#endif diff --git a/extensions/equalizer/tests/engine_test.c b/extensions/equalizer/tests/engine_test.c new file mode 100644 index 0000000..208c6d5 --- /dev/null +++ b/extensions/equalizer/tests/engine_test.c @@ -0,0 +1,487 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The engine on the host, against a double-precision cascade: Apple's loader, + * reset and process are stubs, and the ThreeBandEQ is a byte array. Includes + * engine.c for its state. */ + +#include +#include +#include +#include + +#include "../engine.c" + +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif + +enum { BASS_PRESET = 8, FRAMES = 2048, D = RV_LIMITER_FRAMES }; + +static uint8_t record[ThreeBandEQ_bytes + 16]; /* the last 16 bytes a guard */ +static unsigned int loads, resets, passes, irq_depth; + +static uint32_t irq_save(void) +{ + assert(!irq_depth++); + return 0x13; +} + +static void irq_restore(uint32_t state) +{ + assert(state == 0x13 && irq_depth-- == 1); +} + +static const struct rv_api fake_api = {.irq_save = irq_save, + .irq_restore = irq_restore}; + +static uint8_t *stage(void *eq, unsigned int i) +{ + return (uint8_t *)eq + ThreeBandEQ_stages + i * EQStage_bytes; +} + +/* Apple's loader: three identity stages, bypassed but for the Bass preset's + * second, a +6 dB low shelf at 1 kHz; enabled for a preset at 44.1 or 48 kHz. */ +void EQ_LoadPresetCoefficients(struct ThreeBandEQ *eq) +{ + uint32_t preset = RV_FIELD(eq, ThreeBandEQ_preset, uint32_t); + uint32_t rate = RV_FIELD(eq, ThreeBandEQ_sample_rate, uint32_t); + assert(preset != EQ_CUSTOM_PRESET); + loads++; + for (unsigned int i = 0; i < NATIVE_STAGES; i++) { + int32_t shelf[5] = {UNITY, 0, 0, 0, 0}; + int bass = i == 1 && preset == BASS_PRESET && supported(rate); + if (bass) + assert(rv_dsp_biquad(shelf, EQ_LOW_SHELF, 1000, 7, 60, 0, rate)); + RV_FIELD(stage(eq, i), EQStage_b0, int32_t) = shelf[0]; + RV_FIELD(stage(eq, i), EQStage_b1, int32_t) = shelf[1]; + RV_FIELD(stage(eq, i), EQStage_b2, int32_t) = shelf[2]; + RV_FIELD(stage(eq, i), EQStage_a1, int32_t) = shelf[3]; + RV_FIELD(stage(eq, i), EQStage_a2, int32_t) = shelf[4]; + RV_FIELD(stage(eq, i), EQStage_bypass, uint8_t) = !bass; + } + RV_FIELD(eq, ThreeBandEQ_enabled, uint8_t) = preset && supported(rate); +} + +void EQ_ResetAllBiquadStates(struct ThreeBandEQ *eq) +{ + (void)eq; + resets++; +} + +void EQ_ProcessThreeBiquadsInPlace(struct ThreeBandEQ *eq, int16_t *input, + uint32_t frames, int16_t **output, + uint32_t *output_frames) +{ + (void)eq; + passes++; + *output = input; + *output_frames = frames; +} + +static void process(int16_t *samples, unsigned int frames) +{ + int16_t *output = NULL; + uint32_t count = 0; + eq_process((struct ThreeBandEQ *)record, samples, frames, &output, NULL, &count); + assert(output == samples && count == frames); +} + +static void load(uint32_t preset, uint32_t rate) +{ + RV_FIELD(record, ThreeBandEQ_preset, uint32_t) = preset; + RV_FIELD(record, ThreeBandEQ_sample_rate, uint32_t) = rate; + eq_load((struct ThreeBandEQ *)record, NULL); +} + +static void noise(int16_t *samples, unsigned int frames) +{ + for (unsigned int i = 0; i < frames; i++) { + samples[i * 2] = (int16_t)((int)(i * 71 % 2000) - 1000); + samples[i * 2 + 1] = (int16_t)((int)(i * 173 % 4000) - 2000); + } +} + +static void sine(int16_t *samples, unsigned int frames, double hz, double amplitude) +{ + for (unsigned int i = 0; i < frames; i++) + samples[i * 2] = samples[i * 2 + 1] = + (int16_t)lrint(amplitude * sin(2 * M_PI * hz * i / 44100)); +} + +/* A double-precision cascade from rest; returns the largest magnitude before + * saturation. */ +static double reference(const int32_t (*k)[5], unsigned int stages, const int16_t *in, + int16_t *out, unsigned int frames) +{ + double peak = 0; + for (unsigned int c = 0; c < 2; c++) { + double h[EQ_BANDS][4] = {{0}}; + for (unsigned int i = 0; i < frames; i++) { + double x = in[i * 2 + c]; + for (unsigned int s = 0; s < stages; s++) { + double y = (k[s][0] * x + k[s][1] * h[s][0] + k[s][2] * h[s][1] - + k[s][3] * h[s][2] - k[s][4] * h[s][3]) / + 16777216.0; + h[s][1] = h[s][0]; + h[s][0] = x; + h[s][3] = h[s][2]; + h[s][2] = y; + x = y; + } + peak = fmax(peak, fabs(x)); + long rounded = lrint(x); + out[i * 2 + c] = (int16_t)(rounded > 32767 ? 32767 + : rounded < -32768 ? -32768 + : rounded); + } + } + return peak; +} + +/* The double cascade from rest on the left channel, unsaturated into both; + * returns the largest magnitude. */ +static double reference_wide(const int32_t (*k)[5], const int16_t *in, double *out, + unsigned int frames) +{ + double peak = 0, h[EQ_BANDS][4] = {{0}}; + for (unsigned int i = 0; i < frames; i++) { + double x = in[i * 2]; + for (unsigned int s = 0; s < EQ_BANDS; s++) { + double y = (k[s][0] * x + k[s][1] * h[s][0] + k[s][2] * h[s][1] - + k[s][3] * h[s][2] - k[s][4] * h[s][3]) / + 16777216.0; + h[s][1] = h[s][0]; + h[s][0] = x; + h[s][3] = h[s][2]; + h[s][2] = y; + x = y; + } + out[i * 2] = out[i * 2 + 1] = x; + peak = fmax(peak, fabs(x)); + } + return peak; +} + +/* The output plays D frames late: frame i of `a` against frame i - D of `b`. */ +static int max_difference(const int16_t *a, const int16_t *b, unsigned int frames) +{ + a += D * 2; + frames -= D; + int worst = 0; + for (unsigned int i = 0; i < frames * 2; i++) { + int d = a[i] > b[i] ? a[i] - b[i] : b[i] - a[i]; + worst = d > worst ? d : worst; + } + return worst; +} + +/* The cascade alone, in place, saturated. */ +static void cascade_in_place(struct rv_dsp_stage *stages, int16_t *samples, + unsigned int frames) +{ + int32_t wide[RV_LIMITER_CHUNK_FRAMES * 2]; + for (unsigned int done = 0; done < frames; done += RV_LIMITER_CHUNK_FRAMES) { + rv_dsp_cascade_run(stages, EQ_BANDS, samples + done * 2, wide, + RV_LIMITER_CHUNK_FRAMES); + for (unsigned int i = 0; i < RV_LIMITER_CHUNK_FRAMES * 2; i++) + samples[done * 2 + i] = rv_saturate16(wide[i]); + } +} + +/* Choices: Auto or a precut in tenths below zero; the frequency as an index. */ +static unsigned int precut_choice(int tenths) +{ + return (unsigned int)(1 - tenths); +} + +static unsigned int frequency_choice(unsigned int hz) +{ + for (unsigned int i = 0;; i++) + if (eq_frequencies[i] == hz) + return i; +} + +static unsigned int gain_choice(int tenths) +{ + return (unsigned int)(tenths + 120) / 5; +} + +static unsigned int q_choice(int tenths) +{ + return (unsigned int)(tenths - 3); +} + +static void band(uint8_t *values, unsigned int i, unsigned int type, unsigned int hz, + int q_tenths, int gain_tenths) +{ + values[eq_slot(i, EQ_TYPE)] = (uint8_t)type; + values[eq_slot(i, EQ_FREQUENCY)] = (uint8_t)frequency_choice(hz); + values[eq_slot(i, EQ_Q)] = (uint8_t)q_choice(q_tenths); + values[eq_slot(i, EQ_GAIN)] = (uint8_t)gain_choice(gain_tenths); +} + +static void flat(uint8_t *values, unsigned int precut) +{ + memset(values, 0, EQ_VALUES); + values[EQ_PRECUT] = (uint8_t)precut; + for (unsigned int i = 0; i < EQ_BANDS; i++) + band(values, i, EQ_OFF, 1000, 7, 0); +} + +static void histories_at_rest(void) +{ + struct rv_dsp_stage rest; + rv_dsp_cascade_rest(&rest, 1); + for (unsigned int i = 0; i < EQ_BANDS; i++) + for (unsigned int c = 0; c < 2; c++) { + for (unsigned int n = 0; n < 4; n++) + assert(!playing[i].history[c][n]); + assert(playing[i].error[c] == rest.error[0]); + } +} + +int main(void) +{ + static int16_t samples[FRAMES * 2], expected[FRAMES * 2], previous[FRAMES * 2]; + static struct rv_dsp_stage old_stages[EQ_BANDS], new_stages[EQ_BANDS]; + uint8_t values[EQ_VALUES], untouched[sizeof record]; + eq_engine_start(&fake_api); + memset(record + ThreeBandEQ_bytes, 0xdb, 16); + + /* Before the first load, Apple's process runs. */ + noise(samples, 64); + process(samples, 64); + assert(passes == 1 && !owner); + + for (unsigned int rate = 44100; rate <= 48000; rate += 3900) { + unsigned int bank = rate == 48000; + /* A manual 6.5 dB precut and three bells match the double cascade. */ + flat(values, precut_choice(-65)); + band(values, 0, EQ_PEAKING, 60, 7, 50); + band(values, 1, EQ_PEAKING, 160, 7, 50); + band(values, 2, EQ_PEAKING, 1000, 7, 50); + assert(eq_publish(values) && custom_precut[bank] == 65); + load(EQ_CUSTOM_PRESET, rate); + assert(RV_FIELD(record, ThreeBandEQ_enabled, uint8_t) && + owner == (void *)record); + memcpy(untouched, record, sizeof record); + if (rate == 44100) { + /* The first set fades in from dry: the input plays alone while + * the limiter fills, then blends into the EQ. */ + noise(samples, 256); + memcpy(previous, samples, 512 * sizeof *samples); + process(samples, 256); + assert(!memcmp(samples, previous, D * 2 * sizeof *samples)); + assert(memcmp(samples, previous, 256 * 2 * sizeof *samples)); + eq_reset((struct ThreeBandEQ *)record, NULL); + } + noise(samples, 256); + reference(custom[bank], EQ_BANDS, samples, expected, 256); + process(samples, 256); + assert(max_difference(samples, expected, 256) <= 1); + assert(!memcmp(record, untouched, sizeof record) && passes == 1); + assert(playing[3].bypass && playing[4].bypass); + + /* A live edit fades from the old five stages to the new over 128 frames. */ + memcpy(old_stages, playing, sizeof old_stages); + band(values, 3, EQ_PEAKING, 4000, 7, 50); + band(values, 4, EQ_PEAKING, 8000, 7, 50); + assert(eq_publish(values) && next.fade); + for (unsigned int i = 0; i < EQ_BANDS; i++) { + new_stages[i].b0 = custom[bank][i][0]; + new_stages[i].b1 = custom[bank][i][1]; + new_stages[i].b2 = custom[bank][i][2]; + new_stages[i].a1 = -custom[bank][i][3]; + new_stages[i].a2 = -custom[bank][i][4]; + new_stages[i].bypass = 0; + } + rv_dsp_cascade_rest(new_stages, EQ_BANDS); + noise(samples, 256); + memcpy(expected, samples, 512 * sizeof *samples); + memcpy(previous, samples, 512 * sizeof *samples); + cascade_in_place(old_stages, previous, 128); + cascade_in_place(new_stages, expected, 256); + for (unsigned int i = 0; i < 128; i++) + for (unsigned int c = 0; c < 2; c++) { + unsigned int n = i * 2 + c; + expected[n] = (int16_t)(((int32_t)previous[n] * (127 - (int)i) + + (int32_t)expected[n] * ((int)i + 1)) >> + 7); + } + process(samples, 17); + assert(fade.remaining == 111); + process(samples + 34, 239); + assert(!fade.remaining && + !memcmp(samples + D * 2, expected, (256 - D) * 2 * sizeof *samples)); + assert(!memcmp(record, untouched, sizeof record)); + + /* A reset puts the histories at rest and ends a fade. */ + values[eq_slot(4, EQ_GAIN)] = (uint8_t)gain_choice(-50); + assert(eq_publish(values)); + process(samples, 1); + assert(fade.remaining == 127); + eq_reset((struct ThreeBandEQ *)record, NULL); + assert(rest_pending); + process(samples, 1); + assert(!fade.remaining); + eq_reset((struct ThreeBandEQ *)record, NULL); + process(samples, 0); + histories_at_rest(); + } + + /* A +12 dB bell and its inverse are transparent at a 30000 peak; between + * them the signal passes 60000, which a 16-bit stage would saturate. */ + flat(values, precut_choice(0)); + band(values, 0, EQ_PEAKING, 1000, 7, 120); + band(values, 1, EQ_PEAKING, 1000, 7, -120); + assert(eq_publish(values) && custom_precut[0] == 0); + load(EQ_CUSTOM_PRESET, 44100); + sine(samples, FRAMES, 1000, 30000); + assert(reference(custom[0], 1, samples, expected, FRAMES) > 60000); + memcpy(previous, samples, sizeof samples); + process(samples, FRAMES); + assert(max_difference(samples, previous, FRAMES) <= 2); + + /* Auto precut takes a +6 dB low shelf's boost back out; 0 dB would clip. */ + flat(values, precut_choice(0)); + band(values, 0, EQ_LOW_SHELF, 1000, 7, 60); + assert(eq_publish(values)); + sine(samples, FRAMES, 100, 32767); + assert(reference(custom[0], EQ_BANDS, samples, expected, FRAMES) > 60000); + values[EQ_PRECUT] = EQ_PRECUT_AUTO; + assert(eq_publish(values)); + assert(custom_precut[0] >= 60 && custom_precut[0] <= 61 && + rv_dsp_peak(custom[0], 5, 44100) <= 0); + load(EQ_CUSTOM_PRESET, 44100); + assert(reference(custom[0], EQ_BANDS, samples, expected, FRAMES) <= 32767.5); + process(samples, FRAMES); + assert(max_difference(samples, expected, FRAMES) <= 1); + + /* Error feedback keeps low poles from amplifying the rounding: a 20 Hz bell + * and a 60 Hz shelf, both +12 dB, track the double cascade. */ + flat(values, precut_choice(0)); + band(values, 0, EQ_PEAKING, 20, 19, 120); + band(values, 1, EQ_LOW_SHELF, 60, 7, 120); + assert(eq_publish(values)); + load(EQ_CUSTOM_PRESET, 44100); + sine(samples, FRAMES, 1000, 1000); + reference(custom[0], EQ_BANDS, samples, expected, FRAMES); + process(samples, FRAMES); + double error = 0; + for (unsigned int i = D * 2; i < FRAMES * 2; i++) + error += (double)(samples[i] - expected[i - D * 2]) * + (samples[i] - expected[i - D * 2]); + assert(sqrt(error / ((FRAMES - D) * 2)) < 0.2); + + /* Auto precut bounds the response, not the samples: full-scale input with + * the signs of the time-reversed impulse response lines every tap's + * phase up and goes over. The limiter brings the peak to full scale and + * scales its neighbours alike instead of clipping. */ + flat(values, EQ_PRECUT_AUTO); + band(values, 0, EQ_LOW_SHELF, 60, 7, 60); + band(values, 1, EQ_HIGH_SHELF, 8000, 7, 60); + assert(eq_publish(values)); + load(EQ_CUSTOM_PRESET, 44100); + + enum { TAPS = 512 }; + + static int16_t impulse[TAPS * 2], response[TAPS * 2]; + static double wide_reference[FRAMES * 2]; + impulse[0] = impulse[1] = 32767; + reference(custom[0], EQ_BANDS, impulse, response, TAPS); + for (unsigned int i = 0; i < FRAMES; i++) { + int16_t tap = response[(TAPS - 1 - i % TAPS) * 2]; + samples[i * 2] = samples[i * 2 + 1] = (int16_t)(tap < 0 ? -32767 : 32767); + } + double over = reference_wide(custom[0], samples, wide_reference, FRAMES); + assert(over > 32767 * 1.2); + unsigned int at = 0; + for (unsigned int i = TAPS; i < FRAMES - D; i++) + if (fabs(wide_reference[i * 2]) > fabs(wide_reference[at * 2])) + at = i; + memcpy(previous, samples, sizeof samples); + process(samples, FRAMES); + for (unsigned int i = 0; i < FRAMES - D; i++) + assert(fabs((double)samples[(i + D) * 2]) <= fabs(wide_reference[i * 2]) + 1); + assert(fabs((double)samples[(at + D) * 2]) >= 32760); + double ratio = wide_reference[(at - 1) * 2] / wide_reference[at * 2]; + assert(fabs((double)samples[(at - 1 + D) * 2] / samples[(at + D) * 2] - ratio) < + 0.02); + rv_limiter_rest(&limiter); /* rather than wait out the release */ + + /* An Apple preset: its stages are copied, the first cut by the peak, and + * its record is left as Apple's loader wrote it. */ + unsigned int before = loads; + load(BASS_PRESET, 44100); + assert(loads == before + 1 && RV_FIELD(record, ThreeBandEQ_enabled, uint8_t)); + assert(!plays_custom && next.count == 1); + int32_t shelf[5], attenuated[5]; + assert(rv_dsp_biquad(shelf, EQ_LOW_SHELF, 1000, 7, 60, 0, 44100)); + assert(RV_FIELD(stage(record, 1), EQStage_b0, int32_t) == shelf[0]); + int peak = rv_dsp_peak((const int32_t (*)[5])shelf, 1, 44100); + assert(peak >= 60 && peak <= 61 && (native_precut & 0xff) == (uint32_t)peak); + memcpy(attenuated, shelf, sizeof shelf); + rv_dsp_attenuate(attenuated, (unsigned int)peak); + assert(!memcmp(next.coefficients[0], attenuated, sizeof attenuated)); + uint32_t cached = native_precut; + load(BASS_PRESET, 44100); + assert(loads == before + 2 && native_precut == cached); + eq_reset((struct ThreeBandEQ *)record, NULL); + sine(samples, FRAMES, 100, 32767); + assert(reference((const int32_t (*)[5])attenuated, 1, samples, expected, FRAMES) <= + 32767.5); + process(samples, FRAMES); + assert(max_difference(samples, expected, FRAMES) <= 1); + + /* An unsupported rate: nothing plays, for Apple's presets or Custom. */ + load(BASS_PRESET, 32000); + assert(!RV_FIELD(record, ThreeBandEQ_enabled, uint8_t) && !next.count); + load(EQ_CUSTOM_PRESET, 32000); + assert(!RV_FIELD(record, ThreeBandEQ_enabled, uint8_t) && !next.count && + !plays_custom); + noise(samples, 256); + memcpy(expected, samples, 512 * sizeof *samples); + process(samples, 256); + assert(!memcmp(samples, expected, 512 * sizeof *samples)); /* no delay either */ + + /* Off: Apple's loader disables the EQ; the engine has nothing to play. */ + load(0, 44100); + assert(!RV_FIELD(record, ThreeBandEQ_enabled, uint8_t) && !next.count); + + /* A preset after Off fades in from dry: Apple ran nothing meanwhile, so + * neither the old stages nor what the limiter held play. */ + load(BASS_PRESET, 44100); + eq_reset((struct ThreeBandEQ *)record, NULL); + noise(samples, 512); + memcpy(previous, samples, 1024 * sizeof *samples); + process(samples, 512); + assert(!memcmp(samples, previous, D * 2 * sizeof *samples)); + assert(!fade.remaining && running(playing)); + + /* A flat set passes the audio through undelayed, and nothing runs per + * sample; the reset after its load keeps the fade from the delayed + * output, which ends exactly on the input. */ + flat(values, precut_choice(0)); + assert(eq_publish(values)); + load(EQ_CUSTOM_PRESET, 44100); + eq_reset((struct ThreeBandEQ *)record, NULL); + noise(samples, 512); + memcpy(previous, samples, 1024 * sizeof *samples); + process(samples, 512); + assert(!running(playing) && !fade.remaining); + assert(memcmp(samples, previous, RV_FADE_FRAMES * 2 * sizeof *samples)); + assert(!memcmp(samples + RV_FADE_FRAMES * 2, previous + RV_FADE_FRAMES * 2, + (512 - RV_FADE_FRAMES) * 2 * sizeof *samples)); + + /* Stopping while Custom plays turns the EQ off in Apple's record. */ + load(EQ_CUSTOM_PRESET, 44100); + assert(RV_FIELD(record, ThreeBandEQ_enabled, uint8_t)); + eq_engine_stop(); + assert(!RV_FIELD(record, ThreeBandEQ_enabled, uint8_t) && + !RV_FIELD(record, ThreeBandEQ_preset, uint32_t)); + for (unsigned int i = 0; i < 16; i++) + assert(record[ThreeBandEQ_bytes + i] == 0xdb); + assert(passes == 1 && resets == 8); + puts("engine: cascade headroom, precut, crossfade, reset and stop passed"); + return 0; +} diff --git a/extensions/equalizer/tests/run.py b/extensions/equalizer/tests/run.py new file mode 100755 index 0000000..cbfecf7 --- /dev/null +++ b/extensions/equalizer/tests/run.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +"""Run the host tests with a staged SDK: python3 tests/run.py SDK.""" + +import subprocess +import sys +import tempfile +from pathlib import Path + +root = Path(__file__).resolve().parent +dsp = root.parents[1] / "dsp" + + +def run_engine_test(work): + """The engine against a double-precision cascade, in tests/engine_test.c.""" + program = work / "engine_test" + subprocess.run( + ["cc", "-std=c11", "-Wall", "-Wextra", "-Werror", "-g"] + + [ + "-fsanitize=undefined", + "-fno-sanitize-recover=undefined", + f"-I{sdk}", + f"-I{dsp}", + ] + + ["-D_FORTIFY_SOURCE=0"] # macOS string.h would wrap what rv_libc.h declares + + [str(root / "engine_test.c"), str(dsp / "cascade.c")] + + [ + str(dsp / "filter.c"), + str(dsp / "math.c"), + str(dsp / "limiter.c"), + "-lm", + "-o", + str(program), + ], + check=True, + ) + subprocess.run([str(program)], check=True) + + +sdk = Path(sys.argv[1]).resolve() +with tempfile.TemporaryDirectory(prefix="equalizer-tests-") as name: + run_engine_test(Path(name)) +print("Equalizer tests passed") diff --git a/extensions/eu-volume-limit/Makefile b/extensions/eu-volume-limit/Makefile new file mode 100644 index 0000000..cb973a7 --- /dev/null +++ b/extensions/eu-volume-limit/Makefile @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: GPL-3.0-only +main_SOURCES := main.c +include $(SDK)/rv.mk diff --git a/extensions/eu-volume-limit/README.md b/extensions/eu-volume-limit/README.md new file mode 100644 index 0000000..d100b39 --- /dev/null +++ b/extensions/eu-volume-limit/README.md @@ -0,0 +1,24 @@ +# EU Volume Limit + +By paviro. + +Gives an EU iPod the volume behaviour of a non-EU one. With the EU Volume Limit switch in Settings > Volume Limit off, the volume goes 15% higher; with it on, the EU cap stays. Other iPods are unchanged. + +| | Stock EU iPod | With the extension | +|---|---|---| +| Ceiling with the switch off | 222 | 256 on Apple's scale, 15% higher | +| Ceiling with the switch on | 168 | 168 | +| Default volume limit | 222 | 256; a saved limit is kept | +| High-volume warning | yes | never | +| Saved volume lowered at startup | yes | never | +| Volume lowered after 20 hours of listening | yes | never | + +Apple checks two region flags, bit 0 and bit 7, and accepts a stored override where it checks bit 7. Stock shows the switch only for bit 7 and holds a bit-0 iPod at 222 without one; the extension shows it for either. It patches seven constants in 2.0.5. + +Turned off, Apple's behaviour returns at once, except the startup clamp, which returns at the next boot. The current volume and saved limit are kept. + +| | | +|---|---| +| Default | off | +| Memory | image only | +| Settings | none; Apple stores the switch | diff --git a/extensions/eu-volume-limit/assets/LICENSE.cupertino-icons b/extensions/eu-volume-limit/assets/LICENSE.cupertino-icons new file mode 100644 index 0000000..581f84c --- /dev/null +++ b/extensions/eu-volume-limit/assets/LICENSE.cupertino-icons @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2016 Vladimir Kharlampidi + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/extensions/eu-volume-limit/assets/settings-eu-volume-limit.png b/extensions/eu-volume-limit/assets/settings-eu-volume-limit.png new file mode 100644 index 0000000..058fcd1 Binary files /dev/null and b/extensions/eu-volume-limit/assets/settings-eu-volume-limit.png differ diff --git a/extensions/eu-volume-limit/assets/settings-eu-volume-limit.svg b/extensions/eu-volume-limit/assets/settings-eu-volume-limit.svg new file mode 100644 index 0000000..767f15f --- /dev/null +++ b/extensions/eu-volume-limit/assets/settings-eu-volume-limit.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/extensions/eu-volume-limit/listing.toml b/extensions/eu-volume-limit/listing.toml new file mode 100644 index 0000000..bdbf2e8 --- /dev/null +++ b/extensions/eu-volume-limit/listing.toml @@ -0,0 +1,3 @@ +details = "On an EU iPod, turn the EU Volume Limit switch in Settings > Volume Limit off for the full volume range, no high-volume warning and no automatic lowering. Other iPods are unchanged." + +icon = "assets/settings-eu-volume-limit.png" diff --git a/extensions/eu-volume-limit/main.c b/extensions/eu-volume-limit/main.c new file mode 100644 index 0000000..0d3cd75 --- /dev/null +++ b/extensions/eu-volume-limit/main.c @@ -0,0 +1,35 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#include "rv_api.h" +#include "rv_sites.h" +#include "rv_ui.h" + +static const struct rv_hook hooks[] = { + /* Test SysInfo bits 0 and 7 instead of bit 7 alone. */ + RV_HOOK_WORD(RV_SITE_VolumePolicy_RegionTest_word, 0xe3100081), + /* EU Volume Limit off: ceiling 256 instead of 222. */ + RV_HOOK_WORD(RV_SITE_Volume_EUOffCeiling_word, 0x03a00c01), + /* Default user limit and volume: 256 instead of 222. */ + RV_HOOK_WORD(RV_SITE_Volume_EUDefaultLimit_word, 0xe3a00c01), + /* The warning always reads as acknowledged. */ + RV_HOOK_WORD(RV_SITE_VolumePolicy_WarningPolicyTest_word, 0xe3a00000), + /* No startup volume clamp. */ + RV_HOOK_WORD(RV_SITE_Volume_StartupClampTest_word, 0xe3a00000), + /* No 18-hour exposure check on track change and stop. */ + RV_HOOK_WORD(RV_SITE_VolumeExposure_TrackFinishTest_word, 0xea00000f), + /* bx lr: the 20-hour exposure event never lowers the volume. */ + RV_HOOK_WORD(RV_SITE_MediaPlayer_PostVolumeExposureLimitEvent_word, 0xe12fff1e), +}; + +static const struct rv_descriptor extension = { + .size = sizeof extension, + RV_HOOKS(hooks), +}; + +const struct rv_descriptor *rv_module_entry(const struct rv_api *core, + rv_extension_handle handle) +{ + (void)core; + (void)handle; + return &extension; +} diff --git a/extensions/eu-volume-limit/manifest.toml b/extensions/eu-volume-limit/manifest.toml new file mode 100644 index 0000000..6bd47ab --- /dev/null +++ b/extensions/eu-volume-limit/manifest.toml @@ -0,0 +1,13 @@ +id = "eu-volume-limit" +name = "EU Volume Limit" +description = "Turns off the EU volume cap: 15% more volume with the limit switch off, no high-volume warning and no automatic lowering of the volume." +version = "0.1.0" +author = "RepriseOS contributors" +license = "GPL-3.0-only" +api = "1.89" +stability = "beta" +category = "media" + +[[module]] +name = "main" +trigger = "always" diff --git a/extensions/file-info/Makefile b/extensions/file-info/Makefile new file mode 100644 index 0000000..71e4704 --- /dev/null +++ b/extensions/file-info/Makefile @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: GPL-3.0-only +main_SOURCES := main.c info.c +include $(SDK)/rv.mk diff --git a/extensions/file-info/README.md b/extensions/file-info/README.md new file mode 100644 index 0000000..c4cb315 --- /dev/null +++ b/extensions/file-info/README.md @@ -0,0 +1,33 @@ +# File Info + +Based on the RepriseOS core's [File Info](https://github.com/RepriseOS/repriseos/blob/acbb928/payload/file_info.c), by lgreitis and paviro. + +Adds File Info to the context menu (hold Select) of a song, podcast episode, iTunes U episode, audiobook, movie, TV episode or video playlist entry, and to the Now Playing context menu. Other extensions can open it for a record through its service. The screen lists the item's tags and file properties. + +| Media kind | Rows | +|---|---| +| Song | Title, Artist, Album Artist, Album, Year, Genre, Composer, Grouping, Comment, Duration, Track, Disc, Kind, Sample Rate, Bitrate, File Size, Volume Adjustment, Rating, Play Count, Last Played, Skip Count, Last Skipped, Date Added, Date Modified | +| Podcast episode | Title, Podcast, Artist, Category, Genre, Description, Release Date, Duration, Chapters, Kind, Sample Rate, Bitrate, File Size, Volume Adjustment, Play Count, Last Played, Date Added | +| iTunes U episode | as a podcast episode, with Album in place of Podcast | +| Audiobook | Title, Author, Book, Genre, Description, Duration, Chapters, Kind, Sample Rate, Bitrate, File Size, Volume Adjustment, Play Count, Last Played, Date Added | +| Music video | Title, Artist, Album Artist, Album, Year, Genre, Comment, Duration, Kind, Bitrate, File Size, Volume Adjustment, Rating, Play Count, Last Played, Date Added | +| Movie, TV episode, rental | Title, Show, Year, Genre, Description, Release Date, Duration, Kind, Bitrate, File Size, Volume Adjustment, Rating, Play Count, Last Played, Date Added | + +Rows without a value are left out. Album Artist comes from the Album Artists extension while it runs, and only when it differs from the Artist. + +| Row | Format | +|---|---| +| Kind | iTunes's file kind, such as "AAC audio file" | +| Track, Disc | "3 of 12" when the total is known | +| dates | local time, "2024-03-05 14:07" | +| Volume Adjustment | the Sound Check offset as a percentage | +| Rating | stars out of five, or Unrated | +| File Size | MiB with one decimal | + +Values are read from Apple's library when the screen opens, and go blank if the library reloads. + +| | | +|---|---| +| Default | on | +| Memory | image only, plus about 130 bytes for the row table and the item it shows | +| Settings | none | diff --git a/extensions/file-info/assets/LICENSE.cupertino-icons b/extensions/file-info/assets/LICENSE.cupertino-icons new file mode 100644 index 0000000..581f84c --- /dev/null +++ b/extensions/file-info/assets/LICENSE.cupertino-icons @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2016 Vladimir Kharlampidi + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/extensions/file-info/assets/settings-file-info.png b/extensions/file-info/assets/settings-file-info.png new file mode 100644 index 0000000..eef5690 Binary files /dev/null and b/extensions/file-info/assets/settings-file-info.png differ diff --git a/extensions/file-info/assets/settings-file-info.svg b/extensions/file-info/assets/settings-file-info.svg new file mode 100644 index 0000000..afa249f --- /dev/null +++ b/extensions/file-info/assets/settings-file-info.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/extensions/file-info/info.c b/extensions/file-info/info.c new file mode 100644 index 0000000..8cd39fe --- /dev/null +++ b/extensions/file-info/info.c @@ -0,0 +1,390 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The rows of File Info: which fields a media kind shows, in which order, and + * each value formatted from the MediaItem's getters and its iTunesDB record. + * + * Based on RepriseOS payload/file_info.c (acbb928) by lgreitis and paviro. */ + +#include "info.h" +#include "../album-artists/service.h" +#include "osos-2.0.5.h" +#include "rv_api.h" +#include "rv_libc.h" +#include "rv_media.h" + +enum field { + TITLE, + ARTIST, + AUTHOR, + ALBUM, + PODCAST, + BOOK, + SHOW, + YEAR, + GENRE, + CATEGORY, + COMPOSER, + GROUPING, + COMMENT, + DESCRIPTION, + RELEASE_DATE, + DURATION, + CHAPTERS, + TRACK, + DISC, + KIND, + SAMPLE_RATE, + BITRATE, + FILE_SIZE, + VOLUME, + RATING, + PLAY_COUNT, + LAST_PLAYED, + SKIP_COUNT, + LAST_SKIPPED, + DATE_ADDED, + DATE_MODIFIED, + ALBUM_ARTIST, /* from the Album Artists extension while it runs */ + FIELDS +}; + +/* Labels in field order, each found by its offset into one string. */ +static const char labels[] = + "Title\0Artist\0Author\0Album\0Podcast\0Book\0Show\0Year\0Genre\0Category\0" + "Composer\0Grouping\0Comment\0Description\0Release Date\0Duration\0Chapters\0" + "Track\0Disc\0Kind\0Sample Rate\0Bitrate\0File Size\0Volume Adjustment\0" + "Rating\0Play Count\0Last Played\0Skip Count\0Last Skipped\0Date Added\0" + "Date Modified\0Album Artist"; +static const uint16_t label_offsets[FIELDS] = { + 0, 6, 13, 20, 26, 34, 39, 44, 49, 55, 64, 73, 82, 90, 102, 115, + 124, 133, 139, 144, 149, 161, 169, 179, 197, 204, 215, 227, 238, 251, 262, 276, +}; +_Static_assert(sizeof labels == 276 + sizeof "Album Artist", "label offsets drifted"); + +/* Rows per media kind, in display order. Fields without a value are left out. */ +static const uint8_t song_rows[] = { + TITLE, ARTIST, ALBUM_ARTIST, ALBUM, YEAR, + GENRE, COMPOSER, GROUPING, COMMENT, DURATION, + TRACK, DISC, KIND, SAMPLE_RATE, BITRATE, + FILE_SIZE, VOLUME, RATING, PLAY_COUNT, LAST_PLAYED, + SKIP_COUNT, LAST_SKIPPED, DATE_ADDED, DATE_MODIFIED, FIELDS, +}; +static const uint8_t podcast_rows[] = { + TITLE, PODCAST, ARTIST, CATEGORY, GENRE, DESCRIPTION, + RELEASE_DATE, DURATION, CHAPTERS, KIND, SAMPLE_RATE, BITRATE, + FILE_SIZE, VOLUME, PLAY_COUNT, LAST_PLAYED, DATE_ADDED, FIELDS, +}; +static const uint8_t lecture_rows[] = { + TITLE, ALBUM, ARTIST, CATEGORY, GENRE, DESCRIPTION, + RELEASE_DATE, DURATION, CHAPTERS, KIND, SAMPLE_RATE, BITRATE, + FILE_SIZE, VOLUME, PLAY_COUNT, LAST_PLAYED, DATE_ADDED, FIELDS, +}; +static const uint8_t audiobook_rows[] = { + TITLE, AUTHOR, BOOK, GENRE, DESCRIPTION, DURATION, + CHAPTERS, KIND, SAMPLE_RATE, BITRATE, FILE_SIZE, VOLUME, + PLAY_COUNT, LAST_PLAYED, DATE_ADDED, FIELDS, +}; +static const uint8_t music_video_rows[] = { + TITLE, ARTIST, ALBUM_ARTIST, ALBUM, YEAR, GENRE, + COMMENT, DURATION, KIND, BITRATE, FILE_SIZE, VOLUME, + RATING, PLAY_COUNT, LAST_PLAYED, DATE_ADDED, FIELDS, +}; +static const uint8_t video_rows[] = { + TITLE, SHOW, YEAR, GENRE, DESCRIPTION, RELEASE_DATE, DURATION, KIND, + BITRATE, FILE_SIZE, VOLUME, RATING, PLAY_COUNT, LAST_PLAYED, DATE_ADDED, FIELDS, +}; + +/* The item the rows were worked out for, the native string the last text + * value lives in, and the formatted number of the last other value. */ +static struct { + uint32_t item[MediaItem_bytes / 4]; + uint32_t text[NativeString_bytes / 4]; + uint8_t text_live; + uint8_t unknown; /* the requested field has no value */ + uint8_t rows[FIELDS]; + uint8_t count; + char value[24]; /* the longest is "4294967295 kbps" */ +} info; + +static const struct rv_api *api; + +static const uint8_t *record(const void *item) +{ + return RV_FIELD(item, MediaItem_record, const uint8_t *); +} + +static void release_text(void) +{ + if (info.text_live) + NativeString_Destroy((struct NativeString *)info.text); + info.text_live = 0; +} + +static void number(uint32_t value, const char *unit) +{ + if (!value) { + info.unknown = 1; + return; + } + rv_format(info.value, sizeof info.value, "%lu%s", (unsigned long)value, unit); +} + +static const char *text(const void *item, enum field field) +{ + static const uint16_t slots[FIELDS] = { + [TITLE] = MediaItem_title_method, + [ARTIST] = MediaItem_artist_method, + [AUTHOR] = MediaItem_artist_method, + [ALBUM] = MediaItem_album_method, + [PODCAST] = MediaItem_album_method, + [BOOK] = MediaItem_album_method, + [SHOW] = MediaItem_show_name_method, + [GENRE] = MediaItem_genre_method, + [CATEGORY] = MediaItem_category_method, + [COMPOSER] = MediaItem_composer_method, + [GROUPING] = MediaItem_grouping_method, + [COMMENT] = MediaItem_comment_method, + [DESCRIPTION] = MediaItem_description_method, + [KIND] = MediaItem_file_type_method, + }; + release_text(); + const char *data = + rv_item_text(item, slots[field], (struct NativeString *)info.text); + info.text_live = 1; + if (data) + return data; + info.unknown = 1; + return ""; +} + +/* The Album Artist from the Album Artists extension, which has one only when + * it differs from the Artist. */ +static const char *album_artist(const void *item) +{ + const struct album_artists_service *albums = + api->extension_service(ALBUM_ARTISTS_ID); + uint16_t units[256]; + uint32_t count = albums ? albums->read(record(item), units, 255) : 0; + release_text(); + if (!count) { + info.unknown = 1; + return ""; + } + struct NativeString *string = (struct NativeString *)info.text; + NativeString_InitEmpty(string); + NativeString_AssignUtf16(string, units, (int)count); + info.text_live = 1; + const char *data = NativeString_GetUtf8(string); + return data ? data : ""; +} + +static void ordinal(uint32_t value, uint32_t total) +{ + number(value, ""); + if (value && total >= value) + rv_format(info.value, sizeof info.value, "%lu of %lu", (unsigned long)value, + (unsigned long)total); +} + +/* A local date and time from one of the DateTime getters: "2024-03-05 14:07". + * The record's own word is checked first, since a getter turns an unset + * date into 1904. Release dates have no word; their getter says whether + * the record has one. */ +static void date(const void *item, uint32_t slot, int present) +{ + typedef int (*getter)(void *, const void *); + typedef int (*release_getter)(const void *, void *); + uint16_t when[DateTime_bytes / 2]; + const uint8_t *w = (const uint8_t *)when; + if (present && slot == MediaItem_release_date_method) + present = RV_FIELD(RV_FIELD(item, 0, void *), slot, release_getter)(item, when); + else if (present) + RV_FIELD(RV_FIELD(item, 0, void *), slot, getter)(when, item); + if (!present) { + info.unknown = 1; + return; + } + rv_format(info.value, sizeof info.value, "%u-%02u-%02u %02u:%02u", + RV_FIELD(w, DateTime_year, uint16_t), w[DateTime_month], w[DateTime_day], + w[DateTime_hour], w[DateTime_minute]); +} + +/* Sound Check's per-track adjustment, -255..255 for -100%..+100%. */ +static void volume(int32_t adjustment) +{ + if (!adjustment) { + info.unknown = 1; + return; + } + rv_format(info.value, sizeof info.value, "%s%d%%", adjustment > 0 ? "+" : "", + (int)(adjustment * 100 / 255)); +} + +/* The record keeps the sample rate as an IEEE single. */ +static void sample_rate(uint32_t bits) +{ + uint32_t exponent = bits >> 23 & 0xff, hertz = 0; + if (!(bits >> 31) && exponent >= 127 && exponent < 150) + hertz = ((bits & 0x7fffff) | 0x800000) >> (150 - exponent); + if (!hertz) { + info.unknown = 1; + return; + } + if (hertz % 1000 >= 100) + rv_format(info.value, sizeof info.value, "%lu.%lu kHz", + (unsigned long)(hertz / 1000), (unsigned long)(hertz % 1000 / 100)); + else + rv_format(info.value, sizeof info.value, "%lu kHz", + (unsigned long)(hertz / 1000)); +} + +static const char *value(const void *item, enum field field) +{ + const uint8_t *r = record(item); + switch (field) { + case YEAR: + number(rv_item_value(item, MediaItem_year_method) & 0xffff, ""); + break; + case DURATION: { + uint32_t ms = rv_item_value(item, MediaItem_duration_method); + if (ms) + rv_format_duration(info.value, sizeof info.value, ms / 1000); + else + info.unknown = 1; + break; + } + case CHAPTERS: + number(rv_item_value(item, MediaItem_chapter_count_method), ""); + break; + /* The record keeps the track and disc totals beside the ordinals. */ + case TRACK: + ordinal(rv_item_value(item, MediaItem_track_number_method) & 0xffff, + RV_FIELD(r, MediaRecord_track_total, uint16_t)); + break; + case DISC: + ordinal(rv_item_value(item, MediaItem_disc_number_method) & 0xffff, + RV_FIELD(r, MediaRecord_disc_total, uint16_t)); + break; + case SAMPLE_RATE: + sample_rate(RV_FIELD(r, MediaRecord_sample_rate, uint32_t)); + break; + case BITRATE: + number(rv_item_value(item, MediaItem_bitrate_method) & 0xffff, " kbps"); + break; + case FILE_SIZE: { + uint32_t bytes = rv_item_value(item, MediaItem_file_size_method); + if (bytes) + rv_format(info.value, sizeof info.value, "%lu.%lu MiB", + (unsigned long)(bytes >> 20), + (unsigned long)((bytes & 0xfffff) * 10 >> 20)); + else + info.unknown = 1; + break; + } + case RATING: { + int32_t rating = (int32_t)rv_item_value(item, MediaItem_rating_method); + if (rating > 0 && rating <= 100) + rv_format(info.value, sizeof info.value, "%d/5", (int)(rating / 20)); + else + rv_format(info.value, sizeof info.value, "Unrated"); + break; + } + case VOLUME: + volume(RV_FIELD(r, MediaRecord_volume, int16_t)); + break; + case RELEASE_DATE: + date(item, MediaItem_release_date_method, 1); + break; + case LAST_PLAYED: + date(item, MediaItem_last_played_method, + RV_FIELD(r, MediaRecord_last_played, uint32_t) != 0); + break; + case LAST_SKIPPED: + date(item, MediaItem_last_skipped_method, + RV_FIELD(r, MediaRecord_last_skipped, uint32_t) != 0); + break; + case DATE_ADDED: + date(item, MediaItem_date_added_method, + RV_FIELD(r, MediaRecord_date_added, uint32_t) != 0); + break; + case DATE_MODIFIED: + date(item, MediaItem_date_modified_method, + RV_FIELD(r, MediaRecord_date_modified, uint32_t) != 0); + break; + case PLAY_COUNT: + rv_format(info.value, sizeof info.value, "%lu", + (unsigned long)rv_item_value(item, MediaItem_play_count_method)); + break; + case SKIP_COUNT: + rv_format(info.value, sizeof info.value, "%lu", + (unsigned long)rv_item_value(item, MediaItem_skip_count_method)); + break; + case ALBUM_ARTIST: + return album_artist(item); + default: + return text(item, field); + } + return info.value; +} + +static const uint8_t *rows_for(uint32_t kind) +{ + if (kind & MediaKind_Audiobook) + return audiobook_rows; + if (kind & MediaKind_Podcast) + return podcast_rows; + if (kind & MediaKind_ITunesU) + return lecture_rows; + if (kind & MediaKind_MusicVideo) + return music_video_rows; + if (kind & (MediaKind_Movie | MediaKind_TVShow | MediaKind_Rental)) + return video_rows; + return song_rows; +} + +uint32_t info_rows(const void *item) +{ + if (!item) + return 0; + if (!memcmp(item, info.item, MediaItem_bytes)) + return info.count; + memcpy(info.item, item, MediaItem_bytes); + info.count = 0; + if (!rv_item_valid(item)) + return 0; + uint32_t kind = RV_FIELD(record(item), MediaRecord_media_kind, uint32_t); + for (const uint8_t *row = rows_for(kind); *row != FIELDS; row++) { + info.unknown = 0; + value(item, (enum field) * row); + if (!info.unknown) + info.rows[info.count++] = *row; + } + release_text(); + return info.count; +} + +const char *info_row(const void *item, uint32_t index, const char **out) +{ + if (info_rows(item) <= index) { + *out = NULL; + return ""; + } + enum field field = (enum field)info.rows[index]; + info.unknown = 0; + info.value[0] = 0; + /* The list can outlive the item when the library reloads. */ + *out = rv_item_valid(item) ? value(item, field) : info.value; + return labels + label_offsets[field]; +} + +void info_init(const struct rv_api *core) +{ + api = core; +} + +void info_release(void) +{ + release_text(); + memset(info.item, 0, sizeof info.item); + info.count = 0; +} diff --git a/extensions/file-info/info.h b/extensions/file-info/info.h new file mode 100644 index 0000000..3aa080f --- /dev/null +++ b/extensions/file-info/info.h @@ -0,0 +1,17 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#ifndef INFO_H +#define INFO_H +#include + +/* The rows of File Info for `item` (a MediaItem of the symbols header): how + * many have a value, and the label and value of row `index`. The rows are + * worked out when `item` changes and kept until info_release. */ +uint32_t info_rows(const void *item); +const char *info_row(const void *item, uint32_t index, const char **value); +void info_release(void); +/* The core table, for the Album Artists service. */ +struct rv_api; +void info_init(const struct rv_api *api); + +#endif diff --git a/extensions/file-info/listing.toml b/extensions/file-info/listing.toml new file mode 100644 index 0000000..4802c53 --- /dev/null +++ b/extensions/file-info/listing.toml @@ -0,0 +1,11 @@ +details = "Hold Select on a song, podcast or iTunes U episode, audiobook, movie, TV episode or video playlist entry, or in Now Playing, then choose File Info to see its tags and file properties." + +icon = "assets/settings-file-info.png" + +[[screenshots]] +file = "screenshots/context-menu.png" +alt = "A song's context menu with File Info above Play Next and Play Last." + +[[screenshots]] +file = "screenshots/song.png" +alt = "File Info for a compilation track: Title, Artist, Album Artist, Album and Year." diff --git a/extensions/file-info/main.c b/extensions/file-info/main.c new file mode 100644 index 0000000..6e7ae94 --- /dev/null +++ b/extensions/file-info/main.c @@ -0,0 +1,122 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* File Info in the context menus of songs, podcast and iTunes U episodes, + * audiobooks, movies, TV episodes, video playlists and Now Playing: the item's + * tags and file properties as a list of label and value rows. + * + * Based on RepriseOS payload/file_info.c (acbb928) by lgreitis and paviro. */ + +#include "info.h" +#include "service.h" +#include "osos-2.0.5.h" +#include "rv_api.h" +#include "rv_ui.h" +#include + +static const struct rv_api *api; +static rv_extension_handle self; + +/* The item File Info shows when another extension opened it, held until the + * screen closes. */ +static uint32_t opened[MediaItem_bytes / 4]; +static int holding; + +/* The menu's item, or the one the service opened. */ +static const void *item_of(const struct rv_context *ctx) +{ + return ctx->arg ? ctx->arg : ctx->item; +} + +static int has_item(const struct rv_context *ctx) +{ + return ctx->item != NULL; +} + +static uint32_t count(const struct rv_context *ctx) +{ + return info_rows(item_of(ctx)); +} + +static const char *row(const struct rv_context *ctx, uint32_t index, + const char **detail) +{ + return info_row(item_of(ctx), index, detail); +} + +static uint32_t first(const struct rv_context *ctx) +{ + (void)ctx; + return 0; +} + +static void release(void) +{ + if (holding) + MediaItem_Destroy((struct MediaItem *)opened); + holding = 0; +} + +static void closed(const struct rv_context *ctx) +{ + (void)ctx; + info_release(); + release(); +} + +/* closed is not called when the extension unloads under the screen. */ +static void unload(void) +{ + info_release(); + release(); +} + +static int open(void *record) +{ + release(); + info_release(); + MediaItem_InitFromRecord((struct MediaItem *)opened, record, 0); + holding = 1; + int status = api->ui_push(self, "info", opened); + if (status != RV_OK) + release(); + return status; +} + +static const struct file_info_service service = {open}; + +static const struct rv_screen screens[] = { + RV_SCREEN_DYNAMIC_LIST("info", "File Info", count, row, .layout = RV_LAYOUT_FULL, + .dynamic.detail = RV_DETAIL_BELOW, .dynamic.initial = first, + .closed = closed), +}; + +/* Every context menu that hands over an item. */ +#define ITEM_MENUS \ + (RV_MENU_BIT(RV_MENU_SONG_CONTEXT) | RV_MENU_BIT(RV_MENU_NOW_PLAYING_CONTEXT) | \ + RV_MENU_BIT(RV_MENU_PODCAST_EPISODE_CONTEXT) | \ + RV_MENU_BIT(RV_MENU_ITUNES_U_EPISODE_CONTEXT) | \ + RV_MENU_BIT(RV_MENU_AUDIOBOOK_CONTEXT) | RV_MENU_BIT(RV_MENU_MOVIE_CONTEXT) | \ + RV_MENU_BIT(RV_MENU_TV_EPISODE_CONTEXT) | \ + RV_MENU_BIT(RV_MENU_VIDEO_PLAYLIST_CONTEXT)) + +static const struct rv_menu_entry entries[] = { + RV_MENUS_ENTRY(ITEM_MENUS, 0, RV_ROW_PUSH("File Info", "info"), + .available = has_item), +}; + +static const struct rv_descriptor extension = { + .size = sizeof extension, + RV_SCREENS(screens), + RV_ENTRIES(entries), + .unload = unload, + .service = &service, +}; + +const struct rv_descriptor *rv_module_entry(const struct rv_api *table, + rv_extension_handle handle) +{ + api = table; + self = handle; + info_init(api); + return &extension; +} diff --git a/extensions/file-info/manifest.toml b/extensions/file-info/manifest.toml new file mode 100644 index 0000000..b4adea0 --- /dev/null +++ b/extensions/file-info/manifest.toml @@ -0,0 +1,13 @@ +id = "file-info" +name = "File Info" +description = "Show a song, episode, audiobook or video's tags and file properties from its context menu." +version = "0.1.0" +author = "RepriseOS contributors" +license = "GPL-3.0-only" +api = "1.89" +stability = "beta" +category = "media" + +[[module]] +name = "main" +trigger = "always" diff --git a/extensions/file-info/screenshots/context-menu.png b/extensions/file-info/screenshots/context-menu.png new file mode 100644 index 0000000..006318c Binary files /dev/null and b/extensions/file-info/screenshots/context-menu.png differ diff --git a/extensions/file-info/screenshots/song.png b/extensions/file-info/screenshots/song.png new file mode 100644 index 0000000..75ddfac Binary files /dev/null and b/extensions/file-info/screenshots/song.png differ diff --git a/extensions/file-info/service.h b/extensions/file-info/service.h new file mode 100644 index 0000000..e5e2872 --- /dev/null +++ b/extensions/file-info/service.h @@ -0,0 +1,16 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* What File Info offers other extensions through api->extension_service. */ + +#ifndef FILE_INFO_SERVICE_H +#define FILE_INFO_SERVICE_H + +#define FILE_INFO_ID "file-info" + +struct file_info_service { + /* Opens File Info above the top screen for `record` (a media record of + * the symbols header); RV_OK or the ui_push error. UI task. */ + int (*open)(void *record); +}; + +#endif diff --git a/extensions/file-info/tests/contracts.c b/extensions/file-info/tests/contracts.c new file mode 100644 index 0000000..f0bea5d --- /dev/null +++ b/extensions/file-info/tests/contracts.c @@ -0,0 +1,489 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ +#include +#include +#include +#include +#include "../info.c" + +/* The host formats; the device's rv_libc does the same for these conversions. */ +uint32_t rv_format(char *out, uint32_t capacity, const char *format, ...) +{ + va_list args; + va_start(args, format); + int n = vsnprintf(out, capacity, format, args); + va_end(args); + return (uint32_t)n; +} + +uint32_t rv_format_duration(char *out, uint32_t capacity, uint32_t seconds) +{ + uint32_t minutes = seconds / 60; + if (minutes < 60) + return rv_format(out, capacity, "%u:%02u", minutes, seconds % 60); + return rv_format(out, capacity, "%u:%02u:%02u", minutes / 60, minutes % 60, + seconds % 60); +} + +/* A native string holds one pointer; init, destroy and read are counted. */ +static int strings_live; + +struct NativeString *NativeString_InitEmpty(struct NativeString *s) +{ + RV_FIELD(s, 0, const char *) = ""; + strings_live++; + return s; +} + +struct NativeString *NativeString_Destroy(struct NativeString *s) +{ + assert(strings_live > 0); + strings_live--; + RV_FIELD(s, 0, const char *) = NULL; + return s; +} + +char *NativeString_GetUtf8(struct NativeString *s) +{ + return (char *)RV_FIELD(s, 0, const char *); +} + +/* The native string takes UTF-16 as the Album Artists service hands it over. */ +static char assigned[256]; + +void NativeString_AssignUtf16(struct NativeString *s, const uint16_t *text, + int characters) +{ + for (int i = 0; i < characters; i++) + assigned[i] = (char)text[i]; + assigned[characters] = 0; + RV_FIELD(s, 0, const char *) = assigned; +} + +/* The Album Artists service: present with a text, present without one, or absent. */ +static const char *album_artist_text; +static int album_artists_present; + +static uint32_t read_album_artist(const void *record, uint16_t *text, + uint32_t max_units) +{ + (void)record; + if (!album_artist_text) + return 0; + uint32_t n = 0; + for (; album_artist_text[n] && n < max_units; n++) + text[n] = (uint16_t)album_artist_text[n]; + return n; +} +static const struct album_artists_service album_artists = {read_album_artist}; + +static const void *extension_service(const char *id) +{ + assert(!strcmp(id, ALBUM_ARTISTS_ID)); + return album_artists_present ? &album_artists : NULL; +} +static const struct rv_api fake_api = {.extension_service = extension_service}; + +static int item_valid = 1; + +int MediaItem_IsValid(struct MediaItem *i) +{ + (void)i; + return item_valid; +} + +/* The item under test: a vtable of getters over these values and a record. */ +static struct { + const char *title, *artist, *album, *genre, *composer, *grouping, *kind, *comment, + *category, *description, *show; + uint32_t year, duration, chapters, track, disc, bitrate, file_size, play_count, + skip_count; + int32_t rating, release; +} fake; + +static uint8_t track_record[0x100]; +static uintptr_t methods[0x140 / 4]; +static uint8_t item[MediaItem_bytes]; + +#define TEXT_GETTER(name, field) \ + static void name(const void *i, void *s) \ + { \ + assert(i == item); \ + RV_FIELD(s, 0, const char *) = fake.field; \ + } +TEXT_GETTER(get_title, title) +TEXT_GETTER(get_artist, artist) +TEXT_GETTER(get_album, album) +TEXT_GETTER(get_genre, genre) +TEXT_GETTER(get_composer, composer) +TEXT_GETTER(get_grouping, grouping) +TEXT_GETTER(get_kind, kind) +TEXT_GETTER(get_comment, comment) +TEXT_GETTER(get_category, category) +TEXT_GETTER(get_description, description) +TEXT_GETTER(get_show, show) +#define VALUE_GETTER(name, field) \ + static uint32_t name(const void *i) \ + { \ + assert(i == item); \ + return (uint32_t)fake.field; \ + } +VALUE_GETTER(get_year, year) +VALUE_GETTER(get_duration, duration) +VALUE_GETTER(get_chapters, chapters) +VALUE_GETTER(get_track, track) +VALUE_GETTER(get_disc, disc) +VALUE_GETTER(get_bitrate, bitrate) +VALUE_GETTER(get_file_size, file_size) +VALUE_GETTER(get_play_count, play_count) +VALUE_GETTER(get_skip_count, skip_count) +VALUE_GETTER(get_rating, rating) + +/* The date getters fill a DateTime; each has its own fixed moment. */ +static void fill_date(void *out, unsigned year, unsigned month, unsigned day, + unsigned hour, unsigned minute) +{ + uint8_t *w = out; + memset(w, 0, DateTime_bytes); + RV_FIELD(w, DateTime_year, uint16_t) = (uint16_t)year; + w[DateTime_month] = (uint8_t)month; + w[DateTime_day] = (uint8_t)day; + w[DateTime_hour] = (uint8_t)hour; + w[DateTime_minute] = (uint8_t)minute; +} + +#define DATE_GETTER(name, y, mo, d, h, mi) \ + static int name(void *out, const void *i) \ + { \ + assert(i == item); \ + fill_date(out, y, mo, d, h, mi); \ + return 0; \ + } +DATE_GETTER(get_added, 2024, 3, 5, 14, 7) +DATE_GETTER(get_modified, 2024, 4, 6, 9, 30) +DATE_GETTER(get_played, 2025, 1, 2, 23, 59) +DATE_GETTER(get_skipped, 2025, 2, 3, 0, 1) + +static int get_release(const void *i, void *out) +{ + assert(i == item); + if (fake.release) + fill_date(out, 2019, 12, 24, 18, 0); + return fake.release; +} + +static void set(uint32_t slot, void *fn) +{ + methods[slot / sizeof(void *)] = (uintptr_t)fn; +} + +static void reset(uint32_t kind, float sample_rate, uint16_t tracks, uint16_t discs) +{ + info_release(); + memset(&fake, 0, sizeof fake); + fake.title = "Song A"; + fake.artist = "Artist A"; + fake.album = "Album A"; + fake.genre = "Rock"; + fake.composer = "Composer A"; + fake.grouping = "Set 1"; + fake.kind = "AAC audio file"; + fake.comment = "A note"; + fake.category = "Technology"; + fake.description = "About the episode"; + fake.show = "The Show"; + fake.release = 1; + fake.year = 1999; + fake.duration = 3723000; + fake.chapters = 5; + fake.track = 3; + fake.disc = 1; + fake.bitrate = 256; + fake.file_size = 5767168; + fake.rating = 80; + fake.play_count = 0; + fake.skip_count = 2; + memset(track_record, 0, sizeof track_record); + RV_FIELD(track_record, MediaRecord_media_kind, uint32_t) = kind; + memcpy(track_record + MediaRecord_sample_rate, &sample_rate, 4); + RV_FIELD(track_record, MediaRecord_track_total, uint16_t) = tracks; + RV_FIELD(track_record, MediaRecord_disc_total, uint16_t) = discs; + RV_FIELD(track_record, MediaRecord_volume, int16_t) = -51; + RV_FIELD(track_record, MediaRecord_date_added, uint32_t) = 1; + RV_FIELD(track_record, MediaRecord_date_modified, uint32_t) = 1; + RV_FIELD(track_record, MediaRecord_last_played, uint32_t) = 1; + RV_FIELD(track_record, MediaRecord_last_skipped, uint32_t) = 1; + memset(item, 0, sizeof item); + RV_FIELD(item, 0, void *) = methods; + RV_FIELD(item, MediaItem_record, void *) = track_record; + RV_FIELD(item, MediaItem_generation, uint32_t)++; + item_valid = 1; +} + +/* The label and value of row `index`. */ +static const char *label_of(uint32_t index, const char **value) +{ + return info_row(item, index, value); +} + +static void expect(uint32_t index, const char *label, const char *value) +{ + const char *got; + const char *l = label_of(index, &got); + if (strcmp(l, label) || strcmp(got, value)) + fprintf(stderr, "row %u: got %s = %s, want %s = %s\n", index, l, got, label, + value); + assert(!strcmp(l, label) && !strcmp(got, value)); +} + +static void expect_labels(const char *const *labels, uint32_t count) +{ + assert(info_rows(item) == count); + for (uint32_t i = 0; i < count; i++) { + const char *value; + assert(!strcmp(label_of(i, &value), labels[i])); + assert(value && *value); + } +} + +int main(void) +{ + info_init(&fake_api); + set(MediaItem_title_method, get_title); + set(MediaItem_artist_method, get_artist); + set(MediaItem_album_method, get_album); + set(MediaItem_genre_method, get_genre); + set(MediaItem_composer_method, get_composer); + set(MediaItem_grouping_method, get_grouping); + set(MediaItem_file_type_method, get_kind); + set(MediaItem_comment_method, get_comment); + set(MediaItem_category_method, get_category); + set(MediaItem_description_method, get_description); + set(MediaItem_show_name_method, get_show); + set(MediaItem_date_added_method, get_added); + set(MediaItem_date_modified_method, get_modified); + set(MediaItem_last_played_method, get_played); + set(MediaItem_last_skipped_method, get_skipped); + set(MediaItem_release_date_method, get_release); + set(MediaItem_year_method, get_year); + set(MediaItem_duration_method, get_duration); + set(MediaItem_chapter_count_method, get_chapters); + set(MediaItem_track_number_method, get_track); + set(MediaItem_disc_number_method, get_disc); + set(MediaItem_bitrate_method, get_bitrate); + set(MediaItem_file_size_method, get_file_size); + set(MediaItem_play_count_method, get_play_count); + set(MediaItem_skip_count_method, get_skip_count); + set(MediaItem_rating_method, get_rating); + + /* A song with every field. */ + reset(0, 44100.0f, 12, 0); + assert(info_rows(item) == 23); + expect(0, "Title", "Song A"); + expect(1, "Artist", "Artist A"); + expect(2, "Album", "Album A"); + expect(3, "Year", "1999"); + expect(4, "Genre", "Rock"); + expect(5, "Composer", "Composer A"); + expect(6, "Grouping", "Set 1"); + expect(7, "Comment", "A note"); + expect(8, "Duration", "1:02:03"); + expect(9, "Track", "3 of 12"); + expect(10, "Disc", "1"); + expect(11, "Kind", "AAC audio file"); + expect(12, "Sample Rate", "44.1 kHz"); + expect(13, "Bitrate", "256 kbps"); + expect(14, "File Size", "5.5 MiB"); + expect(15, "Volume Adjustment", "-20%"); + expect(16, "Rating", "4/5"); + expect(17, "Play Count", "0"); + expect(18, "Last Played", "2025-01-02 23:59"); + expect(19, "Skip Count", "2"); + expect(20, "Last Skipped", "2025-02-03 00:01"); + expect(21, "Date Added", "2024-03-05 14:07"); + expect(22, "Date Modified", "2024-04-06 09:30"); + /* The rows are kept for the same item; the last text value's string stays + * until the next text value, a new item or release. */ + assert(info_rows(item) == 23 && strings_live == 1); + expect(0, "Title", "Song A"); + assert(strings_live == 1); + info_release(); + assert(strings_live == 0); + + /* Fields without a value are left out; a disc total below the ordinal is + * ignored; an unset date word skips its getter. */ + reset(0, 48000.0f, 0, 1); + fake.year = 0; + fake.composer = ""; + fake.grouping = NULL; + fake.comment = ""; + fake.kind = ""; + fake.disc = 2; + fake.rating = 0; + RV_FIELD(track_record, MediaRecord_volume, int16_t) = 0; + RV_FIELD(track_record, MediaRecord_last_played, uint32_t) = 0; + RV_FIELD(track_record, MediaRecord_last_skipped, uint32_t) = 0; + RV_FIELD(track_record, MediaRecord_date_modified, uint32_t) = 0; + static const char *const song_short[] = { + "Title", "Artist", "Album", "Genre", "Duration", + "Track", "Disc", "Sample Rate", "Bitrate", "File Size", + "Rating", "Play Count", "Skip Count", "Date Added", + }; + expect_labels(song_short, 14); + expect(5, "Track", "3"); + expect(6, "Disc", "2"); + expect(7, "Sample Rate", "48 kHz"); + expect(10, "Rating", "Unrated"); + + /* Short durations, odd sample rates, large files, full ratings, loud tracks. */ + reset(0, 22050.0f, 0, 0); + fake.duration = 187000; + fake.rating = 100; + fake.file_size = 1048576 * 1000 + 943718; + RV_FIELD(track_record, MediaRecord_volume, int16_t) = 255; + expect(8, "Duration", "3:07"); + expect(10, "Disc", "1"); + expect(12, "Sample Rate", "22 kHz"); + expect(14, "File Size", "1000.8 MiB"); + expect(15, "Volume Adjustment", "+100%"); + expect(16, "Rating", "5/5"); + reset(0, -44100.0f, 0, 0); + assert(info_rows(item) == 22); /* a negative rate is no rate */ + + /* Each media kind has its own rows; audiobooks relabel artist and album, + * videos show their series and release date. */ + reset(MediaKind_Podcast, 44100.0f, 0, 0); + static const char *const podcast[] = { + "Title", "Podcast", "Artist", "Category", "Genre", + "Description", "Release Date", "Duration", "Chapters", "Kind", + "Sample Rate", "Bitrate", "File Size", "Volume Adjustment", "Play Count", + "Last Played", "Date Added", + }; + expect_labels(podcast, 17); + expect(1, "Podcast", "Album A"); + expect(6, "Release Date", "2019-12-24 18:00"); + expect(8, "Chapters", "5"); + fake.release = 0; + RV_FIELD(item, MediaItem_generation, uint32_t)++; + assert(info_rows(item) == 16); + reset(MediaKind_ITunesU, 44100.0f, 0, 0); + static const char *const lecture[] = { + "Title", "Album", "Artist", "Category", "Genre", + "Description", "Release Date", "Duration", "Chapters", "Kind", + "Sample Rate", "Bitrate", "File Size", "Volume Adjustment", "Play Count", + "Last Played", "Date Added", + }; + expect_labels(lecture, 17); + reset(MediaKind_Audiobook, 44100.0f, 0, 0); + static const char *const audiobook[] = { + "Title", "Author", "Book", "Genre", + "Description", "Duration", "Chapters", "Kind", + "Sample Rate", "Bitrate", "File Size", "Volume Adjustment", + "Play Count", "Last Played", "Date Added", + }; + expect_labels(audiobook, 15); + expect(1, "Author", "Artist A"); + expect(2, "Book", "Album A"); + reset(MediaKind_MusicVideo, 44100.0f, 0, 0); + static const char *const music_video[] = { + "Title", + "Artist", + "Album", + "Year", + "Genre", + "Comment", + "Duration", + "Kind", + "Bitrate", + "File Size", + "Volume Adjustment", + "Rating", + "Play Count", + "Last Played", + "Date Added", + }; + expect_labels(music_video, 15); + static const char *const video[] = { + "Title", + "Show", + "Year", + "Genre", + "Description", + "Release Date", + "Duration", + "Kind", + "Bitrate", + "File Size", + "Volume Adjustment", + "Rating", + "Play Count", + "Last Played", + "Date Added", + }; + reset(MediaKind_Movie, 44100.0f, 0, 0); + expect_labels(video, 15); + expect(1, "Show", "The Show"); + reset(MediaKind_TVShow, 44100.0f, 0, 0); + expect_labels(video, 15); + reset(MediaKind_Rental | MediaKind_Movie, 44100.0f, 0, 0); + fake.show = ""; + assert(info_rows(item) == 14); + /* Audiobook wins over the other bits, as the Music menu files it. */ + reset(MediaKind_Audiobook | MediaKind_Podcast, 44100.0f, 0, 0); + expect_labels(audiobook, 15); + + /* An item that is no longer valid keeps its rows with blank values; one + * that was never valid has none. */ + reset(0, 44100.0f, 0, 0); + assert(info_rows(item) == 23); + item_valid = 0; + expect(0, "Title", ""); + expect(13, "Bitrate", ""); + assert(strings_live == 0); + reset(0, 44100.0f, 0, 0); + item_valid = 0; + assert(info_rows(item) == 0); + assert(info_rows(NULL) == 0); + const char *none; + assert(!strcmp(info_row(item, 0, &none), "") && none == NULL); + + /* Album Artist shows after Artist while the Album Artists extension runs + * and has one for the song; an absent service or an empty answer leaves + * the row out. */ + reset(0, 44100.0f, 0, 0); + album_artists_present = 1; + album_artist_text = "Various Artists"; + assert(info_rows(item) == 24); + expect(1, "Artist", "Artist A"); + expect(2, "Album Artist", "Various Artists"); + expect(3, "Album", "Album A"); + assert(strings_live == 1); + reset(MediaKind_MusicVideo, 44100.0f, 0, 0); + assert(info_rows(item) == 16); + expect(2, "Album Artist", "Various Artists"); + reset(MediaKind_Podcast, 44100.0f, 0, 0); + assert(info_rows(item) == 17); + reset(0, 44100.0f, 0, 0); + album_artist_text = NULL; + assert(info_rows(item) == 23); + album_artists_present = 0; + album_artist_text = "Various Artists"; + reset(0, 44100.0f, 0, 0); + assert(info_rows(item) == 23); + album_artist_text = NULL; + info_release(); + assert(strings_live == 0); + + /* A different item replaces the rows; release forgets them. */ + reset(0, 44100.0f, 0, 0); + assert(info_rows(item) == 23); + RV_FIELD(item, MediaItem_generation, uint32_t)++; + fake.year = 0; + assert(info_rows(item) == 22); + info_release(); + assert(strings_live == 0); + fake.year = 2001; + assert(info_rows(item) == 23); + info_release(); + assert(strings_live == 0); + return 0; +} diff --git a/extensions/file-info/tests/run.py b/extensions/file-info/tests/run.py new file mode 100644 index 0000000..8469e29 --- /dev/null +++ b/extensions/file-info/tests/run.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +"""Run the row and formatting tests with a staged SDK: python3 tests/run.py SDK.""" + +import re +import subprocess +import sys +import tempfile +from pathlib import Path + +root = Path(__file__).resolve().parent +sdk = Path(sys.argv[1]).resolve() +with tempfile.TemporaryDirectory(prefix="file-info-tests-") as name: + work = Path(name) + # Widen the pointer-bearing native layouts for the host; record offsets stay. + header = (sdk / "osos-2.0.5.h").read_text() + + def widen(match): + key, value = match.groups() + if key.startswith(("MediaItem_", "NativeString_")): + return f"#define {key} {int(value, 16) * 2:#x}" + return match[0] + + (work / "osos-2.0.5.h").write_text( + re.sub(r"#define (\w+) (0x[0-9a-f]+)", widen, header) + ) + (work / "rv_api.h").write_text((sdk / "rv_api.h").read_text()) + (work / "rv_libc.h").write_text((sdk / "rv_libc.h").read_text()) + (work / "rv_media.h").write_text((sdk / "rv_media.h").read_text()) + executable = work / "contracts" + subprocess.run( + [ + "cc", + "-std=c11", + "-Wall", + "-Wextra", + "-Werror", + "-g", + "-fsanitize=address,undefined", + "-I", + str(work), + str(root / "contracts.c"), + "-o", + str(executable), + ], + check=True, + ) + subprocess.run([str(executable)], check=True) +print("File Info contracts passed") diff --git a/extensions/homebrew/Makefile b/extensions/homebrew/Makefile new file mode 100644 index 0000000..cb973a7 --- /dev/null +++ b/extensions/homebrew/Makefile @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: GPL-3.0-only +main_SOURCES := main.c +include $(SDK)/rv.mk diff --git a/extensions/homebrew/README.md b/extensions/homebrew/README.md new file mode 100644 index 0000000..acad91b --- /dev/null +++ b/extensions/homebrew/README.md @@ -0,0 +1,32 @@ +# Homebrew + +Based on the RepriseOS core's [homebrew patch](https://github.com/RepriseOS/repriseos/blob/b9b1c62/payload/homebrew.c), by lgreitis. + +Lists apps and games from folders under `/Reprise/` and lets Apple's game runtime start them unsigned. A package is a folder with the program, a `Manifest.plist` and an icon, built with the [eApp SDK](https://github.com/RepriseOS/repriseos/tree/main/eapp-sdk). + +| Folder | Appears | +|---|---| +| `/Reprise/Games//` | Extras > Games, with the built-in games and those from iTunes | +| `/Reprise/Apps//` | Extras > Apps | + +Apple builds one games list. Opening Apps sets it aside and builds an apps list from `/Reprise/Apps/`; leaving Apps frees that and restores the games list without a rescan. When disk mode ends, Apple rebuilds the games list from the stock folders and `/Reprise/Games/`. The Apps count in the Extras pane is recounted with each build. The list is never rebuilt while a package runs. + +Only manifests under `/Reprise/Games//` and `/Reprise/Apps//` skip the signature check; games under `iPod_Control/` keep it. The id is one folder name, without `\` or `:` and not starting with a dot. A package with the id of a game under `iPod_Control/` replaces that game in the list. + +| Apple's folder | Game | App | +|---|---|---| +| `iPod_Control/gamedata_RW//` | `/Reprise/Data/Games/gamedata_RW//` | `/Reprise/Data/Apps/appdata_RW//` | +| `iPod_Control/gamestats_WO//` | `/Reprise/Data/Games/gamestats_WO//` | `/Reprise/Data/Apps/appstats_WO//` | +| `iPod_Control/gamedata_ShareRW/` | `/Reprise/Data/Games/gamedata_ShareRW/` | `/Reprise/Data/Apps/appdata_ShareRW/` | + +The shared folder has no id, so all games share one and all apps another. + +On other firmware the same package uses Apple's folders like any game. + +Turned off, the Apps row and both folders' packages disappear at the next list build. + +| | | +|---|---| +| Default | on | +| Memory | image only; the ids of the listed folder while a list holds them, and the games list beside the apps one while Apps is open | +| Settings | none | diff --git a/extensions/homebrew/assets/LICENSE.cupertino-icons b/extensions/homebrew/assets/LICENSE.cupertino-icons new file mode 100644 index 0000000..581f84c --- /dev/null +++ b/extensions/homebrew/assets/LICENSE.cupertino-icons @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2016 Vladimir Kharlampidi + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/extensions/homebrew/assets/apps.png b/extensions/homebrew/assets/apps.png new file mode 100644 index 0000000..ff197d6 Binary files /dev/null and b/extensions/homebrew/assets/apps.png differ diff --git a/extensions/homebrew/assets/render.py b/extensions/homebrew/assets/render.py new file mode 100644 index 0000000..a4ee76d --- /dev/null +++ b/extensions/homebrew/assets/render.py @@ -0,0 +1,386 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +"""Render apps.png, the Extras pane picture of the Apps row: a slate sheet-metal +toolbox with a chrome handle, seen from the front-right, lit like the stock +Extras pictures and standing in a soft contact shadow on a transparent 142 x 87 +canvas. The scene is a signed-distance model marched and shaded with numpy; no +image assets go in. + + python3 assets/render.py + python3 assets/render.py --check +""" + +import argparse +import math +import struct +import sys +import zlib +from pathlib import Path + +import numpy as np + +HERE = Path(__file__).resolve().parent +OUT = HERE / "apps.png" +WIDTH, HEIGHT, SUPERSAMPLE = 142, 87, 4 + +# The toolbox, in a frame where y is up and the tray stands on y = 0. +TRAY = (1.4, 0.85, 0.55) # half length, height, half width +LID_SKIRT, LID_RISE, RIDGE_HALF = 0.12, 0.30, 0.20 +LID_LAP, LID_DROP = 0.012, 0.06 # the skirt stands proud of, and drops over, the tray wall +FOLD = 0.016 # bend radius of the lid's folds +HANDLE = (0.5, 0.26, 0.13, 0.045) # half width, height, corner radius, tube radius +YAW = -30 # degrees the box turns from square-on, showing its right end +CAMERA, LOOK, FOV = (0.11, 1.84, 4.38), (0.0, 0.435, 0.0), 30 +KEY_LIGHT, KEY_POWER = (-1.4, 4.0, 2.2), 4.0 +SHADOW = 0.75 + + +def length(v): + return np.linalg.norm(v, axis=-1) + + +def unit(v): + return v / np.maximum(length(v)[..., None], 1e-9) + + +def rotation(yaw): + """Rotation about y by `yaw` degrees.""" + c, s = math.cos(math.radians(yaw)), math.sin(math.radians(yaw)) + return np.array([[c, 0, s], [0, 1, 0], [-s, 0, c]]) + + +def linear(hex_color): + """A #rrggbb sRGB colour as linear light.""" + c = np.array([int(hex_color[i : i + 2], 16) / 255 for i in (0, 2, 4)]) + return np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4) + + +# ---- distance fields ------------------------------------------------------- + + +def sd_box(q, half, radius): + d = np.abs(q) - (np.array(half) - radius) + return length(np.maximum(d, 0)) + np.minimum(d.max(-1), 0) - radius + + +def sd_capsule(q, a, b, radius): + a, b = np.array(a), np.array(b) + pa, ba = q - a, b - a + h = np.clip((pa @ ba) / (ba @ ba), 0, 1) + return length(pa - ba * h[..., None]) - radius + + +def sd_round_rect(xy, hw, hh, radius): + d = np.abs(xy) - np.array([hw - radius, hh - radius]) + return length(np.maximum(d, 0)) + np.minimum(d.max(-1), 0) - radius + + +def smooth_min(a, b, k): + h = np.clip(0.5 + 0.5 * (b - a) / k, 0, 1) + return b * (1 - h) + a * h - k * h * (1 - h) + + +def smooth_max(a, b, k): + return -smooth_min(-a, -b, k) + + +class Material: + def __init__(self, color, rough=0.05, metal=False, coat=1.0, tint=1.0): + self.color, self.rough, self.metal, self.coat, self.tint = ( + linear(color), + rough, + metal, + coat, + tint, + ) + + +class Shape: + """A distance function in its own frame, placed in the world.""" + + def __init__(self, fn, material, pos=(0, 0, 0), yaw=0.0): + self.fn, self.material = fn, material + self.pos, self.rot = np.array(pos, float), rotation(yaw) + + def local(self, p): + return (p - self.pos) @ self.rot + + def sdf(self, p): + return self.fn(self.local(p)) + + +SLATE = Material("33475c") +STEEL = Material("d8dbe0", rough=0.08, metal=True, tint=1.25) +RUBBER = Material("1a1a1c", rough=0.3, coat=0.3) + + +def toolbox(yaw=YAW): + """Tray, a hip-roof lid with the tray's footprint, two latches over the seam, + and a chrome handle with a rubber grip on two mounting plates.""" + hx, top, hz = TRAY + turn = rotation(yaw) + + def placed(x, y, z): + return turn @ np.array([x, y, z]) + + tray = Shape(lambda q: sd_box(q, (hx, top / 2, hz), 0.04), SLATE, (0, top / 2, 0), yaw) + + slope = (hz - RIDGE_HALF) / LID_RISE + slope_norm = math.sqrt(1 + slope * slope) + lx, lz = hx + LID_LAP, hz + LID_LAP + + def lid_fn(q): + x, y, z = q[..., 0], q[..., 1], q[..., 2] # y = 0 at the skirt's bottom + planes = ( + -y, + y - (LID_SKIRT + LID_RISE), + np.abs(x) - lx, + np.abs(z) - lz, + (z + slope * (y - LID_SKIRT) - lz) / slope_norm, + (-z + slope * (y - LID_SKIRT) - lz) / slope_norm, + ) + d = planes[0] + for plane in planes[1:]: + d = smooth_max(d, plane, FOLD) + return d + + lid_base = top - LID_DROP + lid = Shape(lid_fn, SLATE, (0, lid_base, 0), yaw) + ridge = lid_base + LID_SKIRT + LID_RISE + + hw, hh, corner, tube = HANDLE + + def plates_fn(q): + return np.minimum( + sd_box(q - np.array([-hw, 0, 0]), (0.09, 0.02, 0.12), 0.015), + sd_box(q - np.array([hw, 0, 0]), (0.09, 0.02, 0.12), 0.015), + ) + + plates = Shape(plates_fn, STEEL, (0, ridge + 0.02, 0), yaw) + + def latches_fn(q): + return np.minimum( + sd_box(q - np.array([-0.62, 0, 0]), (0.055, 0.08, 0.022), 0.015), + sd_box(q - np.array([0.62, 0, 0]), (0.055, 0.08, 0.022), 0.015), + ) + + latches = Shape(latches_fn, STEEL, placed(0, lid_base, hz + 0.03), yaw) + + def loop_fn(q): + d2 = sd_round_rect(q[..., [0, 1]], hw, hh, corner) + loop = np.sqrt(d2 * d2 + q[..., 2] ** 2) - tube + return np.maximum(loop, -q[..., 1] - 0.02) + + handle_y = ridge + 0.03 + loop = Shape(loop_fn, STEEL, (0, handle_y, 0), yaw) + grip = Shape( + lambda q: sd_capsule(q, (-hw * 0.55, hh, 0), (hw * 0.55, hh, 0), tube * 1.9), + RUBBER, + (0, handle_y, 0), + yaw, + ) + return [tray, lid, plates, latches, loop, grip] + + +# ---- marching and shading -------------------------------------------------- + + +def scene_sdf(shapes, p): + ds = np.stack([s.sdf(p) for s in shapes], -1) + return ds.min(-1), ds.argmin(-1) + + +def march(shapes, ro, rd, tmax=20.0, steps=128): + t = np.zeros(ro.shape[:-1]) + hit = np.zeros(t.shape, bool) + idx = np.zeros(t.shape, int) + for _ in range(steps): + d, i = scene_sdf(shapes, ro + rd * t[..., None]) + new = (d < 7e-4) & ~hit + hit |= new + idx = np.where(new, i, idx) + t = np.where(hit, t, np.minimum(t + np.maximum(d, 7e-4) * 0.8, tmax)) + return t, hit, idx + + +def normal(shapes, p, e=6e-4): + return unit( + np.stack( + [ + scene_sdf(shapes, p + np.eye(3)[k] * e)[0] + - scene_sdf(shapes, p - np.eye(3)[k] * e)[0] + for k in range(3) + ], + -1, + ) + ) + + +def soft_shadow(shapes, ro, rd, k=6.0, tmin=0.02, tmax=8.0, steps=48): + res = np.ones(ro.shape[:-1]) + t = np.full(res.shape, tmin) + for _ in range(steps): + d, _ = scene_sdf(shapes, ro + rd * t[..., None]) + res = np.minimum(res, np.clip(k * d / t, 0, 1)) + t = np.minimum(t + np.clip(d, 0.015, 0.25), tmax) + return res + + +def ambient_occlusion(shapes, p, n): + occ, scale = 0.0, 1.0 + for i in range(1, 6): + h = 0.03 + 0.14 * i + d, _ = scene_sdf(shapes, p + n * h) + occ += (h - d) * scale + scale *= 0.75 + return np.clip(1 - 2.2 * occ, 0, 1) + + +# A studio in linear light: a graded sky over a dark floor, and softbox strips +# (direction, long axis, width tightness, length tightness, power). +SKY_TOP, SKY_HORIZON, SKY_FLOOR = ( + np.array([0.8, 0.82, 0.88]), + np.array([0.2, 0.21, 0.24]), + np.array([0.01, 0.01, 0.012]), +) +STRIPS = ( + ((-0.35, 0.75, 0.55), (1, 0, -0.4), 60.0, 4.0, 6.0), # key, upper left front + ((-0.25, 0.85, -0.45), (1, 0, 0.5), 18.0, 2.5, 5.0), # top back, seen in the lid + ((0.75, 0.45, 0.25), (0, 0.3, -1), 90.0, 6.0, 2.5), # right rim + ((0.0, 0.2, 1.0), (1, 0, 0), 25.0, 3.0, 0.8), # soft front fill +) + + +def environment(d, blur=0.0): + y = np.clip(d[..., 1], -1, 1) + up, down = np.clip(y, 0, 1)[..., None], np.clip(-y, 0, 1)[..., None] + out = SKY_HORIZON + (SKY_TOP - SKY_HORIZON) * up**0.7 + (SKY_FLOOR - SKY_HORIZON) * down**0.5 + sharp = 1 - 0.85 * min(blur, 1.0) + for direction, axis, width, span, power in STRIPS: + c = unit(np.array(direction, float)) + a = unit(np.array(axis, float) - np.array(axis, float) @ c * c) + along, across = (d * a).sum(-1), (d * np.cross(c, a)).sum(-1) + facing = np.clip((d * c).sum(-1), 0, 1) + glow = power * facing**2 * np.exp(-(across**2) * width * sharp - along**2 * span * sharp) + out = out + glow[..., None] + return out + + +def shade(shapes): + """Linear RGB and alpha of the scene at SUPERSAMPLE times the output size.""" + w, h = WIDTH * SUPERSAMPLE, HEIGHT * SUPERSAMPLE + ys, xs = np.mgrid[0:h, 0:w] + uv = np.stack([(xs + 0.5 - w / 2) / h, -(ys + 0.5 - h / 2) / h], -1) + cam, look = np.array(CAMERA, float), np.array(LOOK, float) + fwd = unit(look - cam) + right = unit(np.cross(fwd, [0, 1, 0])) + up = np.cross(right, fwd) + focal = 1 / math.tan(math.radians(FOV) / 2) / 2 + rd = unit(uv[..., 0:1] * right + uv[..., 1:2] * up + focal * fwd) + ro = np.broadcast_to(cam, rd.shape) + + t, hit, idx = march(shapes, ro, rd) + p = ro + rd * t[..., None] + n = normal(shapes, p) + key = np.array(KEY_LIGHT, float) + ldir = unit(key - p) + v = -rd + half = unit(ldir + v) + ndl = np.clip((n * ldir).sum(-1), 0, 1) + ndh = np.clip((n * half).sum(-1), 0, 1) + ndv = np.clip((n * v).sum(-1), 1e-3, 1) + falloff = 12.0 / np.maximum(length(key - p) ** 2, 1.0) + shadow = soft_shadow(shapes, p + n * 0.02, ldir) + occlusion = ambient_occlusion(shapes, p, n) + reflected = unit(rd - 2 * (n * rd).sum(-1)[..., None] * n) + wrap = np.clip(((n * ldir).sum(-1) + 0.3) / 1.3, 0, 1) ** 1.5 + hemisphere = environment(n, blur=1.0) * 0.35 + + rgb = np.zeros(p.shape) + for k, shape in enumerate(shapes): + mask = idx == k + if not mask.any(): + continue + m = shape.material + base = np.broadcast_to(m.color, p.shape) + f0 = base if m.metal else np.full_like(base, 0.04) + fresnel = f0 + (1 - f0) * ((1 - ndv) ** 5)[..., None] + a2 = max(m.rough, 0.03) ** 2 + dn = ndh * ndh * (a2 - 1) + 1 + ggx = a2 / (math.pi * dn * dn) + specular = (ggx * ndl * shadow * falloff)[..., None] * fresnel * 0.9 + mirror = environment(reflected, blur=m.rough * 1.5) * fresnel * occlusion[..., None] + diffuse = base * ( + (wrap * shadow * KEY_POWER * falloff)[..., None] * np.array([1.0, 0.96, 0.9]) / math.pi + + hemisphere * (occlusion * occlusion)[..., None] + ) + if m.metal: + color = mirror * m.tint + specular * base * KEY_POWER / 3 + else: + color = diffuse * (1 - fresnel) + mirror * m.coat + specular * KEY_POWER / 3 + rgb = np.where(mask[..., None], color, rgb) + + # The contact shadow on the invisible floor. + gt = -ro[..., 1] / np.where(np.abs(rd[..., 1]) < 1e-6, 1e-6, rd[..., 1]) + gp = ro + rd * gt[..., None] + ground_shadow = soft_shadow(shapes, gp + np.array([0, 0.02, 0]), unit(key - gp), k=3.0) + gd, _ = scene_sdf(shapes, gp) + contact = np.clip(1 - gd / 0.4, 0, 1) ** 2 + floor = np.clip(0.5 * (1 - ground_shadow) * contact**0.5 + 0.6 * contact**1.5, 0, 1) * SHADOW + alpha = np.where(hit, 1.0, np.where(gt > 0, floor, 0)) + return rgb, hit, alpha + + +def to_png(rgb, hit, alpha): + """Tone-map, encode as sRGB, box-filter down to the output size, and pack a PNG.""" + x = np.clip(rgb, 0, None) + x = (x * (2.51 * x + 0.03)) / (x * (2.43 * x + 0.59) + 0.14) + x = np.clip(x, 0, 1) + srgb = np.where(x <= 0.0031308, x * 12.92, 1.055 * x ** (1 / 2.4) - 0.055) + color = np.where(hit[..., None], srgb, 0.0) + premultiplied = np.concatenate([color * alpha[..., None], alpha[..., None]], -1) + small = premultiplied.reshape(HEIGHT, SUPERSAMPLE, WIDTH, SUPERSAMPLE, 4).mean((1, 3)) + a = small[..., 3:4] + straight = np.where(a > 1e-4, small[..., :3] / np.maximum(a, 1e-4), 0) + rgba = (np.clip(np.concatenate([straight, a], -1), 0, 1) * 255 + 0.5).astype(np.uint8) + raw = b"".join(b"\x00" + rgba[y].tobytes() for y in range(HEIGHT)) + + def chunk(kind, data): + return ( + struct.pack(">I", len(data)) + + kind + + data + + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF) + ) + + return ( + b"\x89PNG\r\n\x1a\n" + + chunk(b"IHDR", struct.pack(">IIBBBBB", WIDTH, HEIGHT, 8, 6, 0, 0, 0)) + + chunk(b"IDAT", zlib.compress(raw, 9)) + + chunk(b"IEND", b"") + ) + + +def render(): + return to_png(*shade(toolbox())) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument( + "--check", + action="store_true", + help="render in memory and compare with the committed file", + ) + args = parser.parse_args() + png = render() + if not args.check: + OUT.write_bytes(png) + return + if OUT.read_bytes() != png: + sys.exit(f"render.py: {OUT.name} differs from a fresh render") + print(f"{OUT.name} matches") + + +if __name__ == "__main__": + main() diff --git a/extensions/homebrew/assets/settings-homebrew.png b/extensions/homebrew/assets/settings-homebrew.png new file mode 100644 index 0000000..2b816b1 Binary files /dev/null and b/extensions/homebrew/assets/settings-homebrew.png differ diff --git a/extensions/homebrew/assets/settings-homebrew.svg b/extensions/homebrew/assets/settings-homebrew.svg new file mode 100644 index 0000000..9f87f69 --- /dev/null +++ b/extensions/homebrew/assets/settings-homebrew.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/extensions/homebrew/listing.toml b/extensions/homebrew/listing.toml new file mode 100644 index 0000000..ad16d03 --- /dev/null +++ b/extensions/homebrew/listing.toml @@ -0,0 +1,15 @@ +details = "In disk mode, copy a package folder to /Reprise/Games// or /Reprise/Apps//. Games appear in Extras > Games beside the stock ones; Apps gets its own row under Extras. Manifests in those two folders skip Apple's signature check; games under iPod_Control keep it." + +icon = "assets/settings-homebrew.png" + +[[screenshots]] +file = "screenshots/apps-row.png" +alt = "Extras with the Apps row selected and its picture in the pane." + +[[screenshots]] +file = "screenshots/apps.png" +alt = "The Apps list with a homebrew app." + +[[screenshots]] +file = "screenshots/games.png" +alt = "Extras > Games listing a homebrew game beside the stock games." diff --git a/extensions/homebrew/main.c b/extensions/homebrew/main.c new file mode 100644 index 0000000..5592c82 --- /dev/null +++ b/extensions/homebrew/main.c @@ -0,0 +1,466 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* Packages under /Reprise/Games/ and /Reprise/Apps/ in Apple's Games list. The + * games service builds its one list once, so the build entry clears it whenever + * what it holds is not what is wanted (games, or apps while the Apps screen is + * open) and Apple scans again before a screen draws it; Apps scans before its + * screen is pushed. Opening Apps sets a built games list aside instead and + * closing it puts the list back, so Games is not scanned again for a visit to + * Apps. The manifest reader is handed no signature path for a package, which is + * how Apple itself reads a manifest it does not verify. + * + * Adapted from RepriseOS payload/homebrew.c (fd5d367) by lgreitis. */ + +#include + +#include "osos-2.0.5.h" +#include "rv_api.h" +#include "rv_libc.h" +#include "rv_menus.h" +#include "rv_sites.h" +#include "rv_ui.h" + +#define PATH_BYTES 258 /* the text of Apple's legacy path, as the core's file layer */ + +static const struct rv_api *api; +static rv_extension_handle self; + +/* A root as the games service scans it, as the manifest's content folder, and + * where the packages under it keep their data: one folder under `data` for each + * of Apple's UserData, Stats and SharedData, named as on Apple's disk for games + * and with app in place of game for apps. */ +struct root { + const char *path; + const char *content; + const char *data; + const char *user_data, *stats, *shared_data; +}; +static const struct root games_root = {"/Reprise/Games/", "Games", "/Reprise/Data/Games/", + "gamedata_RW/", "gamestats_WO/", "gamedata_ShareRW/"}; +static const struct root apps_root = {"/Reprise/Apps/", "Apps", "/Reprise/Data/Apps/", + "appdata_RW/", "appstats_WO/", "appdata_ShareRW/"}; + +/* The root the last scan listed and its ids, NUL separated, ending in an empty + * name; what GameFiles_BuildPath redirects. */ +static const struct root *listed_root; +static char *listed_ids; + +/* What the list is wanted as, and what it holds: games, or apps while the Apps + * screen is open. A list built before the extension loaded is dropped at the + * first build after, so it is scanned again with the hooks in place. */ +enum listing { GAMES, APPS }; +static enum listing wanted, built; +static int fresh = 1; +/* The games service, from its first list build through the hooks; NULL until then. */ +static void *service; +/* The games list set aside while the Apps screen is open: the words of Apple's + * list that hold its entries, and its ids. Every reader of the list indexes it + * afresh, so exchanging these words swaps the whole list. */ +static const uint32_t list_words[] = {GameList_count, GameList_storage, GameList_capacity}; +static uint32_t kept_words[RV_COUNT(list_words)]; +static char *kept_ids; +static int kept; +/* The apps scans since the games list was kept. */ +static unsigned apps_scans; +/* The packages under /Reprise/Apps/, counted again whenever a list build reads + * the disk anyway, so the Extras pane does not; -1 until first counted. */ +static int apps_count = -1; + +/* 1 for the `n` bytes of a folder name that is one package id: not empty, not + * starting with a dot, no path or drive separator. */ +static int is_package_id(const char *name, unsigned n) +{ + if (!n || name[0] == '.') + return 0; + for (unsigned i = 0; i < n; i++) + if (name[i] == '/' || name[i] == '\\' || name[i] == ':') + return 0; + return 1; +} + +/* 1 for root + id + "/Manifest.plist" under one of the roots. */ +static int is_homebrew_manifest(const char *path) +{ + const struct root *const roots[] = {&games_root, &apps_root}; + + if (!path) + return 0; + for (unsigned r = 0; r < RV_COUNT(roots); r++) { + unsigned n = strlen(roots[r]->path); + if (memcmp(path, roots[r]->path, n) != 0) + continue; + const char *id = path + n, *end = id; + while (*end && *end != '/') + end++; + return is_package_id(id, end - id) && strcmp(end, "/Manifest.plist") == 0; + } + return 0; +} + +static uint32_t on_manifest_reader(void *reader, const char *manifest, uint32_t volume, + const char *signature, const void *next) +{ + if (volume == FileVolume_Disk && is_homebrew_manifest(manifest)) + signature = 0; + return api->hook_next(next, (uint32_t)reader, (uint32_t)manifest, volume, + (uint32_t)signature, 0, 0); +} + +struct folders { + uint32_t bytes; + int ids; + char *out; +}; + +static void count_folder(const char *name, int is_folder, void *arg) +{ + struct folders *f = arg; + if (is_folder && is_package_id(name, strlen(name))) { + f->bytes += strlen(name) + 1; + f->ids++; + } +} + +static void copy_folder(const char *name, int is_folder, void *arg) +{ + struct folders *f = arg; + if (!is_folder || !is_package_id(name, strlen(name))) + return; + unsigned n = strlen(name) + 1; + memcpy(f->out, name, n); + f->out += n; +} + +static void count_package(const char *name, int is_folder, void *arg) +{ + if (is_folder && is_package_id(name, strlen(name))) + ++*(int *)arg; +} + +/* A pane that showed another count of /Reprise/Apps/ reads it again. */ +static void set_apps_count(int count) +{ + int shown = apps_count; + apps_count = count; + if (shown >= 0 && count != shown) + api->ui_pane_refresh(self); +} + +static void count_apps(void) +{ + int count = 0; + api->content_list(self, apps_root.content, count_package, &count); + set_apps_count(count); +} + +/* Remembers the ids under `root`, then lets Apple scan it. Without memory for + * the ids the root is not scanned, but the list still counts as built from it. */ +static void scan_root(void *games, void *list, const struct root *root) +{ + struct folders f = {1, 0, NULL}; + api->content_list(self, root->content, count_folder, &f); + if (root == &apps_root) + set_apps_count(f.ids); + char *ids = api->alloc(self, f.bytes); + if (listed_ids) + api->free(self, listed_ids); + listed_ids = ids; + listed_root = root; + if (!ids) + return; + f.out = ids; + api->content_list(self, root->content, copy_folder, &f); + *f.out = 0; + GamesService_ScanRoot(games, list, FileVolume_Disk, root->path); +} + +static uint32_t on_build_list(void *games, const void *next) +{ + service = games; + if (fresh || built != wanted) { + GamesService_ClearList(games); + built = wanted; + fresh = 0; + } + return api->hook_next(next, (uint32_t)games, 0, 0, 0, 0, 0); +} + +static uint32_t on_scan_built_in_root(void *games, void *list, uint32_t volume, + const char *root, const void *next) +{ + if (wanted == APPS) + return 0; + return api->hook_next(next, (uint32_t)games, (uint32_t)list, volume, (uint32_t)root, 0, 0); +} + +static uint32_t on_scan_disk_root(void *games, void *list, uint32_t volume, const char *root, + const void *next) +{ + if (wanted == APPS) { + apps_scans++; + scan_root(games, list, &apps_root); + return 0; + } + uint32_t result = + api->hook_next(next, (uint32_t)games, (uint32_t)list, volume, (uint32_t)root, 0, 0); + scan_root(games, list, &games_root); + count_apps(); + return result; +} + +static int listed(const char *id) +{ + if (!listed_ids) + return 0; + for (const char *name = listed_ids; *name; name += strlen(name) + 1) + if (strcmp(name, id) == 0) + return 1; + return 0; +} + +/* The folder under the listed root's data folder for UserData, Stats or + * SharedData. */ +static const char *data_folder(uint32_t kind) +{ + switch (kind) { + case GameDirectory_UserData: + return listed_root->user_data; + case GameDirectory_Stats: + return listed_root->stats; + default: + return listed_root->shared_data; + } +} + +/* Appends `text` at `*at`, leaving room for the NUL before `end`; 0 when it + * does not fit. */ +static int append(char **at, char *end, const char *text) +{ + unsigned n = strlen(text); + if (n >= (unsigned)(end - *at)) + return 0; + memcpy(*at, text, n); + *at += n; + return 1; +} + +/* A listed id's package is / and its data /, the + * shared folder without the id as on Apple's disk; Apple's games and a path + * that does not fit stay Apple's. */ +static uint32_t on_build_path(struct NativeString *out, uint32_t kind, struct NativeString *id, + uint32_t storage, const void *next, const char *leaf) +{ + const char *name = id ? NativeString_GetUtf8(id) : NULL; + char path[PATH_BYTES], *at = path, *end = path + sizeof path; + int fits = 0; + if (leaf && *leaf == '/') + leaf++; + if (kind <= GameDirectory_SharedData && storage == GameStorage_Disk && name && + listed(name)) { + if (kind == GameDirectory_Package) + fits = append(&at, end, listed_root->path) && append(&at, end, name) && + append(&at, end, "/"); + else + fits = append(&at, end, listed_root->data) && + append(&at, end, data_folder(kind)) && + (kind == GameDirectory_SharedData || + (append(&at, end, name) && append(&at, end, "/"))); + } + if (fits && append(&at, end, leaf ? leaf : "")) { + *at = 0; + NativeString_InitUtf8(out, path); + return 0; + } + return api->hook_next(next, (uint32_t)out, kind, (uint32_t)id, storage, (uint32_t)leaf, 0); +} + +/* The caption of a row while the list is apps: Apple's words for the play count + * with Opened in place of Played, the last still formatted by Apple. */ +static uint32_t on_played_string(void *resources, uint32_t id, const void *next) +{ + if (wanted == APPS) { + if (id == RES_GamesMenu_NeverPlayed_String) + return (uint32_t)"Never Opened"; + if (id == RES_GamesMenu_PlayedOnce_String) + return (uint32_t)"Opened Once"; + if (id == RES_GamesMenu_PlayedTimes_String) + return (uint32_t)"Opened %d Times"; + } + return api->hook_next(next, (uint32_t)resources, id, 0, 0, 0, 0); +} + +/* Apple keeps loaded row icons by artwork id, row + 1, across screens, so the + * rows of the apps list take Apple's id plus APPS_ARTWORK_BASE and Games and + * Apps never show each other's icons. */ +#define APPS_ARTWORK_BASE 0x10000 + +static uint32_t on_artwork_id(void *games, uint32_t row, uint32_t *out_id, const void *next) +{ + uint32_t found = api->hook_next(next, (uint32_t)games, row, (uint32_t)out_id, 0, 0, 0); + if (found && listed_root == &apps_root) + *out_id += APPS_ARTWORK_BASE; + return found; +} + +/* Apple's artwork id, row + 1, for an artwork id of the list held; 0 for an id + * of the other list. */ +static uint32_t apple_artwork_id(uint32_t id) +{ + if (listed_root != &apps_root) + return id < APPS_ARTWORK_BASE ? id : 0; + return id > APPS_ARTWORK_BASE ? id - APPS_ARTWORK_BASE : 0; +} + +static uint32_t on_artwork_path(void *games, uint32_t id, void *out, const void *next) +{ + id = apple_artwork_id(id); + if (!id) + return 0; + return api->hook_next(next, (uint32_t)games, id, (uint32_t)out, 0, 0, 0); +} + +static uint32_t on_artwork_storage(void *games, uint32_t id, const void *next) +{ + id = apple_artwork_id(id); + if (!id) + return 0; + return api->hook_next(next, (uint32_t)games, id, 0, 0, 0, 0); +} + +/* Empties Apple's list, which frees its entries, and forgets their ids. */ +static void clear_list(void) +{ + GamesService_ClearList(service); + if (listed_ids) + api->free(self, listed_ids); + listed_ids = NULL; +} + +/* Exchanges the entries of Apple's list with the kept ones, ids included. */ +static void swap_list(void) +{ + for (unsigned i = 0; i < RV_COUNT(list_words); i++) { + uint32_t *word = &RV_FIELD(service, GamesService_list + list_words[i], uint32_t); + uint32_t held = *word; + *word = kept_words[i]; + kept_words[i] = held; + } + char *ids = listed_ids; + listed_ids = kept_ids; + kept_ids = ids; +} + +/* Ends the keeping: Apple's clear frees the entries of the list it holds, the + * apps, and the games come back; `restore` keeps them as built, otherwise they + * are freed too and Games is scanned again. */ +static void end_keeping(int restore) +{ + clear_list(); + swap_list(); + memset(kept_words, 0, sizeof kept_words); + listed_root = &games_root; + kept = 0; + if (restore) { + RV_FIELD(service, GamesService_list_built, uint32_t) = 1; + built = GAMES; + return; + } + clear_list(); +} + +/* Back to games once the Apps screen closed: the kept games list returns when + * the apps were scanned once and are still listed. Anything else means Apple + * cleared the list, as it does when disk mode ends; the kept list is out of date + * then and goes. */ +static void apps_closed(const struct rv_context *ctx) +{ + (void)ctx; + wanted = GAMES; + if (kept) + end_keeping(apps_scans == 1 && RV_FIELD(service, GamesService_list_built, uint32_t)); +} + +/* The Apps row: the list is wanted as apps from before the push until the + * screen closes. A games list built through the hooks is set aside for an empty + * one (the kept words start zero), so Games is not scanned again after Apps. + * The apps are scanned before the push: the screen starts Apple's artwork + * session as it activates, before its first count, and the session loads the + * icons of as many rows as the list holds then. */ +static void open_apps(const struct rv_context *ctx) +{ + if (service && !fresh && built == GAMES && + RV_FIELD(service, GamesService_list_built, uint32_t)) { + swap_list(); + listed_root = &apps_root; + RV_FIELD(service, GamesService_list_built, uint32_t) = 0; + built = APPS; + apps_scans = 0; + kept = 1; + } + wanted = APPS; + GamesService_BuildList(GamesService_Get()); + if (api->ui_push(ctx->self, "apps", NULL) == RV_OK) + return; + wanted = GAMES; + if (kept) + end_keeping(1); /* the kept games list is still as built */ +} + +/* The Extras pane beside the Apps row: how many packages the folder holds. */ +static const char *apps_caption(const struct rv_context *ctx) +{ + static char caption[16]; + (void)ctx; + if (apps_count < 0) + count_apps(); + rv_format_int(caption, sizeof caption, apps_count, apps_count == 1 ? " App" : " Apps"); + return caption; +} + +/* Apple builds the list once, so what it holds follows the hooks that were bound + * when it was built: dropped here so Apple builds it again on demand without + * them. A list never built through the hooks holds nothing of ours. */ +static void unload(void) +{ + if (kept) + end_keeping(0); + else if (service) + clear_list(); +} + +static const struct rv_hook hooks[] = { + RV_HOOK_FILTER(RV_SITE_GameManifest_InitReader_call, on_manifest_reader), + RV_HOOK_FILTER(RV_SITE_GamesService_BuildList_entry, on_build_list), + RV_HOOK_FILTER(RV_SITE_GamesService_ScanBuiltInRoot_call, on_scan_built_in_root), + RV_HOOK_FILTER(RV_SITE_GamesService_ScanDiskRoot_call, on_scan_disk_root), + RV_HOOK_FILTER(RV_SITE_GameFiles_BuildPath_entry, on_build_path), + RV_HOOK_FILTER(RV_SITE_GamesService_PlayedString_call, on_played_string), + RV_HOOK_FILTER(RV_SITE_GamesService_PlayedTimesString_call, on_played_string), + RV_HOOK_FILTER(RV_SITE_GamesService_GetArtworkId_entry, on_artwork_id), + RV_HOOK_FILTER(RV_SITE_GamesService_GetArtworkPath_entry, on_artwork_path), + RV_HOOK_FILTER(RV_SITE_GamesService_GetArtworkStorage_entry, on_artwork_storage), +}; + +static const struct rv_screen screens[] = { + RV_SCREEN_STOCK("apps", "Apps", RV_STOCK_SCREEN_GAMES, .closed = apps_closed), +}; + +static const struct rv_menu_entry entries[] = { + RV_MENU_ENTRY(RV_MENU_EXTRAS, RV_EXTRAS_GAMES, RV_ROW_ACTION("Apps", open_apps), + .pane = RV_PANE(.caption_text = apps_caption, .bitmap = RV_BITMAP("apps"))), +}; + +static const struct rv_descriptor extension = { + .size = sizeof extension, + RV_HOOKS(hooks), + RV_SCREENS(screens), + RV_ENTRIES(entries), + .unload = unload, +}; + +const struct rv_descriptor *rv_module_entry(const struct rv_api *core, rv_extension_handle handle) +{ + api = core; + self = handle; + return &extension; +} diff --git a/extensions/homebrew/manifest.toml b/extensions/homebrew/manifest.toml new file mode 100644 index 0000000..65c45e2 --- /dev/null +++ b/extensions/homebrew/manifest.toml @@ -0,0 +1,19 @@ +id = "homebrew" +name = "Homebrew" +description = "Apps and games from /Reprise/Apps and /Reprise/Games under Extras, started without an Apple signature." +version = "0.1.0" +author = "RepriseOS contributors" +license = "GPL-3.0-only" +api = "1.89" +stability = "beta" +category = "system" +content = ["Games", "Apps"] + +[[module]] +name = "main" +trigger = "always" + +[[asset]] +name = "apps" +file = "assets/apps.png" +pane = "picture" diff --git a/extensions/homebrew/screenshots/apps-row.png b/extensions/homebrew/screenshots/apps-row.png new file mode 100644 index 0000000..2e7e959 Binary files /dev/null and b/extensions/homebrew/screenshots/apps-row.png differ diff --git a/extensions/homebrew/screenshots/apps.png b/extensions/homebrew/screenshots/apps.png new file mode 100644 index 0000000..356d6e1 Binary files /dev/null and b/extensions/homebrew/screenshots/apps.png differ diff --git a/extensions/homebrew/screenshots/games.png b/extensions/homebrew/screenshots/games.png new file mode 100644 index 0000000..ca57d85 Binary files /dev/null and b/extensions/homebrew/screenshots/games.png differ diff --git a/extensions/iap-auth-bypass/Makefile b/extensions/iap-auth-bypass/Makefile new file mode 100644 index 0000000..cb973a7 --- /dev/null +++ b/extensions/iap-auth-bypass/Makefile @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: GPL-3.0-only +main_SOURCES := main.c +include $(SDK)/rv.mk diff --git a/extensions/iap-auth-bypass/README.md b/extensions/iap-auth-bypass/README.md new file mode 100644 index 0000000..cc65173 --- /dev/null +++ b/extensions/iap-auth-bypass/README.md @@ -0,0 +1,15 @@ +# iAP Auth Bypass + +Based on the RepriseOS core's [iAP auth bypass](https://github.com/RepriseOS/repriseos/blob/b9b1c62/payload/iap_auth.c), by RaduTek. + +Lets accessories use authentication-gated iPod Accessory Protocol (iAP) lingos and commands without an Apple authentication coprocessor. Both signature verifiers report success, but accessories must still answer the certificate and signature requests of the handshake. + +Disabling it restores signature verification for later handshakes; accessories already authenticated stay connected. + +The handshake, the verification gate and the hook calling conventions are in the [iAP reversing notes](https://github.com/RepriseOS/repriseos/blob/b9b1c62/docs/iap-auth.md). + +| | | +|---|---| +| Default | off | +| Memory | image only | +| Settings | none | diff --git a/extensions/iap-auth-bypass/assets/LICENSE.cupertino-icons b/extensions/iap-auth-bypass/assets/LICENSE.cupertino-icons new file mode 100644 index 0000000..581f84c --- /dev/null +++ b/extensions/iap-auth-bypass/assets/LICENSE.cupertino-icons @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2016 Vladimir Kharlampidi + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/extensions/iap-auth-bypass/assets/settings-iap-auth-bypass.png b/extensions/iap-auth-bypass/assets/settings-iap-auth-bypass.png new file mode 100644 index 0000000..2713d8f Binary files /dev/null and b/extensions/iap-auth-bypass/assets/settings-iap-auth-bypass.png differ diff --git a/extensions/iap-auth-bypass/assets/settings-iap-auth-bypass.svg b/extensions/iap-auth-bypass/assets/settings-iap-auth-bypass.svg new file mode 100644 index 0000000..700982c --- /dev/null +++ b/extensions/iap-auth-bypass/assets/settings-iap-auth-bypass.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/extensions/iap-auth-bypass/listing.toml b/extensions/iap-auth-bypass/listing.toml new file mode 100644 index 0000000..fcc3d45 --- /dev/null +++ b/extensions/iap-auth-bypass/listing.toml @@ -0,0 +1,3 @@ +details = "Enable the extension and connect an accessory without an Apple authentication chip; its authentication-gated iAP commands then work. Nothing is added to the menus." + +icon = "assets/settings-iap-auth-bypass.png" diff --git a/extensions/iap-auth-bypass/main.c b/extensions/iap-auth-bypass/main.c new file mode 100644 index 0000000..fa79cb9 --- /dev/null +++ b/extensions/iap-auth-bypass/main.c @@ -0,0 +1,50 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* Both accessory signature verifiers return zero on success. The General Lingo + * 0x18 handler then acknowledges success and marks the accessory authenticated. + * + * Adapted from RepriseOS payload/iap_auth.c (c99dc33) by RaduTek. */ + +#include "rv_api.h" +#include "rv_sites.h" +#include "rv_ui.h" + +static uint32_t verify_rsa(void *manager, uint32_t channel, uint32_t key_id, + void *signature, const void *next, uint32_t signature_bytes) +{ + (void)manager; + (void)channel; + (void)key_id; + (void)signature; + (void)next; + (void)signature_bytes; + return 0; +} + +static uint32_t verify_alternate(void *authentication, void *signature, + uint32_t signature_bytes, const void *next) +{ + (void)authentication; + (void)signature; + (void)signature_bytes; + (void)next; + return 0; +} + +static const struct rv_hook hooks[] = { + RV_HOOK_REPLACE(RV_SITE_IAP_VerifyDeviceSignatureRSA_call, verify_rsa), + RV_HOOK_REPLACE(RV_SITE_IAP_VerifyDeviceSignatureAlternate_call, verify_alternate), +}; + +static const struct rv_descriptor extension = { + .size = sizeof extension, + RV_HOOKS(hooks), +}; + +const struct rv_descriptor *rv_module_entry(const struct rv_api *core, + rv_extension_handle handle) +{ + (void)core; + (void)handle; + return &extension; +} diff --git a/extensions/iap-auth-bypass/manifest.toml b/extensions/iap-auth-bypass/manifest.toml new file mode 100644 index 0000000..7c5f399 --- /dev/null +++ b/extensions/iap-auth-bypass/manifest.toml @@ -0,0 +1,13 @@ +id = "iap-auth-bypass" +name = "iAP Auth Bypass" +description = "Let accessories use authentication-gated iAP commands without an Apple authentication chip." +version = "0.1.0" +author = "RepriseOS contributors" +license = "GPL-3.0-only" +api = "1.89" +stability = "beta" +category = "system" + +[[module]] +name = "main" +trigger = "always" diff --git a/extensions/night-shift/Makefile b/extensions/night-shift/Makefile index 246d199..9be7f51 100644 --- a/extensions/night-shift/Makefile +++ b/extensions/night-shift/Makefile @@ -1,3 +1,4 @@ # SPDX-License-Identifier: GPL-3.0-only -main_SOURCES := main.c night_shift.c schedule.c sun.c +main_SOURCES := main.c night_shift.c ../shared/schedule.c ../shared/sun.c +EXTRA_CFLAGS := -I../shared include $(SDK)/rv.mk diff --git a/extensions/night-shift/listing.toml b/extensions/night-shift/listing.toml index f04edb1..bff6573 100644 --- a/extensions/night-shift/listing.toml +++ b/extensions/night-shift/listing.toml @@ -1,4 +1,4 @@ -details = "Press Select on Night Shift in Settings to cycle through Auto, On and Off. Auto follows sunset and sunrise in the iPod’s time zone." +details = "Night Shift in Settings opens a choice of Auto, On and Off; while the Appearance extension runs the row sits in its menu after Dark Mode. Auto follows sunset and sunrise in the iPod’s time zone." [[screenshots]] file = "screenshots/settings.png" diff --git a/extensions/night-shift/main.c b/extensions/night-shift/main.c index 9e8ca82..d33fa3c 100644 --- a/extensions/night-shift/main.c +++ b/extensions/night-shift/main.c @@ -1,79 +1,117 @@ /* SPDX-License-Identifier: GPL-3.0-only */ + +/* Night Shift: a Settings row, Auto, On or Off, in the Appearance menu after + * Dark Mode while that extension runs, after Brightness otherwise. While it is + * on Auto a minute timer reads the schedule and the warmth follows it. */ + #include "../shared/legacy.h" #include "ext.h" #include "night_shift.h" -#include "schedule.h" +#include "rv_api.h" #include "rv_menus.h" #include "rv_sites.h" #include "rv_ui.h" +#include "schedule.h" +#include const struct rv_api *api; rv_extension_handle self; enum { MODE = 1 }; -static struct rv_timer *timer; -static int has_zone; -static void tick(void *unused) +static const struct rv_setting settings[] = { + RV_SETTING_CHOICE(MODE, "Night Shift", NIGHT_SHIFT_OFF, night_shift_labels), +}; + +static struct rv_timer *timer; /* the minute tick while on Auto */ +static int zone_known; +static int first_load = 1; + +static void tick(void *arg) { - (void)unused; + (void)arg; struct schedule s; schedule_read(&s); night_shift_follow(&s); - int known = s.state != SCHEDULE_NO_ZONE; - if (known != has_zone) { - has_zone = known; + if (zone_known != (s.state != SCHEDULE_NO_ZONE)) { + zone_known = !zone_known; api->ui_pane_refresh(self); } } -static int first_load = 1; +/* The minute timer while on Auto. At load the extension runs inside Apple's + * preferences load, before the browser holds the preferences object that + * names the time zone: a read that finds no zone is tried again from the + * event loop a second later, so the first screen already follows Auto. */ +static void watch(int on) +{ + struct schedule s; + if (on && !timer) { + timer = api->timer_start(self, 60 * 1000, 1, tick, NULL); + schedule_read(&s); + zone_known = s.state != SCHEDULE_NO_ZONE; + if (!zone_known) + api->timer_start(self, 1000, 0, tick, NULL); + } + if (!on) + rv_timer_cancel(api, self, &timer); +} -static void changed(uint16_t key) +static void setting_changed(uint16_t key) { if (key == RV_SETTING_KEY_ALL) { int import = first_load; first_load = 0; migrate_switch(api, self, import, MODE, 0x5448474e, 0x31544e53, NIGHT_SHIFT_ON, NIGHT_SHIFT_OFF, RV_SETTING_TYPE_INT); + } else if (key != MODE) { + return; } int mode = api->setting_get_int(self, MODE); night_shift_set(mode); - if (mode != NIGHT_SHIFT_AUTO) { - rv_timer_cancel(api, self, &timer); - } else if (!timer) { - timer = api->timer_start(self, 60000, 1, tick, NULL); - /* The time zone service can become available after preferences load. */ - api->timer_start(self, 1000, 0, tick, NULL); - } + watch(mode == NIGHT_SHIFT_AUTO); } -static const char *caption(const struct rv_context *ctx) +static const char *pane_caption(const struct rv_context *ctx) { (void)ctx; return night_shift_caption(); } -static const struct rv_setting settings[] = { - RV_SETTING_LABELLED(MODE, "Night Shift", NIGHT_SHIFT_OFF, night_shift_labels), -}; -static const struct rv_menu_entry entries[] = { - RV_MENU_ENTRY(RV_MENU_SETTINGS, RV_SETTINGS_BRIGHTNESS, - RV_ROW_SETTING("Night Shift", MODE), .caption_setting = MODE, - .pane = RV_PANE(.caption_text = caption, - .bitmap = RV_BITMAP("settings-night-shift"))), -}; static const struct rv_hook hooks[] = { RV_HOOK_FILTER(RV_SITE_DisplayPipe_Init_SetGammaTables_call, night_shift_init_gamma), }; + +/* Declared for its pane icon; the screen the core makes from the setting has none. */ +static const struct rv_screen screens[] = { + RV_SCREEN_CHOICE("night-shift", "Night Shift", MODE, night_shift_labels, + .bitmap = RV_BITMAP("settings-night-shift")), +}; + +static const struct rv_menu_entry entries[] = { + RV_MENU_ENTRY( + RV_MENU_SETTINGS, RV_SETTINGS_BRIGHTNESS, RV_ROW_SETTING("Night Shift", MODE), + .pane = RV_PANE(.caption_text = pane_caption, + .bitmap = RV_BITMAP("settings-night-shift")), + .host = "appearance", .host_screen = "appearance", .host_after = "dark-mode"), +}; + +/* The core stops the timer itself as the module unloads. */ +static void unload(void) +{ + timer = NULL; + night_shift_stop(); +} + static const struct rv_descriptor extension = { .size = sizeof extension, + RV_HOOKS(hooks), RV_SETTINGS(settings), + .unload = unload, + .setting_changed = setting_changed, + RV_SCREENS(screens), RV_ENTRIES(entries), - RV_HOOKS(hooks), - .setting_changed = changed, - .unload = night_shift_stop, }; const struct rv_descriptor *rv_module_entry(const struct rv_api *core, diff --git a/extensions/night-shift/manifest.toml b/extensions/night-shift/manifest.toml index fd37372..938f7d6 100644 --- a/extensions/night-shift/manifest.toml +++ b/extensions/night-shift/manifest.toml @@ -1,12 +1,15 @@ id = "night-shift" name = "Night Shift" description = "Warm the display manually or follow sunset and sunrise in the iPod's time zone." -version = "0.1.2" +version = "0.1.4" author = "RepriseOS and RevolaOS contributors" license = "GPL-3.0-only" -api = "1.81" +api = "1.89" category = "system" +[libraries] +optional = ["reprise"] + [[module]] name = "main" trigger = "always" diff --git a/extensions/night-shift/test.c b/extensions/night-shift/test.c index 1f0b6d9..c21ef1c 100644 --- a/extensions/night-shift/test.c +++ b/extensions/night-shift/test.c @@ -41,8 +41,8 @@ static uint8_t host_preferences[PreferencesFile_time_zone_id + 4]; static uint8_t host_browser[MediaBrowser_preferences + sizeof(void *)]; static uint8_t host_app[App_browser + sizeof(void *)]; void *App = host_app; -#include "sun.c" -#include "schedule.c" +#include "../shared/sun.c" +#include "../shared/schedule.c" #include "night_shift.c" static int allocations; @@ -146,7 +146,7 @@ static void night_shift_contracts(void) /* Auto without a known zone stays neutral and says so. */ night_shift_set(NIGHT_SHIFT_AUTO); assert(gamma_loads == loads + 2); - assert(!strcmp(night_shift_caption(), "Set a time zone")); + assert(!strcmp(night_shift_caption(), "Set a Time Zone")); /* Berlin, 21 June, 23:00 CEST: an hour and a half after sunset. */ put16(host_zones + 90 * TimeZone_bytes + TimeZone_zone_id, 0x1234); memcpy(host_app + App_browser, &(uint8_t *){host_browser}, sizeof(void *)); @@ -210,7 +210,7 @@ static void schedule_contracts(void) put16(host_preferences + PreferencesFile_time_zone_id, 0x7777); schedule_read(&s); assert(s.state == SCHEDULE_NO_ZONE && !schedule_night(&s)); - assert(!strcmp(schedule_caption(), "Set a time zone")); + assert(!strcmp(schedule_caption(), "Set a Time Zone")); put16(host_preferences + PreferencesFile_time_zone_id, 0x1234); clock_now[DateTime_hour] = 23, clock_now[DateTime_minute] = 0; } diff --git a/extensions/playback-log/README.md b/extensions/playback-log/README.md index d856b77..2d1e3c7 100644 --- a/extensions/playback-log/README.md +++ b/extensions/playback-log/README.md @@ -50,7 +50,8 @@ is left; an unfinished play is lost on an abrupt reset or power loss. | `percent` | `listened_ms` as a percentage of `length_ms`; rewinding can make it exceed 100. | | `ended` | `end` (played to the end), `skip` (next/previous button), `change` (another selection or stop). | | `apple` | `played` or `skipped` when the stock firmware updated that counter, otherwise `none`. | -| `artist`, `album_artist`, `album`, `title` | Tags from the iTunesDB. | +| `artist`, `album`, `title` | Tags from the iTunesDB. | +| `album_artist` | The Album Artist from the Album Artists extension while it runs, when it differs from the artist; otherwise empty. | | `track`, `disc`, `year` | Numbers from the iTunesDB, `0` when missing. | | `genre`, `composer` | Tags from the iTunesDB. | | `bitrate` | Average kbps from the iTunesDB. | diff --git a/extensions/playback-log/main.c b/extensions/playback-log/main.c index 81db894..1bc4aba 100644 --- a/extensions/playback-log/main.c +++ b/extensions/playback-log/main.c @@ -1,4 +1,5 @@ /* SPDX-License-Identifier: GPL-3.0-only */ +#include "../album-artists/service.h" #include "../shared/legacy.h" #include "native.h" #include "playback_log_config.h" @@ -118,8 +119,10 @@ static void field_media_text(struct osos_media_item *item, enum osos_media_text if (field) { osos_media_item_text(item, field, &string); } else { + const struct album_artists_service *albums = + api->extension_service(ALBUM_ARTISTS_ID); uint16_t text[255]; - uint32_t units = api->album_artist_read(item->record, text, 255); + uint32_t units = albums ? albums->read(item->record, text, 255) : 0; osos_native_string_assign_utf16(&string, text, units); } const char *text = osos_native_string_data(&string); @@ -657,8 +660,6 @@ static const struct rv_descriptor extension = { const struct rv_descriptor *rv_module_entry(const struct rv_api *core, rv_extension_handle handle) { - if (!rv_has_reprise_services(core)) - return NULL; api = core; self = handle; load_config(); diff --git a/extensions/playback-log/manifest.toml b/extensions/playback-log/manifest.toml index 73fed35..d1b4915 100644 --- a/extensions/playback-log/manifest.toml +++ b/extensions/playback-log/manifest.toml @@ -1,12 +1,15 @@ id = "playback-log" name = "Playback Log" description = "Write a scrobbler log and optional detailed listening reports." -version = "0.1.1" +version = "0.1.3" author = "RepriseOS contributors" license = "GPL-3.0-only" -api = "1.82" +api = "1.89" category = "media" +[libraries] +optional = ["reprise"] + [[module]] name = "main" trigger = "always" diff --git a/extensions/playback-log/test.c b/extensions/playback-log/test.c index 44b56db..d2b44fa 100644 --- a/extensions/playback-log/test.c +++ b/extensions/playback-log/test.c @@ -138,6 +138,8 @@ static int mock_seek(void *h, uint64_t n, int w) #define osos_file_read mock_read #define osos_file_close(h) ((void)(h)) #define osos_file_seek mock_seek +/* Weak like the optional.h of the build, so the tests against NULL stay. */ +#pragma weak reprise_legacy_preference #include "main.c" enum { FINISH, COMPLETE }; @@ -168,14 +170,20 @@ static int32_t mock_enabled(rv_extension_handle ext, uint16_t key) return 0; } -static uint32_t read_artist(void *r, uint16_t *s, uint32_t n) +uint32_t (reprise_legacy_preference)(uint32_t key, void *data, uint32_t capacity) { - (void)r; - (void)s; - (void)n; + (void)key; + (void)data; + (void)capacity; return 0; } +static const void *mock_service(const char *id) +{ + assert(!strcmp(id, ALBUM_ARTISTS_ID)); + return NULL; +} + static void configure(const char *text) { cfw_log_config_parse(&config, text, (uint32_t)strlen(text)); @@ -194,8 +202,8 @@ int main(void) { static const struct rv_api mock = { .hook_next = mock_next, - .album_artist_read = read_artist, .setting_get_int = mock_enabled, + .extension_service = mock_service, }; api = &mock; load_config(); diff --git a/extensions/playback-queue/Makefile b/extensions/playback-queue/Makefile new file mode 100644 index 0000000..c08c2fc --- /dev/null +++ b/extensions/playback-queue/Makefile @@ -0,0 +1,3 @@ +# SPDX-License-Identifier: GPL-3.0-only +main_SOURCES := main.c queue.c +include $(SDK)/rv.mk diff --git a/extensions/playback-queue/README.md b/extensions/playback-queue/README.md new file mode 100644 index 0000000..adba849 --- /dev/null +++ b/extensions/playback-queue/README.md @@ -0,0 +1,27 @@ +# Playback Queue + +Partly adapted from the RepriseOS core's [Play Next](https://github.com/RepriseOS/repriseos/blob/c997a51/payload/play_next.c) and [queue selection](https://github.com/RepriseOS/repriseos/blob/c997a51/payload/queue_selection.c), by lgreitis and brilliant-alien. The Up Next screen follows the one Alex Ball added in [e501359](https://github.com/RepriseOS/repriseos/commit/e501359). + +Adds Play Next and Play Last to the context menu of a song, album, artist or audio podcast episode, and an Up Next screen. Play Next inserts at the front of the queue, Play Last at the end; albums and artists keep their order. Up Next lists the upcoming items' titles and artists or publishers, without the current item, or "No Upcoming Items". + +| Action | Result | +|---|---| +| Select an item | plays it in Now Playing; it and the items before it leave the queue but stay in the history for Previous | +| Hold Select on an item | move it up or down, send it to the top or bottom, remove it, browse its album and artist, or open File Info; moves that would change nothing are hidden | +| Clear Up Next, from the Up Next or Now Playing context menu | removes every upcoming item after a confirmation; the current item and repeat are kept | + +Browse Album and Browse Artist go through Music as the stock song menus do; a compilation track gets Browse Compilation in their place when the stock menus offer it. File Info shows while the File Info extension runs. + +After a removal the highlight moves to the item above, or stays at the top. Returning to Up Next highlights the first item. The list follows playback. + +Adding items while nothing plays builds the queue without starting playback; Play/Pause starts the first item. Adding items while paused keeps playback paused. Playing a selection from the library replaces the queue. + +Podcast episodes keep Apple's saved position and played status. Video podcasts and whole shows cannot be added. Only a player-owned list of media entries without nested groups can be edited; other lists are left alone. + +Up Next shows in Music and not on the Main Menu by default; Settings > Music Menu and Settings > Main Menu change that. On first start a saved Main Menu checkbox of the Up Next row that earlier RepriseOS releases built in carries over, and Up Next then stays out of Music as it did there. Its code stays loaded while the extension is on. + +| | | +|---|---| +| Default | on | +| Memory | image only | +| Settings | the two menu visibility flags | diff --git a/extensions/playback-queue/assets/LICENSE.cupertino-icons b/extensions/playback-queue/assets/LICENSE.cupertino-icons new file mode 100644 index 0000000..581f84c --- /dev/null +++ b/extensions/playback-queue/assets/LICENSE.cupertino-icons @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2016 Vladimir Kharlampidi + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/extensions/playback-queue/assets/settings-playback-queue.png b/extensions/playback-queue/assets/settings-playback-queue.png new file mode 100644 index 0000000..b5a827f Binary files /dev/null and b/extensions/playback-queue/assets/settings-playback-queue.png differ diff --git a/extensions/playback-queue/assets/settings-playback-queue.svg b/extensions/playback-queue/assets/settings-playback-queue.svg new file mode 100644 index 0000000..0649138 --- /dev/null +++ b/extensions/playback-queue/assets/settings-playback-queue.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/extensions/playback-queue/listing.toml b/extensions/playback-queue/listing.toml new file mode 100644 index 0000000..80b4a62 --- /dev/null +++ b/extensions/playback-queue/listing.toml @@ -0,0 +1,15 @@ +details = "Hold Select on a song, album, artist or podcast episode and choose Play Next or Play Last. Choose Up Next in Music, or from the Now Playing context menu, to reorder, remove or clear the upcoming items." + +icon = "assets/settings-playback-queue.png" + +[[screenshots]] +file = "screenshots/up-next.png" +alt = "Up Next listing the upcoming songs with their artists." + +[[screenshots]] +file = "screenshots/item-menu.png" +alt = "Holding Select on an Up Next item: Move to Top, Move Up, Remove, Browse Compilation, File Info and Clear Up Next." + +[[screenshots]] +file = "screenshots/clear.png" +alt = "The Clear Up Next question with its Clear and Cancel buttons." diff --git a/extensions/playback-queue/main.c b/extensions/playback-queue/main.c new file mode 100644 index 0000000..fb85d4a --- /dev/null +++ b/extensions/playback-queue/main.c @@ -0,0 +1,428 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* Play Next and Play Last in music and audio podcast episode context menus, + * and Up Next: pending items in Music, the Main menu and the + * Now Playing context menu. + * + * The Play Last flag around Add to On-The-Go is adapted from RepriseOS + * payload/queue_selection.c (11e5ba7, c997a51) by brilliant-alien and lgreitis. + * Up Next is based on RepriseOS payload/up_next.c (e501359) by Alex Ball. */ + +#include "queue.h" +#include "../file-info/service.h" +#include "../shared/menu_visibility.h" +#include "osos-2.0.5.h" +#include "rv_api.h" +#include "rv_media.h" +#include "rv_menus.h" +#include "rv_sites.h" +#include "rv_ui.h" +#include + +#define KEY_IN_MUSIC 1 /* Settings > Music Menu and Main Menu flip these two */ +#define KEY_IN_MAIN 2 + +static const struct rv_api *api; +static rv_extension_handle self; + +/* Play Last flag of the Add to On-The-Go in progress, -1 when none is. */ +static int32_t adding = -1; + +/* Album and artist rows reuse Add to On-The-Go: it filters the library to the + * selection and hands it to the On-The-Go playlist here. */ +static uint32_t on_the_go_add(uint32_t otg, uint32_t row, uint32_t browser, + uint32_t save, const void *next) +{ + if (adding < 0) + return api->hook_next(next, otg, row, browser, save, 0, 0); + if ((int32_t)row == -1) + queue_add_browser((void *)browser, adding); + return 1; +} + +static void add_selection(const struct rv_context *ctx, int last) +{ + adding = last; + MediaListController_AddSelectionToOnTheGo(ctx->controller); + adding = -1; +} + +static void song_next(const struct rv_context *ctx) +{ + queue_add_item(ctx->item, 0); +} + +static void song_last(const struct rv_context *ctx) +{ + queue_add_item(ctx->item, 1); +} + +static void selection_next(const struct rv_context *ctx) +{ + add_selection(ctx, 0); +} + +static void selection_last(const struct rv_context *ctx) +{ + add_selection(ctx, 1); +} + +static int available(const struct rv_context *ctx) +{ + (void)ctx; + return queue_available(); +} + +static int can_add(const struct rv_context *ctx) +{ + (void)ctx; + return queue_can_add(); +} + +static int can_add_item(const struct rv_context *ctx) +{ + return queue_can_add_item(ctx->item); +} + +static uint32_t toggle_stopped(uint32_t player, const void *next) +{ + if (queue_start_idle()) + return 1; + return api->hook_next(next, player, 0, 0, 0, 0, 0); +} + +static int upcoming(const struct rv_context *ctx) +{ + (void)ctx; + return queue_rows() != 0; +} + +/* Up Next */ + +static char title[128], artist[128]; +static struct rv_timer *refresh_timer; +static uint32_t queue_views; + +static void refresh_queue(void *arg) +{ + (void)arg; + if (queue_changed()) + api->ui_refresh(self, "queue"); +} + +static void queue_opened(const struct rv_context *ctx) +{ + (void)ctx; + if (queue_views++) + return; + queue_changed(); + refresh_timer = api->timer_start(self, 500, 1, refresh_queue, NULL); +} + +static void queue_closed(const struct rv_context *ctx) +{ + (void)ctx; + if (--queue_views) + return; + rv_timer_cancel(api, self, &refresh_timer); +} + +static uint32_t song_count(const struct rv_context *ctx) +{ + (void)ctx; + return queue_rows(); +} + +static const char *song_row(const struct rv_context *ctx, uint32_t index, + const char **detail) +{ + (void)ctx; + queue_text(index, 0, title, sizeof title); + queue_text(index, 1, artist, sizeof artist); + *detail = artist; + return title; +} + +static uint32_t song_first(const struct rv_context *ctx) +{ + (void)ctx; + return 0; +} + +static int song_select(const struct rv_context *ctx, uint32_t index) +{ + queue_play(index); + void *created = ControllerRegistry_InvokeControllerFactory( + UI_GetControllerRegistry(), "TMediaNowPlayingCntlr", "TMediaNowPlayingCntlr"); + if (created) + rv_controller_push(ctx->controller, created); + api->ui_select(self, "queue", 0); + return 0; +} + +static int can_remove(const struct rv_context *ctx) +{ + return ctx->row >= 0 && queue_capture(ctx->row); +} + +static int can_move_up(const struct rv_context *ctx) +{ + return ctx->row > 0 && can_remove(ctx); +} + +static int can_move_down(const struct rv_context *ctx) +{ + return can_remove(ctx) && (uint32_t)ctx->row + 1 < queue_rows(); +} + +static void move_top(const struct rv_context *ctx) +{ + queue_move(ctx->row, 0); + api->ui_refresh(self, "queue"); +} + +static void move_up(const struct rv_context *ctx) +{ + if (ctx->row > 0) + queue_move(ctx->row, ctx->row - 1); + api->ui_refresh(self, "queue"); +} + +static void move_down(const struct rv_context *ctx) +{ + if (ctx->row >= 0) + queue_move(ctx->row, ctx->row + 1); + api->ui_refresh(self, "queue"); +} + +static void move_bottom(const struct rv_context *ctx) +{ + uint32_t count = queue_rows(); + if (count) + queue_move(ctx->row, count - 1); + api->ui_refresh(self, "queue"); +} + +static void remove_song(const struct rv_context *ctx) +{ + queue_remove(ctx->row); + api->ui_refresh(self, "queue"); + api->ui_select(self, "queue", ctx->row > 0 ? (uint32_t)ctx->row - 1 : 0); +} + +/* Browse Album, Artist and Compilation as the stock song list offers them: + * not for audiobooks, videos, iTunes U or records with flag 8F01, and a + * compilation with preference 0x60bc set gets Browse Compilation in place + * of the other two. The name goes to the navigator as + * the pending selection; the stock menus follow it down from the main + * screen. */ +enum browse { BROWSE_NONE, BROWSE_ALBUM_ARTIST, BROWSE_COMPILATION }; + +static enum browse browse_kind(const struct rv_context *ctx) +{ + void *record = + ctx->row >= 0 && queue_capture(ctx->row) ? queue_record(ctx->row) : NULL; + if (!record) + return BROWSE_NONE; + _Alignas(uint32_t) uint8_t storage[MediaItem_bytes]; + struct MediaItem *item = + MediaItem_InitFromRecord((struct MediaItem *)storage, record, 0); + enum browse kind = BROWSE_NONE; + if (!MediaItem_HasRecordFlag8F01(item) && !MediaItem_HasKind200000(item) && + !MediaItem_HasKind8(item) && !MediaItem_HasKind8062(item)) { + void *preferences = PreferencesService_Get(); + kind = MediaItem_IsCompilation(item) && preferences && + PreferencesService_Get60BC(preferences) + ? BROWSE_COMPILATION + : BROWSE_ALBUM_ARTIST; + } + MediaItem_Destroy(item); + return kind; +} + +static int can_browse_pair(const struct rv_context *ctx) +{ + return browse_kind(ctx) == BROWSE_ALBUM_ARTIST; +} + +static int can_browse_compilation(const struct rv_context *ctx) +{ + return browse_kind(ctx) == BROWSE_COMPILATION; +} + +/* ARM: Runtime_OperatorNew returns with mov pc, lr. The screen that takes + * the selection deletes the copy. */ +RV_ARM static void request(const char *key, const struct NativeString *name) +{ + struct NativeString *copy = Runtime_OperatorNew(NativeString_bytes); + if (!copy) + return; + NativeString_InitCopy(copy, name); + _Alignas(uint32_t) uint8_t storage[CppString_bytes]; + CppString_Init(storage, key); + NavigatorProperties_SetPointer(NavigatorProperties, storage, copy); + CppString_Destroy(storage); +} + +static void browse(const struct rv_context *ctx, const char *key, int artist) +{ + void *record = ctx->row >= 0 ? queue_record(ctx->row) : NULL; + if (!record) + return; + _Alignas(uint32_t) uint8_t storage[MediaItem_bytes]; + _Alignas(uint32_t) uint8_t text[NativeString_bytes]; + struct MediaItem *item = + MediaItem_InitFromRecord((struct MediaItem *)storage, record, 0); + struct NativeString *name = (struct NativeString *)text; + NativeString_InitEmpty(name); + if (artist) + MediaItem_GetArtist(item, name); + else + MediaItem_GetAlbum(item, name); + request(key, name); + Navigator_PopToMainScreenOnly(); + NativeString_Destroy(name); + MediaItem_Destroy(item); +} + +static void browse_album(const struct rv_context *ctx) +{ + browse(ctx, "SelectAlbum", 0); +} + +static void browse_artist(const struct rv_context *ctx) +{ + browse(ctx, "SelectArtist", 1); +} + +static void browse_compilation(const struct rv_context *ctx) +{ + browse(ctx, "SelectCompilation", 0); +} + +static const struct file_info_service *file_info(void) +{ + return api->extension_service(FILE_INFO_ID); +} + +static int can_show_info(const struct rv_context *ctx) +{ + return ctx->row >= 0 && file_info() && queue_capture(ctx->row); +} + +static void show_info(const struct rv_context *ctx) +{ + const struct file_info_service *info = file_info(); + void *record = ctx->row >= 0 ? queue_record(ctx->row) : NULL; + if (info && record) + info->open(record); +} + +static const struct rv_context_row song_menu[] = { + RV_CONTEXT_ROW(RV_ROW_ACTION("Move to Top", move_top), .available = can_move_up), + RV_CONTEXT_ROW(RV_ROW_ACTION("Move Up", move_up), .available = can_move_up), + RV_CONTEXT_ROW(RV_ROW_ACTION("Move Down", move_down), .available = can_move_down), + RV_CONTEXT_ROW(RV_ROW_ACTION("Move to Bottom", move_bottom), + .available = can_move_down), + RV_CONTEXT_ROW(RV_ROW_ACTION("Remove", remove_song), .available = can_remove), + RV_CONTEXT_ROW(RV_ROW_ACTION("Browse Album", browse_album), + .available = can_browse_pair), + RV_CONTEXT_ROW(RV_ROW_ACTION("Browse Artist", browse_artist), + .available = can_browse_pair), + RV_CONTEXT_ROW(RV_ROW_ACTION("Browse Compilation", browse_compilation), + .available = can_browse_compilation), + RV_CONTEXT_ROW(RV_ROW_ACTION("File Info", show_info), .available = can_show_info), + RV_CONTEXT_ROW(RV_ROW_PUSH("Clear Up Next", "clear"), .available = upcoming), +}; + +/* Clear is button 0. */ +static int clear_chosen(const struct rv_context *ctx, uint32_t index) +{ + (void)ctx; + if (index == 0) { + queue_clear(); + api->ui_refresh(self, "queue"); + } + return 1; +} + +static const char *const clear_buttons[] = {"Clear", "Cancel"}; + +static const struct rv_screen screens[] = { + RV_SCREEN_DYNAMIC_LIST( + "queue", "Up Next", song_count, song_row, .dynamic.select = song_select, + .layout = RV_LAYOUT_FULL, .dynamic.detail = RV_DETAIL_BELOW, + .dynamic.initial = song_first, .dynamic.empty = "No Upcoming Items", + RV_SCREEN_CONTEXT(song_menu), .opened = queue_opened, .closed = queue_closed), + RV_SCREEN_DIALOG("clear", "Up Next", "Clear Up Next?", + "The items after the current one are removed from the queue.", + clear_buttons, clear_chosen, .dialog.initial = 1), +}; + +/* The menus that hand over one song, and the ones that hand over an album or + * artist. */ +#define ITEM_MENUS \ + (RV_MENU_BIT(RV_MENU_SONG_CONTEXT) | RV_MENU_BIT(RV_MENU_PODCAST_EPISODE_CONTEXT)) +#define SELECTION_MENUS \ + (RV_MENU_BIT(RV_MENU_ALBUM_CONTEXT) | RV_MENU_BIT(RV_MENU_ARTIST_CONTEXT)) + +static const struct rv_menu_entry entries[] = { + RV_MENUS_ENTRY(ITEM_MENUS, 0, RV_ROW_ACTION("Play Next", song_next), + .available = can_add_item), + RV_MENUS_ENTRY(ITEM_MENUS, 0, RV_ROW_ACTION("Play Last", song_last), + .available = can_add_item), + RV_MENUS_ENTRY(SELECTION_MENUS, 0, RV_ROW_ACTION("Play Next", selection_next), + .available = can_add), + RV_MENUS_ENTRY(SELECTION_MENUS, 0, RV_ROW_ACTION("Play Last", selection_last), + .available = can_add), + RV_MENU_ENTRY(RV_MENU_NOW_PLAYING_CONTEXT, 0, RV_ROW_PUSH("Up Next", "queue"), + .available = available), + RV_MENU_ENTRY(RV_MENU_NOW_PLAYING_CONTEXT, 0, RV_ROW_PUSH("Clear Up Next", "clear"), + .available = upcoming), + RV_MENU_ENTRY(RV_MENU_MUSIC, RV_MUSIC_AUDIOBOOKS, RV_ROW_PUSH("Up Next", "queue"), + .shown_by = KEY_IN_MUSIC), + RV_MENU_ENTRY(RV_MENU_MAIN, RV_MAIN_AUDIOBOOKS, RV_ROW_PUSH("Up Next", "queue"), + .shown_by = KEY_IN_MAIN, .preview = RV_PREVIEW_MUSIC), +}; + +static const struct rv_setting settings[] = { + RV_SETTING_BOOL(KEY_IN_MUSIC, "Up Next in Music", 1), + RV_SETTING_BOOL(KEY_IN_MAIN, "Up Next in Main Menu", 0), +}; + +/* The old core's built-in Up Next row in its menu visibility record. */ +#define OLD_MENU_KEY 0x857127e6 + +static int first_load = 1; + +static void changed(uint16_t key) +{ + if (key == RV_SETTING_KEY_ALL) { + int import = first_load; + first_load = 0; + migrate_menu_visibility(api, self, import, OLD_MENU_KEY, KEY_IN_MUSIC, 1, + KEY_IN_MAIN, 0); + } +} + +static const struct rv_hook hooks[] = { + RV_HOOK_FILTER(RV_SITE_MediaPlayer_ToggleStopped_call, toggle_stopped), + RV_HOOK_FILTER(RV_SITE_MediaList_OnTheGoAdd_call, on_the_go_add), +}; + +static const struct rv_descriptor extension = { + .size = sizeof extension, + RV_HOOKS(hooks), + RV_SETTINGS(settings), + .setting_changed = changed, + RV_SCREENS(screens), + RV_ENTRIES(entries), +}; + +const struct rv_descriptor *rv_module_entry(const struct rv_api *core, + rv_extension_handle handle) +{ + api = core; + self = handle; + return &extension; +} diff --git a/extensions/playback-queue/manifest.toml b/extensions/playback-queue/manifest.toml new file mode 100644 index 0000000..7343192 --- /dev/null +++ b/extensions/playback-queue/manifest.toml @@ -0,0 +1,16 @@ +id = "playback-queue" +name = "Playback Queue" +description = "Queue songs, albums, artists or podcast episodes with Play Next or Play Last. View and edit queued items at any time." +version = "0.1.0" +author = "RepriseOS contributors" +license = "GPL-3.0-only" +api = "1.89" +stability = "beta" +category = "media" + +[libraries] +optional = ["reprise"] + +[[module]] +name = "main" +trigger = "always" diff --git a/extensions/playback-queue/queue.c b/extensions/playback-queue/queue.c new file mode 100644 index 0000000..2323e7c --- /dev/null +++ b/extensions/playback-queue/queue.c @@ -0,0 +1,510 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* The player's playing list: inserting after the current song or at the end, + * removing, moving, and making the player drop the track it prepared. + * + * Insertion adapted from RepriseOS payload/play_next.c and + * payload/queue_selection.c (34fad44, 11e5ba7, c997a51) by lgreitis and + * brilliant-alien. */ + +#include "queue.h" +#include "osos-2.0.5.h" +#include "rv_api.h" +#include "rv_libc.h" +#include "rv_media.h" +#include + +static void *view_of(void *player) +{ + return (uint8_t *)player + MediaPlayer_playback_view; +} + +static struct MediaList *list_of(void *player) +{ + return RV_FIELD(view_of(player), MediaListView_list, struct MediaList *); +} + +static struct MediaEntry *root_of(struct MediaList *list) +{ + return RV_FIELD(list, MediaList_root, struct MediaEntry *); +} + +static uint32_t tracks_of(struct MediaList *list) +{ + return RV_FIELD(root_of(list), MediaEntry_tracks, uint16_t); +} + +static uint32_t count_of(void *player) +{ + return tracks_of(list_of(player)); +} + +static int32_t *current_index(void *player) +{ + return &RV_FIELD(player, MediaPlayer_current_index, int32_t); +} + +static int shuffled(struct MediaList *list) +{ + return RV_FIELD(list, MediaList_flags, uint8_t) & MediaListFlags_Shuffled; +} + +static int reversed(struct MediaList *list) +{ + return (RV_FIELD(list, MediaList_order_flags, uint8_t) & + MediaListOrderFlags_Reversed) != 0; +} + +static uint32_t rank_of(struct MediaEntry *entry) +{ + return RV_FIELD(entry, MediaEntry_song_shuffle_rank, uint32_t); +} + +/* The current song when the list is a flat song list the queue can change. */ +static struct MediaEntry *current_entry(void *player) +{ + void *view = view_of(player); + if (!RV_FIELD(player, MediaPlayer_current_track, void *) || + !MediaListView_IsValid(view)) + return NULL; + struct MediaList *list = list_of(player); + uint32_t count = count_of(player); + if (!(RV_FIELD(list, MediaList_flags, uint8_t) & MediaListFlags_PlaybackList)) + return NULL; + if (*current_index(player) < 0 || (uint32_t)*current_index(player) >= count) + return NULL; + struct MediaEntry *current = + PlaybackList_GetEntryByIndex(view, *current_index(player)); + if (!current || + RV_FIELD(current, MediaEntry_parent, struct MediaEntry *) != root_of(list) || + (RV_FIELD(current, MediaEntry_flags, uint32_t) & MediaEntryFlags_Group)) + return NULL; + if (shuffled(list)) { + void *order = RV_FIELD(list, MediaList_shuffle_index, void *); + if (!order || RV_FIELD(order, MediaOrder_count, uint32_t) != count) + return NULL; + } + return current; +} + +static int editable(void *player) +{ + if (RV_FIELD(player, MediaPlayer_current_track, void *)) + return current_entry(player) != NULL; + if (!MediaListView_IsValid(view_of(player))) + return 0; + struct MediaList *list = list_of(player); + if (!root_of(list) || + !(RV_FIELD(list, MediaList_flags, uint8_t) & MediaListFlags_PlaybackList)) + return 0; + uint32_t count = count_of(player); + if (count) { + struct MediaEntry *entry = PlaybackList_GetEntryByIndex(view_of(player), 0); + if (!entry || + RV_FIELD(entry, MediaEntry_parent, struct MediaEntry *) != root_of(list) || + (RV_FIELD(entry, MediaEntry_flags, uint32_t) & MediaEntryFlags_Group)) + return 0; + } + if (shuffled(list) && count) { + void *order = RV_FIELD(list, MediaList_shuffle_index, void *); + if (!order || RV_FIELD(order, MediaOrder_count, uint32_t) != count) + return 0; + } + return 1; +} + +static uint32_t first_pending(void *player) +{ + return RV_FIELD(player, MediaPlayer_current_track, void *) + ? (uint32_t)*current_index(player) + 1 + : 0; +} + +static uint32_t upcoming(void *player) +{ + return count_of(player) - first_pending(player); +} + +static int prepare_queue(void *player) +{ + if (editable(player)) + return 1; + if (RV_FIELD(player, MediaPlayer_current_track, void *)) + return 0; + /* Native initialization attaches the list and playback source without + * loading a current track. Repeat 3 preserves the native preference. */ + MediaPlayer_InitializePlaybackList(player, 0, 3); + return editable(player); +} + +/* Artwork is indexed by list position: stopped before a change, rebuilt after. */ +static void stop_artwork(void *player) +{ + ArtworkSession_Stop((uint8_t *)player + MediaPlayer_artwork_session); +} + +/* After a change the prepared next track may be the wrong one, and the source + * caches the track order. */ +static void changed(void *player) +{ + if (RV_FIELD(player, MediaPlayer_current_track, void *)) + MediaPlayer_RebuildArtwork(player); + MediaPlayer_ClearPreparedTrack(player); + Audio_SetPlaybackSource(RV_FIELD(player, MediaPlayer_playback_source, void *)); +} + +/* A copy of `entry` that ends up at playback index `position`. */ +static struct MediaEntry *insert_at(void *player, struct MediaEntry *entry, + uint32_t position) +{ + struct MediaList *list = list_of(player); + uint32_t count = count_of(player); + int reverse = reversed(list); + uint32_t rank = reverse ? count - position : position; + struct MediaEntry *after = + reverse && !position + ? RV_FIELD(root_of(list), MediaEntry_group_last, struct MediaEntry *) + : NULL; + if (position) { + after = PlaybackList_GetEntryByIndex(view_of(player), position - 1); + if (reverse) + after = RV_FIELD(after, MediaEntry_previous, struct MediaEntry *); + } + struct MediaEntry *cursor[] = {root_of(list), after}; + + void *track_data = RV_FIELD(list, MediaList_track_data, void *); + TrackData_AcquireStringCaches(track_data); + if (shuffled(list)) { + /* The shuffle order sorts by rank; leave a gap at `rank`. */ + void *order = RV_FIELD(list, MediaList_shuffle_index, void *); + struct MediaEntry **entries = + (struct MediaEntry **)((uint8_t *)order + MediaOrder_entries); + for (uint32_t i = 0; i < count; i++) + RV_FIELD(entries[i], MediaEntry_song_shuffle_rank, uint32_t) = + i + (i >= rank); + } + struct MediaEntry *inserted = MediaList_CopyEntryAtPosition(entry, list, cursor, 0); + if (inserted && shuffled(list)) { + RV_FIELD(inserted, MediaEntry_song_shuffle_rank, uint32_t) = rank; + /* Copy notifications may rebuild the order before the rank is set. */ + MediaList_InvalidateOrderCache(list, MediaOrderMode_Shuffle); + } + TrackData_ReleaseStringCaches(track_data); + return inserted; +} + +/* Removes the songs strictly between `from` and `to` in playback order, to the + * end when `to` is NULL. One pass over the list: each removal drops the order + * caches, so looking songs up by index in between would rebuild them every + * time. A removed entry is freed at once. */ +static void remove_between(struct MediaList *list, struct MediaEntry *from, + struct MediaEntry *to) +{ + int reverse = reversed(list); + if (shuffled(list)) { + /* Shuffled songs play by rank, descending when reversed. */ + uint32_t start = from ? rank_of(from) : 0, end = to ? rank_of(to) : 0; + struct MediaEntry *entry = + RV_FIELD(root_of(list), MediaEntry_group_first, struct MediaEntry *); + while (entry) { + struct MediaEntry *next = + RV_FIELD(entry, MediaEntry_next, struct MediaEntry *); + uint32_t rank = rank_of(entry); + int between = reverse ? (!from || rank < start) && (!to || rank > end) + : (!from || rank > start) && (!to || rank < end); + if (between) + MediaEntry_Remove(entry); + entry = next; + } + } else { + uint32_t step = reverse ? MediaEntry_previous : MediaEntry_next; + struct MediaEntry *entry = + from ? RV_FIELD(from, step, struct MediaEntry *) + : RV_FIELD(root_of(list), + reverse ? MediaEntry_group_last : MediaEntry_group_first, + struct MediaEntry *); + while (entry && entry != to) { + struct MediaEntry *next = RV_FIELD(entry, step, struct MediaEntry *); + MediaEntry_Remove(entry); + entry = next; + } + } + MediaList_NotifyChanged(list); +} + +/* Removes one song at playback index `index`, never the current one. */ +static void remove_one(void *player, uint32_t index) +{ + struct MediaEntry *entry = PlaybackList_GetEntryByIndex(view_of(player), index); + if (!entry) + return; + MediaEntry_Remove(entry); + MediaList_NotifyChanged(list_of(player)); + if ((int32_t)index < *current_index(player)) + --*current_index(player); +} + +static struct MediaEntry *item_entry(struct MediaItem *item) +{ + struct MediaEntry *entry = RV_FIELD(item, MediaItem_entry, struct MediaEntry *); + void *record = RV_FIELD(item, MediaItem_record, void *); + if (!entry && record) + entry = RV_FIELD(record, MediaRecord_entries, struct MediaEntry *); + return entry; +} + +static int is_queueable(struct MediaItem *item) +{ + struct MediaEntry *entry = item_entry(item); + return entry && + !(RV_FIELD(entry, MediaEntry_flags, uint32_t) & MediaEntryFlags_Group) && + !MediaItem_HasKind200000(item) && !MediaItem_HasKind8(item) && + !MediaItem_HasKind8062(item); +} + +int queue_available(void) +{ + void *player = rv_player_lock(); + int available = editable(player); + rv_player_unlock(player); + return available; +} + +int queue_can_add(void) +{ + void *player = rv_player_lock(); + int allowed = + !RV_FIELD(player, MediaPlayer_current_track, void *) || editable(player); + rv_player_unlock(player); + return allowed; +} + +int queue_can_add_item(const void *item) +{ + return item && is_queueable((struct MediaItem *)item) && queue_can_add(); +} + +int queue_start_idle(void) +{ + void *player = rv_player_lock(); + int start = MediaPlayer_IsStopped(player) && editable(player) && upcoming(player); + if (start) + MediaPlayer_PlayIndex(player, first_pending(player), 0, 0, 0); + rv_player_unlock(player); + return start; +} + +void queue_add_item(const void *item, int last) +{ + struct MediaItem *song = (struct MediaItem *)item; + void *player = rv_player_lock(); + if (song && is_queueable(song) && prepare_queue(player)) { + uint32_t position = last ? count_of(player) : first_pending(player); + stop_artwork(player); + if (insert_at(player, item_entry(song), position)) + changed(player); + else + MediaPlayer_RebuildArtwork(player); + } + rv_player_unlock(player); +} + +void queue_add_browser(void *browser, int last) +{ + void *player = rv_player_lock(); + struct MediaList *source = browser ? MediaBrowser_GetCurrentList(browser) : NULL; + if (!source || !root_of(source) || !prepare_queue(player)) { + rv_player_unlock(player); + return; + } + /* The songs and order Add to On-The-Go would take for this selection. */ + MediaBrowser_BuildSongs(browser); + uint32_t mode = + shuffled(source) ? MediaOrderMode_Shuffle : MediaBrowser_GetOrderMode(browser); + uint32_t grouped = RV_FIELD(browser, MediaBrowser_order_flag, uint8_t) != 0; + uint32_t count = tracks_of(source); + + stop_artwork(player); + int inserted = 0; + for (uint32_t i = 0; i < count; i++) { + /* Play Next puts each song right after the current one: walk backwards. */ + uint32_t index = last ? i : count - 1 - i; + struct MediaEntry *entry = + MediaList_GetEntryByOrderIndex(source, mode, grouped, index); + if (!entry || !RV_FIELD(entry, MediaEntry_song_record, void *) || + !MediaBrowser_EvaluateEntryFilters(browser, entry, source)) + continue; + if (!editable(player)) + break; + uint32_t position = last ? count_of(player) : first_pending(player); + if (insert_at(player, entry, position)) + inserted = 1; + } + if (inserted) + changed(player); + else + MediaPlayer_RebuildArtwork(player); + rv_player_unlock(player); +} + +uint32_t queue_rows(void) +{ + void *player = rv_player_lock(); + uint32_t rows = editable(player) ? upcoming(player) : 0; + rv_player_unlock(player); + return rows; +} + +int queue_changed(void) +{ + static void *last_list, *last_track; + static uint32_t last_count; + static int32_t last_index; + static uint8_t last_order; + void *player = rv_player_lock(); + int valid = editable(player); + void *list = valid ? list_of(player) : NULL; + void *track = valid ? RV_FIELD(player, MediaPlayer_current_track, void *) : NULL; + uint32_t count = valid ? count_of(player) : 0; + int32_t index = valid ? *current_index(player) : -1; + uint8_t order = valid ? (shuffled(list) != 0) | (reversed(list) << 1) : 0; + int changed = list != last_list || track != last_track || count != last_count || + index != last_index || order != last_order; + last_list = list; + last_track = track; + last_count = count; + last_index = index; + last_order = order; + rv_player_unlock(player); + return changed; +} + +void queue_text(uint32_t row, int artist, char *out, uint32_t capacity) +{ + if (!capacity) + return; + out[0] = 0; + void *player = rv_player_lock(); + if (editable(player) && row < upcoming(player)) { + _Alignas(uint32_t) uint8_t item[MediaItem_bytes]; + _Alignas(uint32_t) uint8_t text[NativeString_bytes]; + MediaItem_InitFromRecord((struct MediaItem *)item, NULL, 0); + if (MediaPlayer_GetItemAtIndex(player, first_pending(player) + row, + (struct MediaItem *)item)) { + const char *utf8 = rv_item_text( + item, artist ? MediaItem_artist_method : MediaItem_title_method, + (struct NativeString *)text); + rv_copy_utf8(out, capacity, utf8); + NativeString_Destroy((struct NativeString *)text); + } + MediaItem_Destroy((struct MediaItem *)item); + } + rv_player_unlock(player); +} + +void queue_play(uint32_t row) +{ + void *player = rv_player_lock(); + if (editable(player) && row < upcoming(player)) { + struct MediaEntry *current = current_entry(player); + uint32_t first = first_pending(player); + struct MediaEntry *selected = + PlaybackList_GetEntryByIndex(view_of(player), first + row); + if (selected) { + stop_artwork(player); + if (row) + remove_between(list_of(player), current, selected); + /* Keep the old current entry alive until Apple has saved its + * position and installed the selected track. */ + if (MediaPlayer_PlayIndex(player, first, 0, 0, 0) && current) + remove_one(player, first - 1); + changed(player); + } + } + rv_player_unlock(player); +} + +/* Playback can advance while a context menu is open. Never edit a different + * song that has since taken the captured row's place. */ +static struct MediaEntry *menu_entry; +static struct MediaList *menu_list; + +int queue_capture(uint32_t row) +{ + void *player = rv_player_lock(); + menu_entry = NULL; + menu_list = NULL; + if (editable(player) && row < upcoming(player)) { + menu_list = list_of(player); + menu_entry = + PlaybackList_GetEntryByIndex(view_of(player), first_pending(player) + row); + } + rv_player_unlock(player); + return menu_entry != NULL; +} + +void *queue_record(uint32_t row) +{ + void *record = NULL; + void *player = rv_player_lock(); + if (editable(player) && row < upcoming(player) && list_of(player) == menu_list && + PlaybackList_GetEntryByIndex(view_of(player), first_pending(player) + row) == + menu_entry) { + _Alignas(uint32_t) uint8_t item[MediaItem_bytes]; + MediaItem_InitFromRecord((struct MediaItem *)item, NULL, 0); + if (MediaPlayer_GetItemAtIndex(player, first_pending(player) + row, + (struct MediaItem *)item)) + record = RV_FIELD(item, MediaItem_record, void *); + MediaItem_Destroy((struct MediaItem *)item); + } + rv_player_unlock(player); + return record; +} + +void queue_move(uint32_t from, uint32_t to) +{ + void *player = rv_player_lock(); + if (editable(player) && from != to && from < upcoming(player) && + to < upcoming(player)) { + uint32_t first = first_pending(player); + struct MediaEntry *entry = + PlaybackList_GetEntryByIndex(view_of(player), first + from); + if (list_of(player) != menu_list || entry != menu_entry) { + rv_player_unlock(player); + return; + } + stop_artwork(player); + /* A copy at the new place, then the original goes. */ + if (insert_at(player, entry, first + to + (to > from))) { + MediaEntry_Remove(entry); + MediaList_NotifyChanged(list_of(player)); + } + changed(player); + } + rv_player_unlock(player); +} + +void queue_remove(uint32_t row) +{ + void *player = rv_player_lock(); + if (editable(player) && row < upcoming(player) && list_of(player) == menu_list && + PlaybackList_GetEntryByIndex(view_of(player), first_pending(player) + row) == + menu_entry) { + stop_artwork(player); + remove_one(player, first_pending(player) + row); + changed(player); + } + rv_player_unlock(player); +} + +void queue_clear(void) +{ + void *player = rv_player_lock(); + struct MediaEntry *current = current_entry(player); + if (editable(player) && upcoming(player)) { + stop_artwork(player); + remove_between(list_of(player), current, NULL); + changed(player); + } + rv_player_unlock(player); +} diff --git a/extensions/playback-queue/queue.h b/extensions/playback-queue/queue.h new file mode 100644 index 0000000..d2876ff --- /dev/null +++ b/extensions/playback-queue/queue.h @@ -0,0 +1,56 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +#ifndef PLAYBACK_QUEUE_H +#define PLAYBACK_QUEUE_H + +#include + +/* The native playback list, from the UI task. Queue access takes the player lock. */ + +/* Whether the player has a list the queue can change, including an idle list. */ +int queue_available(void); +int queue_can_add(void); +int queue_can_add_item(const void *item); +int queue_start_idle(void); + +/* Inserts a supported context item at the first pending position, or at the + * end with `last`. Creates an idle native list when needed. */ +void queue_add_item(const void *item, int last); + +/* Inserts the songs of an album or artist selection as Add to On-The-Go would + * add them; `browser` is what Apple hands to the On-The-Go playlist. */ +void queue_add_browser(void *browser, int last); + +/* Pending items, starting at row 0: all items when idle, otherwise those + * after the current one. */ +uint32_t queue_rows(void); + +/* Whether the playback list, current track, position, count or order changed since + * the previous check. Called on the UI task while Up Next is open. */ +int queue_changed(void); + +/* Title (or artist with `artist`) of row `row` into `out`, empty for a missing + * row. Capacity includes the terminator; UTF-8 characters are kept whole. */ +void queue_text(uint32_t row, int artist, char *out, uint32_t capacity); + +/* Plays row `row`: the songs before it, the current one included, + * leave the list. Earlier songs stay, so Previous still reaches them. */ +void queue_play(uint32_t row); + +/* Captures the row a context menu opens on; 0 for a missing row. */ +int queue_capture(uint32_t row); + +/* The media record of upcoming row `row`, if it still names the captured + * entry; NULL otherwise. */ +void *queue_record(uint32_t row); + +/* Upcoming row `from` to row `to`, if it still names the captured entry. */ +void queue_move(uint32_t from, uint32_t to); + +/* Removes upcoming row `row`. */ +void queue_remove(uint32_t row); + +/* Removes all pending items, preserving the current item and earlier history. */ +void queue_clear(void); + +#endif diff --git a/extensions/playback-queue/screenshots/clear.png b/extensions/playback-queue/screenshots/clear.png new file mode 100644 index 0000000..6efcf14 Binary files /dev/null and b/extensions/playback-queue/screenshots/clear.png differ diff --git a/extensions/playback-queue/screenshots/item-menu.png b/extensions/playback-queue/screenshots/item-menu.png new file mode 100644 index 0000000..ff8e694 Binary files /dev/null and b/extensions/playback-queue/screenshots/item-menu.png differ diff --git a/extensions/playback-queue/screenshots/up-next.png b/extensions/playback-queue/screenshots/up-next.png new file mode 100644 index 0000000..2e819e4 Binary files /dev/null and b/extensions/playback-queue/screenshots/up-next.png differ diff --git a/extensions/reprise/manifest.toml b/extensions/reprise/manifest.toml new file mode 100644 index 0000000..f4b6f12 --- /dev/null +++ b/extensions/reprise/manifest.toml @@ -0,0 +1,15 @@ +id = "reprise" +name = "RepriseOS" +description = "RepriseOS services its core provides to extensions. Nothing to install: list it under [libraries] optional." +version = "0.1.0" +author = "RepriseOS contributors" +license = "GPL-3.0-only" +api = "1.89" +category = "library" +exports = [ + "reprise_legacy_preference", +] + +[[module]] +name = "main" +trigger = "always" diff --git a/extensions/reprise/reprise.h b/extensions/reprise/reprise.h new file mode 100644 index 0000000..ab186bf --- /dev/null +++ b/extensions/reprise/reprise.h @@ -0,0 +1,16 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ + +/* What the RepriseOS core exports as the library `reprise`. There is no + * reprise.rvx: the core answers the id itself. List it under + * `[libraries] optional`, so the extension also runs on other cores, where + * these stay NULL; call them through RV_OPTIONAL or test them first. */ + +#ifndef REPRISE_H +#define REPRISE_H +#include + +/* Copies the stored value of an old firmware preference `key` into `data` + * and returns its size, 0 when absent; at most `capacity` bytes. */ +uint32_t (reprise_legacy_preference)(uint32_t key, void *data, uint32_t capacity); + +#endif diff --git a/extensions/shared/legacy.h b/extensions/shared/legacy.h index 974435c..474e871 100644 --- a/extensions/shared/legacy.h +++ b/extensions/shared/legacy.h @@ -1,20 +1,22 @@ /* SPDX-License-Identifier: GPL-3.0-only */ #pragma once #include "rv_api.h" +#include "../reprise/reprise.h" /* Only the initial load imports the old firmware switch. A later reset records - * the extension default so rebooting cannot resurrect the old preference. */ + * the extension default so rebooting cannot resurrect the old preference. On a + * core without the reprise library nothing is imported. */ static inline void migrate_switch(const struct rv_api *api, rv_extension_handle self, int first_load, uint16_t key, uint32_t old_key, uint32_t old_on, int on, int off, uint8_t type) { uint32_t value; - if (!rv_has_reprise_services(api) || + if (!reprise_legacy_preference || api->setting_read(self, key, &value, sizeof value) == sizeof value) return; int32_t mode = off; if (first_load && - api->legacy_preference(old_key, &value, sizeof value) == sizeof value && + (reprise_legacy_preference)(old_key, &value, sizeof value) == sizeof value && value == old_on) mode = on; api->setting_write(self, key, type, &mode, sizeof mode); diff --git a/extensions/shared/menu_visibility.h b/extensions/shared/menu_visibility.h new file mode 100644 index 0000000..24f5414 --- /dev/null +++ b/extensions/shared/menu_visibility.h @@ -0,0 +1,34 @@ +/* SPDX-License-Identifier: GPL-3.0-only */ +#pragma once +#include "rv_api.h" +#include "../reprise/reprise.h" + +/* The old core kept the Main and Music menu checkboxes of its own rows in one + * record, "MVIS": {key, visible} pairs, bit 0 Main and bit 1 Music. Only the + * initial load imports the row's pair; without one, and on a later reset, the + * extension defaults are recorded so rebooting cannot resurrect the old value. + * On a core without the reprise library nothing is imported. */ +static inline void migrate_menu_visibility(const struct rv_api *api, + rv_extension_handle self, int first_load, + uint32_t old_key, uint16_t music_key, + int music_default, uint16_t main_key, + int main_default) +{ + uint32_t value; + if (!reprise_legacy_preference || + api->setting_read(self, music_key, &value, sizeof value) == sizeof value || + api->setting_read(self, main_key, &value, sizeof value) == sizeof value) + return; + int32_t music = music_default, main = main_default; + uint32_t pairs[16]; + uint32_t bytes = + first_load ? (reprise_legacy_preference)(0x5349564d, pairs, sizeof pairs) : 0; + for (uint32_t i = 0; i + 1 < bytes / 4; i += 2) + if (pairs[i] == old_key && pairs[i + 1] <= 3) { + music = (pairs[i + 1] >> 1) & 1; + main = pairs[i + 1] & 1; + break; + } + api->setting_write(self, music_key, RV_SETTING_TYPE_BOOL, &music, sizeof music); + api->setting_write(self, main_key, RV_SETTING_TYPE_BOOL, &main, sizeof main); +} diff --git a/extensions/night-shift/schedule.c b/extensions/shared/schedule.c similarity index 96% rename from extensions/night-shift/schedule.c rename to extensions/shared/schedule.c index f9c0963..29edb7f 100644 --- a/extensions/night-shift/schedule.c +++ b/extensions/shared/schedule.c @@ -1,7 +1,6 @@ /* SPDX-License-Identifier: GPL-3.0-only */ #include "schedule.h" -#include "ext.h" #include "osos-2.0.5.h" #include "sun.h" #include @@ -75,5 +74,5 @@ const char *schedule_caption(void) { struct schedule s; schedule_read(&s); - return s.state == SCHEDULE_NO_ZONE ? "Set a time zone" : "Sunset to Sunrise"; + return s.state == SCHEDULE_NO_ZONE ? "Set a Time Zone" : "Sunset to Sunrise"; } diff --git a/extensions/night-shift/schedule.h b/extensions/shared/schedule.h similarity index 79% rename from extensions/night-shift/schedule.h rename to extensions/shared/schedule.h index 07b25b2..570b70c 100644 --- a/extensions/night-shift/schedule.h +++ b/extensions/shared/schedule.h @@ -5,8 +5,9 @@ /* The Auto schedule Dark Mode and Night Shift follow: sunset to sunrise in * the city of the time zone set under Settings > Date & Time, by the iPod's - * clock. Reading it is a few integer multiplies; the main module reads it - * once a minute while a row is on Auto. */ + * clock. Reading it is a few integer multiplies; an extension reads it once a + * minute while its row is on Auto. Compiled into each extension that uses it + * with sun.c. */ enum { SCHEDULE_NO_ZONE, /* the time zone is unset or not one of Apple's: day */ SCHEDULE_RISES, /* the sun rises and sets today */ @@ -25,7 +26,7 @@ void schedule_read(struct schedule *out); int schedule_night(const struct schedule *s); /* `value` folded into 0..1439. */ int schedule_minute(int value); -/* "Sunset to Sunrise", or "Set a time zone" without a known zone. */ +/* "Sunset to Sunrise", or "Set a Time Zone" without a known zone. */ const char *schedule_caption(void); #endif diff --git a/extensions/shared/settings_icon.py b/extensions/shared/settings_icon.py index 659db8a..3214a80 100644 --- a/extensions/shared/settings_icon.py +++ b/extensions/shared/settings_icon.py @@ -62,9 +62,10 @@ def supersampled(work, shapes): return [mask] -def glyph(work, font, code, reach): +def glyph(work, font, code, reach, mirror=False): """magick arguments for a mask of the font's glyph at `code`, fitted into a - square of side `reach` centred on the art box.""" + square of side `reach` centred on the art box, flipped left to right when + `mirror` is set.""" path = work / f"{code:x}.png" magick( "-background", @@ -78,6 +79,7 @@ def glyph(work, font, code, reach): f"label:{chr(code)}", "-trim", "+repage", + *(["-flop"] if mirror else []), "-resize", f"{reach}x{reach}", path, diff --git a/extensions/night-shift/sun.c b/extensions/shared/sun.c similarity index 100% rename from extensions/night-shift/sun.c rename to extensions/shared/sun.c diff --git a/extensions/night-shift/sun.h b/extensions/shared/sun.h similarity index 100% rename from extensions/night-shift/sun.h rename to extensions/shared/sun.h diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..b1448e6 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,22 @@ +# SPDX-License-Identifier: GPL-3.0-only + +[tool.ruff] +required-version = "==0.12.12" +target-version = "py311" +line-length = 88 +extend-exclude = ["build", ".sdk", ".rockbox", "toolchains"] + +[tool.ruff.lint] +select = ["E4", "E7", "E9", "F", "I"] + +[tool.ruff.lint.isort] +known-first-party = ["fixtures", "rvt"] + +[tool.ruff.format] +quote-style = "double" +indent-style = "space" + +[tool.ruff.lint.per-file-ignores] +# Scripts that put another directory on sys.path before importing from it. +"extensions/*/assets/render.py" = ["E402"] +"tools/catalog.py" = ["E402"] diff --git a/tests/test_catalog.py b/tests/test_catalog.py index fd4de66..94c96a8 100644 --- a/tests/test_catalog.py +++ b/tests/test_catalog.py @@ -40,8 +40,9 @@ def test_preview_packages_and_referenced_images(self): for entry in entries.values(): assets = [entry["package"]] if entry["category"] != "library": - self.assertTrue(entry["screenshots"][0]["alt"]) - self.assertEqual(entry["screenshots"][0]["width"], 320) + for shot in entry["screenshots"]: + self.assertTrue(shot["alt"]) + self.assertEqual(shot["width"], 320) assets += [entry["icon"], *entry["screenshots"]] for asset in assets: data = (self.out / asset["url"]).read_bytes() @@ -55,7 +56,7 @@ def test_remote_release_and_failed_update_retains_all_assets(self): folder = catalog.ROOT / source["path"] package = (self.packages / "balance.rvx").read_bytes() release = { - "tag_name": "balance/v0.1.0", + "tag_name": "balance/v0.1.1", "published_at": "2026-11-24T00:00:00Z", "assets": [ {"name": "balance.rvx", "size": len(package), "state": "uploaded"} @@ -77,7 +78,7 @@ def download(url, limit): ): self.assertEqual(catalog.generate(sources, self.out, catalog.remote), []) before = self.entries() - release["tag_name"] = "balance/v0.1.1" + release["tag_name"] = "balance/v0.1.2" self.assertTrue(catalog.generate(sources, self.out, catalog.remote)) self.assertEqual(before, self.entries()) self.assertTrue((self.out / before["balance"]["package"]["url"]).exists()) @@ -182,7 +183,7 @@ def test_corrupt_package_is_rejected(self): catalog.snapshot( "balance", source, - "0.1.0", + "0.1.1", lambda path: (folder / path).read_bytes(), package, None, diff --git a/themes/NOTICE b/themes/NOTICE new file mode 100644 index 0000000..40a568a --- /dev/null +++ b/themes/NOTICE @@ -0,0 +1,18 @@ +RepriseOS themes +Copyright (C) lgreitis and RepriseOS contributors. GPL-3.0-only. + +The rvt compiler and the Classic theme are adapted from the RevolaOS themes +repository, revision 6d0ea430642b, copyright 2026 The RevolaOS Authors. +GPL-3.0-only. + +Third-party work included: + +- The Classic theme's dark background, + themes/classic/dark/apple/Background_LightBlue_Image.png, is the RepriseOS + core's former themes/dark/background-dark-image.png by lgreitis (5ec8799). + Its dark palette comes from the core's former payload/dark_mode.c (01c89f6) + by lgreitis and Alex Ball (alexballvideos-netizen). GPL-3.0-only. + +No Apple firmware or artwork ships in this directory. The catalog records the +names, sizes, offsets and checksums of Apple's bitmaps, and Classic's recolour +rules list the colour values they change; neither holds any pixels. diff --git a/themes/README.md b/themes/README.md new file mode 100644 index 0000000..86a413e --- /dev/null +++ b/themes/README.md @@ -0,0 +1,28 @@ +# themes + +First-party themes for RepriseOS and the compiler that builds a theme folder into one `/Reprise/Themes/.rvt` file for the Appearance extension. A theme sets colours, accents and rendering options, and replaces or derives Apple's bitmaps. Authoring needs only Python. + +| Directory | Theme | What it looks like | Appearances | +|---|---|---|---| +| `themes/classic` | Classic | The stock art relit, recoloured and inverted on the iPod. Ships inside the Appearance extension | dark | + +## Build + +From the `themes/` directory: + +```sh +python3 -m rvt compile themes/classic --allow-reserved # into dist/classic/classic.rvt +python3 -m rvt inspect dist/classic/classic.rvt +``` + +Copy `.rvt` to `/Reprise/Themes/`. Classic's recolour rule files are generated by `themes/classic/recolor.py --firmware osos.bin` from a decrypted 2.0.5 firmware. `--check` confirms the committed files match. The other commands, the tests and the package layout are in [The compiler](docs/toolchain.md). + +## Documentation + +| Page | Contents | +|---|---| +| [docs/](docs/README.md) | Authoring, the compiler, the file format, the catalogs, the bitmaps | + +## License + +GPL-3.0-only. See COPYING at the repository root and NOTICE in this directory. diff --git a/themes/docs/README.md b/themes/docs/README.md new file mode 100644 index 0000000..bf4752e --- /dev/null +++ b/themes/docs/README.md @@ -0,0 +1,10 @@ +# Themes documentation + +| Page | Contents | +|---|---| +| [Authoring](authoring.md) | The theme folder, `theme.toml`, colour roles, art, tints, derived art, limits | +| [The compiler](toolchain.md) | The `rvt` commands, warnings, `report.json`, the package layout, tests | +| [File format](format.md) | The `.rvt` layout | +| [Catalog](catalog.md) | Apple's bitmaps and the extension asset catalog, the fingerprint, regenerating | +| [Bitmaps](bitmaps.md) | Every Apple bitmap a theme can replace | +| [Extension bitmaps](extension-bitmaps.md) | The first-party extension bitmaps a theme can replace | diff --git a/themes/docs/authoring.md b/themes/docs/authoring.md new file mode 100644 index 0000000..9bba54e --- /dev/null +++ b/themes/docs/authoring.md @@ -0,0 +1,251 @@ +# Authoring a theme + +A theme is a folder compiled into one `.rvt` file. It sets colours, a palette per accent and a few rendering options, and replaces Apple's bitmaps with same-size art or with rules that derive them. Keys in `theme.toml` and the rule files use American spelling (`colors`, `recolor`). + +## Quickstart + +1. `python3 -m rvt new mytheme` writes `mytheme/theme.toml` with every role and option commented out, and empty `light/` and `dark/` folders, each with `apple/`, `reprise/` and `extensions/`. Run `python3 -m rvt` from the `themes/` directory. +2. Edit `theme.toml`. Put art in `light/apple/` and `dark/apple/`, named after the [bitmaps](bitmaps.md) it replaces, and [extension bitmaps](#extension-bitmaps) in `light/extensions//` and `dark/extensions//`. +3. `python3 -m rvt check mytheme` prints what each rule matched, the warnings and a size table. It writes nothing. +4. `python3 -m rvt compile mytheme` writes `dist/mytheme/mytheme.rvt` and `report.json`. `--strict` turns warnings into errors. +5. Copy `mytheme.rvt` to `/Reprise/Themes/` on the iPod. It appears under Settings > Appearance > Theme. + +The iPod derives the theme's art from `/Reprise/Firmware/reprise.bin`, so that file must be the build that is running; a mismatch leaves the look unchanged and the Theme row reports it. + +``` +mytheme/ + theme.toml + light/ + apple/ art for the light appearance: a PNG per replaced Apple bitmap, a TOML per derived one + extensions/ one folder per extension id, with a PNG per bitmap asset it replaces + reprise/ a PNG per bitmap of the core it replaces; `reprise` is the reserved owner id of the core's own bitmaps + dark/ the same for dark +``` + +A file directly under `light/` or `dark/` is an error. + +## theme.toml + +```toml +schema = 1 +id = "mytheme" # the file's stem; "classic" is the built-in theme +name = "My Theme" # shown in Settings +author = "..." # optional, report only +version = "1.0" # optional, report only + +[light] +menu_covers_default = true # the Menu Covers setting until the listener chooses one + +[light.colors] # any subset of the roles below, "#rrggbb" +accent_fill = "#0071e3" +icon_tint = "#0071e3" # left out, it follows accent_text + +[light.accents] # one colour per accent, or a table; see Accents +blue = "#007aff" +yellow = { accent = "#ffcc00", on_accent = "#000000" } + +[light.rendering] +flat_selection = false +flat_now_playing = false + +[light.tint] # role = [catalog names, globs or id/asset]; see Tint +icon_tint = ["Settings_EQ_*_Image", "Media_*Proxy_Image"] +text = ["StatusBar*_Battery_Image_[3-9]", "StatusBar*_Battery_Image_[12][0-9]"] +darkness_coverage = ["NowPlaying_Blue_Dot_Image"] +solid_coverage = ["Settings_AppleLogo_Image"] + +[light.derive] # rules for derived art; see Derived art +"Settings_Brightness_Image" = { kind = "invert" } + +[dark] # the same tables; an empty table is Classic dark colours and no art +``` + +Declare `[light]`, `[dark]` or both. For a missing appearance the iPod keeps Classic, and turning Dark Mode on with a light-only theme says the theme has no dark appearance. Unknown keys are rejected. `fonts`, `layouts`, `metrics`, `animations`, `sounds`, `strings` and `wallpapers` are rejected as unsupported. + +### Colour roles + +Roles left out keep their Classic value, except `icon_tint`, which follows `accent_text`. + +| Role | Light | Dark | What it colours | +|---|---|---|---| +| `background` | `#ffffff` | `#181818` | Native surfaces; labels on light art | +| `text` | `#202020` | `#e8e8e8` | Native text; labels on dark art | +| `accent_fill` | `#236cc5` | `#00a1ff` | Native accent fills; stock progress, dot, star and playback art the theme leaves stock | +| `accent_text` | `#3185d0` | `#00a1ff` | Native accent text, the Search caret | +| `on_accent` | `#ffffff` | `#ffffff` | Selected-row text and tinted icons on the selection bar, the highlighted Search key, the selected calendar day | +| `selection` | `#236cc5` | `#00a1ff` | The list selection bar; stock selection and focus art the theme leaves stock | +| `cover_border` | `#7e8183` | `#383838` | Cover Flow border | +| `icon_tint` | `#3185d0` | `#00a1ff` | Tinted icons: the Settings icons of extensions and the bitmaps `[tint]` lists under it | + +Keep `on_accent` readable on both `accent_fill` and `selection`. `report.json` lists the contrast of each text and background pair for Theme Default and every accent, and `rvt check` warns about pairs the theme colours that fall below 4.5:1. + +Labels Apple draws in a fixed colour over art take `text` or `background`, whichever differs more in brightness from the centre pixel of the art behind them: + +| Label | Art | +|---|---| +| Stopwatch and Charging header title | `NowPlaying_StatusBar_Image` | +| Screen Lock and Volume Limit combination digits | `LockScreen_TumblerBgnd_Image` | +| Date and time picker values | `DateTimePicker_Well` | +| Cover Flow album title and artist (track list) | `CoverFlow_Backside_Top_Image` | +| Calendar days of the shown month | `Calendar_Active_Cell` | + +Keep `LockScreen_TumblerFocus_Image` and `DateTimePicker_Selection` about as light or dark as the art above. The focused digit and selected value use the same colour as the rest. + +Calendar days of neighbouring months follow the rule against `Calendar_Inactive_Cell`, mixed halfway toward the cell. Weekday names follow it against `background`, as does a cell with a transparent centre. The selected day and its tinted markers use `on_accent` on `Calendar_Hilite_Cell`. + +The Search letter strip and option bars (such as the Clock's Add/Edit bar) follow the rule against the well art (`OptionBar_*_Well_Center_Image`). The highlighted letter uses `on_accent` on the thumb, so keep it readable there. The shuffle selector on Now Playing follows the same rule against its own well under a theme and in Classic's dark appearance, whose art repaints that well. Its thumb does not follow the accent, so in Classic the highlighted label keeps its stock colour. Text typed into the Search box follows the rule against `System_Input_Field_Middle_Image`, and its caret uses `accent_text`. + +Apart from that, Classic keeps the stock colours of all these labels. + +### Accents + +The accents are `blue`, `purple`, `pink`, `red`, `orange`, `green`, `teal`, `yellow` and `graphite`. Each has a built-in fill (`accent_fill`, `selection`) and text colour (`accent_text`, `icon_tint`) per appearance, and uses the appearance's `on_accent`. Blue is Classic's. In `[light.accents]` an accent takes one of these forms: + +| Form | Sets | +|---|---| +| `blue = "#007aff"` | `accent_fill`, `accent_text`, `selection` and `icon_tint` to that colour | +| `yellow = { accent = "#ffcc00", on_accent = "#000000" }` | the same four, and `on_accent` | +| `teal = { accent_fill = "...", accent_text = "...", selection = "...", on_accent = "...", icon_tint = "..." }` | any subset of the five palette slots, each named after the role it replaces | + +Accents left out keep the built-in colours. `report.json` lists them under `accents_builtin`. + +### Menu Covers + +`menu_covers_default`, directly in `[light]` or `[dark]`, sets whether the Main and Music menus show the highlighted row's cover until the listener changes Menu Covers. The default is `true`. + +### Rendering + +| Key | Default | `true` / `false` | +|---|---|---| +| `flat_selection` | `false` | `true`: `selection` throughout the bar. `false`: a gradient ending at `selection`, starting at `selection` lightened 25 % toward white, with a top line lightened 55 % | +| `flat_now_playing` | `false` | `true`: the cover face-on, no reflection; Cover Flow is unchanged. `false`: the tilted cover with its reflection. The flag holds until the listener changes Now Playing Cover | +| `flat_icons` | `false` | `true`: the Settings icons of [extensions](#extension-bitmaps) the theme does not replace are drawn without their reflection. `false`: they keep it | + +Stock blue art for selection, focus and progress that the theme leaves stock is recoloured with `selection` or `accent_fill`, keeping its shading. This covers option bar thumbs, the active button, picker and calendar highlights, the Settings checkmark, the progress and Genius sliders, new-item dots, rating stars and playback glyphs. Replaced art is not recoloured. + +Screens RepriseOS draws itself mix their greys from `background` toward `text`, draw the highlighted row or the cell being edited on the lists' selection bar with `on_accent` text, tint the selected cell from `background` toward `accent_text`, and use `accent_text` for accent text. + +## Art + +A file in `light/apple/` or `dark/apple/` is named after a catalog bitmap. `Settings_About_Band_Image.png` replaces its pixels; `Settings_About_Band_Image.toml` [derives](#derived-art) them from the stock bitmap. A name the catalog lists more than once is given as its hex id, such as `light/apple/0x0DAD012A.png`. Every file must match a catalog bitmap, once per appearance. + +Art must be the bitmap's exact native size. The compiler converts it to the native format: + +| Format | Art | +|---|---| +| Masks (4 and 8) | Opaque grayscale; 4-bit masks round to 16 levels | +| Paletted (0x64, 0x65) | Any RGBA; extra colours are reduced to fit the native palette, with a warning (`palette_reduced` in `report.json`) | +| RGB565 | Opaque | +| BGRA8888 (0x1888) | Any RGBA | + +### Tint + +`[light.tint]` draws bitmaps in a colour role, following the picked accent. Each key is a role listing catalog names, hex ids, case-sensitive globs (`*`, `?`, `[...]`) or extension bitmaps as `/` ([below](#extension-bitmaps)). A glob that matches nothing is a warning; an unknown name is an error. A bitmap may appear under one role only. + +Coverage comes from the PNG if there is one (its alpha, else its gray level; coloured opaque art is rejected), otherwise from the stock bitmap. Tinted art with more coverage levels than the palette holds is reduced on coverage alone. + +| Format | Needs art | How it is tinted | +|---|---|---| +| Masks | No | At draw time | +| Paletted | No | Palette entries rewritten, alpha kept | +| BGRA8888 | No | Pixels rewritten, alpha kept | +| RGB565 | Cannot be tinted | | + +`darkness_coverage` lists tinted bitmaps whose coverage is their darkness instead of their alpha, for stock glyphs drawn black on transparent. `solid_coverage` lists tinted bitmaps drawn flat: coverage levels from 150 of 255 up become full and lower levels stay, for stock masks with gloss in their levels, such as the Apple logo. A bitmap can be in only one of the two, and both apply to stock bitmaps only, not to a PNG. A tinted bitmap cannot also be derived. + +### Derived art + +A rule describes a bitmap as a change to the stock bitmap, which the iPod computes from its firmware when the theme is applied. A rule is either an entry of `[dark.derive]`, keyed by catalog name, hex id or glob, or a file `dark/apple/.toml` with the same table. The file suits a long recolour map. A `[derive]` rule must match at least one bitmap, none with a PNG or `.toml`, and no bitmap matched by another rule. A rule has a `kind` and that kind's keys: + +| `kind` | Keys | Formats | Result | +|---|---|---|---| +| `recolor` | `[map]`: `"#rrggbbaa" = "#rrggbbaa"`, a stock colour and its replacement; keys must be quoted | paletted, BGRA8888, RGB565 | Each palette entry, pixel or RGB565 word equal to a stock colour in the map takes its replacement; the rest stay | +| `alias` | `source`: a catalog name or hex id | any but masks, the same size | The pixels of `source` (the theme's version if it has one, else stock), re-encoded when the layouts differ; a paletted target must have room for the source's colours | +| `invert` | | any but masks | RGB inverted, alpha kept | +| `relight` | the rule's values, all optional, below | paletted | A light icon on a light square redrawn as grays on a dark one | + +Any kind may add `from_other = true` to start from the theme's PNG for that bitmap in the other appearance instead of the stock bitmap. The compiler computes and stores the result. That PNG must exist and must not be tinted. An alias with `from_other` takes the other appearance's PNG of `source`, or of the bitmap itself when `source` is left out. + +```toml +# theme.toml +[dark.derive] +"Clock_*_Image_*" = { kind = "alias", from_other = true } # every digit reuses its light art +"Settings_Brightness_Image" = { kind = "invert", from_other = true } +"NowPlaying_White_Pause_Image" = { kind = "alias", source = "NowPlaying_Black_Pause_Image" } +"Media_*Proxy_Image" = { kind = "relight" } + +# dark/apple/System_ScrollbarCenter_Image.toml +kind = "recolor" +[map] +"#ffffff26" = "#91919126" +"#00000073" = "#7e7e7e73" +``` + +On RGB565 both recolour colours are opaque, with `r` and `b` multiples of 8 and `g` a multiple of 4. An alias may not point at another alias or a tinted bitmap. Aliases with `from_other` do not count against the alias [limit](#limits). + +#### Relight keys + +The keys are `t_zero` and `t_full` (the offsets from the row's background at which a pixel counts as no icon and as all icon), `bg_base`, `bg_ref`, `bg_slope`, `bg_lo`, `bg_hi`, `icon_base`, `icon_luma`, `icon_row`, `icon_lo` and `icon_hi`. [File format](format.md#relight) gives the arithmetic. The defaults are Classic's: `t_zero = 3`, `t_full = 14`, `bg_base = 25`, `bg_ref = 216`, `bg_slope = 0.357` (stored as 91/256), `bg_lo = 24`, `bg_hi = 35`, `icon_base = 394.6`, `icon_luma = -1.170`, `icon_row = -1.769`, `icon_lo = 40`, `icon_hi = 160`. + +Values are rounded to 1/256 and must satisfy `0 <= t_zero < t_full <= 255`, `0 <= bg_lo <= bg_hi <= icon_lo <= icon_hi <= 255`, `bg_base` and `icon_base` within ±1024, `bg_ref`, `icon_luma` and `icon_row` within ±255 and `bg_slope` within ±16. The bitmap must have at most 3,840 pixels and a palette of at least `icon_hi - bg_lo + 1` entries. + +#### Recolour rule from a PNG + +With a decrypted firmware: + +```sh +python3 -m rvt recolor mytheme/dark/apple/Foo.png --firmware osos.bin +``` + +writes `dark/apple/Foo.toml` when the PNG is a pure recolour of the stock bitmap, ignoring small dithering and stray pixels. Otherwise it lists the stock colours painted in more than one colour. Delete the PNG to use the rule. + +#### Previewing derived art + +```sh +python3 -m rvt preview mytheme --firmware osos.bin +``` + +renders every derived bitmap to `dist/mytheme/derived//.png`, writes `derived.json` with the address, size and CRC-32 of each, and warns about map colours that match nothing. + +## Extension bitmaps + +Extensions ship bitmaps as assets: the 78 x 121 Settings icon of their row and any pictures their screens draw. `light/extensions//.png` replaces asset `` of extension `` in light, `dark/extensions/` in dark. The core's id is `reprise`, the reserved owner id of the core's own bitmaps in the theme format, and its bitmaps go in `light/reprise/` and `dark/reprise/`. The extension asset [catalog](catalog.md#extension-asset-catalog) lists which bitmaps exist: + +```sh +python3 -m rvt catalog list --extensions # id, asset, size, format, palette, menu +python3 -m rvt catalog list --extensions --group appearance +python3 -m rvt catalog show appearance/settings-moon +``` + +[Extension bitmaps](extension-bitmaps.md) is the same list as a page. For an extension outside the built-in catalog, pass its `assets.json` to `check`, `compile` and `inspect` with `--extension` (repeatable). Its author makes the file with `python3 /assets.py manifest.toml file.rvx > assets.json`. The compiler encodes the art as the extension's build would: + +| Bitmap | Art | Stored as | +|---|---|---| +| Settings icon (`menu` in the catalog) | Exactly 78 x 121; coverage is the alpha if any pixel is translucent, else the gray level; coloured opaque art is rejected | A Mask8 coverage mask drawn in the icon tint | +| Any other bitmap | Exactly the catalog's width and height, any RGBA | Indexed8 with a palette when the art has at most 256 colours, else BGRA8888; at most 65,536 bytes with its header | + +A `[tint]` role can list a picture as `/` (`reprise/` for the core). `icon_tint = ["homebrew/apps"]` reads `extensions/homebrew/apps.png` as coverage, like a Settings icon, and draws it in that role. The PNG is needed in every appearance that lists it, `darkness_coverage` and `solid_coverage` do not apply, and Settings icons cannot be listed because they are already drawn in the icon tint. + +An unknown (id, asset) compiles only as a Settings icon, from a 78 x 121 coverage PNG, with a warning. Any other size is an error asking for `--extension`. The iPod ignores bitmaps no installed extension uses. + +A Settings icon's art box is rows 12..62, centred on column 39. Stock icons hold their reflection from row 79 down. With `flat_icons` ([Rendering](#rendering)) off, an icon with nothing below row 78 is a warning, because the icons the theme leaves stock keep their reflection. Icons are coverage in both appearances, so one shape goes into both folders. + +## Limits + +| What | Limit | +|---|---| +| `id` | `[a-z0-9][a-z0-9_-]{0,30}`; `classic` is reserved | +| `name` | at most 47 UTF-8 bytes, no control characters | +| Art size | the bitmap's native width and height, nothing else; Settings icons 78 x 121, other extension bitmaps the catalog's size | +| Extension bitmaps | at most 64 per appearance, each at most 65,536 bytes encoded; ids `[a-z][a-z0-9_-]{0,31}`, assets `[a-z0-9_-]{1,31}`, no two with equal hashes; a tinted one is a picture, not a Settings icon | +| Art files | non-interlaced PNG with 8-bit channels or a palette, at most 16 MiB; plain file names inside the folder, no symlinks that leave it | +| `theme.toml`, rule files | at most 256 KiB each | +| Palette per bitmap | the native palette's entries (see [Bitmaps](bitmaps.md)); more colours are reduced with a warning | +| Recolour map | at most 512 pairs, and no more than the bitmap has palette entries or pixels | +| Aliases of stock art | at most 16 per appearance; an alias between differing layouts is re-encoded on the iPod and allowed for bitmaps of at most 3,840 pixels | +| Relight | bitmaps of at most 3,840 pixels; the bounds above | +| Colours | opaque `#rrggbb`; translucent roles are not supported | + +## Unsupported + +Fonts, layouts, metrics, animations, sounds, strings, wallpapers, new bitmaps, bitmaps of another size, translucent colours and appearances other than light and dark. diff --git a/themes/docs/bitmaps.md b/themes/docs/bitmaps.md new file mode 100644 index 0000000..e45da03 --- /dev/null +++ b/themes/docs/bitmaps.md @@ -0,0 +1,717 @@ +# Bitmaps + +Every bitmap of Apple's 2.0.5 firmware a theme can replace, from the +[catalog](catalog.md), grouped by name prefix. Size is width x height in +pixels. Palette is the number of native palette entries. Tintable says whether +`[.tint]` may name it. Appears is filled in by hand. + +Regenerate with `python3 tools/bitmaps_doc.py`; the Appears column survives. + +## Calendar + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `Calendar_Active_Cell` | 41x30 | indexed8 | 120 | yes | Calendar, days of the shown month | +| `Calendar_Alarm` | 18x18 | bgra8888 | - | yes | Calendar | +| `Calendar_Flag` | 11x12 | indexed8 | 19 | yes | Calendar | +| `Calendar_Hilite_Cell` | 41x30 | bgra8888 | - | yes | Calendar, the selected day | +| `Calendar_Inactive_Cell` | 41x30 | indexed8 | 40 | yes | Calendar, days of the neighbouring months | +| `Calendar_Small_Alarm` | 11x11 | bgra8888 | - | yes | Calendar | + +## CapacityView + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `CapacityView_Detailed_AudioCenter_Image` | 1x30 | bgra8888 | - | yes | Settings > About, the capacity bars | +| `CapacityView_Detailed_AudioLeft_Image` | 16x30 | indexed8 | 95 | yes | Settings > About, the capacity bars | +| `CapacityView_Detailed_AudioRight_Image` | 16x30 | indexed8 | 104 | yes | Settings > About, the capacity bars | +| `CapacityView_Detailed_Edge_Image` | 2x30 | indexed8 | 3 | yes | Settings > About, the capacity bars | +| `CapacityView_Detailed_EmptyCenter_Image` | 1x30 | bgra8888 | - | yes | Settings > About, the capacity bars | +| `CapacityView_Detailed_EmptyLeft_Image` | 16x30 | indexed8 | 76 | yes | Settings > About, the capacity bars | +| `CapacityView_Detailed_EmptyRight_Image` | 16x30 | indexed8 | 76 | yes | Settings > About, the capacity bars | +| `CapacityView_Detailed_OtherCenter_Image` | 1x30 | bgra8888 | - | yes | Settings > About, the capacity bars | +| `CapacityView_Detailed_OtherLeft_Image` | 16x30 | indexed8 | 101 | yes | Settings > About, the capacity bars | +| `CapacityView_Detailed_OtherRight_Image` | 16x30 | indexed8 | 97 | yes | Settings > About, the capacity bars | +| `CapacityView_Detailed_PhotosCenter_Image` | 1x30 | bgra8888 | - | yes | Settings > About, the capacity bars | +| `CapacityView_Detailed_PhotosLeft_Image` | 16x30 | indexed8 | 92 | yes | Settings > About, the capacity bars | +| `CapacityView_Detailed_PhotosRight_Image` | 16x30 | indexed8 | 107 | yes | Settings > About, the capacity bars | +| `CapacityView_Detailed_VideoCenter_Image` | 1x30 | bgra8888 | - | yes | Settings > About, the capacity bars | +| `CapacityView_Detailed_VideoLeft_Image` | 16x30 | indexed8 | 92 | yes | Settings > About, the capacity bars | +| `CapacityView_Detailed_VideoRight_Image` | 16x30 | indexed8 | 97 | yes | Settings > About, the capacity bars | +| `CapacityView_Simple_EmptyCenter_Image` | 1x13 | bgra8888 | - | yes | Settings > About, the capacity bars | +| `CapacityView_Simple_EmptyLeft_Image` | 9x13 | bgra8888 | - | yes | Settings > About, the capacity bars | +| `CapacityView_Simple_EmptyRight_Image` | 9x13 | bgra8888 | - | yes | Settings > About, the capacity bars | +| `CapacityView_Simple_FillCenter_Image` | 1x13 | bgra8888 | - | yes | Settings > About, the capacity bars | +| `CapacityView_Simple_FillLeft_Image` | 7x13 | bgra8888 | - | yes | Settings > About, the capacity bars | +| `CapacityView_Simple_FillRight_Image` | 7x13 | bgra8888 | - | yes | Settings > About, the capacity bars | + +## Caption + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `Caption_LeftEndcapBottom_Image` | 9x9 | mask4 | - | yes | Pane captions | +| `Caption_LeftEndcapTop_Image` | 9x9 | mask4 | - | yes | Pane captions | +| `Caption_RightEndcapBottom_Image` | 9x9 | mask4 | - | yes | Pane captions | +| `Caption_RightEndcapTop_Image` | 9x9 | mask4 | - | yes | Pane captions | + +## ChargingMode + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `ChargingMode_Image_Critical` | 205x163 | indexed16 | 5552 | yes | Charging screen | +| `ChargingMode_Image_Empty_CapLeft` | 38x142 | indexed16 | 1243 | yes | Charging screen | +| `ChargingMode_Image_Empty_CapRight` | 45x142 | indexed16 | 1497 | yes | Charging screen | +| `ChargingMode_Image_Empty_Middle` | 8x142 | indexed8 | 225 | yes | Charging screen | +| `ChargingMode_Image_Green_CapLeft` | 38x142 | indexed16 | 1380 | yes | Charging screen | +| `ChargingMode_Image_Green_CapRight` | 45x142 | indexed16 | 1619 | yes | Charging screen | +| `ChargingMode_Image_Green_Middle` | 8x142 | bgra8888 | - | yes | Charging screen | +| `ChargingMode_Image_Green_Middle_Cap` | 8x142 | bgra8888 | - | yes | Charging screen | +| `ChargingMode_Image_ToggleCharged` | 47x29 | mask4 | - | yes | Charging screen | +| `ChargingMode_Image_ToggleCharging` | 23x57 | mask4 | - | yes | Charging screen | + +## Clock + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `Clock_CenterCap_Image` | 73x73 | indexed8 | 9 | yes | Clock faces | +| `Clock_Hours_Image_0` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_1` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_2` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_3` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_4` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_5` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_6` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_7` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_8` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_9` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_10` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_11` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_12` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_13` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_14` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_15` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_16` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_17` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_18` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_19` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_20` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_21` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_22` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_23` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_24` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_25` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_26` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_27` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_28` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Hours_Image_29` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Large_Image` | 132x145 | indexed16 | 1781 | yes | Clock faces | +| `Clock_Mins_Image_0` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Mins_Image_1` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Mins_Image_2` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Mins_Image_3` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Mins_Image_4` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Mins_Image_5` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Mins_Image_6` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Mins_Image_7` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Mins_Image_8` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Mins_Image_9` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Mins_Image_10` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Mins_Image_11` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Mins_Image_12` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Mins_Image_13` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Mins_Image_14` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Mins_Image_15` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Secs_Image_0` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Secs_Image_1` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Secs_Image_2` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Secs_Image_3` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Secs_Image_4` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Secs_Image_5` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Secs_Image_6` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Secs_Image_7` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Secs_Image_8` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Secs_Image_9` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Secs_Image_10` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Secs_Image_11` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Secs_Image_12` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Secs_Image_13` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Secs_Image_14` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Secs_Image_15` | 73x73 | mask4 | - | yes | Clock faces | +| `Clock_Shadow_Image` | 8x26 | indexed8 | 27 | yes | Clock faces | +| `Clock_Small_Image` | 73x73 | indexed16 | 533 | yes | Clock faces | +| `Clock_Small_Night_Image` | 73x73 | indexed16 | 369 | yes | Clock faces | + +## DiskModeImage + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `DiskModeImage_ConnectedIcon` | 113x113 | indexed8 | 64 | yes | Disk Mode | +| `DiskModeImage_DisconnectIcon` | 112x112 | indexed8 | 95 | yes | Disk Mode | +| `DiskModeImage_Progress_Empty_Fill` | 1x12 | indexed8 | 4 | yes | Disk Mode | +| `DiskModeImage_Progress_Empty_LeftCap` | 8x12 | indexed8 | 38 | yes | Disk Mode | +| `DiskModeImage_Progress_Empty_RightCap` | 8x12 | bgra8888 | - | yes | Disk Mode | +| `DiskModeImage_Progress_Full_Fill` | 1x12 | bgra8888 | - | yes | Disk Mode | +| `DiskModeImage_Progress_Full_LeftCap` | 7x12 | bgra8888 | - | yes | Disk Mode | +| `DiskModeImage_Progress_Full_RightCap` | 7x12 | bgra8888 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow1` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow3` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow5` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow7` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow9` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow11` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow13` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow15` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow17` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow19` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow21` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow23` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow25` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow27` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow29` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow31` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow33` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncArrow35` | 76x76 | mask4 | - | yes | Disk Mode | +| `DiskModeImage_SyncIcon` | 112x112 | indexed16 | 1708 | yes | Disk Mode | + +## Genius + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `Genius_Slider_Endcap_Image` | 6x34 | bgra8888 | - | yes | Genius | +| `Genius_Slider_Fill_Image` | 1x34 | bgra8888 | - | yes | Genius | +| `Genius_Slider_Icon_Image` | 18x21 | indexed8 | 137 | yes | Genius | +| `Genius_Slider_Image` | 75x34 | indexed8 | 118 | yes | Genius | + +## Media + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `Media_AlbumsProxy_Image` | 55x55 | indexed8 | 202 | yes | Music lists, the proxy icons | +| `Media_AllAlbumsProxy_Image` | 55x55 | indexed16 | 576 | yes | Music lists, the proxy icons | +| `Media_ArtistsProxy_Image` | 55x55 | indexed8 | 203 | yes | Music lists, the proxy icons | +| `Media_AudioBooksProxy_Image` | 55x55 | indexed8 | 230 | yes | Music lists, the proxy icons | +| `Media_AudioProxy_Image` | 55x55 | indexed8 | 240 | yes | Music lists, the proxy icons | +| `Media_DocumentsProxy_Image` | 55x55 | indexed16 | 295 | yes | Music lists, the proxy icons | +| `Media_Genius_Large_Image` | 114x114 | indexed16 | 4069 | yes | Music lists, the proxy icons | +| `Media_Genius_Normal_Image` | 18x18 | bgra8888 | - | yes | Music lists, the proxy icons | +| `Media_Genius_Refresh_Hi_Image` | 15x18 | indexed8 | 90 | yes | Music lists, the proxy icons | +| `Media_Genius_Refresh_Image` | 15x18 | indexed8 | 90 | yes | Music lists, the proxy icons | +| `Media_Genius_Selected_Image` | 18x18 | bgra8888 | - | yes | Music lists, the proxy icons | +| `Media_MusicVideosProxy_Image` | 55x55 | indexed8 | 234 | yes | Music lists, the proxy icons | +| `Media_NowPlayingIcon_Black_Image` | 24x14 | indexed8 | 65 | yes | Music lists, the proxy icons | +| `Media_NowPlayingIcon_Playlist_Black_Image` | 17x14 | indexed8 | 65 | yes | Music lists, the proxy icons | +| `Media_NowPlayingIcon_Playlist_White_Image` | 17x16 | indexed8 | 64 | yes | Music lists, the proxy icons | +| `Media_NowPlayingIcon_White_Image` | 24x16 | indexed8 | 64 | yes | Music lists, the proxy icons | +| `Media_OTGPlaylist_Image` | 46x57 | indexed8 | 103 | yes | Music lists, the proxy icons | +| `Media_PhotosProxy_Image` | 55x55 | indexed16 | 309 | yes | Music lists, the proxy icons | +| `Media_PlaylistsProxy_Image` | 55x55 | indexed8 | 197 | yes | Music lists, the proxy icons | +| `Media_PodcastsProxy_Image` | 55x55 | indexed8 | 231 | yes | Music lists, the proxy icons | +| `Media_SearchProxy_Image` | 55x55 | indexed8 | 185 | yes | Music lists, the proxy icons | +| `Media_TVShowsProxy_Image` | 55x55 | indexed8 | 169 | yes | Music lists, the proxy icons | +| `Media_VideoStatusIcon_Image` | 23x29 | indexed8 | 4 | yes | Music lists, the proxy icons | +| `Media_VideoStatusIcon_White_Image` | 23x29 | indexed8 | 3 | yes | Music lists, the proxy icons | +| `Media_VideosProxy_Image` | 55x55 | indexed8 | 186 | yes | Music lists, the proxy icons | + +## No_Content + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `No_Content_Albums_Small_Image` | 55x55 | rgb565 | - | no | Empty lists | +| `No_Content_AudioBooks_Small_Image` | 55x55 | rgb565 | - | no | Empty lists | +| `No_Content_Audiobooks_Preview_Image` | 119x119 | mask8 | - | yes | Empty lists | +| `No_Content_Contacts_Preview_Image` | 200x145 | mask4 | - | yes | Empty lists | +| `No_Content_Movies_Preview_Image` | 119x119 | mask8 | - | yes | Empty lists | +| `No_Content_MusicVideos_Small_Image` | 55x55 | rgb565 | - | no | Empty lists | +| `No_Content_Music_Preview_Image` | 119x119 | mask8 | - | yes | Empty lists | +| `No_Content_Music_Video_Preview_Image` | 119x119 | mask8 | - | yes | Empty lists | +| `No_Content_Notes_Preview_Image` | 161x145 | mask4 | - | yes | Empty lists | +| `No_Content_Photo_Preview_Image` | 119x119 | mask8 | - | yes | Empty lists | +| `No_Content_Playlist_Preview_Image` | 119x119 | mask8 | - | yes | Empty lists | +| `No_Content_Podcast_Preview_Image` | 119x119 | mask8 | - | yes | Empty lists | +| `No_Content_Podcasts_Small_Image` | 55x55 | rgb565 | - | no | Empty lists | +| `No_Content_TVShow_Preview_Image` | 119x119 | mask8 | - | yes | Empty lists | +| `No_Content_TVShows_Small_Image` | 55x55 | rgb565 | - | no | Empty lists | +| `No_Content_Videos_Small_Image` | 55x55 | rgb565 | - | no | Empty lists | +| `No_Content_iTunesU_Preview_Image` | 119x119 | mask8 | - | yes | Empty lists | +| `No_Content_iTunesU_Small_Image` | 55x55 | rgb565 | - | no | Empty lists | + +## NowPlaying + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `NowPlaying_Black_FF_Image` | 14x16 | indexed8 | 12 | yes | Now Playing | +| `NowPlaying_Black_Pause_Image` | 14x16 | indexed8 | 3 | yes | Now Playing | +| `NowPlaying_Black_Play_Image` | 14x16 | indexed8 | 18 | yes | Now Playing | +| `NowPlaying_Black_Record_Image` | 13x13 | indexed8 | 73 | yes | Now Playing | +| `NowPlaying_Black_Rew_Image` | 14x16 | indexed8 | 12 | yes | Now Playing | +| `NowPlaying_Black_Volume_Locked_Image` | 19x17 | indexed8 | 10 | yes | Now Playing | +| `NowPlaying_Blue_Dot_Image` | 16x17 | indexed8 | 14 | yes | Now Playing | +| `NowPlaying_Blue_Star_Image` | 16x17 | indexed8 | 92 | yes | Now Playing | +| `NowPlaying_Chaptermark_Image` | 1x14 | bgra8888 | - | yes | Now Playing | +| `NowPlaying_Classic_Repeat_Image` | 19x15 | indexed8 | 25 | yes | Now Playing | +| `NowPlaying_Classic_Repeat_Once_Image` | 19x15 | indexed8 | 59 | yes | Now Playing | +| `NowPlaying_Classic_Shuffle_Image` | 18x14 | indexed8 | 68 | yes | Now Playing | +| `NowPlaying_Dot_Image` | 22x26 | indexed8 | 15 | yes | Now Playing | +| `NowPlaying_Genius_Icon` | 28x28 | bgra8888 | - | yes | Now Playing | +| `NowPlaying_Idle_Battery_0_Image` | 72x40 | indexed8 | 4 | yes | Now Playing, the idle battery | +| `NowPlaying_Idle_Battery_1_Image` | 72x40 | indexed8 | 2 | yes | Now Playing, the idle battery | +| `NowPlaying_Idle_Battery_2_Image` | 72x40 | indexed8 | 2 | yes | Now Playing, the idle battery | +| `NowPlaying_Idle_Battery_3_Image` | 72x40 | indexed8 | 2 | yes | Now Playing, the idle battery | +| `NowPlaying_Idle_Battery_4_Image` | 72x40 | indexed8 | 2 | yes | Now Playing, the idle battery | +| `NowPlaying_Idle_Battery_5_Image` | 72x40 | indexed8 | 2 | yes | Now Playing, the idle battery | +| `NowPlaying_Idle_Battery_6_Image` | 72x40 | indexed8 | 2 | yes | Now Playing, the idle battery | +| `NowPlaying_Idle_Battery_7_Image` | 72x40 | indexed8 | 2 | yes | Now Playing, the idle battery | +| `NowPlaying_Idle_Colon_Image` | 15x76 | indexed8 | 2 | yes | Now Playing | +| `NowPlaying_Idle_Digit_0_Image` | 38x76 | indexed8 | 2 | yes | Now Playing | +| `NowPlaying_Idle_Digit_1_Image` | 27x76 | indexed8 | 2 | yes | Now Playing | +| `NowPlaying_Idle_Digit_2_Image` | 39x76 | indexed8 | 2 | yes | Now Playing | +| `NowPlaying_Idle_Digit_3_Image` | 38x76 | indexed8 | 2 | yes | Now Playing | +| `NowPlaying_Idle_Digit_4_Image` | 38x76 | indexed8 | 2 | yes | Now Playing | +| `NowPlaying_Idle_Digit_5_Image` | 38x76 | indexed8 | 2 | yes | Now Playing | +| `NowPlaying_Idle_Digit_6_Image` | 38x76 | indexed8 | 2 | yes | Now Playing | +| `NowPlaying_Idle_Digit_7_Image` | 38x76 | indexed8 | 2 | yes | Now Playing | +| `NowPlaying_Idle_Digit_8_Image` | 38x76 | indexed8 | 2 | yes | Now Playing | +| `NowPlaying_Idle_Digit_9_Image` | 38x76 | indexed8 | 2 | yes | Now Playing | +| `NowPlaying_Idle_Lock_Image` | 25x38 | indexed8 | 6 | yes | Now Playing | +| `NowPlaying_Idle_Play_Image` | 41x43 | indexed8 | 2 | yes | Now Playing | +| `NowPlaying_Idle_Radio_Image` | 67x40 | indexed8 | 2 | yes | Now Playing | +| `NowPlaying_Large_Blue_Star_Image` | 22x26 | indexed8 | 226 | yes | Now Playing | +| `NowPlaying_Large_Shuffle_Image` | 25x19 | indexed8 | 91 | yes | Now Playing | +| `NowPlaying_Overlay_Image` | 8x37 | indexed8 | 38 | yes | Now Playing | +| `NowPlaying_Paused_Image` | 72x71 | indexed16 | 914 | yes | Now Playing | +| `NowPlaying_ProgressBar_Active_Background_Image` | 8x28 | indexed8 | 36 | yes | Now Playing | +| `NowPlaying_ProgressBar_Active_Fill_Image` | 8x28 | indexed8 | 29 | yes | Now Playing | +| `NowPlaying_ProgressBar_Active_Fill_Orange_Image` | 8x28 | indexed8 | 34 | yes | Now Playing | +| `NowPlaying_ProgressBar_Growth_Image` | 5x7 | indexed8 | 9 | yes | Now Playing | +| `NowPlaying_ProgressBar_Inactive_Background_Image` | 8x24 | indexed8 | 33 | yes | Now Playing | +| `NowPlaying_ProgressBar_Inactive_Fill_Image` | 8x24 | indexed8 | 37 | yes | Now Playing | +| `NowPlaying_ProgressBar_LeftEndcap_Image` | 12x7 | indexed8 | 35 | yes | Now Playing | +| `NowPlaying_ProgressBar_RightEndcap_Image` | 12x7 | indexed8 | 35 | yes | Now Playing | +| `NowPlaying_ProgressBar_Scrub_Image` | 13x28 | indexed8 | 129 | yes | Now Playing | +| `NowPlaying_ProgressFill_Growth_Image` | 2x7 | bgra8888 | - | yes | Now Playing | +| `NowPlaying_ProgressFill_LeftEndcap_Image` | 3x7 | bgra8888 | - | yes | Now Playing | +| `NowPlaying_ProgressFill_RightEndcap_Image` | 4x7 | bgra8888 | - | yes | Now Playing | +| `NowPlaying_Rental_Warning_Overlay_Fill` | 1x104 | bgra8888 | - | yes | Now Playing | +| `NowPlaying_Rental_Warning_Overlay_Left` | 9x104 | bgra8888 | - | yes | Now Playing | +| `NowPlaying_Rental_Warning_Overlay_Right` | 9x104 | bgra8888 | - | yes | Now Playing | +| `NowPlaying_Repeat_Image` | 20x14 | indexed8 | 28 | yes | Now Playing | +| `NowPlaying_Repeat_Once_Image` | 24x16 | indexed8 | 93 | yes | Now Playing | +| `NowPlaying_Scrub_Image` | 14x9 | indexed8 | 25 | yes | Now Playing | +| `NowPlaying_Shuffle_Image` | 18x16 | indexed8 | 68 | yes | Now Playing | +| `NowPlaying_Small_Grey_Star_Image` | 13x13 | indexed8 | 28 | yes | Now Playing | +| `NowPlaying_Small_White_Star_Image` | 13x13 | indexed8 | 28 | yes | Now Playing | +| `NowPlaying_Star_Image` | 13x13 | indexed8 | 28 | yes | Now Playing | +| `NowPlaying_StatusBar_Image` | 320x24 | indexed8 | 41 | yes | Stopwatch and Charging header | +| `NowPlaying_White_FF_Image` | 15x16 | bgra8888 | - | yes | Now Playing | +| `NowPlaying_White_Pause_Image` | 14x16 | indexed8 | 72 | yes | Now Playing | +| `NowPlaying_White_Play_Image` | 14x16 | bgra8888 | - | yes | Now Playing | +| `NowPlaying_White_Rew_Image` | 15x16 | bgra8888 | - | yes | Now Playing | +| `NowPlaying_White_Volume_High_Image` | 19x17 | indexed8 | 51 | yes | Now Playing | +| `NowPlaying_White_Volume_Locked_Image` | 19x17 | indexed8 | 11 | yes | Now Playing | +| `NowPlaying_White_Volume_Low_Image` | 9x17 | indexed8 | 25 | yes | Now Playing | + +## OptionBar + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `OptionBar_Black_Thumb_Center_Image` | 1x26 | bgra8888 | - | yes | Search letter strip and option bars | +| `OptionBar_Black_Thumb_LeftCap_Image` | 6x26 | bgra8888 | - | yes | Search letter strip and option bars | +| `OptionBar_Black_Thumb_RightCap_Image` | 6x26 | bgra8888 | - | yes | Search letter strip and option bars | +| `OptionBar_Black_Well_Center_Image` | 1x26 | bgra8888 | - | yes | Search letter strip and option bars | +| `OptionBar_Black_Well_LeftCap_Image` | 6x26 | bgra8888 | - | yes | Search letter strip and option bars | +| `OptionBar_Black_Well_RightCap_Image` | 6x26 | bgra8888 | - | yes | Search letter strip and option bars | +| `OptionBar_NowPlaying_Thumb_Center_Image` | 1x27 | bgra8888 | - | yes | Search letter strip and option bars | +| `OptionBar_NowPlaying_Thumb_LeftCap_Image` | 8x27 | indexed8 | 48 | yes | Search letter strip and option bars | +| `OptionBar_NowPlaying_Thumb_RightCap_Image` | 8x27 | indexed8 | 48 | yes | Search letter strip and option bars | +| `OptionBar_NowPlaying_Well_Center_Image` | 1x27 | bgra8888 | - | yes | Search letter strip and option bars | +| `OptionBar_NowPlaying_Well_LeftCap_Image` | 8x27 | indexed8 | 70 | yes | Search letter strip and option bars | +| `OptionBar_NowPlaying_Well_RightCap_Image` | 8x27 | indexed8 | 70 | yes | Search letter strip and option bars | +| `OptionBar_White_Thumb_Center_Image` | 1x29 | bgra8888 | - | yes | Search letter strip and option bars | +| `OptionBar_White_Thumb_LeftCap_Image` | 8x29 | bgra8888 | - | yes | Search letter strip and option bars | +| `OptionBar_White_Thumb_RightCap_Image` | 8x29 | bgra8888 | - | yes | Search letter strip and option bars | +| `OptionBar_White_Well_Center_Image` | 1x29 | bgra8888 | - | yes | Search letter strip and option bars | +| `OptionBar_White_Well_LeftCap_Image` | 8x29 | bgra8888 | - | yes | Search letter strip and option bars | +| `OptionBar_White_Well_RightCap_Image` | 8x29 | bgra8888 | - | yes | Search letter strip and option bars | + +## Playlist + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `Playlist_Folder_Icon` | 23x24 | bgra8888 | - | yes | Playlists | +| `Playlist_Genius_Icon` | 23x25 | bgra8888 | - | yes | Playlists | +| `Playlist_Genius_Icon_Hi` | 23x25 | bgra8888 | - | yes | Playlists | +| `Playlist_Regular_Icon` | 23x24 | bgra8888 | - | yes | Playlists | +| `Playlist_Saved_Genius_Icon` | 23x24 | bgra8888 | - | yes | Playlists | +| `Playlist_Smart_Icon` | 23x24 | bgra8888 | - | yes | Playlists | + +## Podcasts + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `Podcasts_new_item_Image` | 13x29 | indexed8 | 46 | yes | Podcasts | +| `Podcasts_new_item_video_Image` | 13x29 | indexed8 | 47 | yes | Podcasts | +| `Podcasts_new_item_video_white_Image` | 13x29 | indexed8 | 32 | yes | Podcasts | +| `Podcasts_new_item_white_Image` | 13x29 | indexed8 | 31 | yes | Podcasts | +| `Podcasts_spacer_Image` | 13x29 | indexed8 | 1 | yes | Podcasts | +| `Podcasts_video_solo_Image` | 13x29 | indexed8 | 4 | yes | Podcasts | +| `Podcasts_video_white_solo_Image` | 13x29 | indexed8 | 3 | yes | Podcasts | + +## Radio + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `Radio_Bottom_Background_Image` | 8x36 | indexed8 | 118 | yes | Radio | +| `Radio_Bottom_Bar_Image` | 320x5 | indexed8 | 150 | yes | Radio | +| `Radio_Current_Image` | 2x36 | bgra8888 | - | yes | Radio | +| `Radio_Digit_0_Image` | 42x98 | indexed8 | 90 | yes | Radio | +| `Radio_Digit_1_Image` | 32x98 | indexed8 | 70 | yes | Radio | +| `Radio_Digit_2_Image` | 39x98 | indexed8 | 83 | yes | Radio | +| `Radio_Digit_3_Image` | 39x98 | indexed8 | 93 | yes | Radio | +| `Radio_Digit_4_Image` | 39x98 | indexed8 | 79 | yes | Radio | +| `Radio_Digit_5_Image` | 39x98 | indexed8 | 92 | yes | Radio | +| `Radio_Digit_6_Image` | 39x98 | indexed8 | 93 | yes | Radio | +| `Radio_Digit_7_Image` | 39x98 | indexed8 | 79 | yes | Radio | +| `Radio_Digit_8_Image` | 39x98 | indexed8 | 90 | yes | Radio | +| `Radio_Digit_9_Image` | 39x98 | indexed8 | 88 | yes | Radio | +| `Radio_Digit_Period_Image` | 18x98 | indexed8 | 44 | yes | Radio | +| `Radio_Icon_Image` | 146x110 | indexed16 | 4401 | yes | Radio | +| `Radio_MHz_Image` | 63x44 | indexed8 | 84 | yes | Radio | +| `Radio_Preset_Image` | 11x11 | indexed8 | 19 | yes | Radio | +| `Radio_Scanning_1_Image` | 19x15 | indexed8 | 6 | yes | Radio | +| `Radio_Scanning_2_Image` | 19x15 | indexed8 | 7 | yes | Radio | +| `Radio_Scanning_3_Image` | 19x15 | indexed8 | 7 | yes | Radio | +| `Radio_Scanning_4_Image` | 19x15 | indexed8 | 7 | yes | Radio | +| `Radio_Scanning_5_Image` | 19x15 | indexed8 | 7 | yes | Radio | +| `Radio_Scanning_6_Image` | 19x15 | indexed8 | 7 | yes | Radio | +| `Radio_Scanning_7_Image` | 19x15 | indexed8 | 7 | yes | Radio | +| `Radio_Signal_Indicator_Dark_Image` | 20x16 | indexed8 | 35 | yes | Radio | +| `Radio_Signal_Indicator_Light_Image` | 20x16 | indexed8 | 101 | yes | Radio | +| `Radio_Ticks_Image` | 320x36 | mask4 | - | yes | Radio | +| `Radio_Ticks_Japan_Image` | 320x36 | mask4 | - | yes | Radio | + +## Settings + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `Settings_About_Band_Image` | 320x39 | indexed16 | 512 | yes | Settings pane previews | +| `Settings_About_Bubble_Deselected_Image` | 6x6 | indexed8 | 4 | yes | Settings pane previews | +| `Settings_About_Bubble_Selected_Image` | 6x6 | indexed8 | 4 | yes | Settings pane previews | +| `Settings_About_Capacity_AudioLegend_Image` | 12x12 | indexed8 | 36 | yes | Settings pane previews | +| `Settings_About_Capacity_Fill_Image` | 1x30 | bgra8888 | - | yes | Settings pane previews | +| `Settings_About_Capacity_LeftCap_Image` | 16x30 | indexed8 | 76 | yes | Settings pane previews | +| `Settings_About_Capacity_OtherLegend_Image` | 12x12 | indexed8 | 34 | yes | Settings pane previews | +| `Settings_About_Capacity_PhotosLegend_Image` | 12x12 | indexed8 | 26 | yes | Settings pane previews | +| `Settings_About_Capacity_RightCap_Image` | 16x30 | indexed8 | 76 | yes | Settings pane previews | +| `Settings_About_Capacity_VideoLegend_Image` | 12x12 | indexed8 | 34 | yes | Settings pane previews | +| `Settings_About_Logo_Image` | 64x72 | indexed16 | 906 | yes | Settings pane previews | +| `Settings_Accessory_TitleBand_Image` | 296x20 | indexed8 | 5 | yes | Settings pane previews | +| `Settings_AppleLogoPreview_Image` | 77x80 | mask8 | - | yes | Settings pane previews | +| `Settings_AppleLogo_Image` | 119x119 | mask8 | - | yes | Settings pane previews | +| `Settings_Audiobooks_Image` | 78x121 | mask8 | - | yes | Settings pane previews | +| `Settings_Backlight_2s_Image` | 78x121 | mask8 | - | yes | Settings > Backlight | +| `Settings_Backlight_5s_Image` | 78x121 | mask8 | - | yes | Settings > Backlight | +| `Settings_Backlight_10s_Image` | 78x121 | mask8 | - | yes | Settings > Backlight | +| `Settings_Backlight_20s_Image` | 78x121 | mask8 | - | yes | Settings > Backlight | +| `Settings_Backlight_30s_Image` | 78x121 | mask8 | - | yes | Settings > Backlight | +| `Settings_Backlight_Image` | 78x122 | mask4 | - | yes | Settings > Backlight | +| `Settings_Backlight_off_Image` | 78x121 | mask8 | - | yes | Settings > Backlight | +| `Settings_Backlight_on_Image` | 78x121 | mask8 | - | yes | Settings > Backlight | +| `Settings_BasePanelWide_Image` | 130x105 | indexed16 | 409 | yes | Settings pane previews | +| `Settings_BasePanel_Image` | 78x121 | indexed16 | 546 | yes | Settings pane previews | +| `Settings_Brightness_Image` | 78x121 | mask8 | - | yes | Settings > Brightness | +| `Settings_ClickerOff_Image` | 78x121 | mask8 | - | yes | Settings pane previews | +| `Settings_ClickerOn_Image` | 78x121 | mask8 | - | yes | Settings pane previews | +| `Settings_DateTime_Calendar_Image` | 130x128 | indexed16 | 298 | yes | Settings pane previews | +| `Settings_DateTime_Capsule_Hilite` | 40x37 | indexed8 | 141 | yes | Settings pane previews | +| `Settings_DateTime_Capsule_Image` | 167x57 | indexed16 | 540 | yes | Settings pane previews | +| `Settings_DateTime_TimeZonePin_Image` | 19x24 | indexed8 | 171 | yes | Settings pane previews | +| `Settings_EQ_Acoustic_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_BassBooster_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_BassReducer_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_Classical_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_Dance_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_Deep_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_Electronic_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_Flat_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_HipHop_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_Jazz_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_Latin_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_Loudness_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_Lounge_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_Piano_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_Pop_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_RandB_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_Rock_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_SmallSpeakers_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_SpokenWord_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_TrebleBooster_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_TrebleReducer_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_EQ_VocalBooster_Image` | 130x79 | mask4 | - | yes | Settings > EQ, the preset previews | +| `Settings_Language_Image` | 159x240 | indexed8 | 30 | yes | Settings pane previews | +| `Settings_Legal_Image` | 20x25 | indexed8 | 17 | yes | Settings pane previews | +| `Settings_MainMenu_CheckmarkBlack_Image` | 14x12 | indexed8 | 4 | yes | Settings pane previews | +| `Settings_MainMenu_CheckmarkWhite_Image` | 14x12 | indexed8 | 22 | yes | Settings pane previews | +| `Settings_MainMenu_Image` | 78x121 | mask4 | - | yes | Settings pane previews | +| `Settings_Radio_Image` | 78x121 | mask8 | - | yes | Settings pane previews | +| `Settings_RepeatAll_Image` | 78x121 | mask8 | - | yes | Settings pane previews | +| `Settings_RepeatOff_Image` | 78x121 | mask8 | - | yes | Settings pane previews | +| `Settings_RepeatOne_Image` | 78x121 | mask8 | - | yes | Settings pane previews | +| `Settings_Reset_Image` | 78x121 | mask8 | - | yes | Settings pane previews | +| `Settings_ShuffleOff_Image` | 78x121 | mask4 | - | yes | Settings pane previews | +| `Settings_ShuffleSongs_Image` | 78x121 | mask8 | - | yes | Settings pane previews | +| `Settings_SortBy_Image` | 78x121 | mask8 | - | yes | Settings pane previews | +| `Settings_SoundCheckOff_Image` | 78x121 | mask8 | - | yes | Settings pane previews | +| `Settings_SoundCheckOn_Image` | 78x121 | mask8 | - | yes | Settings pane previews | +| `Settings_VolumeLimitArrow_Image` | 9x5 | indexed8 | 6 | yes | Settings pane previews | +| `Settings_VolumeLimit_Image` | 78x121 | mask8 | - | yes | Settings pane previews | + +## StatusBarBlack + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `StatusBarBlack_Background_Image` | 320x24 | indexed8 | 79 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_0` | 26x13 | indexed8 | 27 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_1` | 26x13 | indexed8 | 27 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_2` | 26x13 | indexed8 | 27 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_3` | 26x13 | indexed8 | 5 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_4` | 26x13 | indexed8 | 6 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_5` | 26x13 | indexed8 | 5 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_6` | 26x13 | indexed8 | 4 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_7` | 26x13 | indexed8 | 4 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_8` | 26x13 | indexed8 | 4 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_9` | 26x13 | indexed8 | 4 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_10` | 26x13 | indexed8 | 4 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_11` | 26x13 | indexed8 | 4 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_12` | 26x13 | indexed8 | 4 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_13` | 26x13 | indexed8 | 4 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_14` | 26x13 | indexed8 | 4 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_15` | 26x13 | indexed8 | 4 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_16` | 26x13 | indexed8 | 4 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_17` | 26x13 | indexed8 | 4 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_18` | 26x13 | indexed8 | 4 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_19` | 26x13 | indexed8 | 4 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_20` | 26x13 | indexed8 | 4 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_21` | 26x13 | indexed8 | 4 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_22` | 26x13 | indexed8 | 4 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_Charge` | 26x13 | indexed8 | 41 | yes | Status bar on dark screens | +| `StatusBarBlack_Battery_Image_Plug` | 26x13 | indexed8 | 34 | yes | Status bar on dark screens | +| `StatusBarBlack_Lock_Image` | 11x16 | indexed8 | 14 | yes | Status bar on dark screens | + +## StatusBarWhite + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `StatusBarWhite_Background_Image` | 320x20 | indexed8 | 20 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_0` | 26x13 | indexed8 | 62 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_1` | 26x13 | indexed8 | 84 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_2` | 26x13 | indexed8 | 85 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_3` | 26x13 | indexed8 | 87 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_4` | 26x13 | indexed8 | 88 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_5` | 26x13 | indexed8 | 91 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_6` | 26x13 | indexed8 | 90 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_7` | 26x13 | indexed8 | 92 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_8` | 26x13 | indexed8 | 89 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_9` | 26x13 | indexed8 | 92 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_10` | 26x13 | indexed8 | 95 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_11` | 26x13 | indexed8 | 89 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_12` | 26x13 | indexed8 | 93 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_13` | 26x13 | indexed8 | 91 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_14` | 26x13 | indexed8 | 90 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_15` | 26x13 | indexed8 | 88 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_16` | 26x13 | indexed8 | 89 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_17` | 26x13 | indexed8 | 90 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_18` | 26x13 | indexed8 | 85 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_19` | 26x13 | indexed8 | 87 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_20` | 26x13 | indexed8 | 88 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_21` | 26x13 | indexed8 | 78 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_22` | 26x13 | indexed8 | 68 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_Charge` | 26x13 | indexed8 | 55 | yes | Status bar on light screens | +| `StatusBarWhite_Battery_Image_Plug` | 26x13 | indexed8 | 45 | yes | Status bar on light screens | +| `StatusBarWhite_Lock_Image` | 13x16 | indexed8 | 41 | yes | Status bar on light screens | +| `StatusBarWhite_PlayStatus_Image` | 14x16 | bgra8888 | - | yes | Status bar on light screens | + +## Stopwatch + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `Stopwatch_Caps_Image` | 123x123 | indexed8 | 42 | yes | Stopwatch | +| `Stopwatch_Clock_Image` | 145x181 | indexed16 | 2895 | yes | Stopwatch | +| `Stopwatch_Mins_Image_0` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_1` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_2` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_3` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_4` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_5` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_6` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_7` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_8` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_9` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_10` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_11` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_12` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_13` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_14` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_15` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_16` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_17` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_18` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_19` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_20` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_21` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_22` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_23` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_24` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_25` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_26` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_27` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_28` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Mins_Image_29` | 18x18 | mask4 | - | yes | Stopwatch | +| `Stopwatch_PlayPause_Image` | 104x76 | indexed16 | 897 | yes | Stopwatch | +| `Stopwatch_Secs_Image_0` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_1` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_2` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_3` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_4` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_5` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_6` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_7` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_8` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_9` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_10` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_11` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_12` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_13` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_14` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_15` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_16` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_17` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_18` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_19` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_20` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_21` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_22` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_23` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_24` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_25` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_26` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_27` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_28` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_Secs_Image_29` | 124x124 | mask4 | - | yes | Stopwatch | +| `Stopwatch_SmallPause_Image` | 23x17 | indexed8 | 5 | yes | Stopwatch | +| `Stopwatch_SmallPlay_Image` | 23x17 | indexed8 | 22 | yes | Stopwatch | + +## System + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `System_ActiveButtonFill_Image` | 1x22 | bgra8888 | - | yes | | +| `System_ActiveButtonLeftCap_Image` | 5x22 | bgra8888 | - | yes | | +| `System_ActiveButtonRightCap_Image` | 5x22 | bgra8888 | - | yes | | +| `System_Input_Field_Left_Image` | 10x26 | indexed8 | 49 | yes | | +| `System_Input_Field_Middle_Image` | 10x26 | indexed8 | 14 | yes | Search, the text typed into the box | +| `System_Input_Field_Right_Image` | 10x26 | indexed8 | 52 | yes | | +| `System_NormalButtonFill_Image` | 1x26 | bgra8888 | - | yes | | +| `System_NormalButtonLeftCap_Image` | 6x26 | bgra8888 | - | yes | | +| `System_NormalButtonRightCap_Image` | 6x26 | bgra8888 | - | yes | | +| `System_Overlay_BrightnessLess_Image` | 12x13 | indexed8 | 20 | yes | | +| `System_Overlay_BrightnessMore_Image` | 17x17 | indexed8 | 14 | yes | | +| `System_Overlay_Left_Image` | 8x80 | indexed8 | 188 | yes | | +| `System_Overlay_Middle_Image` | 9x80 | indexed8 | 41 | yes | | +| `System_Overlay_Right_Image` | 8x80 | indexed8 | 188 | yes | | +| `System_Overlay_VolumeLeft_Image` | 15x13 | indexed8 | 32 | yes | | +| `System_Overlay_VolumeRight_Image` | 19x17 | indexed8 | 63 | yes | | +| `System_QuickScroll_123_Image` | 74x70 | mask4 | - | yes | | +| `System_QuickScroll_Image` | 74x70 | indexed8 | 168 | yes | | +| `System_ScrollbarBottom_Image` | 6x9 | indexed8 | 7 | yes | | +| `System_ScrollbarCenter_Image` | 6x8 | indexed8 | 2 | yes | | +| `System_ScrollbarTop_Image` | 6x10 | indexed8 | 7 | yes | | +| `System_Submenu_Image` | 10x15 | indexed8 | 34 | yes | | + +## TVOut + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `TVOut_30_Pin_Connector_Image` | 86x98 | indexed16 | 295 | yes | TV Out | +| `TVOut_Background_LeftCap_Image` | 24x48 | indexed8 | 181 | yes | TV Out | +| `TVOut_Background_Middle_Image` | 1x48 | indexed8 | 10 | yes | TV Out | +| `TVOut_Background_RightCap_Image` | 24x48 | indexed8 | 176 | yes | TV Out | +| `TVOut_Charge_Image_Clear_Middle` | 4x50 | indexed8 | 12 | yes | TV Out | +| `TVOut_Charge_Image_Left` | 20x50 | indexed8 | 132 | yes | TV Out | +| `TVOut_Charge_Image_Right` | 20x50 | indexed8 | 135 | yes | TV Out | +| `TVOut_Charge_Image_Set_Middle` | 4x50 | indexed8 | 12 | yes | TV Out | +| `TVOut_Duration_Center_Image` | 1x22 | indexed8 | 3 | yes | TV Out | +| `TVOut_Duration_RightCap_Image` | 10x22 | indexed8 | 52 | yes | TV Out | +| `TVOut_Duration_Scrub_Image` | 20x22 | indexed8 | 9 | yes | TV Out | +| `TVOut_Duration_White_Center_Image` | 1x22 | indexed8 | 4 | yes | TV Out | +| `TVOut_Duration_White_LeftCap_Image` | 10x22 | indexed8 | 67 | yes | TV Out | +| `TVOut_Duration_White_RightCap_Image` | 10x22 | indexed8 | 16 | yes | TV Out | +| `TVOut_FF_Image` | 70x50 | indexed16 | 363 | yes | TV Out | +| `TVOut_Pause_Image` | 70x50 | indexed16 | 303 | yes | TV Out | +| `TVOut_Rew_Image` | 70x50 | indexed16 | 373 | yes | TV Out | +| `TVOut_Volume_Full_Image` | 40x39 | indexed8 | 129 | yes | TV Out | +| `TVOut_Volume_Off_Image` | 42x39 | indexed8 | 70 | yes | TV Out | + +## VoiceMemosImage + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `VoiceMemosImage_Colon` | 7x33 | indexed8 | 28 | yes | Voice Memos | +| `VoiceMemosImage_Meter` | 127x167 | indexed16 | 4454 | yes | Voice Memos | +| `VoiceMemosImage_Microphone` | 110x190 | indexed16 | 2852 | yes | Voice Memos | +| `VoiceMemosImage_Pause` | 86x145 | indexed16 | 796 | yes | Voice Memos | +| `VoiceMemosImage_Reflect_0` | 20x50 | indexed8 | 73 | yes | Voice Memos | +| `VoiceMemosImage_Reflect_1` | 20x50 | indexed8 | 56 | yes | Voice Memos | +| `VoiceMemosImage_Reflect_2` | 20x50 | indexed8 | 66 | yes | Voice Memos | +| `VoiceMemosImage_Reflect_3` | 20x50 | indexed8 | 77 | yes | Voice Memos | +| `VoiceMemosImage_Reflect_4` | 20x50 | indexed8 | 62 | yes | Voice Memos | +| `VoiceMemosImage_Reflect_5` | 20x50 | indexed8 | 70 | yes | Voice Memos | +| `VoiceMemosImage_Reflect_6` | 20x50 | indexed8 | 72 | yes | Voice Memos | +| `VoiceMemosImage_Reflect_7` | 20x50 | indexed8 | 61 | yes | Voice Memos | +| `VoiceMemosImage_Reflect_8` | 20x50 | indexed8 | 74 | yes | Voice Memos | +| `VoiceMemosImage_Reflect_9` | 20x50 | indexed8 | 73 | yes | Voice Memos | + +## Other + +| Name | Size | Format | Palette | Tintable | Appears | +|---|---|---|---|---|---| +| `AddressViewer_NoContactPict_Image` | 55x55 | indexed8 | 216 | yes | Contacts | +| `AddressViewer_NoGroupPict_Image` | 55x55 | indexed16 | 274 | yes | Contacts | +| `AddressViewer_Preview_Image` | 130x146 | indexed16 | 4177 | yes | Contacts | +| `Alarms_Clock_Static_Image` | 127x135 | indexed16 | 5199 | yes | Clock > Alarms | +| `Alarms_Timer_Time_Panel` | 163x53 | indexed16 | 485 | yes | Clock > Alarms | +| `Alarms_Timer_Time_Panel_Focus` | 40x37 | indexed8 | 141 | yes | Clock > Alarms | +| `Background_LightBlue_Image` | 320x240 | indexed16 | 1530 | yes | Background behind the Settings previews | +| `BigDaisyPetal0` | 3x12 | mask4 | - | yes | Activity spinner | +| `BigDaisyPetal1` | 9x13 | mask4 | - | yes | Activity spinner | +| `BigDaisyPetal2` | 12x9 | mask4 | - | yes | Activity spinner | +| `BigDaisyPetal3` | 12x3 | mask4 | - | yes | Activity spinner | +| `BigDaisyPetal4` | 12x9 | mask4 | - | yes | Activity spinner | +| `BigDaisyPetal5` | 9x13 | mask4 | - | yes | Activity spinner | +| `CoverFlow_Backside_Top_Image` | 8x43 | indexed8 | 69 | yes | Cover Flow, the track list behind a cover | +| `CoverFlow_Proxy_Image` | 128x128 | rgb565 | - | no | Cover Flow | +| `CoverFlow_Proxy_Image_iTunesU` | 128x128 | rgb565 | - | no | Cover Flow | +| `DateTimePicker_Bar` | 167x57 | indexed16 | 361 | yes | Date and time picker | +| `DateTimePicker_Selection` | 40x37 | indexed8 | 141 | yes | Date and time picker, the selected value | +| `DateTimePicker_Well` | 40x41 | indexed8 | 211 | yes | Date and time picker, the values | +| `DemoMode_Icon` | 97x97 | indexed16 | 869 | yes | | +| `Extras_Games_Preview_Image` | 142x87 | indexed16 | 5662 | yes | | +| `Games_Proxy_Image` | 55x55 | indexed16 | 519 | yes | | +| `GeniusMixes_Background_Image` | 8x240 | indexed8 | 47 | yes | Genius | +| `LockScreen_Padlock_Image` | 116x165 | indexed16 | 3250 | yes | Screen Lock | +| `LockScreen_TumblerBgnd_Image` | 182x57 | indexed16 | 372 | yes | Screen Lock and Volume Limit, the combination digits | +| `LockScreen_TumblerFocus_Image` | 26x54 | indexed8 | 174 | yes | Screen Lock and Volume Limit, the focused digit | +| `Lozenge_Left_White_Image` | 15x58 | indexed8 | 182 | yes | Lozenges | +| `Lozenge_Middle_White_Image` | 16x58 | indexed8 | 97 | yes | Lozenges | +| `Lozenge_Right_White_Image` | 15x58 | indexed8 | 177 | yes | Lozenges | +| `MainMenu_Backlight_Image` | 119x119 | mask8 | - | yes | Main menu | +| `MainMenu_Shuffle_Image` | 119x119 | mask8 | - | yes | Main menu | +| `MainMenu_Sleep_Image` | 98x146 | mask8 | - | yes | Main menu | +| `Notes_Preview_Image` | 120x146 | indexed16 | 5841 | yes | | +| `Page_White_Active_Image` | 8x8 | indexed8 | 5 | yes | Page indicators | +| `Page_White_Inactive_Image` | 8x8 | indexed8 | 8 | yes | Page indicators | +| `Photos_Slideshow_Top_Strip` | 1x88 | indexed8 | 4 | yes | | +| `PreviewArea_Shadow_Image` | 26x240 | indexed8 | 40 | yes | | +| `RemoteUI_Icon_Apple` | 113x113 | indexed8 | 184 | yes | | +| `Speakers_Icon_Image` | 159x240 | indexed16 | 3155 | yes | | +| `WorldClock_Graybar_Image` | 5x80 | indexed8 | 67 | yes | Clock, world clocks | +| `WorldClock_Map_Image` | 320x240 | mask4 | - | yes | Clock, world clocks | diff --git a/themes/docs/catalog.md b/themes/docs/catalog.md new file mode 100644 index 0000000..77be994 --- /dev/null +++ b/themes/docs/catalog.md @@ -0,0 +1,87 @@ +# Catalog + +The compiler ships two catalogs: Apple's bitmaps in `rvt/data/osos-2.0.5.json` and the first-party extension bitmaps in `rvt/data/extensions.json`. + +## Apple's bitmaps + +`rvt/data/osos-2.0.5.json` lists every `BMap` bitmap of Apple's 2.0.5 firmware a theme can replace. Records and tint bytes refer to bitmaps by their index in this list. The fingerprint in the `.rvt` header makes the Appearance extension refuse a file built against a different list. + +### Fields + +| Field | Contents | +|---|---| +| `schema` | 1 | +| `firmware` | File name, version, byte count and SHA-256 of the decrypted `osos.bin` the offsets refer to | +| `runtime_base`, `runtime_file_offset` | How a file offset becomes an address, below | +| `fingerprint` | The fingerprint of `bitmaps`, below | +| `bitmaps` | The entries, in firmware order | + +Each entry: + +| Key | Contents | +|---|---| +| `id` | Resource id | +| `name` | Resource name, what `theme.toml` and the art files use | +| `offset` | File offset of the bitmap header in `osos.bin` | +| `address` | Where the bitmap lives at run time | +| `bytes` | Bitmap size including its header | +| `format`, `depth` | Native pixel format and bits per pixel: 4 and 8 are masks, 0x64 and 0x65 are paletted, 0x565 is RGB565, 0x1888 is BGRA8888 | +| `width`, `height`, `stride` | Pixel size and row bytes | +| `data_offset` | Where a theme record starts: after the header and, for paletted formats, the colour count | +| `pixels_offset` | Where the rows start, after any palette | +| `palette_colors` | Palette entries, 0 for formats without one | +| `crc32` | CRC-32 of the whole bitmap, for checking the firmware the theme is applied to | + +### Addresses + +Apple loads `osos.bin` at `0x08000000` with the file's first `0xb798` bytes stripped (`OSOS_RUNTIME_FILE_OFFSET` in the core), so + +``` +address = runtime_base + offset - runtime_file_offset +``` + +### Fingerprint + +The first 8 bytes of the SHA-256 of the entry list, serialised as JSON with sorted keys and no whitespace. `rvt.catalog.fingerprint` computes it. + +### Browsing + +`rvt catalog list` prints one line per bitmap, filtered by name prefix with `--group` or by format with `--format`. `rvt catalog show ` prints every field of one bitmap. [Bitmaps](bitmaps.md) is the same list as a page. + +### Provenance + +`rvt/data/osos-2.0.5.json` was produced once from the core repository's former `firmware/bitmaps.json`, the bitmap table its old theme compiler read out of the 2.0.5 resource index (core commit 41ac06e, before both were removed). RepriseOS supports only that firmware, so no regeneration is expected; a catalog for another image would need a walker over its resource index. The fingerprint ties every theme to this catalog, and the Appearance extension compiles the same file into its own table, so a changed catalog means recompiling every theme and the extension. + +## Extension asset catalog + +`rvt/data/extensions.json` lists every bitmap of the first-party extensions and the core, one JSON object per line, sorted by id then asset. The compiler uses it to check art sizes, tell Settings icons from pictures and name bitmaps in `rvt inspect`. A bitmap not in it compiles only as a 78 x 121 Settings icon, with a warning. `--extension assets.json` on `compile`, `check`, `inspect` and `catalog` adds another extension's bitmaps. Its author generates the file from the built package: + +```sh +python3 /assets.py manifest.toml build/.rvx > assets.json +``` + +A later record for the same id and asset replaces an earlier one. + +| Key | Contents | +|---|---| +| `id` | The extension's id; `reprise` is the reserved owner id of the core's own bitmaps | +| `asset` | The asset's name in the manifest | +| `menu` | `true` for a Settings icon (`menu = true` in the manifest): a 78 x 121 coverage mask | +| `format`, `depth` | The BMap format word and bits per pixel as the extension ships it: 8 Mask8, 0x64 Indexed8, 0x1888 BGRA8888 | +| `width`, `height`, `stride` | Pixel size and row bytes | +| `palette_colors` | Palette entries, 0 without one | +| `bytes` | The decoded BMap, header included | +| `preload` | `always`, `optional` or `never`: whether the core loads it with the extension's main module (`preload` in the manifest) | + +`rvt catalog list --extensions [--group ]` prints one line per bitmap, and `rvt catalog show /` prints every field and the two hashes. [Extension bitmaps](extension-bitmaps.md) is the same list as a page. + +### Regenerating + +`make` at the repository root writes `build/assets.json` with the core's and every built extension's bitmaps. Then, from the `themes/` directory: + +```sh +python3 tools/extensions_catalog.py # rvt/data/extensions.json, by id then asset +python3 tools/extension_bitmaps_doc.py # docs/extension-bitmaps.md +``` + +Regenerate when an extension adds, removes or resizes a bitmap asset. `tests/test_assets.py` checks that the committed catalog matches the build and the committed page matches the generator. diff --git a/themes/docs/extension-bitmaps.md b/themes/docs/extension-bitmaps.md new file mode 100644 index 0000000..554ea58 --- /dev/null +++ b/themes/docs/extension-bitmaps.md @@ -0,0 +1,28 @@ +# Extension bitmaps + +The first-party extension bitmaps a theme can replace with +`/extensions//.png`, or `/reprise/.png` +for the core's (id `reprise`). See [Authoring](authoring.md#extension-bitmaps). +Size is width x height in pixels, which the art must match. Menu marks a +Settings icon, a 78 x 121 coverage mask drawn in the icon tint. + +The catalog and how to regenerate it are in +[Catalog](catalog.md#extension-asset-catalog). + +Regenerate this page with `python3 tools/extension_bitmaps_doc.py`. + +| Id | Asset | Size | Format | Palette | Menu | +|---|---|---|---|---|---| +| `appearance` | `settings-accent` | 78x121 | mask8 | - | yes | +| `appearance` | `settings-appearance` | 78x121 | mask8 | - | yes | +| `appearance` | `settings-cover` | 78x121 | mask8 | - | yes | +| `appearance` | `settings-covers` | 78x121 | mask8 | - | yes | +| `appearance` | `settings-moon` | 78x121 | mask8 | - | yes | +| `appearance` | `settings-theme` | 78x121 | mask8 | - | yes | +| `balance` | `settings-balance` | 78x121 | mask8 | - | yes | +| `crossfeed` | `settings-crossfeed` | 78x121 | mask8 | - | yes | +| `equalizer` | `settings-eq` | 78x121 | mask8 | - | yes | +| `homebrew` | `apps` | 142x87 | bgra8888 | - | no | +| `night-shift` | `settings-night-shift` | 78x121 | mask8 | - | yes | +| `playback-log` | `settings-playback-log` | 78x121 | mask8 | - | yes | +| `reprise` | `settings-info` | 78x121 | mask8 | - | yes | diff --git a/themes/docs/format.md b/themes/docs/format.md new file mode 100644 index 0000000..e724eb1 --- /dev/null +++ b/themes/docs/format.md @@ -0,0 +1,111 @@ +# File format + +A theme is one file, `/Reprise/Themes/.rvt`: a header, then optional light and dark appearance packs. [`rvt/data/rvt.h`](../rvt/data/rvt.h) is the contract. The Appearance extension vendors it byte for byte, and `rvt/rvtfile.py` parses every `RVT_*` value from it. Integers are little-endian. + +## Header + +The offsets are the `RVT_HEADER_*` defines. + +| Offset | Size | Field | +|---|---|---| +| 0 | 4 | `"RVT0"` | +| 4 | u16 | Version, `RVT_VERSION` (3); a reader accepts exactly this value | +| 6 | u16 | Header bytes, where the packs begin | +| 8 | 8 | Catalog fingerprint, see [Catalog](catalog.md) | +| 16 | u32 | Appearances present: `RVT_APPEARANCE_LIGHT`, `RVT_APPEARANCE_DARK` | +| 20 | u32 x 4 | Light offset and bytes, dark offset and bytes; 0 when absent | +| 36 | u32 | CRC-32 of the first `RVT_HEADER_BYTES` (128) bytes with this word as zero | +| 40 | 32 | Id, `[a-z0-9][a-z0-9_-]{0,30}`, NUL-padded; the file's stem | +| 72 | 48 | Name, UTF-8, NUL-padded | +| 120 | 8 | Zero, up to `RVT_HEADER_BYTES`; a reader does not check them | + +The light pack starts at the header bytes, and the dark pack follows it, 4-byte aligned. A pack's bytes include its header. A reader places the packs by the header bytes field, not the constant, and skips fields it does not know in a longer header. The CRC always covers the first 128 bytes only. + +## Pack + +The offsets are the `RVT_PACK_*` defines. + +| Offset | Size | Field | +|---|---|---| +| 0 | u32 | Body bytes, at least `RVT_STYLE_BYTES` | +| 4 | u32 | Record count | +| 8 | u32 | CRC-32 of the body | +| 12 | u32 | Extension bitmap count, at most `RVT_EXTENSION_BITMAPS_MAX` (64) | +| 16 | | Body: the style prefix, the records, then the extension bitmaps | + +A pack is at least `RVT_PACK_HEADER_BYTES` (16) plus `RVT_STYLE_BYTES` long. + +## Style prefix + +`RVT_STYLE_BYTES` (856), at the `RVT_STYLE_*` offsets. Every colour is R, G, B, A with A = 255. + +| Offset | Size | Field | +|---|---|---| +| 0 | 8 x 4 | Colour roles in `enum rvt_role` order: background, text, accent fill, accent text, on accent, selection, cover border, icon tint | +| 32 | u32 | Rendering flags: `RVT_FLAG_FLAT_SELECTION`, `RVT_FLAG_MENU_COVERS_OFF`, `RVT_FLAG_FLAT_NOW_PLAYING`, `RVT_FLAG_FLAT_ICONS` | +| 36 | 9 x 5 x 4 | One palette per accent in `enum rvt_accent` order, each in `enum rvt_accent_slot` order: accent fill, accent text, selection, on accent, icon tint; a slot replaces the role of its name while that accent is picked | +| 216 | `RVT_CATALOG_MAX` | One tint byte per catalog index: `RVT_TINT_NONE`, or `RVT_TINT_ROLE` plus an `rvt_role`, or-ed with `RVT_TINT_DARKNESS` when the coverage comes from darkness or with `RVT_TINT_SOLID` when every level from `RVT_SOLID_FLOOR` up is full, never both. A reader packs the roles two per byte, so `RVT_TINT_ROLE + RVT_ROLES` stays at most 16 | + +## Records + +Records follow in ascending catalog index, each index at most once: + +| Size | Field | +|---|---| +| u32 | Catalog index | +| u32 | Kind, `enum rvt_kind` | +| u32 | Payload bytes | +| bytes | Payload, zero-padded to 4 | + +| Kind | Payload | The iPod writes | +|---|---|---| +| `pixels` | The native bytes from `data_offset` to the end: palette and rows | them in place | +| `pixels_lz` | The same bytes as an lz stream; the payload bytes are the stream's size | them in place while decoding | +| `recolor` | u32 count, then count × (`from` RGBA, `to` RGBA), strictly ascending by `from` as a little-endian u32, no `from` equal to its `to`; count 1..`RVT_RECOLOR_MAX` | each palette entry, BGRA8888 pixel or RGB565 word equal to a `from` as its `to` | +| `alias` | u32 source catalog index | the source's bytes after its header when the layouts are equal, else its pixels re-encoded in this bitmap's format; after every other record of the pack | +| `invert` | none | RGB inverted, alpha kept | +| `relight` | `RVT_RELIGHT_WORDS` × i32, 8.8 fixed point, `enum rvt_relight` order | grays per [Relight](#relight) below, a palette of the distinct grays in ascending order with zeros after it, and the rows re-indexed | + +The pixel kinds replace the stock bytes. The other kinds are computed from them, so the iPod restores a bitmap from its firmware before deriving it. The compiler writes `pixels_lz` when the stream is smaller than the raw bytes. + +**lz stream.** The layout is the core's (`rvx-sdk/rvx.h`, summarised in `rvt.h`). Each group is a flag byte and up to 8 items, bit 0 first. A clear bit is a literal byte. A set bit is a two-byte match `LLLLDDDD DDDDDDDD` copying L + 3 bytes from D + 1 bytes back in the output; when L = 15, following bytes are added to the length while they are 255, plus the first that is not. Matches copy from the output itself. The stream has no length field: a decoder stops after the bitmap's bytes (catalog size minus `data_offset`), and the stream must end exactly at the record's end. A stream that ends early, overruns the output or copies from before its start makes the record invalid. The palette-index check and the pack CRC apply to the stored bytes. + +**Tint bytes.** On a paletted or BGRA8888 bitmap without a record, a tint byte tints the stock bitmap with the coverage its `RVT_TINT_DARKNESS` or `RVT_TINT_SOLID` bit names. With a pixel record, the coverage is the record's alpha. A tint byte on a derived bitmap is invalid. On a mask, a tint byte needs no record and keeps the stock levels unless it carries `RVT_TINT_SOLID`, which rewrites them (a 4-bit level counts as level x 17). RGB565 bitmaps take no tint. + +**Derived records.** `recolor` on RGB565 uses opaque, 5-6-5-exact colours. `invert` and `alias` are not for masks. `relight` needs a paletted bitmap of at most `RVT_SCRATCH_PIXELS` pixels with a palette of at least `icon_hi − bg_lo + 1` entries. A pack has at most `RVT_ALIASES_MAX` aliases, and an alias source is neither an alias nor tinted. An alias between equal layouts is a byte copy. Between differing layouts the iPod re-encodes the source's pixels, for bitmaps of at most `RVT_SCRATCH_PIXELS` pixels. If the source has more colours than a paletted target holds, the alias fails and the stock bitmap stays. + +## Relight + +Every word is 8.8 fixed point; `luma = (77 r + 150 g + 29 b) >> 8`. The iPod rejects the record unless `0 <= t_zero < t_full <= 255`, `0 <= bg_lo <= bg_hi <= icon_lo <= icon_hi <= 255`, `|bg_base|` and `|icon_base|` are at most 1024, `|bg_ref|`, `|icon_luma|` and `|icon_row|` at most 255, and `|bg_slope|` at most 16, in pixel units before scaling. + +For each row, the stock pixel in column 0 is the background `bg`. A pixel's offset `o` is its largest channel difference from `bg`, and `t = clamp((o - t_zero) / (t_full - t_zero), 0, 1)` is how much of it is icon. A pixel with `0 < t < 1` and no 8-neighbour at `t = 1` is a drop shadow and takes `t = 0`. Then: + +- `bg_dark = clamp(bg_base + (luma(bg) - bg_ref) * bg_slope, bg_lo, bg_hi)` +- `icon_dark = clamp(icon_base + icon_luma * luma(c) + icon_row * y, icon_lo, icon_hi)` +- the pixel is `bg_dark + (icon_dark - bg_dark) * t`, rounded, opaque. + +The palette becomes the distinct grays in ascending order with zeros after them, and the rows are re-indexed. `rvt.derive` is the reference; the iPod's division must match it byte for byte. + +`from_other` art ([Authoring](authoring.md#derived-art)) is computed by the compiler and stored as a pixel record. One pack never refers into the other. + +## Extension bitmaps + +The extension bitmaps ([Authoring](authoring.md#extension-bitmaps)) follow the last record, ascending by owner then asset, each pair once, at most `RVT_EXTENSION_BITMAPS_MAX` (64) per pack. Each has a `RVT_EXTENSION_BITMAP_BYTES` (24) header: + +| Size | Field | +|---|---| +| u32 | Owner: FNV-1a of the extension id; the core's own bitmaps are owned by the hash of `reprise`, the reserved owner id of the core in the theme format | +| u32 | Asset: FNV-1a of the asset name | +| u32 | Kind, `enum rvt_extension_kind`: `RVT_EXTENSION_BITMAP` (1) the bitmap raw, `RVT_EXTENSION_BITMAP_LZ` (2) the bitmap as one lz stream | +| u32 | Stored bytes: the payload's length | +| u32 | Decoded bytes: the bitmap's length | +| u32 | Tint: `RVT_TINT_NONE` (0), or `RVT_TINT_ROLE` plus an `rvt_role` without coverage bits for a picture the reader paints in that role | +| bytes | Payload, zero-padded to 4 | + +A bitmap is the whole BMap as the iPod decodes it: the `RVT_BMAP_HEADER_BYTES` (28) header (format, reserved, stride, depth, bounds top, left, bottom, right, payload bytes), then the palette and rows. The payload is the bitmap raw (stored equals decoded) or one lz stream that decodes to exactly the decoded bytes and is at most those plus one flag byte per 8. The lz stream is the same as in `pixels_lz`, and the compiler uses it when it is smaller. + +The decoded bytes are at most `RVT_EXTENSION_BITMAP_MAX_BYTES` (65,536) and equal the header plus its payload bytes. A reader checks the header as the core does and rejects the bitmap unless the bounds are in order and within 16 bits, the depth is at most 32, a row fits the stride, and an Indexed8 palette of at most 256 entries and the rows fit the payload. + +A Settings icon has the menu header: Mask8 (8), stride 80, depth 8, bounds 0, 0, 121, 78, 9,680 payload bytes. A tinted bitmap is an Indexed8 or BGRA8888 picture, never a Settings icon. Its palette entries or pixels carry the coverage in their alpha with a placeholder colour, which the reader replaces with the role's colour at each decode. + +The hashes are the core's FNV-1a of the extension id and asset name (`rvx-sdk/rvx.py`, `fnv1a`). The pack CRC covers the extension bitmaps with the records. diff --git a/themes/docs/toolchain.md b/themes/docs/toolchain.md new file mode 100644 index 0000000..685ccf7 --- /dev/null +++ b/themes/docs/toolchain.md @@ -0,0 +1,84 @@ +# The compiler + +`rvt` is a Python 3.11+ package without dependencies. Run it from the `themes/` directory as `python3 -m rvt`. Only `preview` and `recolor` need a firmware. + +## Commands + +| Command | Does | +|---|---| +| `rvt new [--name NAME]` | Writes `/theme.toml` with every role and option as a comment, and the empty `apple/`, `reprise/` and `extensions/` folders of `/light/` and `/dark/`; `reprise` is the reserved owner id of the core's own bitmaps in the theme format | +| `rvt check ` | Compiles without writing; prints what each derive rule matched, the warnings and a size table per appearance | +| `rvt compile [--out DIR]` | The same, then writes `//.rvt` and `report.json`; `--out` defaults to `dist` | +| `rvt inspect [--json]` | Validates an `.rvt` against the catalog and describes it; extension bitmaps are named from the extension asset catalog, by their hashes when it does not know them | +| `rvt catalog list [--group PREFIX] [--format FMT]` | One line per Apple bitmap: name, size, format, palette entries, tintable | +| `rvt catalog list --extensions [--group ID] [--format FMT]` | One line per extension bitmap: id, asset, size, format, palette entries, menu or bitmap | +| `rvt catalog show ` | Every catalog field of one Apple bitmap, by name or hex id | +| `rvt catalog show /` | Every catalog field of one extension bitmap, and its two hashes | +| `rvt preview --firmware FILE` | Renders every derived bitmap of a theme from a decrypted `osos.bin` or the booted `reprise.bin` to `dist//derived/` | +| `rvt recolor --firmware FILE` | Turns `//apple/.png` into a `recolor` rule file when the PNG is a pure recolour of the stock bitmap | + +| Option | On | Does | +|---|---|---| +| `--strict` | `check`, `compile`, `preview` | Turns warnings into errors | +| `--catalog FILE` | all but `new` | Uses another Apple catalog | +| `--extension assets.json` | `check`, `compile`, `preview`, `inspect`, `catalog` | Adds an extension's bitmaps ([Catalog](catalog.md#extension-asset-catalog)); repeatable | +| `--allow-reserved` | `check`, `compile`, `preview` | Accepts the id `classic` | + +Warnings cover: + +- a PNG with more colours than its native palette (reduced to fit) +- a text and background pair the theme colours that falls below 4.5:1 +- a tint glob that matches nothing +- a Settings icon with nothing below its art box while `flat_icons` is off +- an extension bitmap not in the catalog (compiled as a Settings icon) + +`report.json` has the theme's id, name, author and version and, per appearance: + +| Key | Contents | +|---|---| +| `contrast` | Contrast of every text and background pair, for Theme Default and each accent | +| `accents_builtin` | Accents using the built-in colours | +| `records` | Record count per kind | +| `extension_bitmaps` | Extension bitmap count per kind | +| `extension_tinted` | Tinted extension bitmaps and their roles | +| `palette_reduced` | Palette reductions | + +It also has each appearance's size in bytes. The output is deterministic, with sorted keys. + +## Layout + +| Path | Contents | +|---|---| +| `rvt/rvtfile.py` | The `.rvt` header and packs; every constant parsed from `rvt/data/rvt.h` | +| `rvt/data/` | The vendored contracts: the format header, the two catalogs and the SDK's bitmap encoder | +| `rvt/data/rvt.h` | The file format; the Appearance extension compiles against this header | +| `rvt/data/osos-2.0.5.json` | The [catalog](catalog.md) of Apple's bitmaps | +| `rvt/data/extensions.json` | The [extension asset catalog](catalog.md#extension-asset-catalog): the bitmaps of the first-party extensions | +| `rvt/data/bitmap.py` | The SDK's bitmap encoder, a byte copy of the SDK's `bitmap.py` | +| `rvt/catalog.py` | Catalog loading, lookup, the fingerprint | +| `rvt/theme.py` | `theme.toml`: validation and the resolution of colours, accents, tints and rules | +| `rvt/bitmaps.py` | PNG reading, palette fitting, the native pixel formats | +| `rvt/style.py` | The colours, rendering, accent palettes and tint bytes of an appearance; the Classic colours and the built-in accents | +| `rvt/derive.py` | Derivation rules, record payloads and the reference arithmetic of the iPod's derivations | +| `rvt/lz.py` | The core's lz codec | +| `rvt/assets.py` | Extension bitmaps: the folders, encoding, the extension asset catalog, the hashes and the pack table | +| `rvt/errors.py` | `fail`, the one error every check raises | +| `rvt/compiler.py`, `rvt/inspector.py` | Folder to bytes, bytes to a checked description | +| `rvt/firmware.py` | Stock bitmaps from a local firmware for `preview` and `recolor` | +| `rvt/cli.py` | The commands | +| `tests/` | Host tests against a synthetic catalog; a few compare the encoder and lz copies with the SDK checkout `SDK` names, the accent table with the Appearance extension and the extension asset catalog with the build | +| `tools/bitmaps_doc.py` | Writes [Bitmaps](bitmaps.md) from the catalog | +| `tools/extensions_catalog.py` | Writes `rvt/data/extensions.json` from the build's `assets.json`, see [Catalog](catalog.md#extension-asset-catalog) | +| `tools/extension_bitmaps_doc.py` | Writes [Extension bitmaps](extension-bitmaps.md) from `rvt/data/extensions.json` | +| `themes/` | The first-party themes; `themes/classic/recolor.py` generates Classic's recolour rules (needs `--firmware`), `themes/classic/fit.py` snaps Classic's PNGs to their palettes | + +## Tests + +From the repository root, after `make` (the build writes `build/assets.json` and compiles Classic with `--strict`): + +```sh +SDK=../osos-lab/rvx-sdk python3 -m unittest discover -s themes/tests +ruff check . && ruff format --check themes tools tests +``` + +CI runs both on Python 3.12 with the pinned SDK checkout. diff --git a/themes/rvt/__init__.py b/themes/rvt/__init__.py new file mode 100644 index 0000000..9ee5f12 --- /dev/null +++ b/themes/rvt/__init__.py @@ -0,0 +1,2 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""RepriseOS theme compiler: theme.toml folders in, .rvt files out.""" diff --git a/themes/rvt/__main__.py b/themes/rvt/__main__.py new file mode 100644 index 0000000..aa16d39 --- /dev/null +++ b/themes/rvt/__main__.py @@ -0,0 +1,4 @@ +# SPDX-License-Identifier: GPL-3.0-only +from rvt.cli import main + +main() diff --git a/themes/rvt/assets.py b/themes/rvt/assets.py new file mode 100644 index 0000000..c05d76a --- /dev/null +++ b/themes/rvt/assets.py @@ -0,0 +1,474 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""Extension bitmaps: /extensions//.png and +/reprise/.png for the core's own. + +A theme replaces any bitmap asset of an extension, a Settings icon or a canvas +bitmap, with a whole BMap the iPod uses as it would the extension's own: the +28-byte header, then the palette and rows. The compiler encodes a PNG with the +SDK's own encoder, rvt/data/bitmap.py, vendored byte for byte from +rvx-sdk/bitmap.py: `encode_mask` for a pane icon (a 78 x 121 coverage +mask, Mask8, stride 80), `encode_bmap` for any other (Indexed8 with a palette +up to 256 colours, else BGRA8888, rows padded to 4 bytes). The pack stores the +header raw and the rows raw or as one lz stream, at most the rows plus one flag +byte per 8, keyed by the FNV-1a hashes of the extension id and the asset name, +as the core keys them. + +Which (id, asset) pairs exist and what size they are comes from the extension +asset catalog, rvt/data/extensions.json for the first-party extensions, plus +any `--extension assets.json` additions; docs/catalog.md. +""" + +import json +import re +import struct +from importlib.resources import files +from pathlib import Path + +from rvt import bitmaps, lz, rvtfile +from rvt.data import bitmap +from rvt.errors import fail + +HEADER = bitmap.HEADER +MASK8, INDEXED8, BGRA8888 = bitmap.MASK8, bitmap.INDEXED8, bitmap.BGRA8888 +MENU_WIDTH, MENU_HEIGHT = bitmap.ICON_SIZE +MENU_STRIDE = (MENU_WIDTH + 3) & ~3 +MENU_HEADER = HEADER.pack( + MASK8, 0, MENU_STRIDE, 8, 0, 0, MENU_HEIGHT, MENU_WIDTH, MENU_STRIDE * MENU_HEIGHT +) +FORMAT_NAMES = {MASK8: "mask8", INDEXED8: "indexed8", BGRA8888: "bgra8888"} +# The art box of a Settings icon; the rows below it hold the reflection. +ART_ROWS = 79 + +if HEADER.size != rvtfile.BMAP_HEADER_BYTES: + raise ValueError("rvt/data/rvt.h and rvt/data/bitmap.py disagree on the header") + +FOLDER = "extensions" +CORE_ID = "reprise" +# The core's own bitmaps, owned by the id reprise, have their own folder beside +# apple/ and extensions/. +CORE_FOLDER = CORE_ID +ID_PATTERN = re.compile(r"[a-z][a-z0-9_-]{0,31}") +ASSET_PATTERN = re.compile(r"[a-z0-9_-]{1,31}") +PNG_LIMIT = 16 * 1024 * 1024 +CATALOG = files("rvt") / "data" / "extensions.json" +RECORD_KEYS = ( + "id", + "asset", + "menu", + "format", + "width", + "height", + "stride", + "depth", + "palette_colors", + "bytes", + "preload", +) +PRELOAD = ("always", "optional", "never") + + +def owner_hash(identifier: str) -> int: + return rvtfile.fnv1a(identifier.encode()) + + +def asset_hash(asset: str) -> int: + return rvtfile.fnv1a(asset.encode()) + + +# The extension asset catalog + + +def check_record(record: dict, where: str) -> dict: + """A catalog record with exactly the known keys and plausible values.""" + if not isinstance(record, dict) or tuple(sorted(record)) != tuple( + sorted(RECORD_KEYS) + ): + fail(where, f"expected a record with the keys {', '.join(RECORD_KEYS)}") + if not isinstance(record["id"], str) or not ID_PATTERN.fullmatch(record["id"]): + fail(where, f"id must match {ID_PATTERN.pattern}") + if not isinstance(record["asset"], str) or not ASSET_PATTERN.fullmatch( + record["asset"] + ): + fail(where, f"asset must match {ASSET_PATTERN.pattern}") + if not isinstance(record["menu"], bool): + fail(where, "menu is true or false") + if record["preload"] not in PRELOAD: + fail(where, f"preload is one of {', '.join(PRELOAD)}") + for key in ( + "format", + "width", + "height", + "stride", + "depth", + "palette_colors", + "bytes", + ): + value = record[key] + if isinstance(value, bool) or not isinstance(value, int) or value < 0: + fail(where, f"{key} is a non-negative integer") + if not record["width"] or not record["height"]: + fail(where, "width and height are at least 1") + if record["menu"] and (record["width"], record["height"]) != ( + MENU_WIDTH, + MENU_HEIGHT, + ): + fail(where, f"a menu bitmap is {MENU_WIDTH}x{MENU_HEIGHT}") + return record + + +def read_json(path: Path) -> list[dict]: + """The records of an assets.json, one JSON object per line.""" + records = [] + for number, line in enumerate(path.read_text().splitlines(), 1): + if not line.strip(): + continue + try: + record = json.loads(line) + except ValueError as error: + fail(f"{path}:{number}", str(error)) + records.append(check_record(record, f"{path}:{number}")) + return records + + +def load_catalog(extensions: list[Path] = ()) -> dict[tuple[str, str], dict]: + """(id, asset) -> record: the vendored first-party catalog, then every + `--extension assets.json` in order, a later record for a pair replacing an + earlier one.""" + records = {} + sources = [Path(str(CATALOG)), *(Path(p) for p in extensions)] + for number, path in enumerate(sources): + if number and path.suffix != ".json": + fail("--extension", f"{path}: expected an assets.json") + if number and not path.is_file(): + fail("--extension", f"{path} does not exist") + for record in read_json(path): + records[record["id"], record["asset"]] = record + return records + + +def known_names(records: dict[tuple[str, str], dict]) -> dict[tuple[int, int], str]: + """(owner hash, asset hash) -> "id/asset" for the catalog's records.""" + return { + (owner_hash(identifier), asset_hash(asset)): f"{identifier}/{asset}" + for identifier, asset in records + } + + +def label(asset: dict, names: dict[tuple[int, int], str]) -> str: + return names.get( + (asset["owner"], asset["asset"]), + f"{asset['owner']:#010x}/{asset['asset']:#010x}", + ) + + +# The theme folder + + +def find_sources(folder: Path, appearance: str) -> dict[tuple[str, str], Path]: + """(id, asset) -> PNG path: /extensions//.png and + the core's /reprise/.png.""" + root = Path(folder).resolve() + found = {} + + def add(owner: str, directory: Path, where: str) -> None: + for path in sorted(directory.iterdir()): + at = f"{where}/{path.name}" + if path.name.startswith("."): + continue + if path.suffix != ".png" or not ASSET_PATTERN.fullmatch(path.stem): + fail( + at, + f"expected .png with the asset matching {ASSET_PATTERN.pattern}", + ) + found[owner, path.stem] = source_file(path, root, at, PNG_LIMIT) + + core = root / appearance / CORE_FOLDER + if core.is_dir(): + add(CORE_ID, core, f"{appearance}/{CORE_FOLDER}") + directory = root / appearance / FOLDER + if not directory.is_dir(): + return found + for owner in sorted(directory.iterdir()): + where = f"{appearance}/{FOLDER}/{owner.name}" + if owner.name.startswith("."): + continue + if not owner.is_dir(): + fail( + where, + f"expected a folder named after an extension id ({ID_PATTERN.pattern})", + ) + if owner.name == CORE_ID: + fail( + where, + f"{CORE_ID} is the core's id; its bitmaps go in " + f"{appearance}/{CORE_FOLDER}/", + ) + if not ID_PATTERN.fullmatch(owner.name): + fail(where, f"expected an extension id matching {ID_PATTERN.pattern}") + add(owner.name, owner, where) + return found + + +def source_file(path: Path, root: Path, where: str, limit: int) -> Path: + """The resolved path of an art or rule file: a plain file inside the theme + folder of at most `limit` bytes.""" + try: + resolved = path.resolve(strict=True) + except OSError: + fail(where, "does not exist") + if not resolved.is_relative_to(root) or not resolved.is_file(): + fail(where, "must be a file inside the theme folder") + if resolved.stat().st_size > limit: + fail(where, f"exceeds {limit:,} bytes") + return resolved + + +def source_path(appearance: str, identifier: str, asset: str) -> str: + """Where the PNG of (id, asset) sits in the theme, for messages; without + an appearance, the path below it.""" + folder = CORE_FOLDER if identifier == CORE_ID else f"{FOLDER}/{identifier}" + return "/".join(part for part in (appearance, folder, f"{asset}.png") if part) + + +# Encoding + + +def encode( + path: Path, where: str, record: dict | None, tint: str | None = None +) -> bytes: + """The whole BMap of a PNG: the SDK's menu rule for a catalog record with + `menu`, else its picture rule at the record's size. Without a record a + 78 x 121 coverage PNG is a menu bitmap; anything else needs the catalog. + A picture tinted on the iPod is read as coverage and stored in the + placeholder colour `tint`, which the iPod rewrites with the role's.""" + try: + width, height, rgba = bitmaps.read_png(path.read_bytes()) + except ValueError as error: + fail(where, str(error)) + if record is None and (width, height) != (MENU_WIDTH, MENU_HEIGHT): + fail( + where, + f"{width}x{height} is not a menu bitmap and the asset is not in the " + "extension asset catalog; pass --extension assets.json of the extension", + ) + menu = record is None or record["menu"] + if not menu and (width, height) != (record["width"], record["height"]): + fail( + where, + f"expected {record['width']}x{record['height']}, got {width}x{height}", + ) + if tint is not None and menu: + fail(where, "a Settings icon is drawn in the icon tint already; no tint role") + try: + if tint is not None: + rgba = bitmaps.tinted_pixels(bitmaps.coverage(rgba), tint) + encoder = bitmap.encode_mask if menu else bitmap.encode_bmap + data = encoder(width, height, rgba) + except ValueError as error: + fail(where, str(error)) + if len(data) > rvtfile.EXTENSION_BITMAP_MAX_BYTES: + fail( + where, + f"{len(data):,} bytes exceed {rvtfile.EXTENSION_BITMAP_MAX_BYTES:,}", + ) + return data + + +def is_menu(bmap: bytes) -> bool: + """True when the header is the menu header the pane slot accepts.""" + return bmap[: HEADER.size] == MENU_HEADER + + +def has_reflection(bmap: bytes) -> bool: + """True when a menu bitmap's rows below the art box carry anything.""" + return any(bmap[HEADER.size + ART_ROWS * MENU_STRIDE :]) + + +def check_collisions(names: list[tuple[str, str]]) -> None: + """Two (id, asset) pairs of a theme whose hashes agree would stand for one + bitmap on the iPod.""" + seen: dict[tuple[int, int], tuple[str, str]] = {} + for identifier, asset in names: + key = (owner_hash(identifier), asset_hash(asset)) + other = seen.setdefault(key, (identifier, asset)) + if other != (identifier, asset): + fail( + source_path("", identifier, asset), + f"its hashes collide with {source_path('', *other)}; rename one", + ) + + +# The table in the pack + +KIND_NAMES = {value: name for name, value in rvtfile.EXTENSION_KINDS.items()} + + +def tint_byte(role: str) -> int: + """The tint word of a picture drawn in `role`: no coverage bits, the + coverage is the art's alpha.""" + return rvtfile.TINT_ROLE + rvtfile.ROLES.index(role) + + +def tint_role(word: int, where: str) -> str | None: + """The role a tint word names, None for RVT_TINT_NONE.""" + if word == rvtfile.TINT_NONE: + return None + if not rvtfile.TINT_ROLE <= word < rvtfile.TINT_ROLE + len(rvtfile.ROLES): + fail(where, f"unknown tint {word:#x}") + return rvtfile.ROLES[word - rvtfile.TINT_ROLE] + + +def tintable(bmap: bytes) -> bool: + """Whether the iPod can paint a bitmap in a role: an Indexed8 or BGRA8888 + picture, not a Settings icon, which the core draws in the icon tint.""" + fmt = HEADER.unpack_from(bmap)[0] + return fmt in (INDEXED8, BGRA8888) and not is_menu(bmap) + + +def encode_table( + bmaps: dict[tuple[str, str], bytes], + tints: dict[tuple[str, str], str] | None = None, +) -> tuple[bytes, int, dict[str, int]]: + """The extension bitmap table of (id, asset) -> whole BMap, ascending by + the hashes, each as one lz stream when that is smaller, with the tint byte + of the role `tints` gives it; its bytes, its count and the count per kind + name.""" + tints = tints or {} + if len(bmaps) > rvtfile.EXTENSION_BITMAPS_MAX: + fail( + FOLDER, + f"{len(bmaps)} extension bitmaps exceed {rvtfile.EXTENSION_BITMAPS_MAX}", + ) + table = bytearray() + counts: dict[str, int] = {} + ordered = sorted( + bmaps.items(), key=lambda item: (owner_hash(item[0][0]), asset_hash(item[0][1])) + ) + for (identifier, asset), bmap in ordered: + name, data = "bitmap", bmap + packed = lz.lz_encode(bmap) + if len(packed) < len(bmap): + name, data = "bitmap_lz", packed + counts[name] = counts.get(name, 0) + 1 + role = tints.get((identifier, asset)) + table += rvtfile.EXTENSION_BITMAP.pack( + owner_hash(identifier), + asset_hash(asset), + rvtfile.EXTENSION_KINDS[name], + len(data), + len(bmap), + rvtfile.TINT_NONE if role is None else tint_byte(role), + ) + table += data + table += bytes(-len(table) % 4) + return bytes(table), len(bmaps), counts + + +def header_sane(bmap: bytes) -> bool: + """core_bitmap_whole: bounds in order and within 16 bits, depth at most + 32, a row of pixels within the stride, the palette within the payload and + the rows within what is left.""" + fmt, _, stride, depth, top, left, bottom, right, payload = HEADER.unpack_from(bmap) + height, width = bottom - top, right - left + palette = 0 + if fmt == INDEXED8: + colors = ( + struct.unpack_from("= 4 else 0x10000 + ) + palette = 4 + 4 * colors if colors <= 256 else payload + 1 + return ( + bottom >= top + and right >= left + and height <= 0xFFFF + and width <= 0xFFFF + and depth <= 32 + and width * depth <= stride * 8 + and palette <= payload + and height * stride <= payload - palette + ) + + +def describe(bmap: bytes) -> dict: + """Size, format name and palette of a BMap, for inspection.""" + fmt, _, _, _, top, left, bottom, right, _ = HEADER.unpack_from(bmap) + palette = 0 + if fmt == INDEXED8: + palette = struct.unpack_from(" tuple[list[dict], int]: + """The `count` extension bitmaps starting at `at`, each checked: known + kind, ascending unique (owner, asset), a decoded size within the cap, a + payload of the whole BMap raw at that size or as an lz stream no longer + than it plus a flag byte per 8 that decodes to exactly it, a header that + describes exactly that many bytes, zero padding. Returns the bitmaps, each + with its decoded whole BMap as `bmap`, and the offset after the last.""" + if count > rvtfile.EXTENSION_BITMAPS_MAX: + fail(where, f"{count} extension bitmaps exceed {rvtfile.EXTENSION_BITMAPS_MAX}") + found = [] + previous = None + for _ in range(count): + if at + rvtfile.EXTENSION_BITMAP_BYTES > len(body): + fail(where, "truncated extension bitmap header") + owner, asset, kind, stored, decoded, tint = ( + rvtfile.EXTENSION_BITMAP.unpack_from(body, at) + ) + name = f"extension bitmap {owner:#010x}/{asset:#010x}" + role = tint_role(tint, f"{where}: {name}") + if previous is not None and (owner, asset) <= previous: + fail(where, "extension bitmaps must be sorted by unique owner and asset") + previous = (owner, asset) + if kind not in KIND_NAMES: + fail(where, f"{name} has unknown kind {kind:#x}") + at += rvtfile.EXTENSION_BITMAP_BYTES + if decoded <= HEADER.size: + fail(where, f"{name}: decoded size smaller than a header") + if decoded > rvtfile.EXTENSION_BITMAP_MAX_BYTES: + fail( + where, + f"{name}: {decoded:,} bytes exceed {rvtfile.EXTENSION_BITMAP_MAX_BYTES:,}", + ) + end = at + stored + if rvtfile.align(end) > len(body): + fail(where, f"{name}: truncated payload") + bmap = body[at:end] + if KIND_NAMES[kind] == "bitmap_lz": + if stored > decoded + (decoded + 7) // 8: + fail(where, f"{name}: lz stream longer than its bitmap allows") + try: + bmap = lz.lz_decode(bmap, decoded) + except ValueError as error: + fail(where, f"{name}: {error}") + elif stored != decoded: + fail(where, f"{name}: raw payload is not its decoded size") + if HEADER.size + HEADER.unpack_from(bmap)[8] != decoded or not header_sane( + bmap + ): + fail(where, f"{name}: bitmap header does not describe its bytes") + if any(body[end : rvtfile.align(end)]): + fail(where, f"{name}: padding must be zero") + if role is not None and not tintable(bmap): + fail(where, f"{name}: tinted, but not an Indexed8 or BGRA8888 picture") + found.append( + { + "owner": owner, + "asset": asset, + "kind": KIND_NAMES[kind], + "bytes": stored, + "decoded": decoded, + "tint": role, + "bmap": bmap, + **describe(bmap), + } + ) + at = rvtfile.align(end) + return found, at diff --git a/themes/rvt/bitmaps.py b/themes/rvt/bitmaps.py new file mode 100644 index 0000000..c8ead9f --- /dev/null +++ b/themes/rvt/bitmaps.py @@ -0,0 +1,407 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""PNG reading and the native BMap pixel formats a theme can replace. + +A BMap is a 28-byte header (format, stride, depth, bounds, payload bytes), for +paletted formats a 32-bit colour count and the palette as B, G, R, A, then the +rows, each padded to the stride. The 32-bit format stores B, G, R, A too. A theme record carries everything after the +header (and after the colour count, which never changes), so a replacement is +the same size as the original and the device copies it in place. + +Adapted from the RepriseOS core's themes/compiler.py and patching/bitmap.py (8fc840d) by +lgreitis. +""" + +import struct +import zlib +from collections import Counter + +MASK4, MASK8 = 4, 8 +INDEXED8, INDEXED16 = 0x64, 0x65 +RGB565 = 0x565 +BGRA8888 = 0x1888 +MASK_FORMATS = (MASK4, MASK8) +PALETTE_FORMATS = (INDEXED8, INDEXED16) +BGRA_FORMATS = (BGRA8888,) +DEPTHS = {MASK4: 4, MASK8: 8, INDEXED8: 8, INDEXED16: 16, RGB565: 16, BGRA8888: 32} + + +def paeth(a, b, c): + p = a + b - c + return min((a, b, c), key=lambda value: abs(p - value)) + + +def read_png(data: bytes) -> tuple[int, int, bytes]: + """Width, height and RGBA bytes of a PNG.""" + if data[:8] != b"\x89PNG\r\n\x1a\n": + raise ValueError("not a PNG") + chunks = {} + offset = 8 + while offset < len(data): + if offset + 8 > len(data): + raise ValueError("truncated PNG") + size, kind = struct.unpack_from(">I4s", data, offset) + if offset + 12 + size > len(data): + raise ValueError("truncated PNG") + body = data[offset + 8 : offset + 8 + size] + crc = struct.unpack_from(">I", data, offset + 8 + size)[0] + if zlib.crc32(kind + body) != crc: + raise ValueError("PNG chunk checksum mismatch") + chunks.setdefault(kind, bytearray()).extend(body) + offset += size + 12 + if b"IEND" not in chunks or len(chunks.get(b"IHDR", b"")) != 13: + raise ValueError("truncated PNG") + width, height, depth, color, compression, filtering, interlace = struct.unpack( + ">IIBBBBB", chunks[b"IHDR"] + ) + channels = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}.get(color) + if ( + not width + or not height + or not (depth == 8 or color == 3 and depth in (1, 2, 4)) + or channels is None + or any((compression, filtering, interlace)) + ): + raise ValueError("export a non-interlaced PNG with 8-bit channels or a palette") + try: + raw = zlib.decompress(chunks.get(b"IDAT", b"")) + except zlib.error: + raise ValueError("truncated PNG") from None + stride = (width * channels * depth + 7) // 8 + filter_bytes = max(1, (channels * depth + 7) // 8) + if len(raw) != (stride + 1) * height: + raise ValueError("PNG pixel length does not match its dimensions") + palette = chunks.get(b"PLTE", b"") + alpha = chunks.get(b"tRNS", b"") + transparent = ( + tuple(struct.unpack(">" + "H" * channels, alpha)) + if alpha and color in (0, 2) + else None + ) + previous = bytearray(stride) + pixels = bytearray() + for y in range(height): + start = y * (stride + 1) + filter_type = raw[start] + if filter_type > 4: + raise ValueError("unknown PNG row filter") + row = bytearray(raw[start + 1 : start + 1 + stride]) + for x in range(stride): + a = row[x - filter_bytes] if x >= filter_bytes else 0 + b = previous[x] + c = previous[x - filter_bytes] if x >= filter_bytes else 0 + predictor = (0, a, b, (a + b) // 2, paeth(a, b, c))[filter_type] + row[x] = (row[x] + predictor) & 255 + for x in range(width): + p = tuple(row[x * channels : (x + 1) * channels]) + if color == 3: + bit = x * depth + index = (row[bit // 8] >> (8 - depth - bit % 8)) & ((1 << depth) - 1) + if index * 3 + 3 > len(palette): + raise ValueError("PNG pixel exceeds palette") + rgba = ( + *palette[index * 3 : index * 3 + 3], + alpha[index] if index < len(alpha) else 255, + ) + elif color in (0, 4): + rgba = ( + p[0], + p[0], + p[0], + p[1] if color == 4 else 0 if p == transparent else 255, + ) + else: + rgba = p if color == 6 else (*p, 0 if p == transparent else 255) + pixels.extend(rgba) + previous = row + return width, height, bytes(pixels) + + +def describe(resource_id: int, offset: int, data: bytes, name: str = "") -> dict: + """Catalog entry of a native BMap from its bytes.""" + if len(data) < 28: + raise ValueError(f"{resource_id:#x}: truncated bitmap") + fmt, _, stride, depth = struct.unpack_from("<4H", data) + height, width = struct.unpack_from(" 1 << depth) or stride < (width * depth + 7) // 8: + raise ValueError(f"{resource_id:#x}: invalid palette or stride") + if pixels + stride * height != len(data): + raise ValueError(f"{resource_id:#x}: invalid pixel storage") + return { + "id": resource_id, + "name": name, + "offset": offset, + "bytes": len(data), + "format": fmt, + "depth": depth, + "width": width, + "height": height, + "stride": stride, + "data_offset": start + (4 if colors else 0), + "pixels_offset": pixels, + "palette_colors": colors, + "crc32": zlib.crc32(data), + } + + +def tint_kind(fmt: int) -> str | None: + """How a format takes a tint: masks at draw time, palettes and BGRA8888 + pixels by rewriting their colours on the device; RGB565 has neither palette + nor alpha.""" + if fmt in MASK_FORMATS: + return "mask" + if fmt in PALETTE_FORMATS: + return "palette" + if fmt in BGRA_FORMATS: + return "bgra" + return None + + +def encode_pixels(info: dict, width: int, height: int, rgba: bytes) -> bytes: + """Record payload of a catalog bitmap from RGBA pixels of its native size. + 4-bit masks round to the 16 gray levels the format stores.""" + if (width, height) != (info["width"], info["height"]): + raise ValueError( + f"expected {info['width']}x{info['height']}, got {width}x{height}" + ) + colors = [rgba[i : i + 4] for i in range(0, len(rgba), 4)] + if len(colors) != width * height: + raise ValueError("invalid PNG pixel count") + result = bytearray(info["bytes"] - info["data_offset"]) + fmt, stride = info["format"], info["stride"] + start = info["pixels_offset"] - info["data_offset"] + capacity = info["palette_colors"] + if capacity: + unique = list(dict.fromkeys(colors)) + if len(unique) > capacity: + raise ValueError( + f"{len(unique)} colours exceed the {capacity} of its palette" + ) + lookup = {color: index for index, color in enumerate(unique)} + for index, (red, green, blue, alpha) in enumerate(unique): + result[index * 4 : index * 4 + 4] = bytes((blue, green, red, alpha)) + for y in range(height): + for x in range(width): + at = start + y * stride + x * (info["depth"] // 8) + index = lookup[colors[y * width + x]] + if fmt == INDEXED8: + result[at] = index + else: + struct.pack_into("> 3) << 11 | (green >> 2) << 5 | blue >> 3 + ) + else: + if red != green or green != blue or alpha != 255: + raise ValueError("native grayscale requires opaque gray levels") + if fmt == MASK8: + result[at] = red + else: + at = start + y * stride + x // 2 + shift = 4 if x % 2 == 0 else 0 + result[at] = (result[at] & ~(15 << shift)) | ( + round(red / 17) << shift + ) + return bytes(result) + + +def palette_indices_fit(info: dict, payload: bytes) -> bool: + """True when every pixel of a paletted record payload indexes its palette.""" + capacity = info["palette_colors"] + if not capacity: + return True + start = info["pixels_offset"] - info["data_offset"] + width = info["depth"] // 8 + for y in range(info["height"]): + for x in range(info["width"]): + at = start + y * info["stride"] + x * width + if int.from_bytes(payload[at : at + width], "little") >= capacity: + return False + return True + + +def decode_pixels(info: dict, payload: bytes) -> bytes: + """RGBA pixels of a catalog bitmap from its record payload, the inverse of + encode_pixels. RGB565 channels expand with zero low bits.""" + fmt, stride = info["format"], info["stride"] + width, height = info["width"], info["height"] + start = info["pixels_offset"] - info["data_offset"] + palette = [] + for i in range(info["palette_colors"]): + blue, green, red, alpha = payload[i * 4 : i * 4 + 4] + palette.append(bytes((red, green, blue, alpha))) + out = bytearray() + for y in range(height): + row = start + y * stride + for x in range(width): + if fmt == INDEXED8: + out += palette[payload[row + x]] + elif fmt == INDEXED16: + out += palette[struct.unpack_from("> (4 if x % 2 == 0 else 0) & 15 + out += bytes((nibble * 17,) * 3) + b"\xff" + return bytes(out) + + +def write_png(width: int, height: int, rgba: bytes) -> bytes: + """An RGBA PNG with unfiltered rows.""" + rows = b"".join( + b"\0" + rgba[y * width * 4 : (y + 1) * width * 4] for y in range(height) + ) + + def chunk(kind, body): + return ( + struct.pack(">I", len(body)) + + kind + + body + + struct.pack(">I", zlib.crc32(kind + body)) + ) + + return ( + b"\x89PNG\r\n\x1a\n" + + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 6, 0, 0, 0)) + + chunk(b"IDAT", zlib.compress(rows)) + + chunk(b"IEND", b"") + ) + + +def pack_565(red, green, blue): + return (red >> 3) << 11 | (green >> 2) << 5 | blue >> 3 + + +def unpack_565(word): + return (word >> 11) << 3, (word >> 5 & 63) << 2, (word & 31) << 3 + + +def is_565(rgba): + """True for an opaque colour RGB565 stores exactly.""" + red, green, blue, alpha = rgba + return alpha == 255 and not (red & 7 or green & 3 or blue & 7) + + +def coverage(rgba: bytes) -> bytes: + """Per-pixel coverage of tinted art: the alpha channel when the PNG uses one, + otherwise the gray level. Coloured, opaque art has no single coverage.""" + alpha = rgba[3::4] + if any(value != 255 for value in alpha): + return bytes(alpha) + if any( + rgba[i] != rgba[i + 1] or rgba[i + 1] != rgba[i + 2] + for i in range(0, len(rgba), 4) + ): + raise ValueError("tinted art must be grayscale or carry alpha coverage") + return bytes(rgba[::4]) + + +def gray_pixels(levels: bytes) -> bytes: + """Opaque gray pixels of a coverage, for a native mask.""" + return b"".join(bytes((value, value, value, 255)) for value in levels) + + +def distinct(rgba: bytes) -> int: + """Distinct colours of RGBA pixels.""" + return len({rgba[i : i + 4] for i in range(0, len(rgba), 4)}) + + +def fit_levels(levels: bytes, capacity: int) -> bytes: + """Coverage reduced to what a palette of `capacity` entries holds, so the + result does not depend on the colour it is painted in afterwards.""" + return fit_palette(b"".join(bytes((0, 0, 0, level)) for level in levels), capacity)[ + 3::4 + ] + + +def tinted_pixels(levels: bytes, tint: str) -> bytes: + """Placeholder-coloured pixels whose alpha carries the coverage; the device + rewrites the palette entries or BGRA8888 pixels with the live role colour.""" + color = bytes.fromhex(tint.removeprefix("#")) + return b"".join(color + bytes((level,)) if level else bytes(4) for level in levels) + + +def premultiplied(color): + return tuple(value * color[3] / 255 for value in color[:3]) + (color[3],) + + +def fit_palette(rgba: bytes, capacity: int) -> bytes: + """Weighted median cut in premultiplied RGBA, reserving transparent pixels.""" + pixels = [tuple(rgba[i : i + 4]) for i in range(0, len(rgba), 4)] + counts = Counter(pixels) + if len(counts) <= capacity: + return rgba + transparent = any(color[3] == 0 for color in counts) + palette = [(0, 0, 0, 0)] if transparent and capacity > 1 else [] + colors = [color for color in counts if color[3] or not palette] + points = {color: premultiplied(color) for color in colors} + boxes = [colors] if colors else [] + while len(boxes) + len(palette) < capacity: + candidates = [] + for i, box in enumerate(boxes): + if len(box) < 2: + continue + spans = [ + max(points[c][axis] for c in box) - min(points[c][axis] for c in box) + for axis in range(4) + ] + axis = max(range(4), key=spans.__getitem__) + candidates.append((spans[axis] ** 2 * sum(counts[c] for c in box), i, axis)) + if not candidates: + break + _, index, axis = max(candidates) + box = sorted(boxes.pop(index), key=lambda color: (points[color][axis], color)) + halfway = sum(counts[c] for c in box) / 2 + accumulated = 0 + split = 1 + for split, color in enumerate(box[:-1], 1): + accumulated += counts[color] + if accumulated >= halfway: + break + boxes.extend((box[:split], box[split:])) + for box in boxes: + total = sum(counts[c] for c in box) + palette.append( + tuple( + round(sum(c[axis] * counts[c] for c in box) / total) + for axis in range(4) + ) + ) + palette_points = [premultiplied(color) for color in palette] + mapping = {} + for color in counts: + point = premultiplied(color) + index = min( + range(len(palette)), + key=lambda i: sum((a - b) ** 2 for a, b in zip(point, palette_points[i])), + ) + mapping[color] = bytes(palette[index]) + return b"".join(mapping[color] for color in pixels) diff --git a/themes/rvt/catalog.py b/themes/rvt/catalog.py new file mode 100644 index 0000000..f888ee0 --- /dev/null +++ b/themes/rvt/catalog.py @@ -0,0 +1,148 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""The bitmap catalog: every BMap of the pinned Apple firmware that a theme can +replace, by index. A pack's records and tint bytes index into this list, so a +theme is tied to the catalog it was compiled against by the fingerprint.""" + +import hashlib +import json +from importlib.resources import files +from pathlib import Path +from typing import TypedDict + +from rvt import bitmaps, rvtfile + +SCHEMA = 1 + + +class Entry(TypedDict): + """One catalog bitmap; docs/catalog.md describes the fields.""" + + id: int + name: str + offset: int + address: int + bytes: int + format: int + depth: int + width: int + height: int + stride: int + data_offset: int + pixels_offset: int + palette_colors: int + crc32: int + + +ENTRY_KEYS = tuple(Entry.__annotations__) +DEFAULT = files("rvt") / "data" / "osos-2.0.5.json" +FORMAT_NAMES = { + bitmaps.MASK4: "mask4", + bitmaps.MASK8: "mask8", + bitmaps.INDEXED8: "indexed8", + bitmaps.INDEXED16: "indexed16", + bitmaps.RGB565: "rgb565", + bitmaps.BGRA8888: "bgra8888", +} + + +def address(offset: int, runtime_base: int, runtime_file_offset: int) -> int: + """Where a bitmap at a file offset lives: Apple loads osos.bin at + runtime_base with the file's first runtime_file_offset bytes stripped.""" + return runtime_base + offset - runtime_file_offset + + +def canonical(entries: list[Entry]) -> bytes: + return json.dumps(entries, sort_keys=True, separators=(",", ":")).encode() + + +def fingerprint(entries: list[Entry]) -> bytes: + """The first FINGERPRINT_BYTES of the SHA-256 of the canonical entry list.""" + return hashlib.sha256(canonical(entries)).digest()[: rvtfile.FINGERPRINT_BYTES] + + +def is_hex_id(reference: str) -> bool: + return ( + reference[:2].lower() == "0x" + and 1 <= len(reference) - 2 <= 8 + and all(c in "0123456789abcdefABCDEF" for c in reference[2:]) + ) + + +class Catalog: + assets: list[Entry] + + def __init__(self, document: dict): + if not isinstance(document, dict) or document.get("schema") != SCHEMA: + raise ValueError(f"catalog: expected schema {SCHEMA}") + entries = document.get("bitmaps") + if not isinstance(entries, list) or not entries: + raise ValueError("catalog: expected a non-empty bitmap list") + if len(entries) > rvtfile.CATALOG_MAX: + raise ValueError(f"catalog: more than {rvtfile.CATALOG_MAX} bitmaps") + self.assets = entries + self.firmware = document.get("firmware", {}) + runtime = (document.get("runtime_base"), document.get("runtime_file_offset")) + if not all(isinstance(value, int) for value in runtime): + raise ValueError("catalog: expected runtime_base and runtime_file_offset") + self.runtime_base, self.runtime_file_offset = runtime + self.by_id: dict[int, int] = {} + self.by_name: dict[str, list[int]] = {} + for index, asset in enumerate(entries): + if tuple(sorted(asset)) != tuple(sorted(ENTRY_KEYS)): + raise ValueError(f"catalog: bitmap {index} has unexpected keys") + if asset["address"] != address(asset["offset"], *runtime): + raise ValueError(f"catalog: bitmap {asset['id']:#010x} address") + if asset["id"] in self.by_id: + raise ValueError(f"catalog: duplicate bitmap id {asset['id']:#010x}") + self.by_id[asset["id"]] = index + self.by_name.setdefault(asset["name"], []).append(index) + self.fingerprint = fingerprint(entries) + stored = document.get("fingerprint") + if stored is not None and stored != self.fingerprint.hex(): + raise ValueError("catalog: stored fingerprint does not match the bitmaps") + + def resolve(self, reference: str, where: str) -> int: + """Index of a bitmap named by catalog name or hex id.""" + if is_hex_id(reference): + value = int(reference, 16) + if value not in self.by_id: + raise ValueError(f"{where}: {value:#010x} is not a catalog bitmap") + return self.by_id[value] + matches = self.by_name.get(reference) + if not matches: + raise ValueError(f"{where}: {reference!r} is not a catalog bitmap name") + if len(matches) > 1: + ids = ", ".join(f"{self.assets[i]['id']:#010x}" for i in matches) + raise ValueError(f"{where}: {reference!r} is ambiguous; use one of {ids}") + return matches[0] + + def payload_bytes(self, index: int) -> int: + asset = self.assets[index] + return asset["bytes"] - asset["data_offset"] + + def max_body(self) -> int: + """Largest valid body: the style prefix plus one record per bitmap.""" + return rvtfile.STYLE_BYTES + sum( + rvtfile.RECORD_BYTES + payload_max(asset) for asset in self.assets + ) + + +def entries(info: Entry) -> int: + """Colour slots a recolour can touch: palette entries or pixels.""" + return info["palette_colors"] or info["width"] * info["height"] + + +def payload_max(info: Entry) -> int: + """The largest padded payload any record kind allows for a bitmap.""" + pixels = info["bytes"] - info["data_offset"] + pairs = min(rvtfile.RECOLOR_MAX, entries(info)) + return max( + rvtfile.align(pixels), + rvtfile.align(4 + pairs * rvtfile.PAIR.size), + rvtfile.RELIGHT_BYTES, + ) + + +def load(path: Path | None = None) -> Catalog: + source = DEFAULT if path is None else Path(path) + return Catalog(json.loads(source.read_text())) diff --git a/themes/rvt/cli.py b/themes/rvt/cli.py new file mode 100644 index 0000000..a936f53 --- /dev/null +++ b/themes/rvt/cli.py @@ -0,0 +1,319 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""rvt: compile and check theme folders, inspect .rvt files, start a theme, +browse the two catalogs, and with a local firmware preview derived art or +turn a PNG into a recolour rule.""" + +import argparse +import json +import struct +import sys +from pathlib import Path + +from rvt import assets, compiler, inspector, rvtfile, theme +from rvt import catalog as catalog_module +from rvt.bitmaps import tint_kind + + +def main(argv=None) -> int | None: + parser = argparse.ArgumentParser(prog="rvt", description=__doc__) + commands = parser.add_subparsers(dest="command", required=True) + + def catalog_option(command): + command.add_argument( + "--catalog", + type=Path, + default=None, + help="a catalog other than the built-in", + ) + + def extension_option(command): + command.add_argument( + "--extension", + type=Path, + action="append", + default=[], + metavar="assets.json", + help="the bitmaps of an extension outside the first-party catalog, as " + "the SDK's assets.py prints them; repeatable", + ) + + def theme_options(command): + command.add_argument("folder", type=Path, help="folder with theme.toml") + catalog_option(command) + extension_option(command) + command.add_argument( + "--allow-reserved", + action="store_true", + help="accept the reserved id of the built-in theme", + ) + command.add_argument( + "--strict", action="store_true", help="treat warnings as errors" + ) + + build = commands.add_parser("compile", help="theme folder -> .rvt") + theme_options(build) + build.add_argument("--out", type=Path, default=Path("dist")) + + check = commands.add_parser("check", help="compile without writing") + theme_options(check) + + show = commands.add_parser("inspect", help="validate and describe an .rvt") + show.add_argument("file", type=Path) + catalog_option(show) + extension_option(show) + show.add_argument("--json", action="store_true", help="print the full description") + + new = commands.add_parser("new", help="start a theme folder") + new.add_argument("id", help="the theme's id, also the folder's name") + new.add_argument("--name", help="the display name; defaults to the id") + + browse = commands.add_parser( + "catalog", help="list or show Apple's bitmaps and extension bitmaps" + ) + browse_commands = browse.add_subparsers(dest="catalog_command", required=True) + listing = browse_commands.add_parser("list", help="name, size, format, palette") + listing.add_argument( + "--extensions", + action="store_true", + help="extension bitmaps instead of Apple's bitmaps", + ) + listing.add_argument("--group", help="name prefix, or an extension id") + listing.add_argument( + "--format", dest="fmt", help=", ".join(catalog_module.FORMAT_NAMES.values()) + ) + catalog_option(listing) + extension_option(listing) + detail = browse_commands.add_parser( + "show", help="every field of one Apple bitmap or extension bitmap" + ) + detail.add_argument("name", help="catalog name, hex id or /") + catalog_option(detail) + extension_option(detail) + + preview = commands.add_parser( + "preview", help="render the art a theme derives, from a firmware" + ) + theme_options(preview) + preview.add_argument( + "--firmware", type=Path, required=True, help="osos.bin or reprise.bin" + ) + preview.add_argument("--out", type=Path, default=Path("dist")) + + recolor = commands.add_parser( + "recolor", help="turn /apple/.png into a recolour rule file" + ) + recolor.add_argument("png", type=Path, help="//apple/.png") + recolor.add_argument( + "--firmware", type=Path, required=True, help="osos.bin or reprise.bin" + ) + catalog_option(recolor) + + args = parser.parse_args(argv) + try: + if args.command == "new": + print(new_theme(args.id, args.name)) + return None + catalog = catalog_module.load(args.catalog) + extensions = assets.load_catalog(getattr(args, "extension", [])) + if args.command == "compile": + path, build = compiler.write( + catalog, + args.folder, + args.out, + args.allow_reserved, + args.strict, + extensions, + ) + report(build) + print(f"Wrote {path}") + elif args.command == "check": + build = compiler.compile_theme( + catalog, args.folder, args.allow_reserved, args.strict, extensions + ) + report(build) + elif args.command == "inspect": + result = inspector.inspect( + args.file.read_bytes(), catalog, assets.known_names(extensions) + ) + if args.json: + print(json.dumps(result, indent=2, default=lambda b: b.hex())) + else: + print(inspector.describe(result)) + elif args.command == "catalog": + if args.catalog_command == "list" and args.extensions: + for line in extension_list(extensions, args.group, args.fmt): + print(line) + elif args.catalog_command == "list": + for line in catalog_list(catalog, args.group, args.fmt): + print(line) + elif "/" in args.name: + print(extension_show(extensions, args.name)) + else: + print(catalog_show(catalog, args.name)) + elif args.command == "preview": + for line in render(catalog, extensions, args): + print(line) + else: + print(convert(catalog, args), end="") + except (OSError, ValueError, struct.error) as error: + parser.exit(1, f"{error}\n") + return None + + +def report(build: compiler.Build) -> None: + """Notes, warnings and the size table of a compiled theme.""" + for note in build.notes: + print(note) + for warning in build.warnings: + print(f"warning: {warning}", file=sys.stderr) + print(compiler.summary(build.inspection, len(build.data))) + + +def new_theme(identifier: str, name: str | None) -> str: + """Write /theme.toml with every option as a comment, and the apple/, + reprise/ and extensions/ folders of light/ and dark/.""" + rvtfile.check_id(identifier) + if identifier in theme.RESERVED_IDS: + raise ValueError(f"id: {identifier!r} is reserved for the built-in theme") + name = rvtfile.check_name(name or identifier) + folder = Path(identifier) + if folder.exists(): + raise ValueError(f"{folder} exists") + for appearance in rvtfile.APPEARANCES: + for sub in compiler.FOLDERS: + (folder / appearance / sub).mkdir(parents=True) + (folder / "theme.toml").write_text(theme.template(identifier, name)) + return f"Wrote {folder}/theme.toml and {{light,dark}}/{{{','.join(compiler.FOLDERS)}}}/" + + +def catalog_list(catalog, group: str | None, fmt: str | None) -> list[str]: + """name WxH format palette tintable, one line per bitmap.""" + names = catalog_module.FORMAT_NAMES + if fmt is not None and fmt not in names.values(): + raise ValueError(f"--format: expected one of {', '.join(names.values())}") + lines = [] + for asset in catalog.assets: + if group and not asset["name"].startswith(group): + continue + if fmt and names[asset["format"]] != fmt: + continue + lines.append( + f"{asset['name']} {asset['width']}x{asset['height']} " + f"{names[asset['format']]} {asset['palette_colors']} " + f"{'tintable' if tint_kind(asset['format']) else 'untintable'}" + ) + return lines + + +def extension_list(extensions: dict, group: str | None, fmt: str | None) -> list[str]: + """id asset WxH format palette menu, one line per extension bitmap.""" + names = assets.FORMAT_NAMES + if fmt is not None and fmt not in names.values(): + raise ValueError(f"--format: expected one of {', '.join(names.values())}") + lines = [] + for (identifier, asset), record in sorted(extensions.items()): + if group and identifier != group: + continue + name = names.get(record["format"], f"{record['format']:#x}") + if fmt and name != fmt: + continue + lines.append( + f"{identifier} {asset} {record['width']}x{record['height']} {name} " + f"{record['palette_colors']} {'menu' if record['menu'] else 'bitmap'}" + ) + return lines + + +def extension_show(extensions: dict, reference: str) -> str: + """Every field of one extension bitmap, named /.""" + identifier, _, asset = reference.partition("/") + record = extensions.get((identifier, asset)) + if record is None: + raise ValueError( + f"name: {reference!r} is not in the extension asset catalog; " + "--extension adds an extension's assets.json" + ) + lines = [] + for key in assets.RECORD_KEYS: + value = record[key] + if key == "format": + value = f"{value:#x}" + elif isinstance(value, bool): + value = str(value).lower() + lines.append(f"{key} {value}") + lines.append(f"format_name {assets.FORMAT_NAMES.get(record['format'], 'unknown')}") + lines.append(f"owner_hash {assets.owner_hash(identifier):#010x}") + lines.append(f"asset_hash {assets.asset_hash(asset):#010x}") + return "\n".join(lines) + + +def catalog_show(catalog, reference: str) -> str: + """Every field of one bitmap; a name listed twice shows both.""" + if catalog_module.is_hex_id(reference): + indices = [catalog.resolve(reference, "name")] + else: + indices = catalog.by_name.get(reference) + if not indices: + raise ValueError(f"name: {reference!r} is not a catalog bitmap name") + blocks = [] + for index in indices: + asset = catalog.assets[index] + lines = [f"index {index}"] + for key, value in asset.items(): + text = f"{value:#x}" if key in ("id", "address", "format") else value + lines.append(f"{key} {text}") + lines.append(f"format_name {catalog_module.FORMAT_NAMES[asset['format']]}") + blocks.append("\n".join(lines)) + return "\n\n".join(blocks) + + +def convert(catalog, args) -> str: + """Write /.toml beside the PNG and return a summary.""" + from rvt import firmware + + png = args.png.resolve() + appearance = png.parent.parent.name + if ( + png.parent.name != compiler.APPLE + or appearance not in rvtfile.APPEARANCES + or png.suffix != ".png" + ): + raise ValueError( + f"expected //{compiler.APPLE}/.png" + ) + index = catalog.resolve(png.stem, str(args.png)) + pairs, notes = firmware.to_recolor( + catalog, firmware.Firmware(args.firmware, catalog), index, png.read_bytes() + ) + target = png.with_suffix(".toml") + target.write_text(firmware.recolor_text(pairs)) + return "".join(f"{png.name}: {note}\n" for note in notes) + ( + f"Wrote {target} ({len(pairs)} colour pairs); delete {png.name} to use it\n" + ) + + +def render(catalog, extensions, args) -> list[str]: + """Previews of every derived bitmap under //derived/.""" + from rvt import firmware + + build = compiler.compile_theme( + catalog, args.folder, args.allow_reserved, args.strict, extensions + ) + result, warnings = firmware.render( + catalog, firmware.Firmware(args.firmware, catalog), build.data + ) + root = args.out / build.report["id"] / "derived" + listing = {} + for appearance, entries in result.items(): + (root / appearance).mkdir(parents=True, exist_ok=True) + listing[appearance] = {} + for name, entry in entries.items(): + (root / appearance / f"{name}.png").write_bytes(entry.pop("png")) + listing[appearance][name] = entry + (root / "derived.json").write_text(json.dumps(listing, indent=2) + "\n") + count = sum(len(entries) for entries in listing.values()) + return [*warnings, f"Wrote {count} previews and derived.json under {root}"] + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/themes/rvt/compiler.py b/themes/rvt/compiler.py new file mode 100644 index 0000000..836d626 --- /dev/null +++ b/themes/rvt/compiler.py @@ -0,0 +1,422 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""Compile a theme folder (theme.toml, light/, dark/) into .rvt. + +An appearance folder holds `apple/`, a PNG or TOML per catalog bitmap, +`extensions//.png`, the bitmap assets of extensions, and +`reprise/.png`, the core's own. + +Everything is checked and built in memory, the result is read back through the +inspector, and only then are .rvt and report.json written. +""" + +import json +import re +import struct +import zlib +from dataclasses import dataclass, field +from pathlib import Path + +from rvt import assets, bitmaps, derive, inspector, lz, rvtfile, style, theme +from rvt.catalog import Catalog, Entry +from rvt.derive import Rule +from rvt.errors import fail + +FILE_NAME = re.compile(r"[A-Za-z0-9_][A-Za-z0-9._ -]{0,127}") +APPLE = "apple" +FOLDERS = (APPLE, assets.CORE_FOLDER, assets.FOLDER) + + +@dataclass +class Build: + """A compiled theme: the file, the report, the inspector's description of + the file, the warnings `rvt check` prints and `--strict` rejects, the + notes about rule matches, and the payloads the compiler derived from the + other appearance (appearance -> name -> bytes from the bitmap's data + offset).""" + + data: bytes + report: dict + inspection: dict + warnings: list[str] = field(default_factory=list) + notes: list[str] = field(default_factory=list) + resolved: dict[str, dict[str, bytes]] = field(default_factory=dict) + + +def check_layout(folder: Path, appearance: str) -> None: + """An appearance folder holds only apple/, reprise/ and extensions/.""" + directory = Path(folder) / appearance + if not directory.is_dir(): + return + for path in sorted(directory.iterdir()): + if path.name.startswith(".") or (path.is_dir() and path.name in FOLDERS): + continue + fail( + f"{appearance}/{path.name}", + f"catalog art goes in {appearance}/{APPLE}/, extension bitmaps in " + f"{appearance}/{assets.FOLDER}//, the core's in " + f"{appearance}/{assets.CORE_FOLDER}/", + ) + + +def has_art(folder: Path, appearance: str) -> bool: + return any( + path.is_file() and not path.name.startswith(".") + for path in (Path(folder) / appearance).rglob("*") + ) + + +def find_sources(folder: Path, appearance: str, catalog: Catalog) -> dict: + """Catalog index -> ("png" | "toml", path) for every file in the + appearance's apple/ folder: a PNG replaces the bitmap, a TOML derives it.""" + root = Path(folder).resolve() + directory = root / appearance / APPLE + found = {} + if not directory.is_dir(): + return found + for path in sorted(directory.iterdir()): + where = f"{appearance}/{APPLE}/{path.name}" + if path.name.startswith("."): + continue + if path.suffix not in (".png", ".toml") or not FILE_NAME.fullmatch(path.name): + fail(where, "expected .png, .toml or 0x.png") + limit = assets.PNG_LIMIT if path.suffix == ".png" else theme.TOML_LIMIT + resolved = assets.source_file(path, root, where, limit) + index = catalog.resolve(path.stem, where) + if index in found: + fail(where, f"duplicate replacement for {catalog.assets[index]['name']}") + found[index] = (path.suffix[1:], resolved) + return found + + +def pixel_payload( + info: Entry, path: Path, where: str, tint: bool, icon: str +) -> tuple[bytes, int | None]: + """The native payload of a PNG replacement, and the number of distinct + colours (coverage levels for tinted art) when it exceeded the palette and + was reduced. Tinted art is stored in `icon`, the placeholder the iPod + rewrites.""" + kind = bitmaps.tint_kind(info["format"]) if tint else None + capacity = info["palette_colors"] + reduced = None + try: + width, height, rgba = bitmaps.read_png(path.read_bytes()) + if kind == "mask": + rgba = bitmaps.gray_pixels(bitmaps.coverage(rgba)) + elif kind: + levels = bitmaps.coverage(rgba) + if capacity and len(set(levels)) > capacity: + reduced = len(set(levels)) + levels = bitmaps.fit_levels(levels, capacity) + rgba = bitmaps.tinted_pixels(levels, icon) + elif capacity and bitmaps.distinct(rgba) > capacity: + reduced = bitmaps.distinct(rgba) + rgba = bitmaps.fit_palette(rgba, capacity) + payload = bitmaps.encode_pixels(info, width, height, rgba) + except (KeyError, ValueError, zlib.error, struct.error) as error: + fail(where, str(error) or type(error).__name__) + if len(payload) != info["bytes"] - info["data_offset"]: + fail(where, "native encoding changed the bitmap size") + return payload, reduced + + +class Plan: + """One appearance before its bytes: style, tints and records as + index -> Rule, each with the text naming its origin.""" + + def __init__( + self, + catalog: Catalog, + folder: Path, + appearance: str, + table: dict, + extensions: dict, + ): + self.catalog = catalog + self.appearance = appearance + self.warnings: list[str] = [] + self.notes: list[str] = [] + self.reduced: list[dict] = [] + self.resolved: dict[str, bytes] = {} + check_layout(folder, appearance) + sources = find_sources(folder, appearance, catalog) + self.origin = { + index: f"{appearance}/{APPLE}/{path.name}" + for index, (_, path) in sources.items() + } + (self.colors, self.flags, self.palettes), self.report, warnings = ( + theme.resolve_style(appearance, table) + ) + self.warnings += warnings + self.tinted, self.tinted_bitmaps, warnings = theme.resolve_tints( + table, appearance, catalog + ) + self.warnings += warnings + rules, owners, self.notes = theme.resolve_rules( + table, appearance, catalog, sources + ) + self.records: dict[int, Rule] = {} + for index, (source, path) in sorted(sources.items()): + info = catalog.assets[index] + where = self.origin[index] + if source == "png": + payload, reduced = pixel_payload( + info, path, where, index in self.tinted, self.colors["icon_tint"] + ) + if reduced is not None: + self.reduced.append( + { + "name": info["name"], + "colors": reduced, + "palette": info["palette_colors"], + } + ) + self.warnings.append( + f"{where}: {reduced} colours reduced to the " + f"{info['palette_colors']} of its palette" + ) + self.records[index] = Rule("pixels", payload) + else: + self.records[index] = derive.load(path, index, catalog, where) + for index, rule in rules.items(): + self.origin[index] = f"{appearance}.derive.{owners[index]!r}" + self.records[index] = rule + self.check_tints() + self.bitmaps: dict[tuple[str, str], bytes] = {} + sources = assets.find_sources(folder, appearance) + for key, role in self.tinted_bitmaps.items(): + if key not in sources: + fail( + f"{appearance}.tint.{role}", + f"{key[0]}/{key[1]} has no {assets.source_path(appearance, *key)}", + ) + for key, path in sources.items(): + where = assets.source_path(appearance, *key) + record = extensions.get(key) + tint = self.tinted_bitmaps.get(key) + self.bitmaps[key] = assets.encode( + path, where, record, self.colors["icon_tint"] if tint else None + ) + if record is None: + self.warnings.append( + f"{where}: not in the extension asset catalog, compiled as a " + "Settings icon; docs/extension-bitmaps.md lists the first-party " + "bitmaps, --extension adds others" + ) + if not self.flags & rvtfile.FLAGS["flat_icons"]: + for key, bmap in self.bitmaps.items(): + if assets.is_menu(bmap) and not assets.has_reflection(bmap): + self.warnings.append( + f"{assets.source_path(appearance, *key)}: no reflection " + "below the art; draw one or set " + f"flat_icons = true in [{appearance}.rendering]" + ) + + def name(self, index: int) -> str: + return self.catalog.assets[index]["name"] + + def check_tints(self) -> None: + """A tint needs stock art or a PNG, never a derivation; darkness + coverage needs the stock art.""" + for index, (_, coverage) in self.tinted.items(): + record = self.records.get(index) + if record is None: + continue + at = f"{self.appearance}.tint.{self.name(index)}" + if record.kind != "pixels": + fail( + at, + f"{self.name(index)} is derived by {self.origin[index]}; " + "a tint cannot be combined with a derivation", + ) + if coverage != "alpha": + fail( + f"{at}.coverage", + f"coverage needs stock art; remove {self.origin[index]}", + ) + + def resolve_from_other(self, other: "Plan | None") -> None: + """Records starting from the theme's own art in the other appearance + become pixels records computed here, as the iPod would compute them + from that art. The art must be a PNG the other appearance does not + tint, since a tinted PNG carries coverage, not colours.""" + for index, rule in sorted(self.records.items()): + if not rule.from_other: + continue + where = f"{self.origin[index]}.from_other" + if other is None: + fail(where, "the theme has one appearance") + target = rule.spec if rule.kind == "alias" else index + name = self.name(target) + base = other.records.get(target) + if base is None: + fail(where, f"{name} has no art in {other.appearance}/{APPLE}/") + if base.kind != "pixels" or base.from_other: + fail( + where, + f"{name} is derived in {other.appearance}/{APPLE}/; it must be a PNG", + ) + if target in other.tinted: + fail(where, f"{name} is tinted in {other.appearance}/{APPLE}/") + try: + result = derive.apply_record( + self.catalog, self.blank, index, rule.kind, rule.spec, {}, base.spec + ) + except ValueError as error: + fail(where, str(error)) + payload = result[self.catalog.assets[index]["data_offset"] :] + self.records[index] = Rule("pixels", payload) + self.resolved[self.name(index)] = payload + + def blank(self, index: int) -> bytes: + """A bitmap of the right size whose header is never read.""" + return bytes(self.catalog.assets[index]["bytes"]) + + def check_aliases(self) -> None: + aliases = { + index: rule.spec + for index, rule in self.records.items() + if rule.kind == "alias" + } + derive.check_aliases( + aliases, + self.tinted, + self.name, + lambda index: ( + self.appearance if index is None else f"{self.origin[index]}.source" + ), + ) + + def body(self) -> bytes: + """The pack body: style prefix, records and extension bitmaps, pixels + and bitmap rows compressed when that is smaller.""" + body = bytearray(style.encode(*self.style_tuple(), self.tinted)) + counts: dict[str, int] = {} + for index, rule in sorted(self.records.items()): + kind, payload = rule.kind, derive.encode(rule.kind, rule.spec) + if kind == "pixels": + packed = lz.lz_encode(payload) + if len(packed) < len(payload): + kind, payload = "pixels_lz", packed + counts[kind] = counts.get(kind, 0) + 1 + body += rvtfile.RECORD.pack(index, rvtfile.KINDS.index(kind), len(payload)) + body += payload + body += bytes(-len(body) % 4) + if len(body) > self.catalog.max_body(): + fail(self.appearance, "exceeds the largest size the catalog allows") + table, self.bitmap_count, bitmap_counts = assets.encode_table( + self.bitmaps, self.tinted_bitmaps + ) + body += table + self.report["records"] = dict(sorted(counts.items())) + self.report["extension_bitmaps"] = dict(sorted(bitmap_counts.items())) + self.report["extension_tinted"] = { + f"{identifier}/{asset}": role + for (identifier, asset), role in sorted(self.tinted_bitmaps.items()) + } + self.report["palette_reduced"] = self.reduced + self.report["bytes"] = len(body) + return bytes(body) + + def style_tuple(self) -> tuple: + return self.colors, self.flags, self.palettes + + +def compile_theme( + catalog: Catalog, + folder: Path, + allow_reserved: bool = False, + strict: bool = False, + extensions: dict | None = None, +) -> Build: + """The .rvt bytes, report, warnings and notes of a theme folder; with + strict, warnings are errors. `extensions` is the extension asset catalog + ((id, asset) -> record), the vendored one when None. The built-in theme's + packs carry art only: no rendering flags, no tints.""" + folder = Path(folder) + if extensions is None: + extensions = assets.load_catalog() + document = theme.load(folder) + reserved = document["id"] in theme.RESERVED_IDS + if reserved and not allow_reserved: + fail("id", f"{document['id']!r} is reserved for the built-in theme") + for appearance in rvtfile.APPEARANCES: + if appearance not in document and has_art(folder, appearance): + fail(appearance, f"has art but theme.toml declares no [{appearance}]") + plans = { + appearance: Plan(catalog, folder, appearance, document[appearance], extensions) + for appearance in rvtfile.APPEARANCES + if appearance in document + } + for appearance, plan in plans.items(): + if reserved and (plan.flags or plan.tinted or plan.tinted_bitmaps): + fail(appearance, "the built-in theme carries art only: no flags, no tints") + others = [p for a, p in plans.items() if a != appearance] + plan.resolve_from_other(others[0] if others else None) + for plan in plans.values(): + plan.check_aliases() + assets.check_collisions([key for plan in plans.values() for key in plan.bitmaps]) + packs = { + a: (plan.body(), len(plan.records), plan.bitmap_count) + for a, plan in plans.items() + } + report = { + key: document[key] + for key in ("id", "name", "author", "version") + if key in document + } + report["appearances"] = {a: plan.report for a, plan in plans.items()} + data = rvtfile.encode_file( + catalog.fingerprint, document["id"], document["name"], packs + ) + build = Build( + data, + report, + inspector.inspect(data, catalog, assets.known_names(extensions)), + [w for plan in plans.values() for w in plan.warnings], + [n for plan in plans.values() for n in plan.notes], + {a: plan.resolved for a, plan in plans.items()}, + ) + if strict and build.warnings: + fail( + "", + "\n".join( + [f"{len(build.warnings)} warnings with --strict:"] + build.warnings + ), + ) + return build + + +def write( + catalog: Catalog, + folder: Path, + out: Path, + allow_reserved: bool = False, + strict: bool = False, + extensions: dict | None = None, +) -> tuple[Path, Build]: + """Compile and write //.rvt and report.json.""" + build = compile_theme(catalog, folder, allow_reserved, strict, extensions) + directory = Path(out) / build.report["id"] + directory.mkdir(parents=True, exist_ok=True) + path = directory / f"{build.report['id']}.rvt" + path.write_bytes(build.data) + (directory / "report.json").write_text( + json.dumps(build.report, indent=2, sort_keys=True) + "\n" + ) + return path, build + + +def summary(result: dict, size: int) -> str: + """One line per appearance for the console, from an inspect() result.""" + lines = [f"{result['id']}.rvt: {size:,} bytes"] + for appearance, pack in result["appearances"].items(): + counts = inspector.counts(pack["records"]) + pixels = sum(counts.get(kind, 0) for kind in rvtfile.PIXEL_KINDS) + derived = len(pack["records"]) - pixels + lines.append( + f" {appearance}: {len(pack['records'])} bitmaps " + f"({pixels} pixels, {derived} derived), " + f"{len(pack['extension_bitmaps'])} extension bitmaps, " + f"{pack['bytes']:,} bytes" + ) + return "\n".join(lines) diff --git a/themes/rvt/data/__init__.py b/themes/rvt/data/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/themes/rvt/data/bitmap.py b/themes/rvt/data/bitmap.py new file mode 100644 index 0000000..591e0aa --- /dev/null +++ b/themes/rvt/data/bitmap.py @@ -0,0 +1,190 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""PNG to the device's BMap bitmap format, for rvx-pack. + +A BMap is a 28-byte header (format, stride in bytes, depth, bounds as top, left, +bottom, right, payload bytes) and its payload; rows are padded to a word. + +- Picture, with at most 256 colours: indexed, a 32-bit palette count, the + palette as B, G, R, A, then one byte per pixel. Otherwise B, G, R, A per + pixel, not premultiplied. +- Pane picture (`pane = "picture"` in the manifest): a picture of one of the + sizes the menu panes show (PICTURE_SIZES), or the 20 x 16 badge beside a + pane's count line (`"badge"`). +- Pane icon (`"icon"`): what the stock Settings pane icons are, a 78 x 121 mask + of one coverage byte per pixel (0 clear, 255 full) that the device draws in + its own colour. Coverage is the alpha channel when any pixel is translucent, + else the gray level of an opaque grayscale PNG. + +Ships in the SDK beside rvx-pack, so it depends on nothing outside this file. + +Adapted from RepriseOS patching/bitmap.py (bf749b2) by lgreitis. +""" + +import struct +import zlib + +HEADER = struct.Struct("I4s", data, offset) + body = data[offset + 8 : offset + 8 + size] + crc = struct.unpack_from(">I", data, offset + 8 + size)[0] + if zlib.crc32(kind + body) != crc: + raise ValueError("PNG chunk checksum mismatch") + chunks.setdefault(kind, bytearray()).extend(body) + offset += size + 12 + width, height, depth, color, compression, filtering, interlace = struct.unpack( + ">IIBBBBB", chunks[b"IHDR"] + ) + channels = {0: 1, 2: 3, 3: 1, 4: 2, 6: 4}.get(color) + if ( + not width + or not height + or not (depth == 8 or color == 3 and depth in (1, 2, 4)) + or channels is None + or any((compression, filtering, interlace)) + ): + raise ValueError("export a non-interlaced PNG with 8-bit channels or a palette") + raw = zlib.decompress(chunks[b"IDAT"]) + stride = (width * channels * depth + 7) // 8 + filter_bytes = max(1, (channels * depth + 7) // 8) + if len(raw) != (stride + 1) * height: + raise ValueError("PNG pixel length does not match its dimensions") + palette = chunks.get(b"PLTE", b"") + alpha = chunks.get(b"tRNS", b"") + transparent = ( + tuple(struct.unpack(">" + "H" * channels, alpha)) + if alpha and color in (0, 2) + else None + ) + previous = bytearray(stride) + pixels = bytearray() + for y in range(height): + start = y * (stride + 1) + filter_type = raw[start] + if filter_type > 4: + raise ValueError("unknown PNG row filter") + row = bytearray(raw[start + 1 : start + 1 + stride]) + for x in range(stride): + a = row[x - filter_bytes] if x >= filter_bytes else 0 + b = previous[x] + c = previous[x - filter_bytes] if x >= filter_bytes else 0 + predictor = (0, a, b, (a + b) // 2, paeth(a, b, c))[filter_type] + row[x] = (row[x] + predictor) & 255 + for x in range(width): + p = tuple(row[x * channels : (x + 1) * channels]) + if color == 3: + bit = x * depth + index = (row[bit // 8] >> (8 - depth - bit % 8)) & ((1 << depth) - 1) + if index * 3 + 3 > len(palette): + raise ValueError("PNG pixel exceeds palette") + rgba = ( + *palette[index * 3 : index * 3 + 3], + alpha[index] if index < len(alpha) else 255, + ) + elif color in (0, 4): + rgba = ( + p[0], + p[0], + p[0], + p[1] if color == 4 else 0 if p == transparent else 255, + ) + else: + rgba = p if color == 6 else (*p, 0 if p == transparent else 255) + pixels.extend(rgba) + previous = row + return width, height, bytes(pixels) + + +def encode_bmap(width, height, rgba, sizes=()): + """BMap bytes for RGBA pixels: indexed with at most 256 colours, else BGRA; + `sizes` are the (width, height) the picture may have, any when empty.""" + if sizes and (width, height) not in sizes: + allowed = ", ".join(f"{w} x {h}" for w, h in sizes) + raise ValueError(f"the picture is {width} x {height}, not one of {allowed}") + if len(rgba) != width * height * 4: + raise ValueError("RGBA pixel length does not match its dimensions") + pixels = [rgba[i : i + 4] for i in range(0, len(rgba), 4)] + colors = list(dict.fromkeys(pixels)) + indexed = len(colors) <= 256 + depth = 8 if indexed else 32 + stride = (width * depth // 8 + 3) & ~3 + if not width or not height or stride > 0x7FFF: + raise ValueError("bitmap dimensions exceed the row stride") + padding = bytes(stride - width * depth // 8) + payload = bytearray() + if indexed: + payload += struct.pack(".rvt: a header, then one appearance pack + * for light and one for dark, either optional. The layout is documented in + * themes/docs/format.md; this header is its one source of numbers, + * vendored by the appearance extension byte for byte. All integers are + * little-endian. A reader accepts exactly RVT_VERSION and places the packs by + * the header's own header-bytes field, never by RVT_HEADER_BYTES. + * + * Invariants the defines cannot say: records are in ascending catalog index + * and padded to 4 bytes; a pixels record holds the bitmap from its data offset + * to its end (palette, then rows); an lz record decodes to exactly that length + * and the stream must end at the record's end; a recolour table is strictly + * ascending by `from` read as a little-endian u32; an alias names a catalog + * bitmap of the same size that is neither a mask nor tinted, and aliases are + * applied after the other records of the pack; every alpha byte in the style + * prefix is 255. The pack's extension bitmaps follow its last record, + * ascending by owner then asset (both FNV-1a hashes, as the extension package + * catalog keys them; the core's own assets are owned by the hash of "reprise"); + * a bitmap payload is the whole BMap as the iPod decodes it, its 28-byte header + * raw and its rows raw or as one lz stream decoding to the header's payload + * length, the stream at most the payload plus one flag byte per 8; a tinted + * extension bitmap is an Indexed8 or BGRA8888 picture, never a Settings icon, + * whose palette entries or pixels the reader paints in its role, keeping + * their alpha. The relight arithmetic and the bounds of its words are in + * docs/format.md under Relight. */ + +#ifndef RVT_H +#define RVT_H + +#define RVT_MAGIC 0x30545652u /* "RVT0" */ +#define RVT_VERSION 3 +#define RVT_HEADER_BYTES 128 +#define RVT_FINGERPRINT_BYTES 8 +#define RVT_ID_BYTES 32 +#define RVT_NAME_BYTES 48 + +/* Header field offsets. The CRC covers the first RVT_HEADER_BYTES with its own + * word as zero; the bytes after the name up to RVT_HEADER_BYTES are zero. */ +#define RVT_HEADER_MAGIC 0 /* u32 */ +#define RVT_HEADER_VERSION 4 /* u16 */ +#define RVT_HEADER_HEADER_BYTES 6 /* u16, where the packs begin */ +#define RVT_HEADER_FINGERPRINT 8 /* RVT_FINGERPRINT_BYTES */ +#define RVT_HEADER_APPEARANCES 16 /* u32, RVT_APPEARANCE_* bits */ +#define RVT_HEADER_LIGHT_OFFSET 20 /* u32, 0 when absent */ +#define RVT_HEADER_LIGHT_BYTES 24 /* u32 */ +#define RVT_HEADER_DARK_OFFSET 28 /* u32, 0 when absent */ +#define RVT_HEADER_DARK_BYTES 32 /* u32 */ +#define RVT_HEADER_CRC 36 /* u32 */ +#define RVT_HEADER_ID 40 /* RVT_ID_BYTES, NUL-padded ASCII */ +#define RVT_HEADER_NAME 72 /* RVT_NAME_BYTES, NUL-padded UTF-8 */ + +#define RVT_APPEARANCE_LIGHT 1 +#define RVT_APPEARANCE_DARK 2 + +/* Pack header field offsets; the body follows. */ +#define RVT_PACK_BODY_BYTES 0 /* u32, at least RVT_STYLE_BYTES */ +#define RVT_PACK_RECORDS 4 /* u32, record count */ +#define RVT_PACK_CRC 8 /* u32, CRC-32 of the body */ +#define RVT_PACK_EXTENSION_BITMAPS 12 /* u32, at most RVT_EXTENSION_BITMAPS_MAX */ +#define RVT_PACK_HEADER_BYTES 16 + +/* Colour roles, in prefix order. */ +enum rvt_role { + RVT_ROLE_BACKGROUND, + RVT_ROLE_TEXT, + RVT_ROLE_ACCENT_FILL, + RVT_ROLE_ACCENT_TEXT, + RVT_ROLE_ON_ACCENT, + RVT_ROLE_SELECTION, + RVT_ROLE_COVER_BORDER, + RVT_ROLE_ICON_TINT, + RVT_ROLES +}; + +/* Named accents a listener picks, in palette order. */ +enum rvt_accent { + RVT_ACCENT_BLUE, + RVT_ACCENT_PURPLE, + RVT_ACCENT_PINK, + RVT_ACCENT_RED, + RVT_ACCENT_ORANGE, + RVT_ACCENT_GREEN, + RVT_ACCENT_TEAL, + RVT_ACCENT_YELLOW, + RVT_ACCENT_GRAPHITE, + RVT_ACCENTS +}; + +/* The slots of an accent palette, each replacing the role of its name. */ +enum rvt_accent_slot { + RVT_SLOT_ACCENT_FILL, + RVT_SLOT_ACCENT_TEXT, + RVT_SLOT_SELECTION, + RVT_SLOT_ON_ACCENT, + RVT_SLOT_ICON_TINT, + RVT_ACCENT_SLOTS +}; + +#define RVT_FLAG_FLAT_SELECTION 1 +#define RVT_FLAG_MENU_COVERS_OFF 2 +#define RVT_FLAG_FLAT_NOW_PLAYING 4 +#define RVT_FLAG_FLAT_ICONS 8 /* extension menu icons without their reflection */ + +/* Tint bytes: RVT_TINT_ROLE plus an rvt_role. A reader packs them two per + * byte, so they stay below 16. One coverage bit may be or-ed into the byte. */ +#define RVT_TINT_NONE 0 +#define RVT_TINT_ROLE 1 +#define RVT_TINT_DARKNESS 0x80 /* coverage from darkness */ +#define RVT_TINT_SOLID 0x40 /* coverage at or above RVT_SOLID_FLOOR becomes full */ +#define RVT_SOLID_FLOOR 150 /* of 255; a 4-bit mask level at or above 150 x 15 / 255 */ + +/* Catalog bitmaps a pack can address: records and tint bytes index them. */ +#define RVT_CATALOG_MAX 640 + +/* Style prefix offsets. */ +#define RVT_STYLE_COLORS 0 /* RVT_ROLES x RGBA */ +#define RVT_STYLE_FLAGS (RVT_ROLES * 4) +#define RVT_STYLE_PALETTES (RVT_STYLE_FLAGS + 4) /* RVT_ACCENTS x RVT_ACCENT_SLOTS x RGBA */ +#define RVT_STYLE_TINTS (RVT_STYLE_PALETTES + RVT_ACCENTS * RVT_ACCENT_SLOTS * 4) +#define RVT_STYLE_BYTES (RVT_STYLE_TINTS + RVT_CATALOG_MAX) +#define RVT_RECORD_BYTES 12 + +/* Record kinds, the second record word. Every kind but the two pixel kinds is + * computed on the iPod from the bitmap's stock bytes. */ +enum rvt_kind { + RVT_KIND_PIXELS, /* the bitmap's bytes from its data offset to its end */ + RVT_KIND_RECOLOR, /* u32 count, count x {u8 from[4], u8 to[4]} RGBA */ + RVT_KIND_ALIAS, /* u32 source catalog index: its pixels as the pack leaves them */ + RVT_KIND_INVERT, /* no payload: RGB inverted, alpha kept */ + RVT_KIND_RELIGHT, /* RVT_RELIGHT_WORDS x i32 8.8, enum rvt_relight order */ + RVT_KIND_PIXELS_LZ, /* RVT_KIND_PIXELS compressed as RVT_LZ describes */ + RVT_KINDS +}; + +/* RVT_LZ: groups of a flag byte and up to 8 items, bit 0 first. A clear bit is + * a literal byte. A set bit is a match of two bytes, LLLLDDDD DDDDDDDD: it + * copies L + 3 bytes from D + 1 bytes back in the output; L = 15 adds the + * following bytes to the length while they are 255, and the first that is not. + * Matches copy from the output itself, so a decoder needs no window. */ +#define RVT_LZ_WINDOW 4096 +#define RVT_LZ_MIN_MATCH 3 + +/* Relight words, in payload order. */ +enum rvt_relight { + RVT_RELIGHT_T_ZERO, + RVT_RELIGHT_T_FULL, + RVT_RELIGHT_BG_BASE, + RVT_RELIGHT_BG_REF, + RVT_RELIGHT_BG_SLOPE, + RVT_RELIGHT_BG_LO, + RVT_RELIGHT_BG_HI, + RVT_RELIGHT_ICON_BASE, + RVT_RELIGHT_ICON_LUMA, + RVT_RELIGHT_ICON_ROW, + RVT_RELIGHT_ICON_LO, + RVT_RELIGHT_ICON_HI, + RVT_RELIGHT_WORDS +}; +#define RVT_RELIGHT_BYTES (RVT_RELIGHT_WORDS * 4) + +/* Limits the reader's one scratch block per switch imposes: a recolour table + * of RVT_RECOLOR_MAX pairs, or the per-pixel grays of a relight or a + * re-encoded alias plus a 256-byte gray map. */ +#define RVT_SCRATCH_BYTES 4096 +#define RVT_RECOLOR_MAX 512 +#define RVT_SCRATCH_PIXELS 3840 +/* Alias records are applied after the other records of a pack. */ +#define RVT_ALIASES_MAX 16 + +/* Extension bitmaps: {u32 owner, u32 asset, u32 kind, u32 stored, u32 decoded, + * u32 tint} then the payload, 4-byte padded: the whole BMap, header and rows, + * raw or as one lz stream of `stored` bytes that decodes to `decoded`. The + * tint word is RVT_TINT_NONE, or RVT_TINT_ROLE plus an rvt_role without + * coverage bits for a picture drawn in that role. */ +#define RVT_EXTENSION_BITMAP_BYTES 24 +#define RVT_BMAP_HEADER_BYTES 28 +enum rvt_extension_kind { + RVT_EXTENSION_BITMAP = 1, + RVT_EXTENSION_BITMAP_LZ, + RVT_EXTENSION_KINDS +}; +#define RVT_EXTENSION_BITMAPS_MAX 64 +#define RVT_EXTENSION_BITMAP_MAX_BYTES 65536 /* header and rows, decoded */ + +_Static_assert(RVT_TINT_ROLE + RVT_ROLES <= 16, "tint bytes are packed in nibbles"); + +#endif diff --git a/themes/rvt/derive.py b/themes/rvt/derive.py new file mode 100644 index 0000000..9b0c063 --- /dev/null +++ b/themes/rvt/derive.py @@ -0,0 +1,658 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""Derived art: records the iPod computes from the stock bitmaps, so a theme +carries colours and rules instead of pixels. + +The authoring side is a rule with a `kind`: one TOML file per bitmap, or a +glob rule in theme.toml. This module parses rules, checks them against the +catalog, encodes and decodes the record payloads, and holds the reference +arithmetic the appearance extension mirrors, applied here to bitmap bytes for +rules the compiler resolves itself (`from_other`), for tests and for previews. +Nothing here reads the firmware; rvt.firmware supplies stock bytes when a +caller has them. +""" + +import re +import struct +import tomllib +from dataclasses import dataclass +from pathlib import Path + +from rvt import bitmaps, rvtfile +from rvt.catalog import Catalog, Entry, entries +from rvt.errors import fail + +RGBA = re.compile(r"#[0-9A-Fa-f]{8}") +KEYS = { + "recolor": {"kind", "from_other", "map"}, + "alias": {"kind", "from_other", "source"}, + "invert": {"kind", "from_other"}, + "relight": {"kind", "from_other", *rvtfile.RELIGHT_FIELDS}, +} +# Classic dark's relight, fitted to its hand-made proxies. +RELIGHT_DEFAULTS = dict( + zip( + rvtfile.RELIGHT_FIELDS, + (3, 14, 25, 216, 10 / 28, 24, 35, 394.6, -1.170, -1.769, 40, 160), + ) +) +ONE = 256 # 8.8 fixed point +FULL = 255 # coverage scale +# The bounds derive.c accepts, in 8.8 units, so the arithmetic cannot overflow. +LEVEL_MAX = 255 * ONE +assert LEVEL_MAX * FULL < 1 << 24 # the per-pixel products stay in 32 bits with room +BASE_MAX = 1024 * ONE +SLOPE_MAX = 16 * ONE +RELIGHT_BOUNDS = { + "bg_base": BASE_MAX, + "bg_ref": LEVEL_MAX, + "bg_slope": SLOPE_MAX, + "icon_base": BASE_MAX, + "icon_luma": LEVEL_MAX, + "icon_row": LEVEL_MAX, +} + + +@dataclass(frozen=True) +class Rule: + """A record before it is encoded: the kind, its spec (a pixels payload, + recolour pairs, an alias source index, None for invert, relight words) and + whether it starts from the theme's own art in the other appearance.""" + + kind: str + spec: object + from_other: bool = False + + +def to_fixed(value, where: str) -> int: + if isinstance(value, bool) or not isinstance(value, (int, float)): + fail(where, "expected a number") + fixed = round(value * ONE) + if not -(1 << 31) <= fixed < 1 << 31: + fail(where, "out of range") + return fixed + + +def rgba(value, where: str) -> bytes: + if not isinstance(value, str) or not RGBA.fullmatch(value): + fail(where, 'expected "#rrggbbaa"') + return bytes.fromhex(value[1:]) + + +def key(color: bytes) -> int: + """A colour as the little-endian u32 the records sort by.""" + return int.from_bytes(color, "little") + + +def is_mask(info: Entry) -> bool: + return info["format"] in bitmaps.MASK_FORMATS + + +def is_565(info: Entry) -> bool: + return info["format"] == bitmaps.RGB565 + + +def same_layout(first: Entry, second: Entry) -> bool: + return all( + first[k] == second[k] + for k in ( + "format", + "width", + "height", + "stride", + "bytes", + "data_offset", + "pixels_offset", + "palette_colors", + ) + ) + + +# Parsing and checks + + +def load(path: Path, index: int, catalog: Catalog, where: str) -> Rule: + """The rule of a derivation file, see `rule`.""" + try: + table = tomllib.loads(path.read_bytes().decode("utf-8")) + except UnicodeDecodeError: + fail(where, "expected UTF-8") + except tomllib.TOMLDecodeError as error: + fail(where, f"invalid TOML: {error}") + return rule(table, index, catalog, where) + + +def rule(table: dict, index: int, catalog: Catalog, where: str) -> Rule: + """The Rule of a rule table: recolor -> sorted colour pairs, alias -> + source index, invert -> None, relight -> fixed-point words. from_other + says the rule starts from the theme's own PNG in the other appearance + instead of the stock bitmap; an alias may then leave `source` out to + reuse its own art unchanged.""" + if not isinstance(table, dict): + fail(where, "expected a table") + kind = table.get("kind") + if kind not in KEYS: + fail(where, f"expected kind = {', '.join(repr(k) for k in KEYS)}") + for name in sorted(table): + if name not in KEYS[kind]: + fail(f"{where}.{name}", "unknown key") + from_other = table.get("from_other", False) + if not isinstance(from_other, bool): + fail(f"{where}.from_other", "expected true or false") + info = catalog.assets[index] + if kind == "recolor": + pairs = read_map(table.get("map"), f"{where}.map") + check_recolor(pairs, info, where) + return Rule(kind, pairs, from_other) + if kind == "alias": + source = table.get("source") + if source is None and from_other: + return Rule(kind, index, True) + if not isinstance(source, str): + fail(f"{where}.source", "expected a catalog name or hex id") + found = catalog.resolve(source, f"{where}.source") + if found != index or not from_other: + check_alias(info, catalog.assets[found], f"{where}.source", from_other) + return Rule(kind, found, from_other) + if kind == "invert": + check_invert(info, where) + return Rule(kind, None, from_other) + words = relight_words(table, where) + check_relight(words, info, where) + return Rule(kind, words, from_other) + + +def read_map(table, where: str) -> list[tuple[bytes, bytes]]: + if not isinstance(table, dict) or not table: + fail(where, 'expected a table of "#rrggbbaa" = "#rrggbbaa"') + pairs = {} + for source, target in table.items(): + at = f'{where}."{source}"' + source, target = rgba(source, at), rgba(target, at) + if source == target: + fail(at, "maps a colour to itself") + if source in pairs: + fail(at, "duplicate colour") + pairs[source] = target + return sorted(pairs.items(), key=lambda pair: key(pair[0])) + + +def check_recolor(pairs: list, info: Entry, where: str) -> None: + if is_mask(info): + fail(where, f"{info['name']} is a mask; it has no colours to recolour") + if len(pairs) > rvtfile.RECOLOR_MAX: + fail(where, f"more than {rvtfile.RECOLOR_MAX} colour pairs") + if len(pairs) > entries(info): + fail(where, f"more colour pairs than {info['name']} has entries") + if is_565(info): + for source, target in pairs: + for color in (source, target): + if not bitmaps.is_565(color): + fail( + f'{where}."#{color.hex()}"', + "RGB565 needs opaque colours with r and b multiples of 8" + " and g a multiple of 4", + ) + + +def describe_layout(info: Entry) -> str: + return f"{info['name']} ({info['format']:#x} {info['width']}x{info['height']})" + + +def alias_fits(target: Entry, source: Entry) -> bool: + """Whether source's pixels can become target's: the same size, neither a + mask. Equal layouts are copied byte for byte; otherwise the pixels are + re-encoded, and a paletted target must hold the source's distinct colours, + which only the iPod can count.""" + return ( + target["id"] != source["id"] + and not is_mask(target) + and not is_mask(source) + and target["width"] == source["width"] + and target["height"] == source["height"] + ) + + +def check_alias( + target: Entry, source: Entry, where: str, from_other: bool = False +) -> None: + """Of the stock bitmaps; with from_other a bitmap may name itself for its + own art in the other appearance, and the compiler does the re-encoding + the iPod otherwise caps at SCRATCH_PIXELS.""" + if target["id"] == source["id"]: + fail(where, f"{target['name']} cannot alias itself without from_other") + if not alias_fits(target, source): + fail( + where, + f"{describe_layout(source)} does not fit {describe_layout(target)}: an" + " alias needs the same size and no mask on either side", + ) + pixels = target["width"] * target["height"] + if not from_other and not same_layout(target, source): + if pixels > rvtfile.SCRATCH_PIXELS: + fail( + where, + f"{describe_layout(source)} must be re-encoded into " + f"{describe_layout(target)}, which the iPod does for at most " + f"{rvtfile.SCRATCH_PIXELS} pixels", + ) + + +def check_aliases(aliases: dict, tinted: dict, names, where) -> None: + """The pack-wide alias rules: at most ALIASES_MAX, no alias of an alias, + no tinted source. aliases maps index -> source index; names(index) and + where(index) give the messages their words.""" + if len(aliases) > rvtfile.ALIASES_MAX: + fail(where(None), f"more than {rvtfile.ALIASES_MAX} aliases") + for index, source in aliases.items(): + if source in aliases: + fail(where(index), f"{names(source)} is an alias itself") + if source in tinted: + fail(where(index), f"{names(source)} is tinted") + + +def check_invert(info: Entry, where: str) -> None: + if is_mask(info): + fail(where, f"{info['name']} is a mask; tint it instead") + + +def relight_words(table: dict, where: str) -> list[int]: + values = dict(RELIGHT_DEFAULTS) + for name in rvtfile.RELIGHT_FIELDS: + if name in table: + values[name] = table[name] + return [ + to_fixed(values[name], f"{where}.{name}") for name in rvtfile.RELIGHT_FIELDS + ] + + +def relight_levels(words: list[int]) -> int: + """Palette entries a relight may need: one per gray between bg_lo and icon_hi.""" + w = dict(zip(rvtfile.RELIGHT_FIELDS, words)) + return ((w["icon_hi"] + ONE // 2) >> 8) - (w["bg_lo"] >> 8) + 1 + + +def check_relight(words: list[int], info: Entry, where: str) -> None: + """The bounds derive.c enforces, so a rule the compiler accepts is one the + iPod applies.""" + w = dict(zip(rvtfile.RELIGHT_FIELDS, words)) + if not 0 <= w["t_zero"] < w["t_full"] <= LEVEL_MAX: + fail(where, "expected 0 <= t_zero < t_full <= 255") + for name, bound in RELIGHT_BOUNDS.items(): + if abs(w[name]) > bound: + fail(f"{where}.{name}", f"expected -{bound // ONE} to {bound // ONE}") + if not 0 <= w["bg_lo"] <= w["bg_hi"] <= w["icon_lo"] <= w["icon_hi"] <= LEVEL_MAX: + fail(where, "expected 0 <= bg_lo <= bg_hi <= icon_lo <= icon_hi <= 255") + if info["format"] not in bitmaps.PALETTE_FORMATS: + fail(where, f"relight needs a paletted bitmap; {info['name']} is not") + if info["width"] * info["height"] > rvtfile.SCRATCH_PIXELS: + fail(where, f"{info['name']} has more than {rvtfile.SCRATCH_PIXELS} pixels") + if relight_levels(words) > info["palette_colors"]: + fail( + where, + f"needs {relight_levels(words)} palette entries, " + f"{info['name']} has {info['palette_colors']}", + ) + + +# Record payloads + + +def encode(kind: str, spec) -> bytes: + if kind in rvtfile.PIXEL_KINDS: + return spec + if kind == "recolor": + return struct.pack(" object: + """The spec of a payload after its structural checks; catalog checks are + the caller's.""" + if kind == "recolor": + if ( + len(payload) < 4 + rvtfile.PAIR.size + or (len(payload) - 4) % rvtfile.PAIR.size + ): + fail(where, "recolor payload must be a count and whole colour pairs") + count = struct.unpack_from(" int: + return (77 * red + 150 * green + 29 * blue) >> 8 + + +def div255(value: int) -> int: + """value / 255 rounded, as the iPod's pixel helper does.""" + return (value + 1 + (value >> 8)) >> 8 + + +def tdiv(a: int, b: int) -> int: + """Division truncating toward zero, as C does.""" + q = abs(a) // abs(b) + return q if (a < 0) == (b < 0) else -q + + +def clamp(value: int, low: int, high: int) -> int: + return max(low, min(high, value)) + + +def _palette(info, data): + start = info["data_offset"] + return [ + bytearray(data[start + i * 4 : start + i * 4 + 4]) + for i in range(info["palette_colors"]) + ] + + +def _write_palette(info, data, palette): + start = info["data_offset"] + for i, entry in enumerate(palette): + data[start + i * 4 : start + i * 4 + 4] = entry + + +def _index(info, data, x, y): + at = info["pixels_offset"] + y * info["stride"] + if info["format"] == bitmaps.INDEXED8: + return data[at + x] + return struct.unpack_from(" bytes: + table = dict(pairs) + out = bytearray(data) + for at, size in _each_slot(info, out): + target = table.get(_slot_rgba(out, at, size)) + if target is not None: + _set_slot(out, at, size, target) + return bytes(out) + + +def apply_invert(info: Entry, data: bytes) -> bytes: + out = bytearray(data) + for at, size in _each_slot(info, out): + if size == 4: + if info["palette_colors"] or out[at + 3]: + for i in range(3): + out[at + i] ^= 255 + else: + struct.pack_into( + " int: + """A coverage level with the solid floor applied: full from the floor up, + the floor scaled to the level range of the format.""" + return full if level * FULL >= rvtfile.SOLID_FLOOR * full else level + + +def apply_coverage(info: Entry, data: bytes, coverage: str) -> bytes: + """Tinted stock art as the iPod prepares it: alpha, darkness (alpha scaled + by 255 - luma) or solid coverage, on palette entries, BGRA pixels or mask + levels. Alpha coverage leaves the bytes alone.""" + if coverage == "alpha": + return data + out = bytearray(data) + if is_mask(info): + if coverage != "solid": + raise ValueError(f"{info['name']} is a mask; its coverage is its level") + start, stride = info["pixels_offset"], info["stride"] + for y in range(info["height"]): + row = start + y * stride + for x in range(info["width"]): + if info["format"] == bitmaps.MASK8: + out[row + x] = solid_level(out[row + x], FULL) + else: + at, shift = row + x // 2, 4 if x % 2 == 0 else 0 + level = solid_level(out[at] >> shift & 15, 15) + out[at] = out[at] & ~(15 << shift) | level << shift + return bytes(out) + if is_565(info): + raise ValueError(f"{info['name']} has no coverage") + for at, _ in _each_slot(info, out): + blue, green, red, alpha = out[at : at + 4] + if coverage == "darkness": + out[at + 3] = div255(alpha * (FULL - luma(red, green, blue))) + else: + out[at + 3] = solid_level(alpha, FULL) + return bytes(out) + + +def relight_coverage(words: list[int], info: Entry, data: bytes) -> bytearray: + """t per pixel, 0..FULL, after shadow pruning.""" + w = dict(zip(rvtfile.RELIGHT_FIELDS, words)) + palette = _palette(info, data) + width, height = info["width"], info["height"] + t = bytearray(width * height) + for y in range(height): + bg = palette[_index(info, data, 0, y)] + for x in range(width): + c = palette[_index(info, data, x, y)] + o = max(abs(c[i] - bg[i]) for i in range(3)) * ONE + if o <= w["t_zero"]: + value = 0 + elif o >= w["t_full"]: + value = FULL + else: + value = (o - w["t_zero"]) * FULL // (w["t_full"] - w["t_zero"]) + t[y * width + x] = value + pruned = bytearray(t) + for y in range(height): + for x in range(width): + if not 0 < t[y * width + x] < FULL: + continue + solid = False + for dy in (-1, 0, 1): + for dx in (-1, 0, 1): + nx, ny = x + dx, y + dy + if (dx or dy) and 0 <= nx < width and 0 <= ny < height: + solid |= t[ny * width + nx] == FULL + if not solid: + pruned[y * width + x] = 0 + return pruned + + +def relight_gray(words: list[int], c: bytes, bg: bytes, y: int, t: int) -> int: + """The gray of one pixel: c and bg are BGRA, t is 0..FULL.""" + w = dict(zip(rvtfile.RELIGHT_FIELDS, words)) + bgd = w["bg_base"] + tdiv( + (luma(bg[2], bg[1], bg[0]) * ONE - w["bg_ref"]) * w["bg_slope"], ONE + ) + bgd = clamp(bgd, w["bg_lo"], w["bg_hi"]) + icon = w["icon_base"] + w["icon_luma"] * luma(c[2], c[1], c[0]) + w["icon_row"] * y + icon = clamp(icon, w["icon_lo"], w["icon_hi"]) + mixed = bgd + ((icon - bgd) * t + FULL // 2) // FULL + return (mixed + ONE // 2) >> 8 + + +def apply_relight(info: Entry, data: bytes, words: list[int]) -> bytes: + out = bytearray(data) + palette = _palette(info, out) + width, height = info["width"], info["height"] + t = relight_coverage(words, info, out) + grays = bytearray(width * height) + for y in range(height): + bg = palette[_index(info, out, 0, y)] + for x in range(width): + c = palette[_index(info, out, x, y)] + grays[y * width + x] = relight_gray(words, c, bg, y, t[y * width + x]) + levels = sorted(set(grays)) + if len(levels) > info["palette_colors"]: + raise ValueError("relight produced more grays than the palette holds") + lookup = {gray: i for i, gray in enumerate(levels)} + _write_palette( + info, + out, + [bytearray((g, g, g, 255)) for g in levels] + + [bytearray(4) for _ in range(info["palette_colors"] - len(levels))], + ) + for y in range(height): + for x in range(width): + _set_index(info, out, x, y, lookup[grays[y * width + x]]) + return bytes(out) + + +def apply_alias(target: Entry, data: bytes, source: Entry, source_data: bytes) -> bytes: + """Target with the source's pixels: a byte copy for equal layouts, else the + pixels re-encoded; a paletted target takes the distinct colours in order of + first appearance and must have room for them.""" + out = bytearray(data) + if same_layout(target, source): + start = target["data_offset"] + out[start:] = source_data[start:] + return bytes(out) + pixels = bitmaps.decode_pixels(source, source_data[source["data_offset"] :]) + width, height = target["width"], target["height"] + palette = {} + for y in range(height): + at = target["pixels_offset"] + y * target["stride"] + for x in range(width): + i = (y * width + x) * 4 + red, green, blue, alpha = pixels[i : i + 4] + if target["palette_colors"]: + color = bytes((blue, green, red, alpha)) + if color not in palette: + if len(palette) == target["palette_colors"]: + raise ValueError( + f"{source['name']} has more colours than " + f"{target['name']}'s palette holds" + ) + palette[color] = len(palette) + _set_index(target, out, x, y, palette[color]) + elif is_565(target): + word = bitmaps.pack_565(red, green, blue) + struct.pack_into(" bytes: + """One record over stock(index), or over `base`, the other appearance's + pixels payload of this bitmap (of the source, for an alias). An alias + without a base reads its source from results when the pack derived or + replaced it, else from stock.""" + info = catalog.assets[index] + data = stock(index) + if base is not None: + if kind == "alias": + source = catalog.assets[spec] + return apply_alias( + info, data, source, stock(spec)[: source["data_offset"]] + base + ) + data = data[: info["data_offset"]] + base + if kind in rvtfile.PIXEL_KINDS: + return data[: info["data_offset"]] + spec + if kind == "recolor": + return apply_recolor(info, data, spec) + if kind == "invert": + return apply_invert(info, data) + if kind == "relight": + return apply_relight(info, data, spec) + source_data = results[spec] if spec in results else stock(spec) + return apply_alias(info, data, catalog.assets[spec], source_data) + + +def apply_pack(catalog: Catalog, stock, records) -> dict[int, bytes]: + """Index -> derived bitmap bytes for a pack's records (index, kind, spec), + in the device's order: everything but aliases ascending, then the aliases. + stock(index) returns a bitmap's stock bytes.""" + results = {} + aliases = [] + for index, kind, spec in records: + if kind == "alias": + aliases.append((index, spec)) + continue + results[index] = apply_record(catalog, stock, index, kind, spec, results) + for index, source in aliases: + results[index] = apply_record(catalog, stock, index, "alias", source, results) + return results diff --git a/themes/rvt/errors.py b/themes/rvt/errors.py new file mode 100644 index 0000000..78176d8 --- /dev/null +++ b/themes/rvt/errors.py @@ -0,0 +1,7 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""The one error the toolchain raises for bad input.""" + + +def fail(where: str, message: str): + """Raise a ValueError that names where in the input the problem is.""" + raise ValueError(f"{where}: {message}" if where else message) diff --git a/themes/rvt/firmware.py b/themes/rvt/firmware.py new file mode 100644 index 0000000..521d80b --- /dev/null +++ b/themes/rvt/firmware.py @@ -0,0 +1,186 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""A local firmware image as the source of stock bitmaps: previews of derived +art, and derivation files written from an author's PNG when the PNG is a pure +recolour of the stock bitmap. The compiler and inspector never import this +module.""" + +import zlib +from collections import defaultdict + +from rvt import bitmaps, derive, inspector, rvtfile + + +class Firmware: + """Stock bitmaps read at the catalog's offsets; osos.bin or reprise.bin.""" + + def __init__(self, path, catalog): + self.data = path.read_bytes() + self.catalog = catalog + self.checked = {} + + def bitmap(self, index): + info = self.catalog.assets[index] + if index not in self.checked: + data = self.data[info["offset"] : info["offset"] + info["bytes"]] + if len(data) != info["bytes"] or zlib.crc32(data) != info["crc32"]: + raise ValueError( + f"firmware: {info['name']} at {info['offset']:#x} does not carry" + " the catalog checksum" + ) + self.checked[index] = data + return self.checked[index] + + +def render(catalog, firmware, data): + """Every record of an .rvt applied to the stock bitmaps, and every tinted + stock bitmap whose coverage the iPod rewrites (kind `coverage`): + appearance -> name -> {index, kind, address, bytes, crc32, png}, plus + warnings about recolour pairs that match no stock colour.""" + result = {} + warnings = [] + for appearance, pack in inspector.inspect(data, catalog)["appearances"].items(): + records = [ + ( + record["index"], + record["kind"], + record["payload"] + if record["kind"] in rvtfile.PIXEL_KINDS + else record["spec"], + ) + for record in pack["records"] + ] + derived = derive.apply_pack(catalog, firmware.bitmap, records) + for index, tint in pack["tinted"].items(): + if index not in derived and tint["coverage"] != "alpha": + derived[index] = derive.apply_coverage( + catalog.assets[index], firmware.bitmap(index), tint["coverage"] + ) + records.append((index, "coverage", tint["coverage"])) + result[appearance] = {} + for index, kind, spec in records: + info = catalog.assets[index] + bitmap = derived[index] + result[appearance][info["name"]] = { + "index": index, + "kind": kind, + "address": info["address"], + "bytes": info["bytes"], + "crc32": zlib.crc32(bitmap), + "png": bitmaps.write_png( + info["width"], + info["height"], + bitmaps.decode_pixels(info, bitmap[info["data_offset"] :]), + ), + } + if kind == "recolor": + unused = unmatched(info, firmware.bitmap(index), spec) + if unused: + warnings.append( + f"{appearance}/apple/{info['name']}.toml: {len(unused)} of " + f"{len(spec)} pairs match no stock colour: " + + ", ".join(f"#{c.hex()}" for c in unused[:4]) + ) + return result, warnings + + +def stock_colors(info, bitmap): + """The distinct stock colours a recolour can match.""" + pixels = bitmaps.decode_pixels(info, bitmap[info["data_offset"] :]) + if info["palette_colors"]: + start = info["data_offset"] + return { + bytes( + ( + bitmap[start + i * 4 + 2], + bitmap[start + i * 4 + 1], + bitmap[start + i * 4], + bitmap[start + i * 4 + 3], + ) + ) + for i in range(info["palette_colors"]) + } + return {pixels[i : i + 4] for i in range(0, len(pixels), 4)} + + +def unmatched(info, bitmap, pairs): + colors = stock_colors(info, bitmap) + return [source for source, _ in pairs if source not in colors] + + +NOISE = 16 # channel levels an editor's dithering may spread one colour over +STRAY_SHARE = 16 # a stray colour covers at most 1/16 of a stock colour's pixels + + +def quantize_565(color): + red, green, blue, alpha = color + return bytes((red & ~7, green & ~3, blue & ~7, alpha)) + + +def distance(first, second): + """Largest channel difference of two RGBA colours with alpha applied, so + fully transparent colours are equal whatever their RGB.""" + + def visible(color): + return (*(c * color[3] // 255 for c in color[:3]), color[3]) + + return max(abs(a - b) for a, b in zip(visible(first), visible(second))) + + +def to_recolor(catalog, firmware, index, png): + """Colour pairs that turn the stock bitmap into the PNG, and notes about + stray pixels. A stock colour the PNG paints in several colours takes the + most frequent one when the others are within NOISE of it or cover at most + 1/STRAY_SHARE of its pixels; a wider spread is a ValueError naming the + colours. Targets of an RGB565 bitmap are rounded to what the format + stores.""" + info = catalog.assets[index] + width, height, rgba = bitmaps.read_png(png) + if (width, height) != (info["width"], info["height"]): + raise ValueError( + f"expected {info['width']}x{info['height']}, got {width}x{height}" + ) + bitmap = firmware.bitmap(index) + stock = bitmaps.decode_pixels(info, bitmap[info["data_offset"] :]) + targets = defaultdict(lambda: defaultdict(int)) + for i in range(0, len(rgba), 4): + target = rgba[i : i + 4] + if derive.is_565(info): + target = quantize_565(target) + targets[stock[i : i + 4]][target] += 1 + chosen = {} + conflicts = [] + notes = [] + for source, counts in targets.items(): + best = max(counts, key=counts.get) + total = sum(counts.values()) + strays = 0 + for other, count in counts.items(): + if distance(best, other) <= NOISE: + continue + if count * STRAY_SHARE <= total: + strays += count + continue + conflicts.append( + f"#{source.hex()} maps to {len(counts)} colours over {total} pixels" + ) + break + if strays: + notes.append(f"#{source.hex()}: {strays} of {total} pixels ignored") + chosen[source] = best + if conflicts: + raise ValueError( + f"not a pure recolour: {len(conflicts)} stock colours map to several " + "colours\n" + "\n".join(sorted(conflicts)) + ) + pairs = sorted( + ((source, target) for source, target in chosen.items() if source != target), + key=lambda pair: derive.key(pair[0]), + ) + derive.check_recolor(pairs, info, info["name"]) + return pairs, notes + + +def recolor_text(pairs): + lines = ['kind = "recolor"', "", "[map]"] + lines += [f'"#{source.hex()}" = "#{target.hex()}"' for source, target in pairs] + return "\n".join(lines) + "\n" diff --git a/themes/rvt/inspector.py b/themes/rvt/inspector.py new file mode 100644 index 0000000..1a7f3a6 --- /dev/null +++ b/themes/rvt/inspector.py @@ -0,0 +1,205 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""Validate an .rvt and describe it, against the catalog when one is given.""" + +from rvt import assets, bitmaps, derive, lz, rvtfile, style +from rvt.catalog import Catalog +from rvt.errors import fail + + +def inspect_pack( + body: bytes, + count: int, + bitmap_count: int, + catalog: Catalog | None, + where: str, + names: dict | None = None, +) -> dict: + """Decoded style, records and extension bitmaps of one pack after checking + every record. A pixels record's `payload` is the bitmap's bytes from its + data offset, decoded for the lz kind when the catalog gives the size; an + extension bitmap's `bmap` is its decoded whole BMap. Messages name the + bitmap when there is a catalog, else its index; extension bitmaps are + named from `names` ((owner hash, asset hash) -> "id/asset") when it knows + them.""" + if catalog is not None and ( + len(body) > catalog.max_body() + rvtfile.EXTENSION_TABLE_MAX_BYTES + ): + fail(where, "pack exceeds the catalog maximum") + try: + decoded = style.decode(body[: rvtfile.STYLE_BYTES]) + except ValueError as error: + fail(where, str(error)) + entries = catalog.assets if catalog is not None else None + + def label(index): + if entries is not None and index < len(entries): + return entries[index]["name"] + return f"bitmap {index}" + + records = [] + at = rvtfile.STYLE_BYTES + previous = -1 + for _ in range(count): + if at + rvtfile.RECORD_BYTES > len(body): + fail(where, "truncated record header") + offset = at + index, word, length = rvtfile.RECORD.unpack_from(body, at) + if index <= previous: + fail(where, "records must be sorted by unique catalog index") + previous = index + if word >= len(rvtfile.KINDS): + fail(where, f"{label(index)} has unknown record kind {word:#x}") + kind = rvtfile.KINDS[word] + info = None + if entries is not None: + if index >= len(entries): + fail(where, f"catalog index {index} is outside the catalog") + info = entries[index] + if kind == "pixels" and length != catalog.payload_bytes(index): + fail(where, f"{label(index)} does not match the native bitmap") + at += rvtfile.RECORD_BYTES + end = at + length + if (not length and kind != "invert") or rvtfile.align(end) > len(body): + fail(where, "truncated record payload") + payload = body[at:end] + record = {"index": index, "kind": kind, "bytes": length, "offset": offset} + if kind in rvtfile.PIXEL_KINDS: + if kind == "pixels_lz" and info is not None: + try: + payload = lz.lz_decode(payload, catalog.payload_bytes(index)) + except ValueError as error: + fail(where, f"{label(index)}: {error}") + if info is not None and not bitmaps.palette_indices_fit(info, payload): + fail(where, f"{label(index)} has an invalid palette index") + record["payload"] = payload + else: + spec = derive.decode(kind, payload, f"{where} {label(index)}") + record["spec"] = spec + if info is not None: + check_derived(kind, spec, index, catalog, f"{where} {label(index)}") + if any(body[end : rvtfile.align(end)]): + fail(where, "record padding must be zero") + records.append(record) + at = rvtfile.align(end) + if catalog is not None and at > catalog.max_body(): + fail(where, "records exceed the catalog maximum") + decoded["extension_bitmaps"], at = assets.decode_table( + body, at, bitmap_count, where + ) + for found in decoded["extension_bitmaps"]: + found["name"] = assets.label(found, names or {}) + if at != len(body): + fail(where, "trailing bytes after the last extension bitmap") + by_index = {record["index"]: record for record in records} + derive.check_aliases( + {r["index"]: r["spec"] for r in records if r["kind"] == "alias"}, + decoded["tinted"], + label, + lambda index: where if index is None else f"{where} alias {label(index)}", + ) + for index, (role, coverage) in decoded["tinted"].items(): + record = by_index.get(index) + if record is not None and record["kind"] not in rvtfile.PIXEL_KINDS: + fail(where, f"tinted {label(index)} has a derived record") + if record is not None and coverage != "alpha": + fail(where, f"tinted {label(index)} takes its coverage from stock art") + if entries is None: + continue + if index >= len(entries): + fail(where, f"tinted catalog index {index} is outside the catalog") + if bitmaps.tint_kind(entries[index]["format"]) is None: + fail(where, f"tinted {label(index)} has no palette or coverage") + if entries is not None: + for record in records: + record["name"] = entries[record["index"]]["name"] + decoded["tinted"] = { + index: {"name": entries[index]["name"], "role": role, "coverage": coverage} + for index, (role, coverage) in decoded["tinted"].items() + } + else: + decoded["tinted"] = { + index: {"role": role, "coverage": coverage} + for index, (role, coverage) in decoded["tinted"].items() + } + decoded["records"] = records + decoded["bytes"] = len(body) + return decoded + + +def check_derived(kind: str, spec, index: int, catalog: Catalog, where: str) -> None: + """Catalog checks of a derived record.""" + info = catalog.assets[index] + if kind == "recolor": + derive.check_recolor(spec, info, where) + elif kind == "alias": + if spec >= len(catalog.assets): + fail(where, f"alias source {spec} is outside the catalog") + derive.check_alias(info, catalog.assets[spec], where) + elif kind == "invert": + derive.check_invert(info, where) + else: + derive.check_relight(spec, info, where) + + +def inspect( + data: bytes, catalog: Catalog | None = None, names: dict | None = None +) -> dict: + """Header fields and one decoded pack per appearance; raises ValueError.""" + header = rvtfile.decode_file(data) + if catalog is not None and header["fingerprint"] != catalog.fingerprint: + fail( + "header", + f"catalog fingerprint {header['fingerprint'].hex()} is not " + f"{catalog.fingerprint.hex()}", + ) + return { + "id": header["id"], + "name": header["name"], + "version": header["version"], + "fingerprint": header["fingerprint"].hex(), + "appearances": { + appearance: inspect_pack( + body, count, bitmap_count, catalog, appearance, names + ) + for appearance, (body, count, bitmap_count) in header["packs"].items() + }, + } + + +def counts(records: list[dict]) -> dict[str, int]: + """Records per kind, kinds with none left out, in rvt_kind order.""" + result = {} + for record in records: + result[record["kind"]] = result.get(record["kind"], 0) + 1 + return {kind: result[kind] for kind in rvtfile.KINDS if kind in result} + + +def describe(result: dict) -> str: + """A readable summary of an inspect() result.""" + lines = [ + f"{result['id']}: {result['name']} (version {result['version']}, " + f"catalog {result['fingerprint']})" + ] + names = {value: key for key, value in rvtfile.FLAGS.items()} + for appearance, pack in result["appearances"].items(): + flags = [names[bit] for bit in names if pack["rendering"] & bit] or ["none"] + lines.append(f"{appearance}:") + for role, value in pack["colors"].items(): + lines.append(f" {role:13} {value}") + lines.append(f" rendering {', '.join(flags)}") + kinds = ", ".join(f"{n} {kind}" for kind, n in counts(pack["records"]).items()) + lines.append( + f" bitmaps {len(pack['records'])} records" + f"{': ' + kinds if kinds else ''}; {len(pack['tinted'])} tinted; " + f"{pack['bytes']:,} bytes" + ) + listed = ", ".join( + f"{asset['name']} {asset['width']}x{asset['height']} {asset['format']}" + + (f" tinted {asset['tint']}" if asset["tint"] else "") + for asset in pack["extension_bitmaps"] + ) + lines.append( + f" extensions {len(pack['extension_bitmaps'])} extension bitmaps" + f"{': ' + listed if listed else ''}" + ) + return "\n".join(lines) diff --git a/themes/rvt/lz.py b/themes/rvt/lz.py new file mode 100644 index 0000000..0a73d69 --- /dev/null +++ b/themes/rvt/lz.py @@ -0,0 +1,127 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""The lz codec of the RepriseOS core: the bit layout in payload/rvx/compression.c, +which the appearance extension decodes on the iPod. A copy of lz_encode and +lz_decode in rvx-sdk/rvx.py; tests/test_bitmaps.py pins the stream of a +known input so the two copies cannot drift apart unnoticed. + +Groups of a flag byte and up to 8 items, bit 0 first. A clear bit is a literal +byte. A set bit is a match of two bytes, LLLLDDDD DDDDDDDD: it copies L + 3 +bytes from D + 1 bytes back in the output; L = 15 adds the following bytes to +the length while they are 255, and the first that is not. The stream carries +no length: a decoder stops when the output is full and the stream must end +there. +""" + +from rvt import rvtfile + +WINDOW = rvtfile.LZ_WINDOW +MIN_MATCH = rvtfile.LZ_MIN_MATCH +CHAIN = 48 # earlier positions tried per match search + + +def lz_match(data, i, positions): + """Longest match for data[i:] among earlier positions in the window.""" + best_length = best_distance = 0 + limit = len(data) - i + for j in reversed(positions[-CHAIN:]): + distance = i - j + if distance > WINDOW: + break + length = MIN_MATCH + while length < limit and data[j + length] == data[i + length]: + length += 1 + if length > best_length: + best_length, best_distance = length, distance + if length == limit: + break + return best_length, best_distance + + +def lz_encode(data): + """The lz stream for `data`: greedy matching with one step of lookahead.""" + heads = {} + items = [] + + def remember(i): + if i + MIN_MATCH <= len(data): + chain = heads.setdefault(data[i : i + MIN_MATCH], []) + chain.append(i) + if len(chain) > 2 * CHAIN: + del chain[:CHAIN] + + def search(i): + if i + MIN_MATCH > len(data): + return 0, 0 + return lz_match(data, i, heads.get(data[i : i + MIN_MATCH], [])) + + i = 0 + pending = search(0) + while i < len(data): + length, distance = pending + if length: + remember(i) + ahead = search(i + 1) + if ahead[0] > length + 1: + items.append(bytes((data[i],))) + i += 1 + pending = ahead + continue + extra = length - MIN_MATCH + nibble = min(extra, 15) + match = bytes((nibble << 4 | (distance - 1) >> 8, (distance - 1) & 0xFF)) + if nibble == 15: + extra -= 15 + match += b"\xff" * (extra // 255) + bytes((extra % 255,)) + items.append(match) + for k in range(i + 1, i + length): + remember(k) + i += length + else: + items.append(bytes((data[i],))) + remember(i) + i += 1 + pending = search(i) + out = bytearray() + for group in range(0, len(items), 8): + chunk = items[group : group + 8] + out.append(sum(1 << bit for bit, item in enumerate(chunk) if len(item) > 1)) + for item in chunk: + out += item + return bytes(out) + + +def lz_decode(stream, size): + """`size` bytes decoded from an lz stream, which must end exactly there.""" + out = bytearray() + at = 0 + try: + while len(out) < size: + flags = stream[at] + at += 1 + for bit in range(8): + if len(out) == size: + break + if not flags >> bit & 1: + out.append(stream[at]) + at += 1 + continue + high, low = stream[at], stream[at + 1] + at += 2 + length = (high >> 4) + MIN_MATCH + distance = ((high & 15) << 8 | low) + 1 + if high >> 4 == 15: + while True: + more = stream[at] + at += 1 + length += more + if more != 255: + break + if distance > len(out) or len(out) + length > size: + raise ValueError("lz match outside the output") + for _ in range(length): + out.append(out[-distance]) + except IndexError: + raise ValueError("lz stream ends early") from None + if at != len(stream): + raise ValueError("lz stream continues past its output") + return bytes(out) diff --git a/themes/rvt/rvtfile.py b/themes/rvt/rvtfile.py new file mode 100644 index 0000000..09f3239 --- /dev/null +++ b/themes/rvt/rvtfile.py @@ -0,0 +1,399 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""The .rvt file: header and appearance packs. + +Every constant comes from rvt/data/rvt.h, which the appearance extension +vendors byte for byte, so the two sides cannot drift apart. +""" + +import ast +import re +import struct +import zlib +from importlib.resources import files + +HEADER_FILE = files("rvt") / "data" / "rvt.h" + +ID_PATTERN = re.compile(r"[a-z0-9][a-z0-9_-]{0,30}") + + +def _evaluate(node, names): + if isinstance(node, ast.Expression): + return _evaluate(node.body, names) + if isinstance(node, ast.Constant) and isinstance(node.value, int): + return node.value + if isinstance(node, ast.Name): + return names[node.id] + if isinstance(node, ast.BinOp): + left, right = _evaluate(node.left, names), _evaluate(node.right, names) + operators = { + ast.Add: lambda: left + right, + ast.Sub: lambda: left - right, + ast.Mult: lambda: left * right, + ast.LShift: lambda: left << right, + ast.BitOr: lambda: left | right, + } + return operators[type(node.op)]() + raise ValueError(f"unsupported expression in rvt.h: {ast.dump(node)}") + + +def parse(text: str) -> tuple[dict[str, int], dict[str, list[str]], dict[str, int]]: + """Defines (name -> int), enums (name -> ordered member names) and enum + member values (member -> int) of rvt.h. + + Enum members count from zero, or from the integer a member is given; a + define may use them, so the enums are read first.""" + text = re.sub(r"/\*.*?\*/", "", text, flags=re.S) + enums = {} + names = {} + for name, body in re.findall(r"enum\s+(\w+)\s*\{(.*?)\}\s*;", text, re.S): + members = [] + value = 0 + for item in body.split(","): + if not item.strip(): + continue + match = re.fullmatch(r"\s*(RVT_\w+)\s*(?:=\s*(\d+)\s*)?", item) + if not match: + raise ValueError(f"enum {name} has a member this parser cannot read") + member, given = match.groups() + if given is not None: + value = int(given) + members.append(member) + names[member] = value + value += 1 + enums[name] = members + defines = {} + for name, value in re.findall(r"^#define[ \t]+(RVT_\w+)[ \t]+(.+)$", text, re.M): + expression = re.sub(r"\b(0[xX][0-9a-fA-F]+|\d+)[uU]?\b", r"\1", value) + defines[name] = _evaluate(ast.parse(expression, mode="eval"), names) + names[name] = defines[name] + values = {member: names[member] for members in enums.values() for member in members} + return defines, enums, values + + +DEFINES, ENUMS, VALUES = parse(HEADER_FILE.read_text()) + + +def _names(enum, prefix): + """Lower-case member names without the prefix; the last member is the count.""" + members = ENUMS[enum][:-1] + return tuple(m.removeprefix(prefix).lower() for m in members) + + +def _values(enum, prefix): + """Lower-case member name -> value, for enums that do not count from zero.""" + return {m.removeprefix(prefix).lower(): VALUES[m] for m in ENUMS[enum][:-1]} + + +MAGIC = DEFINES["RVT_MAGIC"].to_bytes(4, "little") +VERSION = DEFINES["RVT_VERSION"] +HEADER_BYTES = DEFINES["RVT_HEADER_BYTES"] +FINGERPRINT_BYTES = DEFINES["RVT_FINGERPRINT_BYTES"] +ID_BYTES = DEFINES["RVT_ID_BYTES"] +NAME_BYTES = DEFINES["RVT_NAME_BYTES"] +PACK_HEADER_BYTES = DEFINES["RVT_PACK_HEADER_BYTES"] +APPEARANCES = { + "light": DEFINES["RVT_APPEARANCE_LIGHT"], + "dark": DEFINES["RVT_APPEARANCE_DARK"], +} +FLAGS = { + "flat_selection": DEFINES["RVT_FLAG_FLAT_SELECTION"], + "menu_covers_off": DEFINES["RVT_FLAG_MENU_COVERS_OFF"], + "flat_now_playing": DEFINES["RVT_FLAG_FLAT_NOW_PLAYING"], + "flat_icons": DEFINES["RVT_FLAG_FLAT_ICONS"], +} +TINT_NONE = DEFINES["RVT_TINT_NONE"] +TINT_ROLE = DEFINES["RVT_TINT_ROLE"] +TINT_DARKNESS = DEFINES["RVT_TINT_DARKNESS"] +TINT_SOLID = DEFINES["RVT_TINT_SOLID"] +SOLID_FLOOR = DEFINES["RVT_SOLID_FLOOR"] +CATALOG_MAX = DEFINES["RVT_CATALOG_MAX"] +STYLE_COLORS = DEFINES["RVT_STYLE_COLORS"] +STYLE_FLAGS = DEFINES["RVT_STYLE_FLAGS"] +STYLE_PALETTES = DEFINES["RVT_STYLE_PALETTES"] +STYLE_TINTS = DEFINES["RVT_STYLE_TINTS"] +STYLE_BYTES = DEFINES["RVT_STYLE_BYTES"] +RECORD_BYTES = DEFINES["RVT_RECORD_BYTES"] +RELIGHT_BYTES = DEFINES["RVT_RELIGHT_BYTES"] +SCRATCH_BYTES = DEFINES["RVT_SCRATCH_BYTES"] +RECOLOR_MAX = DEFINES["RVT_RECOLOR_MAX"] +SCRATCH_PIXELS = DEFINES["RVT_SCRATCH_PIXELS"] +ALIASES_MAX = DEFINES["RVT_ALIASES_MAX"] +EXTENSION_BITMAP_BYTES = DEFINES["RVT_EXTENSION_BITMAP_BYTES"] +# Extension bitmap kinds, name -> the kind word. +EXTENSION_KINDS = _values("rvt_extension_kind", "RVT_EXTENSION_") +BMAP_HEADER_BYTES = DEFINES["RVT_BMAP_HEADER_BYTES"] +EXTENSION_BITMAPS_MAX = DEFINES["RVT_EXTENSION_BITMAPS_MAX"] +EXTENSION_BITMAP_MAX_BYTES = DEFINES["RVT_EXTENSION_BITMAP_MAX_BYTES"] +# The largest extension bitmap table: every bitmap at the cap, padded. +EXTENSION_TABLE_MAX_BYTES = EXTENSION_BITMAPS_MAX * ( + EXTENSION_BITMAP_BYTES + EXTENSION_BITMAP_MAX_BYTES +) +# A Settings icon's rows: Mask8, stride 80, 121 rows. +MENU_ROWS_BYTES = 80 * 121 +ROLES = _names("rvt_role", "RVT_ROLE_") +ACCENTS = _names("rvt_accent", "RVT_ACCENT_") +ACCENT_SLOTS = _names("rvt_accent_slot", "RVT_SLOT_") +KINDS = _names("rvt_kind", "RVT_KIND_") +PIXEL_KINDS = ("pixels", "pixels_lz") +LZ_WINDOW = DEFINES["RVT_LZ_WINDOW"] +LZ_MIN_MATCH = DEFINES["RVT_LZ_MIN_MATCH"] +RELIGHT_FIELDS = _names("rvt_relight", "RVT_RELIGHT_") + +# The header fields in RVT_HEADER_* order; the rest up to HEADER_BYTES is zero. +HEADER = struct.Struct(f"<4sHH{FINGERPRINT_BYTES}sIIIIII{ID_BYTES}s{NAME_BYTES}s") +HEADER_OFFSETS = ( + DEFINES["RVT_HEADER_MAGIC"], + DEFINES["RVT_HEADER_VERSION"], + DEFINES["RVT_HEADER_HEADER_BYTES"], + DEFINES["RVT_HEADER_FINGERPRINT"], + DEFINES["RVT_HEADER_APPEARANCES"], + DEFINES["RVT_HEADER_LIGHT_OFFSET"], + DEFINES["RVT_HEADER_LIGHT_BYTES"], + DEFINES["RVT_HEADER_DARK_OFFSET"], + DEFINES["RVT_HEADER_DARK_BYTES"], + DEFINES["RVT_HEADER_CRC"], + DEFINES["RVT_HEADER_ID"], + DEFINES["RVT_HEADER_NAME"], +) +CRC_OFFSET = DEFINES["RVT_HEADER_CRC"] +# A pack header in RVT_PACK_* order: body bytes, record count, body CRC, +# extension bitmap count. +PACK = struct.Struct(" tuple[int, ...]: + """Where each field of a little-endian layout starts; a counted `s` is + one field, a counted number is that many.""" + offsets = [] + at = 0 + for count, code in re.findall(r"(\d*)([a-zA-Z])", layout.format): + fields = [count + code] if code == "s" else [code] * int(count or 1) + for field in fields: + offsets.append(at) + at += struct.calcsize(field) + return tuple(offsets) + + +if ( + MAGIC != b"RVT0" + or HEADER.size > HEADER_BYTES + or _field_offsets(HEADER) != HEADER_OFFSETS + or PACK.size != PACK_HEADER_BYTES + or _field_offsets(PACK) != PACK_OFFSETS + or RECORD.size != RECORD_BYTES + or EXTENSION_BITMAP.size != EXTENSION_BITMAP_BYTES + or EXTENSION_KINDS != {"bitmap": 1, "bitmap_lz": 2} + or BMAP_HEADER_BYTES != 28 + or EXTENSION_BITMAP_MAX_BYTES < BMAP_HEADER_BYTES + MENU_ROWS_BYTES + or STYLE_COLORS != 0 + or STYLE_FLAGS != len(ROLES) * 4 + or STYLE_PALETTES != STYLE_FLAGS + 4 + or STYLE_TINTS != STYLE_PALETTES + len(ACCENTS) * len(ACCENT_SLOTS) * 4 + or STYLE_BYTES != STYLE_TINTS + CATALOG_MAX + or RELIGHT.size != RELIGHT_BYTES + or KINDS != ("pixels", "recolor", "alias", "invert", "relight", "pixels_lz") + or LZ_WINDOW != 4096 + or LZ_MIN_MATCH != 3 + or TINT_ROLE + len(ROLES) > 16 + or TINT_DARKNESS < 16 + or TINT_SOLID < 16 + or TINT_DARKNESS & TINT_SOLID + or not 0 < SOLID_FLOOR <= 255 + or RECOLOR_MAX * PAIR.size > SCRATCH_BYTES + or SCRATCH_PIXELS + 256 > SCRATCH_BYTES +): + raise ValueError("rvt/data/rvt.h does not match the layout this module encodes") + + +def align(size: int) -> int: + return size + -size % 4 + + +def check_id(value: str, where: str = "id") -> str: + if not isinstance(value, str) or not ID_PATTERN.fullmatch(value): + raise ValueError(f"{where}: expected [a-z0-9][a-z0-9_-]{{0,30}}") + return value + + +def check_text(value: str, where: str, limit: int) -> str: + """A non-empty string without control characters of at most `limit` + UTF-8 bytes.""" + if not isinstance(value, str) or not value: + raise ValueError(f"{where}: expected a non-empty string") + if any(ord(c) < 32 or ord(c) == 127 for c in value): + raise ValueError(f"{where}: control characters are not allowed") + if len(value.encode()) > limit: + raise ValueError(f"{where}: exceeds {limit} UTF-8 bytes") + return value + + +def check_name(value: str, where: str = "name") -> str: + return check_text(value, where, NAME_BYTES - 1) + + +def fnv1a(data: bytes) -> int: + """FNV-1a, the hash the core keys extension ids and asset names with.""" + value = 2166136261 + for byte in data: + value = (value ^ byte) * 16777619 & 0xFFFFFFFF + return value + + +def encode_pack(body: bytes, count: int, bitmaps: int = 0) -> bytes: + """Pack header and body; the body is the style prefix, the padded records + and the `bitmaps` extension bitmaps after them.""" + if len(body) % 4: + raise ValueError("pack body is not a multiple of 4 bytes") + return PACK.pack(len(body), count, zlib.crc32(body), bitmaps) + body + + +def encode_file( + fingerprint: bytes, + identifier: str, + name: str, + packs: dict[str, tuple[bytes, int, int]], +) -> bytes: + """A complete .rvt: packs maps an appearance name to (body, record count, + extension bitmap count).""" + if len(fingerprint) != FINGERPRINT_BYTES: + raise ValueError(f"fingerprint must be {FINGERPRINT_BYTES} bytes") + check_id(identifier) + check_name(name) + if not packs: + raise ValueError("a theme needs a light or dark appearance") + mask = 0 + placement = {} + data = bytearray() + offset = HEADER_BYTES + for appearance, bit in APPEARANCES.items(): + if appearance not in packs: + continue + pack = encode_pack(*packs[appearance]) + mask |= bit + placement[appearance] = (offset, len(pack)) + data += pack + offset += len(pack) + header = bytearray(HEADER_BYTES) + HEADER.pack_into( + header, + 0, + MAGIC, + VERSION, + HEADER_BYTES, + fingerprint, + mask, + *placement.get("light", (0, 0)), + *placement.get("dark", (0, 0)), + 0, + identifier.encode("ascii"), + name.encode(), + ) + struct.pack_into(" dict: + if len(data) < HEADER_BYTES: + raise ValueError(f"header: expected {HEADER_BYTES} bytes, got {len(data)}") + ( + magic, + version, + header_bytes, + fingerprint, + mask, + light_offset, + light_bytes, + dark_offset, + dark_bytes, + crc, + raw_id, + raw_name, + ) = HEADER.unpack_from(data) + if magic != MAGIC: + raise ValueError(f"header: bad magic {magic!r}") + if version != VERSION: + raise ValueError(f"header: version {version} is not {VERSION}") + # A larger header is a later layout's; the packs start where it says. + if header_bytes < HEADER_BYTES or header_bytes % 4 or header_bytes > len(data): + raise ValueError(f"header: expected at least {HEADER_BYTES} header bytes") + sealed = bytearray(data[:HEADER_BYTES]) + struct.pack_into(" tuple[bytes, int, int]: + """(body, record count, extension bitmap count) of the pack at offset, + after checking its CRC.""" + body_bytes, count, crc, bitmaps = PACK.unpack_from(data, offset) + if body_bytes != size - PACK_HEADER_BYTES or body_bytes < STYLE_BYTES: + raise ValueError(f"pack at {offset}: body of {body_bytes} bytes does not fit") + body = bytes(data[offset + PACK_HEADER_BYTES : offset + size]) + if zlib.crc32(body) != crc: + raise ValueError(f"pack at {offset}: CRC-32 mismatch") + if bitmaps > EXTENSION_BITMAPS_MAX: + raise ValueError(f"pack at {offset}: {bitmaps} extension bitmaps") + return body, count, bitmaps + + +def decode_file(data: bytes) -> dict: + """Header fields plus packs as appearance -> (body, record count, extension + bitmap count).""" + header = decode_header(data) + header["packs"] = { + appearance: decode_pack(data, offset, size) + for appearance, (offset, size) in header["packs"].items() + } + return header diff --git a/themes/rvt/style.py b/themes/rvt/style.py new file mode 100644 index 0000000..e2797ce --- /dev/null +++ b/themes/rvt/style.py @@ -0,0 +1,189 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""The style prefix of an appearance pack: colour roles, rendering flags, one +palette per named accent and one tint byte per catalog bitmap.""" + +import struct + +from rvt import rvtfile + +ROLES = rvtfile.ROLES +ACCENTS = rvtfile.ACCENTS +# The accent palette slots are the TOML keys of the roles they replace. +ACCENT_SLOTS = rvtfile.ACCENT_SLOTS +if any(slot not in ROLES for slot in ACCENT_SLOTS): + raise ValueError("accent slots do not name roles of rvt.h") +STYLE_BYTES = rvtfile.STYLE_BYTES +FLAGS_OFFSET = rvtfile.STYLE_FLAGS +PALETTE_OFFSET = rvtfile.STYLE_PALETTES +TINT_OFFSET = rvtfile.STYLE_TINTS + +ALL_FLAGS = sum(rvtfile.FLAGS.values()) +# The lowest contrast of a text and background pair that passes. +CONTRAST_MINIMUM = 4.5 + +# Classic light and dark. The dark palette comes from RepriseOS payload/dark_mode.c +# (01c89f6) by lgreitis and Alex Ball (alexballvideos-netizen). +COLOR_DEFAULTS = { + key: dict(zip(ROLES, (f"#{value}" for value in values.split()))) + for key, values in { + "light": "ffffff 202020 236cc5 3185d0 ffffff 236cc5 7e8183 3185d0", + "dark": "181818 e8e8e8 00a1ff 00a1ff ffffff 00a1ff 383838 00a1ff", + }.items() +} +# Built-in accents: light fill, light text, dark fill, dark text. Blue is Classic. +ACCENT_BUILTIN = dict( + zip( + ACCENTS, + ( + ("236cc5", "3185d0", "00a1ff", "00a1ff"), + ("8944ab", "8944ab", "964ebc", "da8fff"), + ("c41e56", "c41e56", "ce2660", "ff6491"), + ("d02028", "d02028", "d42830", "ff6961"), + ("b84800", "b84800", "be4c00", "ff9f0a"), + ("1e803a", "1e803a", "20863e", "30d158"), + ("007378", "007378", "00787d", "40d2d7"), + ("826500", "826500", "846700", "ffd60a"), + ("5c6066", "5c6066", "64686e", "bec2c8"), + ), + ) +) + + +def rgb(color): + return bytes.fromhex(color.removeprefix("#")) + + +def accent_builtin(name: str, appearance: str) -> tuple[str, str]: + """Built-in fill and text of an accent for one appearance.""" + builtin = ACCENT_BUILTIN[name] + fill, text = builtin[2:] if appearance == "dark" else builtin[:2] + return "#" + fill, "#" + text + + +def accent_palette(name: str, appearance: str, colors: dict[str, str]) -> dict: + """The palette an accent starts from: the built-in fill for accent_fill and + selection, the built-in text for accent_text and icon_tint, and the + appearance's own on_accent.""" + fill, text = accent_builtin(name, appearance) + return dict(zip(ACCENT_SLOTS, (fill, text, fill, colors["on_accent"], text))) + + +def contrast(first: str, second: str) -> float: + """WCAG contrast ratio of two #rrggbb colours.""" + + def luminance(color): + linear = [ + v / 12.92 if v <= 0.04045 else ((v + 0.055) / 1.055) ** 2.4 + for v in (c / 255 for c in rgb(color)) + ] + return sum(v * w for v, w in zip(linear, (0.2126, 0.7152, 0.0722))) + + low, high = sorted((luminance(first), luminance(second))) + return (high + 0.05) / (low + 0.05) + + +CONTRAST_PAIRS = ( + ("text", "background"), + ("accent_text", "background"), + ("on_accent", "selection"), + ("on_accent", "accent_fill"), +) + + +# The accent entry of the theme's own colours, as Settings names it. +THEME_DEFAULT = "Theme Default" + + +def contrast_report(colors: dict, palettes: dict) -> list[dict]: + """Contrast of each text/background pair for Theme Default and every accent.""" + report = [] + for name, palette in [(THEME_DEFAULT, {}), *palettes.items()]: + resolved = colors | palette + for foreground, background in CONTRAST_PAIRS: + ratio = contrast(resolved[foreground], resolved[background]) + report.append( + { + "accent": name, + "foreground": foreground, + "background": background, + "ratio": round(ratio, 3), + "passes": ratio >= CONTRAST_MINIMUM, + } + ) + return report + + +COVERAGES = ("alpha", "darkness", "solid") +COVERAGE_BITS = { + "alpha": 0, + "darkness": rvtfile.TINT_DARKNESS, + "solid": rvtfile.TINT_SOLID, +} + + +def tint_byte(role: str, coverage: str = "alpha") -> int: + return rvtfile.TINT_ROLE + ROLES.index(role) | COVERAGE_BITS[coverage] + + +def encode(colors: dict, flags: int, palettes: dict, tinted: dict) -> bytes: + """The style prefix. tinted maps a catalog index to a tint role or a + (role, coverage) pair.""" + if flags & ~ALL_FLAGS: + raise ValueError(f"unknown rendering flags {flags:#x}") + tints = bytearray(rvtfile.CATALOG_MAX) + for index, tint in tinted.items(): + if not 0 <= index < rvtfile.CATALOG_MAX: + raise ValueError( + f"tinted catalog index {index} exceeds {rvtfile.CATALOG_MAX}" + ) + role, coverage = tint if isinstance(tint, tuple) else (tint, "alpha") + tints[index] = tint_byte(role, coverage) + return ( + b"".join(rgb(colors[role]) + b"\xff" for role in ROLES) + + struct.pack(" dict: + """Colours, flags, accent palettes and tinted bitmaps of a prefix.""" + if len(data) != STYLE_BYTES: + raise ValueError(f"style prefix must be {STYLE_BYTES} bytes") + if any(data[i] != 255 for i in range(3, TINT_OFFSET, 4) if i != FLAGS_OFFSET + 3): + raise ValueError("style colours must be opaque") + flags = struct.unpack_from(" None: + if not isinstance(table, dict): + fail(where, "expected a table") + for key in sorted(table): + at = f"{where}.{key}" if where else key + if key in UNSUPPORTED: + fail(at, f"unsupported capability: {UNSUPPORTED[key]} are not themeable") + if key not in allowed: + fail(at, "unknown key") + + +def color(value, where: str) -> str: + if not isinstance(value, str) or not COLOR.fullmatch(value): + fail(where, 'expected "#rrggbb"') + return value.lower() + + +def load(folder: Path) -> dict: + """The validated document; its appearance tables are resolved by the + functions below.""" + path = Path(folder) / "theme.toml" + if not path.is_file(): + fail(str(path), "not found") + if path.stat().st_size > TOML_LIMIT: + fail(path.name, f"exceeds {TOML_LIMIT:,} bytes") + try: + theme = tomllib.loads(path.read_bytes().decode("utf-8")) + except UnicodeDecodeError: + fail(path.name, "expected UTF-8") + except tomllib.TOMLDecodeError as error: + fail(path.name, f"invalid TOML: {error}") + check_keys(theme, THEME_KEYS, "") + for key in ("schema", "id", "name"): + if key not in theme: + fail(key, "required") + if type(theme["schema"]) is not int or theme["schema"] != SCHEMA: + fail("schema", f"unsupported schema {theme['schema']!r}; expected {SCHEMA}") + rvtfile.check_id(theme["id"]) + rvtfile.check_name(theme["name"]) + for key in ("author", "version"): + if key in theme: + rvtfile.check_text(theme[key], key, TEXT_LIMIT) + if not any(key in theme for key in rvtfile.APPEARANCES): + fail("", "declare [light], [dark] or both") + for key in rvtfile.APPEARANCES: + if key in theme: + check_keys(theme[key], APPEARANCE_KEYS, key) + return theme + + +# Colours, accents and rendering + + +def resolve_style(appearance: str, table: dict) -> tuple[tuple, dict, list[str]]: + """(colors, flags, palettes) of an appearance, its report, and warnings + about text and background pairs the theme itself colours that fall below + style.CONTRAST_MINIMUM; a pair no accent changes is warned about once. + icon_tint left out follows accent_text.""" + where = appearance + colors = table.get("colors", {}) + check_keys(colors, set(style.ROLES), f"{where}.colors") + resolved = dict(style.COLOR_DEFAULTS[appearance]) + for role, value in colors.items(): + resolved[role] = color(value, f"{where}.colors.{role}") + if "icon_tint" not in colors: + resolved["icon_tint"] = resolved["accent_text"] + + overrides = table.get("accents", {}) + check_keys(overrides, set(style.ACCENTS), f"{where}.accents") + palettes = { + name: accent_palette(name, appearance, resolved, overrides.get(name), where) + for name in style.ACCENTS + } + + flags = 0 + covers = table.get(MENU_COVERS_DEFAULT, True) + if not isinstance(covers, bool): + fail(f"{where}.{MENU_COVERS_DEFAULT}", "expected true or false") + if not covers: + flags |= rvtfile.FLAGS["menu_covers_off"] + rendering = table.get("rendering", {}) + if not isinstance(rendering, dict): + fail(f"{where}.rendering", "expected a table") + for key in sorted(rendering): + at = f"{where}.rendering.{key}" + if key not in RENDERING: + fail(at, "unknown key") + if not isinstance(rendering[key], bool): + fail(at, "expected true or false") + if rendering[key]: + flags |= rvtfile.FLAGS[RENDERING[key]] + + report = { + "contrast": style.contrast_report(resolved, palettes), + "accents_builtin": [name for name in style.ACCENTS if name not in overrides], + } + warnings = [] + for pair in report["contrast"]: + sides = {pair["foreground"], pair["background"]} + if pair["accent"] != style.THEME_DEFAULT and not sides & set( + style.ACCENT_SLOTS + ): + continue + owned = pair["accent"] in overrides or any( + pair[side] in colors for side in ("foreground", "background") + ) + if owned and not pair["passes"]: + warnings.append( + f"{where}: {pair['foreground']} on {pair['background']} is " + f"{pair['ratio']}:1 with accent {pair['accent']}; " + f"{style.CONTRAST_MINIMUM}:1 is the minimum" + ) + return (resolved, flags, palettes), report, warnings + + +def accent_palette(name, appearance, colors, override, where) -> dict: + """One accent's palette: the built-in fill and text with the appearance's + on_accent, then the override: one colour for fill, text, selection and + icon tint, a table with `accent` and optionally `on_accent`, or a table of + the five palette slots.""" + palette = style.accent_palette(name, appearance, colors) + at = f"{where}.accents.{name}" + if override is None: + return palette + if isinstance(override, str): + override = {"accent": override} + if not isinstance(override, dict): + fail(at, 'expected "#rrggbb" or a table') + if "accent" in override: + check_keys(override, {"accent", "on_accent"}, at) + one = color(override["accent"], f"{at}.accent") + palette.update(accent_fill=one, accent_text=one, selection=one, icon_tint=one) + if "on_accent" in override: + palette["on_accent"] = color(override["on_accent"], f"{at}.on_accent") + return palette + check_keys(override, set(style.ACCENT_SLOTS), at) + for slot, value in override.items(): + palette[slot] = color(value, f"{at}.{slot}") + return palette + + +# Tints and rules + + +def is_glob(pattern: str) -> bool: + return bool(GLOB_CHARS & set(pattern)) + + +def matching(pattern: str, catalog: Catalog, where: str) -> list[int]: + """Catalog indices a name, hex id or glob stands for; a name that is not + in the catalog is an error, a glob may match nothing.""" + if not isinstance(pattern, str): + fail(where, "expected a catalog name, hex id or glob") + if not is_glob(pattern): + return [catalog.resolve(pattern, where)] + return [ + index + for index, asset in enumerate(catalog.assets) + if fnmatch.fnmatchcase(asset["name"], pattern) + ] + + +def extension_key(pattern: str, where: str) -> tuple[str, str] | None: + """(id, asset) when a tint entry names an extension bitmap as `id/asset` + (the core's as `reprise/asset`); None for a catalog name, hex id or glob, + which never contain a slash.""" + if not isinstance(pattern, str) or "/" not in pattern: + return None + identifier, _, asset = pattern.partition("/") + if not assets.ID_PATTERN.fullmatch( + identifier + ) or not assets.ASSET_PATTERN.fullmatch(asset): + fail(where, f"{pattern!r} is not an extension bitmap /") + return identifier, asset + + +def resolve_tints( + table: dict, appearance: str, catalog: Catalog +) -> tuple[dict[int, tuple[str, str]], dict[tuple[str, str], str], list[str]]: + """Catalog index -> (role, coverage) and extension (id, asset) -> role from + [.tint], and warnings about globs that match nothing: role = + [names or globs] per role, a `darkness_coverage` list naming tinted bitmaps + whose coverage is their darkness and a `solid_coverage` list naming those + whose coverage is full from the floor up. An extension bitmap is named + `id/asset` and takes its coverage from its PNG's alpha only.""" + where = f"{appearance}.tint" + tints = table.get("tint", {}) + if not isinstance(tints, dict): + fail(where, "expected a table") + tinted: dict[int, tuple[str, str]] = {} + extensions: dict[tuple[str, str], str] = {} + warnings: list[str] = [] + for role, patterns in tints.items(): + at = f"{where}.{role}" + if role not in COVERAGE_LISTS and role not in style.ROLES: + fail(at, f"expected one of {', '.join((*style.ROLES, *COVERAGE_LISTS))}") + if not isinstance(patterns, list): + fail(at, "expected a list of catalog names, hex ids or globs") + for pattern in patterns: + key = extension_key(pattern, at) + if key is not None: + if role in COVERAGE_LISTS: + fail(at, f"{pattern} takes its coverage from its PNG's alpha") + if key in extensions: + fail(at, f"{pattern} is already tinted {extensions[key]}") + extensions[key] = role + continue + found = matching(pattern, catalog, at) + if not found: + warnings.append(f"{at}: {pattern!r} matches no catalog bitmap") + if role in COVERAGE_LISTS: + continue + for index in found: + info = catalog.assets[index] + if index in tinted: + fail(at, f"{info['name']} is already tinted {tinted[index][0]}") + if bitmaps.tint_kind(info["format"]) is None: + fail( + at, + f"{info['name']} cannot be tinted: it has no palette or coverage", + ) + tinted[index] = (role, "alpha") + for key, coverage in COVERAGE_LISTS.items(): + at = f"{where}.{key}" + for pattern in tints.get(key, []): + for index in matching(pattern, catalog, at): + name = catalog.assets[index]["name"] + if index not in tinted: + fail(at, f"{name} has no tint role") + if tinted[index][1] == coverage: + fail(at, f"{name} is listed twice") + if tinted[index][1] != "alpha": + fail( + at, f"{name} already takes its coverage from {tinted[index][1]}" + ) + tinted[index] = (tinted[index][0], coverage) + return tinted, extensions, warnings + + +def resolve_rules( + table: dict, appearance: str, catalog: Catalog, sources: dict +) -> tuple[dict[int, derive.Rule], dict[int, str], list[str]]: + """Catalog index -> Rule from [.derive], index -> the rule's + pattern, and one note per rule saying how many bitmaps it matched. A rule + matches by name, hex id or glob; it may not match nothing, a bitmap in + `sources` (one with a PNG or a per-file TOML) or a bitmap of another + rule.""" + where = f"{appearance}.derive" + rules = table.get("derive", {}) + if not isinstance(rules, dict): + fail(where, "expected a table of rules") + resolved: dict[int, derive.Rule] = {} + owner: dict[int, str] = {} + notes = [] + for pattern, spec in rules.items(): + at = f"{where}.{pattern!r}" + found = matching(pattern, catalog, at) + if not found: + fail(at, "matches no catalog bitmap") + for index in found: + name = catalog.assets[index]["name"] + if index in sources: + fail(at, f"matches {name}, which has {sources[index][1].name}") + if index in owner: + fail(at, f"matches {name}, which {owner[index]!r} matches too") + owner[index] = pattern + for index in found: + resolved[index] = derive.rule(spec, index, catalog, at) + notes.append( + f"{at} matches {len(found)} bitmap{'s' if len(found) != 1 else ''}" + ) + return resolved, owner, notes + + +# rvt new + + +def template(identifier: str, name: str) -> str: + """A theme.toml with every role and option present as a comment.""" + out = [ + "schema = 1", + f'id = "{identifier}"', + f'name = "{name}"', + '# author = ""', + '# version = "1.0"', + "", + "# Art goes beside this file: /apple/.png or", + "# .toml for Apple's bitmaps, /extensions//", + "# .png for the bitmaps of extensions (rvt catalog list", + "# --extensions), /reprise/.png for the core's own.", + ] + for appearance in rvtfile.APPEARANCES: + defaults = style.COLOR_DEFAULTS[appearance] + out += [ + "", + f"# {appearance.capitalize()} appearance; drop the table to leave it out.", + f"[{appearance}]", + f"# {MENU_COVERS_DEFAULT} = true # Menu Covers until the listener chooses", + "", + "# Roles left out keep the Classic colours shown.", + f"[{appearance}.colors]", + ] + out += [ + f'# {role} = "{value}"' + + (" # left out, it follows accent_text" if role == "icon_tint" else "") + for role, value in defaults.items() + ] + out += [ + "", + "# Accents the listener can pick. One colour fills accent_fill,", + "# accent_text, selection and icon_tint; on_accent comes from the", + "# colours above. Accents left out use the built-in fill and text.", + f"[{appearance}.accents]", + ] + for accent in style.ACCENTS: + fill, _ = style.accent_builtin(accent, appearance) + out.append(f'# {accent} = "{fill}"') + out += [ + '# yellow = { accent = "#ffcc00", on_accent = "#000000" }', + "", + f"[{appearance}.rendering]", + "# flat_selection = false # true: the selection bar is one flat colour", + "# flat_now_playing = false # true: face-on cover art, no reflection", + "# flat_icons = false # true: extension icons this theme does not", + "# # replace lose their reflection", + "", + "# Bitmaps the iPod draws in one live colour, by role; globs allowed.", + f"[{appearance}.tint]", + ] + out += [f"# {role} = []" for role in style.ROLES] + out += [ + f"# {DARKNESS} = [] # coverage from darkness, stock art only", + f"# {SOLID} = [] # coverage full from the floor up, stock art only", + "", + "# Rules that derive bitmaps from the stock art or, with", + "# from_other = true, from this theme's own PNG in the other appearance.", + f"[{appearance}.derive]", + '# "Settings_Brightness_Image" = { kind = "invert" }', + '# "Clock_*_Image_*" = { kind = "alias", from_other = true }', + ] + return "\n".join(out) + "\n" diff --git a/themes/tests/fixtures.py b/themes/tests/fixtures.py new file mode 100644 index 0000000..8665eda --- /dev/null +++ b/themes/tests/fixtures.py @@ -0,0 +1,201 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""Synthetic PNGs, native bitmaps and a six-asset catalog for the tests.""" + +import struct +import sys +import zlib +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from rvt import catalog as catalog_module # noqa: E402 +from rvt.bitmaps import describe # noqa: E402 + + +def png(width, height, color_type, rows): + """A PNG from raw scanlines (each prefixed with its filter byte).""" + + def chunk(kind, body): + return ( + struct.pack(">I", len(body)) + + kind + + body + + struct.pack(">I", zlib.crc32(kind + body)) + ) + + header = struct.pack(">IIBBBBB", width, height, 8, color_type, 0, 0, 0) + return ( + b"\x89PNG\r\n\x1a\n" + + chunk(b"IHDR", header) + + chunk(b"IDAT", zlib.compress(rows)) + + chunk(b"IEND", b"") + ) + + +def rgba_png(width, height, rgba): + rows = b"".join( + b"\0" + rgba[y * width * 4 : (y + 1) * width * 4] for y in range(height) + ) + return png(width, height, 6, rows) + + +def indexed(): + pixels = bytes([0, 1, 0, 1]) + body = struct.pack("> 8 & 255, 7, 255) for i in range(count)] + + +def record(identifier, asset, width, height, menu=False, fmt=None, colors=0): + if menu: + fmt, colors, stride, depth = assets.MASK8, 0, assets.MENU_STRIDE, 8 + else: + fmt = assets.INDEXED8 if fmt is None else fmt + depth = 8 if fmt == assets.INDEXED8 else 32 + stride = (width * depth // 8 + 3) & ~3 + return { + "id": identifier, + "asset": asset, + "menu": menu, + "format": fmt, + "width": width, + "height": height, + "stride": stride, + "depth": depth, + "palette_colors": colors, + "bytes": assets.HEADER.size + + (4 + 4 * colors if colors else 0) + + stride * height, + "preload": "optional" if menu else "never", + } + + +def table(*entries): + """An extension bitmap table from (owner, asset, kind, payload[, decoded + [, stored[, tint]]]); decoded defaults to a Settings icon, stored to the + payload, tint to none.""" + data = b"" + for owner, name, kind, payload, *rest in entries: + decoded = rest[0] if rest else MENU_BYTES + stored = rest[1] if len(rest) > 1 else len(payload) + tint = rest[2] if len(rest) > 2 else 0 + data += rvtfile.EXTENSION_BITMAP.pack(owner, name, kind, stored, decoded, tint) + data += payload + bytes(-len(data + payload) % 4) + return data + + +class EncodingTests(unittest.TestCase): + def test_encoder_is_the_sdk_copy(self): + sdk = ( + Path(os.environ.get("SDK", ROOT.parents[1] / "osos-lab" / "rvx-sdk")) + / "bitmap.py" + ) + if not sdk.is_file(): + self.skipTest("set SDK to the RVX SDK checkout") + self.assertEqual( + (ROOT / "rvt" / "data" / "bitmap.py").read_bytes(), sdk.read_bytes() + ) + + def test_committed_catalog_matches_the_build(self): + built = ROOT.parent / "build" / "assets.json" + if not built.is_file(): + self.skipTest("run make first; build/assets.json is missing") + self.assertEqual(extensions_catalog.convert(built), assets.CATALOG.read_text()) + + def test_hashes_match_the_core(self): + self.assertEqual(assets.owner_hash("reprise"), 0xB3F4A34D) + self.assertEqual(rvtfile.fnv1a(COLLIDING[0].encode()), 0x2C91828D) + self.assertEqual( + rvtfile.fnv1a(COLLIDING[0].encode()), rvtfile.fnv1a(COLLIDING[1].encode()) + ) + + def test_mask_follows_encode_mask(self): + translucent = b"".join(bytes((9, 9, 9, a)) for a in (0, 128, 255)) * ( + W * H // 3 + ) + bmap = assets.bitmap.encode_mask(W, H, translucent) + self.assertEqual(len(bmap), MENU_BYTES) + self.assertEqual(bmap[:28], assets.MENU_HEADER) + self.assertEqual( + assets.HEADER.unpack(bmap[:28]), (8, 0, 80, 8, 0, 0, 121, 78, 9680) + ) + self.assertTrue(assets.is_menu(bmap)) + self.assertEqual(bmap[28:31], bytes((0, 128, 255))) + self.assertEqual(bmap[28 + 78 : 28 + 80], bytes(2)) + gray = b"".join(bytes((v, v, v, 255)) for v in (0, 7, 200)) * (W * H // 3) + self.assertEqual( + assets.bitmap.encode_mask(W, H, gray)[28:31], bytes((0, 7, 200)) + ) + # Opaque art with an alpha hole uses alpha even where it is grayscale. + mixed = bytearray(gray) + mixed[3] = 0 + self.assertEqual( + assets.bitmap.encode_mask(W, H, bytes(mixed))[28:31], bytes((0, 255, 255)) + ) + with self.assertRaisesRegex(ValueError, "a pane icon is coverage"): + assets.bitmap.encode_mask(W, H, bytes((200, 10, 10, 255)) * (W * H)) + with self.assertRaisesRegex(ValueError, "a pane icon is 78 x 121, not 4 x 1"): + assets.bitmap.encode_mask(4, 1, bytes(16)) + + def test_picture_follows_encode_bmap(self): + # Five pixels of three colours: Indexed8, a palette of three, stride 8. + colors = [(1, 2, 3, 255), (4, 5, 6, 128), (1, 2, 3, 255), (7, 8, 9, 0)] + rgba = b"".join(bytes(c) for c in colors) + bytes((4, 5, 6, 128)) + bmap = assets.bitmap.encode_bmap(5, 1, rgba) + fmt, _, stride, depth, top, left, bottom, right, payload = assets.HEADER.unpack( + bmap[:28] + ) + self.assertEqual( + (fmt, stride, depth, top, left, bottom, right), (0x64, 8, 8, 0, 0, 1, 5) + ) + self.assertEqual(payload, 4 + 12 + 8) + self.assertEqual(len(bmap), 28 + payload) + self.assertEqual(struct.unpack_from("/", + tint % '"Third/logo"', + extensions, + ) + self.rejects( + r"light.tint.icon_tint: third/logo has no light/extensions/third/logo.png", + tint % '"third/logo"', + extensions, + ) + self.rejects( + r"light.tint.text: third/logo is already tinted icon_tint", + THEME + '[light.tint]\nicon_tint = ["third/logo"]\ntext = ["third/logo"]\n', + extensions, + **{"light/extensions/third/logo.png": colored}, + ) + self.rejects( + r"light.tint.solid_coverage: third/logo takes its coverage from its PNG", + THEME + + '[light.tint]\nicon_tint = ["third/logo"]\nsolid_coverage = ["third/logo"]\n', + extensions, + **{"light/extensions/third/logo.png": colored}, + ) + self.rejects( + r"light/extensions/third/logo.png: tinted art must be grayscale or carry alpha coverage", + tint % '"third/logo"', + extensions, + **{"light/extensions/third/logo.png": colored}, + ) + self.rejects( + r"light/extensions/appearance/settings-moon.png: a Settings icon is drawn " + r"in the icon tint already; no tint role", + tint % '"appearance/settings-moon"', + extensions, + **{MOON_PNG: icon_png()}, + ) + + def test_unknown_asset_compiles_only_as_a_settings_icon(self): + build = self.theme( + FLAT, + **{ + "light/extensions/third-party/settings-x.png": icon_png(), + MOON_PNG: icon_png(), + }, + ) + self.assertEqual( + build.warnings, + [ + "light/extensions/third-party/settings-x.png: not in the extension " + "asset catalog, compiled as a Settings icon; docs/extension-bitmaps.md " + "lists the first-party bitmaps, --extension adds others" + ], + ) + self.assertEqual( + len(build.inspection["appearances"]["light"]["extension_bitmaps"]), 2 + ) + self.rejects( + r"light/extensions/third-party/logo.png: 4x1 is not a menu bitmap and the " + r"asset is not in the extension asset catalog; pass --extension", + **{"light/extensions/third-party/logo.png": rgba_png(4, 1, bytes(16))}, + ) + + def test_art_outside_its_folder_is_rejected(self): + self.rejects( + r"light/extensions/reprise: reprise is the core's id; its bitmaps go in " + r"light/reprise/", + **{"light/extensions/reprise/settings-info.png": icon_png()}, + ) + self.rejects( + r"light/stray.png: catalog art goes in light/apple/, extension bitmaps " + r"in light/extensions//, the core's in light/reprise/", + **{"light/stray.png": icon_png()}, + ) + self.rejects( + r"dark: has art but theme.toml declares no \[dark\]", + **{"dark/reprise/settings-info.png": icon_png()}, + ) + self.rejects( + "light/reprise/Extensions.png: expected .png", + **{"light/reprise/Extensions.png": icon_png()}, + ) + + def test_reflection_warning_follows_flat_icons_for_menu_bitmaps(self): + files = {MOON_PNG: icon_png()} + build = self.theme(**files) + self.assertEqual( + build.warnings, + [ + f"{MOON_PNG}: no reflection below the art; draw one or set " + "flat_icons = true in [light.rendering]" + ], + ) + build = self.theme(THEME + "[light.rendering]\nflat_icons = true\n", **files) + self.assertEqual(build.warnings, []) + reflected = icon_png(rows=list(range(12, 63)) + [100]) + build = self.theme(**{MOON_PNG: reflected}) + self.assertEqual(build.warnings, []) + extensions = {("third", "logo"): record("third", "logo", 4, 1)} + build = self.theme( + THEME + "[light]\n", + extensions, + **{"light/extensions/third/logo.png": rgba_png(4, 1, bytes(16))}, + ) + self.assertEqual(build.warnings, []) + + def test_bad_names_and_colliding_hashes_are_rejected(self): + cases = { + "light/extensions/Appearance: expected an extension id": { + "light/extensions/Appearance/settings-moon.png": icon_png() + }, + "light/extensions/1st: expected an extension id": { + "light/extensions/1st/x.png": icon_png() + }, + "light/extensions/" + "a" * 33 + ": expected an extension id": { + "light/extensions/" + "a" * 33 + "/x.png": icon_png() + }, + "light/extensions/stray.png: expected a folder named after an extension id": { + "light/extensions/stray.png": icon_png() + }, + "light/extensions/appearance/Settings-Moon.png: expected .png": { + "light/extensions/appearance/Settings-Moon.png": icon_png() + }, + "light/extensions/appearance/settings-moon.toml: expected .png": { + "light/extensions/appearance/settings-moon.toml": b"x" + }, + "light/extensions/appearance/" + "a" * 32 + ".png: expected .png": { + "light/extensions/appearance/" + "a" * 32 + ".png": icon_png() + }, + f"{MOON_PNG}: a pane icon is 78 x 121, not 4 x 1": { + MOON_PNG: rgba_png(4, 1, bytes(16)) + }, + f"{MOON_PNG}: a pane icon is coverage": { + MOON_PNG: rgba_png(W, H, bytes((200, 10, 10, 255)) * (W * H)) + }, + f"{MOON_PNG}: truncated PNG": {MOON_PNG: icon_png()[:-20]}, + "extensions/appearance/e6apaa.png: its hashes collide with " + "extensions/appearance/7yzlaa.png": { + f"light/extensions/appearance/{COLLIDING[0]}.png": icon_png(), + f"dark/extensions/appearance/{COLLIDING[1]}.png": icon_png(), + }, + } + for pattern, files in cases.items(): + with self.subTest(pattern): + self.rejects(pattern, THEME + "[light]\n[dark]\n", **files) + # The same name in both appearances is two bitmaps, not a collision. + build = self.theme( + THEME + "[light]\n[dark]\n", + **{MOON_PNG: icon_png(), MOON_PNG.replace("light", "dark"): icon_png()}, + ) + self.assertEqual( + len(build.inspection["appearances"]["dark"]["extension_bitmaps"]), 1 + ) + self.theme(THEME + "[light]\n[dark]\n") + (self.root / "light" / "extensions" / "appearance").mkdir(parents=True) + outside = self.root.parent / "settings-moon.png" + outside.write_bytes(icon_png()) + (self.root / MOON_PNG).symlink_to(outside) + with self.assertRaisesRegex(ValueError, f"{MOON_PNG}: must be a file inside"): + compile_theme(self.catalog, self.root) + + def test_more_than_the_cap_of_extension_bitmaps_is_rejected(self): + files = { + f"light/extensions/appearance/icon-{i:02}.png": icon_png() + for i in range(65) + } + self.rejects("65 extension bitmaps exceed 64", THEME + "[light]\n", **files) + + +class CliTests(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.root = Path(self.directory.name) + self.catalog = self.root / "catalog.json" + self.catalog.write_text(json.dumps(fixtures.catalog_document())) + self.previous = os.getcwd() + os.chdir(self.root) + + def tearDown(self): + os.chdir(self.previous) + self.directory.cleanup() + + def run_cli(self, *args): + out, err = io.StringIO(), io.StringIO() + status = 0 + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + try: + cli.main([str(a) for a in args]) + except SystemExit as exit_: + status = exit_.code + return status, out.getvalue(), err.getvalue() + + def test_catalog_list_and_show(self): + status, out, _ = self.run_cli("catalog", "list", "--extensions") + self.assertEqual(status, 0) + lines = out.splitlines() + self.assertEqual(lines[0], "appearance settings-accent 78x121 mask8 0 menu") + self.assertEqual(len(lines), len(assets.load_catalog())) + _, out, _ = self.run_cli( + "catalog", "list", "--extensions", "--group", "reprise" + ) + self.assertEqual( + out, + "reprise settings-info 78x121 mask8 0 menu\n", + ) + _, out, _ = self.run_cli( + "catalog", "list", "--extensions", "--format", "indexed8" + ) + self.assertEqual(out, "") + status, _, err = self.run_cli( + "catalog", "list", "--extensions", "--format", "gif" + ) + self.assertEqual(status, 1) + self.assertIn("--format: expected one of mask8, indexed8, bgra8888", err) + _, out, _ = self.run_cli("catalog", "show", "reprise/settings-info") + self.assertIn("id reprise\nasset settings-info\nmenu true\nformat 0x8\n", out) + self.assertIn( + "format_name mask8\nowner_hash 0xb3f4a34d\nasset_hash 0x24c0da6b", out + ) + status, _, err = self.run_cli("catalog", "show", "nope/x") + self.assertEqual(status, 1) + self.assertIn("'nope/x' is not in the extension asset catalog", err) + addition = self.root / "assets.json" + addition.write_text(json.dumps(record("third", "logo", 4, 1)) + "\n") + _, out, _ = self.run_cli( + "catalog", + "list", + "--extensions", + "--group", + "third", + "--extension", + addition, + ) + self.assertEqual(out, "third logo 4x1 indexed8 0 bitmap\n") + _, out, _ = self.run_cli( + "catalog", "show", "third/logo", "--extension", addition + ) + self.assertIn("menu false\n", out) + + def test_compile_and_inspect_with_an_extension(self): + folder = self.root / "src" + png = folder / "light" / "extensions" / "third" / "logo.png" + png.parent.mkdir(parents=True) + png.write_bytes(rgba_png(4, 1, bytes(range(16)))) + (folder / "theme.toml").write_text(THEME + "[light]\n") + status, _, err = self.run_cli("check", folder, "--catalog", self.catalog) + self.assertEqual(status, 1) + self.assertIn("pass --extension", err) + addition = self.root / "assets.json" + addition.write_text(json.dumps(record("third", "logo", 4, 1)) + "\n") + status, out, err = self.run_cli( + "compile", folder, "--catalog", self.catalog, "--extension", addition + ) + self.assertEqual((status, err), (0, "")) + self.assertIn("1 extension bitmaps", out) + rvt = self.root / "dist" / "test" / "test.rvt" + _, out, _ = self.run_cli("inspect", rvt, "--catalog", self.catalog) + self.assertIn("1 extension bitmaps: 0x", out) + _, out, _ = self.run_cli( + "inspect", rvt, "--catalog", self.catalog, "--extension", addition + ) + self.assertIn("1 extension bitmaps: third/logo 4x1 indexed8", out) + _, out, _ = self.run_cli( + "inspect", rvt, "--catalog", self.catalog, "--extension", addition, "--json" + ) + self.assertEqual( + json.loads(out)["appearances"]["light"]["extension_bitmaps"][0]["palette"], + 4, + ) + + +class PageTests(unittest.TestCase): + def test_page_is_the_generator_output(self): + page = ROOT / "docs" / "extension-bitmaps.md" + self.assertEqual(page.read_text(), extension_bitmaps_doc.current()) + + def test_vendored_catalog_is_the_converter_output(self): + source = Path(str(assets.CATALOG)) + self.assertEqual(source.read_text(), extensions_catalog.convert(source)) + with tempfile.TemporaryDirectory() as name: + unsorted = Path(name) / "assets.json" + unsorted.write_text( + json.dumps(record("z", "a", 1, 1)) + + "\n" + + json.dumps(record("a", "b", 1, 1)) + + "\n" + + json.dumps(record("a", "a", 1, 1)) + + "\n" + ) + out = Path(name) / "extensions.json" + with contextlib.redirect_stdout(io.StringIO()): + extensions_catalog.main([str(unsorted), "--out", str(out)]) + self.assertEqual( + [json.loads(line)["asset"] for line in out.read_text().splitlines()], + ["a", "b", "a"], + ) + unsorted.write_text((json.dumps(record("a", "a", 1, 1)) + "\n") * 2) + with self.assertRaisesRegex(ValueError, "a/a is listed twice"): + extensions_catalog.convert(unsorted) + + def test_page_rows(self): + text = extension_bitmaps_doc.page( + { + ("third", "logo"): record("third", "logo", 4, 1, colors=3), + ("reprise", "settings-info"): record( + "reprise", "settings-info", 78, 121, True + ), + } + ) + self.assertIn( + "| `reprise` | `settings-info` | 78x121 | mask8 | - | yes |", text + ) + self.assertIn("| `third` | `logo` | 4x1 | indexed8 | 3 | no |", text) + self.assertLess(text.index("`reprise`"), text.index("`third`")) + with tempfile.TemporaryDirectory() as name: + out = Path(name) / "page.md" + with contextlib.redirect_stdout(io.StringIO()): + extension_bitmaps_doc.main(["--out", str(out)]) + self.assertEqual(out.read_text(), extension_bitmaps_doc.current()) + + +if __name__ == "__main__": + unittest.main() diff --git a/themes/tests/test_bitmaps.py b/themes/tests/test_bitmaps.py new file mode 100644 index 0000000..a20ff8f --- /dev/null +++ b/themes/tests/test_bitmaps.py @@ -0,0 +1,278 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""PNG reading, palette fitting, the native pixel codecs and the lz codec.""" + +import os +import struct +import unittest +import zlib +from pathlib import Path + +import fixtures +from rvt import bitmaps, lz + +# The SDK checkout the extensions build uses (the root Makefile default). +SDK = Path( + os.environ.get("SDK", Path(__file__).resolve().parents[3] / "osos-lab" / "rvx-sdk") +) +RVX = SDK / "rvx.py" + + +def chunk(kind, body): + return ( + struct.pack(">I", len(body)) + + kind + + body + + struct.pack(">I", zlib.crc32(kind + body)) + ) + + +def make_png(width, height, depth, color_type, rows, extra=(), idat_parts=1): + """A PNG from filtered scanlines; `extra` chunks go between IHDR and IDAT + and the compressed rows are split over idat_parts IDAT chunks.""" + header = struct.pack(">IIBBBBB", width, height, depth, color_type, 0, 0, 0) + data = zlib.compress(rows) + size = -(-len(data) // idat_parts) + parts = [data[i : i + size] for i in range(0, len(data), size)] + return ( + b"\x89PNG\r\n\x1a\n" + + chunk(b"IHDR", header) + + b"".join(chunk(kind, body) for kind, body in extra) + + b"".join(chunk(b"IDAT", part) for part in parts) + + chunk(b"IEND", b"") + ) + + +def filtered(raw_rows, stride, bpp, filter_type): + """Scanlines of 8-bit samples encoded with one PNG filter.""" + out = bytearray() + previous = bytes(stride) + for row in raw_rows: + out.append(filter_type) + for x in range(stride): + a = row[x - bpp] if x >= bpp else 0 + b = previous[x] + c = previous[x - bpp] if x >= bpp else 0 + predictor = (0, a, b, (a + b) // 2, bitmaps.paeth(a, b, c))[filter_type] + out.append((row[x] - predictor) & 255) + previous = row + return bytes(out) + + +def packed_indices(indices, depth): + """One scanline of palette indices packed MSB first, with its filter byte.""" + bits = "".join(f"{i:0{depth}b}" for i in indices) + bits += "0" * (-len(bits) % 8) + return b"\0" + int(bits, 2).to_bytes(len(bits) // 8, "big") + + +class PngTests(unittest.TestCase): + RGBA = bytes([10, 20, 30, 255, 40, 50, 60, 128, 70, 80, 90, 0, 1, 2, 3, 4]) + + def test_palette_depths(self): + palette = bytes([255, 0, 0, 0, 255, 0, 0, 0, 255, 9, 9, 9]) + alpha = bytes([255, 128]) + for depth, indices in ((1, [0, 1, 1, 0]), (2, [0, 1, 2, 3]), (4, [3, 2, 1, 0])): + with self.subTest(depth=depth): + png = make_png( + 4, + 1, + depth, + 3, + packed_indices(indices, depth), + [(b"PLTE", palette), (b"tRNS", alpha)], + ) + width, height, rgba = bitmaps.read_png(png) + self.assertEqual((width, height), (4, 1)) + expected = b"".join( + palette[i * 3 : i * 3 + 3] + bytes([alpha[i] if i < 2 else 255]) + for i in indices + ) + self.assertEqual(rgba, expected) + + def test_gray_and_rgb_with_transparent_colour(self): + gray = make_png(3, 1, 8, 0, b"\0\x10\x20\x30", [(b"tRNS", b"\0\x20")]) + self.assertEqual( + bitmaps.read_png(gray)[2], + bytes([16, 16, 16, 255, 32, 32, 32, 0, 48, 48, 48, 255]), + ) + gray_alpha = make_png(2, 1, 8, 4, b"\0\x10\x80\x20\xff") + self.assertEqual( + bitmaps.read_png(gray_alpha)[2], bytes([16, 16, 16, 128, 32, 32, 32, 255]) + ) + rgb = make_png( + 2, + 1, + 8, + 2, + b"\0\x01\x02\x03\x04\x05\x06", + [(b"tRNS", b"\0\x04\0\x05\0\x06")], + ) + self.assertEqual(bitmaps.read_png(rgb)[2], bytes([1, 2, 3, 255, 4, 5, 6, 0])) + + def test_filters_and_multiple_idat_chunks(self): + rows = [self.RGBA[:8], self.RGBA[8:]] + for filter_type in range(5): + with self.subTest(filter=filter_type): + png = make_png( + 2, 2, 8, 6, filtered(rows, 8, 4, filter_type), idat_parts=3 + ) + self.assertEqual(bitmaps.read_png(png), (2, 2, self.RGBA)) + + def test_malformed_png_is_rejected(self): + good = make_png(2, 2, 8, 6, filtered([self.RGBA[:8], self.RGBA[8:]], 8, 4, 0)) + cases = { + "not a PNG": good[1:], + "truncated PNG": good[:-20], + "truncated PNG ": good[:40], + "checksum": good[:-5] + bytes([good[-5] ^ 1]) + good[-4:], + "interlaced": make_png(1, 1, 8, 6, bytes(5))[:28] + + b"\1" + + make_png(1, 1, 8, 6, bytes(5))[29:], + "pixel length": make_png(2, 2, 8, 6, bytes(9)), + "row filter": make_png(1, 1, 8, 6, b"\5\0\0\0\0"), + "exceeds palette": make_png(1, 1, 8, 3, b"\0\3", [(b"PLTE", bytes(3))]), + "16-bit": make_png(1, 1, 16, 6, bytes(9)), + } + for name, bad in cases.items(): + with self.subTest(name), self.assertRaises(ValueError): + bitmaps.read_png(bad) + + def test_write_png_round_trip(self): + png = bitmaps.write_png(2, 2, self.RGBA) + self.assertEqual(bitmaps.read_png(png), (2, 2, self.RGBA)) + + +class PaletteTests(unittest.TestCase): + def test_fit_palette_reserves_transparent_and_keeps_fitting_art(self): + rgba = b"".join(bytes((v, v, v, 255)) for v in range(16)) + bytes(4) + self.assertEqual(bitmaps.fit_palette(rgba, 17), rgba) + fitted = bitmaps.fit_palette(rgba, 4) + colors = {fitted[i : i + 4] for i in range(0, len(fitted), 4)} + self.assertEqual(len(colors), 4) + self.assertIn(bytes(4), colors) + self.assertEqual(fitted[-4:], bytes(4)) + self.assertEqual(bitmaps.distinct(rgba), 17) + + def test_fit_levels_reduces_coverage_alone(self): + levels = bytes(range(0, 256, 5)) + fitted = bitmaps.fit_levels(levels, 8) + self.assertEqual(len(set(fitted)), 8) + self.assertEqual(fitted[0], 0) + self.assertEqual( + bitmaps.fit_levels(bytes([0, 100, 200]), 3), bytes([0, 100, 200]) + ) + # The tint colour does not change which levels survive. + for tint in ("#ff0000", "#00ff00"): + tinted = bitmaps.tinted_pixels(fitted, tint) + self.assertEqual(tinted[3::4], fitted) + + +class CodecTests(unittest.TestCase): + def setUp(self): + self.catalog = fixtures.catalog() + + def round_trip(self, name, rgba): + info = self.catalog.assets[self.catalog.resolve(name, "x")] + payload = bitmaps.encode_pixels(info, info["width"], info["height"], rgba) + self.assertEqual(len(payload), info["bytes"] - info["data_offset"]) + self.assertTrue(bitmaps.palette_indices_fit(info, payload)) + return payload, bitmaps.decode_pixels(info, payload) + + def test_each_format_round_trips(self): + two = bytes([10, 20, 30, 255, 40, 50, 60, 128]) * 2 + payload, back = self.round_trip("Alpha", two) + self.assertEqual(back, two) + self.assertEqual(payload[:8], bytes([30, 20, 10, 255, 60, 50, 40, 128])) + eight = b"".join(bytes((i, i * 2, i * 3, 255)) for i in range(8)) + bytes(16) + eight = eight[:32] + eight[:16] + _, back = self.round_trip("Iota", eight) + self.assertEqual(back, eight) + bgra = bytes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]) + payload, back = self.round_trip("Beta", bgra) + self.assertEqual(back, bgra) + self.assertEqual(payload[:4], bytes([3, 2, 1, 4])) + rgb = bytes([248, 252, 248, 255, 8, 4, 8, 255]) * 2 + payload, back = self.round_trip("Zeta", rgb) + self.assertEqual(back, rgb) + self.assertEqual(struct.unpack_from(" About |\n" + ) + self.assertEqual(appears, {"Alpha": "Settings > About"}) + document = fixtures.catalog_document()["bitmaps"] + text = bitmaps_doc.page(document, appears) + self.assertIn("## Other", text) + self.assertEqual( + bitmaps_doc.group_of("No_Content_Music_Preview_Image"), "No_Content" + ) + self.assertEqual(bitmaps_doc.group_of("Notes_Preview_Image"), "Notes") + self.assertIn("| `Alpha` | 4x1 | indexed8 | 2 | yes | Settings > About |", text) + self.assertIn("| `Delta` | 4x1 | mask8 | - | yes | |", text) + self.assertIn("| `Zeta` | 4x1 | rgb565 | - | no | |", text) + + def test_lookup_and_validation(self): + loaded = fixtures.catalog() + self.assertEqual(loaded.resolve("Alpha", "x"), 0) + self.assertEqual(loaded.resolve("0x20", "x"), 1) + # The largest payload is a relight's 48 bytes, except Iota (8 palette + # entries, a 68-byte recolour) and Kappa (12 pixels, 100 bytes). + self.assertEqual(loaded.max_body(), 856 + 11 * 12 + 9 * 48 + 68 + 100) + with self.assertRaisesRegex(ValueError, "not a catalog bitmap name"): + loaded.resolve("Nope", "x") + with self.assertRaisesRegex(ValueError, "0x00000099 is not a catalog bitmap"): + loaded.resolve("0x99", "x") + with self.assertRaisesRegex(ValueError, "ambiguous; use one of 0x00000020"): + fixtures.catalog(duplicate_name=True).resolve("Beta", "x") + document = fixtures.catalog_document() + document["bitmaps"][0]["address"] += 1 + with self.assertRaisesRegex(ValueError, "address"): + catalog.Catalog(document) + document = fixtures.catalog_document() + document["fingerprint"] = "00" * 8 + with self.assertRaisesRegex(ValueError, "stored fingerprint"): + catalog.Catalog(document) + document = fixtures.catalog_document() + document["bitmaps"][1]["id"] = 0x10 + with self.assertRaisesRegex(ValueError, "duplicate bitmap id"): + catalog.Catalog(document) + document = fixtures.catalog_document() + del document["runtime_base"] + with self.assertRaisesRegex(ValueError, "runtime_base"): + catalog.Catalog(document) + + +if __name__ == "__main__": + unittest.main() diff --git a/themes/tests/test_cli.py b/themes/tests/test_cli.py new file mode 100644 index 0000000..26f76fa --- /dev/null +++ b/themes/tests/test_cli.py @@ -0,0 +1,159 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""rvt new, check, compile --strict, catalog, and report determinism.""" + +import contextlib +import io +import json +import os +import tempfile +import unittest +from pathlib import Path + +import fixtures +from fixtures import rgba_png +from rvt import cli + +THEME = 'schema = 1\nid = "test"\nname = "Test"\n' + + +class CliTests(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.root = Path(self.directory.name) + self.catalog = self.root / "catalog.json" + self.catalog.write_text(json.dumps(fixtures.catalog_document())) + self.previous = os.getcwd() + os.chdir(self.root) + + def tearDown(self): + os.chdir(self.previous) + self.directory.cleanup() + + def run_cli(self, *args): + out, err = io.StringIO(), io.StringIO() + status = 0 + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + try: + cli.main([str(a) for a in args]) + except SystemExit as exit_: + status = exit_.code + return status, out.getvalue(), err.getvalue() + + def theme(self, toml=THEME, **files): + folder = self.root / "src" + folder.mkdir(exist_ok=True) + (folder / "theme.toml").write_text(toml) + for path, content in files.items(): + target = folder / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(content) + return folder + + def test_new_writes_a_compilable_folder(self): + status, out, _ = self.run_cli("new", "mine", "--name", "Mine") + self.assertEqual(status, 0) + self.assertIn("Wrote mine/theme.toml", out) + for appearance in ("light", "dark"): + for sub in ("apple", "reprise", "extensions"): + self.assertTrue((self.root / "mine" / appearance / sub).is_dir()) + status, out, _ = self.run_cli("check", "mine", "--catalog", self.catalog) + self.assertEqual(status, 0) + self.assertIn("mine.rvt:", out) + status, _, err = self.run_cli("new", "mine") + self.assertEqual((status, err), (1, "mine exists\n")) + status, _, err = self.run_cli("new", "classic") + self.assertIn("reserved", err) + status, _, err = self.run_cli("new", "Bad") + self.assertIn("id: expected", err) + + def test_check_prints_warnings_and_sizes_without_writing(self): + rainbow = rgba_png(4, 1, bytes(range(16))) + folder = self.theme(THEME + "[light]\n", **{"light/apple/Alpha.png": rainbow}) + status, out, err = self.run_cli("check", folder, "--catalog", self.catalog) + self.assertEqual(status, 0) + self.assertIn( + "warning: light/apple/Alpha.png: 4 colours reduced to the 2 of its palette", + err, + ) + self.assertIn("light: 1 bitmaps (1 pixels, 0 derived)", out) + self.assertFalse((self.root / "dist").exists()) + status, _, err = self.run_cli( + "check", folder, "--catalog", self.catalog, "--strict" + ) + self.assertEqual(status, 1) + self.assertIn("1 warnings with --strict", err) + status, out, err = self.run_cli( + "compile", folder, "--catalog", self.catalog, "--strict" + ) + self.assertEqual(status, 1) + self.assertFalse((self.root / "dist").exists()) + status, out, err = self.run_cli("compile", folder, "--catalog", self.catalog) + self.assertEqual(status, 0) + self.assertIn("reduced", err) + report = json.loads((self.root / "dist/test/report.json").read_text()) + self.assertEqual( + report["appearances"]["light"]["palette_reduced"], + [{"name": "Alpha", "colors": 4, "palette": 2}], + ) + + def test_report_and_file_are_deterministic(self): + folder = self.theme( + THEME + '[light.tint]\ntext = ["Delta"]\n[dark]\n', + **{"light/apple/Alpha.png": rgba_png(4, 1, bytes(16))}, + ) + outputs = [] + for out in ("one", "two"): + self.run_cli("compile", folder, "--catalog", self.catalog, "--out", out) + outputs.append( + ( + (self.root / out / "test/test.rvt").read_bytes(), + (self.root / out / "test/report.json").read_text(), + ) + ) + self.assertEqual(outputs[0], outputs[1]) + report = json.loads(outputs[0][1]) + self.assertEqual( + sorted(report["appearances"]["light"]), + [ + "accents_builtin", + "bytes", + "contrast", + "extension_bitmaps", + "extension_tinted", + "palette_reduced", + "records", + ], + ) + + def test_catalog_list_and_show(self): + status, out, _ = self.run_cli("catalog", "list", "--catalog", self.catalog) + self.assertEqual(status, 0) + self.assertEqual(out.splitlines()[0], "Alpha 4x1 indexed8 2 tintable") + self.assertEqual(len(out.splitlines()), 11) + _, out, _ = self.run_cli( + "catalog", "list", "--catalog", self.catalog, "--group", "Z" + ) + self.assertEqual(out, "Zeta 4x1 rgb565 0 untintable\n") + _, out, _ = self.run_cli( + "catalog", "list", "--catalog", self.catalog, "--format", "mask4" + ) + self.assertEqual(out, "Epsilon 4x1 mask4 0 tintable\n") + status, _, err = self.run_cli( + "catalog", "list", "--catalog", self.catalog, "--format", "gif" + ) + self.assertEqual(status, 1) + _, out, _ = self.run_cli("catalog", "show", "Iota", "--catalog", self.catalog) + self.assertIn("index 8\nid 0x90\nname Iota\n", out) + self.assertIn("format 0x65\n", out) + self.assertIn("format_name indexed16", out) + _, out, _ = self.run_cli("catalog", "show", "0x90", "--catalog", self.catalog) + self.assertIn("name Iota", out) + status, _, err = self.run_cli( + "catalog", "show", "Nope", "--catalog", self.catalog + ) + self.assertEqual(status, 1) + self.assertIn("not a catalog bitmap name", err) + + +if __name__ == "__main__": + unittest.main() diff --git a/themes/tests/test_compile.py b/themes/tests/test_compile.py new file mode 100644 index 0000000..dca0b1f --- /dev/null +++ b/themes/tests/test_compile.py @@ -0,0 +1,467 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""Compiling theme folders, the inspector and the rejection cases.""" + +import contextlib +import io +import json +import os +import shutil +import struct +import tempfile +import unittest +from pathlib import Path + +import fixtures +from fixtures import rgba_png +from rvt import cli, inspector, lz, rvtfile, style +from rvt.compiler import compile_theme, write + +THEME = 'schema = 1\nid = "test"\nname = "Test"\n' + + +class CompileTests(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.root = Path(self.directory.name) / "src" + self.root.mkdir() + self.catalog = fixtures.catalog() + rgba = bytes([10, 20, 30, 50, 40, 50, 60, 70]) * 2 + self.art = { + "alpha": rgba_png(4, 1, rgba), + "beta": rgba_png(3, 1, bytes(range(12))), + # Coverage art: an alpha ramp over a colour, and an opaque gray ramp. + "alpha-ramp": rgba_png( + 4, 1, b"".join(bytes((200, 10, 10, a)) for a in (0, 85, 170, 255)) + ), + "gray-ramp": rgba_png( + 4, 1, b"".join(bytes((v, v, v, 255)) for v in (0, 86, 170, 255)) + ), + "alpha-ramp3": rgba_png( + 3, 1, b"".join(bytes((200, 10, 10, a)) for a in (0, 128, 255)) + ), + "color": rgba_png(4, 1, bytes([200, 10, 10, 255]) * 4), + "rgb": rgba_png(4, 1, bytes([255, 0, 0, 255, 0, 255, 0, 255]) * 2), + } + + def tearDown(self): + self.directory.cleanup() + + def theme(self, toml=THEME, **files): + """Write theme.toml and art given as "light/apple/Alpha" -> fixture name.""" + (self.root / "theme.toml").write_text(toml) + for appearance in ("light", "dark"): + if (self.root / appearance).is_dir(): + shutil.rmtree(self.root / appearance) + for path, art in files.items(): + if path.endswith(".toml"): + target = self.root / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(art) + continue + target = self.root / f"{path}.png" + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(self.art[art]) + return self.root + + def compile(self, toml=THEME, catalog=None, **files): + self.theme(toml, **files) + self.build = compile_theme(catalog or self.catalog, self.root) + return self.build.data, self.build.report + + def rejects(self, pattern, toml=THEME, catalog=None, **files): + with self.assertRaisesRegex(ValueError, pattern): + self.compile(toml, catalog, **files) + + def test_mask_paletted_and_rgb565_records(self): + toml = ( + THEME + + '[light.colors]\nicon_tint = "#112233"\n[light.tint]\nicon_tint = ["Delta"]\n[dark]\n' + ) + data, report = self.compile( + toml, + **{ + "light/apple/Alpha": "alpha", + "light/apple/Delta": "gray-ramp", + "light/apple/Zeta": "rgb", + }, + ) + result = inspector.inspect(data, self.catalog) + self.assertEqual(sorted(result["appearances"]), ["dark", "light"]) + light = result["appearances"]["light"] + self.assertEqual([r["index"] for r in light["records"]], [0, 3, 5]) + self.assertEqual( + light["tinted"], + {3: {"name": "Delta", "role": "icon_tint", "coverage": "alpha"}}, + ) + self.assertEqual(light["colors"]["icon_tint"], "#112233") + body, count, bitmap_count = rvtfile.decode_file(data)["packs"]["light"] + self.assertEqual((count, bitmap_count), (3, 0)) + at = style.STYLE_BYTES + self.assertEqual(rvtfile.RECORD.unpack_from(body, at), (0, 0, 12)) + at += 12 + self.assertEqual( + body[at : at + 12], bytes([30, 20, 10, 50, 60, 50, 40, 70, 0, 1, 0, 1]) + ) + at += 12 + self.assertEqual(rvtfile.RECORD.unpack_from(body, at), (3, 0, 4)) + at += 12 + self.assertEqual(body[at : at + 4], bytes([0, 86, 170, 255])) + at += 4 + # Two repeated words compress to 7 bytes, so Zeta is an lz record. + self.assertEqual(rvtfile.RECORD.unpack_from(body, at), (5, 5, 7)) + at += 12 + words = struct.pack("<4H", 0xF800, 0x07E0, 0xF800, 0x07E0) + self.assertEqual(lz.lz_decode(body[at : at + 7], 8), words) + self.assertEqual(light["records"][2]["payload"], words) + self.assertEqual(light["records"][2]["bytes"], 7) + self.assertEqual(len(body), at + 8) + self.assertEqual( + report["appearances"]["light"]["records"], {"pixels": 2, "pixels_lz": 1} + ) + self.assertEqual(report["appearances"]["light"]["bytes"], len(body)) + dark = result["appearances"]["dark"] + self.assertEqual(dark["colors"], style.COLOR_DEFAULTS["dark"]) + self.assertEqual( + (dark["records"], dark["tinted"], dark["rendering"]), ([], {}, 0) + ) + self.assertEqual(sorted(report), ["appearances", "id", "name"]) + self.assertEqual( + sorted(report["appearances"]["light"]), + [ + "accents_builtin", + "bytes", + "contrast", + "extension_bitmaps", + "extension_tinted", + "palette_reduced", + "records", + ], + ) + self.assertEqual(len(report["appearances"]["light"]["accents_builtin"]), 9) + self.assertTrue(report["appearances"]["light"]["contrast"]) + + def test_tinted_palette_and_bgra_art_and_palette_reduction(self): + toml = ( + THEME + + '[dark.colors]\nicon_tint = "#112233"\n[dark.tint]\nicon_tint = ["Alpha"]\nselection = ["0x20"]\ntext = ["Epsilon"]\n' + ) + data, _ = self.compile( + toml, + **{ + "dark/apple/Alpha": "alpha-ramp", + "dark/apple/0x20": "alpha-ramp3", + "dark/apple/Epsilon": "alpha-ramp", + }, + ) + pack = inspector.inspect(data, self.catalog)["appearances"]["dark"] + self.assertEqual( + {i: t["role"] for i, t in pack["tinted"].items()}, + {0: "icon_tint", 1: "selection", 4: "text"}, + ) + payloads = {r["name"]: r["payload"] for r in pack["records"]} + # Paletted: transparent reserved, then the tint with the mean coverage + # of the levels the palette cannot hold. + self.assertEqual( + payloads["Alpha"][:8], bytes([0, 0, 0, 0, 0x33, 0x22, 0x11, 170]) + ) + self.assertEqual( + payloads["Beta"], + bytes([0, 0, 0, 0, 0x33, 0x22, 0x11, 128, 0x33, 0x22, 0x11, 255]), + ) + self.assertEqual(payloads["Epsilon"], bytes([0x05, 0xAF])) # 4-bit gray steps + self.assertEqual( + self.build.warnings, + ["dark/apple/Alpha.png: 4 colours reduced to the 2 of its palette"], + ) + self.assertEqual( + self.build.report["appearances"]["dark"]["palette_reduced"], + [{"name": "Alpha", "colors": 4, "palette": 2}], + ) + # A tinted mask without art sets the role and writes no record. + data, _ = self.compile(THEME + '[light.tint]\nicon_tint = ["Delta"]\n') + pack = inspector.inspect(data, self.catalog)["appearances"]["light"] + self.assertEqual((list(pack["tinted"]), pack["records"]), ([3], [])) + + def test_output_is_deterministic_and_accepted_without_catalog(self): + first, _ = self.compile(THEME + "[light]\n", **{"light/apple/Alpha": "alpha"}) + second, _ = self.compile(THEME + "[light]\n", **{"light/apple/Alpha": "alpha"}) + self.assertEqual(first, second) + self.assertEqual(inspector.inspect(first)["id"], "test") + self.assertEqual(self.build.warnings, []) + + def test_style_tables(self): + toml = THEME + ( + '[dark.colors]\naccent_fill = "#ABCDEF"\n' + '[dark.accents.teal]\nselection = "#006666"\n' + "[dark]\nmenu_covers_default = false\n" + "[dark.rendering]\nflat_selection = true\nflat_now_playing = true\n" + ) + data, report = self.compile(toml) + pack = inspector.inspect(data, self.catalog)["appearances"]["dark"] + self.assertEqual(pack["colors"]["accent_fill"], "#abcdef") + self.assertEqual(pack["rendering"], 7) + self.assertEqual(pack["accents"]["teal"]["selection"], "#006666") + self.assertEqual(pack["accents"]["teal"]["on_accent"], "#ffffff") + self.assertEqual(pack["colors"]["icon_tint"], "#00a1ff") + builtin = report["appearances"]["dark"]["accents_builtin"] + self.assertNotIn("teal", builtin) + self.assertIn("yellow", builtin) + + def test_invalid_toml_and_art_are_rejected(self): + cases = { + "schema: unsupported schema 2": THEME.replace("schema = 1", "schema = 2"), + r"^id: expected": THEME.replace('"test"', '"Test"'), + "reserved for the built-in theme": THEME.replace('"test"', '"classic"') + + "[light]\n", + "exceeds 47": THEME.replace('"Test"', '"' + "x" * 48 + '"'), + r"declare \[light\]": THEME, + "extra: unknown key": THEME + "extra = 1\n[light]\n", + "fonts: unsupported capability": THEME + "[light.fonts]\n", + "light.colours: unknown key": THEME + "[light.colours]\n", + "light.colors.accent: unknown key": THEME + + '[light.colors]\naccent = "#000000"\n', + 'light.colors.text: expected "#rrggbb"': THEME + + '[light.colors]\ntext = "#fff"\n', + "light.accents.cyan: unknown key": THEME + "[light.accents.cyan]\n", + "light.rendering.selection: unknown key": THEME + + '[light.rendering]\nselection = "rounded"\n', + "light.menu_covers_default: expected true or false": THEME + + '[light]\nmenu_covers_default = "on"\n', + "light.tint.well: expected one of": THEME + + '[light.tint]\nwell = ["Delta"]\n', + "Zeta cannot be tinted": THEME + '[light.tint]\ntext = ["Zeta"]\n', + "light.tint.text: Delta is already tinted text": THEME + + '[light.tint]\ntext = ["Delta", "0x40"]\n', + "invalid TOML": THEME + "[light]\n[light]\n", + "author: expected a non-empty string": THEME + 'author = ""\n[light]\n', + } + for pattern, toml in cases.items(): + with self.subTest(pattern): + self.rejects(pattern, toml) + light = THEME + "[light]\n" + self.rejects( + "light/apple/Nope.png: 'Nope' is not a catalog bitmap name", + light, + **{"light/apple/Nope": "alpha"}, + ) + self.rejects( + "duplicate replacement for Alpha", + light, + **{"light/apple/Alpha": "alpha", "light/apple/0x10": "alpha"}, + ) + self.rejects( + "light/apple/Alpha.png: expected 4x1, got 3x1", + light, + **{"light/apple/Alpha": "beta"}, + ) + self.rejects( + "light/apple/Zeta.png: native RGB565 requires opaque", + light, + **{"light/apple/Zeta": "alpha-ramp"}, + ) + self.rejects( + "ambiguous", + light, + fixtures.catalog(duplicate_name=True), + **{"light/apple/Beta": "beta"}, + ) + self.rejects( + "grayscale or carry alpha coverage", + light + '[light.tint]\nicon_tint = ["Delta"]\n', + **{"light/apple/Delta": "color"}, + ) + self.rejects( + r"dark: has art but theme.toml declares no \[dark\]", + light, + **{"dark/apple/Alpha": "alpha"}, + ) + # An empty folder, as `rvt new` leaves one, is not art. + self.theme(light) + (self.root / "dark" / "apple").mkdir(parents=True) + (self.root / "dark" / "extensions").mkdir() + compile_theme(self.catalog, self.root) + + def rejects_file(pattern, prepare): + self.theme(light) + (self.root / "light" / "apple").mkdir(parents=True) + prepare(self.root / "light" / "apple") + with self.assertRaisesRegex(ValueError, pattern): + compile_theme(self.catalog, self.root) + + outside = self.root.parent / "Alpha.png" + outside.write_bytes(self.art["alpha"]) + rejects_file( + "light/apple/notes.txt: expected .png", + lambda folder: (folder / "notes.txt").write_text("x"), + ) + rejects_file( + "light/apple/Alpha.png: must be a file inside the theme folder", + lambda folder: (folder / "Alpha.png").symlink_to(outside), + ) + rejects_file( + "light/apple/Alpha.png: must be a file inside the theme folder", + lambda folder: (folder / "Alpha.png").mkdir(), + ) + + def test_reserved_id_with_permission_carries_art_only(self): + classic = THEME.replace('"test"', '"classic"') + self.theme(classic + "[dark]\n") + build = compile_theme(self.catalog, self.root, allow_reserved=True) + self.assertEqual(inspector.inspect(build.data, self.catalog)["id"], "classic") + for table in ( + "[dark.rendering]\nflat_icons = true\n", + "[dark]\nmenu_covers_default = false\n", + '[dark.tint]\ntext = ["Delta"]\n', + ): + self.theme(classic + table) + with self.assertRaisesRegex(ValueError, "dark: the built-in theme carries"): + compile_theme(self.catalog, self.root, allow_reserved=True) + + def test_inspector_checks_packs_against_the_catalog(self): + data, _ = self.compile( + THEME + "[light]\n", **{"light/apple/Delta": "gray-ramp"} + ) + header = rvtfile.decode_file(data) + body, count, _ = header["packs"]["light"] + + def rebuilt(body, count=count, fingerprint=header["fingerprint"]): + return rvtfile.encode_file( + fingerprint, "test", "Test", {"light": (bytes(body), count, 0)} + ) + + def tinted(index, value=1): + data = bytearray(body) + data[style.TINT_OFFSET + index] = value + return rebuilt(data) + + cases = { + "no palette or coverage": tinted(5), + "Epsilon has unknown record kind 0x7": rebuilt( + body[: style.STYLE_BYTES] + + rvtfile.RECORD.pack(4, 7, 4) + + body[style.STYLE_BYTES + 12 :] + ), + "outside the catalog": tinted(11), + "catalog fingerprint": rebuilt(body, fingerprint=bytes(8)), + "truncated record header": rebuilt(body[: style.STYLE_BYTES + 4]), + "trailing bytes": rebuilt(body + bytes(4)), + "truncated record payload": rebuilt( + body + rvtfile.RECORD.pack(4, 0, 2), count=2 + ), + "sorted by unique": rebuilt(body + body[style.STYLE_BYTES :], count=2), + "catalog index 90 is outside": rebuilt( + body[: style.STYLE_BYTES] + + rvtfile.RECORD.pack(90, 0, 4) + + body[style.STYLE_BYTES + 12 :] + ), + "does not match the native bitmap": rebuilt( + body[: style.STYLE_BYTES] + + rvtfile.RECORD.pack(3, 0, 5) + + body[style.STYLE_BYTES + 12 :] + ), + "catalog maximum": rebuilt( + body + bytes(rvtfile.EXTENSION_TABLE_MAX_BYTES + 1024), count=0 + ), + } + for pattern, bad in cases.items(): + with self.subTest(pattern), self.assertRaisesRegex(ValueError, pattern): + inspector.inspect(bad, self.catalog) + data, _ = self.compile(THEME + "[light]\n", **{"light/apple/Alpha": "alpha"}) + body = bytearray(rvtfile.decode_file(data)["packs"]["light"][0]) + body[-1] = 7 + with self.assertRaisesRegex(ValueError, "invalid palette index"): + inspector.inspect(rebuilt(body, 1), self.catalog) + body[-1] = 1 + padded = ( + body[: style.STYLE_BYTES] + + rvtfile.RECORD.pack(0, 0, 10) + + body[style.STYLE_BYTES + 12 :] + ) + with self.assertRaisesRegex(ValueError, "padding must be zero"): + inspector.inspect(rebuilt(padded, 1)) + payload = bytes(body[style.STYLE_BYTES + 12 :]) + stream = lz.lz_encode(payload + payload) + + def lz_record(stream, size=None): + return rebuilt( + body[: style.STYLE_BYTES] + + rvtfile.RECORD.pack(0, 5, size if size is not None else len(stream)) + + stream + + bytes(-len(stream) % 4), + 1, + ) + + with self.assertRaisesRegex(ValueError, "Alpha: lz stream continues"): + inspector.inspect(lz_record(stream), self.catalog) + with self.assertRaisesRegex(ValueError, "Alpha: lz match outside"): + inspector.inspect(lz_record(bytes([1, 0, 5, 0])), self.catalog) + with self.assertRaisesRegex(ValueError, "Alpha: lz stream ends early"): + inspector.inspect(lz_record(lz.lz_encode(payload)[:-1]), self.catalog) + with self.assertRaisesRegex(ValueError, "Alpha: lz stream continues"): + inspector.inspect(lz_record(lz.lz_encode(payload) + b"\0"), self.catalog) + good = lz_record(lz.lz_encode(payload)) + record = inspector.inspect(good, self.catalog)["appearances"]["light"][ + "records" + ][0] + self.assertEqual((record["kind"], record["payload"]), ("pixels_lz", payload)) + # Without a catalog the stream stays as stored. + record = inspector.inspect(good)["appearances"]["light"]["records"][0] + self.assertEqual(record["payload"], lz.lz_encode(payload)) + + def test_cli_writes_after_validation_and_leaves_failures_untouched(self): + out = Path(self.directory.name) / "out" + catalog_path = Path(self.directory.name) / "catalog.json" + catalog_path.write_text(json.dumps(fixtures.catalog_document())) + self.theme(THEME + "[light]\n", **{"light/apple/Alpha": "alpha"}) + args = [ + "compile", + str(self.root), + "--out", + str(out), + "--catalog", + str(catalog_path), + ] + with contextlib.redirect_stdout(io.StringIO()): + cli.main(args) + self.assertEqual(sorted(os.listdir(out / "test")), ["report.json", "test.rvt"]) + before = (out / "test" / "test.rvt").read_bytes() + report = json.loads((out / "test" / "report.json").read_text()) + self.assertEqual(list(report["appearances"]), ["light"]) + (self.root / "theme.toml").write_text(THEME + "[light.fonts]\n") + with self.assertRaises(SystemExit), contextlib.redirect_stderr(io.StringIO()): + cli.main(args) + self.assertEqual((out / "test" / "test.rvt").read_bytes(), before) + truncated = self.art["alpha"][:-10] + (self.root / "theme.toml").write_text(THEME + "[light]\n") + (self.root / "light" / "apple" / "Alpha.png").write_bytes(truncated) + with ( + self.assertRaises(SystemExit), + contextlib.redirect_stderr(io.StringIO()) as err, + ): + cli.main(args) + self.assertIn("light/apple/Alpha.png: truncated PNG", err.getvalue()) + (self.root / "light" / "apple" / "Alpha.png").write_bytes(self.art["alpha"]) + with contextlib.redirect_stdout(io.StringIO()) as output: + cli.main( + [ + "inspect", + str(out / "test" / "test.rvt"), + "--catalog", + str(catalog_path), + ] + ) + self.assertIn("1 records: 1 pixels; 0 tinted", output.getvalue()) + self.assertIn("0 extension bitmaps", output.getvalue()) + + def test_write_returns_the_rvt_path(self): + self.theme(THEME + "[dark]\n") + path, build = write( + self.catalog, self.root, Path(self.directory.name) / "build" + ) + self.assertEqual(path.name, "test.rvt") + self.assertEqual(build.report["id"], "test") + self.assertTrue(path.with_name("report.json").is_file()) + + +if __name__ == "__main__": + unittest.main() diff --git a/themes/tests/test_derive.py b/themes/tests/test_derive.py new file mode 100644 index 0000000..d46e780 --- /dev/null +++ b/themes/tests/test_derive.py @@ -0,0 +1,507 @@ +# SPDX-License-Identifier: GPL-3.0-only +"""Derived art: derivation files, record payloads, the reference arithmetic +applied to fixture bitmaps, rules resolved from the other appearance, and the +firmware helpers against a synthetic image.""" + +import shutil +import struct +import tempfile +import unittest +from pathlib import Path + +import fixtures +from fixtures import rgba_png +from rvt import bitmaps, derive, firmware, inspector +from rvt import rvtfile as format +from rvt.compiler import compile_theme + +THEME = 'schema = 1\nid = "test"\nname = "Test"\n' + +ETA, THETA, IOTA, KAPPA, LAMBDA = 6, 7, 8, 9, 10 +NARROW = 'kind = "relight"\nbg_lo = 24\nbg_hi = 26\nicon_lo = 30\nicon_hi = 31\n' + + +class DeriveTests(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.root = Path(self.directory.name) / "src" + self.root.mkdir() + self.catalog = fixtures.catalog() + self.image = fixtures.firmware_image() + self.firmware = firmware.Firmware(self.image_path(), self.catalog) + + def tearDown(self): + self.directory.cleanup() + + def image_path(self): + path = Path(self.directory.name) / "osos.bin" + path.write_bytes(self.image) + return path + + def theme(self, toml=THEME, **files): + (self.root / "theme.toml").write_text(toml) + for appearance in ("light", "dark"): + if (self.root / appearance).is_dir(): + shutil.rmtree(self.root / appearance) + for path, content in files.items(): + target = self.root / path + target.parent.mkdir(parents=True, exist_ok=True) + if isinstance(content, bytes): + target.write_bytes(content) + else: + target.write_text(content) + + def compile(self, toml=THEME, **files): + self.theme(toml, **files) + self.build = compile_theme(self.catalog, self.root) + return self.build.data, self.build.report + + def rejects(self, pattern, toml=THEME, **files): + with self.assertRaisesRegex(ValueError, pattern): + self.compile(toml, **files) + + def records(self, data, appearance="dark"): + return inspector.inspect(data, self.catalog)["appearances"][appearance][ + "records" + ] + + def stock(self, index): + return fixtures.BITMAPS[index] + + # Files and payloads + + def test_recolor_file_sorts_pairs_and_encodes_them(self): + toml = 'kind = "recolor"\n[map]\n"#000000ff" = "#ffffffff"\n"#ffffffff" = "#000000ff"\n' + data, _ = self.compile(THEME + "[dark]\n", **{"dark/apple/Eta.toml": toml}) + (record,) = self.records(data) + self.assertEqual(record["kind"], "recolor") + self.assertEqual( + record["spec"], + [ + (b"\0\0\0\xff", b"\xff\xff\xff\xff"), + (b"\xff\xff\xff\xff", b"\0\0\0\xff"), + ], + ) + body = format.decode_file(data)["packs"]["dark"][0] + at = format.STYLE_BYTES + self.assertEqual(format.RECORD.unpack_from(body, at), (ETA, 1, 4 + 16)) + self.assertEqual(body[at + 12 : at + 16], struct.pack(" tuple[int, int]: + """Rewrite the PNG with at most the bitmap's palette entries; returns the + colour counts before and after.""" + width, height, rgba = bitmaps.read_png(path.read_bytes()) + before = bitmaps.distinct(rgba) + capacity = entry["palette_colors"] + if capacity and before > capacity: + rgba = bitmaps.fit_palette(rgba, capacity) + path.write_bytes(bitmaps.write_png(width, height, rgba)) + return before, bitmaps.distinct(rgba) + + +def preview(path: Path, folder: Path, suffix: str) -> None: + folder.mkdir(parents=True, exist_ok=True) + subprocess.run( + [ + "magick", + str(path), + "-filter", + "point", + "-resize", + f"{SCALE * 100}%", + str(folder / f"{path.stem}-{suffix}.png"), + ], + check=True, + ) + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--preview", type=Path, help="write before/after PNGs here") + args = parser.parse_args(argv) + entries = catalog.load(None) + for path in sorted((HERE / "dark" / "apple").glob("*.png")): + entry = entries.assets[entries.resolve(path.stem, path.name)] + if args.preview: + preview(path, args.preview, "before") + before, after = fit(path, entry) + if args.preview: + preview(path, args.preview, "after") + print( + f"{path.name}: {before} -> {after} colours (palette {entry['palette_colors']})" + ) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/themes/themes/classic/recolor.py b/themes/themes/classic/recolor.py new file mode 100644 index 0000000..0f9cc6e --- /dev/null +++ b/themes/themes/classic/recolor.py @@ -0,0 +1,169 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +"""Write Classic dark's generated recolour rule files from the stock colours. + +Each bitmap in RULES gets `dark/apple/.toml` mapping every stock colour +through a tonal curve: two luma anchors joined by a line, clamped between +them, give the output grey; the stock alpha is kept. Colours with a chroma at +or above the rule's threshold (the red of a calendar header, the purple of a +Genius atom) pass through unchanged, so only the greys move. Every colour the +bitmap uses is listed, which is what keeps the iPod's result free of stray +stock pixels; a colour the curve leaves unchanged is left out because the +format forbids identity pairs. RGB565 targets lose the low bits the format +drops. The remaining .toml files in dark/apple/ are hand-written. + + python3 themes/classic/recolor.py --firmware osos.bin [--check] + +--check regenerates in memory and reports files that differ, writing nothing. +""" + +import argparse +import sys +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROOT = HERE.parents[1] +sys.path.insert(0, str(ROOT)) + +from rvt import catalog, derive, firmware # noqa: E402 + +# A curve: (stock luma, output grey) at two points; the line through them, +# clamped to the output range. A falling curve inverts a glyph. +SURFACE = ((0x5B, 0x10), (0xFC, 0x2F)) # the recoloured status bar's range +CELL = ((0x90, 0x26), (0xFF, 0x3C)) # a step above the #181818 background +CELL_DIM = ((0x90, 0x20), (0xFF, 0x30)) +WELL = ((0x80, 0x3C), (0xFF, 0x6E)) # the Disk Mode empty bar's grey +GLYPH = ((0x00, 0xE8), (0xA0, 0xA0)) # a dark glyph on transparent, inverted +PAGE = ((0x00, 0xD8), (0xFF, 0x2E)) # a dark glyph on an opaque white page +THUMB = ((0x80, 0x80), (0xFF, 0xC8)) # a white thumb that must stay a thumb +TRACK = ((0xAC, 0x33), (0xFC, 0x4A)) # the playing progress track +# The track's translucent rows are its reflection on the floor below; at the +# stock alphas they need a brighter grey than the track to show on dark. +TRACK_REFLECTION = ((0xAC, 0x70), (0xFC, 0x90)) +DIM = ((0x80, 0x80), (0xFF, 0xE4)) # light art kept, its white taken off glare +# Relight runs on paletted bitmaps only; the one RGB565 proxy square gets a +# curve that lands on relight's background and icon greys. +SQUARE = ((0xB0, 0x8C), (0xD8, 0x19)) + +CHROMA = 24 # below this a colour counts as grey; the extension's accent tint agrees +NEUTRAL = 2 # at most this much cast: the battery outline, not its blue-cast body +CAST = 64 # greys with a colour cast still count as grey; saturated dots pass +ALL = 256 # every colour, whatever its chroma +# The status bar battery needs two curves, told apart by colour cast: its +# neutral-grey outline and nub go brighter than the stock #63 so the frame +# shows on the dark bar, its blue-cast empty body goes dark, and the +# translucent white reflection under it is dropped. +BATTERY = object() +BATTERY_OUTLINE = ((0x60, 0x6A), (0xC8, 0x90)) +BATTERY_BODY = ((0x54, 0x26), (0xA4, 0x50)) + +RULES = { + "Lozenge_Left_White_Image": (SURFACE, CHROMA), + "Lozenge_Middle_White_Image": (SURFACE, CHROMA), + "Lozenge_Right_White_Image": (SURFACE, CHROMA), + "System_Input_Field_Left_Image": (SURFACE, CHROMA), + "System_Input_Field_Middle_Image": (SURFACE, CHROMA), + "System_Input_Field_Right_Image": (SURFACE, CHROMA), + "OptionBar_White_Well_Center_Image": (SURFACE, CHROMA), + "OptionBar_White_Well_LeftCap_Image": (SURFACE, CHROMA), + "OptionBar_White_Well_RightCap_Image": (SURFACE, CHROMA), + "OptionBar_NowPlaying_Well_Center_Image": (SURFACE, CHROMA), + "OptionBar_NowPlaying_Well_LeftCap_Image": (SURFACE, CHROMA), + "OptionBar_NowPlaying_Well_RightCap_Image": (SURFACE, CHROMA), + "WorldClock_Graybar_Image": (SURFACE, CHROMA), + "Calendar_Active_Cell": (CELL, ALL), + "Calendar_Inactive_Cell": (CELL_DIM, ALL), + "Settings_DateTime_Calendar_Image": (DIM, 96), + "Genius_Slider_Image": (CELL, CHROMA), + "NowPlaying_ProgressBar_Active_Background_Image": (TRACK, CHROMA), + "CapacityView_Detailed_EmptyCenter_Image": (WELL, CHROMA), + "CapacityView_Detailed_EmptyLeft_Image": (WELL, CHROMA), + "CapacityView_Detailed_EmptyRight_Image": (WELL, CHROMA), + "CapacityView_Detailed_Edge_Image": (WELL, CHROMA), + "Settings_About_Capacity_Fill_Image": (WELL, CHROMA), + "Settings_About_Capacity_LeftCap_Image": (WELL, CHROMA), + "Settings_About_Capacity_RightCap_Image": (WELL, CHROMA), + **{f"StatusBarWhite_Battery_Image_{i}": (BATTERY, CHROMA) for i in range(23)}, + "StatusBarWhite_Battery_Image_Charge": (GLYPH, CHROMA), + "StatusBarWhite_Battery_Image_Plug": (GLYPH, CHROMA), + "Media_VideoStatusIcon_Image": (GLYPH, CHROMA), + "Podcasts_video_solo_Image": (GLYPH, CHROMA), + "Media_Genius_Refresh_Image": (GLYPH, CHROMA), + "Media_Genius_Normal_Image": (GLYPH, CAST), + "Playlist_Genius_Icon": (GLYPH, CAST), + "Settings_About_Bubble_Deselected_Image": (GLYPH, CHROMA), + "Media_OTGPlaylist_Image": (PAGE, CHROMA), + "No_Content_iTunesU_Small_Image": (SQUARE, ALL), + "OptionBar_NowPlaying_Thumb_Center_Image": (THUMB, CHROMA), + "OptionBar_NowPlaying_Thumb_LeftCap_Image": (THUMB, CHROMA), + "OptionBar_NowPlaying_Thumb_RightCap_Image": (THUMB, CHROMA), +} + + +def gray(curve, level: int) -> int: + (x0, y0), (x1, y1) = curve + value = y0 + (level - x0) * (y1 - y0) / (x1 - x0) + return round(min(max(value, min(y0, y1)), max(y0, y1))) + + +def target(color: bytes, curve, chroma: int, rgb565: bool) -> bytes | None: + """The replacement for one stock colour, or None to leave it alone.""" + red, green, blue, alpha = color + cast = max(red, green, blue) - min(red, green, blue) + if alpha == 0 or cast >= chroma: + return None + luma = derive.luma(red, green, blue) + if curve is BATTERY: + if alpha < 255 and luma > 0xC0: + return bytes(4) + curve = BATTERY_OUTLINE if cast <= NEUTRAL else BATTERY_BODY + elif curve is TRACK and alpha < 255: + curve = TRACK_REFLECTION + level = gray(curve, luma) + out = bytes((level, level, level, alpha)) + if rgb565: + out = firmware.quantize_565(out) + return None if out == color else out + + +def pairs(entries, stock, name: str): + """The sorted colour pairs of one rule file.""" + index = entries.resolve(name, name) + info = entries.assets[index] + curve, chroma = RULES[name] + rgb565 = derive.is_565(info) + result = [] + for color in firmware.stock_colors(info, stock.bitmap(index)): + out = target(color, curve, chroma, rgb565) + if out is not None: + result.append((color, out)) + result.sort(key=lambda pair: derive.key(pair[0])) + derive.check_recolor(result, info, name) + return result + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--firmware", type=Path, required=True, help="osos.bin") + parser.add_argument("--check", action="store_true", help="compare, write nothing") + args = parser.parse_args(argv) + entries = catalog.load(None) + stock = firmware.Firmware(args.firmware, entries) + stale = [] + for name in sorted(RULES): + path = HERE / "dark" / "apple" / f"{name}.toml" + rules = pairs(entries, stock, name) + text = firmware.recolor_text(rules) + if args.check: + if not path.exists() or path.read_text() != text: + stale.append(path.name) + else: + path.write_text(text) + print(f"{path.name}: {len(rules)} colour pairs") + for name in stale: + print(f"{name}: differs from the table", file=sys.stderr) + return 1 if stale else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/themes/themes/classic/theme.toml b/themes/themes/classic/theme.toml new file mode 100644 index 0000000..852a368 --- /dev/null +++ b/themes/themes/classic/theme.toml @@ -0,0 +1,14 @@ +schema = 1 +id = "classic" +name = "Classic" + +[dark.derive] +"Media_NowPlayingIcon_*Black_Image" = { kind = "invert" } +"No_Content_Albums_Small_Image" = { kind = "alias", source = "Media_AlbumsProxy_Image" } +"No_Content_AudioBooks_Small_Image" = { kind = "alias", source = "Media_AudioBooksProxy_Image" } +"No_Content_MusicVideos_Small_Image" = { kind = "alias", source = "Media_MusicVideosProxy_Image" } +"No_Content_Podcasts_Small_Image" = { kind = "alias", source = "Media_PodcastsProxy_Image" } +"No_Content_TVShows_Small_Image" = { kind = "alias", source = "Media_TVShowsProxy_Image" } +"No_Content_Videos_Small_Image" = { kind = "alias", source = "Media_VideosProxy_Image" } +"NowPlaying_White_Pause_Image" = { kind = "alias", source = "NowPlaying_Black_Pause_Image" } +"NowPlaying_White_Play_Image" = { kind = "alias", source = "NowPlaying_Black_Play_Image" } diff --git a/themes/tools/bitmaps_doc.py b/themes/tools/bitmaps_doc.py new file mode 100644 index 0000000..d4343d2 --- /dev/null +++ b/themes/tools/bitmaps_doc.py @@ -0,0 +1,105 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +"""Write docs/bitmaps.md, the catalog as a page: every bitmap a theme can +replace, grouped by name prefix, with its size, format, palette size and +whether it can be tinted. The "Appears" column is written by hand; the +generator keeps what the committed page says.""" + +import argparse +import re +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) + +from rvt import bitmaps, catalog # noqa: E402 + +PAGE = ROOT / "docs" / "bitmaps.md" +# Prefixes with fewer bitmaps than this share the Other group. +GROUP_MINIMUM = 4 +OTHER = "Other" +ROW = re.compile(r"\| `([^`]+)` \| [^|]* \| [^|]* \| [^|]* \| [^|]* \| ([^|]*) \|") +HEAD = """# Bitmaps + +Every bitmap of Apple's 2.0.5 firmware a theme can replace, from the +[catalog](catalog.md), grouped by name prefix. Size is width x height in +pixels. Palette is the number of native palette entries. Tintable says whether +`[.tint]` may name it. Appears is filled in by hand. + +Regenerate with `python3 tools/bitmaps_doc.py`; the Appears column survives. +""" + + +def group_of(name: str) -> str: + """The name's first word; a leading No_ belongs to the next word.""" + parts = name.split("_", 2) + if parts[0] == "No" and len(parts) > 1: + return "_".join(parts[:2]) + return parts[0] + + +def natural(name: str) -> list: + return [int(part) if part.isdigit() else part for part in re.split(r"(\d+)", name)] + + +def groups(assets: list) -> dict[str, list]: + """Prefix -> bitmaps, small prefixes merged into Other, Other last.""" + by_prefix: dict[str, list] = {} + for asset in assets: + by_prefix.setdefault(group_of(asset["name"]), []).append(asset) + result = {} + other = [] + for prefix in sorted(by_prefix): + if len(by_prefix[prefix]) < GROUP_MINIMUM: + other += by_prefix[prefix] + else: + result[prefix] = by_prefix[prefix] + if other: + result[OTHER] = other + return result + + +def appears_from(text: str) -> dict[str, str]: + """Name -> the Appears cell of an existing page.""" + return {name: cell.strip() for name, cell in ROW.findall(text)} + + +def page(assets: list, appears: dict[str, str]) -> str: + lines = [HEAD] + for group, members in groups(assets).items(): + lines += [ + f"## {group}", + "", + "| Name | Size | Format | Palette | Tintable | Appears |", + "|---|---|---|---|---|---|", + ] + for asset in sorted(members, key=lambda a: natural(a["name"])): + palette = asset["palette_colors"] or "-" + tintable = "yes" if bitmaps.tint_kind(asset["format"]) else "no" + lines.append( + f"| `{asset['name']}` | {asset['width']}x{asset['height']} | " + f"{catalog.FORMAT_NAMES[asset['format']]} | {palette} | {tintable} | " + f"{appears.get(asset['name'], '')} |" + ) + lines.append("") + return "\n".join(lines) + + +def current(path: Path = PAGE) -> str: + """The page as the generator writes it today.""" + assets = catalog.load(None).assets + existing = appears_from(path.read_text()) if path.is_file() else {} + return page(assets, existing) + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--out", type=Path, default=PAGE) + args = parser.parse_args(argv) + args.out.write_text(current(args.out)) + print(f"Wrote {args.out}") + + +if __name__ == "__main__": + main() diff --git a/themes/tools/extension_bitmaps_doc.py b/themes/tools/extension_bitmaps_doc.py new file mode 100644 index 0000000..46075af --- /dev/null +++ b/themes/tools/extension_bitmaps_doc.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +"""Write docs/extension-bitmaps.md: the bitmaps of the first-party extensions +a theme can replace, from the vendored extension asset catalog +rvt/data/extensions.json.""" + +import argparse +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) + +from rvt import assets # noqa: E402 + +PAGE = ROOT / "docs" / "extension-bitmaps.md" +HEAD = """# Extension bitmaps + +The first-party extension bitmaps a theme can replace with +`/extensions//.png`, or `/reprise/.png` +for the core's (id `reprise`). See [Authoring](authoring.md#extension-bitmaps). +Size is width x height in pixels, which the art must match. Menu marks a +Settings icon, a 78 x 121 coverage mask drawn in the icon tint. + +The catalog and how to regenerate it are in +[Catalog](catalog.md#extension-asset-catalog). + +Regenerate this page with `python3 tools/extension_bitmaps_doc.py`. +""" + + +def page(records: dict[tuple[str, str], dict]) -> str: + lines = [ + HEAD, + "| Id | Asset | Size | Format | Palette | Menu |", + "|---|---|---|---|---|---|", + ] + for (identifier, asset), record in sorted(records.items()): + fmt = assets.FORMAT_NAMES.get(record["format"], f"{record['format']:#x}") + lines.append( + f"| `{identifier}` | `{asset}` | {record['width']}x{record['height']} | " + f"{fmt} | {record['palette_colors'] or '-'} | " + f"{'yes' if record['menu'] else 'no'} |" + ) + return "\n".join(lines) + "\n" + + +def current() -> str: + """The page as the generator writes it today.""" + return page(assets.load_catalog()) + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--out", type=Path, default=PAGE) + args = parser.parse_args(argv) + args.out.write_text(current()) + print(f"Wrote {args.out}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/themes/tools/extensions_catalog.py b/themes/tools/extensions_catalog.py new file mode 100644 index 0000000..ef59621 --- /dev/null +++ b/themes/tools/extensions_catalog.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-only +"""Write rvt/data/extensions.json from the `build/assets.json` the extensions +build writes: every record checked, one per line with sorted keys, ordered by +id then asset so that diffs read.""" + +import argparse +import json +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) + +from rvt import assets # noqa: E402 + + +def convert(source: Path) -> str: + records = sorted(assets.read_json(source), key=lambda r: (r["id"], r["asset"])) + seen = set() + for record in records: + key = (record["id"], record["asset"]) + if key in seen: + raise ValueError(f"{source}: {key[0]}/{key[1]} is listed twice") + seen.add(key) + return "".join(json.dumps(record, sort_keys=True) + "\n" for record in records) + + +def main(argv=None) -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument( + "assets", + type=Path, + nargs="?", + default=Path(__file__).resolve().parents[2] / "build" / "assets.json", + help="the extensions build's assets.json (default: ../build/assets.json)", + ) + parser.add_argument("--out", type=Path, default=Path(str(assets.CATALOG))) + args = parser.parse_args(argv) + try: + args.out.write_text(convert(args.assets)) + except (OSError, ValueError) as error: + parser.exit(1, f"{error}\n") + print(f"Wrote {args.out}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/catalog.py b/tools/catalog.py index 4c698d2..a099275 100644 --- a/tools/catalog.py +++ b/tools/catalog.py @@ -162,7 +162,7 @@ def image(filename): entry.update( category=manifest.category(doc), api=doc["api"], - requires=manifest.requires(doc), + requires=manifest.libraries(doc)[0], firmware_id=f"{header['firmware']:08x}", repo=source["repo"], source_path=source.get("path", ""), @@ -359,7 +359,7 @@ def local_manifest(identifier, source): doc = tomllib.loads((folder / "manifest.toml").read_text()) if doc["id"] != identifier or not (folder / "listing.toml").is_file(): raise ValueError(f"{identifier}: expected matching local manifest and listing") - return {"category": manifest.category(doc), "requires": manifest.requires(doc)} + return {"category": manifest.category(doc), "requires": manifest.libraries(doc)[0]} def review(sources, previous, body=None, index=None):