From 12d6894be19471f1d52184abbf8660f20b96d8f1 Mon Sep 17 00:00:00 2001
From: William Emfinger
Date: Thu, 12 Nov 2026 23:42:10 -0600
Subject: [PATCH 01/15] Launcher: console filter and quick console navigation
- Left / right on the game list jump to the previous / next console (the
game buttons take left / right as keys: LV_OBJ_FLAG_USER_1 in
Tab5Emu::keypad_read()).
- The console above the boxart opens a console picker (tap it, X on a
gamepad, F on a keyboard): all consoles, or only one console's games.
The console is outlined while the list is filtered, and left / right
then move the filter. Launching a game the filter hides lifts it.
- The selected game is highlighted in the list (the theme has no checked
style for list buttons, so it was not).
- USB link (protocol 3, same remote_control.hpp / emulink as the box):
CONSOLE_FILTER, the filter in STATUS, launcher screenshots.
Co-Authored-By: Claude Opus 5.5 (1M context)
Claude-Session: https://claude.ai/code/session_01SFCMzomCZ5wRHJN4sxwkvY
---
README.md | 8 +
components/gui/include/gui.hpp | 32 +++-
components/gui/src/gui.cpp | 268 ++++++++++++++++++++++++++-
components/tab5-emu/src/tab5-emu.cpp | 6 +-
main/remote_control.hpp | 77 ++++++--
tools/emulink/emulink/cli.py | 12 +-
tools/emulink/emulink/control.py | 15 +-
7 files changed, 388 insertions(+), 30 deletions(-)
diff --git a/README.md b/README.md
index 74777fa..69baf79 100644
--- a/README.md
+++ b/README.md
@@ -224,6 +224,14 @@ DualShock numbering, Backbone Pro quirks. Keyboards: arrows, Z/X/A/S, Enter,
Shift/Backspace, Q/W (L/R) and E/R (L2/R2) map to the gamepad for the
emulators.
+In the launcher, left / right on the game list go to the previous / next
+console's games. Tapping the console above the boxart (or X on a gamepad, F
+on a keyboard) opens the console picker, which shows only one console's
+games, or all of them again; an outline on the console means the list is
+filtered, and left / right then move the filter to the next console.
+`emulink filter ` (snes, gba, genesis, playstation, pc, pico8 or
+all) does the same over USB.
+
Jedi Knight gets the full keyboard and mouse look; on a gamepad the left
stick strafes, the right stick looks, R = fire, L = secondary fire, A =
activate, B = jump, X = crouch, Y = use item.
diff --git a/components/gui/include/gui.hpp b/components/gui/include/gui.hpp
index a76251f..7fef744 100644
--- a/components/gui/include/gui.hpp
+++ b/components/gui/include/gui.hpp
@@ -64,14 +64,36 @@ class Gui {
return rom_infos_;
}
- /// Select the first game whose name or rom path contains `text`
+ /// Select the first game whose name or rom path contains `text` (a game
+ /// the console filter hides lifts the filter)
bool select_rom_matching(std::string_view text);
+ /// The consoles that have games, in list order.
+ std::vector consoles() const;
+ /// The console whose games the list shows, if it is filtered.
+ std::optional console_filter() const;
+ /// Show only `console`'s games (nullopt: every console's); false if it has none.
+ bool set_console_filter(std::optional console);
+
+ /// The launcher screen (RGB565, little endian, rows packed), for the USB
+ /// link's screenshot when no game runs; empty if it cannot be drawn.
+ struct Snapshot {
+ size_t width{0}, height{0};
+ std::vector pixels;
+ };
+ 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);
void update();
void on_volume(const std::vector &data);
@@ -108,7 +130,13 @@ class Gui {
lv_obj_t *video_dropdown_{nullptr};
lv_obj_t *resume_switch_{nullptr};
lv_obj_t *battery_label_{nullptr};
- std::vector rom_buttons_;
+ 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::string metadata_filename_;
std::filesystem::file_time_type metadata_last_modified_{};
diff --git a/components/gui/src/gui.cpp b/components/gui/src/gui.cpp
index f453e6a..54687b1 100644
--- a/components/gui/src/gui.cpp
+++ b/components/gui/src/gui.cpp
@@ -17,7 +17,7 @@ Gui::Gui(const Config &config)
// 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()) {
+ 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_),
@@ -53,7 +53,7 @@ void Gui::resume() {
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()) {
+ 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_),
@@ -146,6 +146,13 @@ void Gui::init_ui() {
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);
@@ -268,24 +275,55 @@ void Gui::update_rom_list() {
break;
}
}
+ build_list(focused_rom_);
+}
+
+// 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 game 0: keep the one to select)
- const int keep_rom = focused_rom_;
+ // event selects that game: keep_rom is selected at the end)
lv_obj_clean(rom_list_);
- rom_buttons_.clear();
+ rom_buttons_.assign(rom_infos_.size(), nullptr);
if (group_) {
lv_group_remove_all_objs(group_);
}
+ int last_console = -1;
for (size_t i = 0; i < rom_infos_.size(); i++) {
+ if (!shown(i)) continue;
const Console console = console_of(rom_infos_[i].platform);
- if (i == 0 || console != console_of(rom_infos_[i - 1].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(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);
- rom_buttons_.push_back(btn);
+ 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_) {
@@ -294,7 +332,8 @@ void Gui::update_rom_list() {
if (o) lv_group_add_obj(group_, o);
}
}
- if (rom_infos_.empty()) {
+ 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_, "");
@@ -302,8 +341,198 @@ void Gui::update_rom_list() {
lv_obj_clean(console_area_);
shown_console_ = -1;
} else {
- select_rom(std::clamp(keep_rom, 0, rom_infos_.size() - 1));
+ select_rom(keep_rom);
+ }
+}
+
+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)
+ }
+ return out;
+}
+
+std::optional Gui::console_filter() const {
+ std::lock_guard lk(mutex_);
+ if (filter_ < 0) return std::nullopt;
+ return static_cast(filter_);
+}
+
+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;
+}
+
+// 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() {
+ 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_]);
+ }
+ }
+}
+
+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)));
+ }
+}
+
+Gui::Snapshot Gui::snapshot() {
+ std::lock_guard lk(mutex_);
+ Snapshot shot;
+ auto *screen = lv_screen_active();
+ if (!screen) {
+ return shot;
+ }
+ lv_obj_update_layout(screen);
+ const int32_t w = lv_obj_get_width(screen), h = lv_obj_get_height(screen);
+ const uint32_t stride = lv_draw_buf_width_to_stride(w, LV_COLOR_FORMAT_RGB565);
+ shot.pixels.resize(stride * h);
+ lv_draw_buf_t buf;
+ if (lv_draw_buf_init(&buf, w, h, LV_COLOR_FORMAT_RGB565, stride, shot.pixels.data(), shot.pixels.size()) !=
+ LV_RESULT_OK ||
+ lv_snapshot_take_to_draw_buf(screen, LV_COLOR_FORMAT_RGB565, &buf) != LV_RESULT_OK) {
+ shot.pixels.clear();
+ return shot;
+ }
+ // (rows packed: the reader expects w * 2 bytes per row)
+ if (stride != static_cast(w) * 2) {
+ for (int32_t y = 1; y < h; y++) {
+ memmove(shot.pixels.data() + y * w * 2, shot.pixels.data() + y * stride, w * 2);
+ }
+ shot.pixels.resize(w * h * 2);
}
+ shot.width = w;
+ shot.height = h;
+ return shot;
}
// A non-selectable row in the game list starting a console's group: the
@@ -349,10 +578,12 @@ void Gui::show_console(Console console) {
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) {
@@ -364,6 +595,11 @@ bool Gui::select_rom_matching(std::string_view text) {
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
+ if (filter_ >= 0 && static_cast(console_of(rom.platform)) != filter_) {
+ filter_ = -1;
+ build_list(i);
+ }
select_rom(i);
return true;
}
@@ -379,13 +615,15 @@ void Gui::select_rom(int index) {
}
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() && lv_group_get_focused(group_) != rom_buttons_[index]) {
+ 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];
@@ -464,6 +702,16 @@ void Gui::event_callback(lv_event_t *e) {
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++) {
diff --git a/components/tab5-emu/src/tab5-emu.cpp b/components/tab5-emu/src/tab5-emu.cpp
index d50243a..b8ad249 100644
--- a/components/tab5-emu/src/tab5-emu.cpp
+++ b/components/tab5-emu/src/tab5-emu.cpp
@@ -337,18 +337,22 @@ void Tab5Emu::keypad_read(lv_indev_t *indev, lv_indev_data_t *data) {
st.right |= key(79);
st.a |= key(40) | key(88) | key(44); // enter, keypad enter, space
st.b |= key(41); // escape
+ 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;
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_check_type(focused, &lv_switch_class) || lv_obj_has_flag(focused, LV_OBJ_FLAG_USER_1);
}
}
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.left) key = horizontal_widget ? LV_KEY_LEFT : LV_KEY_PREV;
diff --git a/main/remote_control.hpp b/main/remote_control.hpp
index 00c3bf6..fb80e28 100644
--- a/main/remote_control.hpp
+++ b/main/remote_control.hpp
@@ -111,7 +111,7 @@ class RemoteControl {
public:
static constexpr uint8_t kModule = 0x20;
static constexpr const char *kProtocol = "emu.control";
- static constexpr uint16_t kProtocolVersion = 2; // 2: in-memory screenshots
+ static constexpr uint16_t kProtocolVersion = 3; // 2: in-memory screenshots, 3: console filter, launcher screenshots
enum class Type : uint8_t {
STATUS = 0x01, ///< () -> {state, rom, platform, console, heap, uptime, ...}
@@ -123,13 +123,18 @@ class RemoteControl {
LOAD = 0x07, ///< (u8 slot)
/// (path: text, optional). With a path: saved there on the card as
/// [u16be w][u16be h][RGB565] -> {path}. Without: -> {width, height, size,
- /// format: rgb565le}, and the game holds still (its frame buffer with it)
- /// while SCREENSHOT_READ reads the pixels, until the last of them is read.
+ /// format: rgb565le, source: game | launcher}, and the game holds still
+ /// (its frame buffer with it) while SCREENSHOT_READ reads the pixels,
+ /// until the last of them is read; with no game running, the launcher's
+ /// screen is drawn into a copy instead.
SCREENSHOT = 0x08,
USB_DRIVE = 0x09, ///< (u8 1 = the PC gets the SD card, 0 = the device takes it back)
RELOAD_ROMS = 0x0A, ///< () re-read metadata.csv
ENTER_UPDATER = 0x0B, ///< () reboot into the updater app (ota_1) for an update
SCREENSHOT_READ = 0x0C, ///< (u32 offset, u16 length) -> raw bytes of the held SCREENSHOT (short at the end)
+ /// (console key: text, e.g. "snes"; empty or "all" for every console) ->
+ /// {filter, consoles: [keys]}: the launcher's list shows only that console's games
+ CONSOLE_FILTER = 0x0D,
FILE_LIST = 0x10, ///< (path[\0offset]) -> {entries: [{name, dir, size}], truncated?, next?}
FILE_READ = 0x11, ///< (u32 offset, u16 length, path) -> raw bytes (short at the end)
FILE_WRITE = 0x12, ///< (u32 offset, path_len u16, path, data); offset 0 truncates
@@ -342,6 +347,7 @@ class RemoteControl {
std::unique_lock lk(shot_mutex_);
if (shot_state_ != ShotState::CAPTURING) return; // the request gave up
auto *cart = current_cart();
+ shot_size_ = 0;
if (cart) {
cart->capture_hold(true);
auto [w, h] = cart->frame_size();
@@ -354,7 +360,15 @@ class RemoteControl {
shot_pixels_ = pixels.data();
shot_size_ = w * h * 2;
}
- shot_state_ = (cart && shot_size_) ? ShotState::HELD : ShotState::IDLE;
+ else {
+ // no game: the launcher's screen, drawn into a copy
+ launcher_shot_ = gui_.snapshot();
+ shot_width_ = launcher_shot_.width;
+ shot_height_ = launcher_shot_.height;
+ shot_pixels_ = launcher_shot_.pixels.data();
+ shot_size_ = launcher_shot_.pixels.size();
+ }
+ shot_state_ = shot_size_ ? ShotState::HELD : ShotState::IDLE;
has_shot_cart_ = cart != nullptr;
shot_cv_.notify_all();
// hold the game while the frame is read
@@ -364,6 +378,7 @@ class RemoteControl {
}
shot_state_ = ShotState::IDLE;
shot_pixels_ = nullptr;
+ launcher_shot_ = {};
shot_cv_.notify_all();
lk.unlock();
if (cart) cart->capture_hold(false);
@@ -374,18 +389,14 @@ class RemoteControl {
fail("the device is busy (is the pause menu open?)");
break;
}
- if (!has_shot_cart_) {
- fail("no game is running");
- break;
- }
if (shot_state_ != ShotState::HELD) {
- fail("this game has no frame to capture");
+ fail(has_shot_cart_ ? "this game has no frame to capture" : "the launcher could not be drawn");
break;
}
width = shot_width_;
height = shot_height_;
- json(fmt::format("{{\"width\":{},\"height\":{},\"size\":{},\"format\":\"{}\"}}", width, height,
- shot_size_, kFrameFormat));
+ json(fmt::format("{{\"width\":{},\"height\":{},\"size\":{},\"format\":\"{}\",\"source\":\"{}\"}}", width,
+ height, shot_size_, kFrameFormat, has_shot_cart_ ? "game" : "launcher"));
break;
}
case Type::SCREENSHOT_READ: {
@@ -452,6 +463,30 @@ class RemoteControl {
return;
#endif
}
+ case Type::CONSOLE_FILTER: {
+ std::string key(text);
+ std::transform(key.begin(), key.end(), key.begin(),
+ [](unsigned char c) { return static_cast(std::tolower(c)); });
+ const auto present = gui_.consoles();
+ bool done = false;
+ if (key.empty() || key == "all") {
+ done = gui_.set_console_filter(std::nullopt);
+ } else {
+ const auto it = std::find_if(present.begin(), present.end(),
+ [&](Console c) { return key == console_info(c).key; });
+ if (it == present.end()) {
+ fail(fmt::format("no games for console '{}'", key));
+ break;
+ }
+ done = gui_.set_console_filter(*it);
+ }
+ if (!done) {
+ fail("the filter could not be set");
+ break;
+ }
+ json(filter_json());
+ break;
+ }
case Type::FILE_LIST: {
// path, optionally followed by '\0' and the index to start at (the "next" of a truncated
// reply)
@@ -679,7 +714,7 @@ class RemoteControl {
"\"uptime_ms\":{},\"internal_free\":{},\"internal_largest\":{},\"internal_min_free\":{},"
"\"psram_free\":{},\"psram_largest\":{},\"psram_min_free\":{},\"dma_free\":{},"
"\"dma_largest\":{},\"firmware\":{},\"built\":{},"
- "\"partition\":{},\"elf_sha256\":{},\"reset_reason\":{},\"last_panic\":{}}}",
+ "\"partition\":{},\"elf_sha256\":{},\"reset_reason\":{},\"last_panic\":{},\"filter\":{}}}",
in_game ? "game" : "menu", quote(rom), platform, quote(console), frames,
BoxEmu::get().frames_blitted(), BoxEmu::get().frames_dropped(),
BoxEmu::get().usb_msc_host_has_card(), esp_timer_get_time() / 1000,
@@ -691,7 +726,22 @@ class RemoteControl {
heap_caps_get_free_size(MALLOC_CAP_DMA | MALLOC_CAP_INTERNAL),
heap_caps_get_largest_free_block(MALLOC_CAP_DMA | MALLOC_CAP_INTERNAL), quote(app->version),
quote(fmt::format("{} {}", app->date, app->time)), quote(running ? running->label : ""),
- quote(elf_sha256()), (int)esp_reset_reason(), quote(DevLink::last_panic()));
+ quote(elf_sha256()), (int)esp_reset_reason(), quote(DevLink::last_panic()),
+ quote(filter_key()));
+ }
+
+ /// The launcher's console filter: its console's key, empty for all.
+ std::string filter_key() const {
+ const auto f = gui_.console_filter();
+ return f ? console_info(*f).key : "";
+ }
+
+ std::string filter_json() const {
+ std::string consoles;
+ for (const Console c : gui_.consoles()) {
+ consoles += fmt::format("{}{}", consoles.empty() ? "" : ",", quote(console_info(c).key));
+ }
+ return fmt::format("{{\"filter\":{},\"consoles\":[{}]}}", quote(filter_key()), consoles);
}
/// Make the bootloader start the updater (ota_1) next. esp_ota_set_boot_partition()
@@ -810,6 +860,7 @@ class RemoteControl {
const uint8_t *shot_pixels_{nullptr};
size_t shot_width_{0}, shot_height_{0}, shot_size_{0};
bool has_shot_cart_{false};
+ Gui::Snapshot launcher_shot_; ///< the launcher's screen, while it is read
FILE *write_file_{nullptr};
std::string write_path_;
uint32_t write_pos_{0};
diff --git a/tools/emulink/emulink/cli.py b/tools/emulink/emulink/cli.py
index de26428..e48350a 100644
--- a/tools/emulink/emulink/cli.py
+++ b/tools/emulink/emulink/cli.py
@@ -140,6 +140,13 @@ def cmd_screenshot(args) -> int:
return 0
+def cmd_filter(args) -> int:
+ with _open(args) as link:
+ r = Control(link).console_filter(args.console)
+ print(f"filter: {r['filter'] or 'all'} (consoles: {', '.join(r['consoles'])})")
+ return 0
+
+
def cmd_ls(args) -> int:
with _open(args) as link:
for e in Control(link).ls(args.path):
@@ -457,7 +464,7 @@ def build_parser() -> argparse.ArgumentParser:
s = sub.add_parser(name, help=f"{name} a save state")
s.add_argument("slot", type=int)
s.set_defaults(fn=fn)
- s = sub.add_parser("screenshot", help="the running game's frame as a PNG")
+ s = sub.add_parser("screenshot", help="the running game's frame (or the launcher's screen) as a PNG")
s.add_argument("-o", "--output")
s.add_argument("--byteswap", action=argparse.BooleanOptionalAction, default=None,
help="RGB565 big-endian (default: the byte order the device reports)")
@@ -490,6 +497,9 @@ def build_parser() -> argparse.ArgumentParser:
s.add_argument("--delete", action="store_true", help="also delete the file")
s.set_defaults(fn=cmd_remove_rom)
sub.add_parser("reload", help="re-read metadata.csv").set_defaults(fn=cmd_reload)
+ s = sub.add_parser("filter", help="show only one console's games in the launcher (a key such as snes, or all)")
+ s.add_argument("console", nargs="?", help="console key, or all (default: show the current filter)")
+ s.set_defaults(fn=cmd_filter)
s = sub.add_parser("drive", help="hand the SD card to the PC as a USB drive (on) or take it back (off)")
s.add_argument("state", choices=("on", "off"))
s.set_defaults(fn=cmd_drive)
diff --git a/tools/emulink/emulink/control.py b/tools/emulink/emulink/control.py
index abe2c6b..dc3140f 100644
--- a/tools/emulink/emulink/control.py
+++ b/tools/emulink/emulink/control.py
@@ -17,6 +17,7 @@
STATUS, LIST_ROMS, LAUNCH, QUIT, BUTTONS, SAVE, LOAD, SCREENSHOT, USB_DRIVE, RELOAD_ROMS, ENTER_UPDATER = range(1, 12)
SCREENSHOT_READ = 0x0C
+CONSOLE_FILTER = 0x0D
FILE_LIST, FILE_READ, FILE_WRITE, FILE_DELETE, MKDIR, FILE_STAT, FILE_CLOSE = range(0x10, 0x17)
#: one FILE_WRITE: the frame payload is at most 4096 bytes, of which 6 + the path are the header
@@ -168,9 +169,9 @@ def screenshot(self, remote_path: str = "screenshots/screenshot.bin") -> str:
return self._call(SCREENSHOT, self.remote(remote_path).encode())["path"]
def frame(self, progress=None) -> "Frame":
- """The running game's frame, copied straight from its frame buffer
- (firmware before protocol 2 saves it on the card and it is read from
- there)."""
+ """The running game's frame, copied straight from its frame buffer,
+ or with no game running (protocol 3) the launcher's screen (firmware
+ before protocol 2 saves it on the card and it is read from there)."""
info = self._call(SCREENSHOT, timeout_s=15)
if "path" in info: # older firmware
data = self.read_file(info["path"])
@@ -200,6 +201,14 @@ def frame(self, progress=None) -> "Frame":
def usb_drive(self, host: bool) -> None:
self._call(USB_DRIVE, bytes([1 if host else 0]), timeout_s=20)
+ def console_filter(self, console: str | None = None) -> dict:
+ """Set the launcher's console filter (a console key such as "snes", or
+ "all"); with None, only report it. -> {filter, consoles}"""
+ if console is None:
+ console = self.status().get("filter", "")
+ # (an empty filter would clear it: ask for the same one again)
+ return self._call(CONSOLE_FILTER, (console or "all").encode())
+
def reload_roms(self) -> int:
return self._call(RELOAD_ROMS)["total"]
From 32a69b9b534f6e0c36db939d3732f9990d2d364a Mon Sep 17 00:00:00 2001
From: William Emfinger
Date: Fri, 13 Nov 2026 08:31:28 -0600
Subject: [PATCH 02/15] Web console: the WebUSB landing page, on GitHub Pages
- web/: the Emulator Console, plain HTML / CSS / ES modules (no build):
dashboard (what runs, frame rate, memory, firmware, last crash, USB
drive), the screen live with an on-screen / keyboard controller and save
states, the library by console with boxart (play, filter the launcher,
add / remove games), the SD card's files (download, upload, delete), the
launcher's settings, the system (info, restart, firmware update through
the updater and espp's OTA console, the other services in their espp
apps) and the console log (Web Serial). link.js is the protocol, shared
with tab5-emu like tools/emulink.
- The WebUSB landing page is now this console on the project's GitHub
Pages (the old espp device_hub.html URL does not exist).
- Link protocol 4: SETTINGS (get / set the launcher's settings, as its
controls do) and the console key and boxart path in LIST_ROMS;
emulink settings [name=value].
- .github/workflows/pages.yml publishes web/ (Pages source: GitHub Actions).
Co-Authored-By: Claude Opus 5.5 (1M context)
Claude-Session: https://claude.ai/code/session_01SFCMzomCZ5wRHJN4sxwkvY
---
.github/workflows/pages.yml | 38 ++
README.md | 12 +
components/gui/include/gui.hpp | 9 +
components/gui/src/gui.cpp | 50 ++
components/tab5-emu/src/usb_device.cpp | 2 +-
main/remote_control.hpp | 40 +-
tools/emulink/emulink/cli.py | 15 +
tools/emulink/emulink/control.py | 6 +
web/README.md | 33 ++
web/app.css | 196 +++++++
web/app.js | 772 +++++++++++++++++++++++++
web/index.html | 267 +++++++++
web/link.js | 444 ++++++++++++++
13 files changed, 1878 insertions(+), 6 deletions(-)
create mode 100644 .github/workflows/pages.yml
create mode 100644 web/README.md
create mode 100644 web/app.css
create mode 100644 web/app.js
create mode 100644 web/index.html
create mode 100644 web/link.js
diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml
new file mode 100644
index 0000000..0849565
--- /dev/null
+++ b/.github/workflows/pages.yml
@@ -0,0 +1,38 @@
+name: Web console (GitHub Pages)
+
+# The Emulator Console (web/): the page the firmware advertises as its WebUSB
+# landing page (esp-cpp.github.io//). Needs Settings -> Pages -> Source:
+# GitHub Actions.
+on:
+ push:
+ branches: [main]
+ paths:
+ - 'web/**'
+ - '.github/workflows/pages.yml'
+ workflow_dispatch:
+
+permissions:
+ contents: read
+ pages: write
+ id-token: write
+
+concurrency:
+ group: pages
+ cancel-in-progress: true
+
+jobs:
+ deploy:
+ runs-on: ubuntu-latest
+ environment:
+ name: github-pages
+ url: ${{ steps.deployment.outputs.page_url }}
+ steps:
+ - uses: actions/checkout@v4
+ - name: Check the scripts parse
+ run: for f in web/*.js; do node --check "$f"; done
+ - uses: actions/configure-pages@v5
+ - uses: actions/upload-pages-artifact@v3
+ with:
+ path: web
+ - id: deployment
+ uses: actions/deploy-pages@v4
diff --git a/README.md b/README.md
index 69baf79..bb4af72 100644
--- a/README.md
+++ b/README.md
@@ -260,6 +260,18 @@ Note that a terminal which opens the console port with DTR low and RTS high
resets the chip (`rst:0x17 CHIP_USB_UART_RESET`); keep both asserted, or
expect a reboot whenever the console re-enumerates (after the USB drive).
+## Web Console
+
+Plug the emulator into a computer and Chrome or Edge offers its web console,
+[esp-cpp.github.io/tab5-emu](https://esp-cpp.github.io/tab5-emu/) (the firmware's
+WebUSB landing page; the source is in [`web/`](./web)). Nothing to install:
+it talks to the device over USB to show what runs (frame rate, memory,
+firmware, the last crash), the game's or the launcher's screen with an
+on-screen controller, the games by console with their boxart (play, filter,
+add, remove), the SD card's files (download, upload, delete), the launcher's
+settings, the system (restart, firmware update through the updater) and the
+console log. It uses the same link as `tools/emulink`, so close that first.
+
## USB drive (file transfer)
Settings > "USB drive" exposes the SD card as a USB mass storage device on
diff --git a/components/gui/include/gui.hpp b/components/gui/include/gui.hpp
index 7fef744..0a70f21 100644
--- a/components/gui/include/gui.hpp
+++ b/components/gui/include/gui.hpp
@@ -75,6 +75,15 @@ class Gui {
/// Show only `console`'s games (nullopt: every console's); false if it has none.
bool set_console_filter(std::optional console);
+ /// The settings the launcher shows, for the USB link: {settings: {name:
+ /// value}, limits: {name: [min, max]}} (volume, muted, brightness, video,
+ /// resume).
+ std::string settings_json() const;
+ /// Change one of them as its control in the launcher does (shown, applied,
+ /// saved once the changes stop); false for an unknown name or a value out
+ /// of range.
+ bool set_setting(const std::string &name, int value);
+
/// The launcher screen (RGB565, little endian, rows packed), for the USB
/// link's screenshot when no game runs; empty if it cannot be drawn.
struct Snapshot {
diff --git a/components/gui/src/gui.cpp b/components/gui/src/gui.cpp
index 54687b1..cbf9c01 100644
--- a/components/gui/src/gui.cpp
+++ b/components/gui/src/gui.cpp
@@ -1,5 +1,7 @@
#include "gui.hpp"
+#include
+
#include "lvgl_private.h"
#include
@@ -505,6 +507,54 @@ void Gui::picker_event(lv_event_t *e) {
}
}
+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();
+ std::string limits;
+ for (const auto &l : kSettingLimits) {
+ limits += fmt::format("{}\"{}\":[{},{}]", limits.empty() ? "" : ",", l.name, l.min, l.max);
+ }
+ 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);
+}
+
+bool Gui::set_setting(const std::string &name, int value) {
+ const auto *limit = std::find_if(std::begin(kSettingLimits), std::end(kSettingLimits),
+ [&](const SettingLimit &l) { return name == l.name; });
+ if (limit == std::end(kSettingLimits) || value < limit->min || value > limit->max) {
+ return false;
+ }
+ std::lock_guard lk(mutex_);
+ auto &emu = Tab5Emu::get();
+ // (saved to the SD card by the main loop once the changes stop, as from the launcher)
+ AppSettings::get().modify([&](Settings &s) {
+ if (name == "volume") s.volume = value;
+ else if (name == "muted") s.muted = value != 0;
+ else if (name == "brightness") s.brightness = value;
+ else if (name == "video") s.video_setting = value;
+ else if (name == "resume") s.resume_last_save = value != 0;
+ });
+ if (name == "volume") emu.volume(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
+ return true;
+}
+
Gui::Snapshot Gui::snapshot() {
std::lock_guard lk(mutex_);
Snapshot shot;
diff --git a/components/tab5-emu/src/usb_device.cpp b/components/tab5-emu/src/usb_device.cpp
index c1382c7..757685f 100644
--- a/components/tab5-emu/src/usb_device.cpp
+++ b/components/tab5-emu/src/usb_device.cpp
@@ -87,7 +87,7 @@ bool Tab5Emu::initialize_usb_device() {
espp::UsbDevice::VendorFunction vendor;
vendor.interface_name = "Tab5 Emu link";
vendor.webusb = true;
- vendor.landing_page_url = "esp-cpp.github.io/espp/apps/device_hub.html";
+ vendor.landing_page_url = "esp-cpp.github.io/tab5-emu/";
vendor.on_receive = [this](std::span data) {
if (vendor_rx_) vendor_rx_(data);
};
diff --git a/main/remote_control.hpp b/main/remote_control.hpp
index fb80e28..7a5c1f9 100644
--- a/main/remote_control.hpp
+++ b/main/remote_control.hpp
@@ -111,11 +111,12 @@ class RemoteControl {
public:
static constexpr uint8_t kModule = 0x20;
static constexpr const char *kProtocol = "emu.control";
- static constexpr uint16_t kProtocolVersion = 3; // 2: in-memory screenshots, 3: console filter, launcher screenshots
+ // 2: in-memory screenshots, 3: console filter, launcher screenshots, 4: settings, boxart / console keys in the list
+ static constexpr uint16_t kProtocolVersion = 4;
enum class Type : uint8_t {
STATUS = 0x01, ///< () -> {state, rom, platform, console, heap, uptime, ...}
- LIST_ROMS = 0x02, ///< (offset: text) -> {total, roms: [{name, path, platform, console}]}
+ LIST_ROMS = 0x02, ///< (offset: text) -> {total, roms: [{name, path, platform, console, key, boxart}]}
LAUNCH = 0x03, ///< (rom path or part of a name / path) -> {rom}
QUIT = 0x04, ///< ()
BUTTONS = 0x05, ///< (u16 buttons, u16 hold ms; 0 = until the next BUTTONS)
@@ -135,6 +136,10 @@ class RemoteControl {
/// (console key: text, e.g. "snes"; empty or "all" for every console) ->
/// {filter, consoles: [keys]}: the launcher's list shows only that console's games
CONSOLE_FILTER = 0x0D,
+ /// (empty, or "name=value" to change one) -> {settings: {name: value},
+ /// limits: {name: [min, max]}}: the launcher's settings (volume,
+ /// brightness, ...), applied and saved like the launcher's own controls
+ SETTINGS = 0x0E,
FILE_LIST = 0x10, ///< (path[\0offset]) -> {entries: [{name, dir, size}], truncated?, next?}
FILE_READ = 0x11, ///< (u32 offset, u16 length, path) -> raw bytes (short at the end)
FILE_WRITE = 0x12, ///< (u32 offset, path_len u16, path, data); offset 0 truncates
@@ -233,9 +238,11 @@ class RemoteControl {
size_t i = offset;
for (; i < roms.size(); i++) {
const auto &r = roms[i];
- auto e = fmt::format("{}{{\"name\":{},\"path\":{},\"platform\":\"{}\",\"console\":{}}}",
- i > offset ? "," : "", quote(r.name), quote(r.rom_path), r.platform,
- quote(console_info(console_of(r.platform)).name));
+ const auto &console = console_info(console_of(r.platform));
+ auto e = fmt::format(
+ "{}{{\"name\":{},\"path\":{},\"platform\":\"{}\",\"console\":{},\"key\":{},\"boxart\":{}}}",
+ i > offset ? "," : "", quote(r.name), quote(r.rom_path), r.platform, quote(console.name),
+ quote(console.key), quote(r.boxart_path));
// (room for the trailer, `],"next":N}`, and reply()'s status byte)
if (j.size() + e.size() + 24 > espp::stream_frame::kMaxPayloadSize) break; // the host asks for the rest
j += e;
@@ -487,6 +494,29 @@ class RemoteControl {
json(filter_json());
break;
}
+ case Type::SETTINGS: {
+ if (!text.empty()) {
+ const auto eq = text.find('=');
+ if (eq == std::string_view::npos) {
+ fail("payload: name=value");
+ break;
+ }
+ const std::string name(text.substr(0, eq));
+ const std::string value(text.substr(eq + 1));
+ char *end = nullptr;
+ const long v = std::strtol(value.c_str(), &end, 10);
+ if (value.empty() || *end) {
+ fail(fmt::format("{}: '{}' is not a number", name, value));
+ break;
+ }
+ if (!gui_.set_setting(name, static_cast(v))) {
+ fail(fmt::format("unknown setting '{}' (or {} is out of range)", name, v));
+ break;
+ }
+ }
+ json(gui_.settings_json());
+ break;
+ }
case Type::FILE_LIST: {
// path, optionally followed by '\0' and the index to start at (the "next" of a truncated
// reply)
diff --git a/tools/emulink/emulink/cli.py b/tools/emulink/emulink/cli.py
index e48350a..8d3e1f7 100644
--- a/tools/emulink/emulink/cli.py
+++ b/tools/emulink/emulink/cli.py
@@ -147,6 +147,18 @@ def cmd_filter(args) -> int:
return 0
+def cmd_settings(args) -> int:
+ with _open(args) as link:
+ c = Control(link)
+ r = None
+ for change in args.change or [None]:
+ r = c.settings(change)
+ for name, value in r["settings"].items():
+ lo, hi = r["limits"].get(name, ("", ""))
+ print(f"{name:<11} {value:>4} ({lo}..{hi})")
+ return 0
+
+
def cmd_ls(args) -> int:
with _open(args) as link:
for e in Control(link).ls(args.path):
@@ -497,6 +509,9 @@ def build_parser() -> argparse.ArgumentParser:
s.add_argument("--delete", action="store_true", help="also delete the file")
s.set_defaults(fn=cmd_remove_rom)
sub.add_parser("reload", help="re-read metadata.csv").set_defaults(fn=cmd_reload)
+ s = sub.add_parser("settings", help="the launcher's settings; name=value changes one (volume=40, muted=1, ...)")
+ s.add_argument("change", nargs="*", help="name=value")
+ s.set_defaults(fn=cmd_settings)
s = sub.add_parser("filter", help="show only one console's games in the launcher (a key such as snes, or all)")
s.add_argument("console", nargs="?", help="console key, or all (default: show the current filter)")
s.set_defaults(fn=cmd_filter)
diff --git a/tools/emulink/emulink/control.py b/tools/emulink/emulink/control.py
index dc3140f..d177315 100644
--- a/tools/emulink/emulink/control.py
+++ b/tools/emulink/emulink/control.py
@@ -18,6 +18,7 @@
STATUS, LIST_ROMS, LAUNCH, QUIT, BUTTONS, SAVE, LOAD, SCREENSHOT, USB_DRIVE, RELOAD_ROMS, ENTER_UPDATER = range(1, 12)
SCREENSHOT_READ = 0x0C
CONSOLE_FILTER = 0x0D
+SETTINGS = 0x0E
FILE_LIST, FILE_READ, FILE_WRITE, FILE_DELETE, MKDIR, FILE_STAT, FILE_CLOSE = range(0x10, 0x17)
#: one FILE_WRITE: the frame payload is at most 4096 bytes, of which 6 + the path are the header
@@ -209,6 +210,11 @@ def console_filter(self, console: str | None = None) -> dict:
# (an empty filter would clear it: ask for the same one again)
return self._call(CONSOLE_FILTER, (console or "all").encode())
+ def settings(self, change: str | None = None) -> dict:
+ """The launcher's settings ({settings, limits}); `change` ("name=value")
+ sets one first (protocol 4)."""
+ return self._call(SETTINGS, (change or "").encode())
+
def reload_roms(self) -> int:
return self._call(RELOAD_ROMS)["total"]
diff --git a/web/README.md b/web/README.md
new file mode 100644
index 0000000..0b424c4
--- /dev/null
+++ b/web/README.md
@@ -0,0 +1,33 @@
+# Emulator Console (web)
+
+The page esp-box-emu and tab5-emu advertise as their WebUSB landing page
+(`esp-cpp.github.io/esp-box-emu/`, `esp-cpp.github.io/tab5-emu/`): Chrome or
+Edge offers it when the emulator is plugged in. It talks to the device's link
+(the vendor interface, the same protocol as `tools/emulink`) and its console
+(the CDC port, with Web Serial).
+
+- **Dashboard**: what runs, frame rate, memory, firmware, uptime, last crash,
+ and the SD card's USB drive mode.
+- **Screen**: the game's (or the launcher's) screen, live, with an on-screen
+ controller (or the keyboard), save states and quit.
+- **Library**: the games by console with their boxart; play, filter (the
+ launcher too), add a game (ROM + boxart + metadata.csv), remove one.
+- **Files**: browse the SD card, download, upload (drag and drop), new
+ folder, delete.
+- **Settings**: volume, mute, brightness, video scaling, resume last save
+ (haptics on the box), as in the launcher.
+- **System**: chip, partitions, reset reason, the services on the link,
+ restart (or into download mode), and the firmware update (the updater with
+ the espp OTA console). The generic services open in their espp web apps.
+- **Console**: the console log, filtered, saved.
+
+Plain HTML / CSS / ES modules, no build step. `link.js` is the protocol
+(stream_frame frames, emu.control, the espp system service), `app.js` the
+page. The files are the same in both repositories (like `tools/emulink`).
+
+Try it locally: `python3 -m http.server -d web 8000`, then open
+http://localhost:8000 (WebUSB needs https or localhost). Only one program can
+use the link at a time: close `emulink` first.
+
+The pages workflow (`.github/workflows/pages.yml`) publishes this folder
+on a push to main.
diff --git a/web/app.css b/web/app.css
new file mode 100644
index 0000000..35daada
--- /dev/null
+++ b/web/app.css
@@ -0,0 +1,196 @@
+:root {
+ --bg: #0f1216;
+ --bg2: #161b21;
+ --card: #1b2129;
+ --line: #2a323c;
+ --text: #e8ecf1;
+ --muted: #93a0ae;
+ --accent: #e5484d;
+ --accent2: #3e8ef7;
+ --ok: #30a46c;
+ --warn: #f5a524;
+ --bad: #e5484d;
+ --radius: 12px;
+ color-scheme: dark;
+}
+@media (prefers-color-scheme: light) {
+ :root:not([data-theme="dark"]) {
+ --bg: #f4f6f8; --bg2: #ffffff; --card: #ffffff; --line: #dde3ea; --text: #15191e; --muted: #5d6874;
+ color-scheme: light;
+ }
+}
+* { box-sizing: border-box; }
+html, body { margin: 0; background: var(--bg); color: var(--text); }
+body { font: 15px/1.45 system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; min-height: 100vh; display: flex; flex-direction: column; }
+code, pre, .mono { font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; }
+a { color: var(--accent2); }
+[hidden] { display: none !important; }
+
+.topbar { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 12px 20px; background: var(--bg2); border-bottom: 1px solid var(--line); position: sticky; top: 0; z-index: 5; flex-wrap: wrap; }
+.brand { display: flex; align-items: center; gap: 12px; }
+.brand-icon { width: 40px; height: 40px; fill: var(--accent); }
+.brand-icon .hole { fill: #fff; }
+.brand-title { font-weight: 700; font-size: 17px; }
+.brand-sub { color: var(--muted); font-size: 13px; }
+.topbar-right { display: flex; align-items: center; gap: 10px; }
+
+.pill { flex-shrink: 0; display: inline-flex; align-items: center; gap: 6px; padding: 4px 12px; border-radius: 999px; background: var(--card); border: 1px solid var(--line); color: var(--muted); font-size: 13px; white-space: nowrap; }
+.pill::before { content: ""; width: 8px; height: 8px; border-radius: 50%; background: var(--muted); }
+.pill.ok { color: var(--text); } .pill.ok::before { background: var(--ok); }
+.pill.playing::before { background: var(--accent2); }
+.pill.warn::before { background: var(--warn); }
+.pill.bad::before { background: var(--bad); }
+
+.btn { appearance: none; border: 1px solid var(--line); background: var(--card); color: var(--text); padding: 7px 14px; border-radius: 8px; font: inherit; cursor: pointer; text-decoration: none; display: inline-flex; align-items: center; gap: 6px; white-space: nowrap; }
+.btn:hover:not(:disabled) { border-color: var(--muted); }
+.btn:disabled { opacity: .5; cursor: default; }
+.btn.primary { background: var(--accent2); border-color: var(--accent2); color: #fff; }
+.btn.danger { background: var(--bad); border-color: var(--bad); color: #fff; }
+.btn.big { padding: 12px 22px; font-size: 16px; }
+.btn.small { padding: 3px 9px; font-size: 13px; }
+
+.tabs { display: flex; gap: 2px; padding: 0 16px; background: var(--bg2); border-bottom: 1px solid var(--line); overflow-x: auto; }
+.tabs button { appearance: none; background: none; border: 0; color: var(--muted); font: inherit; padding: 11px 14px; cursor: pointer; border-bottom: 2px solid transparent; white-space: nowrap; }
+.tabs button.active { color: var(--text); border-bottom-color: var(--accent); }
+.tabs button:disabled { opacity: .4; cursor: default; }
+
+main { flex: 1; padding: 20px; max-width: 1320px; width: 100%; margin: 0 auto; }
+.notice { background: #3a2a12; border: 1px solid var(--warn); padding: 12px 16px; border-radius: var(--radius); margin-bottom: 16px; }
+.welcome { max-width: 640px; margin: 8vh auto; text-align: center; }
+.welcome h1 { font-size: 28px; margin-bottom: 8px; }
+.muted { color: var(--muted); }
+.small { font-size: 13px; }
+.hint { color: var(--muted); font-size: 13px; margin: 8px 0 0; }
+.row { display: flex; align-items: center; flex-wrap: wrap; }
+.col { display: flex; flex-direction: column; align-items: flex-start; }
+.gap { gap: 8px; }
+.end { justify-content: flex-end; }
+
+.grid.cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(290px, 1fr)); gap: 16px; }
+.card { background: var(--card); border: 1px solid var(--line); border-radius: var(--radius); padding: 16px 18px; min-width: 0; }
+.card.wide { grid-column: 1 / -1; }
+.card.slim { padding: 12px 14px; margin-top: 14px; }
+.card.danger { border-color: var(--bad); }
+.card h2 { font-size: 13px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); margin: 0 0 12px; font-weight: 600; }
+.card h3 { margin: 0 0 10px; font-size: 15px; }
+.kv { display: grid; grid-template-columns: auto 1fr; gap: 4px 14px; margin: 0; }
+.kv dt { color: var(--muted); }
+.kv dd { margin: 0; font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
+.kv.two { grid-template-columns: auto 1fr auto 1fr; }
+@media (max-width: 720px) { .kv.two { grid-template-columns: auto 1fr; } }
+pre { white-space: pre-wrap; margin: 0; }
+.spark { width: 100%; height: 56px; margin-top: 10px; display: block; }
+
+.now { display: flex; gap: 18px; align-items: center; }
+.now-art { width: 92px; height: 92px; border-radius: 10px; background: var(--bg); display: flex; align-items: center; justify-content: center; overflow: hidden; flex: none; }
+.now-art img { max-width: 100%; max-height: 100%; }
+.now-art img:not([src]) { display: none; }
+.now-state { color: var(--muted); font-size: 13px; text-transform: uppercase; letter-spacing: .05em; }
+.now-game { font-size: 22px; font-weight: 650; margin: 2px 0 6px; }
+.now-console { margin-bottom: 10px; }
+
+.badge { display: inline-flex; align-items: center; padding: 2px 10px; border-radius: 999px; font-size: 12px; font-weight: 600; color: #fff; background: #606060; white-space: nowrap; }
+
+.mem { display: grid; gap: 8px; }
+.mem-row { display: grid; grid-template-columns: 64px auto 1fr; gap: 10px; align-items: baseline; font-size: 13px; }
+.mem-row .strong { color: var(--text); font-weight: 600; }
+.mem-legend { display: flex; gap: 14px; font-size: 12px; color: var(--muted); margin-top: 6px; }
+.mem-legend i { display: inline-block; width: 10px; height: 3px; vertical-align: middle; margin-right: 5px; }
+.bar { height: 8px; border-radius: 4px; background: var(--bg); overflow: hidden; }
+.bar > i { display: block; height: 100%; background: var(--accent2); }
+.mem-row .num { font-variant-numeric: tabular-nums; color: var(--muted); }
+
+/* screen */
+.screen-layout { display: grid; grid-template-columns: minmax(0, 1fr) 340px; gap: 20px; align-items: start; }
+@media (max-width: 900px) { .screen-layout { grid-template-columns: 1fr; } }
+.screen-wrap { background: var(--card); border: 1px solid var(--line); border-radius: var(--radius); padding: 14px; }
+#screen { max-width: 100%; max-height: 68vh; width: auto; height: auto; aspect-ratio: auto; background: #000; border-radius: 6px; image-rendering: pixelated; display: block; margin: 0 auto; min-width: min(100%, 480px); object-fit: contain; }
+.screen-bar { display: flex; justify-content: space-between; align-items: center; margin: 8px 0; gap: 10px; min-height: 22px; }
+.screen-bar progress { width: 160px; }
+.toggle { display: inline-flex; align-items: center; gap: 6px; cursor: pointer; user-select: none; }
+
+.pad { background: var(--card); border: 1px solid var(--line); border-radius: 28px; padding: 14px 18px; user-select: none; touch-action: none; }
+.pad button { appearance: none; border: 0; font: inherit; color: #fff; cursor: pointer; }
+.pad button.down-now { filter: brightness(1.5); transform: scale(.95); }
+.shoulders, .meta { display: flex; justify-content: space-between; gap: 10px; }
+.shoulders button { flex: 1; background: #3a434e; border-radius: 10px; padding: 6px; }
+.meta { justify-content: center; margin-top: 8px; }
+.meta button { background: #3a434e; border-radius: 999px; padding: 4px 14px; font-size: 12px; }
+.pad-main { display: flex; justify-content: space-between; align-items: center; margin: 12px 0 4px; }
+.dpad { display: grid; grid-template: repeat(3, 38px) / repeat(3, 38px); }
+.dpad button { background: #3a434e; }
+.dpad .up { grid-area: 1 / 2; border-radius: 8px 8px 0 0; }
+.dpad .left { grid-area: 2 / 1; border-radius: 8px 0 0 8px; }
+.dpad .right { grid-area: 2 / 3; border-radius: 0 8px 8px 0; }
+.dpad .down { grid-area: 3 / 2; border-radius: 0 0 8px 8px; }
+.face { display: grid; grid-template: repeat(3, 38px) / repeat(3, 38px); }
+.face button { border-radius: 50%; font-weight: 700; }
+.face .x { grid-area: 1 / 2; background: #3e8ef7; }
+.face .y { grid-area: 2 / 1; background: #30a46c; }
+.face .a { grid-area: 2 / 3; background: #e5484d; }
+.face .b { grid-area: 3 / 2; background: #f5a524; }
+select, input:not([type]), input[type=search], input[type=text], input[type=number] { background: var(--bg); color: var(--text); border: 1px solid var(--line); border-radius: 8px; padding: 7px 10px; font: inherit; min-width: 0; }
+
+/* library */
+.lib-tools, .files-tools, .console-tools { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; margin-bottom: 12px; }
+.lib-tools input[type=search] { flex: 1; min-width: 180px; }
+.chips { display: flex; gap: 8px; flex-wrap: wrap; margin-bottom: 16px; }
+.chip { appearance: none; border: 1px solid var(--line); background: var(--card); color: var(--text); border-radius: 999px; padding: 5px 12px; font: inherit; font-size: 13px; cursor: pointer; display: inline-flex; gap: 8px; align-items: center; }
+.chip .dot { width: 10px; height: 10px; border-radius: 50%; }
+.chip .n { color: var(--muted); }
+.chip.active { border-color: var(--text); background: var(--bg2); }
+.lib-group h3 { display: flex; align-items: center; gap: 10px; margin: 22px 0 10px; font-size: 16px; }
+.lib-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 14px; }
+.game { background: var(--card); border: 1px solid var(--line); border-radius: var(--radius); overflow: hidden; display: flex; flex-direction: column; }
+.game.playing { border-color: var(--accent2); box-shadow: 0 0 0 1px var(--accent2); }
+.game .art { aspect-ratio: 3 / 4; background: var(--bg); display: flex; align-items: center; justify-content: center; color: var(--muted); font-size: 12px; overflow: hidden; }
+.game .art img { width: 100%; height: 100%; object-fit: contain; }
+.game .body { padding: 9px 10px 10px; display: flex; flex-direction: column; gap: 8px; flex: 1; }
+.game .title { font-size: 13px; font-weight: 600; line-height: 1.3; }
+.game .actions { display: flex; gap: 6px; margin-top: auto; }
+.game .actions .btn { flex: 1; justify-content: center; }
+.add-game { margin-bottom: 16px; }
+.form-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 12px; margin-bottom: 12px; }
+.form-grid label { display: flex; flex-direction: column; gap: 4px; font-size: 13px; color: var(--muted); }
+
+/* files */
+.crumbs { display: flex; flex-wrap: wrap; gap: 4px; align-items: center; flex: 1; }
+.crumbs button { appearance: none; background: none; border: 0; color: var(--accent2); font: inherit; cursor: pointer; padding: 2px 4px; }
+.crumbs span { color: var(--muted); }
+.drop { position: relative; background: var(--card); border: 1px solid var(--line); border-radius: var(--radius); overflow: hidden; }
+.drop.over { border-color: var(--accent2); }
+.drop-hint { display: none; position: absolute; inset: 0; align-items: center; justify-content: center; background: rgba(62, 142, 247, .15); font-weight: 600; }
+.drop.over .drop-hint { display: flex; }
+table { width: 100%; border-collapse: collapse; }
+th, td { text-align: left; padding: 8px 12px; border-bottom: 1px solid var(--line); }
+th { color: var(--muted); font-weight: 500; font-size: 13px; }
+td.num, th.num { text-align: right; font-variant-numeric: tabular-nums; }
+td.acts { text-align: right; white-space: nowrap; }
+.files tr:last-child td { border-bottom: 0; }
+.file-name { appearance: none; background: none; border: 0; color: inherit; font: inherit; cursor: pointer; padding: 0; text-align: left; }
+.file-name.dir { color: var(--accent2); }
+.transfer { display: flex; gap: 12px; align-items: center; margin-top: 10px; }
+.transfer progress { flex: 1; }
+
+/* settings */
+.settings { max-width: 640px; }
+.settings-form { display: grid; gap: 18px; }
+.setting { display: grid; grid-template-columns: 170px 1fr 48px; gap: 12px; align-items: center; }
+.setting label { font-weight: 550; }
+.setting output { text-align: right; font-variant-numeric: tabular-nums; color: var(--muted); }
+.setting input[type=range] { width: 100%; accent-color: var(--accent2); }
+
+/* system */
+.modules td code { font-size: 13px; }
+
+/* console */
+.console-tools input[type=search] { flex: 1; min-width: 160px; }
+.log { background: #0a0c0f; color: #cfd6de; border: 1px solid var(--line); border-radius: var(--radius); padding: 12px; height: 62vh; overflow: auto; font-size: 12.5px; line-height: 1.4; white-space: pre-wrap; overflow-wrap: anywhere; }
+.log .I { color: #6fd08c; } .log .W { color: #f5c451; } .log .E { color: #ff7b7b; } .log .D, .log .V { color: #8a96a3; }
+
+.modal { position: fixed; inset: 0; background: rgba(0, 0, 0, .55); display: flex; align-items: center; justify-content: center; z-index: 20; padding: 16px; }
+.modal-box { background: var(--card); border: 1px solid var(--line); border-radius: var(--radius); padding: 20px; max-width: 460px; width: 100%; }
+.modal-box h3 { margin-top: 0; }
+.toast { position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%); background: var(--card); border: 1px solid var(--line); padding: 10px 16px; border-radius: 10px; z-index: 30; max-width: calc(100% - 32px); box-shadow: 0 8px 24px rgba(0, 0, 0, .35); }
+.toast.err { border-color: var(--bad); }
+.foot { text-align: center; color: var(--muted); font-size: 13px; padding: 18px; }
diff --git a/web/app.js b/web/app.js
new file mode 100644
index 0000000..e94d8c5
--- /dev/null
+++ b/web/app.js
@@ -0,0 +1,772 @@
+// Emulator Console: the web app the emulators advertise as their WebUSB
+// landing page. Shared, byte for byte, by esp-box-emu and tab5-emu.
+import { BUTTONS, Control, ControlError, DEVICES, MODULE, PID, ROOT, UsbLink, VID, rgb565ToImageData } from "./link.js";
+
+const $ = (id) => document.getElementById(id);
+const h = (tag, attrs = {}, ...kids) => {
+ const e = document.createElement(tag);
+ for (const [k, v] of Object.entries(attrs)) {
+ if (v == null || v === false) continue;
+ if (k === "class") e.className = v;
+ else if (k.startsWith("on")) e.addEventListener(k.slice(2), v);
+ else if (k === "style") e.style.cssText = v;
+ else e.setAttribute(k, v === true ? "" : v);
+ }
+ for (const kid of kids.flat()) if (kid != null && kid !== false) e.append(kid.nodeType ? kid : String(kid));
+ return e;
+};
+
+// the consoles' accent colors (rom_info.cpp, both firmwares)
+const CONSOLE_COLORS = {
+ nes: "#B22222", snes: "#6A5ACD", gb: "#5B7F3A", gbc: "#8E44AD", sms: "#1F5FAF", gg: "#4F6D8F",
+ genesis: "#C8102E", msx: "#3A7D7D", pc: "#5A6B7B", pico8: "#FF004D", gba: "#4B3FA8", playstation: "#2E6DB4",
+ other: "#606060",
+};
+const ESPP_APPS = "https://esp-cpp.github.io/espp/apps/";
+
+const state = {
+ link: null, ctl: null, discovery: null, status: null, roms: [], romsLoaded: false,
+ tab: "dashboard", statusTimer: null, lastFrames: null, fpsHistory: [], memHistory: [],
+ filter: "", search: "", cwd: ROOT, files: [], live: false, lastShot: null, slot: 1,
+ boxart: new Map(), boxartQueue: [], boxartBusy: false, settings: null, serial: null,
+};
+
+// ------------------------------------------------------------------ helpers --
+function toast(text, err = false) {
+ const t = $("toast");
+ t.textContent = text; t.className = "toast" + (err ? " err" : ""); t.hidden = false;
+ clearTimeout(toast.timer);
+ toast.timer = setTimeout(() => (t.hidden = true), err ? 6000 : 3000);
+}
+
+function confirmModal(title, text, ok = "OK") {
+ return new Promise((resolve) => {
+ $("modalTitle").textContent = title; $("modalText").textContent = text; $("modalOk").textContent = ok;
+ $("modal").hidden = false; $("modalOk").focus();
+ const done = (v) => { $("modal").hidden = true; $("modalOk").onclick = $("modalCancel").onclick = null; resolve(v); };
+ $("modalOk").onclick = () => done(true);
+ $("modalCancel").onclick = () => done(false);
+ });
+}
+
+const fmtBytes = (n) => n == null ? "—" : n >= 1 << 20 ? (n / (1 << 20)).toFixed(2) + " MB" : n >= 1024 ? (n / 1024).toFixed(1) + " KB" : n + " B";
+const fmtUptime = (ms) => {
+ if (ms == null) return "—";
+ const s = Math.floor(ms / 1000), d = Math.floor(s / 86400), hh = Math.floor((s % 86400) / 3600), m = Math.floor((s % 3600) / 60);
+ return (d ? d + "d " : "") + (d || hh ? hh + "h " : "") + m + "m " + (s % 60) + "s";
+};
+const basename = (p) => p.split("/").filter(Boolean).pop() || p;
+const dirname = (p) => p.replace(/\/[^/]*\/?$/, "") || ROOT;
+const badge = (key, name) => h("span", { class: "badge", style: `background:${CONSOLE_COLORS[key] || CONSOLE_COLORS.other}` }, name || key);
+
+async function guarded(fn, okText) {
+ try {
+ const r = await fn();
+ if (okText) toast(okText);
+ return r;
+ } catch (e) {
+ toast(e.message || String(e), true);
+ return undefined;
+ }
+}
+
+function download(name, data, type = "application/octet-stream") {
+ const url = URL.createObjectURL(new Blob([data], { type }));
+ const a = h("a", { href: url, download: name });
+ document.body.append(a); a.click(); a.remove();
+ setTimeout(() => URL.revokeObjectURL(url), 5000);
+}
+
+// -------------------------------------------------------------- connection --
+async function connect(device) {
+ if (state.link) await disconnect();
+ setPill("", "Connecting…");
+ let link;
+ try {
+ link = device ? new UsbLink(device) : await UsbLink.request();
+ await link.open();
+ } catch (e) {
+ setPill("", "Not connected");
+ if (e && e.name === "NotFoundError") return; // the chooser was closed
+ const busy = /claim|access|busy|in use/i.test(String(e.message || e));
+ toast(busy ? "The link is in use: close emulink (or another tab using it) and connect again." : (e.message || String(e)), true);
+ try { await link?.close(); } catch (_) {}
+ return;
+ }
+ state.link = link;
+ state.ctl = new Control(link);
+ link.onclose = () => onLinkLost();
+ try { state.discovery = await link.discover(); } catch (_) { state.discovery = null; }
+ try { localStorage.setItem("emu-console-serial", link.serial); } catch (_) {}
+ $("connectBtn").hidden = true; $("disconnectBtn").hidden = false;
+ $("welcome").hidden = true;
+ $("deviceSub").textContent = `${link.known.name} · ${link.serial || "?"}`;
+ document.title = `${link.known.name} · Emulator Console`;
+ const control = state.discovery?.modules.find((m) => m.id === MODULE.CONTROL);
+ if (state.discovery && !control) toast("This device has no emulator control module", true);
+ else if (control && control.version < 4) toast(`Firmware speaks control protocol ${control.version}: update it for every feature here (4).`, true);
+ showTab(state.tab);
+ if (state.tab !== "library") loadLibrary().catch(() => {}); // (the names for the status)
+ pollStatus();
+ state.statusTimer = setInterval(pollStatus, 1000);
+}
+
+async function disconnect() {
+ clearInterval(state.statusTimer); state.statusTimer = null;
+ stopLive();
+ const link = state.link;
+ state.link = null; state.ctl = null; state.status = null; state.romsLoaded = false; state.settings = null;
+ if (link) { link.onclose = null; await link.close(); }
+ $("connectBtn").hidden = false; $("disconnectBtn").hidden = true;
+ $("welcome").hidden = false;
+ for (const p of document.querySelectorAll("[data-panel]")) p.hidden = true;
+ setPill("", "Not connected");
+ $("deviceSub").textContent = "esp-box-emu · tab5-emu over USB";
+}
+
+function onLinkLost() {
+ const serial = state.link?.serial;
+ disconnect().then(() => {
+ setPill("warn", "Disconnected");
+ toast("The device went away (restarted or unplugged); it reconnects when it is back.");
+ state.waitingFor = serial;
+ });
+}
+
+// a device that comes back (after a restart) is opened again without the chooser
+if (navigator.usb) {
+ navigator.usb.addEventListener("connect", (ev) => {
+ if (state.link || !DEVICES[ev.device.serialNumber]) return;
+ if (state.waitingFor && ev.device.serialNumber !== state.waitingFor) return;
+ setTimeout(() => connect(ev.device), 1200);
+ });
+}
+
+function setPill(cls, text) {
+ const p = $("statusPill");
+ p.className = "pill" + (cls ? " " + cls : ""); p.textContent = text;
+}
+
+async function autoConnect() {
+ const q = new URLSearchParams(location.search);
+ const wanted = q.get("serial") || (() => { try { return localStorage.getItem("emu-console-serial"); } catch (_) { return null; } })();
+ const devs = await UsbLink.permitted();
+ const dev = devs.find((d) => d.serialNumber === wanted) || devs.find((d) => DEVICES[d.serialNumber]);
+ if (dev && (q.get("autoconnect") || DEVICES[dev.serialNumber])) connect(dev);
+}
+
+// ----------------------------------------------------------------- status --
+async function pollStatus() {
+ if (!state.ctl || pollStatus.busy) return;
+ pollStatus.busy = true;
+ try {
+ const st = await state.ctl.status();
+ const now = performance.now();
+ if (state.lastFrames) {
+ const dt = (now - state.lastFrames.t) / 1000;
+ const fps = dt > 0 ? (st.frames_presented - state.lastFrames.n) / dt : 0;
+ state.fpsHistory.push(Math.max(0, fps));
+ if (state.fpsHistory.length > 120) state.fpsHistory.shift();
+ }
+ state.lastFrames = { t: now, n: st.frames_presented };
+ state.memHistory.push([st.internal_free, st.psram_free]);
+ if (state.memHistory.length > 120) state.memHistory.shift();
+ const prev = state.status;
+ state.status = st;
+ renderStatus(prev);
+ } catch (e) {
+ if (state.link) setPill("warn", "Busy");
+ } finally {
+ pollStatus.busy = false;
+ }
+}
+
+function renderStatus(prev) {
+ const st = state.status;
+ if (!st) return;
+ const rom = state.roms.find((r) => r.path === st.rom);
+ if (st.usb_drive) setPill("warn", "SD card on the PC");
+ else if (st.state === "game") setPill("playing", "Playing " + (rom?.name || basename(st.rom)));
+ else setPill("ok", "In the launcher");
+
+ $("nowState").textContent = st.state === "game" ? "Playing" : "In the launcher";
+ $("nowGame").textContent = st.state === "game" ? (rom?.name || basename(st.rom)) : "No game running";
+ $("nowConsole").replaceChildren(st.state === "game" && st.console ? badge(rom?.key, st.console) : "");
+ $("nowQuitBtn").hidden = st.state !== "game";
+ const art = st.state === "game" && rom?.boxart ? state.boxart.get(rom.boxart) : null;
+ if (art) $("nowArt").src = art; else $("nowArt").removeAttribute("src");
+ if (st.state === "game" && rom?.boxart && !state.boxart.has(rom.boxart)) queueBoxart(rom.boxart, () => renderStatus());
+
+ const fps = state.fpsHistory.at(-1);
+ $("fps").textContent = fps == null ? "—" : fps.toFixed(1) + " / s";
+ $("dropped").textContent = st.frames_dropped;
+ $("gameFrames").textContent = st.game_frames || "—";
+ drawSpark($("fpsSpark"), [state.fpsHistory], ["#3e8ef7"]);
+ const memRow = (label, free, largest, min) => h("div", { class: "mem-row" },
+ h("span", {}, label),
+ h("span", { class: "num strong" }, fmtBytes(free) + " free"),
+ h("span", { class: "num" }, `largest ${fmtBytes(largest)}` + (min != null ? ` · lowest ${fmtBytes(min)}` : "")));
+ $("memRows").replaceChildren(
+ memRow("Internal", st.internal_free, st.internal_largest, st.internal_min_free),
+ memRow("PSRAM", st.psram_free, st.psram_largest, st.psram_min_free),
+ memRow("DMA", st.dma_free, st.dma_largest, null));
+ drawSpark($("memSpark"), [state.memHistory.map((m) => m[0]), state.memHistory.map((m) => m[1])], ["#30a46c", "#f5a524"]);
+ $("fw").textContent = st.firmware; $("built").textContent = st.built;
+ $("partition").textContent = st.partition + (st.elf_sha256 ? ` · ${st.elf_sha256}` : "");
+ $("uptime").textContent = fmtUptime(st.uptime_ms);
+ $("reset").textContent = ({ 1: "power-on", 3: "software", 4: "panic", 5: "interrupt WDT", 6: "task WDT", 7: "other WDT", 9: "brownout", 11: "USB" })[st.reset_reason] || `#${st.reset_reason}`;
+ $("driveText").textContent = st.usb_drive ? "The PC has the SD card (a USB drive)." : "The emulator has the SD card.";
+ $("driveBtn").textContent = st.usb_drive ? "Take the SD card back" : "Give the SD card to this PC";
+ $("panicCard").hidden = !st.last_panic;
+ $("panicText").textContent = st.last_panic || "";
+ $("coredumpLink").href = handoffUrl("coredump_console.html", MODULE.COREDUMP);
+ // the game started or ended: the list, the screen and the buttons follow
+ if (prev && (prev.state !== st.state || prev.rom !== st.rom)) {
+ if (state.tab === "library") renderLibrary();
+ if (state.tab === "screen" && !state.live) capture();
+ }
+ if (prev && prev.filter !== st.filter && state.tab === "library") { state.filter = st.filter || ""; renderLibrary(); }
+}
+
+function drawSpark(canvas, series, colors) {
+ const dpr = window.devicePixelRatio || 1, w = canvas.clientWidth || 300, hh = canvas.clientHeight || 56;
+ if (canvas.width !== w * dpr) { canvas.width = w * dpr; canvas.height = hh * dpr; }
+ const g = canvas.getContext("2d");
+ g.setTransform(dpr, 0, 0, dpr, 0, 0);
+ g.clearRect(0, 0, w, hh);
+ series.forEach((s, k) => {
+ if (s.length < 2) return;
+ const max = Math.max(...s) * 1.1 || 1, min = 0;
+ g.strokeStyle = colors[k]; g.lineWidth = 1.5; g.beginPath();
+ s.forEach((v, i) => {
+ const x = (i / (120 - 1)) * w, y = hh - 2 - ((v - min) / (max - min)) * (hh - 4);
+ i ? g.lineTo(x, y) : g.moveTo(x, y);
+ });
+ g.stroke();
+ });
+}
+
+// ------------------------------------------------------------------- tabs --
+function showTab(tab) {
+ state.tab = tab;
+ for (const b of document.querySelectorAll("#tabs button")) b.classList.toggle("active", b.dataset.tab === tab);
+ if (!state.link) return;
+ for (const p of document.querySelectorAll("[data-panel]")) p.hidden = p.dataset.panel !== tab;
+ if (tab !== "screen") stopLive();
+ if (tab === "library") loadLibrary();
+ if (tab === "files") loadFiles(state.cwd);
+ if (tab === "settings") loadSettings();
+ if (tab === "system") loadSystem();
+ if (tab === "screen" && !state.lastShot) capture();
+}
+
+// ----------------------------------------------------------------- screen --
+async function capture() {
+ if (!state.ctl || capture.busy) return;
+ capture.busy = true;
+ const prog = $("screenProgress");
+ const t0 = performance.now();
+ try {
+ const f = await state.ctl.frame((n, total) => { prog.hidden = false; prog.max = total; prog.value = n; });
+ const c = $("screen");
+ c.width = f.width; c.height = f.height;
+ c.getContext("2d").putImageData(rgb565ToImageData(f.data, f.width, f.height, f.format === "rgb565be"), 0, 0);
+ state.lastShot = f;
+ $("screenInfo").textContent = `${f.source === "launcher" ? "Launcher" : "Game"} · ${f.width}×${f.height} · ${Math.round(performance.now() - t0)} ms`;
+ $("savePngBtn").disabled = false;
+ } catch (e) {
+ $("screenInfo").textContent = e.message || String(e);
+ } finally {
+ prog.hidden = true;
+ capture.busy = false;
+ }
+}
+
+async function liveLoop() {
+ while (state.live && state.ctl && state.tab === "screen") {
+ await capture();
+ await new Promise((r) => setTimeout(r, 150));
+ }
+}
+function stopLive() { state.live = false; $("liveToggle").checked = false; }
+
+let heldMask = 0;
+const setButtons = (mask) => {
+ heldMask = mask;
+ if (state.ctl) state.ctl.buttons(mask, 0).catch((e) => toast("Buttons: " + (e.message || e), true));
+};
+function initPad() {
+ for (const b of document.querySelectorAll("#pad [data-btn]")) {
+ const bit = BUTTONS[b.dataset.btn];
+ const down = (ev) => { ev.preventDefault(); b.classList.add("down-now"); b.setPointerCapture?.(ev.pointerId); setButtons(heldMask | bit); };
+ const up = () => { if (!(heldMask & bit)) return; b.classList.remove("down-now"); setButtons(heldMask & ~bit); };
+ b.addEventListener("pointerdown", down);
+ b.addEventListener("pointerup", up);
+ b.addEventListener("pointercancel", up);
+ b.addEventListener("lostpointercapture", up);
+ }
+ const keys = { ArrowUp: "up", ArrowDown: "down", ArrowLeft: "left", ArrowRight: "right", z: "a", x: "b", a: "x", s: "y", q: "l", w: "r", Enter: "start", Shift: "select" };
+ const keyBit = (ev) => BUTTONS[keys[ev.key] || keys[ev.key.toLowerCase()]];
+ addEventListener("keydown", (ev) => {
+ if (state.tab !== "screen" || (ev.target instanceof Element && ev.target.matches("input, select, textarea")) || ev.repeat) return;
+ const bit = keyBit(ev);
+ if (!bit) return;
+ ev.preventDefault(); setButtons(heldMask | bit);
+ });
+ addEventListener("keyup", (ev) => {
+ const bit = keyBit(ev);
+ if (bit && heldMask & bit) setButtons(heldMask & ~bit);
+ });
+ addEventListener("blur", () => { if (heldMask) setButtons(0); });
+}
+
+// ---------------------------------------------------------------- library --
+async function loadLibrary(force = false) {
+ if (!state.ctl) return;
+ if (!state.romsLoaded || force) {
+ const roms = await guarded(() => state.ctl.roms());
+ if (!roms) return;
+ state.roms = roms; state.romsLoaded = true;
+ state.filter = state.status?.filter || "";
+ const folders = [...new Set(roms.map((r) => dirname(r.path).slice(ROOT.length + 1)).filter(Boolean))].sort();
+ $("folders").replaceChildren(...folders.map((f) => h("option", { value: f })));
+ }
+ renderLibrary();
+}
+
+function renderLibrary() {
+ const consoles = [];
+ for (const r of state.roms) {
+ let c = consoles.find((x) => x.key === r.key);
+ if (!c) consoles.push(c = { key: r.key, name: r.console, n: 0 });
+ c.n++;
+ }
+ const chip = (key, name, n) => h("button", { class: "chip" + (state.filter === key ? " active" : ""), onclick: () => pickFilter(key) },
+ key ? h("span", { class: "dot", style: `background:${CONSOLE_COLORS[key] || CONSOLE_COLORS.other}` }) : null, name, h("span", { class: "n" }, n));
+ $("chips").replaceChildren(chip("", "All consoles", state.roms.length), ...consoles.map((c) => chip(c.key, c.name, c.n)));
+
+ const q = state.search.trim().toLowerCase();
+ const playing = state.status?.state === "game" ? state.status.rom : null;
+ const groups = consoles.filter((c) => !state.filter || c.key === state.filter).map((c) => {
+ const games = state.roms.filter((r) => r.key === c.key && (!q || r.name.toLowerCase().includes(q) || r.path.toLowerCase().includes(q)));
+ if (!games.length) return null;
+ return h("section", { class: "lib-group" },
+ h("h3", {}, badge(c.key, c.name), h("span", { class: "muted small" }, games.length + (games.length === 1 ? " game" : " games"))),
+ h("div", { class: "lib-grid" }, games.map((r) => gameCard(r, playing))));
+ }).filter(Boolean);
+ $("lib").replaceChildren(...(groups.length ? groups : [h("p", { class: "muted" }, state.roms.length ? "No game matches." : "No games: add metadata.csv to the SD card, or add a game above.")]));
+ observeArt();
+}
+
+function gameCard(r, playing) {
+ const isPlaying = playing === r.path;
+ const img = h("img", { alt: "", "data-art": r.boxart || null });
+ const cached = r.boxart && state.boxart.get(r.boxart);
+ if (cached) img.src = cached;
+ return h("article", { class: "game" + (isPlaying ? " playing" : ""), title: r.path },
+ h("div", { class: "art" }, r.boxart ? img : "no boxart"),
+ h("div", { class: "body" },
+ h("div", { class: "title" }, r.name),
+ h("div", { class: "actions" },
+ isPlaying
+ ? h("button", { class: "btn small", onclick: () => guarded(() => state.ctl.quit(), "Quit") }, "Quit")
+ : h("button", { class: "btn small primary", disabled: !!playing || state.status?.usb_drive, onclick: () => launch(r) }, "Play"),
+ h("button", { class: "btn small", title: "Take it out of metadata.csv (the file stays on the card)", onclick: () => removeGame(r) }, "Remove"))));
+}
+
+async function launch(r) {
+ await guarded(() => state.ctl.launch(r.path), "Starting " + r.name);
+ pollStatus();
+}
+
+async function removeGame(r) {
+ if (!(await confirmModal("Remove " + r.name + "?", "It is taken out of metadata.csv; the ROM stays on the SD card.", "Remove"))) return;
+ if (await guarded(() => state.ctl.addRom(r.path, r.name, "", true), "Removed " + r.name) !== undefined) loadLibrary(true);
+}
+
+async function pickFilter(key) {
+ state.filter = key;
+ renderLibrary();
+ if ($("syncFilter").checked) await guarded(() => state.ctl.consoleFilter(key));
+}
+
+let artObserver = null;
+function observeArt() {
+ artObserver?.disconnect();
+ artObserver = new IntersectionObserver((entries) => {
+ for (const e of entries) {
+ if (!e.isIntersecting) continue;
+ const img = e.target, path = img.dataset.art;
+ artObserver.unobserve(img);
+ if (!path || img.src) continue;
+ queueBoxart(path, (url) => { if (url) img.src = url; });
+ }
+ }, { rootMargin: "200px" });
+ for (const img of document.querySelectorAll("#lib img[data-art]")) if (!img.src) artObserver.observe(img);
+}
+
+function queueBoxart(path, done) {
+ if (state.boxart.has(path)) { done(state.boxart.get(path)); return; }
+ state.boxartQueue.push({ path, done });
+ pumpBoxart();
+}
+async function pumpBoxart() {
+ if (state.boxartBusy) return;
+ state.boxartBusy = true;
+ while (state.boxartQueue.length && state.ctl) {
+ const { path, done } = state.boxartQueue.shift();
+ if (state.boxart.has(path)) { done(state.boxart.get(path)); continue; }
+ try {
+ const data = await state.ctl.readFile(path);
+ const url = URL.createObjectURL(new Blob([data], { type: "image/jpeg" }));
+ state.boxart.set(path, url);
+ done(url);
+ } catch (_) {
+ state.boxart.set(path, null);
+ done(null);
+ }
+ }
+ state.boxartBusy = false;
+}
+
+async function addGame(ev) {
+ ev.preventDefault();
+ const rom = $("addRomFile").files[0], art = $("addArt").files[0];
+ const folder = $("addFolder").value.trim().replace(/^\/+|\/+$/g, "").replace(/^sdcard\//, "");
+ const name = $("addName").value.trim();
+ if (!rom || !folder || !name) return;
+ const romPath = `${ROOT}/${folder}/${rom.name}`;
+ const artPath = art ? `${ROOT}/boxart/${art.name}` : "";
+ const msg = $("addMsg");
+ try {
+ msg.textContent = "Copying the ROM…";
+ await state.ctl.writeFile(romPath, new Uint8Array(await rom.arrayBuffer()), (n, t) => (msg.textContent = `ROM ${Math.round((n / t) * 100)}%`));
+ if (art) {
+ msg.textContent = "Copying the boxart…";
+ await state.ctl.writeFile(artPath, new Uint8Array(await art.arrayBuffer()));
+ }
+ msg.textContent = "Adding to metadata.csv…";
+ const total = await state.ctl.addRom(romPath, name, artPath ? artPath.slice(ROOT.length + 1) : "");
+ msg.textContent = `Added: ${total} games now.`;
+ $("addGame").reset();
+ loadLibrary(true);
+ } catch (e) {
+ msg.textContent = "";
+ toast(e.message || String(e), true);
+ }
+}
+
+// ------------------------------------------------------------------ files --
+async function loadFiles(path) {
+ const entries = await guarded(() => state.ctl.ls(path));
+ if (!entries) return;
+ state.cwd = path;
+ state.files = entries.sort((a, b) => (b.dir - a.dir) || a.name.localeCompare(b.name));
+ renderFiles();
+}
+
+function renderFiles() {
+ const parts = state.cwd.slice(ROOT.length).split("/").filter(Boolean);
+ const crumbs = [h("button", { onclick: () => loadFiles(ROOT) }, "SD card")];
+ parts.forEach((p, i) => {
+ crumbs.push(h("span", {}, "/"));
+ crumbs.push(h("button", { onclick: () => loadFiles(ROOT + "/" + parts.slice(0, i + 1).join("/")) }, p));
+ });
+ $("crumbs").replaceChildren(...crumbs);
+ const rows = state.files.map((e) => {
+ const path = state.cwd + "/" + e.name;
+ return h("tr", {},
+ h("td", {}, h("button", { class: "file-name" + (e.dir ? " dir" : ""), onclick: () => (e.dir ? loadFiles(path) : downloadFile(path, e.size)) }, (e.dir ? "📁 " : "") + e.name)),
+ h("td", { class: "num" }, e.dir ? "" : fmtBytes(e.size)),
+ h("td", { class: "acts" },
+ e.dir ? null : h("button", { class: "btn small", onclick: () => downloadFile(path, e.size) }, "Download"),
+ " ",
+ h("button", { class: "btn small", onclick: () => deletePath(path, e.dir) }, "Delete")));
+ });
+ if (state.cwd !== ROOT) rows.unshift(h("tr", {}, h("td", { colspan: 3 }, h("button", { class: "file-name dir", onclick: () => loadFiles(dirname(state.cwd)) }, "⬑ up"))));
+ if (!state.files.length) rows.push(h("tr", {}, h("td", { colspan: 3, class: "muted" }, "Empty folder")));
+ $("files").tBodies[0].replaceChildren(...rows);
+}
+
+function transfer(text, n, total) {
+ $("transfer").hidden = !text;
+ $("transferText").textContent = text || "";
+ $("transferProgress").max = total || 1; $("transferProgress").value = n || 0;
+}
+
+async function downloadFile(path, size) {
+ try {
+ transfer("Downloading " + basename(path), 0, size);
+ const data = await state.ctl.readFile(path, (n, t) => transfer(`Downloading ${basename(path)} (${fmtBytes(n)} of ${fmtBytes(t)})`, n, t));
+ download(basename(path), data);
+ } catch (e) {
+ toast(e.message || String(e), true);
+ } finally {
+ transfer("");
+ }
+}
+
+async function uploadFiles(files) {
+ for (const f of files) {
+ try {
+ const data = new Uint8Array(await f.arrayBuffer());
+ await state.ctl.writeFile(state.cwd + "/" + f.name, data, (n, t) => transfer(`Copying ${f.name} (${fmtBytes(n)} of ${fmtBytes(t)})`, n, t));
+ } catch (e) {
+ toast(`${f.name}: ${e.message || e}`, true);
+ break;
+ }
+ }
+ transfer("");
+ loadFiles(state.cwd);
+}
+
+async function deletePath(path, dir) {
+ if (!(await confirmModal("Delete " + basename(path) + "?", dir ? "The folder and everything in it are deleted from the SD card." : "The file is deleted from the SD card.", "Delete"))) return;
+ await guarded(() => state.ctl.rm(path), "Deleted " + basename(path));
+ loadFiles(state.cwd);
+}
+
+// --------------------------------------------------------------- settings --
+const SETTING_INFO = {
+ volume: { label: "Volume", unit: "%" },
+ muted: { label: "Mute", bool: true },
+ brightness: { label: "Brightness", unit: "%" },
+ video: { label: "Video scaling", options: ["Original", "Fit", "Fill"] },
+ resume: { label: "Resume last save", bool: true },
+ haptic: { label: "Haptic effect" },
+};
+
+async function loadSettings() {
+ const r = await guarded(() => state.ctl.settings());
+ if (!r) { $("settingsForm").replaceChildren(h("p", { class: "muted" }, "This firmware has no settings over USB (control protocol 4).")); return; }
+ state.settings = r;
+ const send = debounce((name, value) => guarded(() => state.ctl.settings(`${name}=${value}`)), 250);
+ $("settingsForm").replaceChildren(...Object.entries(r.settings).map(([name, value]) => {
+ const info = SETTING_INFO[name] || { label: name };
+ const [min, max] = r.limits[name] || [0, 100];
+ const id = "set-" + name;
+ let input, out = h("output", { for: id });
+ if (info.bool) {
+ input = h("input", { type: "checkbox", id, checked: !!value, onchange: (e) => send(name, e.target.checked ? 1 : 0) });
+ input = h("label", { class: "toggle" }, input, value ? "On" : "Off");
+ input.querySelector("input").addEventListener("change", (e) => (input.lastChild.textContent = e.target.checked ? "On" : "Off"));
+ } else if (info.options) {
+ input = h("select", { id, onchange: (e) => send(name, e.target.value) }, info.options.map((o, i) => h("option", { value: i, selected: i === value }, o)));
+ } else {
+ out.textContent = value + (info.unit || "");
+ input = h("input", { type: "range", id, min, max, value, oninput: (e) => { out.textContent = e.target.value + (info.unit || ""); send(name, e.target.value); } });
+ }
+ return h("div", { class: "setting" }, h("label", { for: id }, info.label), input, out);
+ }));
+}
+
+function debounce(fn, ms) {
+ const timers = {};
+ return (key, ...args) => { clearTimeout(timers[key]); timers[key] = setTimeout(() => fn(key, ...args), ms); };
+}
+
+// ----------------------------------------------------------------- system --
+async function loadSystem() {
+ const info = await guarded(() => state.ctl.info());
+ const rows = [];
+ const add = (k, v) => { if (v != null && v !== "") rows.push(h("dt", {}, k), h("dd", {}, v)); };
+ if (info) {
+ add("Chip", `${info.chip}${info.chip_revision != null ? " rev " + info.chip_revision : ""}${info.cores ? ", " + info.cores + " cores" : ""}${info.cpu_mhz ? " @ " + info.cpu_mhz + " MHz" : ""}`);
+ add("Project", info.project); add("Firmware", info.firmware); add("ESP-IDF", info.idf);
+ add("Built", [info.build_date, info.build_time].filter(Boolean).join(" "));
+ add("Running from", info.running_partition); add("Boots from", info.boot_partition); add("OTA state", info.ota_state);
+ add("Flash", fmtBytes(info.flash_size)); add("PSRAM", fmtBytes(info.psram_size));
+ add("Free heap", fmtBytes(info.free_heap)); add("Lowest free heap", fmtBytes(info.min_free_heap));
+ add("Last reset", info.reset_reason); add("Uptime", fmtUptime(info.uptime_ms)); add("MAC", info.mac);
+ add("ELF SHA-256", info.elf_sha256 ? h("code", {}, info.elf_sha256.slice(0, 16) + "…") : null);
+ }
+ $("infoList").replaceChildren(...rows);
+ const mods = state.discovery?.modules || [];
+ const registry = await loadRegistry();
+ $("modules").tBodies[0].replaceChildren(...mods.map((m) => {
+ const app = m.id === MODULE.CONTROL ? null : appFor(registry, m);
+ return h("tr", {},
+ h("td", {}, `${m.name} `, h("span", { class: "muted small" }, `0x${m.id.toString(16).padStart(2, "0")}`)),
+ h("td", {}, h("code", {}, m.protocol ? `${m.protocol} v${m.version}` : "—")),
+ h("td", { class: "acts" }, app ? h("button", { class: "btn small", title: app, onclick: () => handOff(app, m.id) }, "Open app")
+ : m.id === MODULE.CONTROL ? h("span", { class: "muted small" }, "this page") : null));
+ }));
+}
+
+// espp's hosted apps and the protocols each speaks (the Device Hub's
+// registry.js); a built-in table when it cannot be loaded
+const FALLBACK_APPS = { "espp.ota": "ota_console.html", "espp.coredump": "coredump_console.html", "espp.system": "system_console.html", "espp.monitor": "system_console.html" };
+function loadRegistry() {
+ if (!loadRegistry.p) {
+ loadRegistry.p = new Promise((resolve) => {
+ if (window.ESPP_APPS) { resolve(window.ESPP_APPS); return; }
+ const s = h("script", { src: ESPP_APPS + "registry.js" });
+ s.onload = () => resolve(window.ESPP_APPS || null);
+ s.onerror = () => resolve(null);
+ document.head.append(s);
+ setTimeout(() => resolve(window.ESPP_APPS || null), 4000);
+ });
+ }
+ return loadRegistry.p;
+}
+function appFor(registry, m) {
+ const ok = (f) => typeof f === "string" && /^[\w.-]+\.html$/.test(f);
+ if (registry?.apps && m.protocol) {
+ const app = registry.apps.find((a) => (a.protocols || []).some((p) => p.id === m.protocol && !p.optional))
+ || registry.apps.find((a) => (a.protocols || []).some((p) => p.id === m.protocol));
+ if (app && ok(app.file)) return app.file;
+ }
+ if (FALLBACK_APPS[m.protocol]) return FALLBACK_APPS[m.protocol];
+ return ok(m.app) ? m.app : null;
+}
+
+function handoffUrl(app, moduleId) {
+ const q = new URLSearchParams({ module: String(moduleId), autoconnect: "1", transport: "usb", vid: "0x" + VID.toString(16).padStart(4, "0"), pid: "0x" + PID.toString(16).padStart(4, "0") });
+ if (state.link?.serial) q.set("serial", state.link.serial);
+ return ESPP_APPS + app + "?" + q;
+}
+
+// an espp app opens the device itself: let go of it first
+async function handOff(app, moduleId) {
+ const tab = window.open("about:blank", "_blank");
+ if (!tab) { toast("Allow pop-ups for this page to open the app", true); return; }
+ const url = handoffUrl(app, moduleId);
+ await disconnect();
+ tab.location.href = url;
+ toast("The device was handed to " + app + "; connect again here when you are done.");
+}
+
+async function updateFirmware() {
+ if (!(await confirmModal("Update the firmware?", "The emulator restarts into its updater (a running game is left without saving). The espp OTA console then opens in a new tab: pick build/.bin there.", "Restart into the updater"))) return;
+ const tab = window.open("about:blank", "_blank");
+ if (!tab) { toast("Allow pop-ups for this page to open the OTA console", true); return; }
+ const url = handoffUrl("ota_console.html", MODULE.OTA);
+ try { await state.ctl.enterUpdater(); } catch (e) { tab.close(); toast(e.message || String(e), true); return; }
+ await disconnect();
+ tab.location.href = url;
+}
+
+async function reboot(bootloader) {
+ const text = bootloader ? "The emulator restarts into the ROM download mode, for idf.py flash. It comes back after a flash or a reset." : "The emulator restarts (a running game is left without saving).";
+ if (!(await confirmModal(bootloader ? "Restart into download mode?" : "Restart the emulator?", text, "Restart"))) return;
+ await guarded(() => state.ctl.reboot(bootloader));
+}
+
+// ---------------------------------------------------------------- console --
+const ANSI = /\x1b\[[0-9;]*m/g;
+let logLines = [];
+async function openSerial() {
+ if (!navigator.serial) { toast("This browser has no Web Serial", true); return; }
+ if (state.serial) { await closeSerial(); return; }
+ let port;
+ try {
+ port = await navigator.serial.requestPort({ filters: [{ usbVendorId: VID, usbProductId: PID }] });
+ await port.open({ baudRate: 115200 });
+ } catch (e) {
+ if (e.name !== "NotFoundError") toast(e.message || String(e), true);
+ return;
+ }
+ state.serial = { port, reader: null };
+ $("serialBtn").textContent = "Close the console port";
+ const decoder = new TextDecoder();
+ let partial = "";
+ try {
+ while (state.serial && port.readable) {
+ const reader = port.readable.getReader();
+ state.serial.reader = reader;
+ try {
+ for (;;) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ partial += decoder.decode(value, { stream: true });
+ const lines = partial.split(/\r?\n/);
+ partial = lines.pop();
+ if (lines.length) appendLog(lines);
+ }
+ } finally {
+ reader.releaseLock();
+ }
+ }
+ } catch (e) {
+ if (state.serial) toast("Console: " + (e.message || e), true);
+ }
+ await closeSerial();
+}
+async function closeSerial() {
+ const s = state.serial;
+ state.serial = null;
+ $("serialBtn").textContent = "Open the console port";
+ if (!s) return;
+ try { await s.reader?.cancel(); } catch (_) {}
+ try { await s.port.close(); } catch (_) {}
+}
+function appendLog(lines) {
+ for (const raw of lines) logLines.push(raw.replace(ANSI, ""));
+ if (logLines.length > 5000) logLines = logLines.slice(-5000);
+ renderLog(lines.map((l) => l.replace(ANSI, "")));
+}
+function logLine(text) {
+ const m = /^(?:\[[^\]]*\/)?([IWEDV])[\] (]/.exec(text) || /^\[[^/\]]*\/([IWEDV])\]/.exec(text);
+ return h("div", { class: m ? m[1] : null }, text);
+}
+function renderLog(fresh) {
+ const log = $("log"), f = $("logFilter").value.toLowerCase();
+ if (fresh && !f) {
+ log.append(...fresh.map(logLine));
+ while (log.childElementCount > 5000) log.firstElementChild.remove();
+ } else {
+ log.replaceChildren(...logLines.filter((l) => !f || l.toLowerCase().includes(f)).slice(-2000).map(logLine));
+ }
+ if ($("autoscroll").checked) log.scrollTop = log.scrollHeight;
+}
+
+// ------------------------------------------------------------------- init --
+function init() {
+ if (!navigator.usb) { $("unsupported").hidden = false; $("connectBtn").disabled = true; $("welcomeConnectBtn").disabled = true; }
+ $("connectBtn").onclick = $("welcomeConnectBtn").onclick = () => connect();
+ $("disconnectBtn").onclick = () => disconnect();
+ for (const b of document.querySelectorAll("#tabs button")) b.onclick = () => showTab(b.dataset.tab);
+ for (const b of document.querySelectorAll("[data-goto]")) b.onclick = () => showTab(b.dataset.goto);
+ $("nowQuitBtn").onclick = $("quitBtn").onclick = () => guarded(() => state.ctl.quit(), "Quit");
+ $("driveBtn").onclick = () => guarded(async () => {
+ const host = !state.status?.usb_drive;
+ await state.ctl.usbDrive(host);
+ pollStatus();
+ }, state.status?.usb_drive ? "The emulator has the SD card again" : "The PC has the SD card");
+ $("captureBtn").onclick = () => capture();
+ $("liveToggle").onchange = (e) => { state.live = e.target.checked; if (state.live) liveLoop(); };
+ $("savePngBtn").onclick = () => $("screen").toBlob((b) => download(`screenshot-${Date.now()}.png`, b, "image/png"), "image/png");
+ $("slot").replaceChildren(...[0, 1, 2, 3, 4, 5].map((s) => h("option", { value: s, selected: s === 1 }, "Slot " + s)));
+ $("saveBtn").onclick = () => guarded(() => state.ctl.save(Number($("slot").value)), "Saved to slot " + $("slot").value);
+ $("loadBtn").onclick = () => guarded(() => state.ctl.load(Number($("slot").value)), "Loaded slot " + $("slot").value);
+ initPad();
+ $("libSearch").oninput = (e) => { state.search = e.target.value; renderLibrary(); };
+ $("reloadRomsBtn").onclick = async () => { await guarded(() => state.ctl.reloadRoms()); loadLibrary(true); };
+ $("addGameToggle").onclick = () => ($("addGame").hidden = !$("addGame").hidden);
+ $("addGame").onsubmit = addGame;
+ $("refreshFilesBtn").onclick = () => loadFiles(state.cwd);
+ $("mkdirBtn").onclick = async () => {
+ const name = $("newFolder").value.trim();
+ if (!name || name.includes("/")) return;
+ if (await guarded(() => state.ctl.mkdir(state.cwd + "/" + name)) !== undefined) { $("newFolder").value = ""; loadFiles(state.cwd); }
+ };
+ $("uploadInput").onchange = (e) => { uploadFiles([...e.target.files]); e.target.value = ""; };
+ const drop = $("drop");
+ drop.addEventListener("dragover", (e) => { e.preventDefault(); drop.classList.add("over"); });
+ drop.addEventListener("dragleave", () => drop.classList.remove("over"));
+ drop.addEventListener("drop", (e) => { e.preventDefault(); drop.classList.remove("over"); if (state.ctl) uploadFiles([...e.dataTransfer.files]); });
+ $("infoBtn").onclick = () => loadSystem();
+ $("updateBtn").onclick = () => updateFirmware();
+ $("rebootBtn").onclick = () => reboot(false);
+ $("bootloaderBtn").onclick = () => reboot(true);
+ $("serialBtn").onclick = () => openSerial();
+ $("logFilter").oninput = () => renderLog();
+ $("clearLogBtn").onclick = () => { logLines = []; $("log").replaceChildren(); };
+ $("saveLogBtn").onclick = () => download(`console-${Date.now()}.log`, logLines.join("\n"), "text/plain");
+ addEventListener("keydown", (e) => { if (e.key === "Escape" && !$("modal").hidden) $("modalCancel").click(); });
+ autoConnect();
+}
+
+init();
+// (for the browser console: emuConsole.ctl.status() and so on)
+window.emuConsole = state;
diff --git a/web/index.html b/web/index.html
new file mode 100644
index 0000000..ef566a3
--- /dev/null
+++ b/web/index.html
@@ -0,0 +1,267 @@
+
+
+
+
+
+ Emulator Console
+
+
+
+
+
+
+
+
+
+
Emulator Console
+
esp-box-emu · tab5-emu over USB
+
+
+
+ Not connected
+
+
+
+
+
+
+
+
+
+ This page needs WebUSB: open it in Chrome or Edge on a desktop (Safari and Firefox do not have it).
+
+
+
+
Plug in the emulator and connect
+
Connect over the USB-C port to see what the emulator is doing, browse and start games, watch and play
+ the screen, move files to and from the SD card, change the settings and inspect the system.
+
Nothing to install: the page talks to the device's link interface (WebUSB). Close
+ emulink first, only one program can use the link at a time.
+
+
+
+
+
+
+
+
Now
+
+
+
+
—
+
—
+
+
+
+
+
+
+
+
+
+
Performance
+
+
Frames shown
—
+
Frames dropped
—
+
Game frames
—
+
+
+
+
+
Memory
+
+
+
internal freePSRAM free
+
+
+
Device
+
+
Firmware
—
+
Built
—
+
Partition
—
+
Uptime
—
+
Last reset
—
+
+
+
+
SD card
+
—
+
+
As a USB drive the card belongs to the PC: eject it there before taking it back.
Keyboard (on this tab): arrows, Z = A, X = B, A = X, S = Y, Q / W = L / R, Enter = Start, Shift = Select.
+
+
Save states
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Name
Size
+
Drop files here to copy them into this folder
+
+
+
+
+
+
+
+
Launcher settings
+
Changed here, shown in the launcher right away and saved to the SD card a moment later.
+
+
+
+
+
+
+
+
+
System
+
+
+
+
+
Firmware update
+
The emulator restarts into its updater, and the espp OTA console opens in a new tab to send the new firmware (build/<app>.bin).
+
+
+
+
Restart
+
+
+
+
+
Download mode is for idf.py flash over USB (the updater, a new partition table...).
+
+
+
Services on the link
+
Module
Protocol
+
The generic services have their own espp web apps; opening one hands the device over to it. The espp Device Hub lists them all.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
The console is the device's CDC serial port (Web Serial), separate from the link: pick the port named after the emulator's console.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/web/link.js b/web/link.js
new file mode 100644
index 0000000..114339b
--- /dev/null
+++ b/web/link.js
@@ -0,0 +1,444 @@
+// The emulator link in the browser: espp stream_frame frames over the
+// device's vendor (WebUSB) interface, routed by module, the same protocol as
+// tools/emulink (frame.py, link.py, control.py). Shared, byte for byte, by
+// esp-box-emu and tab5-emu.
+
+export const VID = 0x1209;
+export const PID = 0x0d32;
+/** The USB serial numbers of the emulators, and what to call them. */
+export const DEVICES = {
+ "esp-box-emu": { name: "ESP-Box-Emu", site: "https://esp-cpp.github.io/esp-box-emu/" },
+ "tab5-emu": { name: "Tab5 Emu", site: "https://esp-cpp.github.io/tab5-emu/" },
+};
+
+export const MODULE = { OTA: 0x00, COREDUMP: 0x04, SYSTEM: 0x07, MONITOR: 0x08, CONTROL: 0x20, DISCOVERY: 0xff };
+
+// emu.control request types (main/remote_control.hpp)
+export const T = {
+ STATUS: 0x01, LIST_ROMS: 0x02, LAUNCH: 0x03, QUIT: 0x04, BUTTONS: 0x05, SAVE: 0x06, LOAD: 0x07,
+ SCREENSHOT: 0x08, USB_DRIVE: 0x09, RELOAD_ROMS: 0x0a, ENTER_UPDATER: 0x0b, SCREENSHOT_READ: 0x0c,
+ CONSOLE_FILTER: 0x0d, SETTINGS: 0x0e,
+ FILE_LIST: 0x10, FILE_READ: 0x11, FILE_WRITE: 0x12, FILE_DELETE: 0x13, MKDIR: 0x14, FILE_STAT: 0x15,
+ FILE_CLOSE: 0x16,
+};
+
+/** GamepadState::buttons bits. */
+export const BUTTONS = {
+ a: 1 << 0, b: 1 << 1, x: 1 << 2, y: 1 << 3, select: 1 << 4, start: 1 << 5,
+ up: 1 << 6, down: 1 << 7, left: 1 << 8, right: 1 << 9, l: 1 << 10, r: 1 << 11, l2: 1 << 12, r2: 1 << 13,
+};
+
+export const ROOT = "/sdcard";
+
+// ---------------------------------------------------------------- framing --
+// [magic u16 = 0x4F54][flags u8][module u8][type u8]{[correlation u16]}[len u32][payload][crc32 u32]
+const MAGIC0 = 0x54, MAGIC1 = 0x4f;
+const VERSION = 1, FLAG_REPLY = 0x01, FLAG_CORRELATION = 0x02;
+export const MAX_PAYLOAD = 4096;
+
+const CRC_TABLE = (() => {
+ const t = new Uint32Array(256);
+ for (let i = 0; i < 256; i++) {
+ let c = i;
+ for (let k = 0; k < 8; k++) c = c & 1 ? (c >>> 1) ^ 0xedb88320 : c >>> 1;
+ t[i] = c >>> 0;
+ }
+ return t;
+})();
+
+export function crc32(bytes, end = bytes.length) {
+ let c = 0xffffffff;
+ for (let i = 0; i < end; i++) c = CRC_TABLE[(c ^ bytes[i]) & 0xff] ^ (c >>> 8);
+ return ~c >>> 0;
+}
+
+export function buildFrame(module, type, payload = new Uint8Array(0), correlation = null) {
+ if (payload.length > MAX_PAYLOAD) throw new Error(`payload too large (${payload.length} > ${MAX_PAYLOAD})`);
+ const hdr = 5 + (correlation !== null ? 2 : 0) + 4;
+ const out = new Uint8Array(hdr + payload.length + 4);
+ const v = new DataView(out.buffer);
+ out[0] = MAGIC0; out[1] = MAGIC1;
+ out[2] = (VERSION << 4) | (correlation !== null ? FLAG_CORRELATION : 0);
+ out[3] = module & 0xff; out[4] = type & 0xff;
+ if (correlation !== null) v.setUint16(5, correlation & 0xffff, true);
+ v.setUint32(hdr - 4, payload.length, true);
+ out.set(payload, hdr);
+ v.setUint32(hdr + payload.length, crc32(out, hdr + payload.length), true);
+ return out;
+}
+
+/** Incremental, resynchronizing frame parser. */
+export class Parser {
+ constructor() { this.buf = new Uint8Array(0); }
+ reset() { this.buf = new Uint8Array(0); }
+ feed(data) {
+ const joined = new Uint8Array(this.buf.length + data.length);
+ joined.set(this.buf); joined.set(data, this.buf.length);
+ let b = joined, frames = [];
+ for (;;) {
+ let i = 0;
+ while (i + 1 < b.length && !(b[i] === MAGIC0 && b[i + 1] === MAGIC1)) i++;
+ if (i + 1 >= b.length) { this.buf = b.slice(b.length ? b.length - 1 : 0); return frames; }
+ b = b.subarray(i);
+ if (b.length < 5) break;
+ const flags = b[2];
+ const hdr = 5 + (flags & FLAG_CORRELATION ? 2 : 0) + 4;
+ if (b.length < hdr) break;
+ const v = new DataView(b.buffer, b.byteOffset, b.length);
+ const corr = flags & FLAG_CORRELATION ? v.getUint16(5, true) : null;
+ const len = v.getUint32(hdr - 4, true);
+ if (len > MAX_PAYLOAD) { b = b.subarray(2); continue; } // not a frame: resync past this magic
+ const total = hdr + len + 4;
+ if (b.length < total) break;
+ if (crc32(b, hdr + len) !== v.getUint32(hdr + len, true)) { b = b.subarray(2); continue; }
+ frames.push({ flags, module: b[3], type: b[4], correlation: corr, payload: b.slice(hdr, hdr + len),
+ isReply: !!(flags & FLAG_REPLY) });
+ b = b.subarray(total);
+ }
+ this.buf = b.slice();
+ return frames;
+ }
+}
+
+export class LinkError extends Error {}
+
+// -------------------------------------------------------------- transport --
+/** The vendor interface of one USB device. */
+export class UsbLink {
+ constructor(device) {
+ this.device = device;
+ this.iface = null; this.epIn = null; this.epOut = null;
+ this.parser = new Parser();
+ this.waiters = new Map(); // correlation -> {module, resolve, reject, timer, types}
+ this.corr = 1;
+ this.reading = false;
+ this.onclose = null;
+ this.sendQueue = Promise.resolve(); // frames go out whole, in order
+ }
+
+ get serial() { return this.device.serialNumber || ""; }
+ get product() { return this.device.productName || "USB device"; }
+ get known() { return DEVICES[this.serial] || { name: this.product, site: "" }; }
+
+ /** Ask for a device (the browser's chooser: needs a click). */
+ static async request() {
+ const device = await navigator.usb.requestDevice({ filters: [{ vendorId: VID, productId: PID }] });
+ return new UsbLink(device);
+ }
+
+ /** Devices this page may already open (no chooser), the emulators first. */
+ static async permitted() {
+ if (!navigator.usb) return [];
+ const devs = await navigator.usb.getDevices();
+ return devs.filter((d) => d.vendorId === VID).sort((a, b) => (DEVICES[b.serialNumber] ? 1 : 0) - (DEVICES[a.serialNumber] ? 1 : 0));
+ }
+
+ async open() {
+ const d = this.device;
+ await d.open();
+ if (d.configuration === null) await d.selectConfiguration(1);
+ let found = null;
+ for (const itf of d.configuration.interfaces) {
+ for (const alt of itf.alternates) {
+ if (alt.interfaceClass !== 0xff) continue;
+ const inEp = alt.endpoints.find((e) => e.type === "bulk" && e.direction === "in");
+ const outEp = alt.endpoints.find((e) => e.type === "bulk" && e.direction === "out");
+ if (inEp && outEp) { found = { itf: itf.interfaceNumber, alt: alt.alternateSetting, inEp, outEp }; break; }
+ }
+ if (found) break;
+ }
+ if (!found) throw new LinkError("the device has no vendor interface");
+ await d.claimInterface(found.itf);
+ if (found.alt !== 0) await d.selectAlternateInterface(found.itf, found.alt);
+ this.iface = found.itf; this.epIn = found.inEp.endpointNumber; this.epOut = found.outEp.endpointNumber;
+ this.readLoop();
+ return this;
+ }
+
+ async close() {
+ this.reading = false;
+ for (const w of this.waiters.values()) { clearTimeout(w.timer); w.reject(new LinkError("disconnected")); }
+ this.waiters.clear();
+ try { if (this.iface !== null) await this.device.releaseInterface(this.iface); } catch (_) { /* gone */ }
+ try { await this.device.close(); } catch (_) { /* gone */ }
+ this.iface = null;
+ }
+
+ async readLoop() {
+ this.reading = true;
+ while (this.reading) {
+ let r;
+ try {
+ r = await this.device.transferIn(this.epIn, 16384);
+ } catch (e) {
+ if (this.reading) { this.reading = false; this.failAll(e); if (this.onclose) this.onclose(e); }
+ return;
+ }
+ if (r.status === "stall") { try { await this.device.clearHalt("in", this.epIn); } catch (_) {} continue; }
+ if (!r.data || !r.data.byteLength) continue;
+ for (const f of this.parser.feed(new Uint8Array(r.data.buffer, r.data.byteOffset, r.data.byteLength))) {
+ if (!f.isReply) continue;
+ const w = f.correlation !== null ? this.waiters.get(f.correlation) : null;
+ if (w && w.module === f.module && (!w.types || w.types.includes(f.type))) {
+ this.waiters.delete(f.correlation); clearTimeout(w.timer); w.resolve(f);
+ }
+ }
+ }
+ }
+
+ failAll(e) {
+ for (const w of this.waiters.values()) { clearTimeout(w.timer); w.reject(new LinkError(String(e.message || e))); }
+ this.waiters.clear();
+ }
+
+ async send(bytes) {
+ let sent = 0;
+ while (sent < bytes.length) {
+ const out = await this.device.transferOut(this.epOut, bytes.subarray(sent));
+ if (out.status !== "ok") throw new LinkError("USB write: " + out.status);
+ if (!out.bytesWritten) throw new LinkError("USB write made no progress");
+ sent += out.bytesWritten;
+ }
+ }
+
+ /** A request and its reply (matched by module and correlation id). The
+ * device answers in order, so several can be in flight (see readChunks). */
+ request(module, type, payload = new Uint8Array(0), { timeoutMs = 15000, types = null } = {}) {
+ const corr = this.corr = (this.corr % 0xffff) + 1;
+ const reply = new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ this.waiters.delete(corr);
+ reject(new LinkError(`no reply from module 0x${module.toString(16)} to request 0x${type.toString(16)}`));
+ }, timeoutMs);
+ this.waiters.set(corr, { module, resolve, reject, timer, types });
+ });
+ const frame = buildFrame(module, type, payload, corr);
+ const sent = this.sendQueue.then(() => this.send(frame));
+ this.sendQueue = sent.catch(() => {});
+ return sent.then(() => reply, (e) => {
+ const w = this.waiters.get(corr);
+ if (w) { clearTimeout(w.timer); this.waiters.delete(corr); }
+ throw e;
+ });
+ }
+
+ /** The dispatcher's module list: {name, firmware, modules: [{id, name, protocol, version, ...}]}. */
+ async discover() {
+ const f = await this.request(MODULE.DISCOVERY, 0x00, undefined, { timeoutMs: 3000 });
+ return parseDiscovery(f.payload);
+ }
+}
+
+export function parseDiscovery(p) {
+ let i = 0;
+ const need = (n) => { if (i + n > p.length) throw new Error("truncated discovery reply"); };
+ const u8 = () => { need(1); return p[i++]; };
+ const u16 = () => { need(2); const v = p[i] | (p[i + 1] << 8); i += 2; return v; };
+ const str = () => { const n = u8(); need(n); const s = new TextDecoder().decode(p.subarray(i, i + n)); i += n; return s; };
+ const version = u8(); u8(); // version, reserved
+ const out = { version, name: str(), firmware: str(), modules: [] };
+ const n = u8();
+ for (let k = 0; k < n; k++) {
+ const m = { id: u8(), name: str(), app: str(), description: str(), protocol: "", version: 0 };
+ if (version >= 2) { m.protocol = str(); m.version = u16(); }
+ out.modules.push(m);
+ }
+ return out;
+}
+
+// ---------------------------------------------------------- emu.control --
+const enc = new TextEncoder(), dec = new TextDecoder();
+const u32le = (v) => { const b = new Uint8Array(4); new DataView(b.buffer).setUint32(0, v, true); return b; };
+const u16le = (v) => { const b = new Uint8Array(2); new DataView(b.buffer).setUint16(0, v, true); return b; };
+const cat = (...parts) => {
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
+ let o = 0;
+ for (const p of parts) { out.set(p, o); o += p.length; }
+ return out;
+};
+
+export class ControlError extends Error {}
+
+/** The emulator's control module (0x20) and the espp system service (7). */
+export class Control {
+ constructor(link) { this.link = link; }
+
+ async call(type, payload = new Uint8Array(0), { timeoutMs = 15000, raw = false } = {}) {
+ if (typeof payload === "string") payload = enc.encode(payload);
+ const f = await this.link.request(MODULE.CONTROL, type, payload, { timeoutMs });
+ if (!f.payload.length) throw new ControlError("empty reply");
+ const body = f.payload.subarray(1);
+ if (f.payload[0] !== 0) {
+ let msg = dec.decode(body);
+ try { msg = JSON.parse(msg).error || msg; } catch (_) { /* plain text */ }
+ throw new ControlError(msg);
+ }
+ if (raw) return body;
+ return body.length ? JSON.parse(dec.decode(body)) : {};
+ }
+
+ remote(path) {
+ if (!path || path === "/" || path === ".") return ROOT;
+ if (path.startsWith(ROOT)) return path;
+ return ROOT + "/" + path.replace(/^\/+/, "");
+ }
+
+ status() { return this.call(T.STATUS); }
+
+ async roms() {
+ let out = [], offset = 0;
+ for (;;) {
+ const r = await this.call(T.LIST_ROMS, String(offset));
+ out = out.concat(r.roms);
+ offset = r.next;
+ if (offset >= r.total || !r.roms.length) return out;
+ }
+ }
+
+ launch(match) { return this.call(T.LAUNCH, match, { timeoutMs: 30000 }); }
+ quit() { return this.call(T.QUIT, undefined, { timeoutMs: 30000 }); }
+ buttons(mask, holdMs = 0) { return this.call(T.BUTTONS, cat(u16le(mask), u16le(holdMs)), { timeoutMs: holdMs + 5000 }); }
+ save(slot) { return this.call(T.SAVE, new Uint8Array([slot]), { timeoutMs: 60000 }); }
+ load(slot) { return this.call(T.LOAD, new Uint8Array([slot]), { timeoutMs: 60000 }); }
+ usbDrive(host) { return this.call(T.USB_DRIVE, new Uint8Array([host ? 1 : 0]), { timeoutMs: 20000 }); }
+ reloadRoms() { return this.call(T.RELOAD_ROMS); }
+ enterUpdater() { return this.call(T.ENTER_UPDATER); }
+ consoleFilter(key) { return this.call(T.CONSOLE_FILTER, key || "all"); }
+ settings(change) { return this.call(T.SETTINGS, change || ""); }
+
+ /** `size` bytes read in 4000-byte chunks, `depth` requests in flight
+ * (the device answers in order; a short chunk is an error: the size is known). */
+ async readChunks(size, request, progress, depth = 4) {
+ const out = new Uint8Array(size);
+ const CH = 4000;
+ let next = 0, done = 0;
+ const one = async () => {
+ while (next < size) {
+ const off = next, n = Math.min(CH, size - off);
+ next += n;
+ const chunk = await request(off, n);
+ if (chunk.length !== n) throw new ControlError(`short read: ${off + chunk.length} of ${size} B`);
+ out.set(chunk, off); done += n;
+ if (progress) progress(done, size);
+ }
+ };
+ await Promise.all(Array.from({ length: Math.min(depth, Math.ceil(size / CH)) }, one));
+ return out;
+ }
+
+ /** The running game's frame, or the launcher's screen: {width, height, format, source, data}. */
+ async frame(progress) {
+ const info = await this.call(T.SCREENSHOT, undefined, { timeoutMs: 15000 });
+ // (the last chunk read lets the game go on: it must be the last one asked for)
+ const last = Math.max(0, info.size - 4000 > 0 ? info.size - ((info.size % 4000) || 4000) : 0);
+ const head = await this.readChunks(last, (off, n) => this.call(T.SCREENSHOT_READ, cat(u32le(off), u16le(n)), { raw: true }), progress);
+ const tail = await this.call(T.SCREENSHOT_READ, cat(u32le(last), u16le(info.size - last)), { raw: true });
+ if (tail.length !== info.size - last) throw new ControlError(`short read at the end of the frame`);
+ const data = new Uint8Array(info.size);
+ data.set(head); data.set(tail, last);
+ if (progress) progress(info.size, info.size);
+ return { ...info, data };
+ }
+
+ // files on the SD card
+ async ls(path) {
+ const p = this.remote(path);
+ let r = await this.call(T.FILE_LIST, p);
+ let out = r.entries;
+ while (r.truncated && r.next != null && r.entries.length) {
+ r = await this.call(T.FILE_LIST, p + "\0" + r.next);
+ out = out.concat(r.entries);
+ }
+ return out;
+ }
+ async stat(path) {
+ try { return await this.call(T.FILE_STAT, this.remote(path)); } catch (e) {
+ if (String(e.message).includes("does not exist")) return null;
+ throw e;
+ }
+ }
+ mkdir(path) { return this.call(T.MKDIR, this.remote(path)); }
+ rm(path) { return this.call(T.FILE_DELETE, this.remote(path), { timeoutMs: 120000 }); }
+
+ async readFile(path, progress) {
+ const p = enc.encode(this.remote(path));
+ const st = await this.call(T.FILE_STAT, p);
+ return this.readChunks(st.size, (off, n) => this.call(T.FILE_READ, cat(u32le(off), u16le(n), p), { raw: true }), progress);
+ }
+
+ async writeFile(path, data, progress) {
+ const p = enc.encode(this.remote(path));
+ const chunk = 3584 - p.length; // the frame payload is at most 4096 bytes
+ if (chunk < 256) throw new ControlError("path too long");
+ let off = 0;
+ do {
+ const part = data.subarray(off, off + chunk);
+ await this.call(T.FILE_WRITE, cat(u32le(off), u16le(p.length), p, part), { timeoutMs: 30000 });
+ off += part.length;
+ if (progress) progress(off, data.length);
+ } while (off < data.length);
+ await this.call(T.FILE_CLOSE);
+ }
+
+ /** Add (or remove) a metadata.csv line; returns the number of games after the reload. */
+ async addRom(romPath, name, boxart = "", remove = false) {
+ const rel = romPath.startsWith(ROOT + "/") ? romPath.slice(ROOT.length + 1) : romPath;
+ for (const [field, value] of [["ROM path", rel], ["boxart path", boxart], ["name", name]]) {
+ if (/[\r\n]/.test(value) || (field !== "name" && value.includes(",")))
+ throw new ControlError(`the ${field} cannot hold ${value.includes(",") ? "a comma" : "a line break"}`);
+ }
+ const meta = "metadata.csv";
+ // only a missing file starts an empty list: a failed read must not rewrite it
+ const text = (await this.stat(meta)) ? dec.decode(await this.readFile(meta)) : "";
+ const lines = text.split(/\r?\n/).filter((l) => l.trim() && l.split(",")[0].trim() !== rel);
+ if (!remove) lines.push(`${rel}, ${boxart}, ${name}`);
+ await this.writeFile(meta, enc.encode(lines.join("\n") + "\n"));
+ return (await this.reloadRoms()).total;
+ }
+
+ // the espp system service
+ async info() {
+ const f = await this.link.request(MODULE.SYSTEM, 0x01, undefined, { timeoutMs: 5000, types: [0x81, 0x84] });
+ if (f.type !== 0x81) throw new ControlError("GET_INFO failed");
+ const p = f.payload, out = {};
+ const strs = { 1: "chip", 5: "idf", 6: "project", 7: "firmware", 8: "build_date", 9: "build_time",
+ 11: "running_partition", 12: "boot_partition" };
+ const le = (v) => v.reduceRight((n, b) => n * 256 + b, 0);
+ for (let i = 0; i + 2 <= p.length;) {
+ const tag = p[i], n = p[i + 1], v = p.subarray(i + 2, i + 2 + n);
+ i += 2 + n;
+ if (strs[tag]) out[strs[tag]] = dec.decode(v);
+ else if (tag === 2) out.chip_revision = le(v);
+ else if (tag === 3) out.cores = v[0];
+ else if (tag === 10) out.elf_sha256 = [...v].map((b) => b.toString(16).padStart(2, "0")).join("");
+ else if (tag === 13) out.ota_state = { 0: "new", 1: "pending verify", 2: "valid", 3: "invalid", 4: "aborted", 0xfe: "undefined", 0xff: "n/a" }[v[0]] ?? v[0];
+ else if (tag === 14) out.reset_reason = RESET_REASONS[v[0]] ?? v[0];
+ else if (tag === 15) out.uptime_ms = le(v);
+ else if (tag === 16) out.mac = [...v].map((b) => b.toString(16).padStart(2, "0")).join(":");
+ else if (tag >= 17 && tag <= 21) out[{ 17: "flash_size", 18: "psram_size", 19: "cpu_mhz", 20: "free_heap", 21: "min_free_heap" }[tag]] = le(v);
+ }
+ return out;
+ }
+
+ reboot(bootloader = false, delayMs = 250) {
+ return this.link.request(MODULE.SYSTEM, bootloader ? 0x03 : 0x02, u16le(delayMs), { timeoutMs: 5000, types: [0x83, 0x84] });
+ }
+}
+
+export const RESET_REASONS = {
+ 0: "unknown", 1: "power-on", 2: "external", 3: "software", 4: "panic", 5: "interrupt WDT", 6: "task WDT",
+ 7: "other WDT", 8: "deep sleep", 9: "brownout", 10: "SDIO", 11: "USB", 12: "JTAG", 13: "eFuse",
+ 14: "power glitch", 15: "CPU lockup",
+};
+
+/** RGB565 pixels (rows packed) into an ImageData. */
+export function rgb565ToImageData(data, width, height, bigEndian = false) {
+ const img = new ImageData(width, height);
+ const px = img.data;
+ for (let i = 0, j = 0; i + 1 < data.length && j < px.length; i += 2, j += 4) {
+ const v = bigEndian ? (data[i] << 8) | data[i + 1] : data[i] | (data[i + 1] << 8);
+ const r = (v >> 11) & 0x1f, g = (v >> 5) & 0x3f, b = v & 0x1f;
+ px[j] = (r << 3) | (r >> 2); px[j + 1] = (g << 2) | (g >> 4); px[j + 2] = (b << 3) | (b >> 2); px[j + 3] = 255;
+ }
+ return img;
+}
From 13c5a11aeb805150a9f59e79f912f199498df4d4 Mon Sep 17 00:00:00 2001
From: William Emfinger
Date: Fri, 13 Nov 2026 09:00:51 -0600
Subject: [PATCH 03/15] web: history graphs fill their width from the first
samples
Co-Authored-By: Claude Opus 5.5 (1M context)
Claude-Session: https://claude.ai/code/session_01SFCMzomCZ5wRHJN4sxwkvY
---
web/app.js | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/web/app.js b/web/app.js
index e94d8c5..938fbfd 100644
--- a/web/app.js
+++ b/web/app.js
@@ -239,7 +239,7 @@ function drawSpark(canvas, series, colors) {
const max = Math.max(...s) * 1.1 || 1, min = 0;
g.strokeStyle = colors[k]; g.lineWidth = 1.5; g.beginPath();
s.forEach((v, i) => {
- const x = (i / (120 - 1)) * w, y = hh - 2 - ((v - min) / (max - min)) * (hh - 4);
+ const x = (i / (s.length - 1)) * w, y = hh - 2 - ((v - min) / (max - min)) * (hh - 4);
i ? g.lineTo(x, y) : g.moveTo(x, y);
});
g.stroke();
From 400f7c53a4c21af48dbe244fcfb40b623437b495 Mon Sep 17 00:00:00 2001
From: William Emfinger
Date: Fri, 13 Nov 2026 09:00:51 -0600
Subject: [PATCH 04/15] Pin esp_tinyusb to 3.0.0
esp_tinyusb 3.0.1 (TinyUSB 0.21.0~6, the DWC2 SETUP-DMA erratum
workaround) corrupts the PSRAM heap on esp-box-emu while a Genesis game
runs (the link task's next allocation hits a tlsf assert or an MMU entry
fault); 3.0.0 is fine. The Tab5 shares the USB device code, and a fresh
build resolves '>=3.0.0' to 3.0.1, so pin it here too.
Co-Authored-By: Claude Opus 5.5 (1M context)
Claude-Session: https://claude.ai/code/session_01SFCMzomCZ5wRHJN4sxwkvY
---
components/tab5-emu/idf_component.yml | 5 +++++
1 file changed, 5 insertions(+)
diff --git a/components/tab5-emu/idf_component.yml b/components/tab5-emu/idf_component.yml
index af30d2e..0e760a4 100644
--- a/components/tab5-emu/idf_component.yml
+++ b/components/tab5-emu/idf_component.yml
@@ -17,6 +17,11 @@ dependencies:
espp/timer: '>=1.3'
# USB mass storage (the SD card as a USB drive), brings esp_tinyusb; needs
# UsbDevice::Config::port (the Tab5's USB-C is the P4's full-speed port)
+ # Pinned: esp_tinyusb 3.0.1 (TinyUSB 0.21.0~6: the DWC2 SETUP-DMA erratum
+ # workaround) corrupts the PSRAM heap on esp-box-emu while a Genesis game
+ # runs (tlsf asserts / MMU faults on the next allocation in the link task);
+ # 3.0.0 does not. Lift once that is understood upstream.
+ espressif/esp_tinyusb: '==3.0.0'
espp/usb_device:
# TEMP: take_msc_from_ejected_host() (esp-cpp/espp#898, merged as
# 08295c0); back to the registry once it is released
From 6c3403356fc8b741d313a3f6f37f8c51a78e9af1 Mon Sep 17 00:00:00 2001
From: William Emfinger
Date: Fri, 13 Nov 2026 10:11:26 -0600
Subject: [PATCH 05/15] Revert "Pin esp_tinyusb to 3.0.0"
The heap corruption seen with Sonic 2 on the box turned out to be
intermittent: the same builds that failed also pass repeated trials, so
the runs that blamed esp_tinyusb 3.0.1 were not evidence of a cause. The
corruption is tracked separately; no pin until it is understood.
Co-Authored-By: Claude Opus 5.5 (1M context)
Claude-Session: https://claude.ai/code/session_01SFCMzomCZ5wRHJN4sxwkvY
---
components/tab5-emu/idf_component.yml | 5 -----
1 file changed, 5 deletions(-)
diff --git a/components/tab5-emu/idf_component.yml b/components/tab5-emu/idf_component.yml
index 0e760a4..af30d2e 100644
--- a/components/tab5-emu/idf_component.yml
+++ b/components/tab5-emu/idf_component.yml
@@ -17,11 +17,6 @@ dependencies:
espp/timer: '>=1.3'
# USB mass storage (the SD card as a USB drive), brings esp_tinyusb; needs
# UsbDevice::Config::port (the Tab5's USB-C is the P4's full-speed port)
- # Pinned: esp_tinyusb 3.0.1 (TinyUSB 0.21.0~6: the DWC2 SETUP-DMA erratum
- # workaround) corrupts the PSRAM heap on esp-box-emu while a Genesis game
- # runs (tlsf asserts / MMU faults on the next allocation in the link task);
- # 3.0.0 does not. Lift once that is understood upstream.
- espressif/esp_tinyusb: '==3.0.0'
espp/usb_device:
# TEMP: take_msc_from_ejected_host() (esp-cpp/espp#898, merged as
# 08295c0); back to the registry once it is released
From 57799db3a88e2754bb63189875ff5b9a8634b85d Mon Sep 17 00:00:00 2001
From: William Emfinger
Date: Fri, 13 Nov 2026 10:11:42 -0600
Subject: [PATCH 06/15] Revert "Pin esp_tinyusb to 3.0.0"
The heap corruption seen with Sonic 2 on the box turned out to be
intermittent: the same builds that failed also pass repeated trials, so
the runs that blamed esp_tinyusb 3.0.1 were not evidence of a cause. The
corruption is tracked separately; no pin until it is understood.
Co-Authored-By: Claude Opus 5.5 (1M context)
Claude-Session: https://claude.ai/code/session_01SFCMzomCZ5wRHJN4sxwkvY
---
components/tab5-emu/idf_component.yml | 5 -----
1 file changed, 5 deletions(-)
diff --git a/components/tab5-emu/idf_component.yml b/components/tab5-emu/idf_component.yml
index 0e760a4..af30d2e 100644
--- a/components/tab5-emu/idf_component.yml
+++ b/components/tab5-emu/idf_component.yml
@@ -17,11 +17,6 @@ dependencies:
espp/timer: '>=1.3'
# USB mass storage (the SD card as a USB drive), brings esp_tinyusb; needs
# UsbDevice::Config::port (the Tab5's USB-C is the P4's full-speed port)
- # Pinned: esp_tinyusb 3.0.1 (TinyUSB 0.21.0~6: the DWC2 SETUP-DMA erratum
- # workaround) corrupts the PSRAM heap on esp-box-emu while a Genesis game
- # runs (tlsf asserts / MMU faults on the next allocation in the link task);
- # 3.0.0 does not. Lift once that is understood upstream.
- espressif/esp_tinyusb: '==3.0.0'
espp/usb_device:
# TEMP: take_msc_from_ejected_host() (esp-cpp/espp#898, merged as
# 08295c0); back to the registry once it is released
From 7613e0d1b4a9b5c4e9b346b71e63787e5e38f8d3 Mon Sep 17 00:00:00 2001
From: William Emfinger
Date: Fri, 13 Nov 2026 21:32:32 -0600
Subject: [PATCH 07/15] Console filter: close the picker on return from a game;
read-only filter query
A game started from the PC (emulink launch) with the console picker open
left it on screen after the game while the keypad drove the list behind
it: resume() closes it. CONSOLE_FILTER takes "?" as a query that changes
nothing, and emulink filter with no argument uses it instead of writing
the current filter back.
Co-Authored-By: Claude Opus 5.5 (1M context)
Claude-Session: https://claude.ai/code/session_01SFCMzomCZ5wRHJN4sxwkvY
---
components/gui/src/gui.cpp | 3 +++
main/remote_control.hpp | 9 +++++++--
tools/emulink/emulink/control.py | 3 +--
3 files changed, 11 insertions(+), 4 deletions(-)
diff --git a/components/gui/src/gui.cpp b/components/gui/src/gui.cpp
index 54687b1..4601219 100644
--- a/components/gui/src/gui.cpp
+++ b/components/gui/src/gui.cpp
@@ -47,6 +47,9 @@ 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();
update_rom_list();
update_shared_state();
lv_screen_load(screen_);
diff --git a/main/remote_control.hpp b/main/remote_control.hpp
index fb80e28..0413ed5 100644
--- a/main/remote_control.hpp
+++ b/main/remote_control.hpp
@@ -132,8 +132,9 @@ class RemoteControl {
RELOAD_ROMS = 0x0A, ///< () re-read metadata.csv
ENTER_UPDATER = 0x0B, ///< () reboot into the updater app (ota_1) for an update
SCREENSHOT_READ = 0x0C, ///< (u32 offset, u16 length) -> raw bytes of the held SCREENSHOT (short at the end)
- /// (console key: text, e.g. "snes"; empty or "all" for every console) ->
- /// {filter, consoles: [keys]}: the launcher's list shows only that console's games
+ /// (console key: text, e.g. "snes"; empty or "all" for every console; "?"
+ /// changes nothing, only reports) -> {filter, consoles: [keys]}: the
+ /// launcher's list shows only that console's games
CONSOLE_FILTER = 0x0D,
FILE_LIST = 0x10, ///< (path[\0offset]) -> {entries: [{name, dir, size}], truncated?, next?}
FILE_READ = 0x11, ///< (u32 offset, u16 length, path) -> raw bytes (short at the end)
@@ -467,6 +468,10 @@ class RemoteControl {
std::string key(text);
std::transform(key.begin(), key.end(), key.begin(),
[](unsigned char c) { return static_cast(std::tolower(c)); });
+ if (key == "?") { // a query: report the filter without touching the list
+ json(filter_json());
+ break;
+ }
const auto present = gui_.consoles();
bool done = false;
if (key.empty() || key == "all") {
diff --git a/tools/emulink/emulink/control.py b/tools/emulink/emulink/control.py
index dc3140f..188dda0 100644
--- a/tools/emulink/emulink/control.py
+++ b/tools/emulink/emulink/control.py
@@ -205,8 +205,7 @@ def console_filter(self, console: str | None = None) -> dict:
"""Set the launcher's console filter (a console key such as "snes", or
"all"); with None, only report it. -> {filter, consoles}"""
if console is None:
- console = self.status().get("filter", "")
- # (an empty filter would clear it: ask for the same one again)
+ return self._call(CONSOLE_FILTER, b"?") # a query: changes nothing
return self._call(CONSOLE_FILTER, (console or "all").encode())
def reload_roms(self) -> int:
From 4e80ee99953ce7c5b01af75aab67ff51ed0c9b97 Mon Sep 17 00:00:00 2001
From: William Emfinger
Date: Fri, 13 Nov 2026 21:34:16 -0600
Subject: [PATCH 08/15] Web console: no reconnect after a hand-off, release
held buttons, per-device caches, serialized file edits
- Automatic reconnection only follows a lost link: a disconnect asked for
here, a hand-off to another app and the OTA hand-off (whose updater
comes up with the same serial) turn it off, and a scheduled reconnect
checks again before it runs.
- The core-dump link hands the device off like the System tab's buttons.
- A button held while the page disconnects is released on the device
first; the pad forgets it; a new connection releases stale input.
- Box art and the last capture are dropped with the link (reads in flight
check their session); missing art is retried once the library reloads
or the card comes back from the PC.
- File writes, deletes and the whole metadata.csv read-modify-write-reload
run one at a time per Control.
Co-Authored-By: Claude Opus 5.5 (1M context)
Claude-Session: https://claude.ai/code/session_01SFCMzomCZ5wRHJN4sxwkvY
---
web/app.js | 66 +++++++++++++++++++++++++++++++++++++++++++++--------
web/link.js | 23 +++++++++++++++----
2 files changed, 75 insertions(+), 14 deletions(-)
diff --git a/web/app.js b/web/app.js
index 938fbfd..cf88bc4 100644
--- a/web/app.js
+++ b/web/app.js
@@ -29,6 +29,9 @@ const state = {
tab: "dashboard", statusTimer: null, lastFrames: null, fpsHistory: [], memHistory: [],
filter: "", search: "", cwd: ROOT, files: [], live: false, lastShot: null, slot: 1,
boxart: new Map(), boxartQueue: [], boxartBusy: false, settings: null, serial: null,
+ // a device that comes back after the link was lost is opened again; off after
+ // a disconnect asked for here or a hand-off to another app (which takes it)
+ reconnect: true, reconnectGen: 0,
};
// ------------------------------------------------------------------ helpers --
@@ -95,7 +98,10 @@ async function connect(device) {
}
state.link = link;
state.ctl = new Control(link);
+ state.reconnect = true;
link.onclose = () => onLinkLost();
+ // input a page lost track of (its link died with a button held) is let go
+ state.ctl.buttons(0, 0).catch(() => {});
try { state.discovery = await link.discover(); } catch (_) { state.discovery = null; }
try { localStorage.setItem("emu-console-serial", link.serial); } catch (_) {}
$("connectBtn").hidden = true; $("disconnectBtn").hidden = false;
@@ -114,9 +120,13 @@ async function connect(device) {
async function disconnect() {
clearInterval(state.statusTimer); state.statusTimer = null;
stopLive();
- const link = state.link;
+ const link = state.link, ctl = state.ctl;
+ // a button still held here would stay pressed in the game
+ if (heldMask && ctl && link?.reading) { try { await ctl.buttons(0, 0); } catch (_) {} }
+ releasePad();
state.link = null; state.ctl = null; state.status = null; state.romsLoaded = false; state.settings = null;
if (link) { link.onclose = null; await link.close(); }
+ forgetDevice();
$("connectBtn").hidden = false; $("disconnectBtn").hidden = true;
$("welcome").hidden = false;
for (const p of document.querySelectorAll("[data-panel]")) p.hidden = true;
@@ -133,12 +143,31 @@ function onLinkLost() {
});
}
+// What this page knew about the device's card (box art, the last capture):
+// dropped with the link, so another board (or the same card changed meanwhile)
+// is not shown stale pictures. Reads still in flight check their session.
+function forgetDevice() {
+ for (const url of state.boxart.values()) if (url) URL.revokeObjectURL(url);
+ state.boxart.clear(); state.boxartQueue = [];
+ state.lastShot = null;
+ const c = $("screen"); c.getContext("2d").clearRect(0, 0, c.width, c.height);
+ $("screenInfo").textContent = ""; $("savePngBtn").disabled = true;
+}
+
+// A disconnect asked for (the button, a hand-off): no automatic reconnection,
+// also not for a connect event already scheduled.
+async function disconnectByUser() {
+ state.reconnect = false; state.reconnectGen++; state.waitingFor = null;
+ await disconnect();
+}
+
// a device that comes back (after a restart) is opened again without the chooser
if (navigator.usb) {
navigator.usb.addEventListener("connect", (ev) => {
- if (state.link || !DEVICES[ev.device.serialNumber]) return;
+ if (state.link || !state.reconnect || !DEVICES[ev.device.serialNumber]) return;
if (state.waitingFor && ev.device.serialNumber !== state.waitingFor) return;
- setTimeout(() => connect(ev.device), 1200);
+ const gen = state.reconnectGen;
+ setTimeout(() => { if (!state.link && state.reconnect && gen === state.reconnectGen) connect(ev.device); }, 1200);
});
}
@@ -220,11 +249,13 @@ function renderStatus(prev) {
$("panicCard").hidden = !st.last_panic;
$("panicText").textContent = st.last_panic || "";
$("coredumpLink").href = handoffUrl("coredump_console.html", MODULE.COREDUMP);
+ $("coredumpLink").onclick = (ev) => { ev.preventDefault(); handOff("coredump_console.html", MODULE.COREDUMP); };
// the game started or ended: the list, the screen and the buttons follow
if (prev && (prev.state !== st.state || prev.rom !== st.rom)) {
if (state.tab === "library") renderLibrary();
if (state.tab === "screen" && !state.live) capture();
}
+ if (prev?.usb_drive && !st.usb_drive) forgetBoxartFailures();
if (prev && prev.filter !== st.filter && state.tab === "library") { state.filter = st.filter || ""; renderLibrary(); }
}
@@ -291,6 +322,11 @@ async function liveLoop() {
function stopLive() { state.live = false; $("liveToggle").checked = false; }
let heldMask = 0;
+// forget the held buttons and their pressed look (the link is going away)
+function releasePad() {
+ heldMask = 0;
+ for (const b of document.querySelectorAll("#pad .down-now")) b.classList.remove("down-now");
+}
const setButtons = (mask) => {
heldMask = mask;
if (state.ctl) state.ctl.buttons(mask, 0).catch((e) => toast("Buttons: " + (e.message || e), true));
@@ -327,6 +363,7 @@ async function loadLibrary(force = false) {
const roms = await guarded(() => state.ctl.roms());
if (!roms) return;
state.roms = roms; state.romsLoaded = true;
+ forgetBoxartFailures();
state.filter = state.status?.filter || "";
const folders = [...new Set(roms.map((r) => dirname(r.path).slice(ROOT.length + 1)).filter(Boolean))].sort();
$("folders").replaceChildren(...folders.map((f) => h("option", { value: f })));
@@ -405,6 +442,12 @@ function observeArt() {
for (const img of document.querySelectorAll("#lib img[data-art]")) if (!img.src) artObserver.observe(img);
}
+// Missing box art is not asked for again on every status poll, only once the
+// card may have changed: the library reloaded, or the card back from the PC.
+function forgetBoxartFailures() {
+ for (const [path, url] of state.boxart) if (!url) state.boxart.delete(path);
+}
+
function queueBoxart(path, done) {
if (state.boxart.has(path)) { done(state.boxart.get(path)); return; }
state.boxartQueue.push({ path, done });
@@ -416,13 +459,16 @@ async function pumpBoxart() {
while (state.boxartQueue.length && state.ctl) {
const { path, done } = state.boxartQueue.shift();
if (state.boxart.has(path)) { done(state.boxart.get(path)); continue; }
+ const ctl = state.ctl;
try {
- const data = await state.ctl.readFile(path);
+ const data = await ctl.readFile(path);
+ if (ctl !== state.ctl) continue; // the link changed meanwhile: not this device's
const url = URL.createObjectURL(new Blob([data], { type: "image/jpeg" }));
state.boxart.set(path, url);
done(url);
} catch (_) {
- state.boxart.set(path, null);
+ if (ctl !== state.ctl) continue;
+ state.boxart.set(path, null); // (forgotten again by forgetBoxartFailures())
done(null);
}
}
@@ -631,7 +677,7 @@ async function handOff(app, moduleId) {
const tab = window.open("about:blank", "_blank");
if (!tab) { toast("Allow pop-ups for this page to open the app", true); return; }
const url = handoffUrl(app, moduleId);
- await disconnect();
+ await disconnectByUser();
tab.location.href = url;
toast("The device was handed to " + app + "; connect again here when you are done.");
}
@@ -641,8 +687,10 @@ async function updateFirmware() {
const tab = window.open("about:blank", "_blank");
if (!tab) { toast("Allow pop-ups for this page to open the OTA console", true); return; }
const url = handoffUrl("ota_console.html", MODULE.OTA);
- try { await state.ctl.enterUpdater(); } catch (e) { tab.close(); toast(e.message || String(e), true); return; }
- await disconnect();
+ // the updater comes up with the same serial: it is the OTA console's, not ours
+ state.reconnect = false; state.reconnectGen++;
+ try { await state.ctl.enterUpdater(); } catch (e) { state.reconnect = true; tab.close(); toast(e.message || String(e), true); return; }
+ await disconnectByUser();
tab.location.href = url;
}
@@ -724,7 +772,7 @@ function renderLog(fresh) {
function init() {
if (!navigator.usb) { $("unsupported").hidden = false; $("connectBtn").disabled = true; $("welcomeConnectBtn").disabled = true; }
$("connectBtn").onclick = $("welcomeConnectBtn").onclick = () => connect();
- $("disconnectBtn").onclick = () => disconnect();
+ $("disconnectBtn").onclick = () => disconnectByUser();
for (const b of document.querySelectorAll("#tabs button")) b.onclick = () => showTab(b.dataset.tab);
for (const b of document.querySelectorAll("[data-goto]")) b.onclick = () => showTab(b.dataset.goto);
$("nowQuitBtn").onclick = $("quitBtn").onclick = () => guarded(() => state.ctl.quit(), "Quit");
diff --git a/web/link.js b/web/link.js
index 114339b..5973952 100644
--- a/web/link.js
+++ b/web/link.js
@@ -261,7 +261,16 @@ export class ControlError extends Error {}
/** The emulator's control module (0x20) and the espp system service (7). */
export class Control {
- constructor(link) { this.link = link; }
+ constructor(link) { this.link = link; this.fileQueue = Promise.resolve(); }
+
+ /** Run `fn` after every earlier file change has finished: the device has one
+ * open file across FILE_WRITE / FILE_CLOSE, and a metadata.csv edit is a
+ * read-modify-write that another edit must not interleave with. */
+ exclusive(fn) {
+ const run = this.fileQueue.then(fn, fn);
+ this.fileQueue = run.catch(() => {});
+ return run;
+ }
async call(type, payload = new Uint8Array(0), { timeoutMs = 15000, raw = false } = {}) {
if (typeof payload === "string") payload = enc.encode(payload);
@@ -358,7 +367,7 @@ export class Control {
}
}
mkdir(path) { return this.call(T.MKDIR, this.remote(path)); }
- rm(path) { return this.call(T.FILE_DELETE, this.remote(path), { timeoutMs: 120000 }); }
+ rm(path) { return this.exclusive(() => this.call(T.FILE_DELETE, this.remote(path), { timeoutMs: 120000 })); }
async readFile(path, progress) {
const p = enc.encode(this.remote(path));
@@ -366,7 +375,8 @@ export class Control {
return this.readChunks(st.size, (off, n) => this.call(T.FILE_READ, cat(u32le(off), u16le(n), p), { raw: true }), progress);
}
- async writeFile(path, data, progress) {
+ writeFile(path, data, progress) { return this.exclusive(() => this.writeFileNow(path, data, progress)); }
+ async writeFileNow(path, data, progress) {
const p = enc.encode(this.remote(path));
const chunk = 3584 - p.length; // the frame payload is at most 4096 bytes
if (chunk < 256) throw new ControlError("path too long");
@@ -381,7 +391,10 @@ export class Control {
}
/** Add (or remove) a metadata.csv line; returns the number of games after the reload. */
- async addRom(romPath, name, boxart = "", remove = false) {
+ addRom(romPath, name, boxart = "", remove = false) {
+ return this.exclusive(() => this.addRomNow(romPath, name, boxart, remove));
+ }
+ async addRomNow(romPath, name, boxart, remove) {
const rel = romPath.startsWith(ROOT + "/") ? romPath.slice(ROOT.length + 1) : romPath;
for (const [field, value] of [["ROM path", rel], ["boxart path", boxart], ["name", name]]) {
if (/[\r\n]/.test(value) || (field !== "name" && value.includes(",")))
@@ -392,7 +405,7 @@ export class Control {
const text = (await this.stat(meta)) ? dec.decode(await this.readFile(meta)) : "";
const lines = text.split(/\r?\n/).filter((l) => l.trim() && l.split(",")[0].trim() !== rel);
if (!remove) lines.push(`${rel}, ${boxart}, ${name}`);
- await this.writeFile(meta, enc.encode(lines.join("\n") + "\n"));
+ await this.writeFileNow(meta, enc.encode(lines.join("\n") + "\n"));
return (await this.reloadRoms()).total;
}
From 1a10e0eca13dd563ca88fd297d4698234ee32279 Mon Sep 17 00:00:00 2001
From: William Emfinger
Date: Fri, 13 Nov 2026 21:58:52 -0600
Subject: [PATCH 09/15] Console filter: select a remotely chosen game once;
intptr_t for button indices; tolerant emulink filter output
Co-Authored-By: Claude Opus 5.5 (1M context)
Claude-Session: https://claude.ai/code/session_01SFCMzomCZ5wRHJN4sxwkvY
---
components/gui/src/gui.cpp | 8 +++++---
tools/emulink/emulink/cli.py | 2 +-
2 files changed, 6 insertions(+), 4 deletions(-)
diff --git a/components/gui/src/gui.cpp b/components/gui/src/gui.cpp
index 4601219..15d27ab 100644
--- a/components/gui/src/gui.cpp
+++ b/components/gui/src/gui.cpp
@@ -316,7 +316,7 @@ void Gui::build_list(int keep_rom) {
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(i));
+ 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);
@@ -598,12 +598,14 @@ bool Gui::select_rom_matching(std::string_view text) {
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
+ // 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);
}
- select_rom(i);
return true;
}
}
diff --git a/tools/emulink/emulink/cli.py b/tools/emulink/emulink/cli.py
index e48350a..ba9498a 100644
--- a/tools/emulink/emulink/cli.py
+++ b/tools/emulink/emulink/cli.py
@@ -143,7 +143,7 @@ def cmd_screenshot(args) -> int:
def cmd_filter(args) -> int:
with _open(args) as link:
r = Control(link).console_filter(args.console)
- print(f"filter: {r['filter'] or 'all'} (consoles: {', '.join(r['consoles'])})")
+ print(f"filter: {r.get('filter') or 'all'} (consoles: {', '.join(r.get('consoles', [])) or 'none'})")
return 0
From b3dc9db24fec659a5033434b378f49d24e6c884f Mon Sep 17 00:00:00 2001
From: William Emfinger
Date: Fri, 13 Nov 2026 22:03:17 -0600
Subject: [PATCH 10/15] Web console: strict settings numbers, no '..' in card
paths, PNG and frame-count guards, ESM parse check
- SETTINGS values parse with std::from_chars into an int (no long -> int wrap).
- Control.remote() refuses '..' segments.
- Game frames shows 0 in a game, a dash only in the launcher.
- Save PNG reports a failed toBlob instead of downloading null.
- The Pages workflow checks web/*.js as ES modules.
Co-Authored-By: Claude Opus 5.5 (1M context)
Claude-Session: https://claude.ai/code/session_01SFCMzomCZ5wRHJN4sxwkvY
---
.github/workflows/pages.yml | 4 ++--
main/remote_control.hpp | 9 +++++----
web/app.js | 7 +++++--
web/link.js | 6 +++++-
4 files changed, 17 insertions(+), 9 deletions(-)
diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml
index 0849565..c30cfd9 100644
--- a/.github/workflows/pages.yml
+++ b/.github/workflows/pages.yml
@@ -28,8 +28,8 @@ jobs:
url: ${{ steps.deployment.outputs.page_url }}
steps:
- uses: actions/checkout@v4
- - name: Check the scripts parse
- run: for f in web/*.js; do node --check "$f"; done
+ - name: Check the scripts parse (as ES modules)
+ run: for f in web/*.js; do node --input-type=module --check < "$f" || exit 1; done
- uses: actions/configure-pages@v5
- uses: actions/upload-pages-artifact@v3
with:
diff --git a/main/remote_control.hpp b/main/remote_control.hpp
index 0aecdd0..5e4f580 100644
--- a/main/remote_control.hpp
+++ b/main/remote_control.hpp
@@ -16,6 +16,7 @@
#include
#include
+#include
#include
#include
#include
@@ -508,13 +509,13 @@ class RemoteControl {
}
const std::string name(text.substr(0, eq));
const std::string value(text.substr(eq + 1));
- char *end = nullptr;
- const long v = std::strtol(value.c_str(), &end, 10);
- if (value.empty() || *end) {
+ int v = 0;
+ const auto [end, ec] = std::from_chars(value.data(), value.data() + value.size(), v);
+ if (value.empty() || ec != std::errc() || end != value.data() + value.size()) {
fail(fmt::format("{}: '{}' is not a number", name, value));
break;
}
- if (!gui_.set_setting(name, static_cast(v))) {
+ if (!gui_.set_setting(name, v)) {
fail(fmt::format("unknown setting '{}' (or {} is out of range)", name, v));
break;
}
diff --git a/web/app.js b/web/app.js
index cf88bc4..153ff17 100644
--- a/web/app.js
+++ b/web/app.js
@@ -229,7 +229,7 @@ function renderStatus(prev) {
const fps = state.fpsHistory.at(-1);
$("fps").textContent = fps == null ? "—" : fps.toFixed(1) + " / s";
$("dropped").textContent = st.frames_dropped;
- $("gameFrames").textContent = st.game_frames || "—";
+ $("gameFrames").textContent = st.state === "game" ? st.game_frames : "—";
drawSpark($("fpsSpark"), [state.fpsHistory], ["#3e8ef7"]);
const memRow = (label, free, largest, min) => h("div", { class: "mem-row" },
h("span", {}, label),
@@ -783,7 +783,10 @@ function init() {
}, state.status?.usb_drive ? "The emulator has the SD card again" : "The PC has the SD card");
$("captureBtn").onclick = () => capture();
$("liveToggle").onchange = (e) => { state.live = e.target.checked; if (state.live) liveLoop(); };
- $("savePngBtn").onclick = () => $("screen").toBlob((b) => download(`screenshot-${Date.now()}.png`, b, "image/png"), "image/png");
+ $("savePngBtn").onclick = () => $("screen").toBlob((b) => {
+ if (b) download(`screenshot-${Date.now()}.png`, b, "image/png");
+ else toast("The PNG could not be made", true);
+ }, "image/png");
$("slot").replaceChildren(...[0, 1, 2, 3, 4, 5].map((s) => h("option", { value: s, selected: s === 1 }, "Slot " + s)));
$("saveBtn").onclick = () => guarded(() => state.ctl.save(Number($("slot").value)), "Saved to slot " + $("slot").value);
$("loadBtn").onclick = () => guarded(() => state.ctl.load(Number($("slot").value)), "Loaded slot " + $("slot").value);
diff --git a/web/link.js b/web/link.js
index 5973952..d4b9bc3 100644
--- a/web/link.js
+++ b/web/link.js
@@ -287,6 +287,8 @@ export class Control {
}
remote(path) {
+ // (the device takes any path: keep this page's on the card)
+ if (path && path.split("/").includes("..")) throw new ControlError(`no '..' in a path: ${path}`);
if (!path || path === "/" || path === ".") return ROOT;
if (path.startsWith(ROOT)) return path;
return ROOT + "/" + path.replace(/^\/+/, "");
@@ -378,7 +380,9 @@ export class Control {
writeFile(path, data, progress) { return this.exclusive(() => this.writeFileNow(path, data, progress)); }
async writeFileNow(path, data, progress) {
const p = enc.encode(this.remote(path));
- const chunk = 3584 - p.length; // the frame payload is at most 4096 bytes
+ // path + data at most 3584 bytes a frame, as emulink: under the 4096-byte
+ // payload (MAX_PAYLOAD) with room to spare
+ const chunk = 3584 - p.length;
if (chunk < 256) throw new ControlError("path too long");
let off = 0;
do {
From b655ce1606bdfab30d4ecf7a48ac9ee4149d7d9c Mon Sep 17 00:00:00 2001
From: William Emfinger
Date: Fri, 13 Nov 2026 22:15:33 -0600
Subject: [PATCH 11/15] Web console: queue reads with file writes and main-loop
commands behind a capture; modal focus; report lost writes
- Whole file reads join the file queue (a read of a file being written
closes its writer on the device).
- Launch, quit, save, load, the drive switch and the ROM reload wait for a
screenshot in progress (it holds the main loop until its last chunk).
- The confirmation is modal for real: the page behind it is inert, Tab
stays on its buttons, Escape cancels, focus returns afterwards, and a
second question answers the first with no.
- Firmware: buffered data lost when a read or the card handover closed
the file is reported by the next FILE_CLOSE.
Co-Authored-By: Claude Opus 5.5 (1M context)
Claude-Session: https://claude.ai/code/session_01SFCMzomCZ5wRHJN4sxwkvY
---
main/remote_control.hpp | 13 ++++++++++---
web/app.js | 20 +++++++++++++++++++-
web/link.js | 42 ++++++++++++++++++++++++-----------------
3 files changed, 54 insertions(+), 21 deletions(-)
diff --git a/main/remote_control.hpp b/main/remote_control.hpp
index 5e4f580..81e993d 100644
--- a/main/remote_control.hpp
+++ b/main/remote_control.hpp
@@ -617,10 +617,14 @@ class RemoteControl {
write_pos_ = offset + n;
break;
}
- case Type::FILE_CLOSE:
- // (a buffered write that fails shows up here)
- if (!close_file()) fail("closing the file failed (card full?)");
+ case Type::FILE_CLOSE: {
+ // (a buffered write that fails shows up here, also one closed earlier
+ // by a read of the file or the card handover)
+ const bool closed = close_file();
+ if (!closed || write_lost_) fail("closing the file failed (card full?)");
+ write_lost_ = false;
break;
+ }
case Type::FILE_DELETE: {
const std::string path(text);
close_file(path);
@@ -841,6 +845,7 @@ class RemoteControl {
}
if (!close_file()) return false; // (the previous file's last data did not land)
if (offset == 0) {
+ write_lost_ = false; // (a new file: an older one's failure is not its)
std::error_code ec;
std::filesystem::create_directories(std::filesystem::path(path).parent_path(), ec);
write_file_ = fopen(path.c_str(), "wb");
@@ -863,6 +868,7 @@ class RemoteControl {
const bool ok = fclose(write_file_) == 0;
write_file_ = nullptr;
write_path_.clear();
+ if (!ok) write_lost_ = true; // (told by the next FILE_CLOSE)
return ok;
}
return true;
@@ -900,4 +906,5 @@ class RemoteControl {
FILE *write_file_{nullptr};
std::string write_path_;
uint32_t write_pos_{0};
+ bool write_lost_{false}; ///< an implicit close_file() lost buffered data
};
diff --git a/web/app.js b/web/app.js
index 153ff17..baed372 100644
--- a/web/app.js
+++ b/web/app.js
@@ -42,13 +42,31 @@ function toast(text, err = false) {
toast.timer = setTimeout(() => (t.hidden = true), err ? 6000 : 3000);
}
+// One question at a time: the rest of the page is inert (no focus, no clicks)
+// while it is open, and focus goes back to where it was afterwards.
function confirmModal(title, text, ok = "OK") {
return new Promise((resolve) => {
+ confirmModal.pending?.(false); // (a question still open is answered "no")
+ const back = document.activeElement;
+ const others = [...document.body.children].filter((e) => e !== $("modal") && e !== $("toast") && !e.inert);
$("modalTitle").textContent = title; $("modalText").textContent = text; $("modalOk").textContent = ok;
+ for (const e of others) e.inert = true;
$("modal").hidden = false; $("modalOk").focus();
- const done = (v) => { $("modal").hidden = true; $("modalOk").onclick = $("modalCancel").onclick = null; resolve(v); };
+ const done = (v) => {
+ confirmModal.pending = null;
+ $("modal").hidden = true; $("modalOk").onclick = $("modalCancel").onclick = $("modal").onkeydown = null;
+ for (const e of others) e.inert = false;
+ if (back instanceof HTMLElement && back.isConnected) back.focus();
+ resolve(v);
+ };
+ confirmModal.pending = done;
$("modalOk").onclick = () => done(true);
$("modalCancel").onclick = () => done(false);
+ $("modal").onkeydown = (ev) => {
+ if (ev.key === "Escape") { ev.preventDefault(); done(false); }
+ // Tab stays on the two buttons
+ if (ev.key === "Tab") { ev.preventDefault(); (document.activeElement === $("modalOk") ? $("modalCancel") : $("modalOk")).focus(); }
+ };
});
}
diff --git a/web/link.js b/web/link.js
index d4b9bc3..1affebc 100644
--- a/web/link.js
+++ b/web/link.js
@@ -261,16 +261,22 @@ export class ControlError extends Error {}
/** The emulator's control module (0x20) and the espp system service (7). */
export class Control {
- constructor(link) { this.link = link; this.fileQueue = Promise.resolve(); }
-
- /** Run `fn` after every earlier file change has finished: the device has one
- * open file across FILE_WRITE / FILE_CLOSE, and a metadata.csv edit is a
- * read-modify-write that another edit must not interleave with. */
- exclusive(fn) {
- const run = this.fileQueue.then(fn, fn);
- this.fileQueue = run.catch(() => {});
+ constructor(link) { this.link = link; this.fileQueue = Promise.resolve(); this.mainQueue = Promise.resolve(); }
+
+ static queue(owner, key, fn) {
+ const run = owner[key].then(fn, fn);
+ owner[key] = run.catch(() => {});
return run;
}
+ /** Run `fn` after every earlier file operation has finished: the device has
+ * one open file across FILE_WRITE / FILE_CLOSE (which a read of the same
+ * file closes), and a metadata.csv edit is a read-modify-write that another
+ * edit must not interleave with. */
+ exclusive(fn) { return Control.queue(this, "fileQueue", fn); }
+ /** Run `fn` after the earlier requests that need the device's main loop: a
+ * screenshot holds the game (the main loop) until its last chunk is read,
+ * so a save, load, quit or launch sent meanwhile would stall the capture. */
+ onMain(fn) { return Control.queue(this, "mainQueue", fn); }
async call(type, payload = new Uint8Array(0), { timeoutMs = 15000, raw = false } = {}) {
if (typeof payload === "string") payload = enc.encode(payload);
@@ -306,13 +312,13 @@ export class Control {
}
}
- launch(match) { return this.call(T.LAUNCH, match, { timeoutMs: 30000 }); }
- quit() { return this.call(T.QUIT, undefined, { timeoutMs: 30000 }); }
+ launch(match) { return this.onMain(() => this.call(T.LAUNCH, match, { timeoutMs: 30000 })); }
+ quit() { return this.onMain(() => this.call(T.QUIT, undefined, { timeoutMs: 30000 })); }
buttons(mask, holdMs = 0) { return this.call(T.BUTTONS, cat(u16le(mask), u16le(holdMs)), { timeoutMs: holdMs + 5000 }); }
- save(slot) { return this.call(T.SAVE, new Uint8Array([slot]), { timeoutMs: 60000 }); }
- load(slot) { return this.call(T.LOAD, new Uint8Array([slot]), { timeoutMs: 60000 }); }
- usbDrive(host) { return this.call(T.USB_DRIVE, new Uint8Array([host ? 1 : 0]), { timeoutMs: 20000 }); }
- reloadRoms() { return this.call(T.RELOAD_ROMS); }
+ save(slot) { return this.onMain(() => this.call(T.SAVE, new Uint8Array([slot]), { timeoutMs: 60000 })); }
+ load(slot) { return this.onMain(() => this.call(T.LOAD, new Uint8Array([slot]), { timeoutMs: 60000 })); }
+ usbDrive(host) { return this.onMain(() => this.call(T.USB_DRIVE, new Uint8Array([host ? 1 : 0]), { timeoutMs: 20000 })); }
+ reloadRoms() { return this.onMain(() => this.call(T.RELOAD_ROMS)); }
enterUpdater() { return this.call(T.ENTER_UPDATER); }
consoleFilter(key) { return this.call(T.CONSOLE_FILTER, key || "all"); }
settings(change) { return this.call(T.SETTINGS, change || ""); }
@@ -338,7 +344,8 @@ export class Control {
}
/** The running game's frame, or the launcher's screen: {width, height, format, source, data}. */
- async frame(progress) {
+ frame(progress) { return this.onMain(() => this.frameNow(progress)); }
+ async frameNow(progress) {
const info = await this.call(T.SCREENSHOT, undefined, { timeoutMs: 15000 });
// (the last chunk read lets the game go on: it must be the last one asked for)
const last = Math.max(0, info.size - 4000 > 0 ? info.size - ((info.size % 4000) || 4000) : 0);
@@ -371,7 +378,8 @@ export class Control {
mkdir(path) { return this.call(T.MKDIR, this.remote(path)); }
rm(path) { return this.exclusive(() => this.call(T.FILE_DELETE, this.remote(path), { timeoutMs: 120000 })); }
- async readFile(path, progress) {
+ readFile(path, progress) { return this.exclusive(() => this.readFileNow(path, progress)); }
+ async readFileNow(path, progress) {
const p = enc.encode(this.remote(path));
const st = await this.call(T.FILE_STAT, p);
return this.readChunks(st.size, (off, n) => this.call(T.FILE_READ, cat(u32le(off), u16le(n), p), { raw: true }), progress);
@@ -406,7 +414,7 @@ export class Control {
}
const meta = "metadata.csv";
// only a missing file starts an empty list: a failed read must not rewrite it
- const text = (await this.stat(meta)) ? dec.decode(await this.readFile(meta)) : "";
+ const text = (await this.stat(meta)) ? dec.decode(await this.readFileNow(meta)) : "";
const lines = text.split(/\r?\n/).filter((l) => l.trim() && l.split(",")[0].trim() !== rel);
if (!remove) lines.push(`${rel}, ${boxart}, ${name}`);
await this.writeFileNow(meta, enc.encode(lines.join("\n") + "\n"));
From 209cd4ba9cef5677a7833ab8c5b52c690b80909d Mon Sep 17 00:00:00 2001
From: William Emfinger
Date: Fri, 13 Nov 2026 22:18:23 -0600
Subject: [PATCH 12/15] Console filter: an empty request only reports it; not
while a launch is pending; a list reload closes the picker
As esp-box-emu (3f9a022, 2968e88), so the protocol and emulink match:
- CONSOLE_FILTER with an empty payload returns {filter, consoles}
without touching the launcher ("all" clears the filter); emulink
filter with no console sends that query.
- Setting it runs on the main loop under the GUI lock, like LAUNCH, and
is refused while a launch the loop has taken has not started its cart.
- Re-reading metadata.csv closes an open console picker.
Co-Authored-By: Claude Opus 5.5 (1M context)
Claude-Session: https://claude.ai/code/session_01SFCMzomCZ5wRHJN4sxwkvY
---
components/gui/src/gui.cpp | 2 ++
main/remote_control.hpp | 47 ++++++++++++++++++--------------
tools/emulink/emulink/control.py | 5 ++--
3 files changed, 31 insertions(+), 23 deletions(-)
diff --git a/components/gui/src/gui.cpp b/components/gui/src/gui.cpp
index 15d27ab..56ff216 100644
--- a/components/gui/src/gui.cpp
+++ b/components/gui/src/gui.cpp
@@ -258,6 +258,8 @@ void Gui::update_rom_list() {
return;
}
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;
diff --git a/main/remote_control.hpp b/main/remote_control.hpp
index 0413ed5..297abfe 100644
--- a/main/remote_control.hpp
+++ b/main/remote_control.hpp
@@ -132,9 +132,9 @@ class RemoteControl {
RELOAD_ROMS = 0x0A, ///< () re-read metadata.csv
ENTER_UPDATER = 0x0B, ///< () reboot into the updater app (ota_1) for an update
SCREENSHOT_READ = 0x0C, ///< (u32 offset, u16 length) -> raw bytes of the held SCREENSHOT (short at the end)
- /// (console key: text, e.g. "snes"; empty or "all" for every console; "?"
- /// changes nothing, only reports) -> {filter, consoles: [keys]}: the
- /// launcher's list shows only that console's games
+ /// (console key: text, e.g. "snes"; "all" for every console) -> {filter,
+ /// consoles: [keys]}: the launcher's list shows only that console's games.
+ /// An empty payload only reports them (nothing changes on the device).
CONSOLE_FILTER = 0x0D,
FILE_LIST = 0x10, ///< (path[\0offset]) -> {entries: [{name, dir, size}], truncated?, next?}
FILE_READ = 0x11, ///< (u32 offset, u16 length, path) -> raw bytes (short at the end)
@@ -468,28 +468,33 @@ class RemoteControl {
std::string key(text);
std::transform(key.begin(), key.end(), key.begin(),
[](unsigned char c) { return static_cast(std::tolower(c)); });
- if (key == "?") { // a query: report the filter without touching the list
- json(filter_json());
+ if (key.empty()) {
+ json(filter_json()); // a query
break;
}
- const auto present = gui_.consoles();
- bool done = false;
- if (key.empty() || key == "all") {
- done = gui_.set_console_filter(std::nullopt);
- } else {
- const auto it = std::find_if(present.begin(), present.end(),
- [&](Console c) { return key == console_info(c).key; });
- if (it == present.end()) {
- fail(fmt::format("no games for console '{}'", key));
- break;
- }
- done = gui_.set_console_filter(*it);
- }
- if (!done) {
- fail("the filter could not be set");
+ // On the main loop, as LAUNCH: a launch it has taken (ready_to_play, no
+ // cart yet) reads the selected game next, which a new filter can change.
+ // The GUI lock keeps a tap on the screen from starting one meanwhile.
+ bool pending = false, unknown = false, done = false;
+ if (!on_main([&] {
+ std::lock_guard lk(BoxEmu::lvgl_mutex());
+ if ((pending = gui_.ready_to_play() && !current_cart())) return;
+ if (key == "all") {
+ done = gui_.set_console_filter(std::nullopt);
+ return;
+ }
+ const auto present = gui_.consoles();
+ const auto it = std::find_if(present.begin(), present.end(),
+ [&](Console c) { return key == console_info(c).key; });
+ if ((unknown = it == present.end())) return;
+ done = gui_.set_console_filter(*it);
+ }, std::chrono::seconds(2))) {
break;
}
- json(filter_json());
+ if (pending) fail("a game is starting");
+ else if (unknown) fail(fmt::format("no games for console '{}'", key));
+ else if (!done) fail("the filter could not be set");
+ else json(filter_json());
break;
}
case Type::FILE_LIST: {
diff --git a/tools/emulink/emulink/control.py b/tools/emulink/emulink/control.py
index 188dda0..36e3caf 100644
--- a/tools/emulink/emulink/control.py
+++ b/tools/emulink/emulink/control.py
@@ -203,9 +203,10 @@ def usb_drive(self, host: bool) -> None:
def console_filter(self, console: str | None = None) -> dict:
"""Set the launcher's console filter (a console key such as "snes", or
- "all"); with None, only report it. -> {filter, consoles}"""
+ "all"); with None, only report it (an empty request changes nothing on
+ the device). -> {filter, consoles}"""
if console is None:
- return self._call(CONSOLE_FILTER, b"?") # a query: changes nothing
+ return self._call(CONSOLE_FILTER, b"")
return self._call(CONSOLE_FILTER, (console or "all").encode())
def reload_roms(self) -> int:
From 4663b3565439f80932087367971f42c6199d85f8 Mon Sep 17 00:00:00 2001
From: William Emfinger
Date: Fri, 13 Nov 2026 22:18:34 -0600
Subject: [PATCH 13/15] Web console: take esp-box-emu's web/ fixes, keep this
branch's extras
web/app.js and web/link.js now match esp-box-emu feat/web-console
(734b32d: session counter, reconnect only when wanted, uploads and Add
Game bound to their board, stale settings writes dropped, timeouts
reject cleanly, keyboard on the pad buttons, ...), plus what it lacks:
- the main-loop queue (a capture is not stalled by save/load/quit/launch)
- no '..' in card paths
- Escape / Tab in the confirmation, and a second one answers the first
- stale input released on connect; the last capture's picture cleared on
disconnect
- missing box art retried after a library reload or the card's return
- game frames shows 0 in a game; a failed toBlob is reported
Co-Authored-By: Claude Opus 5.5 (1M context)
Claude-Session: https://claude.ai/code/session_01SFCMzomCZ5wRHJN4sxwkvY
---
web/app.js | 143 +++++++++++++++++++++++++++++++---------------------
web/link.js | 41 +++++++++------
2 files changed, 110 insertions(+), 74 deletions(-)
diff --git a/web/app.js b/web/app.js
index baed372..576c379 100644
--- a/web/app.js
+++ b/web/app.js
@@ -29,9 +29,10 @@ const state = {
tab: "dashboard", statusTimer: null, lastFrames: null, fpsHistory: [], memHistory: [],
filter: "", search: "", cwd: ROOT, files: [], live: false, lastShot: null, slot: 1,
boxart: new Map(), boxartQueue: [], boxartBusy: false, settings: null, serial: null,
- // a device that comes back after the link was lost is opened again; off after
- // a disconnect asked for here or a hand-off to another app (which takes it)
- reconnect: true, reconnectGen: 0,
+ // a device that comes back is opened again without the chooser, unless the
+ // page let go of it on purpose (Disconnect, or a hand-off to another app)
+ autoReconnect: true,
+ session: 0, // bumped on every disconnect: replies for an older one are dropped
};
// ------------------------------------------------------------------ helpers --
@@ -42,26 +43,25 @@ function toast(text, err = false) {
toast.timer = setTimeout(() => (t.hidden = true), err ? 6000 : 3000);
}
-// One question at a time: the rest of the page is inert (no focus, no clicks)
-// while it is open, and focus goes back to where it was afterwards.
function confirmModal(title, text, ok = "OK") {
return new Promise((resolve) => {
- confirmModal.pending?.(false); // (a question still open is answered "no")
- const back = document.activeElement;
- const others = [...document.body.children].filter((e) => e !== $("modal") && e !== $("toast") && !e.inert);
$("modalTitle").textContent = title; $("modalText").textContent = text; $("modalOk").textContent = ok;
- for (const e of others) e.inert = true;
+ // the page behind is inert (no Tab or clicks into it) until the answer
+ confirmModal.pending?.(false); // (a question still open is answered "no")
+ const back = [...document.body.children].filter((e) => e !== $("modal") && e !== $("toast") && !e.inert);
+ const opener = document.activeElement;
+ for (const e of back) e.inert = true;
$("modal").hidden = false; $("modalOk").focus();
const done = (v) => {
confirmModal.pending = null;
$("modal").hidden = true; $("modalOk").onclick = $("modalCancel").onclick = $("modal").onkeydown = null;
- for (const e of others) e.inert = false;
- if (back instanceof HTMLElement && back.isConnected) back.focus();
+ for (const e of back) e.inert = false;
+ opener?.focus?.();
resolve(v);
};
- confirmModal.pending = done;
$("modalOk").onclick = () => done(true);
$("modalCancel").onclick = () => done(false);
+ confirmModal.pending = done;
$("modal").onkeydown = (ev) => {
if (ev.key === "Escape") { ev.preventDefault(); done(false); }
// Tab stays on the two buttons
@@ -116,11 +116,12 @@ async function connect(device) {
}
state.link = link;
state.ctl = new Control(link);
- state.reconnect = true;
- link.onclose = () => onLinkLost();
+ state.autoReconnect = true;
// input a page lost track of (its link died with a button held) is let go
state.ctl.buttons(0, 0).catch(() => {});
+ link.onclose = () => onLinkLost();
try { state.discovery = await link.discover(); } catch (_) { state.discovery = null; }
+ if (state.link !== link) return; // (lost while discovering: already shown as disconnected)
try { localStorage.setItem("emu-console-serial", link.serial); } catch (_) {}
$("connectBtn").hidden = true; $("disconnectBtn").hidden = false;
$("welcome").hidden = true;
@@ -139,12 +140,15 @@ async function disconnect() {
clearInterval(state.statusTimer); state.statusTimer = null;
stopLive();
const link = state.link, ctl = state.ctl;
- // a button still held here would stay pressed in the game
- if (heldMask && ctl && link?.reading) { try { await ctl.buttons(0, 0); } catch (_) {} }
- releasePad();
+ state.session++;
state.link = null; state.ctl = null; state.status = null; state.romsLoaded = false; state.settings = null;
+ // a button held from this page would stay pressed in the game
+ if (heldMask && ctl) {
+ await Promise.race([ctl.buttons(0, 0).catch(() => {}), new Promise((r) => setTimeout(r, 500))]);
+ }
+ releasePad();
+ clearDeviceCaches();
if (link) { link.onclose = null; await link.close(); }
- forgetDevice();
$("connectBtn").hidden = false; $("disconnectBtn").hidden = true;
$("welcome").hidden = false;
for (const p of document.querySelectorAll("[data-panel]")) p.hidden = true;
@@ -156,36 +160,29 @@ function onLinkLost() {
const serial = state.link?.serial;
disconnect().then(() => {
setPill("warn", "Disconnected");
+ if (!state.autoReconnect) return; // (handed off: the updater went down with it)
toast("The device went away (restarted or unplugged); it reconnects when it is back.");
state.waitingFor = serial;
});
}
-// What this page knew about the device's card (box art, the last capture):
-// dropped with the link, so another board (or the same card changed meanwhile)
-// is not shown stale pictures. Reads still in flight check their session.
-function forgetDevice() {
+// Images and the last screenshot belong to the device (and SD card) they came
+// from: another board can have the same paths.
+function clearDeviceCaches() {
for (const url of state.boxart.values()) if (url) URL.revokeObjectURL(url);
- state.boxart.clear(); state.boxartQueue = [];
+ state.boxart.clear();
+ for (const { done } of state.boxartQueue.splice(0)) done(null);
state.lastShot = null;
const c = $("screen"); c.getContext("2d").clearRect(0, 0, c.width, c.height);
$("screenInfo").textContent = ""; $("savePngBtn").disabled = true;
}
-// A disconnect asked for (the button, a hand-off): no automatic reconnection,
-// also not for a connect event already scheduled.
-async function disconnectByUser() {
- state.reconnect = false; state.reconnectGen++; state.waitingFor = null;
- await disconnect();
-}
-
// a device that comes back (after a restart) is opened again without the chooser
if (navigator.usb) {
navigator.usb.addEventListener("connect", (ev) => {
- if (state.link || !state.reconnect || !DEVICES[ev.device.serialNumber]) return;
- if (state.waitingFor && ev.device.serialNumber !== state.waitingFor) return;
- const gen = state.reconnectGen;
- setTimeout(() => { if (!state.link && state.reconnect && gen === state.reconnectGen) connect(ev.device); }, 1200);
+ const ok = () => state.autoReconnect && !state.link && DEVICES[ev.device.serialNumber] &&
+ (!state.waitingFor || ev.device.serialNumber === state.waitingFor);
+ if (ok()) setTimeout(() => { if (ok()) connect(ev.device); }, 1200);
});
}
@@ -267,7 +264,6 @@ function renderStatus(prev) {
$("panicCard").hidden = !st.last_panic;
$("panicText").textContent = st.last_panic || "";
$("coredumpLink").href = handoffUrl("coredump_console.html", MODULE.COREDUMP);
- $("coredumpLink").onclick = (ev) => { ev.preventDefault(); handOff("coredump_console.html", MODULE.COREDUMP); };
// the game started or ended: the list, the screen and the buttons follow
if (prev && (prev.state !== st.state || prev.rom !== st.rom)) {
if (state.tab === "library") renderLibrary();
@@ -314,9 +310,10 @@ async function capture() {
if (!state.ctl || capture.busy) return;
capture.busy = true;
const prog = $("screenProgress");
- const t0 = performance.now();
+ const t0 = performance.now(), session = state.session;
try {
const f = await state.ctl.frame((n, total) => { prog.hidden = false; prog.max = total; prog.value = n; });
+ if (session !== state.session) return; // (disconnected meanwhile)
const c = $("screen");
c.width = f.width; c.height = f.height;
c.getContext("2d").putImageData(rgb565ToImageData(f.data, f.width, f.height, f.format === "rgb565be"), 0, 0);
@@ -340,15 +337,15 @@ async function liveLoop() {
function stopLive() { state.live = false; $("liveToggle").checked = false; }
let heldMask = 0;
-// forget the held buttons and their pressed look (the link is going away)
-function releasePad() {
- heldMask = 0;
- for (const b of document.querySelectorAll("#pad .down-now")) b.classList.remove("down-now");
-}
const setButtons = (mask) => {
heldMask = mask;
if (state.ctl) state.ctl.buttons(mask, 0).catch((e) => toast("Buttons: " + (e.message || e), true));
};
+// forget the held buttons (the link is going: the device side is released by the caller)
+function releasePad() {
+ heldMask = 0;
+ for (const b of document.querySelectorAll("#pad .down-now")) b.classList.remove("down-now");
+}
function initPad() {
for (const b of document.querySelectorAll("#pad [data-btn]")) {
const bit = BUTTONS[b.dataset.btn];
@@ -358,11 +355,22 @@ function initPad() {
b.addEventListener("pointerup", up);
b.addEventListener("pointercancel", up);
b.addEventListener("lostpointercapture", up);
+ // the keyboard's activation keys on a focused pad button press that button
+ const activate = (ev) => ev.key === "Enter" || ev.key === " ";
+ b.addEventListener("keydown", (ev) => {
+ if (!activate(ev)) return;
+ ev.preventDefault(); ev.stopPropagation();
+ if (!ev.repeat) { b.classList.add("down-now"); setButtons(heldMask | bit); }
+ });
+ b.addEventListener("keyup", (ev) => { if (activate(ev)) { ev.stopPropagation(); up(); } });
+ b.addEventListener("blur", up);
}
const keys = { ArrowUp: "up", ArrowDown: "down", ArrowLeft: "left", ArrowRight: "right", z: "a", x: "b", a: "x", s: "y", q: "l", w: "r", Enter: "start", Shift: "select" };
const keyBit = (ev) => BUTTONS[keys[ev.key] || keys[ev.key.toLowerCase()]];
addEventListener("keydown", (ev) => {
if (state.tab !== "screen" || (ev.target instanceof Element && ev.target.matches("input, select, textarea")) || ev.repeat) return;
+ // (Enter / Space on a focused control activate it: Save, Load, Capture...)
+ if ((ev.key === "Enter" || ev.key === " ") && ev.target instanceof Element && ev.target.closest("button, a")) return;
const bit = keyBit(ev);
if (!bit) return;
ev.preventDefault(); setButtons(heldMask | bit);
@@ -477,16 +485,15 @@ async function pumpBoxart() {
while (state.boxartQueue.length && state.ctl) {
const { path, done } = state.boxartQueue.shift();
if (state.boxart.has(path)) { done(state.boxart.get(path)); continue; }
- const ctl = state.ctl;
+ const session = state.session;
try {
- const data = await ctl.readFile(path);
- if (ctl !== state.ctl) continue; // the link changed meanwhile: not this device's
+ const data = await state.ctl.readFile(path);
+ if (session !== state.session) { done(null); continue; } // (another connection's now)
const url = URL.createObjectURL(new Blob([data], { type: "image/jpeg" }));
state.boxart.set(path, url);
done(url);
} catch (_) {
- if (ctl !== state.ctl) continue;
- state.boxart.set(path, null); // (forgotten again by forgetBoxartFailures())
+ if (session === state.session) state.boxart.set(path, null);
done(null);
}
}
@@ -502,15 +509,23 @@ async function addGame(ev) {
const romPath = `${ROOT}/${folder}/${rom.name}`;
const artPath = art ? `${ROOT}/boxart/${art.name}` : "";
const msg = $("addMsg");
+ // every step on the board it started on (see uploadFiles)
+ const ctl = state.ctl;
+ const still = () => { if (state.ctl !== ctl) throw new Error("Disconnected: the game was not added"); };
try {
msg.textContent = "Copying the ROM…";
- await state.ctl.writeFile(romPath, new Uint8Array(await rom.arrayBuffer()), (n, t) => (msg.textContent = `ROM ${Math.round((n / t) * 100)}%`));
+ const romData = new Uint8Array(await rom.arrayBuffer());
+ still();
+ await ctl.writeFile(romPath, romData, (n, t) => (msg.textContent = `ROM ${Math.round((n / t) * 100)}%`));
if (art) {
msg.textContent = "Copying the boxart…";
- await state.ctl.writeFile(artPath, new Uint8Array(await art.arrayBuffer()));
+ const artData = new Uint8Array(await art.arrayBuffer());
+ still();
+ await ctl.writeFile(artPath, artData);
}
+ still();
msg.textContent = "Adding to metadata.csv…";
- const total = await state.ctl.addRom(romPath, name, artPath ? artPath.slice(ROOT.length + 1) : "");
+ const total = await ctl.addRom(romPath, name, artPath ? artPath.slice(ROOT.length + 1) : "");
msg.textContent = `Added: ${total} games now.`;
$("addGame").reset();
loadLibrary(true);
@@ -571,17 +586,22 @@ async function downloadFile(path, size) {
}
async function uploadFiles(files) {
+ // where they were dropped, on the device they were dropped on (the folder
+ // shown can change while they are copied)
+ const dir = state.cwd, ctl = state.ctl;
for (const f of files) {
+ if (state.ctl !== ctl) break; // (disconnected)
try {
const data = new Uint8Array(await f.arrayBuffer());
- await state.ctl.writeFile(state.cwd + "/" + f.name, data, (n, t) => transfer(`Copying ${f.name} (${fmtBytes(n)} of ${fmtBytes(t)})`, n, t));
+ if (state.ctl !== ctl) break;
+ await ctl.writeFile(dir + "/" + f.name, data, (n, t) => transfer(`Copying ${f.name} (${fmtBytes(n)} of ${fmtBytes(t)})`, n, t));
} catch (e) {
toast(`${f.name}: ${e.message || e}`, true);
break;
}
}
transfer("");
- loadFiles(state.cwd);
+ if (state.ctl === ctl) loadFiles(state.cwd);
}
async function deletePath(path, dir) {
@@ -604,7 +624,11 @@ async function loadSettings() {
const r = await guarded(() => state.ctl.settings());
if (!r) { $("settingsForm").replaceChildren(h("p", { class: "muted" }, "This firmware has no settings over USB (control protocol 4).")); return; }
state.settings = r;
- const send = debounce((name, value) => guarded(() => state.ctl.settings(`${name}=${value}`)), 250);
+ // (a change still waiting when this connection ends is dropped, not sent to the next one)
+ const ctl = state.ctl, session = state.session;
+ const send = debounce((name, value) => {
+ if (state.session === session) guarded(() => ctl.settings(`${name}=${value}`));
+ }, 250);
$("settingsForm").replaceChildren(...Object.entries(r.settings).map(([name, value]) => {
const info = SETTING_INFO[name] || { label: name };
const [min, max] = r.limits[name] || [0, 100];
@@ -695,7 +719,8 @@ async function handOff(app, moduleId) {
const tab = window.open("about:blank", "_blank");
if (!tab) { toast("Allow pop-ups for this page to open the app", true); return; }
const url = handoffUrl(app, moduleId);
- await disconnectByUser();
+ state.autoReconnect = false; // (the app has it now)
+ await disconnect();
tab.location.href = url;
toast("The device was handed to " + app + "; connect again here when you are done.");
}
@@ -705,10 +730,10 @@ async function updateFirmware() {
const tab = window.open("about:blank", "_blank");
if (!tab) { toast("Allow pop-ups for this page to open the OTA console", true); return; }
const url = handoffUrl("ota_console.html", MODULE.OTA);
- // the updater comes up with the same serial: it is the OTA console's, not ours
- state.reconnect = false; state.reconnectGen++;
- try { await state.ctl.enterUpdater(); } catch (e) { state.reconnect = true; tab.close(); toast(e.message || String(e), true); return; }
- await disconnectByUser();
+ // the updater comes up with the same serial: it is the OTA console's to open
+ state.autoReconnect = false;
+ try { await state.ctl.enterUpdater(); } catch (e) { state.autoReconnect = true; tab.close(); toast(e.message || String(e), true); return; }
+ await disconnect();
tab.location.href = url;
}
@@ -790,7 +815,9 @@ function renderLog(fresh) {
function init() {
if (!navigator.usb) { $("unsupported").hidden = false; $("connectBtn").disabled = true; $("welcomeConnectBtn").disabled = true; }
$("connectBtn").onclick = $("welcomeConnectBtn").onclick = () => connect();
- $("disconnectBtn").onclick = () => disconnectByUser();
+ $("disconnectBtn").onclick = () => { state.autoReconnect = false; disconnect(); };
+ // (as the System tab's Open app buttons: the core dump console needs the device)
+ $("coredumpLink").onclick = (e) => { e.preventDefault(); handOff("coredump_console.html", MODULE.COREDUMP); };
for (const b of document.querySelectorAll("#tabs button")) b.onclick = () => showTab(b.dataset.tab);
for (const b of document.querySelectorAll("[data-goto]")) b.onclick = () => showTab(b.dataset.goto);
$("nowQuitBtn").onclick = $("quitBtn").onclick = () => guarded(() => state.ctl.quit(), "Quit");
diff --git a/web/link.js b/web/link.js
index 1affebc..b8f70f8 100644
--- a/web/link.js
+++ b/web/link.js
@@ -214,12 +214,13 @@ export class UsbLink {
});
const frame = buildFrame(module, type, payload, corr);
const sent = this.sendQueue.then(() => this.send(frame));
- this.sendQueue = sent.catch(() => {});
- return sent.then(() => reply, (e) => {
+ this.sendQueue = sent.catch(() => {
const w = this.waiters.get(corr);
if (w) { clearTimeout(w.timer); this.waiters.delete(corr); }
- throw e;
});
+ // (both observed at once: a timeout or a lost link while the frame is
+ // still queued rejects now, and never as an unhandled rejection)
+ return Promise.all([sent, reply]).then(([, f]) => f);
}
/** The dispatcher's module list: {name, firmware, modules: [{id, name, protocol, version, ...}]}. */
@@ -261,22 +262,29 @@ export class ControlError extends Error {}
/** The emulator's control module (0x20) and the espp system service (7). */
export class Control {
- constructor(link) { this.link = link; this.fileQueue = Promise.resolve(); this.mainQueue = Promise.resolve(); }
+ constructor(link) {
+ this.link = link;
+ this.ops = Promise.resolve(); // see exclusive()
+ this.mainOps = Promise.resolve(); // see onMain()
+ }
+
+ /** Requests that need the device's main loop run one at a time: a screenshot
+ * holds the game (the main loop) until its last chunk is read, so a save,
+ * load, quit or launch sent meanwhile would stall the capture. */
+ onMain(fn) {
+ const run = this.mainOps.then(() => fn());
+ this.mainOps = run.catch(() => {});
+ return run;
+ }
- static queue(owner, key, fn) {
- const run = owner[key].then(fn, fn);
- owner[key] = run.catch(() => {});
+ // Operations made of several requests that share the device's state (a file
+ // written in parts, metadata.csv read, changed and written back) run one at
+ // a time: two at once would interleave their writes or lose an edit.
+ exclusive(fn) {
+ const run = this.ops.then(() => fn());
+ this.ops = run.catch(() => {});
return run;
}
- /** Run `fn` after every earlier file operation has finished: the device has
- * one open file across FILE_WRITE / FILE_CLOSE (which a read of the same
- * file closes), and a metadata.csv edit is a read-modify-write that another
- * edit must not interleave with. */
- exclusive(fn) { return Control.queue(this, "fileQueue", fn); }
- /** Run `fn` after the earlier requests that need the device's main loop: a
- * screenshot holds the game (the main loop) until its last chunk is read,
- * so a save, load, quit or launch sent meanwhile would stall the capture. */
- onMain(fn) { return Control.queue(this, "mainQueue", fn); }
async call(type, payload = new Uint8Array(0), { timeoutMs = 15000, raw = false } = {}) {
if (typeof payload === "string") payload = enc.encode(payload);
@@ -378,6 +386,7 @@ export class Control {
mkdir(path) { return this.call(T.MKDIR, this.remote(path)); }
rm(path) { return this.exclusive(() => this.call(T.FILE_DELETE, this.remote(path), { timeoutMs: 120000 })); }
+ // (queued too: a read alongside a write of the same file could see part of it)
readFile(path, progress) { return this.exclusive(() => this.readFileNow(path, progress)); }
async readFileNow(path, progress) {
const p = enc.encode(this.remote(path));
From b31209a0c91e73cbc4e688b5a31dc87ea3dfe3a5 Mon Sep 17 00:00:00 2001
From: William Emfinger
Date: Fri, 13 Nov 2026 22:36:32 -0600
Subject: [PATCH 14/15] README: the web console, how it works and what it does,
with screenshots
Moves the Web Console section up after Emulators, explains the WebUSB
landing page and each tab, and adds screen / library / dashboard / settings /
system screenshots from the Tab5 (docs/images/web-console-*.jpg). The MAC
address is blanked in the system shot.
Co-Authored-By: Claude Opus 5.5 (1M context)
Claude-Session: https://claude.ai/code/session_01SFCMzomCZ5wRHJN4sxwkvY
---
README.md | 60 ++++++++++++++++++++------
docs/images/web-console-dashboard.jpg | Bin 0 -> 64753 bytes
docs/images/web-console-library.jpg | Bin 0 -> 115050 bytes
docs/images/web-console-screen.jpg | Bin 0 -> 92340 bytes
docs/images/web-console-settings.jpg | Bin 0 -> 32272 bytes
docs/images/web-console-system.jpg | Bin 0 -> 64790 bytes
6 files changed, 48 insertions(+), 12 deletions(-)
create mode 100644 docs/images/web-console-dashboard.jpg
create mode 100644 docs/images/web-console-library.jpg
create mode 100644 docs/images/web-console-screen.jpg
create mode 100644 docs/images/web-console-settings.jpg
create mode 100644 docs/images/web-console-system.jpg
diff --git a/README.md b/README.md
index bb4af72..dea863f 100644
--- a/README.md
+++ b/README.md
@@ -101,6 +101,54 @@ https://github.com/user-attachments/assets/641a64b0-b3af-429b-8582-a38fc9a5cdad
+## Web Console
+
+Plug the Tab5 into a computer and it brings its own control panel. Chrome or
+Edge pops up a notification for
+**[esp-cpp.github.io/tab5-emu](https://esp-cpp.github.io/tab5-emu/)**, the
+firmware's WebUSB landing page: click it, pick the Tab5, and the page talks
+to the device straight from the browser. There's nothing to install and no
+server in between.
+
+
+
+
+
+- **Dashboard**: what's running (with its boxart), live frame-rate and
+ memory graphs, the firmware and partition, the last reset reason, and a
+ button that hands the SD card to the PC as a USB drive.
+- **Screen**: capture the game's or the launcher's screen (or keep it
+ **Live**), save it as a PNG, play with the on-screen controller or the
+ keyboard (arrows, Z / X / A / S, Q / W for L / R, Enter = Start), save and
+ load states, quit.
+- **Library**: the games by console with their boxart and counts. Search,
+ filter (the launcher too, if you like), **Play** any of them, or **Add a
+ game**: choose the ROM and its cover and the page uploads both and adds the
+ `metadata.csv` line. **Remove** undoes it.
+- **Files**: browse the SD card, download, upload by drag and drop, new
+ folder, delete.
+- **Settings**: volume, mute, brightness, video scaling and resume last save,
+ shown in the launcher at once and saved to the card a moment later.
+- **System**: chip, memory, ESP-IDF, OTA state and the services on the link;
+ restart (or into download mode), and **Update firmware**, which restarts
+ into the updater and opens the espp OTA console for `build/tab5-emu.bin`.
+- **Console**: the log over Web Serial (pick the console's port), filtered,
+ followed, saved to a file.
+
+