diff --git a/AGENTS.md b/AGENTS.md index e258f5a2..d55603d9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -99,6 +99,9 @@ file dist/M5CardputerZero-APPLaunch # expect ARM aarch64 sh projects/APPLaunch/tests/run_tests.sh # 42 C++ + 17 Python contracts sh ext_components/cp0_lvgl/tests/run_tests.sh # 81 C++ +# 2b. Building ON the device itself (no dev headers, no apt): cross profile + native gcc +scripts/device_launcher.sh build # then: try [secs] | install | rollback | status + # 4. Build the .deb (**does not compile anything** — packages the existing dist/) python3 scripts/debian_packager.py @@ -253,6 +256,7 @@ Screen geometry: **320×170**, a 20px top bar plus a 320×150 content area. | ESC long-press to return home | `main/ui/esc_hold_hint_controller.cpp` | `handle`, `poll` | | Hang watchdog | `main/ui/esc_ui_watchdog.{h,cpp}` | `ESC_UI_RECOVERY_DELAY_MS` (exit code 75) | | Global keyboard shortcuts | `main/ui/model/global_hint_policy.cpp` + `ui_global_hint.cpp` | `action_for` | +| Alt+Tab app switcher (keep apps running) | `main/ui/launch.cpp` (`RunningApp`, `key_filter_cb`) + `ui_app_switcher.cpp` + `model/app_switcher_model.cpp`; external apps are SIGSTOPped by `ext_components/cp0_lvgl/src/cp0/cp0_external_app_runner.cpp` | `ExecSwitchable` / `ResumeSuspended` / `KillSuspended` | | Volume/brightness stepping and persistence | `main/ui/launcher_media_controls.cpp` + `model/setup_value_policy.hpp` | — | | Volume/brightness OSD | `main/ui/launcher_media_osd.cpp` | `model/launcher_media_model.hpp` | | Toast styling | `main/ui/launcher_toast.cpp` | `kShowDurationMs` | @@ -275,7 +279,7 @@ Screen geometry: **320×170**, a 20px top bar plus a 320×150 content area. | Type | Entry point | Behavior | | --- | --- | --- | -| **External executable** (`.desktop`, `Exec`) | `Launch::launch_Exec()` | `cp0_signal_process_api({"ExecBlocking", ...})` — **blocking**; meanwhile `lv_timer_enable(false)` and the child process owns the framebuffer. **Do not** create timers / toasts / threads inside that window | +| **External executable** (`.desktop`, `Exec`) | `Launch::launch_Exec()` | `Launch::run_external()` → `cp0_signal_process_api({"ExecSwitchable", ...})` — **blocking** until the app exits or Alt+Tab suspends it; meanwhile `lv_timer_enable(false)` and the child process owns the framebuffer. **Do not** create timers / toasts / threads inside that window | | **Terminal-style** (CLI, Python, `Terminal=true`) | `Launch::launch_Exec_in_terminal()` + `UISTPage` | goes through `cp0_signal_pty_api`, 30ms polling, ESC long-press to exit | The framebuffer hand-off order for external apps is **asserted point by point** by `tests/test_external_framebuffer_ownership.py` — read that test before refactoring the code. diff --git a/docs/cp0_lvgl.en.md b/docs/cp0_lvgl.en.md index 335517aa..a76bbd36 100644 --- a/docs/cp0_lvgl.en.md +++ b/docs/cp0_lvgl.en.md @@ -138,7 +138,7 @@ Session commands are `BtSessionInit` (returns an id), `BtSessionDeinit id`, `BtS ### Process, OS information, and time -`cp0_signal_process_api` commands are `ExecBlocking executable keep_root`, `Spawn executable keep_root`, `Stop pid`, `CheckLock path`, `Kill pid grace_ms`, `RunArgv background argv...`, `RunSudo password argv...` (legacy only), `CaptureArgv argv...`, `AdbStatus`, `DesktopExecIsSafe executable`, `Shutdown`, `Reboot`, and `DelayMs milliseconds`. `Spawn` returns a PID; `CaptureArgv` returns stdout; `AdbStatus` returns two status lines. +`cp0_signal_process_api` commands are `ExecBlocking executable keep_root`, `ExecSwitchable executable keep_root`, `ResumeSuspended pgid`, `KillSuspended pgid`, `Spawn executable keep_root`, `Stop pid`, `CheckLock path`, `Kill pid grace_ms`, `RunArgv background argv...`, `RunSudo password argv...` (legacy only), `CaptureArgv argv...`, `AdbStatus`, `DesktopExecIsSafe executable`, `Shutdown`, `Reboot`, and `DelayMs milliseconds`. `ExecSwitchable` behaves like `ExecBlocking`, but Alt+Tab (pressed, then released) stops the app's process group and saves the framebuffer; its data is `exited` or `suspended `. `ResumeSuspended` restores the framebuffer, drops input queued for the stopped app, continues it and answers in the same format; `KillSuspended` terminates a suspended group. `Spawn` returns a PID; `CaptureArgv` returns stdout; `AdbStatus` returns two status lines. `cp0_signal_osinfo_api` and `cp0_signal_timedate_api` share one service. Commands are `NetworkDefaultInfoRead`, `EthInfoRead` (three lines: IPv4, gateway, MAC), `NetworkList` (tab-separated interface records), `AccountInfoRead` (user and hostname), `TimeSet timestamp`, `LocalTime` (`year,month,day,hour,minute,second`), `RandomU32`, `NtpGet`, `NtpSet 0|1`, `AptUpdateBackground`, and `UpdateLauncherBackground`. diff --git a/docs/cp0_lvgl.ja.md b/docs/cp0_lvgl.ja.md index 88793805..e11a55a5 100644 --- a/docs/cp0_lvgl.ja.md +++ b/docs/cp0_lvgl.ja.md @@ -113,7 +113,7 @@ Wi-Fi のコマンドは `Status`、`Scan [0..32]`、`Connect ssid [password]` Settings のコマンドは `BacklightRead`、`BacklightMax`、`BacklightWrite value`、`Log topic message`、`TimeStr`、`GpioSet name 0|1`、`GpioGet name`。GPIO 名は `GROVE5V`/`extport_usb`、`EXT5V`/`extport_5vout`、`BACKLIGHT` です。 -Process のコマンドは `ExecBlocking executable keep_root`、`Spawn executable keep_root`、`Stop pid`、`CheckLock path`、`Kill pid grace_ms`、`RunArgv background argv...`、legacy の `RunSudo`、`CaptureArgv argv...`、`AdbStatus`、`DesktopExecIsSafe executable`、`Shutdown`、`Reboot`、`DelayMs milliseconds`。OS 情報と timedate は同じ service で、network/account 情報、`TimeSet`、`LocalTime`、`RandomU32`、`NtpGet`、`NtpSet`、背景更新を処理します。 +Process のコマンドは `ExecBlocking executable keep_root`、`ExecSwitchable executable keep_root`、`ResumeSuspended pgid`、`KillSuspended pgid`、`Spawn executable keep_root`、`Stop pid`、`CheckLock path`、`Kill pid grace_ms`、`RunArgv background argv...`、legacy の `RunSudo`、`CaptureArgv argv...`、`AdbStatus`、`DesktopExecIsSafe executable`、`Shutdown`、`Reboot`、`DelayMs milliseconds`。`ExecSwitchable` は `ExecBlocking` と同じですが、Alt+Tab(押して離す)でアプリのプロセスグループを停止(SIGSTOP)し framebuffer を保存します。data は `exited` または `suspended `。`ResumeSuspended` は framebuffer を復元し、停止中に溜まった入力を破棄して再開し、同じ形式で応答します。`KillSuspended` は停止中のグループを終了します。OS 情報と timedate は同じ service で、network/account 情報、`TimeSet`、`LocalTime`、`RandomU32`、`NtpGet`、`NtpSet`、背景更新を処理します。 ### Battery、screenshot、camera、soundcard diff --git a/docs/cp0_lvgl.md b/docs/cp0_lvgl.md index 62fed524..b1f0998e 100644 --- a/docs/cp0_lvgl.md +++ b/docs/cp0_lvgl.md @@ -251,7 +251,7 @@ int cp0_time_ntp_set(int enable); ### 进程:`cp0_signal_process_api(args, cb)` -命令和参数:`ExecBlocking executable keep_root`、`Spawn executable keep_root`、`Stop pid`、`CheckLock path`、`Kill pid grace_ms`、`RunArgv background argv...`、`RunSudo password argv...`(旧接口,禁止新增使用)、`CaptureArgv argv...`、`AdbStatus`、`DesktopExecIsSafe executable`、`Shutdown`、`Reboot`、`DelayMs milliseconds`。`Spawn` data 为 PID;`CaptureArgv` data 为 stdout;`AdbStatus` data 为 `adbd=active|inactive` 和 `enabled=enabled|disabled` 两行。 +命令和参数:`ExecBlocking executable keep_root`、`ExecSwitchable executable keep_root`、`ResumeSuspended pgid`、`KillSuspended pgid`、`Spawn executable keep_root`、`Stop pid`、`CheckLock path`、`Kill pid grace_ms`、`RunArgv background argv...`、`RunSudo password argv...`(旧接口,禁止新增使用)、`CaptureArgv argv...`、`AdbStatus`、`DesktopExecIsSafe executable`、`Shutdown`、`Reboot`、`DelayMs milliseconds`。`ExecSwitchable` 与 `ExecBlocking` 相同,但 Alt+Tab(按下并松开)会暂停(SIGSTOP)应用进程组并保存 framebuffer,data 为 `exited` 或 `suspended `;`ResumeSuspended` 恢复 framebuffer、丢弃暂停期间积压的输入并继续运行,返回格式相同;`KillSuspended` 结束已暂停的进程组。`Spawn` data 为 PID;`CaptureArgv` data 为 stdout;`AdbStatus` data 为 `adbd=active|inactive` 和 `enabled=enabled|disabled` 两行。 ### OS 信息和时间:`cp0_signal_osinfo_api` / `cp0_signal_timedate_api` diff --git a/ext_components/cp0_lvgl/src/cp0/cp0_external_app_runner.cpp b/ext_components/cp0_lvgl/src/cp0/cp0_external_app_runner.cpp index 5cdc2528..b1cd1d55 100644 --- a/ext_components/cp0_lvgl/src/cp0/cp0_external_app_runner.cpp +++ b/ext_components/cp0_lvgl/src/cp0/cp0_external_app_runner.cpp @@ -8,18 +8,29 @@ #include "cp0_esc_exit_policy.hpp" #include "cp0_esc_state.h" +#include "../cp0_app_switch_hotkey.hpp" #include "../cp0_external_process_group.hpp" #include "cp0_process_commands.hpp" #include #include #include +#include +#include +#include +#include #include +#include #if !defined(_WIN32) +#include #include +#include #include +#include #include +#include +#include #include #include #endif @@ -44,66 +55,203 @@ std::uint64_t monotonic_ms() std::chrono::steady_clock::now().time_since_epoch()).count()); } -} // namespace +#if !defined(_WIN32) -int run(const char *command, bool keep_root) -{ -#if defined(_WIN32) - (void)command; - (void)keep_root; - return -1; -#else - keyboard_pause(); - const bool subreaper = cp0_process_group::enable_subreaper(); +// pgid -> framebuffer contents captured when the group was stopped. +std::mutex g_suspended_mutex; +std::map> g_suspended; - const int keyboard_fd = open(keyboard_device(), O_RDONLY | O_NONBLOCK); - if (keyboard_fd < 0) { - std::perror("[cp0] open evdev"); - keyboard_resume(); - return -1; +const char *framebuffer_device() +{ + for (const char *name : {"APPLAUNCH_LINUX_FBDEV_DEVICE", "LV_LINUX_FBDEV_DEVICE"}) { + const char *value = std::getenv(name); + if (value && value[0]) return value; } - std::printf("[cp0] Opened evdev %s (no EVIOCGRAB; shared with child)\n", keyboard_device()); - std::fflush(stdout); + return "/dev/fb0"; +} - const pid_t pid = fork(); - if (pid < 0) { - close(keyboard_fd); - keyboard_resume(); - return -1; +bool framebuffer_window(int fd, off_t &offset, size_t &length) +{ + fb_var_screeninfo var{}; + fb_fix_screeninfo fix{}; + if (ioctl(fd, FBIOGET_VSCREENINFO, &var) < 0 || ioctl(fd, FBIOGET_FSCREENINFO, &fix) < 0) + return false; + offset = static_cast(var.yoffset) * fix.line_length; + length = static_cast(var.yres) * fix.line_length; + if (length == 0 || static_cast(offset) + length > fix.smem_len) return false; + return true; +} + +std::vector save_framebuffer() +{ + std::vector pixels; + const int fd = open(framebuffer_device(), O_RDONLY | O_CLOEXEC); + if (fd < 0) return pixels; + off_t offset = 0; + size_t length = 0; + if (framebuffer_window(fd, offset, length)) { + pixels.resize(length); + if (pread(fd, pixels.data(), length, offset) != static_cast(length)) + pixels.clear(); } - if (pid == 0) { - close(keyboard_fd); - setpgid(0, 0); - if (keep_root) - execlp("/bin/sh", "sh", "-c", command, static_cast(nullptr)); - else - cp0_process_commands::exec_shell_as_configured_user(command); - _exit(127); + close(fd); + return pixels; +} + +void restore_framebuffer(const std::vector &pixels) +{ + if (pixels.empty()) return; + const int fd = open(framebuffer_device(), O_WRONLY | O_CLOEXEC); + if (fd < 0) return; + off_t offset = 0; + size_t length = 0; + if (framebuffer_window(fd, offset, length) && length == pixels.size()) + (void)!pwrite(fd, pixels.data(), length, offset); + close(fd); +} + +pid_t process_group_of(const char *pid_text) +{ + char path[64]; + std::snprintf(path, sizeof(path), "/proc/%s/stat", pid_text); + FILE *file = std::fopen(path, "re"); + if (!file) return -1; + char buffer[512] = {}; + const size_t read = std::fread(buffer, 1, sizeof(buffer) - 1, file); + std::fclose(file); + buffer[read] = '\0'; + // Fields after "(comm)": state ppid pgrp ... + const char *end_of_comm = std::strrchr(buffer, ')'); + if (!end_of_comm) return -1; + char state = 0; + int ppid = 0; + int pgrp = -1; + if (std::sscanf(end_of_comm + 1, " %c %d %d", &state, &ppid, &pgrp) != 3) return -1; + return static_cast(pgrp); +} + +// A stopped app keeps receiving evdev events in its own client buffer (the +// keyboard is shared, not grabbed). Discard them before continuing the app so +// keys typed into the launcher or other apps are not replayed into it. +void discard_group_input(pid_t pgid) +{ +#if defined(SYS_pidfd_open) && defined(SYS_pidfd_getfd) + DIR *proc = opendir("/proc"); + if (!proc) return; + while (dirent *entry = readdir(proc)) { + if (entry->d_name[0] < '0' || entry->d_name[0] > '9') continue; + if (process_group_of(entry->d_name) != pgid) continue; + const pid_t pid = static_cast(std::atoi(entry->d_name)); + const int pidfd = static_cast(syscall(SYS_pidfd_open, pid, 0)); + if (pidfd < 0) continue; + + char fd_dir_path[64]; + std::snprintf(fd_dir_path, sizeof(fd_dir_path), "/proc/%d/fd", static_cast(pid)); + if (DIR *fd_dir = opendir(fd_dir_path)) { + while (dirent *fd_entry = readdir(fd_dir)) { + if (fd_entry->d_name[0] < '0' || fd_entry->d_name[0] > '9') continue; + char link_path[384]; + char target[128] = {}; + std::snprintf(link_path, sizeof(link_path), "%s/%s", fd_dir_path, fd_entry->d_name); + const ssize_t n = readlink(link_path, target, sizeof(target) - 1); + if (n <= 0 || std::strncmp(target, "/dev/input/event", 16) != 0) continue; + const int local = static_cast( + syscall(SYS_pidfd_getfd, pidfd, std::atoi(fd_entry->d_name), 0)); + if (local < 0) { + std::fprintf(stderr, "[process] cannot drain input of pid=%d: %s\n", + static_cast(pid), std::strerror(errno)); + continue; + } + input_event events[64]; + for (int guard = 0; guard < 256; ++guard) { + pollfd ready{local, POLLIN, 0}; + if (poll(&ready, 1, 0) <= 0 || !(ready.revents & POLLIN)) break; + if (read(local, events, sizeof(events)) <= 0) break; + } + close(local); + } + closedir(fd_dir); + } + close(pidfd); } + closedir(proc); +#else + (void)pgid; +#endif +} - setpgid(pid, pid); - std::fprintf(stderr, - "[process] external app leader=%d pgid=%d subreaper=%d\n", - static_cast(pid), - static_cast(pid), - subreaper ? 1 : 0); +bool any_key_down(int keyboard_fd) +{ + unsigned char keys[KEY_MAX / 8 + 1] = {}; + if (ioctl(keyboard_fd, EVIOCGKEY(sizeof(keys)), keys) < 0) return false; + for (unsigned char byte : keys) + if (byte) return true; + return false; +} + +void wait_for_keys_released(int keyboard_fd) +{ + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(2); + while (any_key_down(keyboard_fd) && std::chrono::steady_clock::now() < deadline) + std::this_thread::sleep_for(std::chrono::milliseconds(10)); +} +int open_keyboard() +{ + const int fd = open(keyboard_device(), O_RDONLY | O_NONBLOCK | O_CLOEXEC); + if (fd < 0) std::perror("[cp0] open evdev"); + return fd; +} + +void finish_supervision(int keyboard_fd) +{ + close(keyboard_fd); + keyboard_resume(); + cp0_esc_state_reset(); + std::printf("[cp0] Returned to launcher\n"); + std::fflush(stdout); +} + +// Supervises a running group until it exits or (when switchable) the user +// presses Alt+Tab. Takes ownership of keyboard_fd and resumes the launcher +// keyboard before returning. +Outcome supervise(pid_t pid, int keyboard_fd, bool switchable) +{ cp0_esc_exit_policy::StateMachine esc_policy; + cp0_app_switch_hotkey::Detector hotkey; bool leader_reaped = false; int status = 0; + Outcome outcome; while (true) { cp0_process_group::reap_available(pid, pid, status, leader_reaped); if (!cp0_process_group::exists(pid)) break; + bool switch_requested = false; struct input_event event; while (read(keyboard_fd, &event, sizeof(event)) == static_cast(sizeof(event))) { - if (event.type == EV_KEY && event.code == KEY_ESC) { + if (event.type != EV_KEY) continue; + if (event.code == KEY_ESC) { if (event.value == 1) cp0_esc_state_write(1); else if (event.value == 0) cp0_esc_state_write(0); } + if (switchable && hotkey.update(event.code, event.value)) switch_requested = true; + } + + if (switch_requested && killpg(pid, SIGSTOP) == 0) { + if (esc_policy.finish().hide_hint) ui_external_esc_hint(0); + std::vector pixels = save_framebuffer(); + { + std::lock_guard lock(g_suspended_mutex); + g_suspended[pid] = std::move(pixels); + } + std::fprintf(stderr, "[process] Alt+Tab: suspended pgid=%d\n", static_cast(pid)); + finish_supervision(keyboard_fd); + outcome.suspended = true; + outcome.pgid = static_cast(pid); + return outcome; } const bool esc_now = cp0_esc_state_read() != 0; @@ -127,12 +275,134 @@ int run(const char *command, bool keep_root) "[process] external app group drained pgid=%d leader_reaped=%d\n", static_cast(pid), leader_reaped ? 1 : 0); - close(keyboard_fd); - keyboard_resume(); - cp0_esc_state_reset(); - std::printf("[cp0] Returned to launcher\n"); + finish_supervision(keyboard_fd); + outcome.exit_code = WIFEXITED(status) ? WEXITSTATUS(status) : -1; + return outcome; +} + +Outcome start(const char *command, bool keep_root, bool switchable) +{ + keyboard_pause(); + const bool subreaper = cp0_process_group::enable_subreaper(); + + const int keyboard_fd = open_keyboard(); + if (keyboard_fd < 0) { + keyboard_resume(); + return {}; + } + std::printf("[cp0] Opened evdev %s (no EVIOCGRAB; shared with child)\n", keyboard_device()); std::fflush(stdout); - return WIFEXITED(status) ? WEXITSTATUS(status) : -1; + + const pid_t pid = fork(); + if (pid < 0) { + close(keyboard_fd); + keyboard_resume(); + return {}; + } + if (pid == 0) { + close(keyboard_fd); + setpgid(0, 0); + if (keep_root) + execlp("/bin/sh", "sh", "-c", command, static_cast(nullptr)); + else + cp0_process_commands::exec_shell_as_configured_user(command); + _exit(127); + } + + setpgid(pid, pid); + std::fprintf(stderr, + "[process] external app leader=%d pgid=%d subreaper=%d switchable=%d\n", + static_cast(pid), + static_cast(pid), + subreaper ? 1 : 0, + switchable ? 1 : 0); + return supervise(pid, keyboard_fd, switchable); +} + +bool take_suspended(pid_t pgid, std::vector &pixels) +{ + std::lock_guard lock(g_suspended_mutex); + auto it = g_suspended.find(pgid); + if (it == g_suspended.end()) return false; + pixels = std::move(it->second); + g_suspended.erase(it); + return true; +} + +#endif + +} // namespace + +int run(const char *command, bool keep_root) +{ +#if defined(_WIN32) + (void)command; + (void)keep_root; + return -1; +#else + return start(command, keep_root, false).exit_code; +#endif +} + +Outcome run_switchable(const char *command, bool keep_root) +{ +#if defined(_WIN32) + (void)command; + (void)keep_root; + return {}; +#else + return start(command, keep_root, true); +#endif +} + +Outcome resume(int pgid) +{ +#if defined(_WIN32) + (void)pgid; + return {}; +#else + std::vector pixels; + if (pgid <= 0 || !take_suspended(static_cast(pgid), pixels)) return {}; + + keyboard_pause(); + const int keyboard_fd = open_keyboard(); + if (keyboard_fd < 0) { + keyboard_resume(); + std::lock_guard lock(g_suspended_mutex); + g_suspended[static_cast(pgid)] = std::move(pixels); + Outcome still_suspended; + still_suspended.suspended = true; + still_suspended.pgid = pgid; + return still_suspended; + } + + // The key that selected this app must not leak its release into the app. + wait_for_keys_released(keyboard_fd); + struct input_event stale; + while (read(keyboard_fd, &stale, sizeof(stale)) > 0) { + } + restore_framebuffer(pixels); + discard_group_input(static_cast(pgid)); + std::fprintf(stderr, "[process] resuming pgid=%d\n", pgid); + killpg(static_cast(pgid), SIGCONT); + return supervise(static_cast(pgid), keyboard_fd, true); +#endif +} + +int terminate(int pgid) +{ +#if defined(_WIN32) + (void)pgid; + return -1; +#else + std::vector pixels; + if (pgid <= 0 || !take_suspended(static_cast(pgid), pixels)) return -1; + std::fprintf(stderr, "[process] terminating suspended pgid=%d\n", pgid); + // SIGTERM stays pending on stopped tasks; SIGCONT lets them handle it. + killpg(static_cast(pgid), SIGTERM); + killpg(static_cast(pgid), SIGCONT); + cp0_process_group::terminate_and_reap(static_cast(pgid), static_cast(pgid)); + return 0; #endif } diff --git a/ext_components/cp0_lvgl/src/cp0/cp0_external_app_runner.hpp b/ext_components/cp0_lvgl/src/cp0/cp0_external_app_runner.hpp index bc2421c8..dfd7883c 100644 --- a/ext_components/cp0_lvgl/src/cp0/cp0_external_app_runner.hpp +++ b/ext_components/cp0_lvgl/src/cp0/cp0_external_app_runner.hpp @@ -8,6 +8,23 @@ namespace cp0_external_app_runner { +struct Outcome { + bool suspended = false; // true: the group is SIGSTOPped and waits for resume()/terminate() + int exit_code = -1; // valid when !suspended + int pgid = 0; // valid when suspended +}; + int run(const char *command, bool keep_root); +// Like run(), but Alt+Tab (pressed, then fully released) stops the whole +// process group, saves the framebuffer and returns control to the launcher. +Outcome run_switchable(const char *command, bool keep_root); + +// Restores the saved framebuffer, discards input the stopped app queued and +// continues a group previously suspended by run_switchable()/resume(). +Outcome resume(int pgid); + +// Terminates a suspended group. Returns 0 on success, -1 for an unknown pgid. +int terminate(int pgid); + } // namespace cp0_external_app_runner diff --git a/ext_components/cp0_lvgl/src/cp0/cp0_lvgl_process.cpp b/ext_components/cp0_lvgl/src/cp0/cp0_lvgl_process.cpp index 2cd38ed7..8c00e6db 100644 --- a/ext_components/cp0_lvgl/src/cp0/cp0_lvgl_process.cpp +++ b/ext_components/cp0_lvgl/src/cp0/cp0_lvgl_process.cpp @@ -48,6 +48,30 @@ class ProcessSystem report(callback, cp0_external_app_runner::run(exec_path->c_str(), keep_root), ""); + } else if (cmd == "ExecSwitchable") { + bool keep_root = false; + const auto *exec_path = cp0_process_api_contract::argument_at(arg, 1); + const auto *keep_root_text = cp0_process_api_contract::argument_at(arg, 2); + if (!cp0_process_api_contract::has_exact_arguments(arg, 3) || !exec_path || + exec_path->empty() || !keep_root_text || + !cp0_process_api_contract::parse_bool(*keep_root_text, keep_root)) + return invalid(callback); + report_outcome(callback, + cp0_external_app_runner::run_switchable(exec_path->c_str(), keep_root)); + } else if (cmd == "ResumeSuspended") { + int pgid = 0; + const auto *text = cp0_process_api_contract::argument_at(arg, 1); + if (!cp0_process_api_contract::has_exact_arguments(arg, 2) || !text || + !cp0_process_api_contract::parse_pid(*text, pgid)) + return invalid(callback); + report_outcome(callback, cp0_external_app_runner::resume(pgid)); + } else if (cmd == "KillSuspended") { + int pgid = 0; + const auto *text = cp0_process_api_contract::argument_at(arg, 1); + if (!cp0_process_api_contract::has_exact_arguments(arg, 2) || !text || + !cp0_process_api_contract::parse_pid(*text, pgid)) + return invalid(callback); + report(callback, cp0_external_app_runner::terminate(pgid), ""); } else if (cmd == "Spawn") { bool keep_root = false; const auto *exec_path = cp0_process_api_contract::argument_at(arg, 1); @@ -177,6 +201,14 @@ class ProcessSystem cp0_process_api_contract::invoke_callback_safely(callback, code, data); } + static void report_outcome(callback_t callback, const cp0_external_app_runner::Outcome &outcome) + { + if (outcome.suspended) + report(callback, 0, "suspended " + std::to_string(outcome.pgid)); + else + report(callback, outcome.exit_code, "exited"); + } + static void invalid(const callback_t &callback) { report(callback, -1, "invalid process api arguments"); diff --git a/ext_components/cp0_lvgl/src/cp0_app_switch_hotkey.hpp b/ext_components/cp0_lvgl/src/cp0_app_switch_hotkey.hpp new file mode 100644 index 00000000..052ff153 --- /dev/null +++ b/ext_components/cp0_lvgl/src/cp0_app_switch_hotkey.hpp @@ -0,0 +1,56 @@ +/* + * SPDX-FileCopyrightText: 2026 M5Stack Technology CO LTD + * + * SPDX-License-Identifier: MIT + */ + +#pragma once + +namespace cp0_app_switch_hotkey { + +inline constexpr int kKeyTab = 15; +inline constexpr int kKeyLeftAlt = 56; +inline constexpr int kKeyRightAlt = 100; + +// Detects Alt+Tab on raw evdev key events while an external app owns the +// screen. The chord fires only after Alt and Tab are both released again so +// the app sees a balanced press/release sequence before it is stopped. +class Detector +{ +public: + // value: evdev EV_KEY value (0 release, 1 press, 2 autorepeat). + bool update(int code, int value) + { + if (value == 2) return false; + const bool down = value == 1; + if (code == kKeyLeftAlt || code == kKeyRightAlt) { + alt_ = down; + } else if (code == kKeyTab) { + tab_ = down; + if (down && alt_) armed_ = true; + } else if (down) { + armed_ = false; + } + if (armed_ && !alt_ && !tab_) { + armed_ = false; + return true; + } + return false; + } + + bool armed() const { return armed_; } + + void reset() + { + alt_ = false; + tab_ = false; + armed_ = false; + } + +private: + bool alt_ = false; + bool tab_ = false; + bool armed_ = false; +}; + +} // namespace cp0_app_switch_hotkey diff --git a/ext_components/cp0_lvgl/src/sdl/sdl_lvgl_process.cpp b/ext_components/cp0_lvgl/src/sdl/sdl_lvgl_process.cpp index 2d9fdaf7..842ca9f9 100644 --- a/ext_components/cp0_lvgl/src/sdl/sdl_lvgl_process.cpp +++ b/ext_components/cp0_lvgl/src/sdl/sdl_lvgl_process.cpp @@ -38,7 +38,7 @@ class ProcessSystem { try { const std::string command = args.empty() ? "" : args.front(); - if (command == "ExecBlocking") { + if (command == "ExecBlocking" || command == "ExecSwitchable") { bool keep_root = false; const auto *executable = cp0_process_api_contract::argument_at(args, 1); const auto *keep_root_text = cp0_process_api_contract::argument_at(args, 2); diff --git a/ext_components/cp0_lvgl/tests/run_tests.sh b/ext_components/cp0_lvgl/tests/run_tests.sh index 4d5fdef9..4281f4ce 100755 --- a/ext_components/cp0_lvgl/tests/run_tests.sh +++ b/ext_components/cp0_lvgl/tests/run_tests.sh @@ -244,6 +244,10 @@ fi -I"$root/include" "$root/tests/test_esc_exit_policy.cpp" -o "$binary" "$binary" +"${CXX:-c++}" -std=c++17 -Wall -Wextra -Werror \ + -I"$root/src" "$root/tests/test_app_switch_hotkey.cpp" -o "$binary" +"$binary" + "${CXX:-c++}" -std=c++17 -Wall -Wextra -Werror -pthread \ -I"$root/include" -I"$root/src" \ "$esc_state_object" \ diff --git a/ext_components/cp0_lvgl/tests/test_app_switch_hotkey.cpp b/ext_components/cp0_lvgl/tests/test_app_switch_hotkey.cpp new file mode 100644 index 00000000..aee65ec2 --- /dev/null +++ b/ext_components/cp0_lvgl/tests/test_app_switch_hotkey.cpp @@ -0,0 +1,71 @@ +/* + * SPDX-FileCopyrightText: 2026 M5Stack Technology CO LTD + * + * SPDX-License-Identifier: MIT + */ + +#include "cp0_app_switch_hotkey.hpp" + +#include + +using cp0_app_switch_hotkey::Detector; +using cp0_app_switch_hotkey::kKeyLeftAlt; +using cp0_app_switch_hotkey::kKeyTab; + +namespace { + +constexpr int kKeyA = 30; + +void fires_after_both_keys_are_released() +{ + Detector detector; + assert(!detector.update(kKeyLeftAlt, 1)); + assert(!detector.update(kKeyTab, 1)); + assert(detector.armed()); + assert(!detector.update(kKeyTab, 2)); + assert(!detector.update(kKeyTab, 0)); + assert(detector.update(kKeyLeftAlt, 0)); + assert(!detector.armed()); +} + +void fires_when_alt_is_released_first() +{ + Detector detector; + detector.update(kKeyLeftAlt, 1); + detector.update(kKeyTab, 1); + assert(!detector.update(kKeyLeftAlt, 0)); + assert(detector.update(kKeyTab, 0)); +} + +void ignores_plain_tab_and_late_alt() +{ + Detector detector; + assert(!detector.update(kKeyTab, 1)); + assert(!detector.update(kKeyLeftAlt, 1)); + assert(!detector.armed()); + assert(!detector.update(kKeyTab, 0)); + assert(!detector.update(kKeyLeftAlt, 0)); +} + +void other_key_cancels_the_chord() +{ + Detector detector; + detector.update(kKeyLeftAlt, 1); + detector.update(kKeyTab, 1); + detector.update(kKeyA, 1); + assert(!detector.armed()); + detector.update(kKeyA, 0); + detector.update(kKeyTab, 0); + assert(!detector.update(kKeyLeftAlt, 0)); +} + +} // namespace + +int main() +{ + fires_after_both_keys_are_released(); + fires_when_alt_is_released_first(); + ignores_plain_tab_and_late_alt(); + other_key_cancels_the_chord(); + return 0; +} diff --git a/projects/APPLaunch/main/ui/launch.cpp b/projects/APPLaunch/main/ui/launch.cpp index c12ca06d..d3147155 100644 --- a/projects/APPLaunch/main/ui/launch.cpp +++ b/projects/APPLaunch/main/ui/launch.cpp @@ -17,7 +17,12 @@ #include "ui_loading.h" #include "cp0_lvgl_app.h" #include "sample_log.h" +#include "launcher_toast.h" +#include "model/app_switcher_model.hpp" +#include "ui_app_page.hpp" +#include +#include #include #include #include @@ -28,6 +33,16 @@ namespace { constexpr size_t kHomeCarouselSlotCount = 5; constexpr int kHomeCarouselCenterSlot = 2; +Launch *g_switch_owner = nullptr; + +void bind_keypad_group(lv_group_t *group) +{ + for (lv_indev_t *input = lv_indev_get_next(nullptr); input; input = lv_indev_get_next(input)) { + const lv_indev_type_t type = lv_indev_get_type(input); + if (type == LV_INDEV_TYPE_KEYPAD || type == LV_INDEV_TYPE_ENCODER) + lv_indev_set_group(input, group); + } +} } // ============================================================ @@ -49,6 +64,10 @@ void Launch::bind_ui() app_directory_watcher_.start([this] { applications_reload(); }); esc_ui_watchdog_.start(); esc_hold_hint_controller().set_force_home_callback(esc_force_home_cb, this); + + previous_key_filter_ = cp0_keyboard_get_key_filter(); + g_switch_owner = this; + cp0_keyboard_set_key_filter(key_filter_cb); } void Launch::launch_app() @@ -56,6 +75,12 @@ void Launch::launch_app() const app *selected = app_at_index(current_app); if (!selected) return; + if (RunningApp *running = find_running_app(selected->Name)) { + switch_to_running_app(running->id); + return; + } + launching_name_ = selected->Name; + try { selected->launch(this); } catch (const std::exception &error) { @@ -73,15 +98,18 @@ void Launch::lv_go_back_home(void *arg) noexcept if (!self || !self->page_lifecycle_.complete_home()) return; try { esc_hold_hint_controller().set_return_home_enabled(false); - SLOGI("[HOME] lv_go_back_home executing (page=%p)", self->app_Page.get()); + const std::uint64_t closing = self->foreground_app_; + SLOGI("[HOME] lv_go_back_home executing (app=%llu)", static_cast(closing)); + self->foreground_app_ = 0; lv_timer_enable(true); if (auto page = self->launch_page_.lock()) page->show_home_screen(); lv_refr_now(nullptr); - self->app_Page.reset(); + self->erase_running_app(closing); self->esc_ui_watchdog_.disarm(); SLOGI("[HOME] lv_go_back_home done, on launcher home"); } catch (...) { - self->app_Page.reset(); + self->erase_running_app(self->foreground_app_); + self->foreground_app_ = 0; self->esc_ui_watchdog_.disarm(); } } @@ -90,7 +118,8 @@ void Launch::go_back_home() { if (!page_lifecycle_.request_home()) return; esc_hold_hint_controller().set_return_home_enabled(false); - SLOGI("[HOME] go_back_home() requested, scheduling async call (page=%p)", app_Page.get()); + SLOGI("[HOME] go_back_home() requested, scheduling async call (app=%llu)", + static_cast(foreground_app_)); if (lv_async_call(lv_go_back_home, this) != LV_RESULT_OK) { page_lifecycle_.cancel_home_request(); esc_hold_hint_controller().set_return_home_enabled(true); @@ -117,9 +146,11 @@ void Launch::abort_page_launch() noexcept try { esc_hold_hint_controller().set_return_home_enabled(false); if (auto page = launch_page_.lock()) page->show_home_screen(); - app_Page.reset(); + erase_running_app(foreground_app_); + foreground_app_ = 0; } catch (...) { - app_Page.reset(); + erase_running_app(foreground_app_); + foreground_app_ = 0; } try { @@ -139,8 +170,7 @@ void Launch::launch_Exec_in_terminal(const std::string &exec, bool sysplause, auto p = std::make_shared(help_factory); if (!p->screen()) throw std::runtime_error("terminal page creation failed"); - app_Page = p; - p->navigate_home = std::bind(&Launch::go_back_home, this); + adopt_page(p, *p); p->terminal_sysplause = sysplause; ui_loading::hide(); cp0_lvgl_start_app_page(*p); @@ -150,6 +180,17 @@ void Launch::launch_Exec_in_terminal(const std::string &exec, bool sysplause, void Launch::launch_Exec(const std::string &exec, bool keep_root) { SLOGI("Launching external app: %s (keep_root=%d)", exec.c_str(), keep_root); + const ExternalOutcome outcome = run_external({"ExecSwitchable", exec, keep_root ? "1" : "0"}); + if (outcome.suspended_pgid > 0) { + register_suspended_external(outcome.suspended_pgid); + open_switcher(); + return; + } + SLOGI("External app exited with code %d", outcome.code); +} + +Launch::ExternalOutcome Launch::run_external(std::list request) +{ ui_loading::show("Loading..."); lv_disp_t *disp = lv_disp_get_default(); lv_indev_t *indev = lv_indev_get_next(nullptr); @@ -159,17 +200,20 @@ void Launch::launch_Exec(const std::string &exec, bool keep_root) lv_refr_now(disp); // External apps own the framebuffer exclusively. Keep process supervision // active in the backend, but stop every Launcher timer/flush until the - // child exits; drawing an LVGL toast here would overwrite the child UI. + // child exits or is suspended with Alt+Tab; drawing an LVGL toast here + // would overwrite the child UI. lv_timer_enable(false); - int result = -1; + ExternalOutcome outcome; try { - cp0_signal_process_api( - {"ExecBlocking", exec, keep_root ? "1" : "0"}, - [&](int code, std::string) { result = code; }); + cp0_signal_process_api(std::move(request), [&](int code, std::string data) { + outcome.code = code; + static const std::string kSuspended = "suspended "; + if (data.compare(0, kSuspended.size(), kSuspended) == 0) + outcome.suspended_pgid = std::atoi(data.c_str() + kSuspended.size()); + }); } catch (...) { - result = -1; + outcome = ExternalOutcome{}; } - SLOGI("External app exited with code %d", result); lv_timer_enable(true); if (indev) lv_indev_set_group(indev, UILaunchPage::home_input_group()); @@ -179,6 +223,307 @@ void Launch::launch_Exec(const std::string &exec, bool keep_root) lv_refr_now(disp); LVGL_RUN_FLAGE = 1; ui_screensaver_set_foreground(1); + return outcome; +} + +// ============================================================ +// Running apps / Alt+Tab switcher +// ============================================================ +void Launch::adopt_page(std::shared_ptr holder, AppPageRoot &page) +{ + RunningApp entry; + entry.id = next_running_id_++; + entry.name = launching_name_.empty() ? page.page_title_ : launching_name_; + entry.holder = std::move(holder); + entry.page = &page; + entry.last_used = ++use_counter_; + const std::uint64_t id = entry.id; + page.navigate_home = [this, id] { close_running_app(id); }; + running_apps_.push_back(std::move(entry)); + foreground_app_ = id; +} + +Launch::RunningApp *Launch::find_running_app(std::uint64_t id) +{ + if (id == 0) return nullptr; + for (RunningApp &entry : running_apps_) + if (entry.id == id) return &entry; + return nullptr; +} + +Launch::RunningApp *Launch::find_running_app(const std::string &name) +{ + for (RunningApp &entry : running_apps_) + if (entry.name == name) return &entry; + return nullptr; +} + +void Launch::erase_running_app(std::uint64_t id) +{ + if (id == 0) return; + auto it = std::find_if(running_apps_.begin(), running_apps_.end(), + [id](const RunningApp &entry) { return entry.id == id; }); + if (it == running_apps_.end()) return; + // Destroy the page after it left the list so re-entrant callbacks see a + // consistent registry. + std::shared_ptr holder = std::move(it->holder); + if (it->page) it->page->navigate_home = nullptr; + running_apps_.erase(it); + holder.reset(); +} + +void Launch::close_running_app(std::uint64_t id, bool immediate) +{ + RunningApp *entry = find_running_app(id); + if (!entry) return; + if (id == foreground_app_) { + go_back_home(); + return; + } + if (entry->pgid > 0) { + const int pgid = entry->pgid; + erase_running_app(id); + try { + cp0_signal_process_api({"KillSuspended", std::to_string(pgid)}, [](int, std::string) {}); + } catch (...) { + } + return; + } + if (immediate) { + erase_running_app(id); + return; + } + // A background page asked to close itself (e.g. its process exited). + // Destroy it outside the page's own LVGL callback. + pending_close_.push_back(id); + if (pending_close_.size() == 1 && lv_async_call(lv_close_pending, this) != LV_RESULT_OK) + pending_close_.clear(); +} + +void Launch::lv_close_pending(void *arg) noexcept +{ + auto *self = static_cast(arg); + if (!self) return; + try { + std::vector ids; + ids.swap(self->pending_close_); + for (std::uint64_t id : ids) { + if (id == self->foreground_app_) continue; + self->erase_running_app(id); + } + } catch (...) { + } +} + +void Launch::send_foreground_page_to_background() +{ + RunningApp *current = find_running_app(foreground_app_); + if (!current) return; + current->saved_screen = lv_screen_active(); + lv_indev_t *indev = lv_indev_get_next(nullptr); + current->saved_group = indev ? lv_indev_get_group(indev) : nullptr; + current->saved_input_context = cp0_keyboard_get_input_context(); + current->saved_keypad_intercept = cp0_keyboard_get_lvgl_keypad_intercept(); + foreground_app_ = 0; + if (page_lifecycle_.request_home()) page_lifecycle_.complete_home(); + esc_hold_hint_controller().set_return_home_enabled(false); + esc_ui_watchdog_.disarm(); + cp0_keyboard_set_input_context(KBD_INPUT_CONTEXT_NAVIGATION); + cp0_keyboard_set_lvgl_keypad_intercept(0); + if (auto page = launch_page_.lock()) page->show_home_screen(); + lv_refr_now(nullptr); + SLOGI("[SWITCH] '%s' moved to background", current->name.c_str()); +} + +void Launch::switch_to_running_app(std::uint64_t id) +{ + RunningApp *entry = find_running_app(id); + if (!entry || id == foreground_app_) return; + if (entry->pgid > 0) { + resume_external(id); + return; + } + + send_foreground_page_to_background(); + if (!page_lifecycle_.begin_app()) return; + esc_hold_hint_controller().set_return_home_enabled(true); + esc_ui_watchdog_.arm(); + foreground_app_ = id; + entry->last_used = ++use_counter_; + SLOGI("[SWITCH] '%s' moved to foreground", entry->name.c_str()); + + lv_obj_t *nested = entry->saved_screen; + if (nested && nested != entry->page->screen() && lv_obj_is_valid(nested)) { + // The page was showing a sub-screen of its own (e.g. SSH terminal). + lv_screen_load(nested); + if (entry->saved_group) bind_keypad_group(entry->saved_group); + lv_obj_invalidate(nested); + lv_refr_now(nullptr); + } else { + cp0_lvgl_start_app_page(*entry->page); + } + cp0_keyboard_set_input_context(entry->saved_input_context); + cp0_keyboard_set_lvgl_keypad_intercept(entry->saved_keypad_intercept); +} + +void Launch::register_suspended_external(int pgid) +{ + RunningApp entry; + entry.id = next_running_id_++; + entry.name = launching_name_.empty() ? std::string("App") : launching_name_; + entry.pgid = pgid; + entry.last_used = ++use_counter_; + running_apps_.push_back(std::move(entry)); + SLOGI("[SWITCH] external '%s' suspended (pgid=%d)", launching_name_.c_str(), pgid); +} + +void Launch::resume_external(std::uint64_t id) +{ + RunningApp *entry = find_running_app(id); + if (!entry || entry->pgid <= 0) return; + send_foreground_page_to_background(); + entry->last_used = ++use_counter_; + SLOGI("[SWITCH] resuming external '%s' (pgid=%d)", entry->name.c_str(), entry->pgid); + + const ExternalOutcome outcome = + run_external({"ResumeSuspended", std::to_string(entry->pgid)}); + // The LVGL thread was blocked while the app ran; the registry is unchanged. + entry = find_running_app(id); + if (!entry) return; + if (outcome.suspended_pgid > 0) { + entry->pgid = outcome.suspended_pgid; + open_switcher(); + return; + } + SLOGI("[SWITCH] external '%s' exited with code %d", entry->name.c_str(), outcome.code); + erase_running_app(id); +} + +bool Launch::switcher_allowed() const +{ + const LauncherPageState state = page_lifecycle_.state(); + return LVGL_RUN_FLAGE != 0 && + (state == LauncherPageState::HOME || state == LauncherPageState::APP_ACTIVE); +} + +void Launch::open_switcher() +{ + if (running_apps_.empty()) { + switcher_.hide(); + launcher_toast().show("No running apps"); + return; + } + + std::vector candidates; + candidates.reserve(running_apps_.size()); + for (const RunningApp &entry : running_apps_) + candidates.push_back({entry.id, entry.last_used}); + const AppSwitcherLayout layout = app_switcher_layout(candidates, foreground_app_); + + std::vector rows; + rows.reserve(layout.ids.size()); + for (std::uint64_t id : layout.ids) { + AppSwitcherOverlay::Entry row; + if (id == 0) { + row.label = "Home"; + row.home = true; + } else if (const RunningApp *entry = find_running_app(id)) { + row.label = entry->pgid > 0 ? entry->name + " (paused)" : entry->name; + row.current = id == foreground_app_; + } + rows.push_back(std::move(row)); + } + switcher_ids_ = layout.ids; + switcher_selected_ = layout.selected; + switcher_.show(rows, switcher_selected_); +} + +void Launch::handle_switcher_key(const struct key_item *item) +{ + const AppSwitcherCommand command = app_switcher_command_for({ + item->key_code, + item->semantic_key, + item->key_state == KBD_KEY_PRESSED, + item->key_state == KBD_KEY_REPEATED, + (item->mods & KBD_MOD_ALT) != 0, + (item->mods & KBD_MOD_SHIFT) != 0, + }); + + switch (command) { + case AppSwitcherCommand::NEXT: + case AppSwitcherCommand::PREVIOUS: + switcher_selected_ = app_switcher_step( + switcher_selected_, command == AppSwitcherCommand::NEXT ? 1 : -1, + switcher_ids_.size()); + switcher_.select(switcher_selected_); + return; + case AppSwitcherCommand::DISMISS: + swallow_release_key_ = item->key_code; + switcher_.hide(); + return; + case AppSwitcherCommand::CLOSE: { + if (switcher_selected_ >= switcher_ids_.size()) return; + const std::uint64_t id = switcher_ids_[switcher_selected_]; + if (id == 0) return; + swallow_release_key_ = item->key_code; + switcher_.hide(); + close_running_app(id, true); + // Reopen with the remaining apps unless the foreground page is + // closing (its async return-home is in flight). + if (page_lifecycle_.state() != LauncherPageState::HOME_PENDING && !running_apps_.empty()) + open_switcher(); + return; + } + case AppSwitcherCommand::ACTIVATE: { + if (switcher_selected_ >= switcher_ids_.size()) return; + const std::uint64_t id = switcher_ids_[switcher_selected_]; + swallow_release_key_ = item->key_code; + switcher_.hide(); + if (id == 0) + send_foreground_page_to_background(); + else + switch_to_running_app(id); + return; + } + case AppSwitcherCommand::NONE: + default: + return; + } +} + +int Launch::key_filter_cb(const struct key_item *item) noexcept +{ + Launch *self = g_switch_owner; + if (!item || !self) return 0; + try { + if (self->swallow_release_key_ != 0 && item->key_code == self->swallow_release_key_ && + item->key_state != KBD_KEY_PRESSED) { + if (item->key_state == KBD_KEY_RELEASED) self->swallow_release_key_ = 0; + return 1; + } + + if (self->switcher_.visible()) { + self->handle_switcher_key(item); + return 1; + } + + const AppSwitcherKeyInput input{ + item->key_code, + item->semantic_key, + item->key_state == KBD_KEY_PRESSED, + item->key_state == KBD_KEY_REPEATED, + (item->mods & KBD_MOD_ALT) != 0, + (item->mods & KBD_MOD_SHIFT) != 0, + }; + if (app_switcher_is_trigger(input)) { + if (self->switcher_allowed()) self->open_switcher(); + self->swallow_release_key_ = item->key_code; + return 1; + } + } catch (...) { + self->switcher_.hide(); + } + return self->previous_key_filter_ ? self->previous_key_filter_(item) : 0; } void Launch::select_next_app() @@ -266,7 +611,7 @@ const app *Launch::app_at_index(int index) const void Launch::esc_force_home_cb(void *user_data) noexcept { auto *self = static_cast(user_data); - if (!self || !self->app_Page || LVGL_RUN_FLAGE == 0) return; + if (!self || self->foreground_app_ == 0 || LVGL_RUN_FLAGE == 0) return; try { SLOGW("[HOME] ESC held for 3000 ms, forcing built-in page home"); self->go_back_home(); @@ -277,6 +622,20 @@ void Launch::esc_force_home_cb(void *user_data) noexcept Launch::~Launch() { + if (g_switch_owner == this) { + cp0_keyboard_set_key_filter(previous_key_filter_); + g_switch_owner = nullptr; + } + switcher_.hide(); + for (const RunningApp &entry : running_apps_) { + if (entry.pgid <= 0) continue; + try { + cp0_signal_process_api({"KillSuspended", std::to_string(entry.pgid)}, + [](int, std::string) {}); + } catch (...) { + } + } + lv_async_call_cancel(lv_close_pending, this); launcher_app_registry_clear_changed_callback(app_registry_changed_cb, this); esc_hold_hint_controller().set_force_home_callback(nullptr, nullptr); esc_hold_hint_controller().set_return_home_enabled(false); diff --git a/projects/APPLaunch/main/ui/launch.h b/projects/APPLaunch/main/ui/launch.h index 1b7509b3..5651f4d1 100644 --- a/projects/APPLaunch/main/ui/launch.h +++ b/projects/APPLaunch/main/ui/launch.h @@ -13,8 +13,11 @@ #include "esc_ui_watchdog.h" #include "model/launcher_navigation_model.hpp" #include "terminal_help_factory.hpp" +#include "ui_app_switcher.h" +#include "keyboard_input.h" #include +#include #include #include #include @@ -25,6 +28,7 @@ class Launch; class UILaunchPage; +class AppPageRoot; template struct page_t @@ -73,6 +77,43 @@ class Launch private: friend struct app; + // An app kept alive while the user switches away from it (Alt+Tab). + // Built-in/terminal pages keep their LVGL screen; external programs are + // stopped (SIGSTOP) by the backend and identified by their process group. + struct RunningApp { + std::uint64_t id = 0; + std::string name; + std::shared_ptr holder; + AppPageRoot *page = nullptr; + lv_obj_t *saved_screen = nullptr; + lv_group_t *saved_group = nullptr; + cp0_keyboard_input_context_t saved_input_context = KBD_INPUT_CONTEXT_NAVIGATION; + int saved_keypad_intercept = 0; + int pgid = 0; + std::uint64_t last_used = 0; + }; + + struct ExternalOutcome { + int code = -1; + int suspended_pgid = 0; + }; + + void adopt_page(std::shared_ptr holder, AppPageRoot &page); + RunningApp *find_running_app(std::uint64_t id); + RunningApp *find_running_app(const std::string &name); + void erase_running_app(std::uint64_t id); + void close_running_app(std::uint64_t id, bool immediate = false); + void send_foreground_page_to_background(); + void switch_to_running_app(std::uint64_t id); + ExternalOutcome run_external(std::list request); + void resume_external(std::uint64_t id); + void register_suspended_external(int pgid); + bool switcher_allowed() const; + void open_switcher(); + void handle_switcher_key(const struct key_item *item); + static int key_filter_cb(const struct key_item *item) noexcept; + static void lv_close_pending(void *arg) noexcept; + void go_back_home(); bool begin_page_launch(); void abort_page_launch() noexcept; @@ -99,7 +140,17 @@ class Launch int fixed_count = 0; bool bound_ = false; std::list app_list; - std::shared_ptr app_Page; + std::vector running_apps_; + std::vector pending_close_; + std::uint64_t foreground_app_ = 0; // 0: launcher home + std::uint64_t next_running_id_ = 1; + std::uint64_t use_counter_ = 0; + std::string launching_name_; + AppSwitcherOverlay switcher_; + std::vector switcher_ids_; + size_t switcher_selected_ = 0; + uint32_t swallow_release_key_ = 0; + cp0_keyboard_key_filter_t previous_key_filter_ = nullptr; }; template @@ -113,8 +164,7 @@ app::app(std::string name, std::string icon, page_t) auto page = std::make_shared(); if (!page->screen()) throw std::runtime_error("application page creation failed"); - owner->app_Page = page; - page->navigate_home = std::bind(&Launch::go_back_home, owner); + owner->adopt_page(page, *page); ui_loading::hide(); cp0_lvgl_start_app_page(*page); }; @@ -135,8 +185,7 @@ app::app(std::string name, std::string icon, page_t, TerminalHelpFactory page = std::make_shared(); if (!page->screen()) throw std::runtime_error("application page creation failed"); - owner->app_Page = page; - page->navigate_home = std::bind(&Launch::go_back_home, owner); + owner->adopt_page(page, *page); ui_loading::hide(); cp0_lvgl_start_app_page(*page); }; diff --git a/projects/APPLaunch/main/ui/model/app_switcher_model.cpp b/projects/APPLaunch/main/ui/model/app_switcher_model.cpp new file mode 100644 index 00000000..99aa0bfb --- /dev/null +++ b/projects/APPLaunch/main/ui/model/app_switcher_model.cpp @@ -0,0 +1,88 @@ +/* + * SPDX-FileCopyrightText: 2026 M5Stack Technology CO LTD + * + * SPDX-License-Identifier: MIT + */ + +#include "app_switcher_model.hpp" + +#include "input_keys.h" + +#include + +bool app_switcher_is_trigger(const AppSwitcherKeyInput &input) +{ + return input.pressed && input.alt && input.key_code == KEY_TAB; +} + +AppSwitcherCommand app_switcher_command_for(const AppSwitcherKeyInput &input) +{ + if (!input.pressed && !input.repeated) + return AppSwitcherCommand::NONE; + + if (input.key_code == KEY_TAB) + return input.shift ? AppSwitcherCommand::PREVIOUS : AppSwitcherCommand::NEXT; + + const uint32_t code = input.semantic_key ? input.semantic_key : input.key_code; + switch (code) { + case KEY_DOWN: + case KEY_RIGHT: + return AppSwitcherCommand::NEXT; + case KEY_UP: + case KEY_LEFT: + return AppSwitcherCommand::PREVIOUS; + default: + break; + } + + if (!input.pressed) + return AppSwitcherCommand::NONE; + + switch (code) { + case KEY_ENTER: + case KEY_SPACE: + return AppSwitcherCommand::ACTIVATE; + case KEY_BACKSPACE: + case KEY_DELETE: + return AppSwitcherCommand::CLOSE; + case KEY_ESC: + return AppSwitcherCommand::DISMISS; + default: + return AppSwitcherCommand::NONE; + } +} + +AppSwitcherLayout app_switcher_layout(const std::vector &running, + uint64_t foreground_id) +{ + std::vector ordered = running; + std::stable_sort(ordered.begin(), ordered.end(), + [foreground_id](const AppSwitcherCandidate &a, const AppSwitcherCandidate &b) { + const bool a_front = a.id == foreground_id; + const bool b_front = b.id == foreground_id; + if (a_front != b_front) return a_front; + return a.last_used > b.last_used; + }); + + AppSwitcherLayout layout; + for (const AppSwitcherCandidate &candidate : ordered) + layout.ids.push_back(candidate.id); + + const bool app_in_front = foreground_id != 0 && + std::any_of(running.begin(), running.end(), + [foreground_id](const AppSwitcherCandidate &c) { return c.id == foreground_id; }); + if (app_in_front) { + layout.ids.push_back(0); + layout.selected = layout.ids.size() > 1 ? 1 : 0; + } + return layout; +} + +size_t app_switcher_step(size_t index, int delta, size_t count) +{ + if (count == 0) return 0; + const long long size = static_cast(count); + long long next = (static_cast(index) + delta) % size; + if (next < 0) next += size; + return static_cast(next); +} diff --git a/projects/APPLaunch/main/ui/model/app_switcher_model.hpp b/projects/APPLaunch/main/ui/model/app_switcher_model.hpp new file mode 100644 index 00000000..1e9c2b7b --- /dev/null +++ b/projects/APPLaunch/main/ui/model/app_switcher_model.hpp @@ -0,0 +1,54 @@ +/* + * SPDX-FileCopyrightText: 2026 M5Stack Technology CO LTD + * + * SPDX-License-Identifier: MIT + */ + +#pragma once + +#include +#include +#include + +enum class AppSwitcherCommand { + NONE, + NEXT, + PREVIOUS, + ACTIVATE, + CLOSE, + DISMISS, +}; + +struct AppSwitcherKeyInput { + uint32_t key_code = 0; // raw evdev code + uint32_t semantic_key = 0; // context-normalized code (0 when none) + bool pressed = false; + bool repeated = false; + bool alt = false; + bool shift = false; +}; + +// Alt+Tab press opens the switcher from anywhere inside the launcher. +bool app_switcher_is_trigger(const AppSwitcherKeyInput &input); + +// Key mapping while the switcher is open. +AppSwitcherCommand app_switcher_command_for(const AppSwitcherKeyInput &input); + +struct AppSwitcherCandidate { + uint64_t id = 0; + uint64_t last_used = 0; +}; + +// id 0 in `ids` stands for the launcher home screen. +struct AppSwitcherLayout { + std::vector ids; + size_t selected = 0; +}; + +// Orders entries most-recently-used first: the foreground app (if any), the +// other running apps, then Home when an app is in the foreground. The initial +// selection is the entry the user most likely wants: the previous app. +AppSwitcherLayout app_switcher_layout(const std::vector &running, + uint64_t foreground_id); + +size_t app_switcher_step(size_t index, int delta, size_t count); diff --git a/projects/APPLaunch/main/ui/ui_app_switcher.cpp b/projects/APPLaunch/main/ui/ui_app_switcher.cpp new file mode 100644 index 00000000..30ad30bc --- /dev/null +++ b/projects/APPLaunch/main/ui/ui_app_switcher.cpp @@ -0,0 +1,126 @@ +/* + * SPDX-FileCopyrightText: 2026 M5Stack Technology CO LTD + * + * SPDX-License-Identifier: MIT + */ + +#include "ui_app_switcher.h" + +#include "ui.h" + +namespace { + +constexpr lv_coord_t kWidth = 260; +constexpr lv_coord_t kRowHeight = 22; +constexpr size_t kMaxVisibleRows = 4; +constexpr uint32_t kPanelColor = 0x16202C; +constexpr uint32_t kBorderColor = 0x3A6EA5; +constexpr uint32_t kSelectedColor = 0x1F5FAF; +constexpr uint32_t kTextColor = 0xFFFFFF; +constexpr uint32_t kMutedColor = 0x9AA7B4; + +lv_font_t *font(int size, lv_freetype_font_style_t style) +{ + return launcher_fonts().get("AlibabaPuHuiTi-3-55-Regular.ttf", size, style); +} + +lv_obj_t *make_label(lv_obj_t *parent, const char *text, int size, lv_freetype_font_style_t style, + uint32_t color) +{ + lv_obj_t *label = lv_label_create(parent); + lv_label_set_text(label, text); + lv_obj_set_style_text_color(label, lv_color_hex(color), 0); + lv_obj_set_style_text_font(label, font(size, style), 0); + return label; +} + +} // namespace + +AppSwitcherOverlay::~AppSwitcherOverlay() +{ + hide(); +} + +void AppSwitcherOverlay::show(const std::vector &entries, size_t selected) +{ + hide(); + lv_obj_t *parent = lv_layer_top(); + if (!parent || entries.empty()) return; + + const size_t visible_rows = entries.size() < kMaxVisibleRows ? entries.size() : kMaxVisibleRows; + const lv_coord_t list_height = static_cast(visible_rows) * kRowHeight; + + container_ = lv_obj_create(parent); + lv_obj_remove_style_all(container_); + lv_obj_set_size(container_, kWidth, list_height + 48); + lv_obj_center(container_); + lv_obj_set_style_bg_color(container_, lv_color_hex(kPanelColor), 0); + lv_obj_set_style_bg_opa(container_, LV_OPA_COVER, 0); + lv_obj_set_style_border_color(container_, lv_color_hex(kBorderColor), 0); + lv_obj_set_style_border_width(container_, 1, 0); + lv_obj_set_style_radius(container_, 8, 0); + lv_obj_set_style_pad_all(container_, 4, 0); + lv_obj_clear_flag(container_, LV_OBJ_FLAG_SCROLLABLE); + lv_obj_clear_flag(container_, LV_OBJ_FLAG_CLICKABLE); + + lv_obj_t *title = make_label(container_, "Running apps", 12, LV_FREETYPE_FONT_STYLE_BOLD, + kTextColor); + lv_obj_align(title, LV_ALIGN_TOP_LEFT, 4, 0); + + lv_obj_t *list = lv_obj_create(container_); + lv_obj_remove_style_all(list); + lv_obj_set_size(list, kWidth - 10, list_height); + lv_obj_align(list, LV_ALIGN_TOP_MID, 0, 18); + lv_obj_set_flex_flow(list, LV_FLEX_FLOW_COLUMN); + lv_obj_set_scrollbar_mode(list, LV_SCROLLBAR_MODE_OFF); + lv_obj_clear_flag(list, LV_OBJ_FLAG_CLICKABLE); + + rows_.clear(); + for (const Entry &entry : entries) { + lv_obj_t *row = lv_obj_create(list); + lv_obj_remove_style_all(row); + lv_obj_set_size(row, LV_PCT(100), kRowHeight); + lv_obj_set_style_radius(row, 4, 0); + lv_obj_set_style_bg_color(row, lv_color_hex(kSelectedColor), 0); + lv_obj_set_style_bg_opa(row, LV_OPA_TRANSP, 0); + lv_obj_clear_flag(row, LV_OBJ_FLAG_SCROLLABLE); + lv_obj_clear_flag(row, LV_OBJ_FLAG_CLICKABLE); + + lv_obj_t *name = make_label(row, entry.label.c_str(), 14, LV_FREETYPE_FONT_STYLE_NORMAL, + kTextColor); + lv_label_set_long_mode(name, LV_LABEL_LONG_DOT); + lv_obj_set_width(name, kWidth - 90); + lv_obj_align(name, LV_ALIGN_LEFT_MID, 6, 0); + + const char *tag = entry.current ? "current" : (entry.home ? "launcher" : ""); + if (tag[0]) { + lv_obj_t *note = make_label(row, tag, 12, LV_FREETYPE_FONT_STYLE_NORMAL, kMutedColor); + lv_obj_align(note, LV_ALIGN_RIGHT_MID, -6, 0); + } + rows_.push_back(row); + } + + lv_obj_t *hint = make_label(container_, "Tab next Enter open Del close Esc", 12, + LV_FREETYPE_FONT_STYLE_NORMAL, kMutedColor); + lv_obj_align(hint, LV_ALIGN_BOTTOM_MID, 0, 0); + + lv_obj_move_foreground(container_); + select(selected); +} + +void AppSwitcherOverlay::select(size_t index) +{ + for (size_t i = 0; i < rows_.size(); ++i) + lv_obj_set_style_bg_opa(rows_[i], i == index ? LV_OPA_COVER : LV_OPA_TRANSP, 0); + if (index < rows_.size()) + lv_obj_scroll_to_view(rows_[index], LV_ANIM_OFF); +} + +void AppSwitcherOverlay::hide() +{ + rows_.clear(); + if (container_) { + lv_obj_delete(container_); + container_ = nullptr; + } +} diff --git a/projects/APPLaunch/main/ui/ui_app_switcher.h b/projects/APPLaunch/main/ui/ui_app_switcher.h new file mode 100644 index 00000000..1291a7ef --- /dev/null +++ b/projects/APPLaunch/main/ui/ui_app_switcher.h @@ -0,0 +1,36 @@ +/* + * SPDX-FileCopyrightText: 2026 M5Stack Technology CO LTD + * + * SPDX-License-Identifier: MIT + */ + +#pragma once + +#include "lvgl/lvgl.h" + +#include +#include +#include + +// Alt+Tab overlay listing running apps. Lives on lv_layer_top() so it floats +// above the launcher home and every built-in page. +class AppSwitcherOverlay +{ +public: + struct Entry { + std::string label; + bool current = false; + bool home = false; + }; + + ~AppSwitcherOverlay(); + + void show(const std::vector &entries, size_t selected); + void select(size_t index); + void hide(); + bool visible() const { return container_ != nullptr; } + +private: + lv_obj_t *container_ = nullptr; + std::vector rows_; +}; diff --git a/projects/APPLaunch/tests/run_tests.sh b/projects/APPLaunch/tests/run_tests.sh index 9559476b..0eb10f92 100755 --- a/projects/APPLaunch/tests/run_tests.sh +++ b/projects/APPLaunch/tests/run_tests.sh @@ -253,6 +253,12 @@ ${CXX:-g++} -std=c++17 -Wall -Wextra -Werror \ "$(dirname "$0")/../main/ui/model/global_hint_policy.cpp" \ -o "$build_dir/test_global_hint_policy" "$build_dir/test_global_hint_policy" +${CXX:-g++} -std=c++17 -Wall -Wextra -Werror \ + -I"$(dirname "$0")/../../../ext_components/cp0_lvgl/include" \ + "$(dirname "$0")/test_app_switcher_model.cpp" \ + "$(dirname "$0")/../main/ui/model/app_switcher_model.cpp" \ + -o "$build_dir/test_app_switcher_model" +"$build_dir/test_app_switcher_model" ${CXX:-g++} -std=c++17 -Wall -Wextra -Werror \ "$(dirname "$0")/test_global_overlay_model.cpp" \ -o "$build_dir/test_global_overlay_model" diff --git a/projects/APPLaunch/tests/test_app_switcher_model.cpp b/projects/APPLaunch/tests/test_app_switcher_model.cpp new file mode 100644 index 00000000..b7913f52 --- /dev/null +++ b/projects/APPLaunch/tests/test_app_switcher_model.cpp @@ -0,0 +1,100 @@ +/* + * SPDX-FileCopyrightText: 2026 M5Stack Technology CO LTD + * + * SPDX-License-Identifier: MIT + */ + +#include "../main/ui/model/app_switcher_model.hpp" + +#include "input_keys.h" + +#include +#include + +namespace { + +AppSwitcherKeyInput press(uint32_t key, bool alt = false, bool shift = false) +{ + AppSwitcherKeyInput input; + input.key_code = key; + input.pressed = true; + input.alt = alt; + input.shift = shift; + return input; +} + +void test_trigger() +{ + assert(app_switcher_is_trigger(press(KEY_TAB, true))); + assert(!app_switcher_is_trigger(press(KEY_TAB))); + assert(!app_switcher_is_trigger(press(KEY_A, true))); + AppSwitcherKeyInput release = press(KEY_TAB, true); + release.pressed = false; + assert(!app_switcher_is_trigger(release)); +} + +void test_commands() +{ + assert(app_switcher_command_for(press(KEY_TAB)) == AppSwitcherCommand::NEXT); + assert(app_switcher_command_for(press(KEY_TAB, true)) == AppSwitcherCommand::NEXT); + assert(app_switcher_command_for(press(KEY_TAB, false, true)) == AppSwitcherCommand::PREVIOUS); + assert(app_switcher_command_for(press(KEY_DOWN)) == AppSwitcherCommand::NEXT); + assert(app_switcher_command_for(press(KEY_UP)) == AppSwitcherCommand::PREVIOUS); + assert(app_switcher_command_for(press(KEY_ENTER)) == AppSwitcherCommand::ACTIVATE); + assert(app_switcher_command_for(press(KEY_BACKSPACE)) == AppSwitcherCommand::CLOSE); + assert(app_switcher_command_for(press(KEY_ESC)) == AppSwitcherCommand::DISMISS); + assert(app_switcher_command_for(press(KEY_A)) == AppSwitcherCommand::NONE); + + AppSwitcherKeyInput semantic = press(KEY_SEMICOLON); + semantic.semantic_key = KEY_UP; + assert(app_switcher_command_for(semantic) == AppSwitcherCommand::PREVIOUS); + + AppSwitcherKeyInput repeat = press(KEY_DOWN); + repeat.pressed = false; + repeat.repeated = true; + assert(app_switcher_command_for(repeat) == AppSwitcherCommand::NEXT); + repeat.key_code = KEY_ENTER; + assert(app_switcher_command_for(repeat) == AppSwitcherCommand::NONE); + + AppSwitcherKeyInput release = press(KEY_ENTER); + release.pressed = false; + assert(app_switcher_command_for(release) == AppSwitcherCommand::NONE); +} + +void test_layout_from_home() +{ + const AppSwitcherLayout layout = app_switcher_layout({{1, 5}, {2, 9}, {3, 7}}, 0); + assert((layout.ids == std::vector{2, 3, 1})); + assert(layout.selected == 0); +} + +void test_layout_from_app() +{ + const AppSwitcherLayout layout = app_switcher_layout({{1, 5}, {2, 9}, {3, 7}}, 1); + assert((layout.ids == std::vector{1, 2, 3, 0})); + assert(layout.selected == 1); + + const AppSwitcherLayout single = app_switcher_layout({{4, 1}}, 4); + assert((single.ids == std::vector{4, 0})); + assert(single.selected == 1); +} + +void test_step() +{ + assert(app_switcher_step(0, 1, 3) == 1); + assert(app_switcher_step(2, 1, 3) == 0); + assert(app_switcher_step(0, -1, 3) == 2); + assert(app_switcher_step(0, 1, 0) == 0); +} + +} // namespace + +int main() +{ + test_trigger(); + test_commands(); + test_layout_from_home(); + test_layout_from_app(); + test_step(); + return 0; +} diff --git a/projects/APPLaunch/tests/test_external_framebuffer_ownership.py b/projects/APPLaunch/tests/test_external_framebuffer_ownership.py index bfbe426e..523b8bb0 100644 --- a/projects/APPLaunch/tests/test_external_framebuffer_ownership.py +++ b/projects/APPLaunch/tests/test_external_framebuffer_ownership.py @@ -8,17 +8,32 @@ source = (Path(__file__).resolve().parents[1] / "main/ui/launch.cpp").read_text( encoding="utf-8" ) -start = source.index("void Launch::launch_Exec(") -end = source.index("\nvoid Launch::select_next_app()", start) -body = source[start:end] + + +def body_of(signature, next_marker): + start = source.index(signature) + end = source.index(next_marker, start + len(signature)) + return source[start:end] + + +launch = body_of("void Launch::launch_Exec(", "\nLaunch::ExternalOutcome Launch::run_external(") +assert '"ExecSwitchable"' in launch +assert "run_external(" in launch + +resume = body_of("void Launch::resume_external(", "\nbool Launch::switcher_allowed()") +assert '"ResumeSuspended"' in resume +assert "run_external(" in resume + +# A fresh launch and an Alt+Tab resume share one framebuffer hand-off sequence. +body = body_of("Launch::ExternalOutcome Launch::run_external(", "\n// ====") paint = body.index("lv_refr_now(disp)") pause = body.index("lv_timer_enable(false)") -execute = body.index('"ExecBlocking"') -resume = body.index("lv_timer_enable(true)") +execute = body.index("cp0_signal_process_api(") +resume_timers = body.index("lv_timer_enable(true)") restore = body.index("page->show_home_screen()") -assert paint < pause < execute < resume < restore +assert paint < pause < execute < resume_timers < restore assert "lv_timer_create" not in body assert "std::thread" not in body assert "launcher_toast" not in body diff --git a/scripts/device_launcher.sh b/scripts/device_launcher.sh new file mode 100755 index 00000000..5d6a4085 --- /dev/null +++ b/scripts/device_launcher.sh @@ -0,0 +1,226 @@ +#!/bin/sh +# SPDX-FileCopyrightText: 2026 M5Stack Technology CO LTD +# SPDX-License-Identifier: MIT +# +# Build and install APPLaunch directly on a CardputerZero (aarch64 Debian). +# +# The stock image has no dev headers (libinput, xkbcommon, freetype, curl...), +# so a native profile cannot compile. Instead this uses the cross profile with +# the downloaded SDK sysroot and points the aarch64-linux-gnu-* toolchain names +# at the native gcc. SCons lives in a private venv; nothing is apt-installed. +# +# scripts/device_launcher.sh build # incremental build -> projects/APPLaunch/dist +# scripts/device_launcher.sh try [secs] # run dist build temporarily (default 1800s); +# # the installed launcher comes back afterwards +# scripts/device_launcher.sh install # install dist binary + resources, restart +# scripts/device_launcher.sh rollback # restore the backed-up originals, restart +# scripts/device_launcher.sh status # show installed/backup/dist binaries +# +# install copies projects/APPLaunch/dist/APPLaunch over /usr/share/APPLaunch but +# never deletes anything there (store apps and packages own files in the same +# tree). Before a file is first overwritten its original is saved under +# $RES_BACKUP/files; files that did not exist are listed in added.list so that +# rollback can remove them again. +# +# Restarting the launcher also ends apps it started (zeroterm and anything in +# it), so restarts are scheduled a few seconds later via systemd-run. +set -eu + +REPO=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd) +PROJECT="$REPO/projects/APPLaunch" +DIST_BIN="$PROJECT/dist/M5CardputerZero-APPLaunch" +INSTALL_BIN=/usr/share/APPLaunch/bin/M5CardputerZero-APPLaunch +BACKUP_BIN="$INSTALL_BIN.orig" +DIST_RES="$PROJECT/dist/APPLaunch" +INSTALL_RES=/usr/share/APPLaunch +RES_BACKUP=/usr/share/APPLaunch.orig-resources +CACHE="${XDG_CACHE_HOME:-$HOME/.cache}/applaunch-device-build" +VENV="$CACHE/venv" +SHIM="$CACHE/toolchain" +SERVICE=APPLaunch.service +RESTART_DELAY=${RESTART_DELAY:-5} + +# Works as the normal user (uses sudo for system files) or as root, e.g. from +# the cardputer-optimize toolkit (builds then run as the owning user and the +# launcher's user systemd instance is reached via runuser). +if [ "$(id -u)" = 0 ]; then + SUDO= + TARGET_USER=${APPLAUNCH_USER:-${SUDO_USER:-$(stat -c %U "$REPO")}} + TARGET_UID=$(id -u "$TARGET_USER") + as_user() { runuser -u "$TARGET_USER" -- env XDG_RUNTIME_DIR="/run/user/$TARGET_UID" "$@"; } +else + SUDO=sudo + as_user() { "$@"; } +fi + +log() { printf '[device_launcher] %s\n' "$*"; } +die() { printf '[device_launcher] error: %s\n' "$*" >&2; exit 1; } + +[ "$(uname -m)" = aarch64 ] || die "run this on the device (aarch64), not $(uname -m)" + +setup_toolchain() { + mkdir -p "$SHIM" + for tool in gcc g++ cpp ar as ld nm objcopy objdump ranlib strip readelf size; do + [ -x "/usr/bin/$tool" ] || die "missing /usr/bin/$tool (install build-essential)" + ln -sf "/usr/bin/$tool" "$SHIM/aarch64-linux-gnu-$tool" + done + if [ ! -x "$VENV/bin/scons" ]; then + log "creating SCons venv in $VENV" + python3 -m venv "$VENV" + "$VENV/bin/pip" install -q scons parse requests tqdm + fi +} + +jobs() { + # ~400MB RAM: one compiler per ~200MB of available memory, at most nproc. + avail_kb=$(awk '/MemAvailable/ {print $2}' /proc/meminfo) + n=$((avail_kb / 200000)) + [ "$n" -ge 1 ] || n=1 + [ "$n" -le "$(nproc)" ] || n=$(nproc) + echo "$n" +} + +cmd_build() { + if [ -z "$SUDO" ]; then + # Never leave root-owned build trees in the user's checkout. + exec runuser -u "$TARGET_USER" -- env HOME="$(getent passwd "$TARGET_USER" | cut -d: -f6)" \ + XDG_CACHE_HOME= "$0" build + fi + setup_toolchain + if [ ! -f "$REPO/SDK/SConstruct" ] && [ ! -d "$REPO/SDK/tools" ]; then + log "initialising SDK submodule" + git -C "$REPO" submodule update --init --depth 1 SDK + fi + n=$(jobs) + log "building with -j$n (first build downloads a ~436MB sysroot and takes a long time)" + cd "$PROJECT" + PATH="$SHIM:$VENV/bin:$PATH" \ + CONFIG_REPO_AUTOMATION=y \ + CONFIG_DEFAULT_FILE=linux_x86_cross_cp0_config_defaults.mk \ + scons -j"$n" + file "$DIST_BIN" | grep -q aarch64 || die "build did not produce an aarch64 binary" + log "built $DIST_BIN" +} + +schedule_restart() { + as_user systemd-run --user --collect --on-active="$RESTART_DELAY" \ + /usr/bin/systemctl --user restart "$SERVICE" >/dev/null + log "launcher restarts in ${RESTART_DELAY}s" +} + +cmd_install() { + [ -x "$DIST_BIN" ] || die "no build at $DIST_BIN; run: $0 build" + file "$DIST_BIN" | grep -q aarch64 || die "$DIST_BIN is not an aarch64 binary" + if [ ! -e "$BACKUP_BIN" ]; then + log "backing up installed launcher to $BACKUP_BIN" + $SUDO cp -a "$INSTALL_BIN" "$BACKUP_BIN" + fi + [ -d "$DIST_RES" ] || die "no resource tree at $DIST_RES; run: $0 build" + # Install next to the target and rename so the swap is atomic. + $SUDO install -m 0755 "$DIST_BIN" "$INSTALL_BIN.new" + $SUDO mv -f "$INSTALL_BIN.new" "$INSTALL_BIN" + log "installed binary $(sha256sum "$INSTALL_BIN" | cut -c1-12)" + install_resources + schedule_restart +} + +install_resources() { + changed=$($SUDO env SRC="$DIST_RES" DST="$INSTALL_RES" BK="$RES_BACKUP" sh -eu <<'EOF' +cd "$SRC" +mkdir -p "$BK/files" +touch "$BK/added.list" +find . -type f | sort | while IFS= read -r f; do + f=${f#./} + t="$DST/$f" + if [ -e "$t" ]; then + cmp -s "$f" "$t" && continue + if [ ! -e "$BK/files/$f" ] && ! grep -qxF "$f" "$BK/added.list"; then + mkdir -p "$BK/files/$(dirname "$f")" + cp -a "$t" "$BK/files/$f" + fi + elif ! grep -qxF "$f" "$BK/added.list"; then + echo "$f" >> "$BK/added.list" + fi + mkdir -p "$(dirname "$t")" + cp --preserve=mode,timestamps "$f" "$t.new" + chown root:root "$t.new" + mv -f "$t.new" "$t" + echo "$f" +done +EOF +) + if [ -n "$changed" ]; then + printf '%s\n' "$changed" | sed 's/^/[device_launcher] updated /' + log "resources: $(printf '%s\n' "$changed" | wc -l) file(s) updated (originals in $RES_BACKUP)" + else + log "resources: already up to date" + fi +} + +rollback_resources() { + [ -d "$RES_BACKUP" ] || return 0 + $SUDO env DST="$INSTALL_RES" BK="$RES_BACKUP" sh -eu <<'EOF' +if [ -d "$BK/files" ]; then + cd "$BK/files" + find . -type f | while IFS= read -r f; do + f=${f#./} + cp -a "$f" "$DST/$f.new" + mv -f "$DST/$f.new" "$DST/$f" + done +fi +if [ -f "$BK/added.list" ]; then + while IFS= read -r f; do + [ -n "$f" ] && rm -f "$DST/$f" + done < "$BK/added.list" +fi +rm -rf "$BK" +EOF + log "restored original resources" +} + +cmd_rollback() { + [ -e "$BACKUP_BIN" ] || die "no backup at $BACKUP_BIN" + $SUDO cp -a "$BACKUP_BIN" "$INSTALL_BIN.new" + $SUDO mv -f "$INSTALL_BIN.new" "$INSTALL_BIN" + log "restored $BACKUP_BIN" + rollback_resources + schedule_restart +} + +cmd_try() { + [ -x "$DIST_BIN" ] || die "no build at $DIST_BIN; run: $0 build" + secs=${1:-1800} + as_user systemd-run --user --unit=applaunch-dev --collect --on-active="$RESTART_DELAY" \ + -p WorkingDirectory=/usr/share/APPLaunch \ + -p RuntimeMaxSec="$secs" \ + -p ExecStartPre="/usr/bin/systemctl --user stop $SERVICE" \ + -p ExecStopPost="/usr/bin/systemctl --user start $SERVICE" \ + "$DIST_BIN" >/dev/null + log "dev launcher starts in ${RESTART_DELAY}s for up to ${secs}s" + log "stop early: systemctl --user stop applaunch-dev logs: journalctl --user -u applaunch-dev -f" +} + +cmd_status() { + for f in "$INSTALL_BIN" "$BACKUP_BIN" "$DIST_BIN"; do + if [ -e "$f" ]; then + printf '%-70s %s %s\n' "$f" "$(sha256sum "$f" | cut -c1-12)" "$(date -r "$f" '+%F %T')" + else + printf '%-70s (missing)\n' "$f" + fi + done + if [ -d "$RES_BACKUP" ]; then + printf 'resource backup: %s file(s) saved, %s file(s) added\n' \ + "$(find "$RES_BACKUP/files" -type f 2>/dev/null | wc -l)" \ + "$(grep -c . "$RES_BACKUP/added.list" 2>/dev/null || echo 0)" + fi + as_user systemctl --user is-active "$SERVICE" | sed "s/^/$SERVICE: /" +} + +case "${1:-}" in + build) cmd_build ;; + install) cmd_install ;; + rollback) cmd_rollback ;; + try) shift; cmd_try "$@" ;; + status) cmd_status ;; + *) sed -n '5,19p' "$0"; exit 2 ;; +esac