Play your Steam library's Windows games on a jailbroken PS5.
C++
Use a game program's own icon when it has no cover
Leonardo Lobato40ac05055e71
diff --git a/cmake/HomebrewUI.cmake b/cmake/HomebrewUI.cmakeindex d299cf3..a7b4932 100644--- a/cmake/HomebrewUI.cmake+++ b/cmake/HomebrewUI.cmake@@ -257,6 +257,7 @@ target_link_libraries(playden_homebrew_runtime_host PUBLIC playden_native_coordiadd_library(playden_homebrew_artwork STATIC"${CMAKE_SOURCE_DIR}/src/homebrew/artwork.cpp""${CMAKE_SOURCE_DIR}/src/homebrew/artwork_backend.cpp"+ "${CMAKE_SOURCE_DIR}/src/homebrew/program_icon.cpp""${CMAKE_SOURCE_DIR}/src/homebrew/title_icon.cpp")target_compile_features(playden_homebrew_artwork PUBLIC cxx_std_20)target_include_directories(playden_homebrew_artwork PUBLIC "${CMAKE_SOURCE_DIR}/src"@@ -463,6 +464,13 @@ if(BUILD_TESTING)target_include_directories(homebrew_title_icon_test PRIVATE "${PLAYDEN_STB_IMAGE_INCLUDE_DIR}")target_link_libraries(homebrew_title_icon_test PRIVATE playden_homebrew_artwork)add_test(NAME homebrew_title_icon COMMAND homebrew_title_icon_test)++ add_executable(homebrew_program_icon_test "${CMAKE_SOURCE_DIR}/tests/homebrew_program_icon_test.cpp")+ target_compile_features(homebrew_program_icon_test PRIVATE cxx_std_20)+ target_include_directories(homebrew_program_icon_test PRIVATE "${PLAYDEN_STB_IMAGE_INCLUDE_DIR}"+ "${CMAKE_SOURCE_DIR}/third_party/ps5-homebrew-ui/third_party/stb")+ target_link_libraries(homebrew_program_icon_test PRIVATE playden_homebrew_artwork)+ add_test(NAME homebrew_program_icon COMMAND homebrew_program_icon_test)add_executable(homebrew_controller_tour_test "${CMAKE_SOURCE_DIR}/tests/homebrew_controller_tour_test.cpp")target_compile_features(homebrew_controller_tour_test PRIVATE cxx_std_20)target_link_libraries(homebrew_controller_tour_test PRIVATE playden_homebrew_model)diff --git a/src/homebrew/artwork_cache.cpp b/src/homebrew/artwork_cache.cppindex 91959af..0b04558 100644--- a/src/homebrew/artwork_cache.cpp+++ b/src/homebrew/artwork_cache.cpp@@ -148,6 +148,15 @@ std::uint32_t LiveArtworkCache::TextureFor(GameId game_id, std::string_view sourreturn entry->texture;}+bool LiveArtworkCache::Failed(GameId game_id, std::string_view source) const {+ const auto& state = *state_;+ if (state.generation == 0) return false;+ for (const auto& entry : state.entries)+ if (entry.key.account_generation == state.generation && entry.key.game_id == game_id && entry.key.source == source)+ return entry.failed && entry.texture == 0;+ return false;+}+void LiveArtworkCache::EndFrame() {auto& state = *state_;state.entries.erase(std::remove_if(state.entries.begin(), state.entries.end(), [&state](const auto& entry) {diff --git a/src/homebrew/artwork_cache.hpp b/src/homebrew/artwork_cache.hppindex c0704ff..02f5d65 100644--- a/src/homebrew/artwork_cache.hpp+++ b/src/homebrew/artwork_cache.hpp@@ -41,6 +41,8 @@ class LiveArtworkCache {[[nodiscard]] std::uint32_t TextureFor(GameId, std::string_view source,std::uint32_t* width = nullptr,std::uint32_t* height = nullptr);+ // Its load failed (it may still be retried): the caller can show something else meanwhile.+ [[nodiscard]] bool Failed(GameId, std::string_view source) const;void EndFrame();[[nodiscard]] ArtworkCacheStats Stats() const noexcept;diff --git a/src/homebrew/controller.cpp b/src/homebrew/controller.cppindex 7ec2f63..bdced6e 100644--- a/src/homebrew/controller.cpp+++ b/src/homebrew/controller.cpp@@ -1,4 +1,5 @@#include "homebrew/controller.hpp"+#include "homebrew/program_icon.hpp"#include "diagnostics/redaction.h"#include "steam/install_volumes.h"#include "steam/secret.h"@@ -1452,6 +1453,10 @@ void Controller::TickRuntime() {game.runtime_current = record->runtime_current;game.save_backups = record->save_backups;game.latest_save_backup = record->latest_save_backup;+ if (auto program = record->launch_path; !program.empty() && !record->install_path.empty()) {+ std::replace(program.begin(), program.end(), '\\', '/');+ game.program_icon = ProgramIconSource(record->install_path + "/" + program);+ }}if (const auto answer = snapshot.activity.find(NumberIn(snapshot, id)); answer != snapshot.activity.end())game.activity = answer->second.first == runtime::NativeActivity::kStopped ? TitleActivity::Stoppeddiff --git a/src/homebrew/host.cpp b/src/homebrew/host.cppindex 23ccc04..bea769e 100644--- a/src/homebrew/host.cpp+++ b/src/homebrew/host.cpp@@ -4,6 +4,7 @@#include "homebrew/render.hpp"#include "homebrew/artwork_backend.hpp"+#include "homebrew/program_icon.hpp"#include "homebrew/simulation.hpp"#include "homebrew/controller.hpp"#include "steam/install_volumes.h"@@ -475,6 +476,7 @@ int main(int argc, char** argv) {std::unique_ptr<playden::stores::Registry> stores; // declared first: the controller uses itstd::unique_ptr<playden::homebrew::Controller> services;std::unique_ptr<playden::homebrew::HttpArtworkBackend> artwork_backend;+ std::unique_ptr<playden::homebrew::ProgramIconArtworkBackend> program_icons;std::unique_ptr<playden::homebrew::ArtworkService> artwork;if (!options->scenario.empty() && !simulation.scenario(options->scenario)) {std::fprintf(stderr, "%s\n", simulation.last_error().c_str());@@ -759,7 +761,8 @@ int main(int argc, char** argv) {if (!options->simulation) {const std::string art_cache_dir = (options->data_directory / "art").string();artwork_backend = std::make_unique<playden::homebrew::HttpArtworkBackend>(PLAYDEN_HOMEBREW_CA_BUNDLE, art_cache_dir);- artwork = std::make_unique<playden::homebrew::ArtworkService>(*artwork_backend);+ program_icons = std::make_unique<playden::homebrew::ProgramIconArtworkBackend>(*artwork_backend);+ artwork = std::make_unique<playden::homebrew::ArtworkService>(*program_icons);}auto render = std::make_unique<playden::homebrew::Render>(PLAYDEN_HOMEBREW_ASSETS_DIR, artwork.get());if (!options->capture.empty() && options->recording.empty()) {diff --git a/src/homebrew/program_icon.cpp b/src/homebrew/program_icon.cppnew file mode 100644index 0000000..6327e48--- /dev/null+++ b/src/homebrew/program_icon.cpp@@ -0,0 +1,330 @@+// program_icon.cpp - A Windows program's own icon, read from its PE resources.+// Copyright (c) 2026 Playden contributors+// SPDX-License-Identifier: GPL-3.0-or-later+#include "homebrew/program_icon.hpp"++#include "homebrew/artwork_backend.hpp"++#include <algorithm>+#include <cstring>+#include <string_view>+#include <utility>+#include <vector>++#include <fcntl.h>+#include <sys/stat.h>+#include <unistd.h>++namespace playden::homebrew {+namespace {++constexpr std::uint32_t kGroupIconType = 14; // RT_GROUP_ICON+constexpr std::uint32_t kIconType = 3; // RT_ICON+constexpr std::size_t kMaxDirectoryEntries = 512;+constexpr std::size_t kMaxGroupBytes = 64 * 1024;+constexpr std::size_t kMaxSections = 96;+constexpr std::size_t kMaxIconAttempts = 8;++std::uint16_t U16(const unsigned char* p) { return static_cast<std::uint16_t>(p[0] | (p[1] << 8)); }+std::uint32_t U32(const unsigned char* p) {+ return static_cast<std::uint32_t>(p[0]) | (static_cast<std::uint32_t>(p[1]) << 8) |+ (static_cast<std::uint32_t>(p[2]) << 16) | (static_cast<std::uint32_t>(p[3]) << 24);+}++// An absolute path none of whose components is a symbolic link (the game's folder could point elsewhere).+bool NoLinks(const std::string& path) {+ if (path.empty() || path.front() != '/') return false;+ for (std::size_t end = path.find('/', 1);; end = path.find('/', end + 1)) {+ struct stat info {};+ if (::lstat(path.substr(0, end).c_str(), &info) != 0 || S_ISLNK(info.st_mode)) return false;+ if (end == std::string::npos) return true;+ }+}++// Reads at file offsets, never past the end. Opened without blocking, so a FIFO in its place can't stall.+class File {+ public:+ explicit File(const std::string& path)+ : fd_(NoLinks(path) ? ::open(path.c_str(), O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC) : -1) {+ struct stat info {};+ if (fd_ >= 0 && (::fstat(fd_, &info) != 0 || !S_ISREG(info.st_mode))) Close();+ if (fd_ >= 0) size_ = static_cast<std::uint64_t>(info.st_size);+ }+ ~File() { Close(); }+ File(const File&) = delete;+ File& operator=(const File&) = delete;++ bool Read(std::uint64_t offset, void* out, std::size_t count) const {+ if (fd_ < 0 || offset > size_ || count > size_ - offset) return false;+ auto* bytes = static_cast<unsigned char*>(out);+ for (std::size_t done = 0; done < count;) {+ const auto got = ::pread(fd_, bytes + done, count - done, static_cast<off_t>(offset + done));+ if (got <= 0) return false;+ done += static_cast<std::size_t>(got);+ }+ return true;+ }++ private:+ void Close() {+ if (fd_ >= 0) ::close(fd_);+ fd_ = -1;+ }+ int fd_ = -1;+ std::uint64_t size_ = 0;+};++struct Section {+ std::uint32_t address = 0, raw_size = 0, raw_offset = 0;+};++// The file offset of `count` bytes at an address relative to the image, inside one section's file data.+std::optional<std::uint64_t> FileOffset(const std::vector<Section>& sections, std::uint32_t rva, std::uint32_t count) {+ for (const auto& s : sections) {+ if (rva < s.address) continue;+ const std::uint64_t into = rva - s.address;+ if (into + count > s.raw_size) continue;+ return static_cast<std::uint64_t>(s.raw_offset) + into;+ }+ return std::nullopt;+}++struct Resources {+ const File& file;+ std::vector<Section> sections;+ std::uint32_t root = 0; // the resource directory's address+ std::uint32_t size = 0;++ struct Entry {+ bool named = false;+ std::uint32_t id = 0;+ bool directory = false;+ std::uint32_t offset = 0; // from the resource directory's start+ };++ // A directory's entries (named ones first, as Windows orders them), or nothing when it doesn't fit.+ std::optional<std::vector<Entry>> Directory(std::uint32_t offset) const {+ unsigned char head[16];+ if (offset > size || size - offset < sizeof(head)) return std::nullopt;+ const auto at = FileOffset(sections, root + offset, sizeof(head));+ if (!at || !file.Read(*at, head, sizeof(head))) return std::nullopt;+ const std::size_t count = static_cast<std::size_t>(U16(head + 12)) + U16(head + 14);+ if (count > kMaxDirectoryEntries || (size - offset - sizeof(head)) / 8 < count) return std::nullopt;+ std::vector<unsigned char> rows(count * 8);+ const auto rows_at = FileOffset(sections, root + offset + 16, static_cast<std::uint32_t>(rows.size()));+ if (count && (!rows_at || !file.Read(*rows_at, rows.data(), rows.size()))) return std::nullopt;+ std::vector<Entry> entries;+ for (std::size_t i = 0; i < count; ++i) {+ const std::uint32_t name = U32(&rows[i * 8]), data = U32(&rows[i * 8 + 4]);+ entries.push_back({(name & 0x80000000u) != 0, name & 0x7fffffffu, (data & 0x80000000u) != 0, data & 0x7fffffffu});+ }+ return entries;+ }++ // The data of a type's resource (`id`, or the first one when nothing is named), in its first language.+ std::optional<std::vector<unsigned char>> Data(std::uint32_t type, std::optional<std::uint32_t> id,+ std::size_t limit) const {+ const auto types = Directory(0);+ if (!types) return std::nullopt;+ const auto type_entry = std::find_if(types->begin(), types->end(), [&](const Entry& entry) {+ return !entry.named && entry.id == type && entry.directory;+ });+ if (type_entry == types->end()) return std::nullopt;+ const auto names = Directory(type_entry->offset);+ if (!names) return std::nullopt;+ const auto name_entry = std::find_if(names->begin(), names->end(), [&](const Entry& entry) {+ return entry.directory && (!id || (!entry.named && entry.id == *id));+ });+ if (name_entry == names->end()) return std::nullopt;+ const auto languages = Directory(name_entry->offset);+ if (!languages || languages->empty() || languages->front().directory) return std::nullopt;+ // A data entry: the data's address relative to the image, then its size.+ const auto leaf = languages->front().offset;+ unsigned char row[8];+ if (leaf > size || size - leaf < sizeof(row)) return std::nullopt;+ const auto row_at = FileOffset(sections, root + leaf, sizeof(row));+ if (!row_at || !file.Read(*row_at, row, sizeof(row))) return std::nullopt;+ const std::uint32_t data_rva = U32(row), data_size = U32(row + 4);+ if (data_size == 0 || data_size > limit) return std::nullopt;+ const auto data_at = FileOffset(sections, data_rva, data_size);+ std::vector<unsigned char> bytes(data_size);+ if (!data_at || !file.Read(*data_at, bytes.data(), bytes.size())) return std::nullopt;+ return bytes;+ }+};++std::optional<Resources> OpenResources(const File& file) {+ unsigned char dos[64];+ if (!file.Read(0, dos, sizeof(dos)) || dos[0] != 'M' || dos[1] != 'Z') return std::nullopt;+ const std::uint32_t pe = U32(dos + 0x3c);+ unsigned char header[24];+ if (!file.Read(pe, header, sizeof(header)) || std::memcmp(header, "PE\0\0", 4) != 0) return std::nullopt;+ const std::uint16_t section_count = U16(header + 6), optional_size = U16(header + 20);+ if (section_count == 0 || section_count > kMaxSections || optional_size < 2) return std::nullopt;+ std::vector<unsigned char> optional(optional_size);+ if (!file.Read(pe + 24ull, optional.data(), optional.size())) return std::nullopt;+ const std::uint16_t magic = U16(optional.data());+ const std::size_t counted = magic == 0x10b ? 92 : magic == 0x20b ? 108 : 0;+ if (counted == 0 || optional.size() < counted + 4 || U32(&optional[counted]) < 3) return std::nullopt;+ const std::size_t resource_directory = counted + 4 + 2 * 8;+ if (optional.size() < resource_directory + 8) return std::nullopt;+ Resources resources{file, {}, U32(&optional[resource_directory]), U32(&optional[resource_directory + 4])};+ if (resources.root == 0 || resources.size < 16 || resources.root > 0xffffffffu - resources.size) return std::nullopt;+ std::vector<unsigned char> table(section_count * 40u);+ if (!file.Read(pe + 24ull + optional_size, table.data(), table.size())) return std::nullopt;+ for (std::size_t i = 0; i < section_count; ++i) {+ const auto* row = &table[i * 40];+ resources.sections.push_back({U32(row + 12), U32(row + 16), U32(row + 20)});+ }+ return resources;+}++// A BMP icon image: a BITMAPINFOHEADER, the palette, the colour rows, then a 1-bit transparency mask,+// both bottom-up, with a height counting the two.+std::optional<ArtworkImage> DecodeDib(const std::vector<unsigned char>& bytes) {+ if (bytes.size() < 40) return std::nullopt;+ const std::uint32_t header = U32(bytes.data());+ const auto width = static_cast<std::int32_t>(U32(bytes.data() + 4));+ const auto double_height = static_cast<std::int32_t>(U32(bytes.data() + 8));+ const std::uint16_t bits = U16(bytes.data() + 14);+ const std::uint32_t compression = U32(bytes.data() + 16);+ const std::uint32_t used = U32(bytes.data() + 32);+ if (header < 40 || header > bytes.size() || width <= 0 || double_height <= 0 || double_height % 2 != 0 ||+ static_cast<std::uint32_t>(width) > kMaxProgramIconSide ||+ static_cast<std::uint32_t>(double_height / 2) > kMaxProgramIconSide)+ return std::nullopt;+ // 32-bit icons may say BI_BITFIELDS with the usual BGRA layout.+ if (compression != 0 && !(compression == 3 && bits == 32)) return std::nullopt;+ if (bits != 1 && bits != 4 && bits != 8 && bits != 24 && bits != 32) return std::nullopt;+ const std::uint32_t w = static_cast<std::uint32_t>(width), h = static_cast<std::uint32_t>(double_height / 2);+ const std::size_t colours = bits <= 8 ? (used != 0 && used <= (1u << bits) ? used : (1u << bits)) : 0;+ const std::size_t masks = compression == 3 && header == 40 ? 12 : 0;+ const std::size_t palette = header + masks;+ const std::size_t stride = ((static_cast<std::size_t>(w) * bits + 31) / 32) * 4;+ const std::size_t mask_stride = ((w + 31) / 32) * 4;+ const std::size_t pixels = palette + colours * 4;+ if (pixels > bytes.size() || (bytes.size() - pixels) / stride < h) return std::nullopt;+ const std::size_t mask = pixels + stride * h;+ const bool has_mask = bytes.size() >= mask && (bytes.size() - mask) / mask_stride >= h;+ ArtworkImage image;+ image.width = w;+ image.height = h;+ image.rgba.resize(static_cast<std::size_t>(w) * h * 4);+ bool any_alpha = false;+ for (std::uint32_t y = 0; y < h; ++y) {+ const auto* row = &bytes[pixels + (h - 1 - y) * stride];+ auto* out = &image.rgba[static_cast<std::size_t>(y) * w * 4];+ for (std::uint32_t x = 0; x < w; ++x, out += 4) {+ const unsigned char* bgr = nullptr;+ unsigned char alpha = 255;+ if (bits == 32) {+ bgr = row + x * 4;+ alpha = bgr[3];+ any_alpha = any_alpha || alpha != 0;+ } else if (bits == 24) {+ bgr = row + x * 3;+ } else {+ const std::size_t bit = static_cast<std::size_t>(x) * bits;+ const unsigned index = (row[bit / 8] >> (8 - bits - bit % 8)) & ((1u << bits) - 1);+ if (index >= colours) return std::nullopt;+ bgr = &bytes[palette + index * 4];+ }+ out[0] = bgr[2];+ out[1] = bgr[1];+ out[2] = bgr[0];+ out[3] = alpha;+ }+ }+ // Without alpha in its colours (an older 32-bit icon too), the mask says what is transparent.+ if (bits == 32 && any_alpha) return image;+ for (std::uint32_t y = 0; y < h; ++y) {+ const auto* row = has_mask ? &bytes[mask + (h - 1 - y) * mask_stride] : nullptr;+ for (std::uint32_t x = 0; x < w; ++x)+ image.rgba[(static_cast<std::size_t>(y) * w + x) * 4 + 3] =+ row && (row[x / 8] >> (7 - x % 8)) & 1 ? 0 : 255;+ }+ return image;+}++} // namespace++std::optional<ArtworkImage> ReadProgramIcon(const std::string& path) {+ File file(path);+ const auto resources = OpenResources(file);+ if (!resources) return std::nullopt;+ // GRPICONDIR: reserved, type 1, count, then 14-byte entries (width, height, colours, reserved, planes,+ // bits, bytes, the RT_ICON id); a width or height of 0 means 256.+ const auto group = resources->Data(kGroupIconType, std::nullopt, kMaxGroupBytes);+ if (!group || group->size() < 6 || U16(group->data() + 2) != 1) return std::nullopt;+ struct Choice {+ std::uint32_t area = 0, bits = 0, id = 0;+ };+ std::vector<Choice> choices;+ const std::size_t count = std::min<std::size_t>(U16(group->data() + 4), (group->size() - 6) / 14);+ for (std::size_t i = 0; i < count; ++i) {+ const auto* row = group->data() + 6 + i * 14;+ const std::uint32_t width = row[0] ? row[0] : 256, height = row[1] ? row[1] : 256;+ choices.push_back({width * height, U16(row + 6), U16(row + 12)});+ }+ std::stable_sort(choices.begin(), choices.end(), [](const Choice& a, const Choice& b) {+ return a.area != b.area ? a.area > b.area : a.bits > b.bits;+ });+ // The largest that decodes: a malformed image falls back to the next one, a few times at most.+ std::vector<std::uint32_t> tried;+ for (const auto& choice : choices) {+ if (tried.size() >= kMaxIconAttempts) break;+ if (std::find(tried.begin(), tried.end(), choice.id) != tried.end()) continue;+ tried.push_back(choice.id);+ const auto bytes = resources->Data(kIconType, choice.id, kMaxProgramIconBytes);+ if (!bytes) continue;+ static constexpr unsigned char kPng[] = {0x89, 'P', 'N', 'G', '\r', '\n', 0x1a, '\n'};+ std::optional<ArtworkImage> image;+ if (bytes->size() >= sizeof(kPng) && std::memcmp(bytes->data(), kPng, sizeof(kPng)) == 0) {+ // The size from its IHDR chunk first, so an oversized image is never decoded.+ const auto big_endian = [&](std::size_t at) {+ return (std::uint32_t{(*bytes)[at]} << 24) | (std::uint32_t{(*bytes)[at + 1]} << 16) |+ (std::uint32_t{(*bytes)[at + 2]} << 8) | (*bytes)[at + 3];+ };+ if (bytes->size() < 24 || std::memcmp(bytes->data() + 12, "IHDR", 4) != 0 || big_endian(16) == 0 ||+ big_endian(16) > kMaxProgramIconSide || big_endian(20) == 0 || big_endian(20) > kMaxProgramIconSide)+ continue;+ image = DecodeArtwork(std::vector<std::uint8_t>(bytes->begin(), bytes->end()));+ } else {+ image = DecodeDib(*bytes);+ }+ if (image && image->width <= kMaxProgramIconSide && image->height <= kMaxProgramIconSide) return image;+ }+ return std::nullopt;+}++std::optional<std::string> ProgramIconPath(const std::string& source) {+ const std::size_t prefix = std::strlen(kProgramIconScheme);+ if (source.size() <= prefix || source.compare(0, prefix, kProgramIconScheme) != 0) return std::nullopt;+ auto path = source.substr(prefix);+ // An absolute path to a .exe, with no "." or ".." component.+ if (path.front() != '/' || path.find('\0') != std::string::npos || path.size() < 5) return std::nullopt;+ std::string extension = path.substr(path.size() - 4);+ for (char& c : extension) c = static_cast<char>(c >= 'A' && c <= 'Z' ? c - 'A' + 'a' : c);+ if (extension != ".exe") return std::nullopt;+ for (std::size_t start = 1; start <= path.size();) {+ const auto end = std::min(path.find('/', start), path.size());+ const auto part = std::string_view(path).substr(start, end - start);+ if (part.empty() || part == "." || part == "..") return std::nullopt;+ start = end + 1;+ }+ return path;+}++ProgramIconArtworkBackend::ProgramIconArtworkBackend(ArtworkBackend& next, std::string host_prefix)+ : next_(next), host_prefix_(std::move(host_prefix)) {+ while (!host_prefix_.empty() && host_prefix_.back() == '/') host_prefix_.pop_back();+}++std::optional<ArtworkImage> ProgramIconArtworkBackend::Load(const ArtworkKey& key, const std::atomic<bool>& cancel) {+ const auto path = ProgramIconPath(key.source);+ if (!path) return next_.Load(key, cancel);+ if (cancel.load(std::memory_order_acquire)) return std::nullopt;+ return ReadProgramIcon(host_prefix_ + *path);+}++} // namespace playden::homebrewdiff --git a/src/homebrew/program_icon.hpp b/src/homebrew/program_icon.hppnew file mode 100644index 0000000..bfcafcc--- /dev/null+++ b/src/homebrew/program_icon.hpp@@ -0,0 +1,44 @@+#pragma once+// program_icon.hpp - A Windows program's own icon, read from its PE resources.+// Copyright (c) 2026 Playden contributors+// SPDX-License-Identifier: GPL-3.0-or-later+#include "homebrew/artwork.hpp"++#include <atomic>+#include <cstddef>+#include <cstdint>+#include <optional>+#include <string>++namespace playden::homebrew {++// Bounds for a program's icon: one image's bytes and its side in pixels.+inline constexpr std::size_t kMaxProgramIconBytes = 1024 * 1024;+inline constexpr std::uint32_t kMaxProgramIconSide = 512;++// The largest image of the program's first icon group (RT_GROUP_ICON), as Explorer shows it, decoded to+// RGBA: PNG or a BMP (1, 4, 8, 24 or 32 bits, with its transparency mask). Nothing for a file that isn't+// a Windows program, has no icon, or is malformed; reads are bounded and never follow a symbolic link.+std::optional<ArtworkImage> ReadProgramIcon(const std::string& path);++// The program-icon source of the UI's artwork (homebrew/artwork.hpp): the program's console path behind+// a prefix no store URL has. ProgramIconPath gives the path back, or nothing for any other source.+inline constexpr const char* kProgramIconScheme = "program-icon:";+inline std::string ProgramIconSource(const std::string& console_path) {+ return console_path.empty() ? std::string() : kProgramIconScheme + console_path;+}+std::optional<std::string> ProgramIconPath(const std::string& source);++// Loads program-icon sources from the game's files (a console path under `host_prefix` on the desktop+// build) and passes every other source to `next`. Both outlive it.+class ProgramIconArtworkBackend final : public ArtworkBackend {+ public:+ ProgramIconArtworkBackend(ArtworkBackend& next, std::string host_prefix = "");+ std::optional<ArtworkImage> Load(const ArtworkKey&, const std::atomic<bool>& cancel) override;++ private:+ ArtworkBackend& next_;+ std::string host_prefix_;+};++} // namespace playden::homebrewdiff --git a/src/homebrew/ps5.cpp b/src/homebrew/ps5.cppindex eeaac79..c127383 100644--- a/src/homebrew/ps5.cpp+++ b/src/homebrew/ps5.cpp@@ -19,6 +19,7 @@#include "runtime/settings_storage.h"#include "runtime/writable_folders.h"#include "homebrew/runtime_host.hpp"+#include "homebrew/program_icon.hpp"#include "homebrew/title_icon.hpp"#include "platform/ps5/title_allow_list.h"#include "platform/ps5/console_address.h"@@ -559,8 +560,8 @@ int main() {std::fclose(file);}};- // The game's PS5 title icon, from its Steam cover; without one, the packaged- // generic icon. Only a missing generic icon leaves the kit's.+ // The game's PS5 title icon, from its Steam cover; without one, its program's own+ // icon, then the packaged generic icon. Only a missing generic icon leaves the kit's.std::optional<std::string> generic_icon;if (FILE* file = std::fopen((paths.assets_root + "/generic-title-icon.png").c_str(), "rb")) {std::string bytes;@@ -579,7 +580,8 @@ int main() {if (grant->apps.count(dlc)) owned.push_back(dlc);return owned;};- config.title_icon = [trust = paths.trust_store, art_cache_dir, generic_icon](const playden::GameId& game) -> std::optional<std::string> {+ config.title_icon = [trust = paths.trust_store, art_cache_dir, generic_icon](+ const playden::GameId& game, const std::filesystem::path& program) -> std::optional<std::string> {// A store with no cover for the game (an imported one) gets the generic icon.const auto source = playden::homebrew::CoverUrl(game);std::optional<playden::homebrew::ArtworkImage> cover;@@ -589,8 +591,16 @@ int main() {cover = backend.Load({1, game, source}, cancel);}if (auto icon = cover ? playden::homebrew::MakeTitleIcon(*cover) : std::nullopt) return icon;+ // An imported game, or a Steam game without a cover: the icon inside its program.+ const auto own = program.empty() ? std::nullopt : playden::homebrew::ReadProgramIcon(program.string());+ if (auto icon = own ? playden::homebrew::MakeProgramTitleIcon(*own) : std::nullopt) {+ playden::app::AppendLogLine(log_root, "runtime.log", "title icon app=" + playden::ToKey(game) ++ " uses the program's icon: no cover program=" + program.filename().string());+ return icon;+ }playden::app::AppendLogLine(log_root, "runtime.log", "title icon app=" + playden::ToKey(game) +- (generic_icon ? " uses the generic icon: no cover" : " has no cover or generic icon"));+ (generic_icon ? " uses the generic icon: no cover or program icon"+ : " has no cover, program icon or generic icon"));return generic_icon;};// What Playden downloads for a game's bottle (Microsoft's Visual C++ redistributable, for games that need@@ -901,7 +911,9 @@ int main() {playden::homebrew::Render renderer(paths.assets_root);#elseplayden::homebrew::HttpArtworkBackend artwork_backend(paths.trust_store, art_cache_dir);- playden::homebrew::ArtworkService artwork(artwork_backend);+ // Games without store art show the icon inside their program, read from the game's files.+ playden::homebrew::ProgramIconArtworkBackend program_icons(artwork_backend);+ playden::homebrew::ArtworkService artwork(program_icons);playden::homebrew::Render renderer(paths.assets_root, &artwork);#endifhui::ps5::Pad pad;diff --git a/src/homebrew/runtime_host.cpp b/src/homebrew/runtime_host.cppindex cc80c29..e51cfec 100644--- a/src/homebrew/runtime_host.cpp+++ b/src/homebrew/runtime_host.cpp@@ -2678,7 +2678,12 @@ rt::PackageActionResult RuntimeHost::WriteTitleMetadata(Composition& c, const rtconst std::string name = title_name.empty() ? "Steam game " + std::to_string(record.runtime_number) : title_name;if (!replace_value("titleName", JsonEscaped(name)))Log("title metadata app=" + std::to_string(record.runtime_number) + " keeps the kit's name: unexpected layout");- const auto icon = config_.title_icon ? config_.title_icon(GameOf(record)) : std::nullopt;+ std::filesystem::path program;+ if (auto launch = record.launch_path; !launch.empty() && !record.install_path.empty()) {+ std::replace(launch.begin(), launch.end(), '\\', '/');+ program = HostPath(record.install_path) / launch;+ }+ const auto icon = config_.title_icon ? config_.title_icon(GameOf(record), program) : std::nullopt;Log("title metadata app=" + std::to_string(record.runtime_number) + " name=" + name + " icon=" +(icon ? std::to_string(icon->size()) + "B" : std::string("kit")));return c.installer->WriteTitleMetadata(record, param, icon);diff --git a/src/homebrew/runtime_host.hpp b/src/homebrew/runtime_host.hppindex d19d869..2645a2b 100644--- a/src/homebrew/runtime_host.hpp+++ b/src/homebrew/runtime_host.hpp@@ -110,10 +110,11 @@ struct RuntimeHostConfig {// startup. The wrapper writes it inside the private bottle tree, which only// the app user can read.std::function<void(const std::string& title_id, const std::string& text)> title_log;- // The game's PS5 title icon: a 512x512 PNG made from its store artwork, or- // nothing (the kit's icon stays). Runs on the worker; may use the network.- // Named by the game, so a runtime number never reaches a store's artwork.- std::function<std::optional<std::string>(const GameId& game)> title_icon;+ // The game's PS5 title icon: a 512x512 PNG made from its store artwork, else from+ // the icon of `program` (the program the title starts, a host path; empty when+ // unknown), or nothing (the kit's icon stays). Runs on the worker; may use the+ // network. Named by the game, so a runtime number never reaches a store's artwork.+ std::function<std::optional<std::string>(const GameId& game, const std::filesystem::path& program)> title_icon;// The DLC of a Steam game this account owns, from the Library's license read and app lookups// (EntitledLibraryBackend::DlcOf). Each prepare adds them to what the download recorded, so DLC past// the 64 that Steam's listofdlc names, or bought after the download, reach the emulator. Empty: none.diff --git a/src/homebrew/simulation.hpp b/src/homebrew/simulation.hppindex c79afb3..a3efc03 100644--- a/src/homebrew/simulation.hpp+++ b/src/homebrew/simulation.hpp@@ -262,6 +262,9 @@ struct LiveRuntimeGame {// came from the game's own steam_appid.txt (which wins over the one in Game settings).std::uint32_t steam_app_id = 0;bool steam_app_from_game_file = false;+ // The artwork source of the icon inside the program its title starts (homebrew/program_icon.hpp), shown+ // where the game has no cover art; empty before it is prepared.+ std::string program_icon;};// A preparation that ended Ready, listed in Queue after the waiting games.struct LiveCompletedPreparation {diff --git a/src/homebrew/title_icon.cpp b/src/homebrew/title_icon.cppindex dc9c139..15c9a0c 100644--- a/src/homebrew/title_icon.cpp+++ b/src/homebrew/title_icon.cpp@@ -4,6 +4,7 @@#include "homebrew/title_icon.hpp"#include <algorithm>+#include <cmath>#include <cstdint>#include <vector>@@ -49,4 +50,47 @@ std::optional<std::string> MakeTitleIcon(const ArtworkImage& cover) {return png;}+std::optional<ArtworkImage> ProgramIconTile(const ArtworkImage& icon, std::uint32_t side) {+ if (icon.width == 0 || icon.height == 0 || side == 0 || side > kMaxArtworkDimension ||+ icon.rgba.size() != static_cast<std::size_t>(icon.width) * icon.height * 4)+ return std::nullopt;+ // The UI's placeholder tile colour, so the icon sits on the same dark ground.+ constexpr std::uint8_t kGround[3] = {0x24, 0x20, 0x1d};+ ArtworkImage tile;+ tile.width = tile.height = side;+ tile.rgba.resize(static_cast<std::size_t>(side) * side * 4);+ for (std::size_t i = 0; i < tile.rgba.size(); i += 4)+ tile.rgba[i] = kGround[0], tile.rgba[i + 1] = kGround[1], tile.rgba[i + 2] = kGround[2], tile.rgba[i + 3] = 255;+ // Two thirds of the tile, keeping the icon's shape; bilinear, on alpha-weighted colours.+ const double scale = side * 2.0 / 3.0 / std::max(icon.width, icon.height);+ const auto box_w = static_cast<std::uint32_t>(std::max(1.0, icon.width * scale));+ const auto box_h = static_cast<std::uint32_t>(std::max(1.0, icon.height * scale));+ const std::uint32_t left = (side - box_w) / 2, top = (side - box_h) / 2;+ const auto at = [&](std::uint32_t x, std::uint32_t y) { return &icon.rgba[(static_cast<std::size_t>(y) * icon.width + x) * 4]; };+ for (std::uint32_t y = 0; y < box_h; ++y)+ for (std::uint32_t x = 0; x < box_w; ++x) {+ const double sx = std::clamp((x + 0.5) / scale - 0.5, 0.0, icon.width - 1.0);+ const double sy = std::clamp((y + 0.5) / scale - 0.5, 0.0, icon.height - 1.0);+ const auto x0 = static_cast<std::uint32_t>(sx), y0 = static_cast<std::uint32_t>(sy);+ const std::uint32_t x1 = std::min(x0 + 1, icon.width - 1), y1 = std::min(y0 + 1, icon.height - 1);+ const double fx = sx - x0, fy = sy - y0;+ const std::uint8_t* corners[4] = {at(x0, y0), at(x1, y0), at(x0, y1), at(x1, y1)};+ const double weights[4] = {(1 - fx) * (1 - fy), fx * (1 - fy), (1 - fx) * fy, fx * fy};+ double colour[3] = {0, 0, 0}, alpha = 0;+ for (int c = 0; c < 4; ++c) {+ const double a = weights[c] * corners[c][3] / 255.0;+ alpha += a;+ for (int k = 0; k < 3; ++k) colour[k] += a * corners[c][k];+ }+ auto* out = &tile.rgba[(static_cast<std::size_t>(top + y) * side + left + x) * 4];+ for (int k = 0; k < 3; ++k) out[k] = static_cast<std::uint8_t>(std::lround(colour[k] + (1 - alpha) * out[k]));+ }+ return tile;+}++std::optional<std::string> MakeProgramTitleIcon(const ArtworkImage& icon) {+ const auto tile = ProgramIconTile(icon, kTitleIconSize);+ return tile ? MakeTitleIcon(*tile) : std::nullopt;+}+} // namespace playden::homebrewdiff --git a/src/homebrew/title_icon.hpp b/src/homebrew/title_icon.hppindex ace1ef0..df421d2 100644--- a/src/homebrew/title_icon.hpp+++ b/src/homebrew/title_icon.hpp@@ -1,5 +1,5 @@#pragma once-// title_icon.hpp - A game's PS5 title icon from its store cover art.+// title_icon.hpp - A game's PS5 title icon from its store cover art, or its program's icon.// Copyright (c) 2026 Playden contributors// SPDX-License-Identifier: MIT#include "homebrew/artwork.hpp"@@ -15,4 +15,10 @@ inline constexpr std::uint32_t kTitleIconSize = 512;// encoded as an opaque RGB PNG. Nothing for an empty or malformed image.std::optional<std::string> MakeTitleIcon(const ArtworkImage& cover);+// A game without cover art: its program's own icon (homebrew/program_icon.hpp), scaled to fill+// two thirds of a dark 512x512 tile and centred, encoded as MakeTitleIcon does.+std::optional<std::string> MakeProgramTitleIcon(const ArtworkImage& icon);+// The same tile as an image, for the UI's artwork.+std::optional<ArtworkImage> ProgramIconTile(const ArtworkImage& icon, std::uint32_t side);+} // namespace playden::homebrewdiff --git a/src/homebrew/view.cpp b/src/homebrew/view.cppindex 55b4a56..591a105 100644--- a/src/homebrew/view.cpp+++ b/src/homebrew/view.cpp@@ -1757,6 +1757,8 @@ class Render::Impl? (game.art_failed || game.art_pending || !game.id.steam_app() ? 0 : art_[texture_index]): (live_artwork_ && current_state_ && !current_state_->account().id.empty()? store_texture(game.id, CoverUrl(game)) : 0);+ // No cover from the store: the icon inside the game's program, over its colour (#213).+ const std::uint32_t icon = simulated || texture != 0 ? 0 : program_icon_texture(game.id, CoverUrl(game));const TileStatus status = tile_status(game.id);// Glow first: it is a filled soft shape, and the art must cover its middle so only the// light outside the tile shows, as on macOS. The art itself is never tinted.@@ -1770,6 +1772,13 @@ class Render::Implscene_.gradient_rect(rect, 8.0F, id_color(game.id), gfx::Color::rgb(0x24201D));// A thumbnail (the Queue's) is too narrow for words: its row names the game.const bool words_fit = rect.w >= 120.0F;+ if (icon != 0)+ {+ // Above the title on a tile; alone, and larger, on a thumbnail.+ const float side = words_fit ? std::min(rect.w * 0.5F, rect.h * 0.36F) : std::min(rect.w, rect.h) * 0.72F;+ const float centre = words_fit ? rect.y + rect.h * 0.34F : rect.cy();+ scene_.image(icon, {rect.cx() - side * 0.5F, centre - side * 0.5F, side, side}, gfx::kFullUv, kText, 0.0F);+ }if (words_fit && game.art_pending){ui::text(scene_, fonts_.display, "Artwork loading", rect.cx(), rect.y + rect.h * 0.52F,@@ -1780,8 +1789,8 @@ class Render::Impl// The focus overlay names a focused tile, so the placeholder need not repeat it.const float placeholder = title_overlay ? 1.0F - amount : 1.0F;const ui::FontRef &face = font_for(game.title, fonts_.display);- ui::paragraph(scene_, face, game.title, rect.cx(), rect.y + rect.h * 0.42F,- 28.0F, rect.w - 36.0F, 31.0F, kText.with_alpha(placeholder), 4, gfx::Align::center);+ ui::paragraph(scene_, face, game.title, rect.cx(), rect.y + rect.h * (icon != 0 ? 0.62F : 0.42F),+ 28.0F, rect.w - 36.0F, 31.0F, kText.with_alpha(placeholder), icon != 0 ? 3 : 4, gfx::Align::center);}}const bool downloading = status.job != nullptr &&@@ -2514,6 +2523,17 @@ class Render::Implreturn url.empty() || !live_artwork_ ? 0 : live_artwork_->TextureFor(id, url, width, height);}+ // The icon inside a prepared game's program (program_icon.hpp), for a game whose store has no cover+ // or whose cover failed to load; 0 otherwise, and while the cover may still come.+ std::uint32_t program_icon_texture(GameId id, const std::string &cover_url)+ {+ if (!live_artwork_ || current_state_ == nullptr) return 0;+ if (!cover_url.empty() && !live_artwork_->Failed(id, cover_url)) return 0;+ const auto game = current_state_->runtime_games.find(id);+ if (game == current_state_->runtime_games.end() || game->second.program_icon.empty()) return 0;+ return live_artwork_->TextureFor(id, game->second.program_icon);+ }+// A label over its value, as the macOS details metadata.void detail_cell(std::string_view label, std::string_view value, float x, float y, float width,gfx::Color tone = kText)@@ -2565,8 +2585,13 @@ class Render::Implscene_.image(cover, rect, gfx::kFullUv, kText, 6.0F);return;}- // No cover: the game's colour alone.+ // No cover: the game's colour, with its program's icon when there is one.scene_.gradient_rect(rect, 6.0F, id_color(id), gfx::Color::rgb(0x24201D));+ if (const std::uint32_t icon = program_icon_texture(id, CoverUrl(id)))+ {+ const float side = std::min(rect.w, rect.h) * 0.72F;+ scene_.image(icon, {rect.cx() - side * 0.5F, rect.cy() - side * 0.5F, side, side}, gfx::kFullUv, kText, 0.0F);+ }}// The Saves tab: filter chips and Sync all over one list of games with saves on this console.diff --git a/tests/homebrew_artwork_cache_test.cpp b/tests/homebrew_artwork_cache_test.cppindex 07c6be2..e49a4e5 100644--- a/tests/homebrew_artwork_cache_test.cpp+++ b/tests/homebrew_artwork_cache_test.cpp@@ -251,7 +251,37 @@ void TextureCountEvictsLeastRecentlySeenUnusedEntry() {} // namespace+// A cover that failed to load says so, so a tile can show the program's icon meanwhile (#213).+void FailedLoadIsReported() {+ ControlledArtwork backend;+ backend.failed.insert(SteamId(30));+ ArtworkService service(backend, 1h);+ FakeTextures textures;+ LiveArtworkCache cache(service, textures);+ cache.BeginFrame(1);+ assert(!cache.Failed(SteamId(30), "cover") && cache.TextureFor(SteamId(30), "cover") == 0);+ assert(cache.TextureFor(SteamId(31), "cover") == 0);+ cache.EndFrame();+ const auto deadline = std::chrono::steady_clock::now() + 3s;+ bool failed = false;+ while (!failed && std::chrono::steady_clock::now() < deadline) {+ cache.BeginFrame(1);+ (void)cache.TextureFor(SteamId(30), "cover");+ (void)cache.TextureFor(SteamId(31), "cover");+ cache.EndFrame();+ failed = cache.Failed(SteamId(30), "cover");+ std::this_thread::sleep_for(1ms);+ }+ assert(failed && !cache.Failed(SteamId(30), "other") && !cache.Failed(SteamId(32), "cover"));+ assert(AwaitTexture(cache, 1, SteamId(31), "cover") != 0 && !cache.Failed(SteamId(31), "cover"));+ // Another account's cache knows nothing of it.+ cache.BeginFrame(2);+ assert(!cache.Failed(SteamId(30), "cover"));+ cache.EndFrame();+}+int main() {+ FailedLoadIsReported();DeduplicatesAndUploadsOnlyOnUiThread();UploadCountIsBoundedPerFrame();LateSourceAndGenerationCannotPopulateCurrentIdentity();diff --git a/tests/homebrew_artwork_graphical_test.cpp b/tests/homebrew_artwork_graphical_test.cppindex 55b6cd1..85a1be0 100644--- a/tests/homebrew_artwork_graphical_test.cpp+++ b/tests/homebrew_artwork_graphical_test.cpp@@ -1,4 +1,5 @@#include "homebrew/artwork.hpp"+#include "homebrew/program_icon.hpp"#include "homebrew/render.hpp"#include "homebrew/simulation.hpp"#include "gfx/gl_program.hpp"@@ -17,7 +18,17 @@ struct Backend final : ArtworkBackend {std::atomic<bool> release{false};std::optional<ArtworkImage> Load(const ArtworkKey& key, const std::atomic<bool>& cancel) override {while (!release && !cancel) std::this_thread::sleep_for(1ms);- if (cancel || key.game_id == SteamId(44)) return std::nullopt;+ if (cancel) return std::nullopt;+ // The program's icon: a 32x32 orange disc on a transparent ground.+ if (ProgramIconPath(key.source)) {+ ArtworkImage icon{32,32,std::vector<std::uint8_t>(32*32*4,0)};+ for (int y=0;y<32;++y) for (int x=0;x<32;++x)+ if ((x-16)*(x-16)+(y-16)*(y-16)<15*15) {+ auto* p=&icon.rgba[(y*32+x)*4]; p[0]=240; p[1]=140; p[2]=30; p[3]=255;+ }+ return icon;+ }+ if (key.game_id == SteamId(44)) return std::nullopt;ArtworkImage result{64,96,{}};result.rgba.resize(64*96*4);for (std::size_t i=0;i<result.rgba.size();i+=4) {@@ -69,6 +80,20 @@ int main(int argc,char** argv) {assert(renderer.diagnostics().live_artwork_gpu_bytes==2*64*96*4);for(int i=0;i<16;++i) renderer.draw(model,1920,1080);assert(renderer.capture_png(output/"ready.png",1920,1080));+ // A game whose cover failed shows the icon inside its program once it is prepared (#213).+ LiveRuntimeGame prepared;+ prepared.game_id=SteamId(44);+ prepared.status="Ready";+ prepared.program_icon=ProgramIconSource("/data/playden-games/44/Game.exe");+ model.UpdateRuntime(RuntimeState::Ready,{prepared});+ const auto icon_deadline=std::chrono::steady_clock::now()+3s;+ while(renderer.diagnostics().live_artwork_texture_count<3 && std::chrono::steady_clock::now()<icon_deadline) {+ renderer.draw(model,1920,1080);+ std::this_thread::sleep_for(1ms);+ }+ assert(renderer.diagnostics().live_artwork_texture_count==3);+ for(int i=0;i<16;++i) renderer.draw(model,1920,1080);+ assert(renderer.capture_png(output/"program-icon.png",1920,1080));const auto generation=model.state().account_generation;model.UpdateAccount({AuthState::SignedOut,{},{},{},{},true});// Same-account replacement in one render interval must still invalidate resources.diff --git a/tests/homebrew_program_icon_test.cpp b/tests/homebrew_program_icon_test.cppnew file mode 100644index 0000000..4deddc8--- /dev/null+++ b/tests/homebrew_program_icon_test.cpp@@ -0,0 +1,282 @@+// homebrew_program_icon_test.cpp - A program's icon from its PE resources, and the tile made from it.+// Copyright (c) 2026 Playden contributors+// SPDX-License-Identifier: GPL-3.0-or-later+#include "homebrew/program_icon.hpp"+#include "homebrew/title_icon.hpp"++#include <cstdio>+#include <cstdlib>+#include <filesystem>+#include <string>+#include <vector>++#include <sys/stat.h>+#include <unistd.h>++#define STB_IMAGE_STATIC+#define STB_IMAGE_IMPLEMENTATION+#include "stb_image.h"+#define STB_IMAGE_WRITE_STATIC+#define STB_IMAGE_WRITE_IMPLEMENTATION+#include "stb_image_write.h"++#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "%s:%d: CHECK failed: %s\n", __FILE__, __LINE__, #x); std::exit(1); } } while (0)++namespace fs = std::filesystem;+using namespace playden::homebrew;+using Bytes = std::string;++namespace {++void Put16(Bytes* b, std::size_t at, std::uint32_t v) { (*b)[at] = char(v & 0xff); (*b)[at + 1] = char((v >> 8) & 0xff); }+void Put32(Bytes* b, std::size_t at, std::uint32_t v) { for (int i = 0; i < 4; ++i) (*b)[at + i] = char((v >> (8 * i)) & 0xff); }+void Add16(Bytes* b, std::uint32_t v) { b->resize(b->size() + 2); Put16(b, b->size() - 2, v); }+void Add32(Bytes* b, std::uint32_t v) { b->resize(b->size() + 4); Put32(b, b->size() - 4, v); }++constexpr std::uint32_t kRsrcRva = 0x1000;+constexpr std::uint32_t kRsrcFile = 0x200;++struct Icon {+ std::uint8_t width, height; // as the group lists them (0: 256)+ std::uint16_t bits;+ Bytes data;+};++// A resource section: RT_ICON (3) with one entry per icon (ids 1..n), RT_GROUP_ICON (14) with group 101.+Bytes Resources(const std::vector<Icon>& icons) {+ Bytes group;+ Add16(&group, 0); Add16(&group, 1); Add16(&group, static_cast<std::uint32_t>(icons.size()));+ for (std::size_t i = 0; i < icons.size(); ++i) {+ group += char(icons[i].width); group += char(icons[i].height); group += '\0'; group += '\0';+ Add16(&group, 1); Add16(&group, icons[i].bits); Add32(&group, static_cast<std::uint32_t>(icons[i].data.size()));+ Add16(&group, static_cast<std::uint32_t>(i + 1));+ }+ std::vector<Bytes> blobs;+ for (const auto& icon : icons) blobs.push_back(icon.data);+ blobs.push_back(group);+ const std::size_t n = icons.size();+ // Directories: root (2 entries), icons (n), group (1), then one language directory per blob (1 entry each).+ const auto dir_size = [](std::size_t entries) { return 16 + 8 * entries; };+ const std::uint32_t icons_dir = static_cast<std::uint32_t>(dir_size(2));+ const std::uint32_t group_dir = icons_dir + static_cast<std::uint32_t>(dir_size(n));+ const std::uint32_t languages = group_dir + static_cast<std::uint32_t>(dir_size(1));+ const std::uint32_t leaves = languages + static_cast<std::uint32_t>(dir_size(1) * blobs.size());+ std::uint32_t data = leaves + static_cast<std::uint32_t>(16 * blobs.size());+ Bytes out;+ const auto directory = [&](std::vector<std::pair<std::uint32_t, std::uint32_t>> entries) {+ Add32(&out, 0); Add32(&out, 0); Add32(&out, 0); Add16(&out, 0); Add16(&out, static_cast<std::uint32_t>(entries.size()));+ for (const auto& [id, offset] : entries) { Add32(&out, id); Add32(&out, offset); }+ };+ directory({{3, 0x80000000u | icons_dir}, {14, 0x80000000u | group_dir}});+ std::vector<std::pair<std::uint32_t, std::uint32_t>> icon_entries;+ for (std::size_t i = 0; i < n; ++i)+ icon_entries.push_back({static_cast<std::uint32_t>(i + 1), 0x80000000u | (languages + static_cast<std::uint32_t>(dir_size(1) * i))});+ directory(icon_entries);+ directory({{101, 0x80000000u | (languages + static_cast<std::uint32_t>(dir_size(1) * n))}});+ for (std::size_t i = 0; i < blobs.size(); ++i) directory({{1033, leaves + static_cast<std::uint32_t>(16 * i)}});+ for (const auto& blob : blobs) {+ Add32(&out, kRsrcRva + data); Add32(&out, static_cast<std::uint32_t>(blob.size())); Add32(&out, 0); Add32(&out, 0);+ data += static_cast<std::uint32_t>((blob.size() + 3) / 4 * 4);+ }+ for (const auto& blob : blobs) { out += blob; out.resize((out.size() + 3) / 4 * 4, '\0'); }+ return out;+}++// A 32-bit program whose one section is the resources (or no resource directory at all).+Bytes Program(const Bytes& rsrc, bool with_directory = true) {+ Bytes pe(kRsrcFile, '\0');+ pe[0] = 'M'; pe[1] = 'Z'; Put32(&pe, 0x3c, 0x40);+ pe[0x40] = 'P'; pe[0x41] = 'E';+ Put16(&pe, 0x44, 0x14c); Put16(&pe, 0x46, 1); Put16(&pe, 0x54, 0xe0);+ const std::size_t opt = 0x58;+ Put16(&pe, opt, 0x10b);+ Put32(&pe, opt + 92, 16);+ if (with_directory) { Put32(&pe, opt + 96 + 16, kRsrcRva); Put32(&pe, opt + 96 + 20, static_cast<std::uint32_t>(rsrc.size())); }+ const std::size_t section = opt + 0xe0;+ std::copy_n(".rsrc", 5, pe.begin() + section);+ Put32(&pe, section + 8, static_cast<std::uint32_t>(rsrc.size()));+ Put32(&pe, section + 12, kRsrcRva);+ Put32(&pe, section + 16, static_cast<std::uint32_t>(rsrc.size()));+ Put32(&pe, section + 20, kRsrcFile);+ return pe + rsrc;+}++// A bottom-up BMP icon image (BITMAPINFOHEADER with the doubled height) from top-down RGBA pixels.+Bytes Dib(int w, int h, int bits, const std::vector<std::uint32_t>& rgba, const std::vector<std::uint32_t>& palette = {},+ const std::vector<bool>& transparent = {}) {+ Bytes out;+ Add32(&out, 40); Add32(&out, w); Add32(&out, 2 * h); Add16(&out, 1); Add16(&out, bits);+ Add32(&out, 0); Add32(&out, 0); Add32(&out, 0); Add32(&out, 0);+ Add32(&out, static_cast<std::uint32_t>(palette.size())); Add32(&out, 0);+ for (auto colour : palette) { out += char((colour >> 8) & 0xff); out += char((colour >> 16) & 0xff); out += char(colour >> 24); out += '\0'; }+ const std::size_t stride = (static_cast<std::size_t>(w) * bits + 31) / 32 * 4;+ for (int y = h - 1; y >= 0; --y) {+ Bytes row(stride, '\0');+ for (int x = 0; x < w; ++x) {+ const auto p = rgba[static_cast<std::size_t>(y) * w + x]; // 0xRRGGBBAA, or a palette index+ if (bits == 32) { row[x * 4] = char((p >> 8) & 0xff); row[x * 4 + 1] = char((p >> 16) & 0xff); row[x * 4 + 2] = char(p >> 24); row[x * 4 + 3] = char(p & 0xff); }+ else if (bits == 24) { row[x * 3] = char((p >> 8) & 0xff); row[x * 3 + 1] = char((p >> 16) & 0xff); row[x * 3 + 2] = char(p >> 24); }+ else if (bits == 4) row[x / 2] = char(row[x / 2] | (p << (x % 2 ? 0 : 4)));+ }+ out += row;+ }+ const std::size_t mask_stride = (static_cast<std::size_t>(w) + 31) / 32 * 4;+ for (int y = h - 1; y >= 0; --y) {+ Bytes row(mask_stride, '\0');+ for (int x = 0; x < w; ++x)+ if (!transparent.empty() && transparent[static_cast<std::size_t>(y) * w + x]) row[x / 8] = char(row[x / 8] | (0x80 >> (x % 8)));+ out += row;+ }+ return out;+}++Bytes Png(int w, int h, std::uint32_t rgba) {+ std::vector<std::uint8_t> pixels(static_cast<std::size_t>(w) * h * 4);+ for (std::size_t i = 0; i < pixels.size(); i += 4)+ pixels[i] = rgba >> 24, pixels[i + 1] = (rgba >> 16) & 0xff, pixels[i + 2] = (rgba >> 8) & 0xff, pixels[i + 3] = rgba & 0xff;+ Bytes png;+ stbi_write_png_to_func([](void* context, void* data, int size) { static_cast<Bytes*>(context)->append(static_cast<char*>(data), size); },+ &png, w, h, 4, pixels.data(), w * 4);+ return png;+}++std::string Write(const fs::path& path, const Bytes& bytes) {+ FILE* file = std::fopen(path.c_str(), "wb");+ CHECK(file);+ std::fwrite(bytes.data(), 1, bytes.size(), file);+ std::fclose(file);+ return path.string();+}++const std::uint8_t* Pixel(const ArtworkImage& image, std::uint32_t x, std::uint32_t y) {+ return &image.rgba[(static_cast<std::size_t>(y) * image.width + x) * 4];+}++struct FakeBackend : ArtworkBackend {+ std::vector<std::string> asked;+ std::optional<ArtworkImage> Load(const ArtworkKey& key, const std::atomic<bool>&) override {+ asked.push_back(key.source);+ return ArtworkImage{1, 1, {1, 2, 3, 255}};+ }+};++} // namespace++int main() {+ // The real path: the system's temporary folder is behind a link on macOS, and links are refused.+ const fs::path root = fs::canonical(fs::temp_directory_path()) / ("playden-program-icon-" + std::to_string(::getpid()));+ fs::remove_all(root);+ fs::create_directories(root / "Game");++ // A PNG and a smaller BMP: the largest, the PNG, is the icon.+ const auto both = Write(root / "Game/Both.exe", Program(Resources({+ {16, 16, 32, Dib(16, 16, 32, std::vector<std::uint32_t>(256, 0x00ff00ffu))},+ {0, 0, 32, Png(256, 256, 0xff0000ffu)}})));+ auto icon = ReadProgramIcon(both);+ CHECK(icon && icon->width == 256 && icon->height == 256 && Pixel(*icon, 10, 10)[0] == 255 && Pixel(*icon, 10, 10)[3] == 255);++ // A 32-bit BMP: rows bottom-up in the file, top-down in the image, with its own alpha.+ std::vector<std::uint32_t> bands(4 * 4);+ for (int y = 0; y < 4; ++y) for (int x = 0; x < 4; ++x) bands[y * 4 + x] = y == 0 ? 0xff000080u : 0x0000ffffu;+ icon = ReadProgramIcon(Write(root / "Game/Bands.exe", Program(Resources({{4, 4, 32, Dib(4, 4, 32, bands)}}))));+ CHECK(icon && icon->width == 4 && icon->height == 4);+ CHECK(Pixel(*icon, 0, 0)[0] == 255 && Pixel(*icon, 0, 0)[3] == 0x80);+ CHECK(Pixel(*icon, 0, 3)[2] == 255 && Pixel(*icon, 0, 3)[0] == 0 && Pixel(*icon, 0, 3)[3] == 255);++ // A 4-bit BMP: palette colours, and the mask's set bits are transparent; 24-bit uses the mask too.+ std::vector<std::uint32_t> indexes(8 * 2, 1);+ indexes[0] = 0;+ std::vector<bool> holes(8 * 2, false);+ holes[7] = true;+ icon = ReadProgramIcon(Write(root / "Game/Old.exe", Program(Resources({+ {8, 2, 4, Dib(8, 2, 4, indexes, {0x000000ffu, 0x00ff00ffu}, holes)}}))));+ CHECK(icon && icon->width == 8 && icon->height == 2);+ CHECK(Pixel(*icon, 0, 0)[1] == 0 && Pixel(*icon, 0, 0)[3] == 255);+ CHECK(Pixel(*icon, 1, 0)[1] == 255 && Pixel(*icon, 7, 0)[3] == 0 && Pixel(*icon, 7, 1)[3] == 255);+ icon = ReadProgramIcon(Write(root / "Game/True.exe", Program(Resources({+ {8, 2, 24, Dib(8, 2, 24, std::vector<std::uint32_t>(16, 0x123456ffu), {}, holes)}}))));+ CHECK(icon && Pixel(*icon, 0, 0)[0] == 0x12 && Pixel(*icon, 0, 0)[2] == 0x56 && Pixel(*icon, 7, 0)[3] == 0);++ // A broken largest image falls back to the next one.+ icon = ReadProgramIcon(Write(root / "Game/Fallback.exe", Program(Resources({+ {0, 0, 32, Bytes("\x89PNG\r\n\x1a\nbroken", 14)},+ {4, 4, 32, Dib(4, 4, 32, bands)}}))));+ CHECK(icon && icon->width == 4);++ // Nothing, and no crash, for what isn't a program with an icon.+ CHECK(!ReadProgramIcon((root / "Game/Missing.exe").string()));+ CHECK(!ReadProgramIcon(Write(root / "Game/Text.exe", "MZ just text")));+ CHECK(!ReadProgramIcon(Write(root / "Game/Bare.exe", Program(Bytes(64, '\0'), false))));+ CHECK(!ReadProgramIcon(Write(root / "Game/Empty.exe", Program(Resources({})))));+ { // A BMP claiming 4096 pixels a side, and one with more rows than bytes.+ auto big = Dib(4, 4, 32, bands);+ Put32(&big, 4, 4096); Put32(&big, 8, 8192);+ CHECK(!ReadProgramIcon(Write(root / "Game/Big.exe", Program(Resources({{4, 4, 32, big}})))));+ auto short_rows = Dib(4, 4, 32, bands);+ Put32(&short_rows, 8, 2 * 400);+ CHECK(!ReadProgramIcon(Write(root / "Game/Short.exe", Program(Resources({{4, 4, 32, short_rows}})))));+ }+ { // A directory claiming more entries than fit.+ auto rsrc = Resources({{4, 4, 32, Dib(4, 4, 32, bands)}});+ Put16(&rsrc, 14, 0xffff);+ CHECK(!ReadProgramIcon(Write(root / "Game/Count.exe", Program(rsrc))));+ }+ // Every truncation of a good program reads safely.+ const auto good = Program(Resources({{0, 0, 32, Png(32, 32, 0xff0000ffu)}, {4, 4, 32, Dib(4, 4, 32, bands)}}));+ for (std::size_t size = 0; size < good.size(); size += 3)+ (void)ReadProgramIcon(Write(root / "Game/Cut.exe", good.substr(0, size)));+ // A symbolic link is not followed, as the program or as one of its folders; a FIFO doesn't block.+ fs::create_symlink(root / "Game/Bands.exe", root / "Game/Link.exe");+ CHECK(!ReadProgramIcon((root / "Game/Link.exe").string()));+ fs::create_directory_symlink(root / "Game", root / "Linked");+ CHECK(!ReadProgramIcon((root / "Linked/Bands.exe").string()) && ReadProgramIcon((root / "Game/Bands.exe").string()));+ CHECK(::mkfifo((root / "Game/Pipe.exe").c_str(), 0600) == 0);+ CHECK(!ReadProgramIcon((root / "Game/Pipe.exe").string()));+ CHECK(!ReadProgramIcon("relative/Game.exe"));+ { // A PNG larger than an icon is skipped before it is decoded; the group's smaller BMP is used.+ auto big = Png(600, 2, 0xff0000ffu);+ CHECK(!ReadProgramIcon(Write(root / "Game/BigPng.exe", Program(Resources({{0, 0, 32, big}})))));+ icon = ReadProgramIcon(Write(root / "Game/BigPngBmp.exe", Program(Resources({{0, 0, 32, big}, {4, 4, 32, Dib(4, 4, 32, bands)}}))));+ CHECK(icon && icon->width == 4);+ }++ // The artwork source carries an absolute .exe path, nothing else.+ CHECK(ProgramIconSource("/data/playden-games/1/Game.exe") == "program-icon:/data/playden-games/1/Game.exe");+ CHECK(ProgramIconSource("").empty());+ CHECK(ProgramIconPath("program-icon:/data/playden-games/1/Game.EXE") == std::string("/data/playden-games/1/Game.EXE"));+ for (const char* bad : {"program-icon:", "program-icon:relative/Game.exe", "program-icon:/a/../b/Game.exe",+ "program-icon:/a//Game.exe", "program-icon:/a/Game.dll", "https://x/Game.exe", "program-icon:/./Game.exe"})+ CHECK(!ProgramIconPath(bad));++ // The backend reads program icons from the game's files, under the desktop prefix, and passes on the rest.+ FakeBackend next;+ ProgramIconArtworkBackend backend(next, root.string() + "/");+ const std::atomic<bool> cancel{false};+ const playden::GameId game = playden::GameId::Steam(10);+ icon = backend.Load({1, game, ProgramIconSource("/Game/Bands.exe")}, cancel);+ CHECK(icon && icon->width == 4 && next.asked.empty());+ CHECK(!backend.Load({1, game, ProgramIconSource("/Game/Missing.exe")}, cancel) && next.asked.empty());+ icon = backend.Load({1, game, "https://cdn.cloudflare.steamstatic.com/steam/apps/10/library_600x900.jpg"}, cancel);+ CHECK(icon && icon->width == 1 && next.asked.size() == 1);++ // The tile: the icon two thirds of the side, centred on the dark ground; transparency shows the ground.+ ArtworkImage half{2, 2, {255, 0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255, 255, 0, 0, 255}};+ auto tile = ProgramIconTile(half, 300);+ CHECK(tile && tile->width == 300 && tile->height == 300);+ CHECK(Pixel(*tile, 0, 0)[0] == 0x24 && Pixel(*tile, 0, 0)[3] == 255);+ CHECK(Pixel(*tile, 150, 150)[0] == 255 && Pixel(*tile, 150, 150)[1] == 0);+ CHECK(Pixel(*tile, 40, 150)[0] == 0x24); // outside the 200-pixel box+ ArtworkImage clear{1, 1, {255, 255, 255, 0}};+ tile = ProgramIconTile(clear, 30);+ CHECK(tile && Pixel(*tile, 15, 15)[0] == 0x24);+ CHECK(!ProgramIconTile(ArtworkImage{}, 30) && !ProgramIconTile(half, 0));+ const auto png = MakeProgramTitleIcon(half);+ int width = 0, height = 0, components = 0;+ auto* pixels = stbi_load_from_memory(reinterpret_cast<const stbi_uc*>(png->data()), static_cast<int>(png->size()),+ &width, &height, &components, 3);+ CHECK(pixels && width == 512 && height == 512 && pixels[0] == 0x24 && pixels[(256 * 512 + 256) * 3] == 255);+ stbi_image_free(pixels);++ fs::remove_all(root);+ std::puts("program icon tests passed");+}diff --git a/tests/homebrew_runtime_host_test.cpp b/tests/homebrew_runtime_host_test.cppindex bfc2080..0f24e61 100644--- a/tests/homebrew_runtime_host_test.cpp+++ b/tests/homebrew_runtime_host_test.cpp@@ -571,7 +571,7 @@ void PreparesExistingDownloadToReady() {++uuids; return std::string("00000000-0000-4000-8000-00000000000") + std::to_string(uuids);};config.unix_time = [] { return std::int64_t{1760000000}; };- config.title_icon = [](const playden::GameId& game) -> std::optional<std::string> {+ config.title_icon = [](const playden::GameId& game, const fs::path&) -> std::optional<std::string> {return game == playden::GameId::Steam(220) ? std::optional<std::string>("game-icon-png") : std::nullopt;};const auto game = fixture.root / "data/homebrew/FAKE77031/games/220";@@ -1174,7 +1174,7 @@ void RepairsBottleRegistryModes() {CHECK(chmod(title_param.c_str(), 0644) == 0);Write(title_param, Read(fixture.root / "kit/titles/variant/sce_sys/param.json"), 0644);auto named = config;- named.title_icon = [](const playden::GameId&) -> std::optional<std::string> { return std::string("game-icon-png"); };+ named.title_icon = [](const playden::GameId&, const fs::path&) -> std::optional<std::string> { return std::string("game-icon-png"); };RuntimeHost upgraded(named);CHECK(upgraded.Start());CHECK(!WaitFor(upgraded, Started).installs[0].title_current);@@ -3034,8 +3034,10 @@ void LocalGameKeepsItsBottle() {config.removal_confirm_polls = 3;config.removal_poll_interval = std::chrono::milliseconds(1);std::vector<playden::GameId> icons;- config.title_icon = [&icons](const playden::GameId& game) -> std::optional<std::string> {+ std::vector<fs::path> icon_programs;+ config.title_icon = [&icons, &icon_programs](const playden::GameId& game, const fs::path& program) -> std::optional<std::string> {icons.push_back(game);+ icon_programs.push_back(program);return std::nullopt;};config.unregister_title = [&fixture](const std::string&, const std::string&) {@@ -3076,6 +3078,8 @@ void LocalGameKeepsItsBottle() {CHECK(!ready.refusals.count(number) && ready.installs.size() == 1 && ready.installs[0].game == local);CHECK(ready.installs[0].install_id == "local-0f8fad5b-d9cb-469f-a165-70867728950e");CHECK(std::find(icons.begin(), icons.end(), local) != icons.end()); // named by game, not by number+ // With the program the title starts, on the host, for a game without cover art.+ CHECK(!icon_programs.empty() && icon_programs.back() == fixture.root / "data/playden-import/Imported/Bin/Game.exe");CHECK(ready.generated_recipes.size() == 1 && ready.generated_recipes[0].id == playden::GeneratedRecipeId(local) &&playden::runtime::RecipeGame(ready.generated_recipes[0]) == local);// A store's name in the title name (any store's) is not the game's: the kept bottle names the game.