diff --git a/ext_components/cp0_lvgl/include/cp0_lvgl_app.h b/ext_components/cp0_lvgl/include/cp0_lvgl_app.h index 8a980ab2..3f233c51 100644 --- a/ext_components/cp0_lvgl/include/cp0_lvgl_app.h +++ b/ext_components/cp0_lvgl/include/cp0_lvgl_app.h @@ -190,6 +190,26 @@ cp0_battery_info_t cp0_battery_read(void); int cp0_backlight_read(void); int cp0_backlight_max(void); int cp0_backlight_write(int val); +/* Red status LED staging for the screen-off state: suspend turns the trigger + * off and the led dark while remembering the previous trigger and brightness; + * restore brings them back. Both degrade to a no-op (negative return) when + * the sysfs nodes are missing or not writable. */ +int cp0_status_led_suspend(void); +void cp0_status_led_restore(void); +/* CPU frequency staging: 1 pins the cpufreq governor to powersave, 0 restores + * the previously active governor. Negative when the node is not writable. */ +int cp0_cpufreq_powersave_set(int enable); +/* Startup safety net: if the governor is still sitting on powersave from a + * previous process that died during the screen-off stage, restore the + * platform default (ondemand). Returns 1 when a stale pin was cleared. */ +int cp0_cpufreq_wake_reset(void); +/* Bluetooth radio power for the screen-off staging: fire-and-forget async + * D-Bus call, safe from the LVGL thread. */ +void cp0_bluetooth_power_set_async(int enabled); +/* LCD panel power through the framebuffer blanking ioctl: 1 blanks the panel + * (display off + MIPI sleep), 0 wakes it again and flushes the framebuffer + * back. 0 on success, negative when no framebuffer can be blanked. */ +int cp0_panel_fb_blank(int blank); void cp0_time_str(char *buf, int buf_size); #ifdef __cplusplus diff --git a/ext_components/cp0_lvgl/include/cp0_status_pause.h b/ext_components/cp0_lvgl/include/cp0_status_pause.h new file mode 100644 index 00000000..d260ccf9 --- /dev/null +++ b/ext_components/cp0_lvgl/include/cp0_status_pause.h @@ -0,0 +1,26 @@ +/* + * SPDX-FileCopyrightText: 2026 M5Stack Technology CO LTD + * + * SPDX-License-Identifier: MIT + */ + +#ifndef CP0_STATUS_PAUSE_H +#define CP0_STATUS_PAUSE_H + +#ifdef __cplusplus +extern "C" { +#endif + +/* Set while the launcher's screen-off state holds the panel dark. Periodic + * UI refreshers (top-bar clock/status, battery events) and the network status + * polling worker consult this and skip their work, so nothing redraws or + * probes the system bus while the screen is off. Wi-Fi itself stays + * connected; the flag only pauses observation. */ +void cp0_status_pause_set(int paused); +int cp0_status_pause_get(void); + +#ifdef __cplusplus +} +#endif + +#endif /* CP0_STATUS_PAUSE_H */ 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..beda3f1c 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 @@ -10,10 +10,17 @@ #include "cp0_esc_state.h" #include "../cp0_external_process_group.hpp" #include "cp0_process_commands.hpp" +#include "cp0_lvgl_app.h" +#include "hal_lvgl_bsp.h" +#include "../cp0_sync_signal.hpp" +#include #include +#include #include #include +#include +#include #include #if !defined(_WIN32) @@ -46,6 +53,177 @@ std::uint64_t monotonic_ms() } // namespace +#if !defined(_WIN32) +namespace { + +/* ---- app-idle backlight staging ------------------------------------------ + * The LVGL thread blocks inside ExecBlocking for the whole app lifetime, so + * the launcher's own screensaver cannot run while a child owns the screen. + * This supervision loop is the only launcher-side code that stays alive, so + * it carries the idle staging: after the configured dark_time with no key + * activity and no audio rendering, the backlight goes dark. Stage 1 only - + * deep sleep stays launcher-home-only, because the keyboard queue drops + * events while an app is foreground, so a deep-sleeping launcher could never + * be woken by a key. Audio actually rendering (radio/music/TV through the + * app) suppresses the staging entirely so the panel stays on for the + * session, and any key press lights the panel back up. */ + +constexpr std::uint64_t kSinkProbePeriodMs = 5000; + +constexpr const char *kBacklightBrightness = "/sys/class/backlight/backlight/brightness"; +constexpr const char *kBacklightMax = "/sys/class/backlight/backlight/max_brightness"; + +int read_int_sysfile(const char *path, int fallback) +{ + FILE *f = std::fopen(path, "r"); + if (!f) return fallback; + int value = fallback; + if (std::fscanf(f, "%d", &value) != 1) value = fallback; + std::fclose(f); + return value; +} + +int backlight_read_raw() +{ + return read_int_sysfile(kBacklightBrightness, -1); +} + +int backlight_write_raw(int val) +{ + if (val < 0) val = 0; + const int maximum = read_int_sysfile(kBacklightMax, 100); + if (val > maximum) val = maximum; + FILE *f = std::fopen(kBacklightBrightness, "w"); + if (!f) return -1; + const int written = std::fprintf(f, "%d", val); + const int close_result = std::fclose(f); + return written > 0 && close_result == 0 ? val : -1; +} + +/* One pactl spawn collects the sinks in the RUNNING state; for each one a + * short pw-record capture of the sink monitor (via stream.capture.sink) + * measures the real output energy. SDL and pygame keep their mixers open + * forever and pump digital silence, which holds a sink in RUNNING without + * any audible media, so only energy counts as "playing". A failed capture + * (no bytes at all) falls back to treating the sink as playing, so a broken + * probe can never sleep the panel in the middle of real media. */ + +constexpr int kAudioPeakThreshold = 200; +constexpr int kMaxProbeSinks = 3; + +int monitor_peak(const char *sink_name) +{ + char command[320]; + std::snprintf(command, sizeof(command), + "timeout 0.45 pw-record -a -P \"stream.capture.sink=true\" " + "--target '%s' --rate 16000 --channels 1 --format s16 - 2>/dev/null", + sink_name); + FILE *capture = ::popen(command, "r"); + if (!capture) return -1; + int peak = 0; + std::size_t bytes = 0; + for (;;) { + unsigned char sample[2] = {}; + const std::size_t got = std::fread(sample, 1, 2, capture); + if (got < 2) { + bytes += got; + break; + } + bytes += 2; + const auto value = static_cast( + static_cast(sample[0]) | + (static_cast(sample[1]) << 8)); + const int magnitude = value < 0 ? -static_cast(value) : value; + if (magnitude > peak) peak = magnitude; + } + ::pclose(capture); + if (bytes == 0) return -1; + return peak; +} + +bool any_media_rendering() +{ + bool playing = false; + FILE *sinks = ::popen("pactl list sinks 2>/dev/null", "r"); + if (!sinks) return false; + char line[256] = {}; + bool sink_running = false; + int probed = 0; + while (probed < kMaxProbeSinks && std::fgets(line, sizeof(line), sinks) != nullptr) { + if (std::strstr(line, "State: ") != nullptr) { + sink_running = std::strstr(line, "RUNNING") != nullptr; + } else if (sink_running && std::strstr(line, "Name: ") != nullptr) { + sink_running = false; + const char *value = std::strchr(line, ':'); + if (!value) continue; + ++value; + while (*value == ' ' || *value == '\t') ++value; + std::size_t len = std::strlen(value); + while (len > 0 && (value[len - 1] == '\n' || value[len - 1] == '\r')) + --len; + if (len == 0 || len >= 128) continue; + char sink_name[128]; + std::snprintf(sink_name, sizeof(sink_name), "%.*s", static_cast(len), value); + ++probed; + const int peak = monitor_peak(sink_name); + if (peak < 0 || peak >= kAudioPeakThreshold) { + playing = true; + break; + } + } + } + ::pclose(sinks); + return playing; +} + +/* dark_time drives the screen-off staging on the launcher home; the same + * whitelist (0/10/30/60/300, 0 = disabled) applies here. The config service + * is mutex-guarded, so reading it from this supervision thread is safe. */ +int app_dark_time_seconds() +{ + constexpr int kDefaultSeconds = 30; + int value = kDefaultSeconds; + try { + cp0::signal::invoke_noexcept([&] { + cp0_signal_config_api({"GetInt", "dark_time", std::to_string(kDefaultSeconds)}, + [&](int code, std::string data) { + if (code != 0) return; + int parsed = 0; + const char *begin = data.data(); + const char *end = begin + data.size(); + const auto result = std::from_chars(begin, end, parsed); + if (result.ec == std::errc{} && result.ptr == end && + (parsed == 0 || parsed == 10 || parsed == 30 || + parsed == 60 || parsed == 300)) + value = parsed; + }); + }); + } catch (...) { + } + return value; +} + +/* Wi-Fi power save amplifies the stall: with PSM on, the radio's periodic + * naps stall the streaming TCP fetch long enough that ffplay's reconnect + * kicks in (up to 5 s of audible gap through a Bluetooth speaker), and the + * busy 2.4 GHz coexistence between the Wi-Fi side and the Bluetooth side of + * the same CYW4343 combo adds transport pressure. While media actually + * renders, the fetch traffic keeps the radio awake anyway, so PSM saves + * nothing but costs the stalls - drop it for the playback period and + * restore it once idle. The image ships a narrow sudoers rule allowing + * exactly these two commands (see etc/sudoers.d/applaunch-wifi-psm); when + * the rule is missing the call fails silently and PSM simply stays on. */ +void wifi_power_save_set(bool enable) +{ + /* iw wants the on/off keywords, not 0/1. */ + std::system(enable + ? "sudo -n /usr/sbin/iw dev wlan0 set power_save on >/dev/null 2>&1" + : "sudo -n /usr/sbin/iw dev wlan0 set power_save off >/dev/null 2>&1"); +} + +} // namespace +#endif + int run(const char *command, bool keep_root) { #if defined(_WIN32) @@ -92,17 +270,38 @@ int run(const char *command, bool keep_root) bool leader_reaped = false; int status = 0; + const int dark_time_seconds = app_dark_time_seconds(); + const bool staging_enabled = dark_time_seconds > 0; + std::uint64_t last_activity_ms = monotonic_ms(); + std::uint64_t last_probe_ms = 0; + bool staged = false; + int staged_prev_raw = -1; + bool wifi_psm_off = false; + auto restore_stage = [&]() { + if (!staged) return; + if (staged_prev_raw > 0) (void)backlight_write_raw(staged_prev_raw); + staged = false; + staged_prev_raw = -1; + (void)cp0_status_led_restore(); + }; + while (true) { cp0_process_group::reap_available(pid, pid, status, leader_reaped); if (!cp0_process_group::exists(pid)) break; 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.value == 1) - cp0_esc_state_write(1); - else if (event.value == 0) - cp0_esc_state_write(0); + if (event.type == EV_KEY) { + 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 (event.value == 1) { + last_activity_ms = monotonic_ms(); + restore_stage(); + } } } @@ -118,9 +317,51 @@ int run(const char *command, bool keep_root) std::fprintf(stderr, "[process] grace timeout: SIGKILL pgid=%d\n", static_cast(pid)); killpg(pid, SIGKILL); } + + /* The media probe drives both the staging and the Wi-Fi PSM toggle, + * so it runs even when the dim staging is disabled (dark_time = 0): + * streaming radio/music must keep the stall-free PSM-off period + * regardless of whether the panel is allowed to go dark. */ + { + const std::uint64_t now_ms = monotonic_ms(); + if (now_ms - last_probe_ms >= kSinkProbePeriodMs) { + last_probe_ms = now_ms; + if (any_media_rendering()) { + /* Radio/music/TV actually audible: media suppresses the + * sleep staging, so the panel stays on for the session. */ + last_activity_ms = now_ms; + restore_stage(); + if (!wifi_psm_off) { + wifi_power_save_set(false); + wifi_psm_off = true; + } + } else { + if (wifi_psm_off) { + wifi_power_save_set(true); + wifi_psm_off = false; + } + if (staging_enabled && !staged && + now_ms - last_activity_ms >= + static_cast(dark_time_seconds) * 1000ULL) { + const int previous = backlight_read_raw(); + if (previous > 0 && backlight_write_raw(0) == 0) { + staged_prev_raw = previous; + staged = true; + (void)cp0_status_led_suspend(); + } + } + } + } + } std::this_thread::sleep_for(std::chrono::milliseconds(10)); } + restore_stage(); + /* The app left the media probe behind; never leave PSM off after it. */ + if (wifi_psm_off) { + wifi_power_save_set(true); + wifi_psm_off = false; + } if (esc_policy.finish().hide_hint) ui_external_esc_hint(0); cp0_process_group::reap_available(pid, pid, status, leader_reaped); std::fprintf(stderr, diff --git a/ext_components/cp0_lvgl/src/cp0/cp0_lvgl_bluetooth.cpp b/ext_components/cp0_lvgl/src/cp0/cp0_lvgl_bluetooth.cpp index 47a364f2..de7c6626 100644 --- a/ext_components/cp0_lvgl/src/cp0/cp0_lvgl_bluetooth.cpp +++ b/ext_components/cp0_lvgl/src/cp0/cp0_lvgl_bluetooth.cpp @@ -74,3 +74,10 @@ int remove(const char *address) } } // namespace cp0_bluetooth_backend + +extern "C" void cp0_bluetooth_power_set_async(int enabled) +{ + /* Fire-and-forget: the screen-off staging calls this on the LVGL thread + * and must never wait on D-Bus. */ + cp0_bluez_dbus::set_power_async(enabled, nullptr); +} diff --git a/ext_components/cp0_lvgl/src/cp0/cp0_lvgl_network.cpp b/ext_components/cp0_lvgl/src/cp0/cp0_lvgl_network.cpp index 434fd827..d4557471 100644 --- a/ext_components/cp0_lvgl/src/cp0/cp0_lvgl_network.cpp +++ b/ext_components/cp0_lvgl/src/cp0/cp0_lvgl_network.cpp @@ -7,6 +7,7 @@ #include "cp0_lvgl_app.h" #include "keyboard_input.h" // LVGL_RUN_FLAGE #include "hal_lvgl_bsp.h" +#include "cp0_status_pause.h" // screen-off polling hold #include "../cp0_app_internal_utils.h" #include "../cp0_network_api_contract.hpp" #include "../cp0_callback_result.hpp" @@ -503,6 +504,17 @@ class WifiSystem auto last_refresh = std::chrono::steady_clock::time_point{}; while (running_.load()) { const auto now = std::chrono::steady_clock::now(); + if (cp0_status_pause_get()) { + /* The panel is dark: hold all status polling instead of the + * 60 s hidden backstop. Wi-Fi itself stays connected; the + * cache refreshes right after the flag clears (last_refresh + * reset below makes the first awake iteration refresh). */ + last_refresh = std::chrono::steady_clock::time_point{}; + std::unique_lock lock(wake_mutex_); + wake_.wait_for(lock, kVisiblePollInterval, + [this] { return !running_.load(); }); + continue; + } if (last_refresh == std::chrono::steady_clock::time_point{} || status_visible() || now - last_refresh >= kHiddenPollInterval) { update_status_cache(); diff --git a/ext_components/cp0_lvgl/src/cp0/cp0_lvgl_settings.cpp b/ext_components/cp0_lvgl/src/cp0/cp0_lvgl_settings.cpp index 9c4f797f..94d8045d 100644 --- a/ext_components/cp0_lvgl/src/cp0/cp0_lvgl_settings.cpp +++ b/ext_components/cp0_lvgl/src/cp0/cp0_lvgl_settings.cpp @@ -25,6 +25,7 @@ #include #include #include +#include #include #include #include @@ -511,3 +512,182 @@ extern "C" void cp0_time_str(char *buf, int buf_size) { SettingsSystem::api_time_str(buf, buf_size); } + +namespace { + +/* ---- screen-off power staging ------------------------------------------ + * Status LED, cpufreq governor and panel blank helpers used by the launcher's + * screen-off sequence. Every one of them degrades to a failure return when + * the sysfs node is missing or not writable; the tmpfiles.d rule shipped in + * the package (mirror of the image's cardputerzero-leds.conf) grants the gpio + * group write access at boot. */ + +constexpr const char *kStatusLedDir = "/sys/class/leds/ACT"; +constexpr const char *kCpufreqGovernorPaths[] = { + "/sys/devices/system/cpu/cpufreq/policy0/scaling_governor", + "/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor", +}; + +bool g_status_led_suspended = false; +std::string g_status_led_trigger; +int g_status_led_brightness = 0; + +bool g_cpufreq_saved_valid = false; +std::string g_cpufreq_saved_governor; + +bool write_text_node(const char *path, const std::string &value) +{ + FILE *f = std::fopen(path, "w"); + if (!f) return false; + const int written = std::fprintf(f, "%s", value.c_str()); + const int close_result = std::fclose(f); + return written > 0 && close_result == 0; +} + +bool read_text_node(const char *path, std::string &value) +{ + FILE *f = std::fopen(path, "r"); + if (!f) return false; + char buffer[256]; + value.clear(); + while (std::fgets(buffer, sizeof(buffer), f)) value += buffer; + const bool ok = std::ferror(f) == 0; + std::fclose(f); + return ok; +} + +bool read_int_node(const char *path, int &value) +{ + std::string text; + if (!read_text_node(path, text)) return false; + char *end = nullptr; + const long parsed = std::strtol(text.c_str(), &end, 10); + if (end == text.c_str()) return false; + value = static_cast(parsed); + return true; +} + +/* The trigger node lists every trigger and brackets the active one, e.g. + * "none default ... [actpwr] mmc0". */ +std::string active_trigger_token(const std::string &trigger_list) +{ + const auto open = trigger_list.find_last_of('['); + const auto close = trigger_list.find_last_of(']'); + if (open == std::string::npos || close == std::string::npos || close < open) + return {}; + return trigger_list.substr(open + 1, close - open - 1); +} + +const char *first_writable_governor_path() +{ + for (const char *path : kCpufreqGovernorPaths) { + /* Open read-write without truncating: this is both the writability + * probe and the handle check for a node that must keep its content. */ + FILE *f = std::fopen(path, "r+"); + if (f) { + std::fclose(f); + return path; + } + } + return nullptr; +} + +std::string trim_node_text(std::string text) +{ + while (!text.empty() && + (text.back() == '\n' || text.back() == '\r' || text.back() == ' ')) + text.pop_back(); + return text; +} + +} // namespace + +extern "C" int cp0_status_led_suspend(void) +{ + const std::string trigger_path = std::string(kStatusLedDir) + "/trigger"; + const std::string brightness_path = std::string(kStatusLedDir) + "/brightness"; + /* The LED classdev can be re-registered by a deferred probe after the + * first suspend (fresh node, default trigger, root-only perms), so every + * call re-asserts the dark state instead of trusting a suspended flag; + * the restore values are saved once, from the first pre-suspend read. */ + if (!g_status_led_suspended) { + std::string trigger_list; + int brightness = 0; + if (!read_text_node(trigger_path.c_str(), trigger_list) || + !read_int_node(brightness_path.c_str(), brightness)) + return -1; + g_status_led_trigger = active_trigger_token(trigger_list); + g_status_led_brightness = brightness > 0 ? brightness : 0; + } + if (!write_text_node(trigger_path.c_str(), "none") || + !write_text_node(brightness_path.c_str(), "0")) + return -1; + g_status_led_suspended = true; + return 0; +} + +extern "C" void cp0_status_led_restore(void) +{ + if (!g_status_led_suspended) return; + g_status_led_suspended = false; + const std::string trigger_path = std::string(kStatusLedDir) + "/trigger"; + const std::string brightness_path = std::string(kStatusLedDir) + "/brightness"; + if (!g_status_led_trigger.empty()) + (void)write_text_node(trigger_path.c_str(), g_status_led_trigger); + if (g_status_led_brightness > 0) + (void)write_text_node(brightness_path.c_str(), + std::to_string(g_status_led_brightness)); + g_status_led_trigger.clear(); + g_status_led_brightness = 0; +} + +extern "C" int cp0_cpufreq_powersave_set(int enable) +{ + const char *path = first_writable_governor_path(); + if (!path) return -1; + if (enable) { + if (!g_cpufreq_saved_valid) { + std::string current; + if (!read_text_node(path, current)) return -1; + current = trim_node_text(std::move(current)); + if (current.empty()) return -1; + g_cpufreq_saved_governor = current; + g_cpufreq_saved_valid = true; + } + return write_text_node(path, "powersave") ? 0 : -1; + } + if (!g_cpufreq_saved_valid) return 0; + const std::string restore = std::move(g_cpufreq_saved_governor); + g_cpufreq_saved_governor.clear(); + g_cpufreq_saved_valid = false; + return write_text_node(path, restore) ? 0 : -1; +} + +extern "C" int cp0_cpufreq_wake_reset(void) +{ + const char *path = first_writable_governor_path(); + if (!path) return 0; + std::string current; + if (!read_text_node(path, current)) return 0; + current = trim_node_text(std::move(current)); + if (current != "powersave") return 0; + /* A previous process died while the screen-off stage had pinned the + * governor down; restore the platform default. */ + return write_text_node(path, "ondemand") ? 1 : -1; +} + +extern "C" int cp0_panel_fb_blank(int blank) +{ + const char *paths[] = {"/dev/fb_lcd", "/dev/fb0"}; + for (const char *path : paths) { + const int fd = open(path, O_RDWR | O_CLOEXEC); + if (fd < 0) continue; + const int result = ioctl(fd, FBIOBLANK, + blank ? FB_BLANK_POWERDOWN : FB_BLANK_UNBLANK); + const int saved_errno = errno; + close(fd); + if (result == 0) return 0; + errno = saved_errno; + } + return -1; +} diff --git a/ext_components/cp0_lvgl/src/cp0_status_pause.c b/ext_components/cp0_lvgl/src/cp0_status_pause.c new file mode 100644 index 00000000..0cc42229 --- /dev/null +++ b/ext_components/cp0_lvgl/src/cp0_status_pause.c @@ -0,0 +1,22 @@ +/* + * SPDX-FileCopyrightText: 2026 M5Stack Technology CO LTD + * + * SPDX-License-Identifier: MIT + */ + +#include "cp0_status_pause.h" + +/* Plain volatile int on purpose: single-word flag, set from the LVGL thread + * (screensaver) and read from the LVGL thread plus the network polling + * worker. Same pattern as LVGL_RUN_FLAGE. */ +static volatile int s_status_pause = 0; + +void cp0_status_pause_set(int paused) +{ + s_status_pause = paused ? 1 : 0; +} + +int cp0_status_pause_get(void) +{ + return s_status_pause; +} diff --git a/ext_components/cp0_lvgl/src/sdl/sdl_lvgl_settings.cpp b/ext_components/cp0_lvgl/src/sdl/sdl_lvgl_settings.cpp index c94c7726..16399f37 100644 --- a/ext_components/cp0_lvgl/src/sdl/sdl_lvgl_settings.cpp +++ b/ext_components/cp0_lvgl/src/sdl/sdl_lvgl_settings.cpp @@ -202,3 +202,31 @@ extern "C" void cp0_time_str(char *buffer, int buffer_size) { SettingsSystem::api_time_str(buffer, buffer_size); } + +/* The simulator has no status LED, cpufreq or framebuffer blanking; the + * screen-off power staging degrades to no-ops on this backend. */ +extern "C" int cp0_status_led_suspend(void) +{ + return 0; +} + +extern "C" void cp0_status_led_restore(void) +{ +} + +extern "C" int cp0_cpufreq_powersave_set(int enable) +{ + (void)enable; + return 0; +} + +extern "C" int cp0_cpufreq_wake_reset(void) +{ + return 0; +} + +extern "C" int cp0_panel_fb_blank(int blank) +{ + (void)blank; + return 0; +} diff --git a/ext_components/cp0_lvgl/src/ui_app_page.cpp b/ext_components/cp0_lvgl/src/ui_app_page.cpp index 02a34b91..95a71ac8 100644 --- a/ext_components/cp0_lvgl/src/ui_app_page.cpp +++ b/ext_components/cp0_lvgl/src/ui_app_page.cpp @@ -10,6 +10,7 @@ #include "cp0_pointer_lifecycle.hpp" #include "cp0_status_lifecycle.hpp" #include "cp0_status_component_contract.hpp" +#include "cp0_status_pause.h" namespace { @@ -1021,6 +1022,7 @@ AppTopBarComponent *AppTopBarRegion::component(const std::string &id) const void AppTopBarRegion::battery_event_cb(lv_event_t *event) { + if (cp0_status_pause_get()) return; // screen off: nothing on the panel is visible auto *self = static_cast(lv_event_get_user_data(event)); auto *battery = static_cast(lv_event_get_param(event)); if (!battery) return; @@ -1030,6 +1032,7 @@ void AppTopBarRegion::battery_event_cb(lv_event_t *event) void AppTopBarRegion::time_timer_cb(lv_timer_t *timer) { + if (cp0_status_pause_get()) return; // screen off: skip the per-second redraw auto *self = static_cast(lv_timer_get_user_data(timer)); cp0::callback::invoke_if_present( self, [](AppTopBarRegion ®ion) { region.update_time(); }); @@ -1037,6 +1040,7 @@ void AppTopBarRegion::time_timer_cb(lv_timer_t *timer) void AppTopBarRegion::status_timer_cb(lv_timer_t *timer) { + if (cp0_status_pause_get()) return; // screen off: the network worker pauses too auto *self = static_cast(lv_timer_get_user_data(timer)); cp0::callback::invoke_if_present( self, [](AppTopBarRegion ®ion) { region.update_status(); }); diff --git a/projects/APPLaunch/main/src/main.cpp b/projects/APPLaunch/main/src/main.cpp index 80f4fe6b..e45c4d97 100644 --- a/projects/APPLaunch/main/src/main.cpp +++ b/projects/APPLaunch/main/src/main.cpp @@ -31,6 +31,13 @@ int main(void) else SLOGE("[BOOT] failed to set m5ioe1 line 9 low: %s", data.c_str()); }); + /* Defensive wake reset: a previous process may have died while the + * screen-off deep stage had blanked the panel or pinned the CPU + * governor. Both calls are no-ops after a normal boot. */ + if (cp0_panel_fb_blank(0) == 0) + SLOGI("[BOOT] panel unblanked (defensive wake reset)"); + if (cp0_cpufreq_wake_reset() > 0) + SLOGI("[BOOT] cleared a stale cpufreq powersave pin"); if (launcher_media_controls::restore_startup_backlight()) SLOGI("[BOOT] restored working backlight brightness"); else diff --git a/projects/APPLaunch/main/ui/animation/launcher_carousel_layout.h b/projects/APPLaunch/main/ui/animation/launcher_carousel_layout.h deleted file mode 100644 index 0c57c118..00000000 --- a/projects/APPLaunch/main/ui/animation/launcher_carousel_layout.h +++ /dev/null @@ -1,46 +0,0 @@ -/* - * SPDX-FileCopyrightText: 2026 M5Stack Technology CO LTD - * - * SPDX-License-Identifier: MIT - */ - -#pragma once - -#include "lvgl/lvgl.h" - -#include -#include - -namespace launcher_carousel_layout { - -struct Slot -{ - lv_coord_t x; - lv_coord_t y; - lv_coord_t width; - lv_coord_t height; - bool hidden; -}; - -inline constexpr size_t kPanelCount = 5; -inline constexpr size_t kTitleOffset = kPanelCount; -inline constexpr size_t kElementCount = kPanelCount * 2; -inline constexpr lv_coord_t kSideCardRadius = 17; -inline constexpr lv_coord_t kCenterCardRadius = 22; - -inline constexpr std::array kSlots = {{ - {-177, 4, 61, 61, true}, - {-99, -6, 80, 80, false}, - {0, -16, 100, 100, false}, - {99, -6, 80, 80, false}, - {177, 4, 61, 61, true}, - {-177, 50, 0, 0, true}, - {-99, 50, 0, 0, false}, - {0, 50, 0, 0, false}, - {99, 50, 0, 0, false}, - {177, 50, 0, 0, true}, -}}; - -static_assert(kTitleOffset + kPanelCount == kElementCount); - -} // namespace launcher_carousel_layout diff --git a/projects/APPLaunch/main/ui/animation/launcher_grid_layout.h b/projects/APPLaunch/main/ui/animation/launcher_grid_layout.h new file mode 100644 index 00000000..2ba28df4 --- /dev/null +++ b/projects/APPLaunch/main/ui/animation/launcher_grid_layout.h @@ -0,0 +1,57 @@ +/* + * SPDX-FileCopyrightText: 2026 M5Stack Technology CO LTD + * + * SPDX-License-Identifier: MIT + */ + +#pragma once + +#include "lvgl/lvgl.h" + +#include +#include + +namespace launcher_grid_layout { + +// 3x2 app grid, one page shows six apps. Cells keep the carousel's +// center-offset convention: coordinates are offsets from the container +// centre (the container is a 320x150 object aligned CENTER). +inline constexpr size_t kCols = 3; +inline constexpr size_t kRows = 2; +inline constexpr size_t kCells = kCols * kRows; + +// Square cards: the icon artwork is square, so cards stay square and the +// title lives under the card inside the same cell. +inline constexpr lv_coord_t kCardSize = 58; +inline constexpr lv_coord_t kCardRadius = 14; +inline constexpr lv_coord_t kTitleWidth = 96; + +// Selection affordance: the theme accent (same yellow as the page slider +// knob) borders and backlights the selected tile; every card keeps full +// icon brightness, the yellow tile alone marks the selection. +inline constexpr uint32_t kSelectedBorderColor = 0xF2C94C; +inline constexpr uint32_t kSelectedBgColor = 0xF2C94C; +inline constexpr lv_opa_t kSelectedBgOpa = 50; // ~20% tint + +struct Cell +{ + lv_coord_t card_x; + lv_coord_t card_y; + lv_coord_t title_x; + lv_coord_t title_y; +}; + +inline constexpr std::array kCellLayout = {{ + // row 0: cards y -44 (spans -73..-15), titles y -8 + {-107, -44, -107, -8}, + { 0, -44, 0, -8}, + { 107, -44, 107, -8}, + // row 1: cards y 32 (spans 3..61), titles y 67 + {-107, 32, -107, 67}, + { 0, 32, 0, 67}, + { 107, 32, 107, 67}, +}}; + +static_assert(kCellLayout.size() == kCells); + +} // namespace launcher_grid_layout diff --git a/projects/APPLaunch/main/ui/animation/ui_launcher_animation.cpp b/projects/APPLaunch/main/ui/animation/ui_launcher_animation.cpp index 95b515e8..b19d4b45 100644 --- a/projects/APPLaunch/main/ui/animation/ui_launcher_animation.cpp +++ b/projects/APPLaunch/main/ui/animation/ui_launcher_animation.cpp @@ -7,7 +7,6 @@ #include "ui_launcher_animation.h" #include "animation.hpp" -#include "launcher_carousel_layout.h" #include "lvgl/src/misc/lv_text_private.h" #include @@ -19,192 +18,59 @@ namespace { constexpr int kLauncherAnimationTimeMs = 200; -struct LauncherHomeAnimContext { - lv_obj_t *items[launcher_carousel_layout::kElementCount]; - bool to_right; +struct LauncherPageSlideContext { + lv_obj_t *container = nullptr; + bool forward = true; launcher_home_animation::ReadyCallback ready_cb; launcher_home_animation::AliveCallback alive_cb; }; -lv_coord_t radius_for_slot(const launcher_carousel_layout::Slot &slot) -{ - return slot.width == 100 ? launcher_carousel_layout::kCenterCardRadius : - launcher_carousel_layout::kSideCardRadius; -} - -void sync_panel_radius(lv_obj_t *panel, lv_coord_t radius) -{ - if (!panel) return; - const auto selector = LV_PART_MAIN | LV_STATE_DEFAULT; - lv_obj_set_style_radius(panel, radius, selector); - if (lv_obj_t *clip = lv_obj_get_child(panel, 0)) { - const lv_coord_t border = lv_obj_get_style_border_width(panel, LV_PART_MAIN); - lv_obj_set_style_radius( - clip, std::max(0, radius - border), selector); - } -} - -void compensate_image_scale(lv_obj_t *panel) -{ - if (!panel) return; - lv_obj_t *clip = lv_obj_get_child(panel, 0); - lv_obj_t *image = clip ? lv_obj_get_child(clip, 0) : nullptr; - if (!image || !lv_obj_check_type(image, &lv_image_class)) return; - - // Percentage-sized children are resolved during layout. Make sure the - // scale is computed from the current animation frame's content size. - lv_obj_update_layout(panel); - const int32_t source_width = lv_image_get_src_width(image); - const int32_t source_height = lv_image_get_src_height(image); - const int32_t target_width = lv_obj_get_width(image); - const int32_t target_height = lv_obj_get_height(image); - if (source_width <= 1 || source_height <= 1 || target_width <= 1 || target_height <= 1) - return; - - constexpr uint32_t scale_unit = LV_SCALE_NONE; - const uint32_t scale_x = static_cast( - (static_cast(target_width - 1) * scale_unit + source_width - 2) / - (source_width - 1)); - const uint32_t scale_y = static_cast( - (static_cast(target_height - 1) * scale_unit + source_height - 2) / - (source_height - 1)); - lv_image_set_pivot(image, source_width / 2, source_height / 2); - lv_image_set_scale_x(image, scale_x); - lv_image_set_scale_y(image, scale_y); -} - -void apply_panel_slot(lv_obj_t *obj, const launcher_carousel_layout::Slot &slot) -{ - if (!obj) { - return; - } - - lv_obj_set_x(obj, slot.x); - lv_obj_set_y(obj, slot.y); - lv_obj_set_width(obj, slot.width); - lv_obj_set_height(obj, slot.height); - compensate_image_scale(obj); -} +// The container is a 320-wide object aligned CENTER, so x is an offset from +// the centred position; sliding it slides every grid cell with it. +constexpr lv_coord_t kPageSlideStartX = 340; -void apply_label_slot(lv_obj_t *obj, const launcher_carousel_layout::Slot &slot) +void page_slide_tick(LauncherPageSlideContext *ctx, LvglAnimation *anim) { - if (!obj) { - return; - } - - lv_obj_set_x(obj, slot.x); - lv_obj_set_y(obj, slot.y); + if (ctx->alive_cb && !ctx->alive_cb()) return; + const lv_coord_t start_x = ctx->forward ? kPageSlideStartX : -kPageSlideStartX; + lv_obj_set_x(ctx->container, anim->Animation_map(start_x, 0)); } -void animate_panel(lv_obj_t *obj, const launcher_carousel_layout::Slot &from, - const launcher_carousel_layout::Slot &to, LvglAnimation *anim) +void page_slide_finish(const std::shared_ptr &ctx) { - if (!obj) { - return; - } - - lv_obj_set_x(obj, anim->Animation_map(from.x, to.x)); - lv_obj_set_y(obj, anim->Animation_map(from.y, to.y)); - lv_obj_set_width(obj, anim->Animation_map(from.width, to.width)); - lv_obj_set_height(obj, anim->Animation_map(from.height, to.height)); - sync_panel_radius(obj, anim->Animation_map(radius_for_slot(from), radius_for_slot(to))); - compensate_image_scale(obj); + if (ctx->alive_cb && !ctx->alive_cb()) return; + lv_obj_set_x(ctx->container, 0); + if (ctx->ready_cb) ctx->ready_cb(); } -void animate_label(lv_obj_t *obj, const launcher_carousel_layout::Slot &from, - const launcher_carousel_layout::Slot &to, LvglAnimation *anim) -{ - if (!obj) { - return; - } +} // namespace - lv_obj_set_x(obj, anim->Animation_map(from.x, to.x)); - lv_obj_set_y(obj, anim->Animation_map(from.y, to.y)); -} +namespace launcher_home_animation { -void animate_home(LauncherHomeAnimContext *ctx, LvglAnimation *anim) +void animate_page_slide(lv_obj_t *container, bool forward, + ReadyCallback ready_cb, AliveCallback alive_cb) { - if (ctx->alive_cb && !ctx->alive_cb()) + if (!container) { + if (ready_cb) ready_cb(); return; - constexpr size_t title_offset = launcher_carousel_layout::kTitleOffset; - const auto &slots = launcher_carousel_layout::kSlots; - if (ctx->to_right) { - for (size_t i = 0; i + 1 < launcher_carousel_layout::kPanelCount; ++i) { - animate_panel(ctx->items[i], slots[i], slots[i + 1], anim); - animate_label(ctx->items[i + title_offset], slots[i + title_offset], - slots[i + title_offset + 1], anim); - } - } else { - for (size_t i = 1; i < launcher_carousel_layout::kPanelCount; ++i) { - animate_panel(ctx->items[i], slots[i], slots[i - 1], anim); - animate_label(ctx->items[i + title_offset], slots[i + title_offset], - slots[i + title_offset - 1], anim); - } - } -} - -void finish_home(const std::shared_ptr &ctx) -{ - if (ctx->alive_cb && !ctx->alive_cb()) return; - constexpr size_t title_offset = launcher_carousel_layout::kTitleOffset; - const auto &slots = launcher_carousel_layout::kSlots; - if (ctx->to_right) { - for (size_t i = 0; i + 1 < launcher_carousel_layout::kPanelCount; ++i) { - apply_panel_slot(ctx->items[i], slots[i + 1]); - apply_label_slot(ctx->items[i + title_offset], slots[i + title_offset + 1]); - } - } else { - for (size_t i = 1; i < launcher_carousel_layout::kPanelCount; ++i) { - apply_panel_slot(ctx->items[i], slots[i - 1]); - apply_label_slot(ctx->items[i + title_offset], slots[i + title_offset - 1]); - } - } - - if (ctx->ready_cb) { - ctx->ready_cb(); - } - -} - -void launcher_home_animate(lv_obj_t **items, bool to_right, - launcher_home_animation::ReadyCallback ready_cb, - launcher_home_animation::AliveCallback alive_cb) -{ - auto ctx = std::make_shared(); - ctx->to_right = to_right; - ctx->ready_cb = ready_cb; - ctx->alive_cb = alive_cb; - - for (size_t i = 0; i < launcher_carousel_layout::kElementCount; ++i) { - ctx->items[i] = items[i]; } - + auto ctx = std::make_shared(); + ctx->container = container; + ctx->forward = forward; + ctx->ready_cb = std::move(ready_cb); + ctx->alive_cb = std::move(alive_cb); + + const lv_coord_t start_x = forward ? kPageSlideStartX : -kPageSlideStartX; + lv_obj_set_x(container, start_x); if (!LvglAnimation::start_raw( - kLauncherAnimationTimeMs, - [ctx](LvglAnimation *anim) { - animate_home(ctx.get(), anim); - }, - [ctx](LvglAnimation *) { - finish_home(ctx); - })) { - finish_home(ctx); + kLauncherAnimationTimeMs, + [ctx](LvglAnimation *anim) { page_slide_tick(ctx.get(), anim); }, + [ctx](LvglAnimation *) { page_slide_finish(ctx); })) { + lv_obj_set_x(container, 0); + if (ctx->ready_cb) ctx->ready_cb(); } } -} // namespace - -namespace launcher_home_animation { - -void animate_right(lv_obj_t **items, ReadyCallback ready_cb, AliveCallback alive_cb) -{ - launcher_home_animate(items, true, std::move(ready_cb), std::move(alive_cb)); -} - -void animate_left(lv_obj_t **items, ReadyCallback ready_cb, AliveCallback alive_cb) -{ - launcher_home_animate(items, false, std::move(ready_cb), std::move(alive_cb)); -} - namespace { // Hold at each end before LONG_SCROLL moves left, then back right. diff --git a/projects/APPLaunch/main/ui/animation/ui_launcher_animation.h b/projects/APPLaunch/main/ui/animation/ui_launcher_animation.h index 3ad521cb..0bfe0004 100644 --- a/projects/APPLaunch/main/ui/animation/ui_launcher_animation.h +++ b/projects/APPLaunch/main/ui/animation/ui_launcher_animation.h @@ -15,8 +15,11 @@ namespace launcher_home_animation { using ReadyCallback = std::function; using AliveCallback = std::function; -void animate_right(lv_obj_t **items, ReadyCallback ready_cb, AliveCallback alive_cb); -void animate_left(lv_obj_t **items, ReadyCallback ready_cb, AliveCallback alive_cb); +// Slide the whole grid container in from the left/right edge (a page flip). +// forward=true enters from the right edge, false from the left. The +// container must be alive for the whole animation; alive_cb guards that. +void animate_page_slide(lv_obj_t *container, bool forward, + ReadyCallback ready_cb, AliveCallback alive_cb); // Selected titles bounce (pause, left, pause, right). Others end in "...". void set_title_text(lv_obj_t *label, const char *text); diff --git a/projects/APPLaunch/main/ui/launch.cpp b/projects/APPLaunch/main/ui/launch.cpp index c12ca06d..f4a329e5 100644 --- a/projects/APPLaunch/main/ui/launch.cpp +++ b/projects/APPLaunch/main/ui/launch.cpp @@ -25,11 +25,6 @@ #include #include -namespace { -constexpr size_t kHomeCarouselSlotCount = 5; -constexpr int kHomeCarouselCenterSlot = 2; -} - // ============================================================ // Launch // ============================================================ @@ -181,18 +176,12 @@ void Launch::launch_Exec(const std::string &exec, bool keep_root) ui_screensaver_set_foreground(1); } -void Launch::select_next_app() +void Launch::select_app_relative(int delta) { - int next = normalized_app_index(current_app + 1); + int next = normalized_app_index(current_app + delta); if (next >= 0) current_app = next; } -void Launch::select_previous_app() -{ - int previous = normalized_app_index(current_app - 1); - if (previous >= 0) current_app = previous; -} - std::size_t Launch::app_count() const { return app_list.size(); @@ -204,13 +193,6 @@ std::size_t Launch::current_app_index() const return normalized < 0 ? 0 : static_cast(normalized); } -const app *Launch::carousel_slot_app(size_t slot) const -{ - if (slot >= kHomeCarouselSlotCount) - return nullptr; - return app_at_index(current_app + static_cast(slot) - kHomeCarouselCenterSlot); -} - void Launch::applications_load() { launcher_append_desktop_apps(app_list); @@ -222,7 +204,7 @@ void Launch::refresh_home_carousel() int normalized = normalized_app_index(current_app); if (normalized < 0) return; current_app = normalized; - if (auto page = launch_page_.lock()) page->refresh_carousel(); + if (auto page = launch_page_.lock()) page->refresh_grid(); } void Launch::reload_home_icons() diff --git a/projects/APPLaunch/main/ui/launch.h b/projects/APPLaunch/main/ui/launch.h index 1b7509b3..57c1c0e3 100644 --- a/projects/APPLaunch/main/ui/launch.h +++ b/projects/APPLaunch/main/ui/launch.h @@ -63,11 +63,11 @@ class Launch void bind_ui(); void set_launch_page(std::shared_ptr launch_page); - void select_next_app(); - void select_previous_app(); + void select_app_relative(int delta); std::size_t app_count() const; std::size_t current_app_index() const; - const app *carousel_slot_app(size_t slot) const; + /* Absolute lookup into the (wrapped) app list; drives the home grid. */ + const app *app_at_index(int index) const; void launch_app(); private: @@ -85,14 +85,13 @@ class Launch void applications_reload(); void rebuild_builtin_apps(); int normalized_app_index(int index) const; - const app *app_at_index(int index) const; static void lv_go_back_home(void *arg) noexcept; static void esc_force_home_cb(void *user_data) noexcept; static void app_registry_changed_cb(void *user_data) noexcept; std::weak_ptr launch_page_; - int current_app = 2; + int current_app = 0; AppDirectoryWatcher app_directory_watcher_; EscUiWatchdog esc_ui_watchdog_; LauncherPageLifecycleModel page_lifecycle_; diff --git a/projects/APPLaunch/main/ui/model/launcher_grid_model.hpp b/projects/APPLaunch/main/ui/model/launcher_grid_model.hpp new file mode 100644 index 00000000..78c8bf34 --- /dev/null +++ b/projects/APPLaunch/main/ui/model/launcher_grid_model.hpp @@ -0,0 +1,146 @@ +/* + * SPDX-FileCopyrightText: 2026 M5Stack Technology CO LTD + * + * SPDX-License-Identifier: MIT + */ + +#pragma once + +#include + +// Selection model for the 3x2 home grid. The selected app is one absolute +// index into the app list; pages never show wrapped filler, so a ragged +// last page simply leaves its trailing cells empty and every move targets a +// real app. +class LauncherGridModel +{ +public: + static constexpr size_t kCols = 3; + static constexpr size_t kRows = 2; + static constexpr size_t kCellsPerPage = kCols * kRows; + + void set_app_count(size_t count) + { + if (app_count_ == count) return; + app_count_ = count; + if (app_count_ == 0) { + index_ = 0; + return; + } + if (index_ >= app_count_) index_ = app_count_ - 1; + } + + size_t index() const { return index_; } + + void set_index(size_t index) + { + if (app_count_ == 0) return; + index_ = index % app_count_; + } + + size_t page() const { return app_count_ == 0 ? 0 : index_ / kCellsPerPage; } + + size_t page_count() const + { + return app_count_ == 0 ? 0 : (app_count_ + kCellsPerPage - 1) / kCellsPerPage; + } + + // Each move returns true when the selection changed. After a move, + // crossed_page() reports whether the new selection sits on another grid + // page (the caller plays the page-flip animation) and moved_forward() + // reports the travel direction for the slide. + // + // Left/right stay inside the current row: stepping past the row edge + // flips to the neighbouring page at the same row, clamped to a real app + // when that page is ragged; walking right past the very last app wraps + // to the first page's first cell. Up/down swap rows and wrap through + // the page boundary. + bool move_row_right() { return move_row(1); } + bool move_row_left() { return move_row(-1); } + bool move_up() { return step(-static_cast(kCols)); } + bool move_down() { return step(static_cast(kCols)); } + + // Direct page flip (I/O keys): keep the cursor's cell position on the + // neighbouring page; a ragged neighbour clamps to its last real app. + bool flip_page(int dir) + { + crossed_page_ = false; + moved_forward_ = false; + const size_t pages = page_count(); + if (app_count_ == 0 || pages == 1) return false; + const size_t page = index_ / kCellsPerPage; + const size_t cell = index_ % kCellsPerPage; + const size_t neighbour = dir > 0 ? (page + 1) % pages + : (page + pages - 1) % pages; + size_t target = neighbour * kCellsPerPage + cell; + if (target >= app_count_) target = app_count_ - 1; + if (target == index_) return false; + index_ = target; + crossed_page_ = index_ / kCellsPerPage != page; + moved_forward_ = dir > 0; + return true; + } + + bool crossed_page() const { return crossed_page_; } + bool moved_forward() const { return moved_forward_; } + +private: + bool step(int delta) + { + crossed_page_ = false; + moved_forward_ = false; + if (app_count_ == 0) return false; + const size_t previous = index_; + const int raw = static_cast(index_) + delta; + int wrapped = raw % static_cast(app_count_); + if (wrapped < 0) wrapped += static_cast(app_count_); + index_ = static_cast(wrapped); + if (index_ == previous) return false; + crossed_page_ = index_ / kCellsPerPage != previous / kCellsPerPage; + moved_forward_ = delta > 0; + return true; + } + + // dir 1 = right, -1 = left. Within the row this is a plain +-1 (right + // past the very last app wraps to the front); at the row edge the target + // jumps to the neighbouring page's same-row far cell, clamped to a real + // app when that page is ragged. + bool move_row(int dir) + { + crossed_page_ = false; + moved_forward_ = false; + if (app_count_ == 0) return false; + const size_t page = index_ / kCellsPerPage; + const size_t cell = index_ % kCellsPerPage; + const size_t row = cell / kCols; + const size_t col = cell % kCols; + const size_t pages = page_count(); + size_t target; + if (dir > 0 && col + 1 < kCols) { + target = index_ + 1; + if (target >= app_count_) target = 0; // wrap past the last app + } else if (dir < 0 && col > 0) { + target = index_ - 1; // always real: empty cells sit at the end + } else { + const size_t neighbour = dir > 0 ? (page + 1) % pages + : (page + pages - 1) % pages; + target = neighbour * kCellsPerPage + row * kCols + + (dir > 0 ? 0 : kCols - 1); + if (target >= app_count_) + target = app_count_ - 1; // ragged neighbour: nearest real app + } + if (target == index_) return false; + index_ = target; + // Crossing is a page-number change, nothing else: on a single-page + // list the row-edge wrap stays on the same page and animates as a + // plain highlight move. + crossed_page_ = index_ / kCellsPerPage != page; + moved_forward_ = dir > 0; + return true; + } + + size_t app_count_ = 0; + size_t index_ = 0; + bool crossed_page_ = false; + bool moved_forward_ = false; +}; diff --git a/projects/APPLaunch/main/ui/ui.h b/projects/APPLaunch/main/ui/ui.h index 413d45df..b95a6ed9 100644 --- a/projects/APPLaunch/main/ui/ui.h +++ b/projects/APPLaunch/main/ui/ui.h @@ -83,7 +83,7 @@ inline const cp0_battery_info_t *battery_info(lv_event_t *event) void init(); void deinit(); -const lv_font_t *carousel_title_font(); +const lv_font_t *grid_title_font(); } inline Cp0FontService &launcher_fonts() { return cp0_fonts(); } diff --git a/projects/APPLaunch/main/ui/ui_launch_page.cpp b/projects/APPLaunch/main/ui/ui_launch_page.cpp index f5f60364..00364b01 100644 --- a/projects/APPLaunch/main/ui/ui_launch_page.cpp +++ b/projects/APPLaunch/main/ui/ui_launch_page.cpp @@ -8,94 +8,56 @@ #include "launch.h" +#include "animation/launcher_grid_layout.h" #include "animation/ui_launcher_animation.h" -#include "animation/launcher_carousel_layout.h" +#include "ui.h" #include -void UILaunchPage::rotate_carousel_left(size_t start, size_t end) +void UILaunchPage::move_grid_next() { - auto &items = carousel_elements_; - std::rotate(items.begin() + start, items.begin() + start + 1, items.begin() + end + 1); + if (!begin_grid_move()) return; + if (grid_.move_row_right()) finish_grid_move(); } -void UILaunchPage::rotate_carousel_right(size_t start, size_t end) +void UILaunchPage::move_grid_previous() { - auto &items = carousel_elements_; - std::rotate(items.begin() + start, items.begin() + end, items.begin() + end + 1); + if (!begin_grid_move()) return; + if (grid_.move_row_left()) finish_grid_move(); } -namespace { - -UILaunchPage *active_launch_page = nullptr; -lv_group_t *home_input_group = nullptr; -using launcher_carousel_layout::Slot; -using launcher_carousel_layout::kSlots; -static_assert(UILaunchPage::kPageSlider == launcher_carousel_layout::kElementCount); -static_assert(UILaunchPage::kLauncherCarouselElementCount == - launcher_carousel_layout::kElementCount + 1); - - -// ============================================================ -// Force the panel to the specified slot -// ============================================================ - -static void snap_panel_to_slot(lv_obj_t *panel, int slot) +void UILaunchPage::move_grid_down() { - const Slot &layout = kSlots[slot]; - lv_obj_set_x(panel, layout.x); - lv_obj_set_y(panel, layout.y); - lv_obj_set_width(panel, layout.width); - lv_obj_set_height(panel, layout.height); - - const lv_coord_t radius = slot == UILaunchPage::kCardCenter ? - launcher_carousel_layout::kCenterCardRadius : - launcher_carousel_layout::kSideCardRadius; - const auto selector = LV_PART_MAIN | LV_STATE_DEFAULT; - lv_obj_set_style_radius(panel, radius, selector); - if (lv_obj_t *clip = lv_obj_get_child(panel, 0)) { - const lv_coord_t border = lv_obj_get_style_border_width(panel, LV_PART_MAIN); - lv_obj_set_style_radius( - clip, std::max(0, radius - border), selector); - } - - if (layout.hidden) - { - lv_obj_add_flag(panel, LV_OBJ_FLAG_HIDDEN); - } - else - { - lv_obj_clear_flag(panel, LV_OBJ_FLAG_HIDDEN); - } + if (!begin_grid_move()) return; + if (grid_.move_down()) finish_grid_move(); } +void UILaunchPage::move_grid_up() +{ + if (!begin_grid_move()) return; + if (grid_.move_up()) finish_grid_move(); +} -// ============================================================ -// Force the label to the specified slot -// ============================================================ +void UILaunchPage::move_grid_page_next() +{ + if (!begin_grid_move()) return; + if (grid_.flip_page(1)) finish_grid_move(); +} -static void snap_label_to_slot(lv_obj_t *label, int slot, bool selected = false) +void UILaunchPage::move_grid_page_previous() { - const Slot &layout = kSlots[slot]; - lv_obj_set_x(label, layout.x); - lv_obj_set_y(label, layout.y); - - // Constrain label width to the matching card width so long names never overflow. - // Label slots are 5..9; corresponding card slots are 0..4. - const int card_w = kSlots[slot - launcher_carousel_layout::kTitleOffset].width; - lv_obj_set_width(label, card_w > 0 ? card_w : LV_SIZE_CONTENT); - launcher_home_animation::apply_title_overflow(label, selected); - - if (layout.hidden) - { - lv_obj_add_flag(label, LV_OBJ_FLAG_HIDDEN); - } - else - { - lv_obj_clear_flag(label, LV_OBJ_FLAG_HIDDEN); - } + if (!begin_grid_move()) return; + if (grid_.flip_page(-1)) finish_grid_move(); } +namespace { + +UILaunchPage *active_launch_page = nullptr; +lv_group_t *home_input_group = nullptr; +// Grid cells never move: the layout is static, and page flips slide the whole +// container instead of repositioning individual cells. +static_assert(UILaunchPage::kLauncherGridElementCount == + launcher_grid_layout::kCells * 2); } // namespace @@ -107,14 +69,14 @@ lv_group_t *UILaunchPage::home_input_group() return ::home_input_group; } -lv_obj_t *UILaunchPage::panel(size_t slot) +lv_obj_t *UILaunchPage::panel(size_t cell) { - return carousel_elements_[kCardFarLeft + slot]; + return grid_elements_[cell]; } -lv_obj_t *UILaunchPage::label(size_t slot) +lv_obj_t *UILaunchPage::label(size_t cell) { - return carousel_elements_[kTitleFarLeft + slot]; + return grid_elements_[kTitleOffset + cell]; } void UILaunchPage::bind_home_input_group() @@ -143,27 +105,18 @@ UILaunchPage::UILaunchPage(Launch *launch) UILaunchPage::~UILaunchPage() { startup_sound_state_->alive.store(false); - *carousel_alive_ = false; - navigation_.cancel_navigation(); - if (carousel_container_) { + *grid_alive_ = false; + if (grid_container_) { lv_obj_remove_event_cb_with_user_data( - carousel_container_, UILaunchPage::on_owned_obj_deleted, this); - for (lv_obj_t *element : carousel_elements_) { + grid_container_, UILaunchPage::on_owned_obj_deleted, this); + for (lv_obj_t *element : grid_elements_) { if (element) lv_obj_remove_event_cb_with_user_data( element, UILaunchPage::on_owned_obj_deleted, this); } - if (left_arrow_button_) - lv_obj_remove_event_cb_with_user_data( - left_arrow_button_, UILaunchPage::on_owned_obj_deleted, this); - if (right_arrow_button_) - lv_obj_remove_event_cb_with_user_data( - right_arrow_button_, UILaunchPage::on_owned_obj_deleted, this); - lv_obj_delete(carousel_container_); - carousel_container_ = nullptr; - carousel_elements_.fill(nullptr); - left_arrow_button_ = nullptr; - right_arrow_button_ = nullptr; + lv_obj_delete(grid_container_); + grid_container_ = nullptr; + grid_elements_.fill(nullptr); } if (home_key_registered_ && root_screen_) { lv_obj_remove_event_cb_with_user_data( @@ -231,13 +184,10 @@ void UILaunchPage::on_root_deleted(lv_event_t *event) noexcept self->stop_startup_delay(); self->stop_startup_sound_timer(); self->startup_sound_state_->alive.store(false); - *self->carousel_alive_ = false; - self->carousel_elements_.fill(nullptr); - self->carousel_container_ = nullptr; - self->left_arrow_button_ = nullptr; - self->right_arrow_button_ = nullptr; + *self->grid_alive_ = false; + self->grid_elements_.fill(nullptr); + self->grid_container_ = nullptr; self->home_key_registered_ = false; - self->navigation_.cancel_navigation(); } catch (...) { } } @@ -252,25 +202,20 @@ void UILaunchPage::on_owned_obj_deleted(lv_event_t *event) noexcept self->startup_gif_ == target, self->startup_gif_done_); if (self->startup_logo_scr_ == target) self->startup_logo_scr_ = nullptr; if (self->startup_gif_ == target) self->startup_gif_ = nullptr; - bool carousel_object_deleted = self->carousel_container_ == target || - self->left_arrow_button_ == target || self->right_arrow_button_ == target; - for (lv_obj_t *&element : self->carousel_elements_) { + bool grid_object_deleted = self->grid_container_ == target; + for (lv_obj_t *&element : self->grid_elements_) { if (element == target) { element = nullptr; - carousel_object_deleted = true; + grid_object_deleted = true; } } - if (self->left_arrow_button_ == target) self->left_arrow_button_ = nullptr; - if (self->right_arrow_button_ == target) self->right_arrow_button_ = nullptr; - if (self->carousel_container_ == target) { - self->carousel_container_ = nullptr; - self->carousel_elements_.fill(nullptr); - self->left_arrow_button_ = nullptr; - self->right_arrow_button_ = nullptr; + if (self->grid_container_ == target) { + self->grid_container_ = nullptr; + self->grid_elements_.fill(nullptr); } - if (carousel_object_deleted) { - *self->carousel_alive_ = false; - self->cancel_switch_animation(); + if (grid_object_deleted) { + *self->grid_alive_ = false; + self->cancel_page_flip_animation(); } if (recover_gif) { self->startup_gif_done_ = true; @@ -280,40 +225,41 @@ void UILaunchPage::on_owned_obj_deleted(lv_event_t *event) noexcept } } -void UILaunchPage::fill_right_entering_slot(lv_obj_t *panel, lv_obj_t *label) +void UILaunchPage::refresh_grid() { if (!launch_) return; - launch_->select_next_app(); - if (const app *item = launch_->carousel_slot_app(kCardFarRight)) - update_carousel_item(panel, label, item->Name.c_str(), item->Icon); -} - -void UILaunchPage::fill_left_entering_slot(lv_obj_t *panel, lv_obj_t *label) -{ - if (!launch_) - return; - - launch_->select_previous_app(); - if (const app *item = launch_->carousel_slot_app(kCardFarLeft)) - update_carousel_item(panel, label, item->Name.c_str(), item->Icon); -} - -void UILaunchPage::refresh_carousel() -{ - if (!launch_) - return; - - set_page_slider_position(launch_->current_app_index()); - - for (size_t slot = 0; slot < launcher_carousel_layout::kPanelCount; ++slot) { - if (const app *item = launch_->carousel_slot_app(slot)) - update_carousel_slot(slot, item->Name.c_str(), item->Icon); - else - update_carousel_slot(slot, "", {}); + grid_.set_app_count(launch_->app_count()); + grid_.set_index(launch_->current_app_index()); + + /* Pages never show wrapped filler: cells past the end of the app list + * stay empty (hidden card + title) on a ragged last page. */ + const size_t page_base = grid_.page() * LauncherGridModel::kCellsPerPage; + for (size_t cell = 0; cell < launcher_grid_layout::kCells; ++cell) { + const bool real = page_base + cell < launch_->app_count(); + if (real) { + if (const app *item = launch_->app_at_index(static_cast(page_base + cell))) + update_grid_cell(cell, item->Name.c_str(), item->Icon); + else + update_grid_cell(cell, "", {}); + } else { + update_grid_cell(cell, "", {}); + } + if (panel(cell)) { + if (real) + lv_obj_clear_flag(panel(cell), LV_OBJ_FLAG_HIDDEN); + else + lv_obj_add_flag(panel(cell), LV_OBJ_FLAG_HIDDEN); + } + if (label(cell)) { + if (real) + lv_obj_clear_flag(label(cell), LV_OBJ_FLAG_HIDDEN); + else + lv_obj_add_flag(label(cell), LV_OBJ_FLAG_HIDDEN); + } } - launcher_home_animation::apply_title_overflow(label(kCardCenter), true); + apply_grid_highlight(); } void UILaunchPage::reload_home_icons(const std::vector &icon_paths) @@ -323,10 +269,9 @@ void UILaunchPage::reload_home_icons(const std::vector &icon_paths) home_icon_pool_.swap(replacement); // Keep the old pool alive until every image widget no longer references it. - for (size_t slot = 0; slot < launcher_carousel_layout::kPanelCount; ++slot) - set_panel_icon(panel(slot), {}); - set_page_slider_range(icon_paths.size(), launch_ ? launch_->current_app_index() : 0); - refresh_carousel(); + for (size_t cell = 0; cell < launcher_grid_layout::kCells; ++cell) + set_panel_icon(panel(cell), {}); + refresh_grid(); } void UILaunchPage::launch_selected_app() @@ -335,130 +280,110 @@ void UILaunchPage::launch_selected_app() launch_->launch_app(); } -void UILaunchPage::finish_switch_animation() +void UILaunchPage::select_grid_cell(size_t cell) { - if (std::any_of(carousel_elements_.begin(), carousel_elements_.begin() + - launcher_carousel_layout::kElementCount, - [](lv_obj_t *element) { return element == nullptr; })) { - cancel_switch_animation(); - return; - } - for (size_t i = 0; i < launcher_carousel_layout::kPanelCount; ++i) - { - snap_panel_to_slot(carousel_elements_[i], i); - } - - for (size_t i = launcher_carousel_layout::kTitleOffset; - i < launcher_carousel_layout::kElementCount; ++i) - { - snap_label_to_slot(carousel_elements_[i], static_cast(i), i == kTitleCenter); - } - - navigation_.finish_navigation(); - - for (size_t i = 0; i < launcher_carousel_layout::kPanelCount; ++i) { - uint32_t color = (i == kCardCenter) ? BORDER_COLOR_CENTER : BORDER_COLOR_SIDE; - lv_obj_set_style_border_color(carousel_elements_[i], lv_color_hex(color), LV_PART_MAIN | LV_STATE_DEFAULT); - } - - for (size_t i = launcher_carousel_layout::kTitleOffset; - i < launcher_carousel_layout::kElementCount; ++i) { - lv_obj_set_style_text_font(carousel_elements_[i], launcher_ui::carousel_title_font(), - LV_PART_MAIN | LV_STATE_DEFAULT); - } - + if (!launch_) return; + grid_.set_app_count(launch_->app_count()); + grid_.set_index(launch_->current_app_index()); + const size_t target = grid_.page() * LauncherGridModel::kCellsPerPage + cell; + grid_.set_index(target); + launch_->select_app_relative(static_cast(target) - + static_cast(launch_->current_app_index())); + apply_grid_highlight(); } -void UILaunchPage::cancel_switch_animation() +void UILaunchPage::apply_grid_highlight() { - if (!navigation_.cancel_navigation()) return; - if (launch_) { - if (active_navigation_moves_next_) - launch_->select_previous_app(); - else - launch_->select_next_app(); + const size_t page_base = grid_.page() * LauncherGridModel::kCellsPerPage; + for (size_t cell = 0; cell < launcher_grid_layout::kCells; ++cell) { + const bool selected = page_base + cell == grid_.index(); + lv_obj_t *card = grid_elements_[cell]; + if (card) { + const auto selector = LV_PART_MAIN | LV_STATE_DEFAULT; + const uint32_t border = selected ? launcher_grid_layout::kSelectedBorderColor + : BORDER_COLOR_SIDE; + lv_obj_set_style_border_color(card, lv_color_hex(border), selector); + lv_obj_set_style_bg_color( + card, lv_color_hex(launcher_grid_layout::kSelectedBgColor), selector); + lv_obj_set_style_bg_opa(card, selected ? launcher_grid_layout::kSelectedBgOpa + : LV_OPA_TRANSP, + selector); + } + if (label(cell)) + launcher_home_animation::apply_title_overflow(label(cell), selected); } - set_page_slider_position(launch_ ? launch_->current_app_index() : 0); } -void UILaunchPage::switch_right() +bool UILaunchPage::begin_grid_move() { - if (std::any_of(carousel_elements_.begin(), carousel_elements_.begin() + - launcher_carousel_layout::kElementCount, - [](lv_obj_t *element) { return element == nullptr; })) return; - if (!navigation_.begin_navigation(LauncherNavigationDirection::PREVIOUS)) - return; - active_navigation_moves_next_ = false; - - lv_obj_clear_flag(carousel_elements_[0], LV_OBJ_FLAG_HIDDEN); - - std::weak_ptr alive = carousel_alive_; - launcher_home_animation::animate_right( - carousel_elements_.data(), - [this, alive]() { - auto state = alive.lock(); - if (state && *state) finish_switch_animation(); - }, - [alive]() { - auto state = alive.lock(); - return state && *state; - }); - - snap_panel_to_slot(carousel_elements_[4], 0); - - lv_obj_clear_flag(carousel_elements_[5], LV_OBJ_FLAG_HIDDEN); - - snap_label_to_slot(carousel_elements_[9], 5); - - fill_left_entering_slot(carousel_elements_[4], carousel_elements_[9]); - - set_carousel_element_clickable(kCardCenter, false); - rotate_carousel_right(0, 4); - set_carousel_element_clickable(kCardCenter, true); - - rotate_carousel_right(5, 9); - launcher_home_animation::apply_title_overflow(label(kCardCenter), true); + if (page_flip_active_) return false; + if (!launch_) return false; + if (std::any_of(grid_elements_.begin(), grid_elements_.end(), + [](lv_obj_t *element) { return element == nullptr; })) + return false; + + grid_.set_app_count(launch_->app_count()); + grid_.set_index(launch_->current_app_index()); + return true; +} - set_page_slider_position(launch_ ? launch_->current_app_index() : 0); +void UILaunchPage::finish_grid_move() +{ + // The model already sits on the new index; sync Launch through a signed + // delta (select_app_relative wraps, so any magnitude works). + launch_->select_app_relative(static_cast(grid_.index()) - + static_cast(launch_->current_app_index())); + if (grid_.crossed_page()) + start_page_flip(grid_.moved_forward()); + else + apply_grid_highlight(); } -void UILaunchPage::switch_left() +void UILaunchPage::start_page_flip(bool forward) { - if (std::any_of(carousel_elements_.begin(), carousel_elements_.begin() + - launcher_carousel_layout::kElementCount, - [](lv_obj_t *element) { return element == nullptr; })) return; - if (!navigation_.begin_navigation(LauncherNavigationDirection::NEXT)) - return; - active_navigation_moves_next_ = true; + if (!grid_container_) return; + page_flip_active_ = true; + set_grid_clickable(false); - lv_obj_clear_flag(carousel_elements_[4], LV_OBJ_FLAG_HIDDEN); + refresh_grid(); - std::weak_ptr alive = carousel_alive_; - launcher_home_animation::animate_left( - carousel_elements_.data(), + std::weak_ptr alive = grid_alive_; + launcher_home_animation::animate_page_slide( + grid_container_, forward, [this, alive]() { auto state = alive.lock(); - if (state && *state) finish_switch_animation(); + if (state && *state) finish_page_flip_animation(); }, [alive]() { auto state = alive.lock(); return state && *state; }); +} - snap_panel_to_slot(carousel_elements_[0], 4); - - lv_obj_clear_flag(carousel_elements_[9], LV_OBJ_FLAG_HIDDEN); - - snap_label_to_slot(carousel_elements_[5], 9); - - fill_right_entering_slot(carousel_elements_[0], carousel_elements_[5]); - - set_carousel_element_clickable(kCardCenter, false); - rotate_carousel_left(0, 4); - set_carousel_element_clickable(kCardCenter, true); +void UILaunchPage::finish_page_flip_animation() +{ + if (grid_container_) + lv_obj_set_x(grid_container_, 0); + set_grid_clickable(true); + page_flip_active_ = false; + apply_grid_highlight(); +} - rotate_carousel_left(5, 9); - launcher_home_animation::apply_title_overflow(label(kCardCenter), true); +void UILaunchPage::cancel_page_flip_animation() +{ + if (!page_flip_active_) return; + page_flip_active_ = false; + if (grid_container_) + lv_obj_set_x(grid_container_, 0); +} - set_page_slider_position(launch_ ? launch_->current_app_index() : 0); +void UILaunchPage::set_grid_clickable(bool clickable) +{ + for (size_t cell = 0; cell < launcher_grid_layout::kCells; ++cell) { + if (!grid_elements_[cell]) continue; + if (clickable) + lv_obj_add_flag(grid_elements_[cell], LV_OBJ_FLAG_CLICKABLE); + else + lv_obj_clear_flag(grid_elements_[cell], LV_OBJ_FLAG_CLICKABLE); + } } diff --git a/projects/APPLaunch/main/ui/ui_launch_page.h b/projects/APPLaunch/main/ui/ui_launch_page.h index 0419e2f9..c03cd0a1 100644 --- a/projects/APPLaunch/main/ui/ui_launch_page.h +++ b/projects/APPLaunch/main/ui/ui_launch_page.h @@ -8,6 +8,7 @@ #include "home_icon_buffer_pool.hpp" #include "launcher_ui_app_page.hpp" +#include "model/launcher_grid_model.hpp" #include "model/launcher_navigation_model.hpp" #include "model/launcher_startup_contract.hpp" #include @@ -18,6 +19,10 @@ class Launch; +// Home screen: a 3x2 grid showing six apps per page. Arrow keys move the +// selection inside the grid (up/down swap rows); stepping past the last +// column flips to the next page with a slide animation, and the app list +// wraps around at both ends. class UILaunchPage : public home_base { public: @@ -28,36 +33,46 @@ class UILaunchPage : public home_base void load_home_screen(); void start_startup_gif(); void create_screen(); - enum LauncherCarouselElement : size_t { - kCardFarLeft = 0, - kCardLeft, - kCardCenter, - kCardRight, - kCardFarRight, - kTitleFarLeft, - kTitleLeft, - kTitleCenter, - kTitleRight, - kTitleFarRight, - kPageSlider, - kLauncherCarouselElementCount, + enum LauncherGridElement : size_t { + kCard0 = 0, + kCard1, + kCard2, + kCard3, + kCard4, + kCard5, + kTitleOffset, + kTitle0 = kTitleOffset, + kTitle1, + kTitle2, + kTitle3, + kTitle4, + kTitle5, + kLauncherGridElementCount, }; void init_input_group(); static void bind_home_input_group(); static lv_group_t *home_input_group(); - lv_obj_t *panel(size_t slot); - lv_obj_t *label(size_t slot); + lv_obj_t *panel(size_t cell); + lv_obj_t *label(size_t cell); - void refresh_carousel(); + void refresh_grid(); void reload_home_icons(const std::vector &icon_paths); - void update_carousel_slot(size_t slot, const char *title, const std::string &icon); - void update_carousel_item(lv_obj_t *panel, lv_obj_t *label, const char *title, - const std::string &icon); + void update_grid_cell(size_t cell, const char *title, const std::string &icon); + void update_grid_item(lv_obj_t *panel, lv_obj_t *label, const char *title, + const std::string &icon); void launch_selected_app(); + void move_grid_next(); + void move_grid_previous(); + void move_grid_up(); + void move_grid_down(); + void move_grid_page_next(); + void move_grid_page_previous(); + void select_grid_cell(size_t cell); + bool navigation_ready() const { return !page_flip_active_; } protected: - std::array carousel_elements_ = {}; + std::array grid_elements_ = {}; private: struct StartupTimerContext @@ -80,12 +95,12 @@ class UILaunchPage : public home_base }; void create_app_container(lv_obj_t *parent); - void switch_left(); - void switch_right(); - void fill_left_entering_slot(lv_obj_t *panel, lv_obj_t *label); - void fill_right_entering_slot(lv_obj_t *panel, lv_obj_t *label); - void finish_switch_animation(); - void cancel_switch_animation(); + bool begin_grid_move(); + void finish_grid_move(); + void start_page_flip(bool forward); + void finish_page_flip_animation(); + void cancel_page_flip_animation(); + void apply_grid_highlight(); void handle_home_key(lv_event_t *event); void handle_startup_gif_event(lv_event_t *event); void play_startup_sound_with_retry(); @@ -97,14 +112,8 @@ class UILaunchPage : public home_base void finish_startup_delay(); void release_startup_screen(lv_obj_t *&screen); - void rotate_carousel_left(size_t start, size_t end); - void rotate_carousel_right(size_t start, size_t end); - void set_page_slider_range(size_t page_count, size_t selected_page); - void set_page_slider_position(size_t page); - void set_carousel_element_clickable(size_t element, bool clickable); + void set_grid_clickable(bool clickable); void set_panel_icon(lv_obj_t *panel, const std::string &src); - static void on_left_arrow_clicked(lv_event_t *event) noexcept; - static void on_right_arrow_clicked(lv_event_t *event) noexcept; static void on_app_clicked(lv_event_t *event) noexcept; static void on_home_key(lv_event_t *event) noexcept; static void on_startup_gif_event(lv_event_t *event) noexcept; @@ -116,9 +125,7 @@ class UILaunchPage : public home_base Launch *launch_ = nullptr; lv_obj_t *startup_gif_ = nullptr; - lv_obj_t *left_arrow_button_ = nullptr; - lv_obj_t *right_arrow_button_ = nullptr; - lv_obj_t *carousel_container_ = nullptr; + lv_obj_t *grid_container_ = nullptr; lv_timer_t *startup_sound_timer_ = nullptr; lv_timer_t *startup_delay_timer_ = nullptr; StartupTimerContext *startup_sound_context_ = nullptr; @@ -128,14 +135,14 @@ class UILaunchPage : public home_base std::array startup_logo_path_ = {}; bool startup_gif_done_ = false; int startup_sound_retry_count_ = 0; - LauncherNavigationModel navigation_; + LauncherGridModel grid_; LauncherStartupDelayModel startup_delay_model_; LauncherStartupGeneration startup_sound_generation_; LauncherStartupGeneration startup_delay_generation_; HomeIconBufferPool home_icon_pool_; std::shared_ptr startup_sound_state_ = std::make_shared(); - std::shared_ptr carousel_alive_ = std::make_shared(true); + std::shared_ptr grid_alive_ = std::make_shared(true); bool home_key_registered_ = false; - bool active_navigation_moves_next_ = false; + bool page_flip_active_ = false; }; diff --git a/projects/APPLaunch/main/ui/ui_launch_page_carousel_view.cpp b/projects/APPLaunch/main/ui/ui_launch_page_carousel_view.cpp index eff45c63..fb01ff54 100644 --- a/projects/APPLaunch/main/ui/ui_launch_page_carousel_view.cpp +++ b/projects/APPLaunch/main/ui/ui_launch_page_carousel_view.cpp @@ -6,10 +6,11 @@ #include "ui_launch_page.h" -#include "animation/launcher_carousel_layout.h" +#include "animation/launcher_grid_layout.h" #include "animation/ui_launcher_animation.h" #include "cp0_enum_cast.h" #include "launcher_platform.hpp" +#include "ui.h" #include #include @@ -19,27 +20,20 @@ extern "C" { LV_FONT_DECLARE(launcher_montserrat_bold_latin_16) } -const lv_font_t *launcher_ui::carousel_title_font() +const lv_font_t *launcher_ui::grid_title_font() { - return launcher_fonts().get("Montserrat-Bold.ttf", 16, LV_FREETYPE_FONT_STYLE_BOLD, + return launcher_fonts().get("Montserrat-Bold.ttf", 12, LV_FREETYPE_FONT_STYLE_BOLD, LV_FREETYPE_FONT_RENDER_MODE_BITMAP, &launcher_montserrat_bold_latin_16); } namespace { -using launcher_carousel_layout::Slot; -using launcher_carousel_layout::kSlots; +using launcher_grid_layout::Cell; +using launcher_grid_layout::kCellLayout; -enum class HomeSliderMetric : lv_coord_t { - Width = 160, - Height = 8, - OffsetY = 65, -}; - -static_assert(UILaunchPage::kPageSlider == launcher_carousel_layout::kElementCount); -static_assert(UILaunchPage::kLauncherCarouselElementCount == - launcher_carousel_layout::kElementCount + 1); +static_assert(UILaunchPage::kLauncherGridElementCount == + launcher_grid_layout::kCells * 2); // LVGL's software scaler limits the transformed image to // ((source_size - 1) * scale) >> 8. The usual floor(source/target) scale @@ -63,68 +57,26 @@ void compensate_image_scale(lv_obj_t *image) const uint32_t scale_y = static_cast( (static_cast(target_height - 1) * scale_unit + source_height - 2) / (source_height - 1)); - // Keep manual compensation centered when the image grows during a - // carousel transition by explicitly fixing the source pivot. + // Keep manual compensation centred on the source so resampling stays + // symmetric while the page slide moves the grid. lv_image_set_pivot(image, source_width / 2, source_height / 2); lv_image_set_scale_x(image, scale_x); lv_image_set_scale_y(image, scale_y); } -lv_obj_t *create_page_slider(lv_obj_t *parent, size_t page_count, size_t selected_page) -{ - lv_obj_t *slider = lv_slider_create(parent); - if (!slider) return nullptr; - - lv_obj_remove_style_all(slider); - lv_obj_set_size( - slider, - CP0_ENUM_CAST(lv_coord_t, HomeSliderMetric::Width), - CP0_ENUM_CAST(lv_coord_t, HomeSliderMetric::Height)); - lv_obj_set_pos( - slider, 0, CP0_ENUM_CAST(lv_coord_t, HomeSliderMetric::OffsetY)); - lv_obj_set_align(slider, LV_ALIGN_CENTER); - lv_obj_clear_flag( - slider, static_cast(LV_OBJ_FLAG_CLICKABLE | - LV_OBJ_FLAG_CLICK_FOCUSABLE | - LV_OBJ_FLAG_SCROLLABLE | - LV_OBJ_FLAG_SCROLL_ON_FOCUS)); - - lv_obj_set_style_bg_color(slider, lv_color_hex(0x212021), LV_PART_MAIN); - lv_obj_set_style_bg_opa(slider, LV_OPA_COVER, LV_PART_MAIN); - lv_obj_set_style_radius(slider, LV_RADIUS_CIRCLE, LV_PART_MAIN); - lv_obj_set_style_pad_all(slider, 0, LV_PART_MAIN); - // Keep the 8px knob inside the 160px track at both end values. The - // main background remains dark across the full slider width. - lv_obj_set_style_pad_left(slider, 4, LV_PART_MAIN); - lv_obj_set_style_pad_right(slider, 4, LV_PART_MAIN); - lv_obj_set_style_bg_color(slider, lv_color_hex(0x212021), LV_PART_INDICATOR); - lv_obj_set_style_bg_opa(slider, LV_OPA_COVER, LV_PART_INDICATOR); - lv_obj_set_style_radius(slider, LV_RADIUS_CIRCLE, LV_PART_INDICATOR); - lv_obj_set_style_bg_color(slider, lv_color_hex(0xF2C94C), LV_PART_KNOB); - lv_obj_set_style_bg_opa(slider, LV_OPA_COVER, LV_PART_KNOB); - lv_obj_set_style_radius(slider, LV_RADIUS_CIRCLE, LV_PART_KNOB); - lv_obj_set_style_pad_all(slider, 0, LV_PART_KNOB); - const size_t max_page = page_count > 0 ? page_count - 1 : 0; - lv_slider_set_range(slider, 0, static_cast(max_page)); - lv_slider_set_value(slider, static_cast(selected_page), LV_ANIM_OFF); - return slider; -} - -lv_obj_t *create_carousel_card(lv_obj_t *parent, const Slot &slot, - lv_coord_t radius, uint32_t border_color, - bool clickable) +lv_obj_t *create_grid_card(lv_obj_t *parent, const Cell &cell, uint32_t border_color, + bool clickable) { lv_obj_t *card = lv_obj_create(parent); if (!card) return nullptr; - lv_obj_set_size(card, slot.width, slot.height); - lv_obj_set_pos(card, slot.x, slot.y); + lv_obj_set_size(card, launcher_grid_layout::kCardSize, launcher_grid_layout::kCardSize); + lv_obj_set_pos(card, cell.card_x, cell.card_y); lv_obj_set_align(card, LV_ALIGN_CENTER); lv_obj_clear_flag(card, LV_OBJ_FLAG_SCROLLABLE); if (!clickable) lv_obj_clear_flag(card, LV_OBJ_FLAG_CLICKABLE); - if (slot.hidden) - lv_obj_add_flag(card, LV_OBJ_FLAG_HIDDEN); - lv_obj_set_style_radius(card, radius, LV_PART_MAIN | LV_STATE_DEFAULT); + lv_obj_set_style_radius(card, launcher_grid_layout::kCardRadius, + LV_PART_MAIN | LV_STATE_DEFAULT); lv_obj_set_style_bg_color(card, lv_color_hex(0xFFFFFF), LV_PART_MAIN | LV_STATE_DEFAULT); lv_obj_set_style_bg_opa(card, LV_OPA_TRANSP, LV_PART_MAIN | LV_STATE_DEFAULT); lv_obj_set_style_border_color(card, lv_color_hex(border_color), LV_PART_MAIN | LV_STATE_DEFAULT); @@ -133,75 +85,24 @@ lv_obj_t *create_carousel_card(lv_obj_t *parent, const Slot &slot, return card; } -lv_obj_t *create_carousel_title(lv_obj_t *parent, const Slot &slot, - lv_coord_t width, const char *text) +lv_obj_t *create_grid_title(lv_obj_t *parent, const Cell &cell, const char *text) { lv_obj_t *title = lv_label_create(parent); if (!title) return nullptr; - lv_obj_set_width(title, width); - lv_obj_set_pos(title, slot.x, slot.y); + lv_obj_set_width(title, launcher_grid_layout::kTitleWidth); + lv_obj_set_pos(title, cell.title_x, cell.title_y); lv_obj_set_align(title, LV_ALIGN_CENTER); lv_obj_set_style_text_align(title, LV_TEXT_ALIGN_CENTER, LV_PART_MAIN | LV_STATE_DEFAULT); - lv_obj_set_style_text_font( - title, - launcher_ui::carousel_title_font(), - LV_PART_MAIN | LV_STATE_DEFAULT); + lv_obj_set_style_text_font(title, launcher_ui::grid_title_font(), + LV_PART_MAIN | LV_STATE_DEFAULT); launcher_home_animation::set_title_text(title, text); lv_obj_set_style_text_color(title, lv_color_hex(0xFFFFFF), LV_PART_MAIN | LV_STATE_DEFAULT); lv_obj_set_style_text_opa(title, LV_OPA_COVER, LV_PART_MAIN | LV_STATE_DEFAULT); - if (slot.hidden) - lv_obj_add_flag(title, LV_OBJ_FLAG_HIDDEN); return title; } -lv_obj_t *create_carousel_arrow(lv_obj_t *parent, lv_coord_t x, const char *asset) -{ - lv_obj_t *button = lv_btn_create(parent); - if (!button) return nullptr; - lv_obj_set_size(button, 17, 23); - lv_obj_set_pos(button, x, -4); - lv_obj_set_align(button, LV_ALIGN_CENTER); - lv_obj_add_flag(button, LV_OBJ_FLAG_SCROLL_ON_FOCUS); - lv_obj_clear_flag(button, LV_OBJ_FLAG_SCROLLABLE); - lv_obj_set_style_radius(button, 0, LV_PART_MAIN | LV_STATE_DEFAULT); - lv_obj_set_style_bg_color(button, lv_color_hex(0xFFFFFF), LV_PART_MAIN | LV_STATE_DEFAULT); - lv_obj_set_style_bg_opa(button, LV_OPA_TRANSP, LV_PART_MAIN | LV_STATE_DEFAULT); - lv_obj_set_style_bg_img_src(button, launcher_platform::path_c(asset), LV_PART_MAIN | LV_STATE_DEFAULT); - lv_obj_set_style_shadow_color(button, lv_color_hex(0x000000), LV_PART_MAIN | LV_STATE_DEFAULT); - lv_obj_set_style_shadow_opa(button, LV_OPA_TRANSP, LV_PART_MAIN | LV_STATE_DEFAULT); - return button; -} - } // namespace -void UILaunchPage::set_page_slider_range(size_t page_count, size_t selected_page) -{ - lv_obj_t *slider = carousel_elements_[kPageSlider]; - if (!slider) return; - const size_t max_page = page_count > 0 ? page_count - 1 : 0; - lv_slider_set_range(slider, 0, static_cast(max_page)); - set_page_slider_position(selected_page); -} - -void UILaunchPage::set_page_slider_position(size_t page) -{ - lv_obj_t *slider = carousel_elements_[kPageSlider]; - if (!slider) return; - const int32_t max_page = lv_slider_get_max_value(slider); - const int32_t value = page > static_cast(max_page) - ? max_page : static_cast(page); - lv_slider_set_value(slider, value, LV_ANIM_OFF); -} - -void UILaunchPage::set_carousel_element_clickable(size_t element, bool clickable) -{ - if (element >= carousel_elements_.size() || !carousel_elements_[element]) return; - if (clickable) - lv_obj_add_flag(carousel_elements_[element], LV_OBJ_FLAG_CLICKABLE); - else - lv_obj_clear_flag(carousel_elements_[element], LV_OBJ_FLAG_CLICKABLE); -} - void UILaunchPage::set_panel_icon(lv_obj_t *panel, const std::string &src) { if (!panel) @@ -242,23 +143,19 @@ void UILaunchPage::set_panel_icon(lv_obj_t *panel, const std::string &src) lv_obj_set_style_border_width(clip, 0, selector); lv_obj_set_style_pad_all(clip, 0, selector); - // Match the decoded buffer to the card content size. The far slots are - // hidden while they enter the carousel, so use the side-card size for - // them and avoid a second transparent-edge resample when they appear. - const lv_coord_t source_card_size = lv_obj_get_width(panel) >= 100 ? 100 : 80; const uint32_t image_size = static_cast(std::max( - 1, source_card_size - 2 * card_border)); + 1, launcher_grid_layout::kCardSize - 2 * card_border)); lv_image_set_src(image, home_icon_pool_.find(src, image_size)); compensate_image_scale(image); } -void UILaunchPage::update_carousel_slot(size_t slot, const char *title, const std::string &icon) +void UILaunchPage::update_grid_cell(size_t cell, const char *title, const std::string &icon) { - update_carousel_item(panel(slot), label(slot), title, icon); + update_grid_item(panel(cell), label(cell), title, icon); } -void UILaunchPage::update_carousel_item(lv_obj_t *panel, lv_obj_t *label, - const char *title, const std::string &icon) +void UILaunchPage::update_grid_item(lv_obj_t *panel, lv_obj_t *label, + const char *title, const std::string &icon) { launcher_home_animation::set_title_text(label, title ? title : ""); set_panel_icon(panel, icon); @@ -266,8 +163,8 @@ void UILaunchPage::update_carousel_item(lv_obj_t *panel, lv_obj_t *label, void UILaunchPage::create_screen() { - const bool complete = carousel_container_ && left_arrow_button_ && right_arrow_button_ && - std::all_of(carousel_elements_.begin(), carousel_elements_.end(), + const bool complete = grid_container_ && + std::all_of(grid_elements_.begin(), grid_elements_.end(), [](lv_obj_t *element) { return element != nullptr; }); if (!complete) create_app_container(content_container()); @@ -287,67 +184,35 @@ void UILaunchPage::create_app_container(lv_obj_t *parent) lv_obj_set_style_border_width(container, 0, LV_PART_MAIN); lv_obj_set_style_pad_all(container, 0, LV_PART_MAIN); - std::array elements = {}; + std::array elements = {}; - const size_t page_count = launch_ ? launch_->app_count() : 0; - const size_t selected_page = launch_ ? launch_->current_app_index() : 0; - elements[kPageSlider] = create_page_slider(container, page_count, selected_page); - - elements[kTitleCenter] = create_carousel_title(container, kSlots[kTitleCenter], 100, "CLI"); - elements[kTitleRight] = create_carousel_title(container, kSlots[kTitleRight], 80, "GAME"); - elements[kTitleLeft] = create_carousel_title(container, kSlots[kTitleLeft], 80, "STORE"); - - elements[kCardLeft] = create_carousel_card( - container, kSlots[kCardLeft], launcher_carousel_layout::kSideCardRadius, - 0x222222, false); - elements[kCardCenter] = create_carousel_card( - container, kSlots[kCardCenter], launcher_carousel_layout::kCenterCardRadius, - 0x444444, true); - elements[kCardRight] = create_carousel_card( - container, kSlots[kCardRight], launcher_carousel_layout::kSideCardRadius, - 0x222222, false); - elements[kCardFarRight] = create_carousel_card( - container, kSlots[kCardFarRight], launcher_carousel_layout::kSideCardRadius, - 0x333333, false); - elements[kCardFarLeft] = create_carousel_card( - container, kSlots[kCardFarLeft], launcher_carousel_layout::kSideCardRadius, - 0x333333, false); - - lv_obj_t *left_arrow = create_carousel_arrow(container, -151, "carousel_left_arrow.png"); - lv_obj_t *right_arrow = create_carousel_arrow(container, 150, "carousel_right_arrow.png"); - - elements[kTitleFarLeft] = create_carousel_title(container, kSlots[kTitleFarLeft], 61, "one"); - elements[kTitleFarRight] = create_carousel_title(container, kSlots[kTitleFarRight], 61, "three"); + for (size_t cell = 0; cell < launcher_grid_layout::kCells; ++cell) { + const Cell &layout = kCellLayout[cell]; + elements[kTitle0 + cell] = create_grid_title(container, layout, ""); + elements[kCard0 + cell] = create_grid_card( + container, layout, BORDER_COLOR_SIDE, true); + } - const bool complete = left_arrow && right_arrow && + const bool complete = std::all_of(elements.begin(), elements.end(), [](lv_obj_t *element) { return element != nullptr; }); if (!complete) { lv_obj_delete(container); return; } - *carousel_alive_ = false; - if (carousel_container_) lv_obj_delete(carousel_container_); - carousel_alive_ = std::make_shared(true); - carousel_container_ = container; - carousel_elements_ = elements; - left_arrow_button_ = left_arrow; - right_arrow_button_ = right_arrow; - - lv_obj_add_event_cb(carousel_elements_[kCardLeft], on_app_clicked, LV_EVENT_CLICKED, this); - lv_obj_add_event_cb(carousel_elements_[kCardCenter], on_app_clicked, LV_EVENT_CLICKED, this); - lv_obj_add_event_cb(carousel_elements_[kCardRight], on_app_clicked, LV_EVENT_CLICKED, this); - lv_obj_add_event_cb(carousel_elements_[kCardFarRight], on_app_clicked, LV_EVENT_CLICKED, this); - lv_obj_add_event_cb(carousel_elements_[kCardFarLeft], on_app_clicked, LV_EVENT_CLICKED, this); - lv_obj_add_event_cb(left_arrow_button_, on_left_arrow_clicked, LV_EVENT_CLICKED, this); - lv_obj_add_event_cb(right_arrow_button_, on_right_arrow_clicked, LV_EVENT_CLICKED, this); - lv_obj_add_event_cb(carousel_container_, on_owned_obj_deleted, LV_EVENT_DELETE, this); - for (lv_obj_t *element : carousel_elements_) + *grid_alive_ = false; + if (grid_container_) lv_obj_delete(grid_container_); + grid_alive_ = std::make_shared(true); + grid_container_ = container; + grid_elements_ = elements; + + for (size_t cell = 0; cell < launcher_grid_layout::kCells; ++cell) + lv_obj_add_event_cb(grid_elements_[kCard0 + cell], on_app_clicked, LV_EVENT_CLICKED, this); + lv_obj_add_event_cb(grid_container_, on_owned_obj_deleted, LV_EVENT_DELETE, this); + for (lv_obj_t *element : grid_elements_) lv_obj_add_event_cb(element, on_owned_obj_deleted, LV_EVENT_DELETE, this); - lv_obj_add_event_cb(left_arrow_button_, on_owned_obj_deleted, LV_EVENT_DELETE, this); - lv_obj_add_event_cb(right_arrow_button_, on_owned_obj_deleted, LV_EVENT_DELETE, this); - launcher_home_animation::apply_title_overflow(carousel_elements_[kTitleCenter], true); if (!home_key_registered_ && screen()) { lv_obj_add_event_cb(screen(), on_home_key, (lv_event_code_t)LV_EVENT_KEYBOARD, this); home_key_registered_ = true; } + apply_grid_highlight(); } diff --git a/projects/APPLaunch/main/ui/ui_launch_page_input.cpp b/projects/APPLaunch/main/ui/ui_launch_page_input.cpp index 841cd567..880456d1 100644 --- a/projects/APPLaunch/main/ui/ui_launch_page_input.cpp +++ b/projects/APPLaunch/main/ui/ui_launch_page_input.cpp @@ -6,6 +6,7 @@ #include "ui_launch_page.h" +#include "animation/launcher_grid_layout.h" #include "hal_lvgl_bsp.h" #include "input_keys.h" #include "keyboard_input.h" @@ -88,27 +89,61 @@ void UILaunchPage::handle_home_key(lv_event_t *event) switch (code) { case KEY_UP: - break; + { + if (navigation_ready()) + { + audio_play_switch(); + move_grid_up(); + } + } + break; case KEY_DOWN: - break; + { + if (navigation_ready()) + { + audio_play_switch(); + move_grid_down(); + } + } + break; case KEY_LEFT: { - if (navigation_.keyboard_navigation_enabled()) + if (navigation_ready()) { audio_play_switch(); - switch_right(); + move_grid_previous(); } } break; case KEY_RIGHT: { - if (navigation_.keyboard_navigation_enabled()) + if (navigation_ready()) + { + audio_play_switch(); + move_grid_next(); + } + } + break; + + case KEY_I: + { + if (navigation_ready()) { audio_play_switch(); - switch_left(); + move_grid_page_previous(); + } + } + break; + + case KEY_O: + { + if (navigation_ready()) + { + audio_play_switch(); + move_grid_page_next(); } } break; @@ -124,26 +159,18 @@ void UILaunchPage::handle_home_key(lv_event_t *event) } } -void UILaunchPage::on_left_arrow_clicked(lv_event_t *event) noexcept -{ - try { - if (UILaunchPage *self = page_from_event(event)) self->switch_right(); - } catch (...) { - } -} - -void UILaunchPage::on_right_arrow_clicked(lv_event_t *event) noexcept -{ - try { - if (UILaunchPage *self = page_from_event(event)) self->switch_left(); - } catch (...) { - } -} - void UILaunchPage::on_app_clicked(lv_event_t *event) noexcept { try { - if (UILaunchPage *self = page_from_event(event)) self->launch_selected_app(); + UILaunchPage *self = page_from_event(event); + if (!self) return; + lv_obj_t *target = static_cast(lv_event_get_target(event)); + for (size_t cell = 0; cell < launcher_grid_layout::kCells; ++cell) { + if (self->grid_elements_[cell] != target) continue; + self->select_grid_cell(cell); + self->launch_selected_app(); + return; + } } catch (...) { } } diff --git a/projects/APPLaunch/main/ui/ui_screensaver.cpp b/projects/APPLaunch/main/ui/ui_screensaver.cpp index 4048c7b7..4fdfff34 100644 --- a/projects/APPLaunch/main/ui/ui_screensaver.cpp +++ b/projects/APPLaunch/main/ui/ui_screensaver.cpp @@ -9,6 +9,7 @@ #include "cp0_lvgl_app.h" #include "cp0_enum_cast.h" +#include "cp0_status_pause.h" #include "hal_lvgl_bsp.h" #include "keyboard_input.h" #include "launcher_media_controls.h" @@ -25,6 +26,8 @@ #include #include +#include +#include #include #include #include @@ -106,6 +109,14 @@ LockscreenBackgroundCache s_background_cache; /* Raw backlight value captured when the panel is forced dark, or -1 while the * backlight is under normal control. */ int s_screen_off_backlight_raw = -1; +/* Deep panel sleep stage: once the black state has held for the configured + * panel-sleep delay, the SPI panel itself is blanked (display off + MIPI + * sleep), the CPU governor is pinned to powersave and every LVGL timer is + * stopped, so the process sleeps on the input semaphore until a key arrives. + * Any key reverses the whole stage. */ +bool s_deep_asleep = false; +/* Tick when the current black state began, or 0 while the panel is lit. */ +uint32_t s_black_since = 0; /* ---- per-user wallpaper override --------------------------------------- * The optional ~/.config/APPLaunch/config.json entry replaces the packaged @@ -296,6 +307,86 @@ void update_timer_period() lv_timer_set_period(s_timer, s_model.hold_pending() ? kHoldPollMs : kIdleCheckMs); } +/* One pactl spawn scanned for a sink that is actively rendering. This is the + * "is music playing" signal for the deep-sleep Bluetooth guard: powering the + * radio off severs a connected speaker's A2DP link mid-song. A failed probe + * counts as idle, so the radio still goes down when no mixer can be reached. */ +bool any_sink_rendering() noexcept +{ + FILE *probe = ::popen("pactl list sinks 2>/dev/null", "r"); + if (!probe) return false; + char line[256] = {}; + bool rendering = false; + while (::fgets(line, sizeof(line), probe) != nullptr) { + if (::strstr(line, "State: RUNNING") != nullptr) { + rendering = true; + break; + } + } + ::pclose(probe); + return rendering; +} + +/* Power the Bluetooth radio down for deep sleep - unless audio is rendering + * right now, in which case a connected speaker must keep its link. The pactl + * probe can block for tens of milliseconds, so it runs on an async worker + * instead of the LVGL thread (same pattern as the system-sound prepare); the + * power call itself rides the bluez client's fire-and-forget queue, which is + * safe to post from any thread. Wake always powers the radio back on, so one + * skipped power-down only costs idle drain until the next wake + idle cycle. */ +std::future s_bluetooth_sleep_power_future; + +void drop_bluetooth_for_deep_sleep() noexcept +{ + try { + if (s_bluetooth_sleep_power_future.valid()) + (void)s_bluetooth_sleep_power_future.get(); + s_bluetooth_sleep_power_future = std::async(std::launch::async, [] { + if (!any_sink_rendering()) + cp0_bluetooth_power_set_async(0); + }); + } catch (...) { + } +} + +/* Stage 2 of the screen-off sequence, after the black state has held for the + * configured delay: blank the panel itself, pin the CPU governor and stop + * every LVGL timer - including this file's own - so the process sleeps on the + * input semaphore until a key posts it. Key input does not depend on timers, + * so wake-up stays instant. */ +void deep_sleep_enter() noexcept +{ + if (s_deep_asleep) return; + try { + if (cp0_panel_fb_blank(1) != 0) + SLOGW("[POWER] panel blank failed; staying on the backlit-dark stage"); + if (cp0_cpufreq_powersave_set(1) != 0) + SLOGW("[POWER] cpufreq powersave unavailable"); + /* Re-assert the LED (a deferred LED re-registration can relight it + * after stage 1); drop the Bluetooth radio only when nothing is + * playing, so music through a connected speaker survives the dark. */ + (void)cp0_status_led_suspend(); + drop_bluetooth_for_deep_sleep(); + } catch (...) { + } + s_deep_asleep = true; + lv_timer_enable(false); +} + +/* Reverse of deep_sleep_enter(); idempotent, called from every exit path. */ +void deep_sleep_exit() noexcept +{ + if (!s_deep_asleep) return; + s_deep_asleep = false; + lv_timer_enable(true); + try { + (void)cp0_cpufreq_powersave_set(0); + (void)cp0_panel_fb_blank(0); + cp0_bluetooth_power_set_async(1); + } catch (...) { + } +} + void suspend_screen_off_backlight() noexcept { if (s_screen_off_backlight_raw >= 0) return; @@ -304,18 +395,29 @@ void suspend_screen_off_backlight() noexcept } catch (...) { s_screen_off_backlight_raw = -1; } + /* Stage 1: with the backlight gone, the periodic UI refreshers (clock, + * status, battery) and the network status polling stand down for the whole + * dark period, and the red status LED follows the panel dark. Wi-Fi + * itself stays connected. */ + cp0_status_pause_set(1); + (void)cp0_status_led_suspend(); } void release_screen_off_backlight() noexcept { if (s_screen_off_backlight_raw < 0) return; + /* Waking the panel comes first so the restored frame lands on a lit panel. */ + deep_sleep_exit(); const int raw = s_screen_off_backlight_raw; /* Clear first so a throwing backend cannot latch the panel dark. */ s_screen_off_backlight_raw = -1; + s_black_since = 0; try { launcher_media_controls::restore_backlight(raw); } catch (...) { } + (void)cp0_status_led_restore(); + cp0_status_pause_set(0); } void suspend_system_sound() noexcept @@ -370,8 +472,10 @@ void curtain_exit_anim_exec(void *object, int32_t y) noexcept void finish_screensaver_exit() noexcept { + deep_sleep_exit(); (void)finish_system_sound_prepare(); release_screen_off_backlight(); + s_black_since = 0; try { if (s_overlay) { lv_obj_add_flag(s_overlay, LV_OBJ_FLAG_HIDDEN); @@ -417,14 +521,18 @@ void overlay_delete_cb(lv_event_t *event) noexcept s_hint = nullptr; s_exiting = false; s_model.deactivate(); + deep_sleep_exit(); release_screen_off_backlight(); + s_black_since = 0; update_timer_period(); } catch (...) { s_overlay = nullptr; if (s_hint) lv_obj_delete(s_hint); s_hint = nullptr; s_exiting = false; + deep_sleep_exit(); release_screen_off_backlight(); + s_black_since = 0; update_timer_period(); try { s_model.deactivate(); @@ -461,6 +569,24 @@ int timeout_seconds() noexcept } } +/* Delay before the black state deepens into the panel-sleep stage; 0 keeps the + * device on the backlit-dark stage indefinitely. */ +int panel_sleep_seconds() noexcept +{ + try { + bool succeeded = false; + std::string response; + cp0_signal_config_api({"GetInt", "panel_sleep_time", "30"}, + [&](int code, std::string data) { + succeeded = code == 0; + response = std::move(data); + }); + return screensaver_timeout_from_config(succeeded, response); + } catch (...) { + return screensaver_timeout_from_config(false, {}); + } +} + void create_objects() { lv_display_t *display = lv_display_get_default(); @@ -569,6 +695,7 @@ void enter_lockscreen() suspend_system_sound(); suspend_screen_off_backlight(); + s_black_since = now; play_lockscreen_sound("lock.mp3"); lv_obj_move_foreground(s_overlay); @@ -584,6 +711,7 @@ void show_lockscreen_panel() lv_obj_move_foreground(s_overlay); lv_obj_clear_flag(s_overlay, LV_OBJ_FLAG_HIDDEN); release_screen_off_backlight(); + s_black_since = 0; show_hint(s_lock.state() == LockscreenState::Armed ? "Press ENTER to unlock" : "Press TAB to unlock"); @@ -595,6 +723,7 @@ void sleep_lockscreen() apply_panel(full_screen_panel()); hide_hint(); suspend_screen_off_backlight(); + s_black_since = lv_tick_get(); play_lockscreen_sound("lock.mp3"); } @@ -610,6 +739,12 @@ void timer_cb(lv_timer_t *timer) noexcept /* The visible lock states fall back to the black screen when idle. */ if (s_lock.poll(now).sleep) sleep_lockscreen(); + /* While the black state holds, count towards the deep panel sleep. */ + if (!s_deep_asleep && s_black_since != 0) { + const int seconds = panel_sleep_seconds(); + if (seconds > 0 && now - s_black_since >= static_cast(seconds) * 1000u) + deep_sleep_enter(); + } return; } @@ -656,7 +791,9 @@ extern "C" void ui_screensaver_deinit(void) } cancel_exit_animation(); (void)finish_system_sound_prepare(); + deep_sleep_exit(); release_screen_off_backlight(); + s_black_since = 0; if (s_overlay) lv_obj_delete(s_overlay); if (s_hint) @@ -683,6 +820,9 @@ extern "C" int ui_screensaver_filter_key(const struct key_item *item) return 1; if (s_model.active()) { + /* Any key wakes the panel first (and reverses the deep-sleep stage); + * the lock flow then decides what the key means. */ + deep_sleep_exit(); /* The lock screen owns every key while it is up. */ const LockscreenDecision decision = s_lock.handle_key(item->key_code, pressed, released, now); diff --git a/projects/APPLaunch/tests/run_tests.sh b/projects/APPLaunch/tests/run_tests.sh index 9559476b..0102a6da 100755 --- a/projects/APPLaunch/tests/run_tests.sh +++ b/projects/APPLaunch/tests/run_tests.sh @@ -5,7 +5,7 @@ set -eu test_root=$(CDPATH= cd -- "$(dirname "$0")" && pwd) settings_ui_root=$(CDPATH= cd -- "$test_root/../main/ui/settings" && pwd) -python3 "$test_root/test_carousel_border_contract.py" +python3 "$test_root/test_grid_contract.py" python3 "$test_root/test_external_framebuffer_ownership.py" python3 "$test_root/test_settings_input_font_contract.py" python3 "$test_root/test_settings_menu_order.py" @@ -18,6 +18,7 @@ python3 "$test_root/test_settings_storage_build_contract.py" python3 "$test_root/test_settings_software_page_contract.py" python3 "$test_root/test_static_resource_staging.py" python3 "$test_root/test_lockscreen_contract.py" +python3 "$test_root/test_power_contract.py" python3 "$test_root/test_home_icon_fallback_contract.py" python3 "$test_root/test_lodepng_override_contract.py" PYTHONPATH="$test_root/..${PYTHONPATH:+:$PYTHONPATH}" \ @@ -190,6 +191,11 @@ ${CXX:-g++} -std=c++17 -Wall -Wextra -Werror \ -I"$test_root/../../../ext_components/cp0_lvgl/include" \ "$test_root/test_lockscreen_state_model.cpp" \ -o "$build_dir/test_lockscreen_state_model" +${CXX:-g++} -std=c++17 -Wall -Wextra -Werror \ + -I"$test_root/../main/ui" \ + "$test_root/test_launcher_grid_model.cpp" \ + -o "$build_dir/test_launcher_grid_model" +"$build_dir/test_launcher_grid_model" "$build_dir/test_lockscreen_state_model" ${CXX:-g++} -std=c++17 -Wall -Wextra -Werror \ -I"$test_root/../../../ext_components/cp0_lvgl/include" \ diff --git a/projects/APPLaunch/tests/test_external_framebuffer_ownership.py b/projects/APPLaunch/tests/test_external_framebuffer_ownership.py index bfbe426e..35a57369 100644 --- a/projects/APPLaunch/tests/test_external_framebuffer_ownership.py +++ b/projects/APPLaunch/tests/test_external_framebuffer_ownership.py @@ -9,7 +9,7 @@ encoding="utf-8" ) start = source.index("void Launch::launch_Exec(") -end = source.index("\nvoid Launch::select_next_app()", start) +end = source.index("\nvoid Launch::select_app_relative(int delta)", start) body = source[start:end] paint = body.index("lv_refr_now(disp)") diff --git a/projects/APPLaunch/tests/test_grid_contract.py b/projects/APPLaunch/tests/test_grid_contract.py new file mode 100644 index 00000000..ce0c8a6e --- /dev/null +++ b/projects/APPLaunch/tests/test_grid_contract.py @@ -0,0 +1,115 @@ +# SPDX-FileCopyrightText: 2026 M5Stack Technology CO LTD +# +# SPDX-License-Identifier: MIT + +"""Wiring contract for the 3x2 home app grid. + +The grid model logic is covered by test_launcher_grid_model.cpp. This pins +the textual wiring that is easy to lose in a refactor: the card theme +invariants inherited from the carousel, the page-flip plumbing and the +arrow-key wiring. +""" + +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +UI = ROOT / "main/ui" + +PAGE_HEADER = (UI / "ui_launch_page.h").read_text(encoding="utf-8") +PAGE = (UI / "ui_launch_page.cpp").read_text(encoding="utf-8") +VIEW = (UI / "ui_launch_page_carousel_view.cpp").read_text(encoding="utf-8") +INPUT = (UI / "ui_launch_page_input.cpp").read_text(encoding="utf-8") +ANIMATION_H = (UI / "animation/ui_launcher_animation.h").read_text(encoding="utf-8") +ANIMATION = (UI / "animation/ui_launcher_animation.cpp").read_text(encoding="utf-8") +LAYOUT = (UI / "animation/launcher_grid_layout.h").read_text(encoding="utf-8") +MODEL = (UI / "model/launcher_grid_model.hpp").read_text(encoding="utf-8") +LAUNCH_H = (UI / "launch.h").read_text(encoding="utf-8") +LAUNCH = (UI / "launch.cpp").read_text(encoding="utf-8") + +# ---- layout ------------------------------------------------------------- +# 3 columns x 2 rows, six apps per page, square cards so the square icon +# artwork is never stretched by the per-axis image compensation. +assert "kCols = 3" in LAYOUT and "kRows = 2" in LAYOUT +assert "kCells = kCols * kRows" in LAYOUT +assert "kCardSize = 58" in LAYOUT +assert "static_assert(kCellLayout.size() == kCells)" in LAYOUT +assert "launcher_carousel_layout" not in PAGE + VIEW + ANIMATION + INPUT +assert "kLauncherGridElementCount ==" in VIEW or "kLauncherGridElementCount ==" in PAGE + +# The old carousel plumbing must stay gone. +for gone in ( + "switch_left", + "switch_right", + "rotate_carousel", + "carousel_slot_app", + "select_next_app", + "select_previous_app", + "kHomeCarouselSlotCount", + "animate_left", + "animate_right", + "arrow_button_", + "create_grid_arrow", +): + assert gone not in PAGE_HEADER + PAGE + VIEW + INPUT + ANIMATION_H, gone + assert gone not in LAUNCH_H + LAUNCH, gone + +# ---- selection model ---------------------------------------------------- +# The UI drives the model's named moves; left/right stay inside the row and +# the model decides when an edge move means a page flip. +assert "void select_app_relative(int delta);" in LAUNCH_H +assert "select_app_relative(static_cast(grid_.index())" in PAGE +assert "class LauncherGridModel" in MODEL +assert "kCellsPerPage = kCols * kRows" in MODEL +assert "crossed_page_" in MODEL and "moved_forward_" in MODEL +assert "bool move_row_right() { return move_row(1); }" in MODEL +assert "bool move_row_left() { return move_row(-1); }" in MODEL +assert "grid_.move_row_right()" in PAGE and "grid_.move_row_left()" in PAGE +assert "grid_.move_down()" in PAGE and "grid_.move_up()" in PAGE +# Moves ignore while a page flip animates, so strides cannot interleave. +assert "if (page_flip_active_) return false;" in PAGE + +# ---- page flip ---------------------------------------------------------- +assert "void animate_page_slide(lv_obj_t *container, bool forward," in ANIMATION_H +assert "void animate_page_slide(lv_obj_t *container, bool forward," in ANIMATION +assert "void UILaunchPage::start_page_flip(bool forward)" in PAGE +assert "finish_page_flip_animation()" in PAGE +assert "cancel_page_flip_animation()" in PAGE + +# ---- card theme (inherited from the carousel contract) ------------------ +# Every card keeps the theme border: the factory never overrides the border +# width and draws it with border_post, never clip_corner. +start = VIEW.index("lv_obj_t *create_grid_card") +end = VIEW.index("lv_obj_t *create_grid_title", start) +factory = VIEW[start:end] +assert "lv_obj_set_style_border_width(card," not in factory +assert "lv_obj_set_style_border_post(card, true," in factory +assert "lv_obj_set_style_clip_corner(card," not in factory +# The selection highlight: theme-accent border + lit tile on the selection; +# every card keeps full icon brightness (no dimming of neighbours). +assert "kSelectedBorderColor" in LAYOUT and "kSelectedBorderColor" in PAGE +assert "BORDER_COLOR_SIDE" in PAGE +assert "kSelectedBgOpa" in LAYOUT and "set_style_bg_opa" in PAGE +assert "kUnselectedIconOpa" not in LAYOUT + PAGE +assert "kUnselectedTitleColor" not in LAYOUT + PAGE +assert "BORDER_COLOR_CENTER" not in PAGE + +# ---- arrows and keys ---------------------------------------------------- +# All four arrows move the grid; F/Z/X/C remap onto them as before, and the +# old no-op UP/DOWN branches are gone. +assert "move_grid_up()" in INPUT and "move_grid_down()" in INPUT +assert "move_grid_previous()" in INPUT and "move_grid_next()" in INPUT +assert "move_grid_page_previous()" in INPUT and "move_grid_page_next()" in INPUT +assert "case KEY_UP:" in INPUT and "case KEY_DOWN:" in INPUT +assert "case KEY_I:" in INPUT and "case KEY_O:" in INPUT +assert "fzxc_to_arrow" in INPUT +# Clicking a card selects its cell, then launches. +assert "select_grid_cell(cell);" in INPUT +assert "launch_selected_app();" in INPUT +assert "void UILaunchPage::select_grid_cell(size_t cell)" in PAGE + +# Ragged pages ------------------------------------------------------------- +# Pages never show wrapped filler: cells past the app count are hidden, and +# the model owns the clamped edge/wrap targets plus the I/O page flips. +assert "LV_OBJ_FLAG_HIDDEN" in PAGE and "real" in PAGE +assert "bool flip_page(int dir)" in MODEL diff --git a/projects/APPLaunch/tests/test_launcher_grid_model.cpp b/projects/APPLaunch/tests/test_launcher_grid_model.cpp new file mode 100644 index 00000000..6cd1667f --- /dev/null +++ b/projects/APPLaunch/tests/test_launcher_grid_model.cpp @@ -0,0 +1,137 @@ +/* + * SPDX-FileCopyrightText: 2026 M5Stack Technology CO LTD + * + * SPDX-License-Identifier: MIT + */ + +#include "model/launcher_grid_model.hpp" + +#include + +int main() +{ + using Model = LauncherGridModel; + constexpr size_t kCells = Model::kCellsPerPage; + static_assert(kCells == 6); + static_assert(Model::kCols == 3); + static_assert(Model::kRows == 2); + + // Empty app list: nothing moves, indices stay put. + { + Model model; + assert(model.page_count() == 0); + assert(!model.move_row_right()); + assert(!model.move_row_left()); + assert(!model.move_up()); + assert(!model.move_down()); + assert(!model.flip_page(1)); + assert(!model.crossed_page()); + } + + // Exactly one page: right/left wrap inside the same row, up/down wrap + // through the rows, flips are no-ops, nothing crosses a page. + { + Model model; + model.set_app_count(4); + assert(model.page_count() == 1); + assert(model.move_row_right() && model.index() == 1 && !model.crossed_page()); + assert(model.move_row_right() && model.index() == 2 && !model.crossed_page()); + // Right past the row end wraps to the row start of the same page. + assert(model.move_row_right() && model.index() == 0 && !model.crossed_page()); + assert(model.moved_forward()); + // Left from the row start wraps to the row end of the same page. + assert(model.move_row_left() && model.index() == 2 && !model.crossed_page()); + assert(!model.moved_forward()); + assert(model.move_row_left() && model.index() == 1); + assert(model.move_row_left() && model.index() == 0); + // Down from app 0 wraps within the page: (0 + 3) % 4 = 3. + assert(model.move_down() && model.index() == 3 && !model.crossed_page()); + // Up from app 3 wraps back: (3 - 3 + 4) % 4 = 0. + assert(model.move_up() && model.index() == 0); + // Direct page flips need at least two pages. + assert(!model.flip_page(1)); + assert(!model.flip_page(-1)); + } + + // Two full pages: row moves stay in the row, edge moves flip pages at + // the same row, up/down swap rows and cross the page boundary by stride. + { + Model model; + model.set_app_count(12); + assert(model.page_count() == 2); + + assert(model.move_row_right() && model.index() == 1 && !model.crossed_page()); + assert(model.move_row_right() && model.index() == 2 && !model.crossed_page()); + assert(model.move_row_right() && model.index() == 6); + assert(model.crossed_page() && model.moved_forward()); + assert(model.move_row_left() && model.index() == 2); + assert(model.crossed_page() && !model.moved_forward()); + + model.set_index(9); // page 1, row 1, col 0 + assert(model.move_row_left() && model.index() == 5); + assert(model.crossed_page() && !model.moved_forward()); + model.set_index(11); // page 1, row 1, col 2: right wraps to page 0 + assert(model.move_row_right() && model.index() == 3); + assert(model.crossed_page() && model.moved_forward()); + + model.set_index(0); + assert(model.move_down() && model.index() == 3 && !model.crossed_page()); + assert(model.move_down() && model.index() == 6 && model.crossed_page()); + assert(model.moved_forward()); + assert(model.move_up() && model.index() == 3 && model.crossed_page()); + assert(!model.moved_forward()); + + // I/O flips keep the cell position. + model.set_index(7); // page 1, cell 1 + assert(model.flip_page(-1) && model.index() == 1); + assert(model.crossed_page() && !model.moved_forward()); + assert(model.flip_page(1) && model.index() == 7 && model.moved_forward()); + } + + // Ragged list (13 apps = two pages plus a single app on page 3): the + // last page shows one app and empty cells; every edge move lands on a + // real app, and LEFT from the very first app reaches the last page. + { + Model model; + model.set_app_count(13); + assert(model.page_count() == 3); + + model.set_index(0); // Settings, page 0 row 0 col 0 + assert(model.move_row_left() && model.index() == 12); + assert(model.crossed_page() && !model.moved_forward()); + // And back: right past the very last app wraps to the front. + assert(model.move_row_right() && model.index() == 0); + assert(model.crossed_page() && model.moved_forward()); + + model.set_index(11); // page 1, row 1, col 2 + assert(model.move_row_right() && model.index() == 12); + assert(model.crossed_page() && model.moved_forward()); // clamped real app + model.set_index(12); + assert(model.move_row_left() && model.index() == 8); + assert(model.crossed_page() && !model.moved_forward()); // page 1 row 0 col 2 + + model.set_index(2); // page 0, row 0, col 2 + assert(model.move_row_right() && model.index() == 6 && model.crossed_page()); + model.set_index(6); + assert(model.move_row_left() && model.index() == 2 && model.crossed_page()); + + // Up/down stride still wraps modulo the app count. + model.set_index(12); + assert(model.move_up() && model.index() == 9 && model.crossed_page()); + assert(model.move_down() && model.index() == 12 && model.crossed_page()); + model.set_index(12); + assert(model.move_down() && model.index() == 2 && model.crossed_page()); + + // I/O flip onto the ragged page keeps the cell when it exists. + model.set_index(6); + assert(model.flip_page(1) && model.index() == 12 && model.moved_forward()); + assert(model.flip_page(1) && model.index() == 0 && model.moved_forward()); + // Clamp when the kept cell would be past the end: page 1 cell 5 is + // real (app 11), page 2 cell 5 is not -> clamp to app 12. + model.set_index(11); + assert(model.flip_page(1) && model.index() == 12); + assert(model.crossed_page() && model.moved_forward()); + } + + return 0; +} diff --git a/projects/APPLaunch/tests/test_lockscreen_contract.py b/projects/APPLaunch/tests/test_lockscreen_contract.py index 338e84cf..ab443181 100644 --- a/projects/APPLaunch/tests/test_lockscreen_contract.py +++ b/projects/APPLaunch/tests/test_lockscreen_contract.py @@ -147,3 +147,32 @@ assert "void restore_backlight(int raw);" in CONTROLS_HEADER assert "write_backlight_raw(0)" in CONTROLS assert "if (raw <= 0) return;" in CONTROLS + +# ---- screen-off power staging ------------------------------------------- +# Stage 1 (backlight dark) also stands down the periodic UI refreshers and the +# red status LED; stage 2, after the configured delay, blanks the SPI panel, +# pins the CPU governor and stops the LVGL timers until a key arrives. Every +# exit path must reverse the stage before restoring the backlight. +assert "cp0_status_pause_set(1)" in SOURCE +assert "cp0_status_pause_set(0)" in SOURCE +assert "cp0_status_led_suspend()" in SOURCE +assert "cp0_status_led_restore()" in SOURCE +assert "void deep_sleep_enter()" in SOURCE +assert "void deep_sleep_exit()" in SOURCE +assert "cp0_panel_fb_blank(1)" in SOURCE +assert "cp0_panel_fb_blank(0)" in SOURCE +assert "cp0_cpufreq_powersave_set(1)" in SOURCE +assert "cp0_cpufreq_powersave_set(0)" in SOURCE +# Stage 2 drops the Bluetooth radio and any LED re-registration relight; the +# wake path powers Bluetooth back up. +assert "cp0_bluetooth_power_set_async(0)" in SOURCE +assert "cp0_bluetooth_power_set_async(1)" in SOURCE +# The timer stop is what makes the process sleep on the input semaphore; the +# key path must always bring the timers back before the lock flow runs. +assert "lv_timer_enable(false)" in SOURCE +assert "lv_timer_enable(true)" in SOURCE +assert 'cp0_signal_config_api({"GetInt", "panel_sleep_time", "30"}' in SOURCE +# The wake order inside the release: panel first, then backlight, LED and the +# refresh pause together with it. +assert "deep_sleep_exit();" in SOURCE +assert SOURCE.count("deep_sleep_exit();") >= 4 diff --git a/projects/APPLaunch/tests/test_power_contract.py b/projects/APPLaunch/tests/test_power_contract.py new file mode 100644 index 00000000..a529fcca --- /dev/null +++ b/projects/APPLaunch/tests/test_power_contract.py @@ -0,0 +1,137 @@ +# SPDX-FileCopyrightText: 2026 M5Stack Technology CO LTD +# +# SPDX-License-Identifier: MIT + +"""Wiring contract for the screen-off power staging. + +The launcher's ui_screensaver.cpp drives the stages; this pins the platform +half (status pause flag, LED/governor/panel helpers, the paused callbacks and +the network polling hold) and the packaging that makes the sysfs nodes +writable for the device user. +""" + +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +PLATFORM = ROOT / "../../ext_components/cp0_lvgl" + +PAUSE_HEADER = (PLATFORM / "include/cp0_status_pause.h").read_text() +PAUSE_IMPL = (PLATFORM / "src/cp0_status_pause.c").read_text() +PAGE = (PLATFORM / "src/ui_app_page.cpp").read_text() +NETWORK = (PLATFORM / "src/cp0/cp0_lvgl_network.cpp").read_text() +SETTINGS_DEVICE = (PLATFORM / "src/cp0/cp0_lvgl_settings.cpp").read_text() +SETTINGS_SDL = (PLATFORM / "src/sdl/sdl_lvgl_settings.cpp").read_text() +BLUETOOTH = (PLATFORM / "src/cp0/cp0_lvgl_bluetooth.cpp").read_text() +APP_HEADER = (PLATFORM / "include/cp0_lvgl_app.h").read_text() +PACKAGER = (ROOT / "../../scripts/debian_packager.py").read_text() +SCREENSAVER = (ROOT / "main/ui/ui_screensaver.cpp").read_text() +RUNNER = (PLATFORM / "src/cp0/cp0_external_app_runner.cpp").read_text() + +# The pause flag crosses layers as a plain C symbol, same pattern as +# LVGL_RUN_FLAGE: set from the launcher, read from the top bar and the +# network worker. +assert "void cp0_status_pause_set(int paused);" in PAUSE_HEADER +assert "int cp0_status_pause_get(void);" in PAUSE_HEADER +assert "static volatile int s_status_pause" in PAUSE_IMPL + +# The top bar's per-second clock, the 5 s status poll and battery events all +# stand down while the panel is dark; each callback gates before touching +# LVGL or the bus. +assert PAGE.count("cp0_status_pause_get()") >= 3 +assert "void AppTopBarRegion::time_timer_cb" in PAGE +assert "void AppTopBarRegion::status_timer_cb" in PAGE +assert "void AppTopBarRegion::battery_event_cb" in PAGE + +# The network worker holds *all* polling during the dark period (no 60 s +# hidden backstop either) and refreshes right after the flag clears. Nothing +# here disconnects Wi-Fi; only observation pauses. +assert "#include \"cp0_status_pause.h\"" in NETWORK +assert "if (cp0_status_pause_get())" in NETWORK +assert "Wi-Fi" in NETWORK or "wifi" in NETWORK.lower() + +# Device implementations exist next to the backlight sysfs helpers; the SDL +# simulator gets no-ops. +for symbol in ( + "cp0_status_led_suspend", + "cp0_status_led_restore", + "cp0_cpufreq_powersave_set", + "cp0_cpufreq_wake_reset", + "cp0_panel_fb_blank", +): + assert f"int {symbol}(void)" in APP_HEADER or f"{symbol}(" in APP_HEADER + assert f'"{symbol}"' not in SETTINGS_DEVICE + assert f"{symbol}(void)" in SETTINGS_DEVICE or f"{symbol}(int" in SETTINGS_DEVICE + assert symbol in SETTINGS_SDL + +# The Bluetooth radio staging rides the platform's own bluez client with an +# extern C fire-and-forget wrapper; the backend compiles for both profiles. +assert "void cp0_bluetooth_power_set_async(int enabled);" in APP_HEADER +assert "cp0_bluetooth_power_set_async(int enabled)" in BLUETOOTH +assert "set_power_async(enabled, nullptr)" in BLUETOOTH + +# Deep sleep no longer drops the radio unconditionally: the power-down rides an +# async worker (the file's stored-future pattern, no raw std::thread) that +# probes the mixer first, so music actually rendering through a connected +# speaker keeps its A2DP link until the next wake, while a failed probe still +# counts as idle (power saving stays the default). +assert "State: RUNNING" in SCREENSAVER +assert "any_sink_rendering()" in SCREENSAVER +assert "drop_bluetooth_for_deep_sleep()" in SCREENSAVER +assert "if (!any_sink_rendering())" in SCREENSAVER +assert "s_bluetooth_sleep_power_future" in SCREENSAVER +assert "std::async(std::launch::async" in SCREENSAVER + +# While an external app owns the screen the LVGL thread is blocked inside +# ExecBlocking, so the runner's supervision loop carries the idle staging: +# after dark_time with no key activity and no audible media the backlight +# goes dark (stage 1 only), any key press lights it back up, and media +# actually rendering (radio/music/TV) suppresses the staging entirely so the +# panel stays on for the session. Deep sleep must stay launcher-home-only: +# the keyboard queue drops events while an app is foreground, so a +# deep-sleeping launcher could never be woken by a key. +assert "pactl list sinks" in RUNNER +assert "pw-record" in RUNNER +assert "stream.capture.sink=true" in RUNNER +assert "any_media_rendering()" in RUNNER +assert "kAudioPeakThreshold" in RUNNER +assert '"dark_time"' in RUNNER +assert "cp0_status_led_suspend()" in RUNNER +assert "cp0_status_led_restore()" in RUNNER +assert "restore_stage()" in RUNNER +assert "cp0_panel_fb_blank" not in RUNNER +assert "cp0_cpufreq_powersave_set" not in RUNNER +assert "cp0_bluetooth_power_set_async" not in RUNNER + +# Streaming under Wi-Fi PSM stalls the fetch and gaps the audio, so the +# supervision toggles power save off while media renders and restores it +# when idle or on app exit - riding a narrow sudoers rule shipped by the +# deb for exactly the two iw commands. A missing rule degrades to today's +# behaviour (PSM stays on), never to a broken audio path. +assert "wifi_power_save_set" in RUNNER +assert "sudo -n /usr/sbin/iw dev wlan0 set power_save" in RUNNER +assert "set power_save off" in RUNNER +assert "set power_save on" in RUNNER +assert "wifi_psm_off" in RUNNER +assert "applaunch-wifi-psm" in PACKAGER +assert "/usr/sbin/iw dev wlan0 set power_save off" in PACKAGER +assert "/usr/sbin/iw dev wlan0 set power_save on" in PACKAGER +assert "mode=0o440" in PACKAGER + +# The LED stage saves the active trigger token before detaching it, so the +# red status led comes back with its original behaviour. +assert "active_trigger_token" in SETTINGS_DEVICE +assert '"/sys/class/leds/ACT"' in SETTINGS_DEVICE +assert "FB_BLANK_POWERDOWN" in SETTINGS_DEVICE +assert "FB_BLANK_UNBLANK" in SETTINGS_DEVICE + +# The package ships the tmpfiles rule granting the gpio group write access to +# the staged nodes, mirroring the image's cardputerzero-leds.conf, and the +# postinst applies it immediately. +assert "applaunch-power.conf" in PACKAGER +assert "61-applaunch-power.rules" in PACKAGER +assert "chgrp gpio" in PACKAGER +assert "scaling_governor" in PACKAGER +assert "0664 root gpio" in PACKAGER +assert "systemd-tmpfiles --create" in PACKAGER +assert "TMPFILES_PATH = PurePosixPath(\"usr/lib/tmpfiles.d\")" in PACKAGER diff --git a/scripts/debian_packager.py b/scripts/debian_packager.py index 78b05b14..37a20c1a 100755 --- a/scripts/debian_packager.py +++ b/scripts/debian_packager.py @@ -38,6 +38,8 @@ SYSTEM_SERVICE_PATH = PurePosixPath("usr/lib/systemd/system") POLKIT_RULES_PATH = PurePosixPath("usr/share/polkit-1/rules.d") LIBEXEC_PATH = PurePosixPath("usr/libexec") +TMPFILES_PATH = PurePosixPath("usr/lib/tmpfiles.d") +UDEV_RULES_PATH = PurePosixPath("usr/lib/udev/rules.d") LAUNCHER_UPDATE_ABI = "1" OPTIONAL_BINARIES = ( @@ -253,6 +255,7 @@ def _postinst_text(config: PackageConfig) -> str: mkdir -p /var/cache/{config.app_name} chown 1000:1000 /var/cache/{config.app_name} || true ln -sfn /var/cache/{config.app_name} /usr/share/{config.app_name}/cache +{_postinst_tmpfiles_snippet()} SERVICE_NAME="{service_name}" SERVICE_FILE="{service_file}" {adb_migration} @@ -279,6 +282,7 @@ def _postinst_text(config: PackageConfig) -> str: mkdir -p /var/cache/{config.app_name} chown 1000:1000 /var/cache/{config.app_name} || true ln -sfn /var/cache/{config.app_name} /usr/share/{config.app_name}/cache +{_postinst_tmpfiles_snippet()} APP_UID=1000 APP_USER="$(getent passwd "$APP_UID" | cut -d: -f1)" APP_GID="$(getent passwd "$APP_UID" | cut -d: -f4)" @@ -426,6 +430,48 @@ def _apt_update_service_text() -> str: """ +def _power_tmpfiles_text() -> str: + return """# Screen-off power staging permissions for the launcher. +# The launcher (device user, gpio group) stages the red status LED, the +# cpufreq governor and the panel blank ioctl when the panel is dark. Same +# pattern as the image's cardputerzero-leds.conf. +z /sys/class/leds/ACT/brightness 0664 root gpio - +z /sys/class/leds/ACT/trigger 0664 root gpio - +z /sys/devices/system/cpu/cpufreq/policy0/scaling_governor 0664 root gpio - +z /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor 0664 root gpio - +""" + + +def _postinst_tmpfiles_snippet() -> str: + return """# Apply the screen-off power staging permissions right away (normally done +# by systemd-tmpfiles-setup at boot). Only the APPLaunch package ships the +# conf; other packages reusing this builder simply skip the block. +if [ -f /usr/lib/tmpfiles.d/applaunch-power.conf ] && command -v systemd-tmpfiles >/dev/null 2>&1; then + systemd-tmpfiles --create /usr/lib/tmpfiles.d/applaunch-power.conf >/dev/null 2>&1 || true +fi +""" + + +def _wifi_psm_sudoers_text() -> str: + return """# Wi-Fi power save toggle for the launcher's media supervision. +# Streaming under Wi-Fi PSM stalls the TCP fetch (radio/music/TV) and gaps +# the audio audibly through Bluetooth speakers, so the supervision drops +# PSM only while media is actually rendering and restores it when idle. +# Narrow rule: these two exact commands, nothing else. (uid 1000 = pi) +pi ALL=(root) NOPASSWD: /usr/sbin/iw dev wlan0 set power_save off, /usr/sbin/iw dev wlan0 set power_save on +""" + + +def _power_udev_rules_text() -> str: + return """# Screen-off power staging permissions, re-applied on hotplug: the ACT +# status LED classdev can be re-registered by a deferred probe after boot, +# which resets its permissions and relights the default trigger. Same +# pattern as the image's 60-cardputerzero-leds.rules. +ACTION=="add", SUBSYSTEM=="leds", KERNEL=="ACT", RUN+="/bin/chgrp gpio $sys$devpath/brightness", RUN+="/bin/chmod g+w $sys$devpath/brightness" +ACTION=="add", SUBSYSTEM=="leds", KERNEL=="ACT", RUN+="/bin/chgrp gpio $sys$devpath/trigger", RUN+="/bin/chmod g+w $sys$devpath/trigger" +""" + + def _updater_polkit_text() -> str: return """// Permit a local administrator to start only the fixed updater units. // APPLaunch runs as a systemd user service, so it is not attached to the @@ -1029,6 +1075,18 @@ def prepare_package_tree( "applaunch-apps-updater", _apps_updater_script_text(), mode=0o755, ) + _write_text( + paths.package_root / Path(*TMPFILES_PATH.parts) / "applaunch-power.conf", + _power_tmpfiles_text(), + ) + _write_text( + paths.package_root / Path(*UDEV_RULES_PATH.parts) / "61-applaunch-power.rules", + _power_udev_rules_text(), + ) + _write_text( + paths.package_root / "etc" / "sudoers.d" / "applaunch-wifi-psm", + _wifi_psm_sudoers_text(), mode=0o440, + ) print(f"Staged package tree: {paths.package_root}") print(f" binary: {binary}")