diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index b5e1638..4121c62 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -23,7 +23,7 @@ jobs: - name: Checkout the game submodules (without their desktop-only nested submodules) run: | - git submodule update --init components/jk/OpenJKDF2 components/mgs/mgs_reversing components/mgs/psyz components/tpm/tpm-decomp components/genesis/gwenesis components/pico8/femto8 components/nes/nofrendo components/gbc/gnuboy components/msx/fmsx components/sms/smsplus components/doom/prboom components/darkforces/TheForceEngine components/emulink + git submodule update --init components/jk/OpenJKDF2 components/mgs/mgs_reversing components/mgs/psyz components/tpm/tpm-decomp components/genesis/gwenesis components/pico8/femto8 components/nes/nofrendo components/gbc/gnuboy components/msx/fmsx components/sms/smsplus components/doom/prboom components/darkforces/TheForceEngine components/emulink components/emu-ui # ScummVM's history is large: only the pinned commit git submodule update --init --depth 1 components/scummvm/scummvm diff --git a/.gitmodules b/.gitmodules index fc8b601..78cdeca 100644 --- a/.gitmodules +++ b/.gitmodules @@ -53,3 +53,7 @@ path = components/emulink url = https://github.com/esp-cpp/emulink.git branch = main +[submodule "components/emu-ui"] + path = components/emu-ui + url = https://github.com/esp-cpp/emu-ui.git + branch = main diff --git a/README.md b/README.md index 3170799..09ec9ca 100644 --- a/README.md +++ b/README.md @@ -177,8 +177,9 @@ has the details. main/ app_main, Cart base class, per-game carts components/ tab5-emu/ HAL (Tab5Emu): display / PPA video path, audio, SD, input - gui/ LVGL launcher (rom list + boxart + settings) - menu/ LVGL in-game pause menu (resume/reset/save/load/quit) + emu-ui/ the launcher's and the pause menu's screens (shared with esp-box-emu) + gui/ the launcher: the games, boxart and settings for emu-ui + menu/ the in-game pause menu (resume/reset/save/load/quit) on emu-ui rom_info/ metadata.csv parsing statistics/ frame timing jk/ OpenJKDF2 port: engine submodule + ESP32 platform layer + glue diff --git a/components/emu-ui b/components/emu-ui new file mode 160000 index 0000000..bf14c65 --- /dev/null +++ b/components/emu-ui @@ -0,0 +1 @@ +Subproject commit bf14c65d2cbb2ef15ef5a112e9751fb5990c2767 diff --git a/components/gui/CMakeLists.txt b/components/gui/CMakeLists.txt index cdfccb1..9b8e4f7 100644 --- a/components/gui/CMakeLists.txt +++ b/components/gui/CMakeLists.txt @@ -1,4 +1,4 @@ idf_component_register( INCLUDE_DIRS "include" SRC_DIRS "src" - REQUIRES lvgl timer logger rom_info settings tab5-emu) + REQUIRES lvgl emu-ui timer logger rom_info settings tab5-emu app_update esp_app_format) diff --git a/components/gui/include/console_art.hpp b/components/gui/include/console_art.hpp deleted file mode 100644 index 2cb664c..0000000 --- a/components/gui/include/console_art.hpp +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once - -#include - -#include "lvgl.h" - -#include "rom_info.hpp" - -/// Draw a small icon of `info`'s console (a gamepad, a handheld, a disc...) -/// out of plain LVGL objects into a new `h * 8 / 5` x `h` container in -/// `parent`. Generic shapes in the console's accent color; no logos. -lv_obj_t *console_icon_create(lv_obj_t *parent, const ConsoleInfo &info, int h); - -/// A rounded badge in the console's accent color: the icon and the console's -/// name, `h` pixels tall, sized to its content. -lv_obj_t *console_badge_create(lv_obj_t *parent, const ConsoleInfo &info, int h, const lv_font_t *font); - -/// The SD card art for `info`, if there is any: `/boxart/consoles/.jpg`. -std::string console_art_path(const std::string &root, const ConsoleInfo &info); diff --git a/components/gui/include/gui.hpp b/components/gui/include/gui.hpp index 0a70f21..1c39361 100644 --- a/components/gui/include/gui.hpp +++ b/components/gui/include/gui.hpp @@ -2,10 +2,12 @@ #include #include +#include #include #include #include #include +#include #include #include "lvgl.h" @@ -14,20 +16,23 @@ #include "high_resolution_timer.hpp" #include "logger.hpp" -#include "console_art.hpp" +#include "emu-ui/launcher.hpp" + #include "rom_info.hpp" #include "settings.hpp" #include "tab5-emu.hpp" -/// The launcher GUI: a list of games (from metadata.csv on the SD card), -/// grouped under a header per console, with the selected game's boxart and -/// console, plus settings (volume, brightness, video scaling, resume), which -/// are kept in AppSettings. Hand-written LVGL, laid out for the Tab5's -/// 1280x720 landscape screen. +/// The launcher: the games in metadata.csv on the SD card, grouped by +/// console, with the selected game's boxart, a console picker and the +/// settings (kept in AppSettings). The screens are emu-ui's (shared with +/// esp-box-emu); this is the Tab5's side of them: the games, the images, +/// the settings and the USB drive. class Gui { public: struct Config { std::string metadata_filename = "metadata.csv"; + /// Where the carts keep their save states (the list shows each game's count) + std::string save_dir{std::string(Tab5Emu::mount_point) + "/saves"}; espp::Logger::Verbosity log_level{espp::Logger::Verbosity::WARN}; }; @@ -51,6 +56,8 @@ class Gui { void resume(); void update_rom_list(); + /// Give the launcher rom_infos_ (with their save counts), keeping `selected_path` selected + void show_games(const std::string &selected_path); /// Re-read metadata.csv even if its modification time did not change (FAT /// times are coarse, and without a set clock they may not move at all). void reload_rom_list() { @@ -93,61 +100,29 @@ class Gui { Snapshot snapshot(); protected: - void init_ui(); - void deinit_ui(); - void update_shared_state(); - void select_rom(int index); - void build_list(int keep_rom); - void step_console(int dir); - void update_filter_marker(); - void open_console_picker(); - void close_console_picker(); - static void picker_event(lv_event_t *e); + std::vector settings_rows(); + void set_usb_drive(bool on); void update(); - void on_volume(const std::vector &data); void on_battery(const std::vector &data); - static void event_callback(lv_event_t *e); - - std::vector rom_infos_; - std::atomic focused_rom_{-1}; - - lv_obj_t *screen_{nullptr}; - lv_group_t *group_{nullptr}; ///< gamepad / keyboard focus order - lv_obj_t *rom_list_{nullptr}; - lv_obj_t *boxart_{nullptr}; - lv_draw_buf_t *boxart_buf_{nullptr}; ///< decoded boxart the image widget shows - void load_boxart(const std::string &path); /// Decode a JPEG on the SD card into a new RGB565 draw buffer (nullptr if it cannot) lv_draw_buf_t *decode_image(const std::string &path); + const void *cover(size_t index); + const void *console_art(const std::string &key); - // the console the selected game runs on: its SD card art, or a badge - lv_obj_t *console_area_{nullptr}; - lv_draw_buf_t *console_art_buf_{nullptr}; - int shown_console_{-1}; - void show_console(Console console); - void add_console_header(Console console); - lv_obj_t *title_label_{nullptr}; - lv_obj_t *play_button_{nullptr}; - lv_obj_t *volume_slider_{nullptr}; - lv_obj_t *brightness_slider_{nullptr}; - lv_obj_t *mute_switch_{nullptr}; - lv_obj_t *usb_switch_{nullptr}; - lv_obj_t *usb_label_{nullptr}; - void set_usb_drive(bool on); - lv_obj_t *video_dropdown_{nullptr}; - lv_obj_t *resume_switch_{nullptr}; - lv_obj_t *battery_label_{nullptr}; - std::vector rom_buttons_; ///< per game (rom_infos_ index); nullptr if filtered out - - // the console filter: the Console whose games the list shows, -1 all - int filter_{-1}; - lv_obj_t *picker_{nullptr}; ///< the console picker, while it is open - lv_group_t *picker_group_{nullptr}; - std::vector picker_consoles_; ///< the picker's rows: Console, -1 all + std::vector rom_infos_; + std::atomic focused_rom_{-1}; + std::unique_ptr launcher_; + lv_draw_buf_t *boxart_buf_{nullptr}; ///< the selected game's decoded boxart + /// boxart/consoles/.jpg, decoded once (nullptr: there is none) + std::map console_art_; + std::string usb_note_; + bool usb_drive_shown_{false}; std::string metadata_filename_; + std::string save_dir_; + std::unordered_map save_counts_; ///< per rom stem (emu_ui::count_saves) std::filesystem::file_time_type metadata_last_modified_{}; std::atomic paused_{false}; diff --git a/components/gui/src/console_art.cpp b/components/gui/src/console_art.cpp deleted file mode 100644 index 771973c..0000000 --- a/components/gui/src/console_art.cpp +++ /dev/null @@ -1,135 +0,0 @@ -#include "console_art.hpp" - -#include -#include - -namespace { - -lv_obj_t *shape(lv_obj_t *parent, int x, int y, int w, int h, int radius, lv_color_t color) { - auto *o = lv_obj_create(parent); - lv_obj_remove_style_all(o); - lv_obj_remove_flag(o, LV_OBJ_FLAG_SCROLLABLE); - lv_obj_remove_flag(o, LV_OBJ_FLAG_CLICKABLE); - lv_obj_set_pos(o, x, y); - lv_obj_set_size(o, w, h); - lv_obj_set_style_radius(o, radius, 0); - lv_obj_set_style_bg_color(o, color, 0); - lv_obj_set_style_bg_opa(o, LV_OPA_COVER, 0); - return o; -} - -// a + shaped d-pad centered at (cx, cy), `s` across -void dpad(lv_obj_t *parent, int cx, int cy, int s, lv_color_t color) { - const int t = std::max(2, s / 3); - shape(parent, cx - s / 2, cy - t / 2, s, t, 1, color); - shape(parent, cx - t / 2, cy - s / 2, t, s, 1, color); -} - -void dot(lv_obj_t *parent, int cx, int cy, int d, lv_color_t color) { - shape(parent, cx - d / 2, cy - d / 2, d, d, LV_RADIUS_CIRCLE, color); -} - -} // namespace - -lv_obj_t *console_icon_create(lv_obj_t *parent, const ConsoleInfo &info, int h) { - const int w = h * 8 / 5; - auto *box = lv_obj_create(parent); - lv_obj_remove_style_all(box); - lv_obj_remove_flag(box, LV_OBJ_FLAG_SCROLLABLE); - lv_obj_remove_flag(box, LV_OBJ_FLAG_CLICKABLE); - lv_obj_set_size(box, w, h); - - const lv_color_t body = lv_color_white(); - const lv_color_t accent = lv_color_hex(info.color); - const lv_color_t dark = lv_color_hex(0x202428); - - switch (info.shape) { - case ConsoleShape::GAMEPAD: { - // a wide rounded controller: d-pad left, two buttons right - const int bh = h * 6 / 10, by = (h - bh) / 2; - shape(box, 0, by, w, bh, bh / 2, body); - dpad(box, w * 27 / 100, h / 2, bh * 6 / 10, accent); - dot(box, w * 66 / 100, h / 2 + bh / 8, bh / 4, accent); - dot(box, w * 80 / 100, h / 2 - bh / 8, bh / 4, accent); - break; - } - case ConsoleShape::HANDHELD_TALL: { - // a portrait handheld: screen on top, d-pad and buttons below it - const int bw = h * 66 / 100, bx = (w - bw) / 2; - shape(box, bx, 0, bw, h, bw / 6, body); - shape(box, bx + bw / 8, h / 10, bw * 6 / 8, h * 4 / 10, 2, dark); - dpad(box, bx + bw * 30 / 100, h * 72 / 100, bw * 3 / 10, accent); - dot(box, bx + bw * 68 / 100, h * 76 / 100, bw / 6, accent); - dot(box, bx + bw * 84 / 100, h * 66 / 100, bw / 6, accent); - break; - } - case ConsoleShape::HANDHELD_WIDE: { - // a landscape handheld: screen in the middle, d-pad and buttons beside it - const int bh = h * 7 / 10, by = (h - bh) / 2; - shape(box, 0, by, w, bh, bh * 4 / 10, body); - shape(box, w * 30 / 100, by + bh / 6, w * 40 / 100, bh * 2 / 3, 2, dark); - dpad(box, w * 15 / 100, h / 2, bh * 4 / 10, accent); - dot(box, w * 82 / 100, h / 2 + bh / 10, bh / 5, accent); - dot(box, w * 90 / 100, h / 2 - bh / 10, bh / 5, accent); - break; - } - case ConsoleShape::DISC: { - // a CD: rim, label ring, hole - const int d = h, x = (w - d) / 2; - shape(box, x, 0, d, d, LV_RADIUS_CIRCLE, body); - dot(box, w / 2, h / 2, d * 45 / 100, accent); - dot(box, w / 2, h / 2, d * 15 / 100, body); - break; - } - case ConsoleShape::COMPUTER: { - // a monitor on a stand - const int mw = w * 70 / 100, mh = h * 66 / 100, mx = (w - mw) / 2; - shape(box, mx, 0, mw, mh, 3, body); - shape(box, mx + mw / 12, mh / 8, mw * 10 / 12, mh * 6 / 8, 1, accent); - shape(box, w / 2 - w / 14, mh, w / 7, h / 6, 0, body); - shape(box, w / 2 - w / 5, h - h / 8, w * 2 / 5, h / 8, 2, body); - break; - } - case ConsoleShape::FANTASY: { - // a tiny cartridge-console: a square with a screen of palette dots - const int s = h, x = (w - s) / 2; - shape(box, x, 0, s, s, s / 6, body); - const int sx = x + s / 8, sy = s / 8, ss = s * 6 / 8; - shape(box, sx, sy, ss, ss * 3 / 4, 2, dark); - const uint32_t palette[] = {0xFF004D, 0xFFA300, 0xFFEC27, 0x00E436}; - const int p = std::max(2, ss / 6); - for (int i = 0; i < 4; i++) { - shape(box, sx + ss / 10 + i * (p + p / 3), sy + ss * 3 / 8 - p / 2, p, p, 0, lv_color_hex(palette[i])); - } - break; - } - } - return box; -} - -lv_obj_t *console_badge_create(lv_obj_t *parent, const ConsoleInfo &info, int h, const lv_font_t *font) { - auto *badge = lv_obj_create(parent); - lv_obj_remove_style_all(badge); - lv_obj_remove_flag(badge, LV_OBJ_FLAG_SCROLLABLE); - lv_obj_remove_flag(badge, LV_OBJ_FLAG_CLICKABLE); - lv_obj_set_size(badge, LV_SIZE_CONTENT, h); - lv_obj_set_style_radius(badge, h / 2, 0); - lv_obj_set_style_bg_color(badge, lv_color_hex(info.color), 0); - lv_obj_set_style_bg_opa(badge, LV_OPA_COVER, 0); - lv_obj_set_style_pad_hor(badge, h / 3, 0); - lv_obj_set_style_pad_column(badge, h / 4, 0); - lv_obj_set_flex_flow(badge, LV_FLEX_FLOW_ROW); - lv_obj_set_flex_align(badge, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER); - console_icon_create(badge, info, h * 6 / 10); - auto *label = lv_label_create(badge); - lv_label_set_text(label, info.name); - lv_obj_set_style_text_color(label, lv_color_white(), 0); - if (font) lv_obj_set_style_text_font(label, font, 0); - return badge; -} - -std::string console_art_path(const std::string &root, const ConsoleInfo &info) { - const std::string path = root + "/boxart/consoles/" + info.key + ".jpg"; - std::error_code ec; - return std::filesystem::exists(path, ec) ? path : std::string{}; -} diff --git a/components/gui/src/gui.cpp b/components/gui/src/gui.cpp index 01cb68c..a3d4caf 100644 --- a/components/gui/src/gui.cpp +++ b/components/gui/src/gui.cpp @@ -1,31 +1,66 @@ #include "gui.hpp" -#include - -#include "lvgl_private.h" +#include "emu-ui/saves.hpp" #include +#include + +#include +#include +#include "lvgl_private.h" // (lv_image_decoder_dsc_t) using namespace std::chrono_literals; +namespace { + +// the Console of a console key (rom_info's ConsoleInfo::key) +std::optional console_of_key(const std::string &key) { + for (int c = 0; c < static_cast(Console::UNKNOWN); c++) { + if (key == console_info(static_cast(c)).key) return static_cast(c); + } + return std::nullopt; +} + +std::string version_text() { + const auto *app = esp_app_get_description(); + const auto *part = esp_ota_get_running_partition(); + return fmt::format("{} {}", app ? app->version : "", part ? part->label : ""); +} + +struct SettingLimit { + const char *name; + int min, max; +}; +// (the same ranges as the launcher's own controls) +constexpr SettingLimit kSettingLimits[] = { + {"volume", 0, 100}, {"muted", 0, 1}, {"brightness", 5, 100}, {"video", 0, 2}, {"resume", 0, 1}}; + +} // namespace + Gui::Gui(const Config &config) : metadata_filename_(config.metadata_filename) + , save_dir_(config.save_dir) , logger_({.tag = "Gui", .level = config.log_level}) { - init_ui(); - update_rom_list(); - update_shared_state(); - // gamepad / keyboard navigation from the first screen on (resume() does - // the same after a game) - if (auto *keypad = Tab5Emu::get().keypad_indev(); keypad && group_) { - lv_indev_set_group(keypad, group_); - if (focused_rom_ >= 0 && focused_rom_ < (int)rom_buttons_.size() && rom_buttons_[focused_rom_]) { - lv_group_focus_obj(rom_buttons_[focused_rom_]); - } - logger_.info("keypad group attached: {} objects, focused rom {}, focused obj {}", lv_group_get_obj_count(group_), - focused_rom_.load(), fmt::ptr(lv_group_get_focused(group_))); - } else { - logger_.warn("no keypad input device / group at startup"); + { + std::lock_guard lk(mutex_); + launcher_ = std::make_unique(emu_ui::Launcher::Config{ + .metrics = emu_ui::Metrics::large_1280x720(), + .brand = "tab5-emu", + .keypad = Tab5Emu::get().keypad_indev(), + .cover = [this](size_t i) { return cover(i); }, + .console_art = [this](const std::string &key) { return console_art(key); }, + .on_play = + [this](size_t i) { + focused_rom_ = i; + ready_to_play_ = true; + }, + .on_select = [this](size_t i) { focused_rom_ = i; }, + .settings = settings_rows(), + .version = version_text(), + }); + update_rom_list(); + launcher_->show(); } task_.periodic(16 * 1000); using namespace std::placeholders; @@ -37,7 +72,12 @@ Gui::~Gui() { espp::EventManager::get().remove_subscriber(volume_changed_topic, "gui"); espp::EventManager::get().remove_subscriber(battery_topic, "gui"); task_.stop(); - deinit_ui(); + std::lock_guard lk(mutex_); + launcher_.reset(); + if (boxart_buf_) lv_draw_buf_destroy(boxart_buf_); + for (auto &[key, buf] : console_art_) { + if (buf) lv_draw_buf_destroy(buf); + } } void Gui::pause() { @@ -49,206 +89,111 @@ void Gui::pause() { void Gui::resume() { std::lock_guard lk(mutex_); - // a game started from the PC (emulink launch) leaves the console picker open - // behind it: back from the game, the list has the keypad, so close it - close_console_picker(); + // (a game started from the PC, emulink launch, may have left the picker open) + launcher_->close_picker(); update_rom_list(); - update_shared_state(); - lv_screen_load(screen_); - lv_obj_invalidate(screen_); - if (auto *keypad = Tab5Emu::get().keypad_indev(); keypad && group_) { - lv_indev_set_group(keypad, group_); - if (focused_rom_ >= 0 && focused_rom_ < (int)rom_buttons_.size() && rom_buttons_[focused_rom_]) { - lv_group_focus_obj(rom_buttons_[focused_rom_]); - } - logger_.info("keypad group attached: {} objects, focused rom {}, focused obj {}", lv_group_get_obj_count(group_), - focused_rom_.load(), fmt::ptr(lv_group_get_focused(group_))); - } else { - logger_.warn("no keypad input device / group at startup"); - } + launcher_->refresh_settings(); + launcher_->show(); + lv_obj_invalidate(launcher_->screen()); task_.periodic(16 * 1000); paused_ = false; } void Gui::update() { - if (!paused_) { - std::lock_guard lk(mutex_); - // the USB link can start or end the drive mode too (emulink drive on / - // off; an eject alone does not, the hand-over is never automatic): follow - // it with the switch, and pick up what the PC copied over - const bool drive_on = Tab5Emu::get().usb_msc_host_has_card(); - if (usb_switch_ && drive_on != lv_obj_has_state(usb_switch_, LV_STATE_CHECKED)) { - if (drive_on) { - lv_obj_add_state(usb_switch_, LV_STATE_CHECKED); - lv_obj_add_state(play_button_, LV_STATE_DISABLED); - lv_label_set_text(usb_label_, "The PC has the SD card. Eject it there, then switch off."); - } else { - lv_obj_remove_state(usb_switch_, LV_STATE_CHECKED); - lv_obj_remove_state(play_button_, LV_STATE_DISABLED); - lv_label_set_text(usb_label_, "SD card as a USB drive on the USB-C port"); - reload_rom_list(); - } - } - lv_timer_handler(); - } + if (paused_) return; + std::lock_guard lk(mutex_); + // the USB link can start or end the drive mode too (emulink drive on / + // off; an eject alone does not, the hand-over is never automatic): follow + // it, and pick up what the PC copied over + const bool drive_on = Tab5Emu::get().usb_msc_host_has_card(); + if (drive_on != usb_drive_shown_) { + usb_drive_shown_ = drive_on; + usb_note_ = drive_on ? "The PC has the SD card. Eject it there, then switch this off." : ""; + launcher_->set_play_enabled(!drive_on); + launcher_->refresh_settings(); + if (!drive_on) reload_rom_list(); + } + lv_timer_handler(); } -void Gui::update_shared_state() { +std::vector Gui::settings_rows() { + using K = emu_ui::Row::Kind; auto &emu = Tab5Emu::get(); - lv_slider_set_value(volume_slider_, (int)emu.volume(), LV_ANIM_OFF); - lv_slider_set_value(brightness_slider_, (int)emu.brightness(), LV_ANIM_OFF); - if (emu.is_muted()) - lv_obj_add_state(mute_switch_, LV_STATE_CHECKED); - else - lv_obj_remove_state(mute_switch_, LV_STATE_CHECKED); - lv_dropdown_set_selected(video_dropdown_, (int)emu.video_setting()); - if (AppSettings::get().get_settings().resume_last_save) - lv_obj_add_state(resume_switch_, LV_STATE_CHECKED); - else - lv_obj_remove_state(resume_switch_, LV_STATE_CHECKED); + // (saved to the SD card by the main loop once the changes stop) + std::vector rows; + rows.push_back({.label = "Volume", .kind = K::SLIDER, .step = 5, + .get = [&emu] { return (int)std::lround(emu.volume()); }, + .set = [&emu](int v) { + emu.volume(v); + AppSettings::get().modify([v](Settings &s) { s.volume = v; }); + }, + .symbol = LV_SYMBOL_VOLUME_MAX}); + rows.push_back({.label = "Mute", .kind = K::TOGGLE, .get = [&emu] { return emu.is_muted() ? 1 : 0; }, + .set = [&emu](int v) { + emu.mute(v != 0); + AppSettings::get().modify([v](Settings &s) { s.muted = v != 0; }); + }, + .symbol = LV_SYMBOL_MUTE}); + rows.push_back({.label = "Brightness", .kind = K::SLIDER, .min = 5, .step = 5, + .get = [&emu] { return (int)std::lround(emu.brightness()); }, + .set = [&emu](int v) { + emu.brightness(v); + AppSettings::get().modify([v](Settings &s) { s.brightness = v; }); + }, + .symbol = LV_SYMBOL_EYE_OPEN}); + rows.push_back({.label = "Video scaling", .kind = K::CHOICE, .choices = {"Original", "Fit", "Fill"}, + .get = [&emu] { return (int)emu.video_setting(); }, + .set = [&emu](int v) { + emu.video_setting(static_cast(v)); + AppSettings::get().modify([v](Settings &s) { s.video_setting = v; }); + }, + .symbol = LV_SYMBOL_IMAGE}); + rows.push_back({.label = "Resume last save", .kind = K::TOGGLE, + .get = [] { return AppSettings::get().get_settings().resume_last_save ? 1 : 0; }, + .set = [](int v) { AppSettings::get().modify([v](Settings &s) { s.resume_last_save = v != 0; }); }, + .symbol = LV_SYMBOL_REFRESH}); + rows.push_back({.label = "USB drive", .kind = K::TOGGLE, + .get = [&emu] { return emu.usb_msc_host_has_card() ? 1 : 0; }, + .set = [this](int v) { set_usb_drive(v != 0); }, + .note = + [this] { + return usb_note_.empty() ? std::string("The SD card as a USB drive on the USB-C port") : usb_note_; + }, + .symbol = LV_SYMBOL_USB}); + return rows; } -void Gui::on_volume(const std::vector &) { - std::lock_guard lk(mutex_); - update_shared_state(); +// USB drive mode: hand the SD card to a PC. Nothing may touch the card +// meanwhile, so Play is off; when it ends the list is reloaded so anything +// copied over shows up. +void Gui::set_usb_drive(bool on) { + auto &emu = Tab5Emu::get(); + if (on) { + if (!emu.initialize_usb_msc()) { + usb_note_ = "The USB drive could not start (no SD card?)"; + return; + } + usb_drive_shown_ = true; + usb_note_ = "Plug the USB-C port into a PC. Eject there, then switch this off."; + launcher_->set_play_enabled(false); + } else { + emu.deinitialize_usb_msc(); + usb_drive_shown_ = false; + usb_note_.clear(); + launcher_->set_play_enabled(true); + reload_rom_list(); + } } -void Gui::on_battery(const std::vector &) { +void Gui::on_volume(const std::vector &) { std::lock_guard lk(mutex_); - auto status = Tab5Emu::get().battery_status(); - lv_label_set_text_fmt(battery_label_, "%s %.0f%% %.2fV", status.is_charging ? LV_SYMBOL_CHARGE : LV_SYMBOL_BATTERY_3, - status.charge_percent, status.voltage_v); + launcher_->refresh_settings(); } -void Gui::init_ui() { - std::lock_guard lk(mutex_); - screen_ = lv_obj_create(nullptr); - lv_obj_set_style_bg_color(screen_, lv_color_hex(0x101418), 0); - lv_obj_remove_flag(screen_, LV_OBJ_FLAG_SCROLLABLE); - - const int W = Tab5Emu::lcd_width(), H = Tab5Emu::lcd_height(); - - // header - auto header = lv_label_create(screen_); - lv_label_set_text(header, "tab5-emu"); - lv_obj_set_style_text_font(header, &lv_font_montserrat_32, 0); - lv_obj_set_style_text_color(header, lv_color_white(), 0); - lv_obj_align(header, LV_ALIGN_TOP_LEFT, 24, 16); - - battery_label_ = lv_label_create(screen_); - lv_label_set_text(battery_label_, LV_SYMBOL_BATTERY_EMPTY " --%"); - lv_obj_set_style_text_font(battery_label_, &lv_font_montserrat_20, 0); - lv_obj_set_style_text_color(battery_label_, lv_color_white(), 0); - lv_obj_align(battery_label_, LV_ALIGN_TOP_RIGHT, -24, 22); - - // rom list (left) - rom_list_ = lv_list_create(screen_); - lv_obj_set_size(rom_list_, W / 3, H - 100); - lv_obj_align(rom_list_, LV_ALIGN_TOP_LEFT, 24, 76); - lv_obj_set_style_text_font(rom_list_, &lv_font_montserrat_24, 0); - - // console of the selected game (center top): its SD card art or a badge - console_area_ = lv_obj_create(screen_); - lv_obj_remove_style_all(console_area_); - lv_obj_remove_flag(console_area_, LV_OBJ_FLAG_SCROLLABLE); - // a tap on it opens the console picker (so does X on a gamepad, F on a keyboard) - lv_obj_add_flag(console_area_, LV_OBJ_FLAG_CLICKABLE); - lv_obj_add_flag(console_area_, LV_OBJ_FLAG_OVERFLOW_VISIBLE); // (the filter outline) - lv_obj_add_event_cb(console_area_, [](lv_event_t *e) { - static_cast(lv_event_get_user_data(e))->open_console_picker(); - }, LV_EVENT_CLICKED, this); - - lv_obj_set_size(console_area_, 400, 56); - lv_obj_align(console_area_, LV_ALIGN_TOP_MID, 40, 76); - lv_obj_set_flex_flow(console_area_, LV_FLEX_FLOW_ROW); - lv_obj_set_flex_align(console_area_, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER); - - // boxart + title (center) - boxart_ = lv_image_create(screen_); - lv_obj_set_size(boxart_, 360, 360); - lv_image_set_inner_align(boxart_, LV_IMAGE_ALIGN_CONTAIN); - lv_obj_align(boxart_, LV_ALIGN_TOP_MID, 40, 144); - - title_label_ = lv_label_create(screen_); - lv_label_set_text(title_label_, ""); - lv_obj_set_style_text_font(title_label_, &lv_font_montserrat_24, 0); - lv_obj_set_style_text_color(title_label_, lv_color_white(), 0); - lv_label_set_long_mode(title_label_, LV_LABEL_LONG_WRAP); - lv_obj_set_width(title_label_, 400); - lv_obj_set_style_text_align(title_label_, LV_TEXT_ALIGN_CENTER, 0); - lv_obj_align_to(title_label_, boxart_, LV_ALIGN_OUT_BOTTOM_MID, 0, 16); - - play_button_ = lv_button_create(screen_); - lv_obj_set_size(play_button_, 240, 72); - lv_obj_align(play_button_, LV_ALIGN_BOTTOM_MID, 40, -32); - auto play_label = lv_label_create(play_button_); - lv_label_set_text(play_label, LV_SYMBOL_PLAY " Play"); - lv_obj_set_style_text_font(play_label, &lv_font_montserrat_24, 0); - lv_obj_center(play_label); - lv_obj_add_event_cb(play_button_, event_callback, LV_EVENT_CLICKED, this); - - // settings (right) - auto settings = lv_obj_create(screen_); - lv_obj_set_size(settings, W / 4, H - 100); - lv_obj_align(settings, LV_ALIGN_TOP_RIGHT, -24, 76); - lv_obj_set_flex_flow(settings, LV_FLEX_FLOW_COLUMN); - lv_obj_set_style_pad_row(settings, 18, 0); - - auto make_label = [&](const char *text) { - auto l = lv_label_create(settings); - lv_label_set_text(l, text); - lv_obj_set_style_text_font(l, &lv_font_montserrat_20, 0); - return l; - }; - - make_label(LV_SYMBOL_VOLUME_MAX " Volume"); - volume_slider_ = lv_slider_create(settings); - lv_obj_set_width(volume_slider_, lv_pct(90)); - lv_slider_set_range(volume_slider_, 0, 100); - lv_obj_add_event_cb(volume_slider_, event_callback, LV_EVENT_VALUE_CHANGED, this); - - make_label(LV_SYMBOL_MUTE " Mute"); - mute_switch_ = lv_switch_create(settings); - lv_obj_add_event_cb(mute_switch_, event_callback, LV_EVENT_VALUE_CHANGED, this); - - make_label(LV_SYMBOL_EYE_OPEN " Brightness"); - brightness_slider_ = lv_slider_create(settings); - lv_obj_set_width(brightness_slider_, lv_pct(90)); - lv_slider_set_range(brightness_slider_, 5, 100); - lv_obj_add_event_cb(brightness_slider_, event_callback, LV_EVENT_VALUE_CHANGED, this); - - make_label(LV_SYMBOL_USB " USB drive"); - usb_switch_ = lv_switch_create(settings); - lv_obj_add_event_cb(usb_switch_, event_callback, LV_EVENT_VALUE_CHANGED, this); - usb_label_ = lv_label_create(settings); - lv_label_set_text(usb_label_, "SD card as a USB drive on the USB-C port"); - lv_obj_set_width(usb_label_, lv_pct(95)); - lv_label_set_long_mode(usb_label_, LV_LABEL_LONG_WRAP); - - make_label(LV_SYMBOL_IMAGE " Video scaling"); - video_dropdown_ = lv_dropdown_create(settings); - lv_dropdown_set_options(video_dropdown_, "Original\nFit\nFill"); - lv_obj_set_width(video_dropdown_, lv_pct(90)); - lv_obj_add_event_cb(video_dropdown_, event_callback, LV_EVENT_VALUE_CHANGED, this); - - make_label(LV_SYMBOL_REFRESH " Resume last save"); - resume_switch_ = lv_switch_create(settings); - lv_obj_add_event_cb(resume_switch_, event_callback, LV_EVENT_VALUE_CHANGED, this); - - // gamepad / keyboard focus order (see Tab5Emu::keypad_indev()): the ROM - // buttons come first (added by update_rom_list), then the controls - group_ = lv_group_create(); - lv_group_set_wrap(group_, true); - - lv_screen_load(screen_); -} - -void Gui::deinit_ui() { +void Gui::on_battery(const std::vector &) { std::lock_guard lk(mutex_); - if (screen_) { - lv_obj_delete(screen_); - screen_ = nullptr; - } + const auto status = Tab5Emu::get().battery_status(); + launcher_->set_battery((int)std::lround(status.charge_percent), status.is_charging); } void Gui::update_rom_list() { @@ -256,12 +201,18 @@ void Gui::update_rom_list() { std::error_code ec; auto path = std::string(Tab5Emu::mount_point) + "/" + metadata_filename_; auto mtime = std::filesystem::last_write_time(path, ec); + // (the saves are counted each time: a game played since may have saved) + auto saves = emu_ui::count_saves(save_dir_); if (!ec && mtime == metadata_last_modified_ && !rom_infos_.empty()) { + if (saves != save_counts_) { + save_counts_ = std::move(saves); + const int f = focused_rom_; + show_games(f >= 0 && f < (int)rom_infos_.size() ? rom_infos_[f].rom_path : std::string()); + } return; } + save_counts_ = std::move(saves); metadata_last_modified_ = mtime; - // (an open picker's consoles and counts are the old list's) - close_console_picker(); // keep the selected game selected across a reload (its index may change); // at boot that is the last game played std::string selected_path; @@ -275,253 +226,66 @@ void Gui::update_rom_list() { std::stable_sort(rom_infos_.begin(), rom_infos_.end(), [](const RomInfo &a, const RomInfo &b) { return console_of(a.platform) < console_of(b.platform); }); - focused_rom_ = -1; - for (size_t i = 0; i < rom_infos_.size(); i++) { - if (rom_infos_[i].rom_path == selected_path) { - focused_rom_ = i; - break; - } - } - build_list(focused_rom_); + show_games(selected_path); } -// The game list: the games that pass the console filter, under a header per -// console; `keep_rom` stays selected if it is shown, else the first game. -void Gui::build_list(int keep_rom) { - std::lock_guard lk(mutex_); - // a filter for a console that is no longer on the card shows them all - if (filter_ >= 0 && std::none_of(rom_infos_.begin(), rom_infos_.end(), [this](const RomInfo &r) { - return static_cast(console_of(r.platform)) == filter_; - })) { - filter_ = -1; - } - auto shown = [this](size_t i) { - return filter_ < 0 || static_cast(console_of(rom_infos_[i].platform)) == filter_; - }; - if (keep_rom < 0 || keep_rom >= (int)rom_infos_.size() || !shown(keep_rom)) { - keep_rom = -1; - for (size_t i = 0; i < rom_infos_.size() && keep_rom < 0; i++) { - if (shown(i)) keep_rom = i; - } - } - // (adding the first button to the empty group focuses it, and its FOCUSED - // event selects that game: keep_rom is selected at the end) - lv_obj_clean(rom_list_); - rom_buttons_.assign(rom_infos_.size(), nullptr); - if (group_) { - lv_group_remove_all_objs(group_); - } - int last_console = -1; +void Gui::show_games(const std::string &selected_path) { + int selected = -1; + std::vector games; + games.reserve(rom_infos_.size()); for (size_t i = 0; i < rom_infos_.size(); i++) { - if (!shown(i)) continue; - const Console console = console_of(rom_infos_[i].platform); - if (static_cast(console) != last_console) { - last_console = static_cast(console); - add_console_header(console); - } - auto btn = lv_list_add_button(rom_list_, nullptr, rom_infos_[i].name.c_str()); - lv_obj_set_user_data(btn, reinterpret_cast(static_cast(i))); - lv_obj_add_event_cb(btn, event_callback, LV_EVENT_CLICKED, this); - lv_obj_add_event_cb(btn, event_callback, LV_EVENT_FOCUSED, this); - lv_obj_add_event_cb(btn, event_callback, LV_EVENT_KEY, this); - // left / right come to the game as keys (not focus moves): they change - // the console (see Tab5Emu::keypad_read()) - lv_obj_add_flag(btn, LV_OBJ_FLAG_USER_1); - // the selected game (the theme has no checked look for list buttons) - lv_obj_set_style_bg_color(btn, lv_palette_main(LV_PALETTE_BLUE), LV_STATE_CHECKED); - lv_obj_set_style_bg_opa(btn, LV_OPA_COVER, LV_STATE_CHECKED); - rom_buttons_[i] = btn; - if (group_) lv_group_add_obj(group_, btn); - } - if (group_) { - for (auto *o : {play_button_, volume_slider_, mute_switch_, brightness_slider_, usb_switch_, video_dropdown_, - resume_switch_}) { - if (o) lv_group_add_obj(group_, o); - } - } - update_filter_marker(); - if (keep_rom < 0) { - lv_list_add_text(rom_list_, "No games found.\nAdd metadata.csv to the SD card."); - focused_rom_ = -1; - lv_label_set_text(title_label_, ""); - lv_image_set_src(boxart_, nullptr); - lv_obj_clean(console_area_); - shown_console_ = -1; - } else { - select_rom(keep_rom); + const auto &rom = rom_infos_[i]; + const auto &info = console_info(console_of(rom.platform)); + const auto it = save_counts_.find(std::filesystem::path(rom.rom_path).stem().string()); + games.push_back({.title = rom.name, .console_key = info.key, .console_name = info.name, + .console_short = info.short_name, .saves = it == save_counts_.end() ? 0 : it->second}); + if (selected < 0 && rom.rom_path == selected_path) selected = i; } + focused_rom_ = -1; + launcher_->set_games(std::move(games), selected); + focused_rom_ = launcher_->selected(); } std::vector Gui::consoles() const { std::lock_guard lk(mutex_); std::vector out; - for (const auto &r : rom_infos_) { - const Console c = console_of(r.platform); - if (out.empty() || out.back() != c) out.push_back(c); // (grouped by console) + for (const auto &key : launcher_->consoles()) { + if (auto c = console_of_key(key)) out.push_back(*c); } return out; } std::optional Gui::console_filter() const { std::lock_guard lk(mutex_); - if (filter_ < 0) return std::nullopt; - return static_cast(filter_); + const auto f = launcher_->filter(); + return f ? console_of_key(*f) : std::nullopt; } bool Gui::set_console_filter(std::optional console) { std::lock_guard lk(mutex_); - const auto present = consoles(); - if (console && std::find(present.begin(), present.end(), *console) == present.end()) { - return false; // no games for it - } - filter_ = console ? static_cast(*console) : -1; - build_list(focused_rom_); // (the selected game stays if the filter shows it) - return true; + return launcher_->set_filter(console ? std::optional(console_info(*console).key) : std::nullopt); } -// Left / right: the previous / next console's first game; with a filter on, -// the filter moves to that console. -void Gui::step_console(int dir) { - std::lock_guard lk(mutex_); - const auto present = consoles(); - if (present.size() < 2 || focused_rom_ < 0 || focused_rom_ >= (int)rom_infos_.size()) { - return; - } - const Console current = console_of(rom_infos_[focused_rom_].platform); - const int n = present.size(); - const int at = std::find(present.begin(), present.end(), current) - present.begin(); - const Console next = present[(at + (dir < 0 ? n - 1 : 1)) % n]; - if (filter_ >= 0) { - set_console_filter(next); - return; - } - for (size_t i = 0; i < rom_infos_.size(); i++) { - if (console_of(rom_infos_[i].platform) == next) { - select_rom(i); - if (rom_buttons_[i]) lv_obj_scroll_to_view(rom_buttons_[i], LV_ANIM_ON); - return; - } - } -} - -// With a filter on, the console above the boxart is outlined (the area is also the -// button that opens the console picker). -void Gui::update_filter_marker() { - if (!console_area_) return; - // (on the badge / art itself, which is narrower than the area) - if (auto *shown = lv_obj_get_child(console_area_, 0)) { - lv_obj_set_style_outline_color(shown, lv_color_white(), 0); - lv_obj_set_style_outline_pad(shown, 3, 0); - lv_obj_set_style_outline_width(shown, filter_ >= 0 ? 3 : 0, 0); - } -} - -// The console picker: "All consoles" and each console on the card with its -// number of games, over the launcher. A tap / A picks one, B or a tap beside -// the list closes it. -void Gui::open_console_picker() { - std::lock_guard lk(mutex_); - if (picker_) { - return; - } - const auto present = consoles(); - picker_ = lv_obj_create(screen_); - lv_obj_remove_style_all(picker_); - lv_obj_set_size(picker_, lv_pct(100), lv_pct(100)); - lv_obj_set_style_bg_color(picker_, lv_color_black(), 0); - lv_obj_set_style_bg_opa(picker_, LV_OPA_60, 0); - lv_obj_add_flag(picker_, LV_OBJ_FLAG_CLICKABLE); - lv_obj_add_event_cb(picker_, picker_event, LV_EVENT_CLICKED, this); - - auto *list = lv_list_create(picker_); - lv_obj_set_size(list, 480, LV_SIZE_CONTENT); - lv_obj_set_style_max_height(list, Tab5Emu::lcd_height() - 120, 0); - lv_obj_center(list); - lv_obj_set_style_text_font(list, &lv_font_montserrat_24, 0); - lv_list_add_text(list, "Show games for"); - - picker_group_ = lv_group_create(); - lv_group_set_wrap(picker_group_, true); - picker_consoles_.clear(); - lv_obj_t *focus = nullptr; - auto add = [&](int console, const std::string &text) { - auto *btn = lv_list_add_button(list, console < 0 ? LV_SYMBOL_LIST : nullptr, text.c_str()); - lv_obj_set_height(btn, 64); - if (console >= 0) { - auto *icon = console_icon_create(btn, console_info(static_cast(console)), 32); - lv_obj_move_to_index(icon, 0); - } - if (console == filter_) lv_obj_add_state(btn, LV_STATE_CHECKED); - lv_obj_set_user_data(btn, reinterpret_cast(static_cast(picker_consoles_.size()))); - lv_obj_add_event_cb(btn, picker_event, LV_EVENT_CLICKED, this); - lv_obj_add_event_cb(btn, picker_event, LV_EVENT_KEY, this); - lv_group_add_obj(picker_group_, btn); - picker_consoles_.push_back(console); - if (console == filter_) focus = btn; - }; - add(-1, fmt::format("All consoles ({})", rom_infos_.size())); - for (const Console c : present) { - const auto n = std::count_if(rom_infos_.begin(), rom_infos_.end(), - [c](const RomInfo &r) { return console_of(r.platform) == c; }); - add(static_cast(c), fmt::format("{} ({})", console_info(c).name, n)); - } - if (focus) lv_group_focus_obj(focus); - if (auto *keypad = Tab5Emu::get().keypad_indev()) lv_indev_set_group(keypad, picker_group_); -} - -void Gui::close_console_picker() { +bool Gui::select_rom_matching(std::string_view text) { std::lock_guard lk(mutex_); - if (!picker_) { - return; - } - // (out of the group before the group goes; the objects go after this event) - lv_group_remove_all_objs(picker_group_); - lv_group_delete(picker_group_); - picker_group_ = nullptr; - lv_obj_delete_async(picker_); - picker_ = nullptr; - if (auto *keypad = Tab5Emu::get().keypad_indev(); keypad && group_) { - lv_indev_set_group(keypad, group_); - if (focused_rom_ >= 0 && focused_rom_ < (int)rom_buttons_.size() && rom_buttons_[focused_rom_]) { - lv_group_focus_obj(rom_buttons_[focused_rom_]); + // an exact path or name first (one ROM's path can contain another's), then + // the first game containing the text + for (const bool exact : {true, false}) { + for (size_t i = 0; i < rom_infos_.size(); i++) { + const auto &rom = rom_infos_[i]; + if (exact ? (rom.rom_path == text || rom.name == text) + : (rom.name.find(text) != std::string::npos || rom.rom_path.find(text) != std::string::npos)) { + // (a game started from the link must not leave the picker over the list) + launcher_->close_picker(); + launcher_->select(i); // (lifts a filter that hides it) + focused_rom_ = i; + return true; + } } } + return false; } -void Gui::picker_event(lv_event_t *e) { - auto *gui = static_cast(lv_event_get_user_data(e)); - if (!gui || !gui->picker_) { - return; - } - auto *target = static_cast(lv_event_get_target(e)); - const auto code = lv_event_get_code(e); - if (code == LV_EVENT_KEY) { - const auto key = lv_indev_get_key(lv_indev_active()); - if (key == LV_KEY_ESC || key == LV_KEY_HOME) gui->close_console_picker(); - return; - } - if (target == gui->picker_) { - gui->close_console_picker(); // a tap beside the list - return; - } - const auto index = reinterpret_cast(lv_obj_get_user_data(target)); - if (index >= 0 && index < (intptr_t)gui->picker_consoles_.size()) { - const int console = gui->picker_consoles_[index]; - gui->close_console_picker(); - gui->set_console_filter(console < 0 ? std::nullopt : std::optional(static_cast(console))); - } -} - -namespace { -struct SettingLimit { - const char *name; - int min, max; -}; -// (the same ranges as the launcher's own sliders) -constexpr SettingLimit kSettingLimits[] = { - {"volume", 0, 100}, {"muted", 0, 1}, {"brightness", 5, 100}, {"video", 0, 2}, {"resume", 0, 1}}; -} // namespace - std::string Gui::settings_json() const { auto &emu = Tab5Emu::get(); const auto s = AppSettings::get().get_settings(); @@ -532,8 +296,7 @@ std::string Gui::settings_json() const { return fmt::format("{{\"settings\":{{\"volume\":{},\"muted\":{},\"brightness\":{},\"video\":{},\"resume\":{}}}," "\"limits\":{{{}}}}}", (int)std::lround(emu.volume()), emu.is_muted() ? 1 : 0, (int)std::lround(emu.brightness()), - (int)emu.video_setting(), - s.resume_last_save ? 1 : 0, limits); + (int)emu.video_setting(), s.resume_last_save ? 1 : 0, limits); } bool Gui::set_setting(const std::string &name, int value) { @@ -556,7 +319,7 @@ bool Gui::set_setting(const std::string &name, int value) { else if (name == "muted") emu.mute(value != 0); else if (name == "brightness") emu.brightness(value); else if (name == "video") emu.video_setting(static_cast(value)); - update_shared_state(); // the launcher's controls show it + launcher_->refresh_settings(); // the launcher shows it return true; } @@ -590,124 +353,35 @@ Gui::Snapshot Gui::snapshot() { return shot; } -// A non-selectable row in the game list starting a console's group: the -// console's icon and name on its accent color. -void Gui::add_console_header(Console console) { - const auto &info = console_info(console); - auto *hdr = lv_obj_create(rom_list_); - lv_obj_remove_style_all(hdr); - lv_obj_remove_flag(hdr, LV_OBJ_FLAG_SCROLLABLE); - lv_obj_remove_flag(hdr, LV_OBJ_FLAG_CLICKABLE); - lv_obj_set_size(hdr, lv_pct(100), 44); - lv_obj_set_style_bg_color(hdr, lv_color_hex(info.color), 0); - lv_obj_set_style_bg_opa(hdr, LV_OPA_COVER, 0); - lv_obj_set_style_pad_hor(hdr, 12, 0); - lv_obj_set_style_pad_column(hdr, 12, 0); - lv_obj_set_flex_flow(hdr, LV_FLEX_FLOW_ROW); - lv_obj_set_flex_align(hdr, LV_FLEX_ALIGN_START, LV_FLEX_ALIGN_CENTER, LV_FLEX_ALIGN_CENTER); - console_icon_create(hdr, info, 26); - auto *label = lv_label_create(hdr); - lv_label_set_text(label, info.name); - lv_obj_set_style_text_color(label, lv_color_white(), 0); - lv_obj_set_style_text_font(label, &lv_font_montserrat_20, 0); -} - -// Above the boxart: the SD card art of the selected game's console -// (boxart/consoles/.jpg) if there is one, else the firmware's badge. -// Only on this screen: in a game the screen is the game's. -void Gui::show_console(Console console) { - if (shown_console_ == static_cast(console)) { - return; - } - shown_console_ = static_cast(console); - lv_obj_clean(console_area_); - if (console_art_buf_) { - lv_draw_buf_destroy(console_art_buf_); - console_art_buf_ = nullptr; - } - const auto &info = console_info(console); - if (const auto art = console_art_path(Tab5Emu::mount_point, info); !art.empty()) { - console_art_buf_ = decode_image(art); - if (console_art_buf_) { - auto *img = lv_image_create(console_area_); - lv_obj_set_size(img, lv_pct(100), lv_pct(100)); - lv_image_set_inner_align(img, LV_IMAGE_ALIGN_CONTAIN); - lv_image_set_src(img, console_art_buf_); - update_filter_marker(); - return; - } - } - console_badge_create(console_area_, info, 48, &lv_font_montserrat_24); - update_filter_marker(); -} - -bool Gui::select_rom_matching(std::string_view text) { - std::lock_guard lk(mutex_); - // an exact path or name first (one ROM's path can contain another's), then - // the first game containing the text - for (const bool exact : {true, false}) { - for (size_t i = 0; i < rom_infos_.size(); i++) { - const auto &rom = rom_infos_[i]; - if (exact ? (rom.rom_path == text || rom.name == text) - : (rom.name.find(text) != std::string::npos || rom.rom_path.find(text) != std::string::npos)) { - // a game the console filter hides: show them all (build_list() - // selects it) - if (filter_ >= 0 && static_cast(console_of(rom.platform)) != filter_) { - filter_ = -1; - build_list(i); - } else { - select_rom(i); - } - return true; - } - } - } - return false; -} - -void Gui::select_rom(int index) { - std::lock_guard lk(mutex_); - if (index < 0 || index >= (int)rom_infos_.size()) { - return; - } - focused_rom_ = index; - for (size_t i = 0; i < rom_buttons_.size(); i++) { - if (!rom_buttons_[i]) continue; // (hidden by the console filter) - if ((int)i == index) - lv_obj_add_state(rom_buttons_[i], LV_STATE_CHECKED); - else - lv_obj_remove_state(rom_buttons_[i], LV_STATE_CHECKED); - } - // keep the keypad focus (and its highlight) on the selected game too - if (group_ && index < (int)rom_buttons_.size() && rom_buttons_[index] && - lv_group_get_focused(group_) != rom_buttons_[index]) { - lv_group_focus_obj(rom_buttons_[index]); - } - const auto &rom = rom_infos_[index]; - lv_label_set_text(title_label_, rom.name.c_str()); - show_console(console_of(rom.platform)); - load_boxart(rom.boxart_path); -} - -// LVGL's JPEG decoder (TJPGD) only yields the image block by block, and LVGL -// cannot scale a block-decoded image, so decode the boxart into a full RGB565 -// buffer here (once per selection) and show that. The POSIX fs driver is -// registered as 'S:' and passes the rest of the path through unchanged. -void Gui::load_boxart(const std::string &path) { - lv_image_set_src(boxart_, nullptr); +// The selected game's boxart, decoded once per selection (the launcher has +// already let go of the previous one). +const void *Gui::cover(size_t index) { if (boxart_buf_) { lv_draw_buf_destroy(boxart_buf_); boxart_buf_ = nullptr; } - if (path.empty()) { - return; - } - boxart_buf_ = decode_image(path); - if (boxart_buf_) { - lv_image_set_src(boxart_, boxart_buf_); + if (index < rom_infos_.size() && !rom_infos_[index].boxart_path.empty()) { + boxart_buf_ = decode_image(rom_infos_[index].boxart_path); } + return boxart_buf_; } +// boxart/consoles/.jpg on the card, if there is one (kept: the launcher +// asks again on every selection) +const void *Gui::console_art(const std::string &key) { + if (auto it = console_art_.find(key); it != console_art_.end()) return it->second; + lv_draw_buf_t *buf = nullptr; + const std::string path = std::string(Tab5Emu::mount_point) + "/boxart/consoles/" + key + ".jpg"; + std::error_code ec; + if (std::filesystem::exists(path, ec)) buf = decode_image(path); + console_art_[key] = buf; + return buf; +} + +// LVGL's JPEG decoder (TJPGD) only yields the image block by block, and LVGL +// cannot scale a block-decoded image, so decode it into a full RGB565 buffer +// here and show that. The POSIX fs driver is registered as 'S:' and passes +// the rest of the path through unchanged. lv_draw_buf_t *Gui::decode_image(const std::string &path) { const std::string src = "S:" + path; lv_image_decoder_dsc_t dsc{}; @@ -750,99 +424,3 @@ lv_draw_buf_t *Gui::decode_image(const std::string &path) { logger_.info("image '{}': {}x{}", path, w, h); return out; } - -void Gui::event_callback(lv_event_t *e) { - auto gui = static_cast(lv_event_get_user_data(e)); - if (!gui) { - return; - } - auto target = static_cast(lv_event_get_target(e)); - auto code = lv_event_get_code(e); - auto &emu = Tab5Emu::get(); - if (code == LV_EVENT_KEY) { - // on a game: left / right change the console, X (home) opens the picker - const auto key = lv_indev_get_key(lv_indev_active()); - if (key == LV_KEY_LEFT || key == LV_KEY_RIGHT) { - gui->step_console(key == LV_KEY_LEFT ? -1 : 1); - } else if (key == LV_KEY_HOME) { - gui->open_console_picker(); - } - return; - } - if (code == LV_EVENT_FOCUSED) { - // gamepad / keyboard: moving the focus through the list selects the game - for (size_t i = 0; i < gui->rom_buttons_.size(); i++) { - if (gui->rom_buttons_[i] == target) { - if (gui->focused_rom_ != (int)i) gui->select_rom(i); - return; - } - } - } else if (code == LV_EVENT_CLICKED) { - if (target == gui->play_button_) { - if (gui->focused_rom_ >= 0) { - gui->ready_to_play_ = true; - } - return; - } - for (size_t i = 0; i < gui->rom_buttons_.size(); i++) { - if (gui->rom_buttons_[i] == target) { - // a tap selects; enter on the already selected game (gamepad A / - // keyboard enter) starts it - const bool from_keypad = lv_indev_get_type(lv_indev_active()) == LV_INDEV_TYPE_KEYPAD; - if (from_keypad && gui->focused_rom_ == (int)i) { - gui->ready_to_play_ = true; - } else { - gui->select_rom(i); - } - return; - } - } - } else if (code == LV_EVENT_VALUE_CHANGED) { - // (saved to the SD card by the main loop once the changes stop) - auto &settings = AppSettings::get(); - if (target == gui->volume_slider_) { - const int v = lv_slider_get_value(gui->volume_slider_); - emu.volume(v); - settings.modify([v](Settings &s) { s.volume = v; }); - } else if (target == gui->brightness_slider_) { - const int v = lv_slider_get_value(gui->brightness_slider_); - emu.brightness(v); - settings.modify([v](Settings &s) { s.brightness = v; }); - } else if (target == gui->mute_switch_) { - const bool v = lv_obj_has_state(gui->mute_switch_, LV_STATE_CHECKED); - emu.mute(v); - settings.modify([v](Settings &s) { s.muted = v; }); - } else if (target == gui->usb_switch_) { - gui->set_usb_drive(lv_obj_has_state(gui->usb_switch_, LV_STATE_CHECKED)); - } else if (target == gui->video_dropdown_) { - const int v = lv_dropdown_get_selected(gui->video_dropdown_); - emu.video_setting(static_cast(v)); - settings.modify([v](Settings &s) { s.video_setting = v; }); - } else if (target == gui->resume_switch_) { - const bool v = lv_obj_has_state(gui->resume_switch_, LV_STATE_CHECKED); - settings.modify([v](Settings &s) { s.resume_last_save = v; }); - } - } -} - -// USB drive mode: hand the SD card to a PC. Nothing may touch the card -// meanwhile, so Play is disabled; when it ends the ROM list is reloaded so -// anything copied over shows up. -void Gui::set_usb_drive(bool on) { - auto &emu = Tab5Emu::get(); - if (on) { - if (!emu.initialize_usb_msc()) { - lv_obj_remove_state(usb_switch_, LV_STATE_CHECKED); - lv_label_set_text(usb_label_, "USB drive could not start (no SD card?)"); - return; - } - lv_obj_add_state(play_button_, LV_STATE_DISABLED); - lv_label_set_text(usb_label_, "Plug the USB-C port into a PC. Eject there, then switch off."); - } else { - emu.deinitialize_usb_msc(); - lv_obj_remove_state(play_button_, LV_STATE_DISABLED); - lv_label_set_text(usb_label_, "SD card as a USB drive on the USB-C port"); - update_rom_list(); - update_shared_state(); - } -} diff --git a/components/menu/CMakeLists.txt b/components/menu/CMakeLists.txt index ff158be..0e71a78 100644 --- a/components/menu/CMakeLists.txt +++ b/components/menu/CMakeLists.txt @@ -1,4 +1,4 @@ idf_component_register( INCLUDE_DIRS "include" SRC_DIRS "src" - REQUIRES lvgl timer logger tab5-emu statistics) + REQUIRES lvgl emu-ui timer logger tab5-emu statistics) diff --git a/components/menu/include/menu.hpp b/components/menu/include/menu.hpp index 0b58601..18d1478 100644 --- a/components/menu/include/menu.hpp +++ b/components/menu/include/menu.hpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include @@ -13,12 +14,14 @@ #include "high_resolution_timer.hpp" #include "logger.hpp" +#include "emu-ui/pause_menu.hpp" + #include "statistics.hpp" #include "tab5-emu.hpp" /// In-game pause menu: resume / reset / save / load / quit, a save slot /// selector with the slot's screenshot, and the shared volume / brightness / -/// video scaling settings. +/// video scaling settings. The screen is emu-ui's (shared with esp-box-emu). class Menu { public: static constexpr size_t MAX_SLOT = 5; @@ -31,6 +34,8 @@ class Menu { std::string paused_image_path; action_fn action_callback; slot_image_fn slot_image_callback; + std::string game_title; ///< in the menu's title bar + std::string console_key; ///< rom_info's ConsoleInfo::key: the background espp::Logger::Verbosity log_level{espp::Logger::Verbosity::WARN}; }; @@ -44,49 +49,34 @@ class Menu { void pause(); void resume(); - /// Click the button of an action as a tap on it would (the automated - /// launch tests) + /// Do an action as a tap on its row would (the automated launch tests) void click(Action action); protected: - void init_ui(); - void deinit_ui(); void update(); - void update_shared_state(); void update_slot_display(); void update_pause_image(); void on_volume(const std::vector &data); - static void event_callback(lv_event_t *e); - /// Load a "[w:u16be][h:u16be][rgb565]" screenshot file into an lv image - bool load_screenshot(const std::string &path, lv_obj_t *image, std::vector &storage, - lv_image_dsc_t &desc); + void on_action(emu_ui::PauseMenu::Action action); std::string paused_image_path_; action_fn action_callback_; slot_image_fn slot_image_callback_; + std::unique_ptr view_; - lv_obj_t *screen_{nullptr}; - lv_group_t *group_{nullptr}; ///< gamepad / keyboard focus order - lv_obj_t *pause_image_{nullptr}; - lv_obj_t *slot_image_{nullptr}; - lv_obj_t *slot_label_{nullptr}; - lv_obj_t *fps_label_{nullptr}; - lv_obj_t *volume_slider_{nullptr}; - lv_obj_t *mute_switch_{nullptr}; - lv_obj_t *brightness_slider_{nullptr}; - lv_obj_t *video_dropdown_{nullptr}; - lv_obj_t *btn_resume_{nullptr}; - lv_obj_t *btn_reset_{nullptr}; - lv_obj_t *btn_save_{nullptr}; - lv_obj_t *btn_load_{nullptr}; - lv_obj_t *btn_quit_{nullptr}; - lv_obj_t *btn_slot_prev_{nullptr}; - lv_obj_t *btn_slot_next_{nullptr}; /// screenshots are at most the largest native game frame (JK's 640x480 menu / HUD) static constexpr size_t SCREENSHOT_MAX_BYTES = 640 * 480 * 2; - std::vector pause_image_data_; + /// A screenshot's pixels, only while the menu is open: a game loading (JK's + /// level load) needs every MB of PSRAM it can get + struct ImageBuffer { + uint8_t *data{nullptr}; + std::span span() const { return data ? std::span(data, SCREENSHOT_MAX_BYTES) : std::span(); } + void allocate(); + void release(); + }; + ImageBuffer pause_image_data_; lv_image_dsc_t pause_image_desc_{}; - std::vector slot_image_data_; + ImageBuffer slot_image_data_; lv_image_dsc_t slot_image_desc_{}; std::atomic selected_slot_{0}; diff --git a/components/menu/src/menu.cpp b/components/menu/src/menu.cpp index 89b7a99..79cb1b9 100644 --- a/components/menu/src/menu.cpp +++ b/components/menu/src/menu.cpp @@ -1,19 +1,61 @@ #include "menu.hpp" -#include -#include +#include + +#include + +// The screenshot buffers (1.2 MB) are allocated when the menu opens and freed +// when it closes, not held while the game runs: Jedi Knight's level load +// needs that room. heap_caps_malloc does not throw: if a game leaves no +// 600 KB block, the menu shows no screenshot. +void Menu::ImageBuffer::allocate() { + if (!data) data = static_cast(heap_caps_malloc(SCREENSHOT_MAX_BYTES, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT)); +} + +void Menu::ImageBuffer::release() { + heap_caps_free(data); + data = nullptr; +} Menu::Menu(const Config &config) : paused_image_path_(config.paused_image_path) , action_callback_(config.action_callback) , slot_image_callback_(config.slot_image_callback) , logger_({.tag = "Menu", .level = config.log_level}) { - // the screenshot buffers are sized now, while the heap still has room: a - // running game (JK) can leave PSRAM without a 600 KB block, and a failed - // allocation on pause would throw std::bad_alloc (no way to recover there) - pause_image_data_.reserve(SCREENSHOT_MAX_BYTES); - slot_image_data_.reserve(SCREENSHOT_MAX_BYTES); - init_ui(); + using K = emu_ui::Row::Kind; + auto &emu = Tab5Emu::get(); + std::vector settings; + settings.push_back({.label = "Volume", .kind = K::SLIDER, .step = 5, + .get = [&emu] { return (int)std::lround(emu.volume()); }, + .set = [&emu](int v) { emu.volume(v); }, + .symbol = LV_SYMBOL_VOLUME_MAX}); + settings.push_back({.label = "Mute", .kind = K::TOGGLE, .get = [&emu] { return emu.is_muted() ? 1 : 0; }, + .set = [&emu](int v) { emu.mute(v != 0); }, + .symbol = LV_SYMBOL_MUTE}); + settings.push_back({.label = "Brightness", .kind = K::SLIDER, .min = 5, .step = 5, + .get = [&emu] { return (int)std::lround(emu.brightness()); }, + .set = [&emu](int v) { emu.brightness(v); }, + .symbol = LV_SYMBOL_EYE_OPEN}); + settings.push_back({.label = "Video scaling", .kind = K::CHOICE, .choices = {"Original", "Fit", "Fill"}, + .get = [&emu] { return (int)emu.video_setting(); }, + .set = [&emu](int v) { emu.video_setting(static_cast(v)); }, + .symbol = LV_SYMBOL_IMAGE}); + { + std::lock_guard lk(mutex_); + view_ = std::make_unique(emu_ui::PauseMenu::Config{ + .metrics = emu_ui::Metrics::large_1280x720(), + .keypad = emu.keypad_indev(), + .slots = static_cast(MAX_SLOT) + 1, + .on_action = [this](emu_ui::PauseMenu::Action a) { on_action(a); }, + .on_slot = + [this](int slot) { + selected_slot_ = slot; + update_slot_display(); + }, + .settings = std::move(settings), + }); + view_->set_game(config.game_title, config.console_key); + } using namespace std::placeholders; espp::EventManager::get().add_subscriber(volume_changed_topic, "menu", std::bind(&Menu::on_volume, this, _1), 4 * 1024); logger_.info("Menu created"); @@ -22,15 +64,18 @@ Menu::Menu(const Config &config) Menu::~Menu() { espp::EventManager::get().remove_subscriber(volume_changed_topic, "menu"); task_.stop(); - deinit_ui(); + std::lock_guard lk(mutex_); + view_.reset(); + pause_image_data_.release(); + slot_image_data_.release(); } void Menu::select_slot(int slot) { - if (slot < 0) - slot = MAX_SLOT; - if (slot > (int)MAX_SLOT) - slot = 0; + if (slot < 0) slot = MAX_SLOT; + if (slot > (int)MAX_SLOT) slot = 0; selected_slot_ = slot; + std::lock_guard lk(mutex_); + view_->set_slot(slot); // (calls on_slot when it changes) update_slot_display(); } @@ -39,29 +84,45 @@ void Menu::pause() { task_.stop(); // wait out a timer callback already in lv_timer_handler() (stop() does not) std::lock_guard lk(mutex_); + // the game gets the screenshots' room back + view_->set_pause_image(nullptr); + view_->set_slot_image(nullptr); + pause_image_data_.release(); + slot_image_data_.release(); } void Menu::resume() { std::lock_guard lk(mutex_); - update_shared_state(); + pause_image_data_.allocate(); + slot_image_data_.allocate(); + if (!pause_image_data_.data || !slot_image_data_.data) { + logger_.warn("No room for the menu's screenshots (PSRAM largest block {} KB)", + heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM) / 1024); + } update_pause_image(); update_slot_display(); - lv_label_set_text_fmt(fps_label_, "%.1f FPS", get_fps()); - lv_screen_load(screen_); - lv_obj_invalidate(screen_); - if (auto *keypad = Tab5Emu::get().keypad_indev(); keypad && group_) { - lv_indev_set_group(keypad, group_); - lv_group_focus_obj(btn_resume_); - } + view_->set_fps(get_fps()); + const auto battery = Tab5Emu::get().battery_status(); + view_->set_battery((int)std::lround(battery.charge_percent), battery.is_charging); + view_->show(); + lv_obj_invalidate(view_->screen()); task_.periodic(16 * 1000); paused_ = false; } void Menu::click(Action action) { std::lock_guard lk(mutex_); - lv_obj_t *const buttons[] = {btn_resume_, btn_reset_, btn_save_, btn_load_, btn_quit_}; - if (auto *btn = buttons[static_cast(action)]) { - lv_obj_send_event(btn, LV_EVENT_CLICKED, nullptr); + view_->click(static_cast(action)); +} + +void Menu::on_action(emu_ui::PauseMenu::Action a) { + // (the same order: RESUME, RESET, SAVE, LOAD, QUIT) + const auto action = static_cast(a); + action_callback_(action); + if (action == Action::SAVE) { + update_slot_display(); // the new screenshot + } else if (action == Action::LOAD) { + update_pause_image(); // the loaded state } } @@ -74,230 +135,17 @@ void Menu::update() { void Menu::on_volume(const std::vector &) { std::lock_guard lk(mutex_); - update_shared_state(); -} - -void Menu::update_shared_state() { - auto &emu = Tab5Emu::get(); - lv_slider_set_value(volume_slider_, (int)emu.volume(), LV_ANIM_OFF); - if (emu.is_muted()) - lv_obj_add_state(mute_switch_, LV_STATE_CHECKED); - else - lv_obj_remove_state(mute_switch_, LV_STATE_CHECKED); - lv_slider_set_value(brightness_slider_, (int)emu.brightness(), LV_ANIM_OFF); - lv_dropdown_set_selected(video_dropdown_, (int)emu.video_setting()); -} - -bool Menu::load_screenshot(const std::string &path, lv_obj_t *image, std::vector &storage, - lv_image_dsc_t &desc) { - // stdio, not ifstream: a read error (EIO from the card) makes libstdc++'s - // filebuf throw, and exceptions are off, so that would abort - FILE *file = fopen(path.c_str(), "rb"); - if (!file) { - lv_image_set_src(image, nullptr); - return false; - } - uint8_t header[4]; - const bool header_ok = fread(header, 1, sizeof(header), file) == sizeof(header); - uint16_t w = (header[0] << 8) | header[1]; - uint16_t h = (header[2] << 8) | header[3]; - if (!header_ok || w == 0 || h == 0 || w > 2048 || h > 2048 || (size_t)w * h * 2 > storage.capacity()) { - fclose(file); - lv_image_set_src(image, nullptr); - return false; - } - storage.resize((size_t)w * h * 2); // within the reserved capacity: no allocation - const bool data_ok = fread(storage.data(), 1, storage.size(), file) == storage.size(); - fclose(file); - if (!data_ok) { - lv_image_set_src(image, nullptr); - return false; - } - memset(&desc, 0, sizeof(desc)); - desc.header.magic = LV_IMAGE_HEADER_MAGIC; - desc.header.cf = LV_COLOR_FORMAT_RGB565; - desc.header.w = w; - desc.header.h = h; - desc.header.stride = w * 2; - desc.data_size = storage.size(); - desc.data = storage.data(); - lv_image_set_src(image, &desc); - return true; + view_->refresh_settings(); } void Menu::update_pause_image() { - load_screenshot(paused_image_path_, pause_image_, pause_image_data_, pause_image_desc_); + const bool ok = emu_ui::load_screenshot(paused_image_path_.c_str(), pause_image_data_.span(), pause_image_desc_); + view_->set_pause_image(ok ? &pause_image_desc_ : nullptr); } void Menu::update_slot_display() { std::lock_guard lk(mutex_); - lv_label_set_text_fmt(slot_label_, "Slot %d", (int)selected_slot_); - auto path = slot_image_callback_ ? slot_image_callback_() : ""; - if (path.empty() || !load_screenshot(path, slot_image_, slot_image_data_, slot_image_desc_)) { - lv_image_set_src(slot_image_, nullptr); - } -} - -void Menu::init_ui() { - std::lock_guard lk(mutex_); - screen_ = lv_obj_create(nullptr); - lv_obj_set_style_bg_color(screen_, lv_color_hex(0x101418), 0); - lv_obj_remove_flag(screen_, LV_OBJ_FLAG_SCROLLABLE); - const int W = Tab5Emu::lcd_width(), H = Tab5Emu::lcd_height(); - - auto title = lv_label_create(screen_); - lv_label_set_text(title, "Paused"); - lv_obj_set_style_text_font(title, &lv_font_montserrat_32, 0); - lv_obj_set_style_text_color(title, lv_color_white(), 0); - lv_obj_align(title, LV_ALIGN_TOP_LEFT, 24, 16); - - fps_label_ = lv_label_create(screen_); - lv_label_set_text(fps_label_, ""); - lv_obj_set_style_text_font(fps_label_, &lv_font_montserrat_20, 0); - lv_obj_set_style_text_color(fps_label_, lv_color_white(), 0); - lv_obj_align(fps_label_, LV_ALIGN_TOP_RIGHT, -24, 22); - - // paused game image (left) - pause_image_ = lv_image_create(screen_); - lv_obj_set_size(pause_image_, 480, 360); - lv_image_set_inner_align(pause_image_, LV_IMAGE_ALIGN_CONTAIN); - lv_obj_align(pause_image_, LV_ALIGN_TOP_LEFT, 24, 80); - - // save slot (left, below) - btn_slot_prev_ = lv_button_create(screen_); - lv_obj_set_size(btn_slot_prev_, 64, 48); - lv_obj_align(btn_slot_prev_, LV_ALIGN_TOP_LEFT, 24, 460); - lv_label_set_text(lv_label_create(btn_slot_prev_), LV_SYMBOL_LEFT); - lv_obj_center(lv_obj_get_child(btn_slot_prev_, 0)); - lv_obj_add_event_cb(btn_slot_prev_, event_callback, LV_EVENT_CLICKED, this); - - slot_label_ = lv_label_create(screen_); - lv_label_set_text(slot_label_, "Slot 0"); - lv_obj_set_style_text_font(slot_label_, &lv_font_montserrat_24, 0); - lv_obj_set_style_text_color(slot_label_, lv_color_white(), 0); - lv_obj_align(slot_label_, LV_ALIGN_TOP_LEFT, 110, 470); - - btn_slot_next_ = lv_button_create(screen_); - lv_obj_set_size(btn_slot_next_, 64, 48); - lv_obj_align(btn_slot_next_, LV_ALIGN_TOP_LEFT, 220, 460); - lv_label_set_text(lv_label_create(btn_slot_next_), LV_SYMBOL_RIGHT); - lv_obj_center(lv_obj_get_child(btn_slot_next_, 0)); - lv_obj_add_event_cb(btn_slot_next_, event_callback, LV_EVENT_CLICKED, this); - - slot_image_ = lv_image_create(screen_); - lv_obj_set_size(slot_image_, 240, 180); - lv_image_set_inner_align(slot_image_, LV_IMAGE_ALIGN_CONTAIN); - lv_obj_align(slot_image_, LV_ALIGN_TOP_LEFT, 300, 460); - - // actions (center) - auto actions = lv_obj_create(screen_); - lv_obj_set_size(actions, 300, H - 100); - lv_obj_align(actions, LV_ALIGN_TOP_MID, 100, 76); - lv_obj_set_flex_flow(actions, LV_FLEX_FLOW_COLUMN); - lv_obj_set_style_pad_row(actions, 16, 0); - auto make_button = [&](const char *text) { - auto b = lv_button_create(actions); - lv_obj_set_size(b, lv_pct(100), 64); - auto l = lv_label_create(b); - lv_label_set_text(l, text); - lv_obj_set_style_text_font(l, &lv_font_montserrat_24, 0); - lv_obj_center(l); - lv_obj_add_event_cb(b, event_callback, LV_EVENT_CLICKED, this); - return b; - }; - btn_resume_ = make_button(LV_SYMBOL_PLAY " Resume"); - btn_save_ = make_button(LV_SYMBOL_SAVE " Save"); - btn_load_ = make_button(LV_SYMBOL_UPLOAD " Load"); - btn_reset_ = make_button(LV_SYMBOL_REFRESH " Reset"); - btn_quit_ = make_button(LV_SYMBOL_CLOSE " Quit"); - - // settings (right) - auto settings = lv_obj_create(screen_); - lv_obj_set_size(settings, W / 4, H - 100); - lv_obj_align(settings, LV_ALIGN_TOP_RIGHT, -24, 76); - lv_obj_set_flex_flow(settings, LV_FLEX_FLOW_COLUMN); - lv_obj_set_style_pad_row(settings, 18, 0); - auto make_label = [&](const char *text) { - auto l = lv_label_create(settings); - lv_label_set_text(l, text); - lv_obj_set_style_text_font(l, &lv_font_montserrat_20, 0); - return l; - }; - make_label(LV_SYMBOL_VOLUME_MAX " Volume"); - volume_slider_ = lv_slider_create(settings); - lv_obj_set_width(volume_slider_, lv_pct(90)); - lv_slider_set_range(volume_slider_, 0, 100); - lv_obj_add_event_cb(volume_slider_, event_callback, LV_EVENT_VALUE_CHANGED, this); - make_label(LV_SYMBOL_MUTE " Mute"); - mute_switch_ = lv_switch_create(settings); - lv_obj_add_event_cb(mute_switch_, event_callback, LV_EVENT_VALUE_CHANGED, this); - make_label(LV_SYMBOL_EYE_OPEN " Brightness"); - brightness_slider_ = lv_slider_create(settings); - lv_obj_set_width(brightness_slider_, lv_pct(90)); - lv_slider_set_range(brightness_slider_, 5, 100); - lv_obj_add_event_cb(brightness_slider_, event_callback, LV_EVENT_VALUE_CHANGED, this); - make_label(LV_SYMBOL_IMAGE " Video scaling"); - video_dropdown_ = lv_dropdown_create(settings); - lv_dropdown_set_options(video_dropdown_, "Original\nFit\nFill"); - lv_obj_set_width(video_dropdown_, lv_pct(90)); - lv_obj_add_event_cb(video_dropdown_, event_callback, LV_EVENT_VALUE_CHANGED, this); - - // gamepad / keyboard focus order (see Tab5Emu::keypad_indev()) - group_ = lv_group_create(); - for (auto *o : {btn_resume_, btn_save_, btn_load_, btn_reset_, btn_quit_, btn_slot_prev_, btn_slot_next_, volume_slider_, - mute_switch_, brightness_slider_, video_dropdown_}) { - lv_group_add_obj(group_, o); - } - lv_group_set_wrap(group_, true); -} - -void Menu::deinit_ui() { - std::lock_guard lk(mutex_); - if (group_) { - if (auto *keypad = Tab5Emu::get().keypad_indev(); keypad && lv_indev_get_group(keypad) == group_) { - lv_indev_set_group(keypad, nullptr); - } - lv_group_delete(group_); - group_ = nullptr; - } - if (screen_) { - lv_obj_delete(screen_); - screen_ = nullptr; - } -} - -void Menu::event_callback(lv_event_t *e) { - auto menu = static_cast(lv_event_get_user_data(e)); - if (!menu) { - return; - } - auto target = static_cast(lv_event_get_target(e)); - auto code = lv_event_get_code(e); - auto &emu = Tab5Emu::get(); - if (code == LV_EVENT_CLICKED) { - if (target == menu->btn_resume_) - menu->action_callback_(Action::RESUME); - else if (target == menu->btn_reset_) - menu->action_callback_(Action::RESET); - else if (target == menu->btn_save_) { - menu->action_callback_(Action::SAVE); - menu->update_slot_display(); - } else if (target == menu->btn_load_) - menu->action_callback_(Action::LOAD); - else if (target == menu->btn_quit_) - menu->action_callback_(Action::QUIT); - else if (target == menu->btn_slot_prev_) - menu->select_slot(menu->selected_slot_ - 1); - else if (target == menu->btn_slot_next_) - menu->select_slot(menu->selected_slot_ + 1); - } else if (code == LV_EVENT_VALUE_CHANGED) { - if (target == menu->volume_slider_) - emu.volume(lv_slider_get_value(menu->volume_slider_)); - else if (target == menu->mute_switch_) - emu.mute(lv_obj_has_state(menu->mute_switch_, LV_STATE_CHECKED)); - else if (target == menu->brightness_slider_) - emu.brightness(lv_slider_get_value(menu->brightness_slider_)); - else if (target == menu->video_dropdown_) - emu.video_setting(static_cast(lv_dropdown_get_selected(menu->video_dropdown_))); - } + const auto path = slot_image_callback_ ? slot_image_callback_() : std::string{}; + const bool ok = !path.empty() && emu_ui::load_screenshot(path.c_str(), slot_image_data_.span(), slot_image_desc_); + view_->set_slot_image(ok ? &slot_image_desc_ : nullptr); } diff --git a/components/rom_info/include/rom_info.hpp b/components/rom_info/include/rom_info.hpp index 8988164..b3b7239 100644 --- a/components/rom_info/include/rom_info.hpp +++ b/components/rom_info/include/rom_info.hpp @@ -29,20 +29,16 @@ enum class Console : uint8_t { UNKNOWN }; -/// The shape the firmware draws for a console that has no art on the SD card. -enum class ConsoleShape : uint8_t { GAMEPAD, HANDHELD_TALL, HANDHELD_WIDE, DISC, COMPUTER, FANTASY }; - struct ConsoleInfo { const char *name; ///< shown in the list header and the badge const char *short_name; ///< for a small screen's badge - const char *key; ///< art on the SD card: boxart/consoles/.jpg - uint32_t color; ///< badge / header accent (0xRRGGBB) - ConsoleShape shape; + const char *key; ///< art on the SD card (boxart/consoles/.jpg) and + ///< the launcher's look (emu_ui::console_style) }; /// The console `platform` games are grouped under. Console console_of(Emulator platform); -/// Name, art key and colors of `console`. +/// Name and key of `console`. const ConsoleInfo &console_info(Console console); /// Parse the metadata csv (rom_path, boxart_path, name) relative to the SD diff --git a/components/rom_info/src/rom_info.cpp b/components/rom_info/src/rom_info.cpp index d55a688..8cf5bf5 100644 --- a/components/rom_info/src/rom_info.cpp +++ b/components/rom_info/src/rom_info.cpp @@ -163,19 +163,19 @@ Console console_of(Emulator platform) { const ConsoleInfo &console_info(Console console) { static const ConsoleInfo infos[] = { - {"NES", "NES", "nes", 0xB22222, ConsoleShape::GAMEPAD}, - {"Super Nintendo", "SNES", "snes", 0x6A5ACD, ConsoleShape::GAMEPAD}, - {"Game Boy", "Game Boy", "gb", 0x5B7F3A, ConsoleShape::HANDHELD_TALL}, - {"Game Boy Color", "GB Color", "gbc", 0x8E44AD, ConsoleShape::HANDHELD_TALL}, - {"Game Boy Advance", "GBA", "gba", 0x4B3FA8, ConsoleShape::HANDHELD_WIDE}, - {"Master System", "SMS", "sms", 0x1F5FAF, ConsoleShape::GAMEPAD}, - {"Game Gear", "Game Gear", "gg", 0x4F6D8F, ConsoleShape::HANDHELD_WIDE}, - {"Sega Genesis", "Genesis", "genesis", 0xC8102E, ConsoleShape::GAMEPAD}, - {"MSX", "MSX", "msx", 0x3A7D7D, ConsoleShape::COMPUTER}, - {"PlayStation", "PlayStation", "playstation", 0x2E6DB4, ConsoleShape::DISC}, - {"PC", "PC", "pc", 0x5A6B7B, ConsoleShape::COMPUTER}, - {"PICO-8", "PICO-8", "pico8", 0xFF004D, ConsoleShape::FANTASY}, - {"Other", "Other", "other", 0x606060, ConsoleShape::GAMEPAD}, + {"NES", "NES", "nes"}, + {"Super Nintendo", "SNES", "snes"}, + {"Game Boy", "Game Boy", "gb"}, + {"Game Boy Color", "GB Color", "gbc"}, + {"Game Boy Advance", "GBA", "gba"}, + {"Master System", "SMS", "sms"}, + {"Game Gear", "Game Gear", "gg"}, + {"Sega Genesis", "Genesis", "genesis"}, + {"MSX", "MSX", "msx"}, + {"PlayStation", "PlayStation", "playstation"}, + {"PC", "PC", "pc"}, + {"PICO-8", "PICO-8", "pico8"}, + {"Other", "Other", "other"}, }; const auto i = static_cast(console); return infos[i < std::size(infos) ? i : std::size(infos) - 1]; diff --git a/components/tab5-emu/src/tab5-emu.cpp b/components/tab5-emu/src/tab5-emu.cpp index 5c5901f..8ff276c 100644 --- a/components/tab5-emu/src/tab5-emu.cpp +++ b/components/tab5-emu/src/tab5-emu.cpp @@ -369,21 +369,22 @@ void Tab5Emu::keypad_read(lv_indev_t *indev, lv_indev_data_t *data) { st.x |= key(9); // f: the launcher's console filter } // left / right adjust a focused slider or dropdown, otherwise move focus - bool horizontal_widget = false; + bool horizontal_widget = false, all_keys = false; if (auto *group = lv_indev_get_group(indev)) { if (auto *focused = lv_group_get_focused(group)) { - // (an object flagged LV_OBJ_FLAG_USER_1 takes left / right as keys too: - // the launcher's games change the console with them) - horizontal_widget = lv_obj_check_type(focused, &lv_slider_class) || lv_obj_check_type(focused, &lv_dropdown_class) || - lv_obj_check_type(focused, &lv_switch_class) || lv_obj_has_flag(focused, LV_OBJ_FLAG_USER_1); + // (an object flagged LV_OBJ_FLAG_USER_1 takes every arrow as a key, + // not a focus move: emu-ui's game list, rows and console picker) + all_keys = lv_obj_has_flag(focused, LV_OBJ_FLAG_USER_1); + horizontal_widget = all_keys || lv_obj_check_type(focused, &lv_slider_class) || + lv_obj_check_type(focused, &lv_dropdown_class) || lv_obj_check_type(focused, &lv_switch_class); } } uint32_t key = 0; if (st.a) key = LV_KEY_ENTER; else if (st.b) key = LV_KEY_ESC; else if (st.x) key = LV_KEY_HOME; // (the launcher's console picker) - else if (st.up) key = LV_KEY_PREV; - else if (st.down) key = LV_KEY_NEXT; + else if (st.up) key = all_keys ? LV_KEY_UP : LV_KEY_PREV; + else if (st.down) key = all_keys ? LV_KEY_DOWN : LV_KEY_NEXT; else if (st.left) key = horizontal_widget ? LV_KEY_LEFT : LV_KEY_PREV; else if (st.right) key = horizontal_widget ? LV_KEY_RIGHT : LV_KEY_NEXT; if (key) { diff --git a/docs/PLAN.md b/docs/PLAN.md index 5a8ac96..c65f8a2 100644 --- a/docs/PLAN.md +++ b/docs/PLAN.md @@ -183,10 +183,13 @@ not PSRAM. Rules that keep everything booting: - Emulator cores keep no static state in internal RAM (`bss_to_psram.py` for .bss; big initialized tables are `const` so they live in flash). -- Plain `malloc` of >256 bytes goes to PSRAM - (`CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL=256`); anything that needs internal - or DMA memory asks for it explicitly. JK's level load otherwise drained - the DMA heap and SD reads failed. +- Plain `malloc` / `new` of any size goes to PSRAM first + (`CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL=0`, as on the box); anything that + needs internal or DMA memory asks for it explicitly. JK's level load + otherwise drained the DMA heap and SD reads failed. (It was 256 until + 2026-11: every allocation of 256 bytes or less went to internal RAM first, + and the emu-ui launcher's game list alone then left Metal Gear Solid with + ~500 bytes of DMA memory and a black screen.) - The 64 KB video tile is allocated at boot and kept; allocating it at the first frame fell back to PSRAM once the GUI had fragmented the heap (JK dropped from 38 to 21 fps). diff --git a/main/cart.hpp b/main/cart.hpp index 8e1238f..61167e4 100644 --- a/main/cart.hpp +++ b/main/cart.hpp @@ -58,6 +58,8 @@ class Cart { .paused_image_path = get_paused_image_path(), .action_callback = std::bind(&Cart::on_menu_action, this, std::placeholders::_1), .slot_image_callback = [this]() -> std::string { return get_screenshot_path(false); }, + .game_title = info_.name, + .console_key = console_info(console_of(info_.platform)).key, .log_level = espp::Logger::Verbosity::WARN}); std::error_code ec; @@ -72,6 +74,9 @@ class Cart { Tab5Emu::get().free_romdata(); } + /// Where the save states are (the launcher counts them) + static std::string save_dir() { return FS_PREFIX + "/" + SAVE_DIR; } + std::string get_rom_filename() const { return info_.rom_path; } virtual void reset() { logger_.info("Base reset"); } diff --git a/main/main.cpp b/main/main.cpp index 1abfa64..0603141 100644 --- a/main/main.cpp +++ b/main/main.cpp @@ -165,7 +165,7 @@ extern "C" void app_main(void) { logger.info("initializing gui..."); // initialize the gui - Gui gui({.log_level = espp::Logger::Verbosity::WARN}); + Gui gui({.save_dir = Cart::save_dir(), .log_level = espp::Logger::Verbosity::WARN}); internal_free_log("gui"); // the USB link's services (core dump, system, monitor) and the test control diff --git a/sdkconfig.defaults b/sdkconfig.defaults index d477104..b5c59db 100644 --- a/sdkconfig.defaults +++ b/sdkconfig.defaults @@ -30,7 +30,7 @@ CONFIG_ESP_TASK_WDT_EN=n CONFIG_ESP_MAIN_TASK_STACK_SIZE=16384 CONFIG_ESP_SYSTEM_EVENT_TASK_STACK_SIZE=4096 -CONFIG_ESP_TIMER_TASK_STACK_SIZE=6144 +CONFIG_ESP_TIMER_TASK_STACK_SIZE=8192 CONFIG_ESP_SYSTEM_USE_FRAME_POINTER=y CONFIG_FREERTOS_HZ=1000 @@ -48,10 +48,13 @@ CONFIG_SPIRAM=y CONFIG_SPIRAM_SPEED_200M=y CONFIG_SPIRAM_XIP_FROM_PSRAM=y CONFIG_SPIRAM_USE_MALLOC=y -# anything larger than this is attempted to allocate within SPIRAM first -# small plain-malloc allocations (LVGL objects, strings) go to PSRAM too: -# internal RAM is the scarce resource on the P4 (SD DMA buffers, USB, tiles) -CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL=256 +# Every plain malloc / new goes to PSRAM first, whatever its size (as on the +# box): internal RAM is the scarce resource on the P4 (SD DMA buffers, USB, +# tiles), and code that needs internal or DMA memory asks for it with +# heap_caps_malloc. (256 sent everything of 256 bytes or less to internal RAM +# first: the launcher's game titles, every small std::string and map node, +# which left Metal Gear Solid without DMA memory.) +CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL=0 # reserve internal memory for DMA / task stacks CONFIG_SPIRAM_MALLOC_RESERVE_INTERNAL=131072 CONFIG_SPIRAM_ALLOW_STACK_EXTERNAL_MEMORY=y