From 7d369b2c35676857595c0e41f3d688dacdde593d Mon Sep 17 00:00:00 2001 From: cottongin Date: Wed, 18 Nov 2026 08:40:56 -0500 Subject: [PATCH] feat(device-ui): add 320x170 shadcn Bento UI, modals, and keyboard controller --- device-ui/CMakeLists.txt | 91 +- device-ui/src/app_ui.cpp | 1364 ++++++++++++++++++++++++ device-ui/src/app_ui.hpp | 49 + device-ui/src/main.cpp | 676 ++++++++++++ device-ui/src/ui_controller.cpp | 658 ++++++++++++ device-ui/src/ui_controller.hpp | 145 +++ device-ui/tests/test_ui_navigation.cpp | 446 ++++++++ 7 files changed, 3428 insertions(+), 1 deletion(-) create mode 100644 device-ui/src/app_ui.cpp create mode 100644 device-ui/src/app_ui.hpp create mode 100644 device-ui/src/main.cpp create mode 100644 device-ui/src/ui_controller.cpp create mode 100644 device-ui/src/ui_controller.hpp create mode 100644 device-ui/tests/test_ui_navigation.cpp diff --git a/device-ui/CMakeLists.txt b/device-ui/CMakeLists.txt index 5dd0c8e..8e6ddd5 100644 --- a/device-ui/CMakeLists.txt +++ b/device-ui/CMakeLists.txt @@ -11,10 +11,26 @@ option(CP0_UI_TARGET_DEVICE "Target CardputerZero Linux fbdev/evdev instead of S find_package(SQLite3 REQUIRED) find_package(Threads REQUIRED) +find_package(PkgConfig QUIET) + +# Optional LVGL v9 discovery (never download over network via FetchContent) +set(CP0_LVGL_TARGET "") +find_package(lvgl QUIET) +if(TARGET lvgl::lvgl) + set(CP0_LVGL_TARGET lvgl::lvgl) +elseif(TARGET lvgl) + set(CP0_LVGL_TARGET lvgl) +elseif(PkgConfig_FOUND) + pkg_check_modules(LVGL QUIET IMPORTED_TARGET lvgl) + if(TARGET PkgConfig::LVGL) + set(CP0_LVGL_TARGET PkgConfig::LVGL) + endif() +endif() add_library(cp0_ui_core STATIC src/theme.cpp src/ipc_client.cpp + src/ui_controller.cpp ) target_include_directories(cp0_ui_core PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/src @@ -27,7 +43,70 @@ endif() target_compile_options(cp0_ui_core PRIVATE -Wall -Wextra -Wpedantic) if(CP0_UI_BUILD_APP) - message(STATUS "CP0_UI_BUILD_APP=ON: app target will be configured in Task 6") + set(CP0_FREETYPE_TARGET "") + find_package(Freetype QUIET) + if(TARGET Freetype::Freetype) + set(CP0_FREETYPE_TARGET Freetype::Freetype) + elseif(PkgConfig_FOUND) + pkg_check_modules(FREETYPE QUIET IMPORTED_TARGET freetype2) + if(TARGET PkgConfig::FREETYPE) + set(CP0_FREETYPE_TARGET PkgConfig::FREETYPE) + endif() + endif() + + add_executable(cp0-sync-ui + src/app_ui.cpp + src/main.cpp + ) + target_link_libraries(cp0-sync-ui PRIVATE + cp0_ui_core + Threads::Threads + ) + target_compile_options(cp0-sync-ui PRIVATE -Wall -Wextra -Wpedantic) + + if(CP0_FREETYPE_TARGET) + target_compile_definitions(cp0-sync-ui PRIVATE CP0_HAS_FREETYPE=1) + target_link_libraries(cp0-sync-ui PRIVATE ${CP0_FREETYPE_TARGET}) + message(STATUS "FreeType2 enabled via ${CP0_FREETYPE_TARGET}") + else() + message(STATUS "FreeType2 not found: using built-in 5x7 bitmap fallback") + endif() + + if(CP0_LVGL_TARGET) + target_compile_definitions(cp0-sync-ui PRIVATE CP0_HAS_LVGL=1) + target_link_libraries(cp0-sync-ui PRIVATE ${CP0_LVGL_TARGET}) + message(STATUS "LVGL detected via ${CP0_LVGL_TARGET}") + else() + message(STATUS "LVGL not installed: using built-in 320x170 ShadcnCanvas renderer") + endif() + + if(CP0_UI_TARGET_DEVICE) + target_compile_definitions(cp0-sync-ui PRIVATE CP0_UI_TARGET_DEVICE=1) + message(STATUS "Target backend: Linux fbdev + evdev") + else() + set(CP0_SDL2_TARGET "") + if(PkgConfig_FOUND) + pkg_check_modules(SDL2 QUIET IMPORTED_TARGET sdl2) + if(TARGET PkgConfig::SDL2) + set(CP0_SDL2_TARGET PkgConfig::SDL2) + endif() + endif() + if(NOT CP0_SDL2_TARGET) + find_package(SDL2 REQUIRED) + if(TARGET SDL2::SDL2) + set(CP0_SDL2_TARGET SDL2::SDL2) + endif() + endif() + if(CP0_SDL2_TARGET) + target_link_libraries(cp0-sync-ui PRIVATE ${CP0_SDL2_TARGET}) + else() + target_include_directories(cp0-sync-ui PRIVATE ${SDL2_INCLUDE_DIRS}) + target_link_libraries(cp0-sync-ui PRIVATE ${SDL2_LIBRARIES}) + endif() + message(STATUS "Target backend: SDL2 320x170 simulator") + endif() + + install(TARGETS cp0-sync-ui RUNTIME DESTINATION bin) endif() if(CP0_UI_BUILD_TESTS) @@ -41,4 +120,14 @@ if(CP0_UI_BUILD_TESTS) ) target_compile_options(test_ipc_and_theme PRIVATE -Wall -Wextra -Wpedantic) add_test(NAME test_ipc_and_theme COMMAND test_ipc_and_theme) + + add_executable(test_ui_navigation + tests/test_ui_navigation.cpp + ) + target_link_libraries(test_ui_navigation PRIVATE + cp0_ui_core + Threads::Threads + ) + target_compile_options(test_ui_navigation PRIVATE -Wall -Wextra -Wpedantic) + add_test(NAME test_ui_navigation COMMAND test_ui_navigation) endif() diff --git a/device-ui/src/app_ui.cpp b/device-ui/src/app_ui.cpp new file mode 100644 index 0000000..155da59 --- /dev/null +++ b/device-ui/src/app_ui.cpp @@ -0,0 +1,1364 @@ +#include "app_ui.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(CP0_HAS_LVGL) +#include +#endif + +#if defined(CP0_HAS_FREETYPE) +#include +#include FT_FREETYPE_H +#endif + +namespace cp0 { + +namespace { + +// --------------------------------------------------------------------------- +// Formatting helpers +// --------------------------------------------------------------------------- + +std::string format_bytes(int64_t bytes) { + if (bytes < 0) { + bytes = 0; + } + std::ostringstream oss; + if (bytes < 1024) { + oss << bytes << " B"; + } else if (bytes < 1024LL * 1024) { + oss << std::fixed << std::setprecision(1) << (static_cast(bytes) / 1024.0) << " KB"; + } else if (bytes < 1024LL * 1024 * 1024) { + oss << std::fixed << std::setprecision(1) + << (static_cast(bytes) / (1024.0 * 1024.0)) << " MB"; + } else { + oss << std::fixed << std::setprecision(2) + << (static_cast(bytes) / (1024.0 * 1024.0 * 1024.0)) << " GB"; + } + return oss.str(); +} + +std::string format_hhmmss(int64_t ts_ms) { + if (ts_ms <= 0) { + return "--:--:--"; + } + std::time_t secs = static_cast(ts_ms / 1000); + std::tm tm_val{}; + if (::localtime_r(&secs, &tm_val) == nullptr) { + return "--:--:--"; + } + char buf[16]; + std::snprintf( + buf, + sizeof(buf), + "%02d:%02d:%02d", + tm_val.tm_hour, + tm_val.tm_min, + tm_val.tm_sec + ); + return std::string(buf); +} + +std::string short_log_tag(const std::string& level) { + if (level == "ERROR" || level == "ERR") { + return "ER"; + } + if (level == "WARN" || level == "WARNING") { + return "WN"; + } + if (level == "OK") { + return "OK"; + } + return "IN"; +} + +// --------------------------------------------------------------------------- +// Built-in 5x7 ASCII bitmap font (0x20..0x7E) fallback +// --------------------------------------------------------------------------- + +// Each glyph is 5 columns x 7 rows, packed as 5 bytes where bit 0 = top row, bit 6 = bottom row. +constexpr std::array, 95> kFont5x7 = {{ + {0x00, 0x00, 0x00, 0x00, 0x00}, // ' ' + {0x00, 0x00, 0x5f, 0x00, 0x00}, // '!' + {0x00, 0x07, 0x00, 0x07, 0x00}, // '"' + {0x14, 0x7f, 0x14, 0x7f, 0x14}, // '#' + {0x24, 0x2a, 0x7f, 0x2a, 0x12}, // '$' + {0x23, 0x13, 0x08, 0x64, 0x62}, // '%' + {0x36, 0x49, 0x55, 0x22, 0x50}, // '&' + {0x00, 0x05, 0x03, 0x00, 0x00}, // '\'' + {0x00, 0x1c, 0x22, 0x41, 0x00}, // '(' + {0x00, 0x41, 0x22, 0x1c, 0x00}, // ')' + {0x14, 0x08, 0x3e, 0x08, 0x14}, // '*' + {0x08, 0x08, 0x3e, 0x08, 0x08}, // '+' + {0x00, 0x50, 0x30, 0x00, 0x00}, // ',' + {0x08, 0x08, 0x08, 0x08, 0x08}, // '-' + {0x00, 0x60, 0x60, 0x00, 0x00}, // '.' + {0x20, 0x10, 0x08, 0x04, 0x02}, // '/' + {0x3e, 0x51, 0x49, 0x45, 0x3e}, // '0' + {0x00, 0x42, 0x7f, 0x40, 0x00}, // '1' + {0x42, 0x61, 0x51, 0x49, 0x46}, // '2' + {0x21, 0x41, 0x45, 0x4b, 0x31}, // '3' + {0x18, 0x14, 0x12, 0x7f, 0x10}, // '4' + {0x27, 0x45, 0x45, 0x45, 0x39}, // '5' + {0x3c, 0x4a, 0x49, 0x49, 0x30}, // '6' + {0x01, 0x71, 0x09, 0x05, 0x03}, // '7' + {0x36, 0x49, 0x49, 0x49, 0x36}, // '8' + {0x06, 0x49, 0x49, 0x29, 0x1e}, // '9' + {0x00, 0x36, 0x36, 0x00, 0x00}, // ':' + {0x00, 0x56, 0x36, 0x00, 0x00}, // ';' + {0x08, 0x14, 0x22, 0x41, 0x00}, // '<' + {0x14, 0x14, 0x14, 0x14, 0x14}, // '=' + {0x00, 0x41, 0x22, 0x14, 0x08}, // '>' + {0x02, 0x01, 0x51, 0x09, 0x06}, // '?' + {0x32, 0x49, 0x79, 0x41, 0x3e}, // '@' + {0x7e, 0x11, 0x11, 0x11, 0x7e}, // 'A' + {0x7f, 0x49, 0x49, 0x49, 0x36}, // 'B' + {0x3e, 0x41, 0x41, 0x41, 0x22}, // 'C' + {0x7f, 0x41, 0x41, 0x22, 0x1c}, // 'D' + {0x7f, 0x49, 0x49, 0x49, 0x41}, // 'E' + {0x7f, 0x09, 0x09, 0x09, 0x01}, // 'F' + {0x3e, 0x41, 0x49, 0x49, 0x7a}, // 'G' + {0x7f, 0x08, 0x08, 0x08, 0x7f}, // 'H' + {0x00, 0x41, 0x7f, 0x41, 0x00}, // 'I' + {0x20, 0x40, 0x41, 0x3f, 0x01}, // 'J' + {0x7f, 0x08, 0x14, 0x22, 0x41}, // 'K' + {0x7f, 0x40, 0x40, 0x40, 0x40}, // 'L' + {0x7f, 0x02, 0x0c, 0x02, 0x7f}, // 'M' + {0x7f, 0x04, 0x08, 0x10, 0x7f}, // 'N' + {0x3e, 0x41, 0x41, 0x41, 0x3e}, // 'O' + {0x7f, 0x09, 0x09, 0x09, 0x06}, // 'P' + {0x3e, 0x41, 0x51, 0x21, 0x5e}, // 'Q' + {0x7f, 0x09, 0x19, 0x29, 0x46}, // 'R' + {0x46, 0x49, 0x49, 0x49, 0x31}, // 'S' + {0x01, 0x01, 0x7f, 0x01, 0x01}, // 'T' + {0x3f, 0x40, 0x40, 0x40, 0x3f}, // 'U' + {0x1f, 0x20, 0x40, 0x20, 0x1f}, // 'V' + {0x3f, 0x40, 0x38, 0x40, 0x3f}, // 'W' + {0x63, 0x14, 0x08, 0x14, 0x63}, // 'X' + {0x07, 0x08, 0x70, 0x08, 0x07}, // 'Y' + {0x61, 0x51, 0x49, 0x45, 0x43}, // 'Z' + {0x00, 0x7f, 0x41, 0x41, 0x00}, // '[' + {0x02, 0x04, 0x08, 0x10, 0x20}, // '\' + {0x00, 0x41, 0x41, 0x7f, 0x00}, // ']' + {0x04, 0x02, 0x01, 0x02, 0x04}, // '^' + {0x40, 0x40, 0x40, 0x40, 0x40}, // '_' + {0x00, 0x01, 0x02, 0x04, 0x00}, // '`' + {0x20, 0x54, 0x54, 0x54, 0x78}, // 'a' + {0x7f, 0x48, 0x44, 0x44, 0x38}, // 'b' + {0x38, 0x44, 0x44, 0x44, 0x20}, // 'c' + {0x38, 0x44, 0x44, 0x48, 0x7f}, // 'd' + {0x38, 0x54, 0x54, 0x54, 0x18}, // 'e' + {0x08, 0x7e, 0x09, 0x01, 0x02}, // 'f' + {0x0c, 0x52, 0x52, 0x52, 0x3e}, // 'g' + {0x7f, 0x08, 0x04, 0x04, 0x78}, // 'h' + {0x00, 0x44, 0x7d, 0x40, 0x00}, // 'i' + {0x20, 0x40, 0x44, 0x3d, 0x00}, // 'j' + {0x7f, 0x10, 0x28, 0x44, 0x00}, // 'k' + {0x00, 0x41, 0x7f, 0x40, 0x00}, // 'l' + {0x7c, 0x04, 0x18, 0x04, 0x78}, // 'm' + {0x7c, 0x08, 0x04, 0x04, 0x78}, // 'n' + {0x38, 0x44, 0x44, 0x44, 0x38}, // 'o' + {0x7c, 0x14, 0x14, 0x14, 0x08}, // 'p' + {0x08, 0x14, 0x14, 0x18, 0x7c}, // 'q' + {0x7c, 0x08, 0x04, 0x04, 0x08}, // 'r' + {0x48, 0x54, 0x54, 0x54, 0x20}, // 's' + {0x04, 0x3f, 0x44, 0x40, 0x20}, // 't' + {0x3c, 0x40, 0x40, 0x20, 0x7c}, // 'u' + {0x1c, 0x20, 0x40, 0x20, 0x1c}, // 'v' + {0x3c, 0x40, 0x30, 0x40, 0x3c}, // 'w' + {0x44, 0x28, 0x10, 0x28, 0x44}, // 'x' + {0x0c, 0x50, 0x50, 0x50, 0x3c}, // 'y' + {0x44, 0x64, 0x54, 0x4c, 0x44}, // 'z' + {0x00, 0x08, 0x36, 0x41, 0x00}, // '{' + {0x00, 0x00, 0x7f, 0x00, 0x00}, // '|' + {0x00, 0x41, 0x36, 0x08, 0x00}, // '}' + {0x08, 0x04, 0x08, 0x10, 0x08}, // '~' +}}; + +enum class FontRole { + Sans, + Mono, +}; + +#if defined(CP0_HAS_FREETYPE) +struct CachedGlyph { + int width = 0; + int rows = 0; + int left = 0; + int top = 0; + int advance_x = 0; + std::vector alpha; +}; +#endif + +// --------------------------------------------------------------------------- +// 320x170 Anti-Aliased Software Framebuffer + FreeType2 / Fallback Renderer +// --------------------------------------------------------------------------- + +class ShadcnCanvas { +public: + static constexpr int kW = LvglAppView::kWidth; + static constexpr int kH = LvglAppView::kHeight; + + ShadcnCanvas() : buf_(static_cast(kW * kH), 0xff09090bU) { + init_fonts(); + } + + ~ShadcnCanvas() { +#if defined(CP0_HAS_FREETYPE) + if (sans_face_ != nullptr) { + FT_Done_Face(sans_face_); + sans_face_ = nullptr; + } + if (mono_face_ != nullptr) { + FT_Done_Face(mono_face_); + mono_face_ = nullptr; + } + if (ft_lib_ != nullptr) { + FT_Done_FreeType(ft_lib_); + ft_lib_ = nullptr; + } +#endif + } + + bool using_freetype() const { return has_ft_sans_ || has_ft_mono_; } + + const uint32_t* pixels() const { return buf_.data(); } + + void clear(uint32_t rgb) { + uint32_t argb = 0xff000000U | (rgb & 0x00ffffffU); + std::fill(buf_.begin(), buf_.end(), argb); + } + + void dim_rect(int x, int y, int w, int h, uint32_t rgb, uint8_t alpha) { + int x0 = std::max(0, x); + int y0 = std::max(0, y); + int x1 = std::min(kW, x + w); + int y1 = std::min(kH, y + h); + for (int py = y0; py < y1; ++py) { + for (int px = x0; px < x1; ++px) { + blend_pixel(px, py, rgb, alpha); + } + } + } + + void fill_rect(int x, int y, int w, int h, uint32_t rgb) { + int x0 = std::max(0, x); + int y0 = std::max(0, y); + int x1 = std::min(kW, x + w); + int y1 = std::min(kH, y + h); + uint32_t argb = 0xff000000U | (rgb & 0x00ffffffU); + for (int py = y0; py < y1; ++py) { + for (int px = x0; px < x1; ++px) { + buf_[static_cast(py * kW + px)] = argb; + } + } + } + + void draw_round_box( + int x, + int y, + int w, + int h, + int radius, + uint32_t fill_rgb, + uint32_t border_rgb, + int border_w + ) { + if (w <= 0 || h <= 0) { + return; + } + float r = static_cast(std::max(0, std::min(radius, std::min(w, h) / 2))); + float hx = static_cast(w) * 0.5f; + float hy = static_cast(h) * 0.5f; + float cx = static_cast(x) + hx; + float cy = static_cast(y) + hy; + float bw = static_cast(std::max(0, border_w)); + + int x0 = std::max(0, x); + int y0 = std::max(0, y); + int x1 = std::min(kW, x + w); + int y1 = std::min(kH, y + h); + + for (int py = y0; py < y1; ++py) { + for (int px = x0; px < x1; ++px) { + float dx = std::abs((static_cast(px) + 0.5f) - cx) - (hx - r); + float dy = std::abs((static_cast(py) + 0.5f) - cy) - (hy - r); + float ox = std::max(dx, 0.0f); + float oy = std::max(dy, 0.0f); + float dist = std::hypot(ox, oy) + std::min(std::max(dx, dy), 0.0f) - r; + + float outer = std::clamp(0.5f - dist, 0.0f, 1.0f); + if (outer <= 0.001f) { + continue; + } + if (bw <= 0.0f) { + uint8_t a = static_cast(std::lround(outer * 255.0f)); + blend_pixel(px, py, fill_rgb, a); + continue; + } + float inner = std::clamp(0.5f - (dist + bw), 0.0f, 1.0f); + float edge = std::max(0.0f, outer - inner); + if (inner > 0.001f) { + uint8_t ia = static_cast(std::lround(inner * 255.0f)); + blend_pixel(px, py, fill_rgb, ia); + } + if (edge > 0.001f) { + uint8_t ba = static_cast(std::lround(edge * 255.0f)); + blend_pixel(px, py, border_rgb, ba); + } + } + } + } + + void draw_circle(float cx, float cy, float radius, uint32_t rgb, bool hollow = false) { + int x0 = std::max(0, static_cast(std::floor(cx - radius - 1.0f))); + int y0 = std::max(0, static_cast(std::floor(cy - radius - 1.0f))); + int x1 = std::min(kW, static_cast(std::ceil(cx + radius + 1.0f))); + int y1 = std::min(kH, static_cast(std::ceil(cy + radius + 1.0f))); + for (int py = y0; py < y1; ++py) { + for (int px = x0; px < x1; ++px) { + float d = std::hypot( + (static_cast(px) + 0.5f) - cx, + (static_cast(py) + 0.5f) - cy + ); + float alpha_f = 0.0f; + if (hollow) { + float ring_d = std::abs(d - radius); + alpha_f = std::clamp(0.75f - ring_d, 0.0f, 1.0f); + } else { + alpha_f = std::clamp(radius + 0.5f - d, 0.0f, 1.0f); + } + if (alpha_f > 0.01f) { + blend_pixel(px, py, rgb, static_cast(std::lround(alpha_f * 255.0f))); + } + } + } + } + + void draw_checkmark(int x, int y, uint32_t rgb) { + // Crisp 7x6 checkmark stroke + static constexpr std::array, 7> pts = {{ + {0, 3}, {1, 4}, {2, 5}, {3, 4}, {4, 3}, {5, 2}, {6, 1} + }}; + for (const auto& pt : pts) { + blend_pixel(x + pt.first, y + pt.second, rgb, 255); + blend_pixel(x + pt.first, y + pt.second + 1, rgb, 170); + } + } + + int measure_text(FontRole role, int px_size, const std::string& text) { +#if defined(CP0_HAS_FREETYPE) + FT_Face face = select_face(role); + if (face != nullptr) { + int width = 0; + for (unsigned char ch : text) { + if (ch < 0x20 || ch > 0x7e) { + ch = '?'; + } + const auto* g = get_glyph(role, face, px_size, ch); + width += (g != nullptr) ? g->advance_x : (px_size / 2); + } + return width; + } +#else + (void)role; +#endif + int scale = (px_size >= 14) ? 2 : 1; + return static_cast(text.size()) * 6 * scale; + } + + int line_height(FontRole role, int px_size) { +#if defined(CP0_HAS_FREETYPE) + FT_Face face = select_face(role); + if (face != nullptr) { + FT_Set_Pixel_Sizes(face, 0, static_cast(px_size)); + int h = static_cast(face->size->metrics.height >> 6); + return std::max(px_size, h); + } +#else + (void)role; +#endif + int scale = (px_size >= 14) ? 2 : 1; + return 8 * scale; + } + + std::string truncate_right(FontRole role, int px_size, const std::string& s, int max_w) { + if (max_w <= 0) { + return ""; + } + if (measure_text(role, px_size, s) <= max_w) { + return s; + } + const std::string ell = "..."; + if (measure_text(role, px_size, ell) > max_w) { + return ""; + } + std::string cur = s; + while (!cur.empty() && measure_text(role, px_size, cur + ell) > max_w) { + cur.pop_back(); + } + return cur + ell; + } + + std::string truncate_left_path(FontRole role, int px_size, const std::string& s, int max_w) { + if (max_w <= 0) { + return ""; + } + if (measure_text(role, px_size, s) <= max_w) { + return s; + } + const std::string ell = "..."; + int ell_w = measure_text(role, px_size, ell); + if (ell_w > max_w) { + return ""; + } + size_t pos = 0; + while (pos < s.size() && measure_text(role, px_size, ell + s.substr(pos)) > max_w) { + ++pos; + } + return ell + s.substr(pos); + } + + void draw_text( + FontRole role, + int px_size, + int x, + int y, + const std::string& text, + uint32_t rgb + ) { +#if defined(CP0_HAS_FREETYPE) + FT_Face face = select_face(role); + if (face != nullptr) { + FT_Set_Pixel_Sizes(face, 0, static_cast(px_size)); + int ascender = static_cast(face->size->metrics.ascender >> 6); + int baseline_y = y + ascender; + int pen_x = x; + for (unsigned char ch : text) { + if (ch < 0x20 || ch > 0x7e) { + ch = '?'; + } + const auto* g = get_glyph(role, face, px_size, ch); + if (g == nullptr) { + pen_x += px_size / 2; + continue; + } + int gx = pen_x + g->left; + int gy = baseline_y - g->top; + for (int r = 0; r < g->rows; ++r) { + for (int c = 0; c < g->width; ++c) { + uint8_t cov = g->alpha[static_cast(r * g->width + c)]; + if (cov > 0) { + blend_pixel(gx + c, gy + r, rgb, cov); + } + } + } + pen_x += g->advance_x; + } + return; + } +#else + (void)role; +#endif + int scale = (px_size >= 14) ? 2 : 1; + int pen_x = x; + for (unsigned char ch : text) { + if (ch < 0x20 || ch > 0x7e) { + ch = '?'; + } + const auto& glyph = kFont5x7[static_cast(ch - 0x20)]; + for (int col = 0; col < 5; ++col) { + uint8_t bits = glyph[static_cast(col)]; + for (int row = 0; row < 7; ++row) { + if ((bits & (1U << row)) != 0) { + fill_rect(pen_x + col * scale, y + row * scale, scale, scale, rgb); + } + } + } + pen_x += 6 * scale; + } + } + +private: + void init_fonts() { +#if defined(CP0_HAS_FREETYPE) + if (FT_Init_FreeType(&ft_lib_) != 0) { + ft_lib_ = nullptr; + return; + } + + auto try_load_list = [&](const std::vector& paths, FT_Face& out_face) -> bool { + for (const auto& p : paths) { + if (p.empty()) { + continue; + } + if (FT_New_Face(ft_lib_, p.c_str(), 0, &out_face) == 0) { + return true; + } + } + return false; + }; + + std::vector sans_candidates; + if (const char* env_sans = std::getenv("CP0_FONT_SANS")) { + sans_candidates.emplace_back(env_sans); + } else { + sans_candidates = { + "/usr/share/cp0-sync/fonts/Inter-Regular.ttf", + "/usr/share/cp0-sync/fonts/Inter.ttf", + "assets/fonts/Inter-Regular.ttf", + "assets/fonts/Inter.ttf", + "/usr/share/fonts/truetype/inter/Inter-Regular.ttf", + "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", + "/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf", + "/System/Library/Fonts/SFNS.ttf", + "/System/Library/Fonts/Geneva.ttf", + "/System/Library/Fonts/Helvetica.ttc", + }; + } + + std::vector mono_candidates; + if (const char* env_mono = std::getenv("CP0_FONT_MONO")) { + mono_candidates.emplace_back(env_mono); + } else { + mono_candidates = { + "/usr/share/cp0-sync/fonts/JetBrainsMono-Regular.ttf", + "/usr/share/cp0-sync/fonts/JetBrainsMono.ttf", + "assets/fonts/JetBrainsMono-Regular.ttf", + "assets/fonts/JetBrainsMono.ttf", + "/usr/share/fonts/truetype/jetbrains-mono/JetBrainsMono-Regular.ttf", + "/usr/share/fonts/truetype/dejavu/DejaVuSansMono.ttf", + "/usr/share/fonts/truetype/liberation/LiberationMono-Regular.ttf", + "/System/Library/Fonts/SFNSMono.ttf", + "/System/Library/Fonts/Monaco.ttf", + "/System/Library/Fonts/Menlo.ttc", + }; + } + + has_ft_sans_ = try_load_list(sans_candidates, sans_face_); + has_ft_mono_ = try_load_list(mono_candidates, mono_face_); +#endif + } + +#if defined(CP0_HAS_FREETYPE) + FT_Face select_face(FontRole role) const { + if (role == FontRole::Mono) { + return mono_face_ != nullptr ? mono_face_ : sans_face_; + } + return sans_face_ != nullptr ? sans_face_ : mono_face_; + } + + const CachedGlyph* get_glyph(FontRole role, FT_Face face, int px_size, uint32_t codepoint) { + uint64_t key = (static_cast(role == FontRole::Mono ? 1 : 0) << 48) | + (static_cast(px_size & 0xffff) << 32) | + static_cast(codepoint); + auto it = glyph_cache_.find(key); + if (it != glyph_cache_.end()) { + return &it->second; + } + + FT_Set_Pixel_Sizes(face, 0, static_cast(px_size)); + if (FT_Load_Char(face, codepoint, FT_LOAD_RENDER) != 0) { + return nullptr; + } + + FT_GlyphSlot slot = face->glyph; + CachedGlyph cg; + cg.width = static_cast(slot->bitmap.width); + cg.rows = static_cast(slot->bitmap.rows); + cg.left = slot->bitmap_left; + cg.top = slot->bitmap_top; + cg.advance_x = static_cast(slot->advance.x >> 6); + cg.alpha.resize(static_cast(cg.width * cg.rows)); + + if (slot->bitmap.pixel_mode == FT_PIXEL_MODE_GRAY) { + for (int r = 0; r < cg.rows; ++r) { + const uint8_t* src = slot->bitmap.buffer + r * slot->bitmap.pitch; + std::memcpy(cg.alpha.data() + r * cg.width, src, static_cast(cg.width)); + } + } else if (slot->bitmap.pixel_mode == FT_PIXEL_MODE_MONO) { + for (int r = 0; r < cg.rows; ++r) { + const uint8_t* src = slot->bitmap.buffer + r * slot->bitmap.pitch; + for (int c = 0; c < cg.width; ++c) { + uint8_t byte = src[c >> 3]; + bool on = (byte & (0x80U >> (c & 7))) != 0; + cg.alpha[static_cast(r * cg.width + c)] = on ? 255 : 0; + } + } + } + + auto [ins_it, _] = glyph_cache_.emplace(key, std::move(cg)); + return &ins_it->second; + } +#endif + + void blend_pixel(int x, int y, uint32_t fg_rgb, uint8_t alpha) { + if (x < 0 || x >= kW || y < 0 || y >= kH || alpha == 0) { + return; + } + size_t idx = static_cast(y * kW + x); + if (alpha == 255) { + buf_[idx] = 0xff000000U | (fg_rgb & 0x00ffffffU); + return; + } + uint32_t bg = buf_[idx]; + uint32_t a = alpha; + uint32_t inv = 255U - a; + uint32_t fr = (fg_rgb >> 16) & 0xffU; + uint32_t fg = (fg_rgb >> 8) & 0xffU; + uint32_t fb = fg_rgb & 0xffU; + uint32_t br = (bg >> 16) & 0xffU; + uint32_t bg_c = (bg >> 8) & 0xffU; + uint32_t bb = bg & 0xffU; + uint32_t rr = (fr * a + br * inv + 127U) / 255U; + uint32_t rg = (fg * a + bg_c * inv + 127U) / 255U; + uint32_t rb = (fb * a + bb * inv + 127U) / 255U; + buf_[idx] = 0xff000000U | (rr << 16) | (rg << 8) | rb; + } + + std::vector buf_; + bool has_ft_sans_ = false; + bool has_ft_mono_ = false; + +#if defined(CP0_HAS_FREETYPE) + FT_Library ft_lib_ = nullptr; + FT_Face sans_face_ = nullptr; + FT_Face mono_face_ = nullptr; + std::map glyph_cache_; +#endif +}; + +// --------------------------------------------------------------------------- +// Component drawing helpers matching Spec Section 5.4 +// --------------------------------------------------------------------------- + +void draw_kbd_hint( + ShadcnCanvas& canvas, + const ShadcnPalette& pal, + int& cursor_x, + int y, + const std::string& key_text, + const std::string& label +) { + int kw = canvas.measure_text(FontRole::Mono, 9, key_text) + 6; + canvas.draw_round_box(cursor_x, y, kw, 13, 3, pal.card, pal.border, 1); + canvas.draw_text(FontRole::Mono, 9, cursor_x + 3, y + 2, key_text, pal.foreground); + cursor_x += kw + 3; + canvas.draw_text(FontRole::Sans, 9, cursor_x, y + 2, label, pal.muted_foreground); + cursor_x += canvas.measure_text(FontRole::Sans, 9, label) + 7; +} + +void draw_pill_badge( + ShadcnCanvas& canvas, + int x, + int y, + int h, + const std::string& text, + uint32_t bg_rgb, + uint32_t border_rgb, + uint32_t fg_rgb, + bool with_dot, + bool hollow_dot = false, + bool with_check = false +) { + int text_w = canvas.measure_text(FontRole::Sans, 9, text); + int icon_w = (with_dot || with_check) ? 10 : 0; + int w = icon_w + text_w + 10; + canvas.draw_round_box(x, y, w, h, h / 2, bg_rgb, border_rgb, 1); + int tx = x + 5; + if (with_dot) { + canvas.draw_circle( + static_cast(x + 8), + static_cast(y) + static_cast(h) * 0.5f, + 2.5f, + fg_rgb, + hollow_dot + ); + tx += 9; + } else if (with_check) { + canvas.draw_checkmark(x + 5, y + (h - 7) / 2, fg_rgb); + tx += 9; + } + canvas.draw_text(FontRole::Sans, 9, tx, y + (h - 10) / 2, text, fg_rgb); +} + +int measure_pill_badge_w(ShadcnCanvas& canvas, const std::string& text, bool with_icon) { + int text_w = canvas.measure_text(FontRole::Sans, 9, text); + return (with_icon ? 10 : 0) + text_w + 10; +} + +} // namespace + +// --------------------------------------------------------------------------- +// LvglAppView::Impl +// --------------------------------------------------------------------------- + +struct LvglAppView::Impl { + ThemeMode theme = ThemeMode::Dark; + ShadcnPalette pal = get_palette(ThemeMode::Dark); + ShadcnCanvas canvas; + +#if defined(CP0_HAS_LVGL) + lv_obj_t* screen = nullptr; + lv_style_t style_bg; + lv_style_t style_card; + bool lvgl_styles_inited = false; +#endif + + void render_top_bar(const UiState& state) { + // Segmented TabsList pill container (radius 5px, padding 2px) + const char* tab_labels[3] = {"1 Status", "2 Folders", "3 Logs"}; + int tab_widths[3]{}; + int list_w = 4; + for (int i = 0; i < 3; ++i) { + tab_widths[i] = canvas.measure_text(FontRole::Sans, 9, tab_labels[i]) + 10; + list_w += tab_widths[i]; + } + canvas.draw_round_box(6, 3, list_w, 18, 5, pal.muted, pal.border, 1); + + int tx = 8; + for (int i = 0; i < 3; ++i) { + bool active = (static_cast(state.tab) == i); + if (active) { + int border_w = (pal.active_tab_border != pal.active_tab_bg) ? 1 : 0; + canvas.draw_round_box( + tx, + 5, + tab_widths[i], + 14, + 4, + pal.active_tab_bg, + pal.active_tab_border, + border_w + ); + } + uint32_t fg = active ? pal.active_tab_fg : pal.muted_foreground; + canvas.draw_text(FontRole::Sans, 9, tx + 5, 7, tab_labels[i], fg); + tx += tab_widths[i]; + } + + // Right-aligned pill status Badge + std::string badge_text; + uint32_t badge_bg = pal.muted; + uint32_t badge_fg = pal.muted_foreground; + uint32_t badge_border = pal.border; + bool hollow = false; + + if (!state.status.ok) { + badge_text = "Daemon Off"; + badge_bg = pal.status_error_bg; + badge_fg = pal.status_error; + badge_border = pal.status_error; + } else if (state.status.target_host.empty()) { + badge_text = "No Target"; + badge_bg = pal.muted; + badge_fg = pal.muted_foreground; + badge_border = pal.border; + hollow = true; + } else if (state.status.syncing) { + badge_text = "Syncing"; + badge_bg = pal.status_online_bg; + badge_fg = pal.status_online; + badge_border = pal.status_online; + } else if (state.status.mac_online) { + badge_text = "Mac Online"; + badge_bg = pal.status_online_bg; + badge_fg = pal.status_online; + badge_border = pal.status_online; + } else { + badge_text = "Mac Sleeping"; + badge_bg = pal.status_sleeping_bg; + badge_fg = pal.status_sleeping; + badge_border = pal.status_sleeping; + } + + int bw = measure_pill_badge_w(canvas, badge_text, true); + draw_pill_badge( + canvas, + LvglAppView::kWidth - 6 - bw, + 3, + 18, + badge_text, + badge_bg, + badge_border, + badge_fg, + true, + hollow, + false + ); + } + + void render_status_tab(const UiState& state) { + // Two side-by-side Bento Card stat tiles (radius 6px, 1px border) + canvas.draw_round_box(6, 27, 151, 56, 6, pal.card, pal.border, 1); + canvas.draw_text(FontRole::Sans, 9, 14, 33, "PENDING QUEUE", pal.muted_foreground); + + std::string pending_num = std::to_string(state.status.pending_count); + canvas.draw_text(FontRole::Mono, 18, 14, 46, pending_num, pal.foreground); + int num_w = canvas.measure_text(FontRole::Mono, 18, pending_num); + canvas.draw_text( + FontRole::Sans, + 9, + 14 + num_w + 5, + 53, + state.status.pending_count == 1 ? "file" : "files", + pal.muted_foreground + ); + canvas.draw_text( + FontRole::Mono, + 9, + 14, + 68, + format_bytes(state.status.pending_bytes) + " queued", + pal.muted_foreground + ); + + canvas.draw_round_box(163, 27, 151, 56, 6, pal.card, pal.border, 1); + canvas.draw_text(FontRole::Sans, 9, 171, 33, "TOTAL SYNCED", pal.muted_foreground); + canvas.draw_text( + FontRole::Mono, + 18, + 171, + 46, + std::to_string(state.status.synced_count), + pal.foreground + ); + if (state.status.failed_count > 0) { + canvas.draw_text( + FontRole::Sans, + 9, + 171, + 68, + std::to_string(state.status.failed_count) + " failed (Tab 3)", + pal.status_error + ); + } else { + canvas.draw_text(FontRole::Sans, 9, 171, 68, "1-way verified", pal.status_online); + } + + // Full-width Target summary Card + canvas.draw_round_box(6, 87, 308, 59, 6, pal.card, pal.border, 1); + + canvas.draw_text(FontRole::Sans, 9, 14, 94, "TARGET", pal.muted_foreground); + int label_w = canvas.measure_text(FontRole::Sans, 9, "TARGET") + 6; + + std::string target_str = state.status.target_host.empty() + ? "Not set (press C)" + : (state.status.target_host + ":" + + std::to_string(state.status.target_port)); + std::string right_note; + uint32_t right_color = pal.muted_foreground; + if (state.status.syncing && !state.status.current_file.empty()) { + right_note = "Uploading"; + right_color = pal.status_online; + } else if (state.status.next_retry_sec > 0 && !state.status.mac_online) { + right_note = "Retry " + std::to_string(state.status.next_retry_sec) + "s"; + right_color = pal.status_sleeping; + } else if (state.status.from_fallback) { + right_note = "Cached"; + } + int right_w = right_note.empty() ? 0 : (canvas.measure_text(FontRole::Sans, 9, right_note) + 8); + int max_target_w = 292 - label_w - right_w; + std::string target_fit = canvas.truncate_right(FontRole::Mono, 10, target_str, max_target_w); + canvas.draw_text(FontRole::Mono, 10, 14 + label_w, 93, target_fit, pal.foreground); + if (!right_note.empty()) { + int rw = canvas.measure_text(FontRole::Sans, 9, right_note); + canvas.draw_text(FontRole::Sans, 9, 306 - rw, 94, right_note, right_color); + } + + std::string dest = state.status.mac_dest_root.empty() + ? "~/Pictures/CardputerZero/" + : (state.status.mac_dest_root + "/"); + std::string dest_fit = canvas.truncate_left_path(FontRole::Mono, 9, "-> " + dest, 292); + canvas.draw_text(FontRole::Mono, 9, 14, 110, dest_fit, pal.muted_foreground); + + std::string footer_msg; + uint32_t footer_color = pal.muted_foreground; + if (!state.feedback_banner.empty()) { + footer_msg = state.feedback_banner; + footer_color = pal.status_online; + } else if (state.status.syncing && !state.status.current_file.empty()) { + footer_msg = "File: " + state.status.current_file; + footer_color = pal.foreground; + } else if (!state.status.last_error.empty() && state.status.last_error != "none") { + footer_msg = "Err: " + state.status.last_error; + footer_color = pal.status_error; + } else if (!state.status.last_synced_file.empty()) { + footer_msg = "Last sync: " + state.status.last_synced_file; + } else { + footer_msg = "Watching for new photos..."; + } + std::string msg_fit = canvas.truncate_right(FontRole::Mono, 9, footer_msg, 292); + canvas.draw_text(FontRole::Mono, 9, 14, 126, msg_fit, footer_color); + } + + void render_folders_tab(const UiState& state) { + if (state.status.folders.empty()) { + canvas.draw_round_box(6, 27, 308, 119, 6, pal.card, pal.border, 1); + std::string empty_msg = "No watched folders yet. Press [A] to add."; + int ew = canvas.measure_text(FontRole::Sans, 10, empty_msg); + canvas.draw_text( + FontRole::Sans, + 10, + 6 + (308 - ew) / 2, + 80, + empty_msg, + pal.muted_foreground + ); + return; + } + + constexpr int kVisible = 4; + int total = static_cast(state.status.folders.size()); + int start = 0; + if (state.folder_cursor >= kVisible) { + start = state.folder_cursor - kVisible + 1; + } + if (start + kVisible > total) { + start = std::max(0, total - kVisible); + } + + for (int slot = 0; slot < kVisible && (start + slot) < total; ++slot) { + int idx = start + slot; + const auto& f = state.status.folders[static_cast(idx)]; + bool selected = (idx == state.folder_cursor); + int ry = 27 + slot * 30; + canvas.draw_round_box( + 6, + ry, + 308, + 27, + 6, + selected ? pal.muted : pal.card, + selected ? pal.ring : pal.border, + 1 + ); + + std::string badge_text; + uint32_t b_bg = pal.status_online_bg; + uint32_t b_fg = pal.status_online; + bool check = false; + if (!f.exists) { + badge_text = "! missing"; + b_bg = pal.status_error_bg; + b_fg = pal.status_error; + } else if (f.failed > 0) { + badge_text = std::to_string(f.failed) + " err"; + b_bg = pal.status_error_bg; + b_fg = pal.status_error; + } else if (f.pending > 0) { + badge_text = std::to_string(f.pending) + " queued"; + b_bg = pal.status_sleeping_bg; + b_fg = pal.status_sleeping; + } else { + badge_text = "synced"; + check = true; + } + + int bw = measure_pill_badge_w(canvas, badge_text, check); + draw_pill_badge( + canvas, + 308 - bw, + ry + 5, + 17, + badge_text, + b_bg, + b_fg, + b_fg, + false, + false, + check + ); + + int max_text_w = 308 - 14 - bw - 12; + std::string title = f.label.empty() ? "Folder" : f.label; + std::string title_fit = canvas.truncate_right(FontRole::Sans, 9, title, max_text_w); + canvas.draw_text(FontRole::Sans, 9, 13, ry + 4, title_fit, pal.foreground); + + std::string path_fit = canvas.truncate_left_path(FontRole::Mono, 9, f.path, max_text_w); + canvas.draw_text(FontRole::Mono, 9, 13, ry + 15, path_fit, pal.muted_foreground); + } + } + + void render_logs_tab(const UiState& state) { + canvas.draw_round_box(6, 27, 308, 119, 6, pal.card, pal.border, 1); + if (state.status.logs.empty()) { + std::string msg = "No daemon logs recorded yet."; + int mw = canvas.measure_text(FontRole::Sans, 10, msg); + canvas.draw_text(FontRole::Sans, 10, 6 + (308 - mw) / 2, 80, msg, pal.muted_foreground); + return; + } + + constexpr int kRows = 6; + int total = static_cast(state.status.logs.size()); + int start = std::min(state.log_scroll, std::max(0, total - kRows)); + + for (int r = 0; r < kRows && (start + r) < total; ++r) { + const auto& entry = state.status.logs[static_cast(start + r)]; + int ry = 30 + r * 19; + if (r > 0) { + canvas.fill_rect(12, ry - 1, 296, 1, pal.border); + } + std::string tstr = format_hhmmss(entry.ts); + canvas.draw_text(FontRole::Mono, 9, 12, ry + 4, tstr, pal.muted_foreground); + + std::string tag = short_log_tag(entry.level); + uint32_t tag_color = pal.status_online; + if (tag == "ER") { + tag_color = pal.status_error; + } else if (tag == "WN") { + tag_color = pal.status_sleeping; + } + canvas.draw_text(FontRole::Mono, 9, 68, ry + 4, tag, tag_color); + + std::string msg_fit = canvas.truncate_right(FontRole::Mono, 9, entry.message, 218); + canvas.draw_text(FontRole::Mono, 9, 86, ry + 4, msg_fit, pal.foreground); + } + } + + void render_modal(const UiState& state) { + if (state.modal == ModalKind::None) { + return; + } + canvas.dim_rect(0, 0, LvglAppView::kWidth, 150, 0x000000, 145); + + if (state.modal == ModalKind::TargetPicker) { + canvas.draw_round_box(12, 14, 296, 130, 6, pal.card, pal.ring, 1); + canvas.draw_text(FontRole::Sans, 10, 20, 20, "Select Target Mac", pal.foreground); + std::string manual_hint = "[T] Manual"; + int hw = canvas.measure_text(FontRole::Mono, 9, manual_hint); + canvas.draw_text(FontRole::Mono, 9, 300 - hw, 21, manual_hint, pal.muted_foreground); + canvas.fill_rect(18, 34, 284, 1, pal.border); + + if (state.peers.empty()) { + canvas.draw_text( + FontRole::Sans, + 10, + 22, + 66, + "No Tailscale peers found.", + pal.muted_foreground + ); + canvas.draw_text( + FontRole::Sans, + 9, + 22, + 82, + "Press [T] to type host[:port] manually.", + pal.muted_foreground + ); + return; + } + + constexpr int kRows = 4; + int total = static_cast(state.peers.size()); + int start = 0; + if (state.peer_cursor >= kRows) { + start = state.peer_cursor - kRows + 1; + } + if (start + kRows > total) { + start = std::max(0, total - kRows); + } + + for (int r = 0; r < kRows && (start + r) < total; ++r) { + int idx = start + r; + const auto& peer = state.peers[static_cast(idx)]; + bool sel = (idx == state.peer_cursor); + int ry = 38 + r * 25; + canvas.draw_round_box( + 18, + ry, + 284, + 22, + 4, + sel ? pal.muted : pal.card, + sel ? pal.ring : pal.border, + 1 + ); + canvas.draw_circle( + 28.0f, + static_cast(ry + 11), + 3.0f, + peer.online ? pal.status_online : pal.muted_foreground, + !peer.online + ); + std::string host = !peer.dns_name.empty() + ? peer.dns_name + : (!peer.tailscale_ips.empty() ? peer.tailscale_ips[0] : peer.hostname); + std::string line = peer.hostname + " (" + peer.os + ") " + host; + std::string fit = canvas.truncate_right(FontRole::Mono, 9, line, 258); + canvas.draw_text(FontRole::Mono, 9, 36, ry + 6, fit, pal.foreground); + } + return; + } + + if (state.modal == ModalKind::DirPicker) { + canvas.draw_round_box(12, 14, 296, 130, 6, pal.card, pal.ring, 1); + canvas.draw_text(FontRole::Sans, 10, 20, 19, "Add Watch Folder", pal.foreground); + std::string manual_hint = "[T] Manual"; + int hw = canvas.measure_text(FontRole::Mono, 9, manual_hint); + canvas.draw_text(FontRole::Mono, 9, 300 - hw, 20, manual_hint, pal.muted_foreground); + + canvas.draw_round_box(18, 33, 284, 16, 3, pal.muted, pal.border, 1); + std::string cur_fit = canvas.truncate_left_path( + FontRole::Mono, + 9, + state.dir_current_path, + 272 + ); + canvas.draw_text(FontRole::Mono, 9, 24, 36, cur_fit, pal.foreground); + + if (state.dir_entries.empty()) { + canvas.draw_text( + FontRole::Sans, + 9, + 22, + 72, + "(No subdirectories — Space adds current dir)", + pal.muted_foreground + ); + return; + } + + constexpr int kRows = 4; + int total = static_cast(state.dir_entries.size()); + int start = 0; + if (state.dir_cursor >= kRows) { + start = state.dir_cursor - kRows + 1; + } + if (start + kRows > total) { + start = std::max(0, total - kRows); + } + + for (int r = 0; r < kRows && (start + r) < total; ++r) { + int idx = start + r; + bool sel = (idx == state.dir_cursor); + int ry = 53 + r * 22; + canvas.draw_round_box( + 18, + ry, + 284, + 19, + 4, + sel ? pal.muted : pal.card, + sel ? pal.ring : pal.border, + 1 + ); + const std::string& full = state.dir_entries[static_cast(idx)]; + size_t slash = full.rfind('/'); + std::string name = (slash != std::string::npos) ? full.substr(slash + 1) : full; + std::string disp = "> " + name + "/"; + std::string fit = canvas.truncate_right(FontRole::Mono, 9, disp, 268); + canvas.draw_text(FontRole::Mono, 9, 24, ry + 5, fit, pal.foreground); + } + return; + } + + if (state.modal == ModalKind::ConfirmRemove) { + canvas.draw_round_box(22, 30, 276, 98, 6, pal.card, pal.ring, 1); + canvas.draw_text(FontRole::Sans, 11, 34, 40, "Remove Watched Folder?", pal.foreground); + std::string path_fit = canvas.truncate_left_path( + FontRole::Mono, + 9, + state.confirm_folder_path, + 252 + ); + canvas.draw_text(FontRole::Mono, 9, 34, 60, path_fit, pal.muted_foreground); + canvas.draw_text( + FontRole::Sans, + 9, + 34, + 78, + "Local files on disk will NOT be deleted.", + pal.status_online + ); + canvas.draw_text( + FontRole::Mono, + 9, + 34, + 100, + "[Y] Confirm Remove [N / Esc] Cancel", + pal.foreground + ); + return; + } + + if (state.modal == ModalKind::TextInput) { + canvas.draw_round_box(18, 32, 284, 92, 6, pal.card, pal.ring, 1); + std::string title = (state.text_purpose == TextInputPurpose::TargetHost) + ? "Enter Mac Host[:Port]" + : "Enter Folder Path"; + canvas.draw_text(FontRole::Sans, 10, 28, 42, title, pal.foreground); + + canvas.draw_round_box(28, 60, 264, 24, 4, pal.muted, pal.ring, 1); + std::string shown = canvas.truncate_left_path( + FontRole::Mono, + 10, + state.text_buffer + "_", + 250 + ); + canvas.draw_text(FontRole::Mono, 10, 35, 67, shown, pal.foreground); + + if (!state.modal_error.empty()) { + std::string err = canvas.truncate_right(FontRole::Sans, 9, state.modal_error, 264); + canvas.draw_text(FontRole::Sans, 9, 28, 94, err, pal.status_error); + } else { + std::string ex = (state.text_purpose == TextInputPurpose::TargetHost) + ? "Example: macbook.ts.net or 100.64.0.5:8765" + : "Example: /media/sdcard/DCIM"; + canvas.draw_text(FontRole::Mono, 9, 28, 94, ex, pal.muted_foreground); + } + } + } + + void render_footer(const UiState& state) { + canvas.fill_rect(0, 150, LvglAppView::kWidth, 20, pal.muted); + canvas.fill_rect(0, 150, LvglAppView::kWidth, 1, pal.border); + + int x = 6; + int y = 154; + + switch (state.modal) { + case ModalKind::TargetPicker: + draw_kbd_hint(canvas, pal, x, y, "j/k", "Move"); + draw_kbd_hint(canvas, pal, x, y, "Ent", "Use"); + draw_kbd_hint(canvas, pal, x, y, "T", "Type"); + draw_kbd_hint(canvas, pal, x, y, "Esc", "Back"); + return; + case ModalKind::DirPicker: + draw_kbd_hint(canvas, pal, x, y, "Ent", "Open"); + draw_kbd_hint(canvas, pal, x, y, "Bksp", "Up"); + draw_kbd_hint(canvas, pal, x, y, "Spc", "Watch"); + draw_kbd_hint(canvas, pal, x, y, "T", "Type"); + return; + case ModalKind::ConfirmRemove: + draw_kbd_hint(canvas, pal, x, y, "Y", "Remove"); + draw_kbd_hint(canvas, pal, x, y, "N/Esc", "Cancel"); + return; + case ModalKind::TextInput: + draw_kbd_hint(canvas, pal, x, y, "Bksp", "Del"); + draw_kbd_hint(canvas, pal, x, y, "Ent", "Save"); + draw_kbd_hint(canvas, pal, x, y, "Esc", "Cancel"); + return; + case ModalKind::None: + break; + } + + switch (state.tab) { + case ActiveTab::Status: + draw_kbd_hint(canvas, pal, x, y, "Ent", "Sync"); + draw_kbd_hint(canvas, pal, x, y, "C", "Target"); + draw_kbd_hint(canvas, pal, x, y, "T", "Theme"); + draw_kbd_hint(canvas, pal, x, y, "Q", "Quit"); + break; + case ActiveTab::Folders: + draw_kbd_hint(canvas, pal, x, y, "A", "Add"); + draw_kbd_hint(canvas, pal, x, y, "D", "Del"); + draw_kbd_hint(canvas, pal, x, y, "Ent", "Sync"); + draw_kbd_hint(canvas, pal, x, y, "T", "Theme"); + break; + case ActiveTab::Logs: + draw_kbd_hint(canvas, pal, x, y, "j/k", "Scroll"); + draw_kbd_hint(canvas, pal, x, y, "R", "Retry"); + draw_kbd_hint(canvas, pal, x, y, "T", "Theme"); + draw_kbd_hint(canvas, pal, x, y, "Q", "Quit"); + break; + } + } + + void render(const UiState& state) { + if (state.theme != theme) { + theme = state.theme; + pal = get_palette(theme); + } + canvas.clear(pal.background); + render_top_bar(state); + + switch (state.tab) { + case ActiveTab::Status: + render_status_tab(state); + break; + case ActiveTab::Folders: + render_folders_tab(state); + break; + case ActiveTab::Logs: + render_logs_tab(state); + break; + } + + render_modal(state); + render_footer(state); + +#if defined(CP0_HAS_LVGL) + if (!lvgl_styles_inited) { + lv_style_init(&style_bg); + lv_style_init(&style_card); + lvgl_styles_inited = true; + } + lv_style_set_bg_color(&style_bg, lv_color_hex(pal.background)); + lv_style_set_bg_color(&style_card, lv_color_hex(pal.card)); + lv_style_set_border_color(&style_card, lv_color_hex(pal.border)); + if (screen != nullptr) { + lv_obj_report_style_change(&style_bg); + lv_obj_report_style_change(&style_card); + } +#endif + } +}; + +LvglAppView::LvglAppView() : impl_(std::make_unique()) {} +LvglAppView::~LvglAppView() = default; + +void LvglAppView::apply_theme(ThemeMode mode) { + impl_->theme = mode; + impl_->pal = get_palette(mode); +} + +void LvglAppView::render(const UiState& state) { + impl_->render(state); +} + +const uint32_t* LvglAppView::pixels() const { + return impl_->canvas.pixels(); +} + +bool LvglAppView::save_ppm(const std::string& path) const { + std::ofstream out(path, std::ios::binary | std::ios::trunc); + if (!out.is_open()) { + return false; + } + out << "P6\n" << kWidth << " " << kHeight << "\n255\n"; + const uint32_t* px = pixels(); + std::vector rgb(static_cast(kWidth * kHeight * 3)); + for (int i = 0; i < kWidth * kHeight; ++i) { + uint32_t c = px[i]; + rgb[static_cast(i * 3 + 0)] = static_cast((c >> 16) & 0xffU); + rgb[static_cast(i * 3 + 1)] = static_cast((c >> 8) & 0xffU); + rgb[static_cast(i * 3 + 2)] = static_cast(c & 0xffU); + } + out.write(reinterpret_cast(rgb.data()), static_cast(rgb.size())); + return out.good(); +} + +bool LvglAppView::using_freetype() const { + return impl_->canvas.using_freetype(); +} + +ThemeMode LvglAppView::active_theme() const { + return impl_->theme; +} + +} // namespace cp0 diff --git a/device-ui/src/app_ui.hpp b/device-ui/src/app_ui.hpp new file mode 100644 index 0000000..79c13e2 --- /dev/null +++ b/device-ui/src/app_ui.hpp @@ -0,0 +1,49 @@ +#pragma once + +#include "theme.hpp" +#include "ui_controller.hpp" + +#include +#include +#include + +namespace cp0 { + +/// 320x170 shadcn/ui Zinc Bento Card & Segmented Tabs view renderer. +/// Supports LVGL v9 when CP0_HAS_LVGL is defined, and a built-in zero-external-LVGL +/// FreeType2 + anti-aliased RGBA framebuffer renderer otherwise. +class LvglAppView { +public: + static constexpr int kWidth = 320; + static constexpr int kHeight = 170; + + LvglAppView(); + ~LvglAppView(); + + LvglAppView(const LvglAppView&) = delete; + LvglAppView& operator=(const LvglAppView&) = delete; + + /// Swap active Zinc Dark / Zinc Light palette tokens without recreating view objects. + void apply_theme(ThemeMode mode); + + /// Re-render the 320x170 view from the current UiState. + void render(const UiState& state); + + /// Return 320*170 ARGB8888 (0xAARRGGBB) framebuffer pixels. + const uint32_t* pixels() const; + + /// Write current 320x170 framebuffer as a binary PPM (P6) image. + bool save_ppm(const std::string& path) const; + + /// True if at least one FreeType font (.ttf/.ttc/.otf) was loaded. + bool using_freetype() const; + + /// Return currently applied theme mode. + ThemeMode active_theme() const; + +private: + struct Impl; + std::unique_ptr impl_; +}; + +} // namespace cp0 diff --git a/device-ui/src/main.cpp b/device-ui/src/main.cpp new file mode 100644 index 0000000..63a4cf4 --- /dev/null +++ b/device-ui/src/main.cpp @@ -0,0 +1,676 @@ +#include "app_ui.hpp" +#include "ipc_client.hpp" +#include "ui_controller.hpp" + +#include +#include +#include +#include +#include +#include +#include + +#if defined(CP0_UI_TARGET_DEVICE) && defined(__linux__) +#include +#include +#include +#include +#include +#include +#include +#include +#else +#include +#endif + +namespace { + +volatile std::sig_atomic_t g_signal_stop = 0; + +void handle_signal(int /*sig*/) { + g_signal_stop = 1; +} + +void print_usage(const char* argv0) { + std::cout << "Usage: " << argv0 << " [options]\n" + << " --sim Run desktop 320x170 SDL2 simulator\n" + << " --scale <1..4> Integer window scale factor (default: 1)\n" + << " --render-test Render 320x170 snapshot to PPM file and exit\n" + << " --theme Theme override for --render-test\n" + << " --tab Initial tab for --render-test\n" + << " --help Show this help message\n"; +} + +cp0::DaemonStatus make_sample_status(const std::string& theme_str) { + cp0::DaemonStatus st; + st.ok = true; + st.target_host = "macbook-pro.ts.net"; + st.target_port = 8765; + st.theme = theme_str; + st.mac_online = true; + st.mac_dest_root = "/Users/user/Pictures/CardputerZero"; + st.syncing = false; + st.pending_count = 3; + st.pending_bytes = 4404019; + st.synced_count = 148; + st.failed_count = 0; + st.last_synced_file = "IMG_0148.JPG"; + + cp0::FolderStatus f1; + f1.id = "camera"; + f1.path = "/home/pi/Pictures/DCIM/Camera"; + f1.label = "Camera"; + f1.exists = true; + f1.pending = 3; + f1.synced = 148; + st.folders.push_back(f1); + + cp0::FolderStatus f2; + f2.id = "sd"; + f2.path = "/media/pi/SDCARD/DCIM"; + f2.label = "SD Card"; + f2.exists = true; + f2.pending = 0; + f2.synced = 64; + st.folders.push_back(f2); + + cp0::LogEntry l1; + l1.id = 2; + l1.ts = 1731900500000LL; + l1.level = "INFO"; + l1.message = "Synced IMG_0148.JPG (1.4 MB)"; + cp0::LogEntry l2; + l2.id = 1; + l2.ts = 1731900490000LL; + l2.level = "WARN"; + l2.message = "Mac sleeping, retry in 10s"; + st.logs = {l1, l2}; + return st; +} + +bool dispatch_action( + const cp0::IpcClient& ipc, + cp0::UiController& ctrl, + cp0::LvglAppView& view, + const cp0::IpcAction& action, + bool& running, + std::chrono::steady_clock::time_point& feedback_until +) { + using cp0::ActionType; + if (action.type == ActionType::None) { + return false; + } + + auto set_timed_feedback = [&](const std::string& msg) { + ctrl.set_feedback(msg); + feedback_until = std::chrono::steady_clock::now() + std::chrono::seconds(3); + }; + + switch (action.type) { + case ActionType::Quit: + running = false; + return true; + case ActionType::SyncNow: { + auto res = ipc.sync_now(); + set_timed_feedback(res.ok ? "Sync triggered" : res.error); + ctrl.update_status(ipc.fetch_status()); + return true; + } + case ActionType::AddFolder: { + auto res = ipc.add_folder(action.folder_path, action.folder_label); + set_timed_feedback(res.ok ? "Folder added" : res.error); + ctrl.update_status(ipc.fetch_status()); + return true; + } + case ActionType::RemoveFolder: { + auto res = ipc.remove_folder(action.folder_id); + set_timed_feedback(res.ok ? "Folder removed" : res.error); + ctrl.update_status(ipc.fetch_status()); + return true; + } + case ActionType::SetTarget: { + auto res = ipc.set_target(action.target_host, action.target_port); + set_timed_feedback(res.ok ? ("Target: " + action.target_host) : res.error); + ctrl.update_status(ipc.fetch_status()); + return true; + } + case ActionType::SetTheme: { + view.apply_theme(action.theme); + ipc.set_theme(action.theme); + return true; + } + case ActionType::RetryFailed: { + auto res = ipc.retry_failed(); + set_timed_feedback(res.ok ? "Retrying failed files" : res.error); + ctrl.update_status(ipc.fetch_status()); + return true; + } + case ActionType::None: + break; + } + return false; +} + +#if defined(CP0_UI_TARGET_DEVICE) && defined(__linux__) + +char map_evdev_code(uint16_t code, bool shift) { + switch (code) { + case KEY_1: return shift ? '!' : '1'; + case KEY_2: return shift ? '@' : '2'; + case KEY_3: return shift ? '#' : '3'; + case KEY_4: return shift ? '$' : '4'; + case KEY_5: return shift ? '%' : '5'; + case KEY_6: return shift ? '^' : '6'; + case KEY_7: return shift ? '&' : '7'; + case KEY_8: return shift ? '*' : '8'; + case KEY_9: return shift ? '(' : '9'; + case KEY_0: return shift ? ')' : '0'; + case KEY_A: return shift ? 'A' : 'a'; + case KEY_B: return shift ? 'B' : 'b'; + case KEY_C: return shift ? 'C' : 'c'; + case KEY_D: return shift ? 'D' : 'd'; + case KEY_E: return shift ? 'E' : 'e'; + case KEY_F: return shift ? 'F' : 'f'; + case KEY_G: return shift ? 'G' : 'g'; + case KEY_H: return shift ? 'H' : 'h'; + case KEY_I: return shift ? 'I' : 'i'; + case KEY_J: return shift ? 'J' : 'j'; + case KEY_K: return shift ? 'K' : 'k'; + case KEY_L: return shift ? 'L' : 'l'; + case KEY_M: return shift ? 'M' : 'm'; + case KEY_N: return shift ? 'N' : 'n'; + case KEY_O: return shift ? 'O' : 'o'; + case KEY_P: return shift ? 'P' : 'p'; + case KEY_Q: return shift ? 'Q' : 'q'; + case KEY_R: return shift ? 'R' : 'r'; + case KEY_S: return shift ? 'S' : 's'; + case KEY_T: return shift ? 'T' : 't'; + case KEY_U: return shift ? 'U' : 'u'; + case KEY_V: return shift ? 'V' : 'v'; + case KEY_W: return shift ? 'W' : 'w'; + case KEY_X: return shift ? 'X' : 'x'; + case KEY_Y: return shift ? 'Y' : 'y'; + case KEY_Z: return shift ? 'Z' : 'z'; + case KEY_MINUS: return shift ? '_' : '-'; + case KEY_EQUAL: return shift ? '+' : '='; + case KEY_LEFTBRACE: return shift ? '{' : '['; + case KEY_RIGHTBRACE: return shift ? '}' : ']'; + case KEY_SEMICOLON: return shift ? ':' : ';'; + case KEY_APOSTROPHE: return shift ? '"' : '\''; + case KEY_COMMA: return shift ? '<' : ','; + case KEY_DOT: return shift ? '>' : '.'; + case KEY_SLASH: return shift ? '?' : '/'; + case KEY_BACKSLASH: return shift ? '|' : '\\'; + default: return 0; + } +} + +void blit_fbdev( + uint8_t* fb_mem, + const fb_var_screeninfo& vinfo, + const fb_fix_screeninfo& finfo, + const uint32_t* pixels +) { + int fb_w = static_cast(vinfo.xres); + int fb_h = static_cast(vinfo.yres); + int copy_w = std::min(fb_w, cp0::LvglAppView::kWidth); + int copy_h = std::min(fb_h, cp0::LvglAppView::kHeight); + int bpp = static_cast(vinfo.bits_per_pixel); + int stride = static_cast(finfo.line_length); + + for (int y = 0; y < copy_h; ++y) { + uint8_t* row = fb_mem + (y + static_cast(vinfo.yoffset)) * stride + + static_cast(vinfo.xoffset) * (bpp / 8); + const uint32_t* src = pixels + y * cp0::LvglAppView::kWidth; + if (bpp == 32) { + std::memcpy(row, src, static_cast(copy_w) * 4); + } else if (bpp == 16) { + auto* dst16 = reinterpret_cast(row); + for (int x = 0; x < copy_w; ++x) { + uint32_t c = src[x]; + uint16_t r = static_cast((c >> 19) & 0x1fU); + uint16_t g = static_cast((c >> 10) & 0x3fU); + uint16_t b = static_cast((c >> 3) & 0x1fU); + dst16[x] = static_cast((r << 11) | (g << 5) | b); + } + } + } +} + +std::vector open_keyboard_evdevs() { + std::vector fds; + if (const char* override_dev = std::getenv("CP0_EVDEV_DEVICE")) { + int fd = ::open(override_dev, O_RDONLY | O_NONBLOCK); + if (fd >= 0) { + fds.push_back(fd); + } + return fds; + } + + DIR* dir = ::opendir("/dev/input"); + if (dir == nullptr) { + return fds; + } + struct dirent* ent = nullptr; + while ((ent = ::readdir(dir)) != nullptr) { + if (std::strncmp(ent->d_name, "event", 5) != 0) { + continue; + } + std::string dev_path = std::string("/dev/input/") + ent->d_name; + int fd = ::open(dev_path.c_str(), O_RDONLY | O_NONBLOCK); + if (fd < 0) { + continue; + } + unsigned long ev_bits[4]{}; + if (::ioctl(fd, EVIOCGBIT(0, sizeof(ev_bits)), ev_bits) >= 0 && + (ev_bits[0] & (1UL << EV_KEY)) != 0) { + fds.push_back(fd); + } else { + ::close(fd); + } + } + ::closedir(dir); + return fds; +} + +int run_device_loop(cp0::IpcClient& ipc, cp0::UiController& ctrl, cp0::LvglAppView& view) { + const char* fb_dev = std::getenv("CP0_FB_DEVICE"); + if (fb_dev == nullptr || fb_dev[0] == '\0') { + fb_dev = "/dev/fb0"; + } + int fb_fd = ::open(fb_dev, O_RDWR); + if (fb_fd < 0) { + std::cerr << "Failed to open framebuffer " << fb_dev << "\n"; + return 1; + } + + fb_var_screeninfo vinfo{}; + fb_fix_screeninfo finfo{}; + if (::ioctl(fb_fd, FBIOGET_VSCREENINFO, &vinfo) < 0 || + ::ioctl(fb_fd, FBIOGET_FSCREENINFO, &finfo) < 0) { + std::cerr << "Failed to query framebuffer info\n"; + ::close(fb_fd); + return 1; + } + + size_t map_size = finfo.smem_len; + void* mapped = ::mmap(nullptr, map_size, PROT_READ | PROT_WRITE, MAP_SHARED, fb_fd, 0); + if (mapped == MAP_FAILED) { + std::cerr << "Failed to mmap framebuffer\n"; + ::close(fb_fd); + return 1; + } + auto* fb_mem = static_cast(mapped); + + std::vector ev_fds = open_keyboard_evdevs(); + std::vector pfds; + pfds.reserve(ev_fds.size()); + for (int fd : ev_fds) { + pfds.push_back(pollfd{fd, POLLIN, 0}); + } + + ctrl.update_status(ipc.fetch_status()); + view.apply_theme(ctrl.state().theme); + view.render(ctrl.state()); + blit_fbdev(fb_mem, vinfo, finfo, view.pixels()); + + bool running = true; + bool shift_down = false; + auto last_poll = std::chrono::steady_clock::now(); + auto feedback_until = std::chrono::steady_clock::time_point{}; + + while (running && !g_signal_stop) { + bool dirty = false; + if (!pfds.empty()) { + int prc = ::poll(pfds.data(), static_cast(pfds.size()), 50); + if (prc > 0) { + for (const auto& p : pfds) { + if ((p.revents & POLLIN) == 0) { + continue; + } + struct input_event ev{}; + while (::read(p.fd, &ev, sizeof(ev)) == sizeof(ev)) { + if (ev.type != EV_KEY) { + continue; + } + if (ev.code == KEY_LEFTSHIFT || ev.code == KEY_RIGHTSHIFT) { + shift_down = (ev.value != 0); + continue; + } + if (ev.value != 1 && ev.value != 2) { + continue; + } + cp0::IpcAction act; + bool handled = true; + switch (ev.code) { + case KEY_UP: + act = ctrl.handle_key(0, cp0::KeyCode::Up); + break; + case KEY_DOWN: + act = ctrl.handle_key(0, cp0::KeyCode::Down); + break; + case KEY_LEFT: + act = ctrl.handle_key(0, cp0::KeyCode::Left); + break; + case KEY_RIGHT: + act = ctrl.handle_key(0, cp0::KeyCode::Right); + break; + case KEY_ENTER: + case KEY_KPENTER: + act = ctrl.handle_key(0, cp0::KeyCode::Enter); + break; + case KEY_ESC: + act = ctrl.handle_key(0, cp0::KeyCode::Escape); + break; + case KEY_BACKSPACE: + act = ctrl.handle_key(0, cp0::KeyCode::Backspace); + break; + case KEY_DELETE: + act = ctrl.handle_key(0, cp0::KeyCode::Delete); + break; + case KEY_SPACE: + act = ctrl.handle_key(' ', cp0::KeyCode::Space); + break; + default: { + char c = map_evdev_code(ev.code, shift_down); + if (c != 0) { + act = ctrl.handle_key(c, cp0::KeyCode::Char); + } else { + handled = false; + } + break; + } + } + if (handled) { + dirty = true; + if (ctrl.consume_peer_refresh()) { + ctrl.set_peers(ipc.list_tailscale_peers()); + } + dispatch_action(ipc, ctrl, view, act, running, feedback_until); + } + } + } + } + } else { + ::usleep(50000); + } + + auto now = std::chrono::steady_clock::now(); + if (!ctrl.state().feedback_banner.empty() && now >= feedback_until) { + ctrl.clear_feedback(); + dirty = true; + } + if (now - last_poll >= std::chrono::milliseconds(1000)) { + ctrl.update_status(ipc.fetch_status()); + last_poll = now; + dirty = true; + } + if (dirty) { + view.render(ctrl.state()); + blit_fbdev(fb_mem, vinfo, finfo, view.pixels()); + } + } + + for (int fd : ev_fds) { + ::close(fd); + } + ::munmap(mapped, map_size); + ::close(fb_fd); + return 0; +} + +#else + +int run_sdl_loop( + cp0::IpcClient& ipc, + cp0::UiController& ctrl, + cp0::LvglAppView& view, + int scale +) { + if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) != 0) { + std::cerr << "SDL_Init failed: " << SDL_GetError() << "\n"; + return 1; + } + + SDL_Window* window = SDL_CreateWindow( + "CardputerZero Photo Sync", + SDL_WINDOWPOS_CENTERED, + SDL_WINDOWPOS_CENTERED, + cp0::LvglAppView::kWidth * scale, + cp0::LvglAppView::kHeight * scale, + SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE + ); + if (window == nullptr) { + std::cerr << "SDL_CreateWindow failed: " << SDL_GetError() << "\n"; + SDL_Quit(); + return 1; + } + + SDL_Renderer* renderer = SDL_CreateRenderer( + window, + -1, + SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC + ); + if (renderer == nullptr) { + renderer = SDL_CreateRenderer(window, -1, 0); + } + if (renderer == nullptr) { + std::cerr << "SDL_CreateRenderer failed: " << SDL_GetError() << "\n"; + SDL_DestroyWindow(window); + SDL_Quit(); + return 1; + } + + SDL_RenderSetLogicalSize(renderer, cp0::LvglAppView::kWidth, cp0::LvglAppView::kHeight); + SDL_Texture* texture = SDL_CreateTexture( + renderer, + SDL_PIXELFORMAT_ARGB8888, + SDL_TEXTUREACCESS_STREAMING, + cp0::LvglAppView::kWidth, + cp0::LvglAppView::kHeight + ); + if (texture == nullptr) { + std::cerr << "SDL_CreateTexture failed: " << SDL_GetError() << "\n"; + SDL_DestroyRenderer(renderer); + SDL_DestroyWindow(window); + SDL_Quit(); + return 1; + } + + SDL_StartTextInput(); + + ctrl.update_status(ipc.fetch_status()); + view.apply_theme(ctrl.state().theme); + view.render(ctrl.state()); + + auto present = [&]() { + SDL_UpdateTexture( + texture, + nullptr, + view.pixels(), + cp0::LvglAppView::kWidth * static_cast(sizeof(uint32_t)) + ); + SDL_RenderClear(renderer); + SDL_RenderCopy(renderer, texture, nullptr, nullptr); + SDL_RenderPresent(renderer); + }; + present(); + + bool running = true; + auto last_poll = std::chrono::steady_clock::now(); + auto feedback_until = std::chrono::steady_clock::time_point{}; + + while (running && !g_signal_stop) { + bool dirty = false; + SDL_Event ev; + if (SDL_WaitEventTimeout(&ev, 50) != 0) { + do { + if (ev.type == SDL_QUIT) { + running = false; + break; + } + if (ev.type == SDL_WINDOWEVENT && + (ev.window.event == SDL_WINDOWEVENT_EXPOSED || + ev.window.event == SDL_WINDOWEVENT_RESIZED)) { + dirty = true; + continue; + } + if (ev.type == SDL_TEXTINPUT) { + for (int i = 0; ev.text.text[i] != '\0'; ++i) { + char ch = ev.text.text[i]; + cp0::IpcAction act = ctrl.handle_key(ch, cp0::KeyCode::Char); + dirty = true; + if (ctrl.consume_peer_refresh()) { + ctrl.set_peers(ipc.list_tailscale_peers()); + } + dispatch_action(ipc, ctrl, view, act, running, feedback_until); + } + continue; + } + if (ev.type == SDL_KEYDOWN) { + SDL_Keycode sym = ev.key.keysym.sym; + uint16_t mod = ev.key.keysym.mod; + if ((mod & (KMOD_CTRL | KMOD_GUI)) != 0 && sym == SDLK_q) { + running = false; + break; + } + cp0::IpcAction act; + bool handled = true; + switch (sym) { + case SDLK_UP: + act = ctrl.handle_key(0, cp0::KeyCode::Up); + break; + case SDLK_DOWN: + act = ctrl.handle_key(0, cp0::KeyCode::Down); + break; + case SDLK_LEFT: + act = ctrl.handle_key(0, cp0::KeyCode::Left); + break; + case SDLK_RIGHT: + act = ctrl.handle_key(0, cp0::KeyCode::Right); + break; + case SDLK_RETURN: + case SDLK_KP_ENTER: + act = ctrl.handle_key(0, cp0::KeyCode::Enter); + break; + case SDLK_ESCAPE: + act = ctrl.handle_key(0, cp0::KeyCode::Escape); + break; + case SDLK_BACKSPACE: + act = ctrl.handle_key(0, cp0::KeyCode::Backspace); + break; + case SDLK_DELETE: + act = ctrl.handle_key(0, cp0::KeyCode::Delete); + break; + default: + handled = false; + break; + } + if (handled) { + dirty = true; + if (ctrl.consume_peer_refresh()) { + ctrl.set_peers(ipc.list_tailscale_peers()); + } + dispatch_action(ipc, ctrl, view, act, running, feedback_until); + } + } + } while (running && SDL_PollEvent(&ev) != 0); + } + + auto now = std::chrono::steady_clock::now(); + if (!ctrl.state().feedback_banner.empty() && now >= feedback_until) { + ctrl.clear_feedback(); + dirty = true; + } + if (now - last_poll >= std::chrono::milliseconds(1000)) { + ctrl.update_status(ipc.fetch_status()); + last_poll = now; + dirty = true; + } + if (running && dirty) { + view.render(ctrl.state()); + present(); + } + } + + SDL_StopTextInput(); + SDL_DestroyTexture(texture); + SDL_DestroyRenderer(renderer); + SDL_DestroyWindow(window); + SDL_Quit(); + return 0; +} + +#endif + +} // namespace + +int main(int argc, char* argv[]) { + std::signal(SIGINT, handle_signal); + std::signal(SIGTERM, handle_signal); + + int scale = 1; + std::string render_test_path; + std::string render_theme = "dark"; + std::string render_tab = "status"; + + for (int i = 1; i < argc; ++i) { + std::string arg = argv[i]; + if (arg == "--help" || arg == "-h") { + print_usage(argv[0]); + return 0; + } + if (arg == "--sim") { + continue; + } + if (arg == "--scale" && i + 1 < argc) { + int parsed = std::atoi(argv[++i]); + if (parsed >= 1 && parsed <= 4) { + scale = parsed; + } + continue; + } + if (arg == "--render-test" && i + 1 < argc) { + render_test_path = argv[++i]; + continue; + } + if (arg == "--theme" && i + 1 < argc) { + render_theme = argv[++i]; + continue; + } + if (arg == "--tab" && i + 1 < argc) { + render_tab = argv[++i]; + continue; + } + std::cerr << "Unknown option: " << arg << "\n"; + print_usage(argv[0]); + return 2; + } + + cp0::UiController ctrl; + cp0::LvglAppView view; + + if (!render_test_path.empty()) { + ctrl.update_status(make_sample_status(render_theme)); + if (render_tab == "folders") { + ctrl.handle_key('2', cp0::KeyCode::Char); + } else if (render_tab == "logs") { + ctrl.handle_key('3', cp0::KeyCode::Char); + } + view.apply_theme(ctrl.state().theme); + view.render(ctrl.state()); + if (!view.save_ppm(render_test_path)) { + std::cerr << "Failed to write PPM to " << render_test_path << "\n"; + return 1; + } + return 0; + } + + cp0::IpcClient ipc; +#if defined(CP0_UI_TARGET_DEVICE) && defined(__linux__) + (void)scale; + return run_device_loop(ipc, ctrl, view); +#else + return run_sdl_loop(ipc, ctrl, view, scale); +#endif +} diff --git a/device-ui/src/ui_controller.cpp b/device-ui/src/ui_controller.cpp new file mode 100644 index 0000000..fd9ae7f --- /dev/null +++ b/device-ui/src/ui_controller.cpp @@ -0,0 +1,658 @@ +#include "ui_controller.hpp" + +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; + +namespace cp0 { + +namespace { + +std::string trim_ascii(const std::string& s) { + size_t start = 0; + while (start < s.size() && std::isspace(static_cast(s[start]))) { + ++start; + } + size_t end = s.size(); + while (end > start && std::isspace(static_cast(s[end - 1]))) { + --end; + } + return s.substr(start, end - start); +} + +std::string to_lower_ascii(std::string s) { + for (char& ch : s) { + ch = static_cast(std::tolower(static_cast(ch))); + } + return s; +} + +std::string expand_tilde(const std::string& path) { + if (path.empty() || path[0] != '~') { + return path; + } + if (path.size() == 1 || path[1] == '/') { + const char* home = std::getenv("HOME"); + if (home != nullptr && home[0] != '\0') { + return std::string(home) + path.substr(1); + } + } + return path; +} + +bool is_valid_dir(const std::string& path) { + if (path.empty()) { + return false; + } + std::error_code ec; + return fs::is_directory(fs::path(path), ec); +} + +bool parse_strict_port(const std::string& s, int& port_out) { + if (s.empty()) { + return false; + } + long val = 0; + for (char ch : s) { + if (!std::isdigit(static_cast(ch))) { + return false; + } + val = val * 10 + (ch - '0'); + if (val > 65535) { + return false; + } + } + if (val < 1 || val > 65535) { + return false; + } + port_out = static_cast(val); + return true; +} + +bool parse_host_port( + const std::string& raw, + std::string& host_out, + int& port_out, + std::string& err_out +) { + std::string trimmed = trim_ascii(raw); + if (trimmed.empty()) { + err_out = "Host cannot be empty"; + return false; + } + + port_out = 8765; + if (trimmed.front() == '[') { + size_t close = trimmed.find(']'); + if (close == std::string::npos || close <= 1) { + err_out = "Invalid bracketed host"; + return false; + } + host_out = trimmed.substr(1, close - 1); + if (close + 1 < trimmed.size()) { + if (trimmed[close + 1] != ':') { + err_out = "Invalid host:port syntax"; + return false; + } + if (!parse_strict_port(trimmed.substr(close + 2), port_out)) { + err_out = "Port must be 1..65535"; + return false; + } + } + } else { + size_t first_colon = trimmed.find(':'); + size_t last_colon = trimmed.rfind(':'); + if (first_colon != std::string::npos && first_colon == last_colon) { + host_out = trim_ascii(trimmed.substr(0, first_colon)); + std::string port_str = trim_ascii(trimmed.substr(first_colon + 1)); + if (!parse_strict_port(port_str, port_out)) { + err_out = "Port must be 1..65535"; + return false; + } + } else { + host_out = trimmed; + } + } + + if (host_out.empty() || host_out.find('/') != std::string::npos) { + err_out = "Invalid target host"; + return false; + } + for (char ch : host_out) { + if (std::isspace(static_cast(ch))) { + err_out = "Host cannot contain spaces"; + return false; + } + } + return true; +} + +std::string resolve_peer_host(const TailscalePeer& peer) { + if (!peer.dns_name.empty()) { + return peer.dns_name; + } + if (!peer.tailscale_ips.empty()) { + return peer.tailscale_ips[0]; + } + return peer.hostname; +} + +KeyCode normalize_key(char ch, KeyCode key) { + if (key != KeyCode::Char) { + return key; + } + if (ch == ' ') { + return KeyCode::Space; + } + if (ch == '\n' || ch == '\r') { + return KeyCode::Enter; + } + if (ch == '\b' || static_cast(ch) == 0x7f) { + return KeyCode::Backspace; + } + if (static_cast(ch) == 0x1b) { + return KeyCode::Escape; + } + return KeyCode::Char; +} + +} // namespace + +void UiController::update_status(const DaemonStatus& status) { + state_.status = status; + + if (status.ok && !status.theme.empty()) { + if (!initial_status_applied_) { + state_.theme = theme_from_string(status.theme); + initial_status_applied_ = true; + last_daemon_theme_ = status.theme; + } else if (status.theme != last_daemon_theme_) { + state_.theme = theme_from_string(status.theme); + last_daemon_theme_ = status.theme; + } + } + + if (state_.status.folders.empty()) { + state_.folder_cursor = 0; + } else if (state_.folder_cursor >= static_cast(state_.status.folders.size())) { + state_.folder_cursor = static_cast(state_.status.folders.size()) - 1; + } else if (state_.folder_cursor < 0) { + state_.folder_cursor = 0; + } + + if (state_.status.logs.empty()) { + state_.log_scroll = 0; + } else if (state_.log_scroll >= static_cast(state_.status.logs.size())) { + state_.log_scroll = static_cast(state_.status.logs.size()) - 1; + } else if (state_.log_scroll < 0) { + state_.log_scroll = 0; + } +} + +void UiController::set_peers(const std::vector& peers) { + state_.peers = peers; + state_.needs_peer_refresh = false; + if (state_.peers.empty()) { + state_.peer_cursor = 0; + } else if (state_.peer_cursor >= static_cast(state_.peers.size())) { + state_.peer_cursor = static_cast(state_.peers.size()) - 1; + } else if (state_.peer_cursor < 0) { + state_.peer_cursor = 0; + } +} + +void UiController::set_dir_picker_start_path(const std::string& path) { + dir_picker_start_path_ = path; +} + +void UiController::set_feedback(const std::string& message) { + state_.feedback_banner = message; +} + +void UiController::clear_feedback() { + state_.feedback_banner.clear(); +} + +bool UiController::consume_peer_refresh() { + bool v = state_.needs_peer_refresh; + state_.needs_peer_refresh = false; + return v; +} + +IpcAction UiController::handle_key(char ch, KeyCode key) { + if (state_.modal == ModalKind::TextInput) { + return handle_text_input_key(ch, key); + } + + KeyCode norm = normalize_key(ch, key); + switch (state_.modal) { + case ModalKind::None: + return handle_global_key(ch, norm); + case ModalKind::TargetPicker: + return handle_target_picker_key(ch, norm); + case ModalKind::DirPicker: + return handle_dir_picker_key(ch, norm); + case ModalKind::ConfirmRemove: + return handle_confirm_remove_key(ch, norm); + case ModalKind::TextInput: + return handle_text_input_key(ch, key); + } + return IpcAction{}; +} + +void UiController::open_target_picker() { + state_.modal = ModalKind::TargetPicker; + state_.peer_cursor = 0; + state_.modal_error.clear(); + state_.needs_peer_refresh = true; +} + +void UiController::open_dir_picker() { + std::string start = "/"; + if (is_valid_dir(dir_picker_start_path_)) { + start = dir_picker_start_path_; + } else { + const char* home = std::getenv("HOME"); + if (home != nullptr && is_valid_dir(home)) { + start = home; + } + } + state_.modal = ModalKind::DirPicker; + state_.modal_error.clear(); + load_directory(start); +} + +void UiController::load_directory(const std::string& path, const std::string& select_name) { + std::error_code ec; + fs::path resolved = fs::weakly_canonical(fs::path(path), ec); + if (ec || resolved.empty()) { + resolved = fs::path(path); + } + + state_.dir_current_path = resolved.string(); + state_.dir_entries.clear(); + + fs::directory_iterator it( + resolved, + fs::directory_options::skip_permission_denied, + ec + ); + if (!ec) { + for (const auto& entry : it) { + std::error_code entry_ec; + if (!entry.is_directory(entry_ec) || entry_ec) { + continue; + } + std::string name = entry.path().filename().string(); + if (name.empty() || name[0] == '.') { + continue; + } + state_.dir_entries.push_back(entry.path().string()); + } + } + + std::sort( + state_.dir_entries.begin(), + state_.dir_entries.end(), + [](const std::string& a, const std::string& b) { + std::string na = fs::path(a).filename().string(); + std::string nb = fs::path(b).filename().string(); + std::string la = to_lower_ascii(na); + std::string lb = to_lower_ascii(nb); + if (la != lb) { + return la < lb; + } + return na < nb; + } + ); + + if (state_.dir_entries.empty()) { + state_.dir_cursor = -1; + return; + } + + state_.dir_cursor = 0; + if (!select_name.empty()) { + for (size_t i = 0; i < state_.dir_entries.size(); ++i) { + if (fs::path(state_.dir_entries[i]).filename().string() == select_name) { + state_.dir_cursor = static_cast(i); + break; + } + } + } +} + +void UiController::open_text_input(TextInputPurpose purpose) { + state_.modal = ModalKind::TextInput; + state_.text_purpose = purpose; + state_.text_buffer.clear(); + state_.modal_error.clear(); +} + +void UiController::close_modal() { + state_.modal = ModalKind::None; + state_.text_purpose = TextInputPurpose::None; + state_.text_buffer.clear(); + state_.modal_error.clear(); + state_.confirm_folder_id.clear(); + state_.confirm_folder_path.clear(); + state_.confirm_folder_label.clear(); +} + +IpcAction UiController::handle_global_key(char ch, KeyCode key) { + IpcAction action; + + if (key == KeyCode::Escape) { + action.type = ActionType::Quit; + return action; + } + + if (key == KeyCode::Enter) { + action.type = ActionType::SyncNow; + return action; + } + + if (key == KeyCode::Left) { + int idx = static_cast(state_.tab); + state_.tab = static_cast((idx + 2) % 3); + return action; + } + + if (key == KeyCode::Right) { + int idx = static_cast(state_.tab); + state_.tab = static_cast((idx + 1) % 3); + return action; + } + + if (key == KeyCode::Up || (key == KeyCode::Char && std::tolower(static_cast(ch)) == 'k')) { + if (state_.tab == ActiveTab::Folders && state_.folder_cursor > 0) { + --state_.folder_cursor; + } else if (state_.tab == ActiveTab::Logs && state_.log_scroll > 0) { + --state_.log_scroll; + } + return action; + } + + if (key == KeyCode::Down || (key == KeyCode::Char && std::tolower(static_cast(ch)) == 'j')) { + if (state_.tab == ActiveTab::Folders) { + int max_idx = static_cast(state_.status.folders.size()) - 1; + if (state_.folder_cursor < max_idx) { + ++state_.folder_cursor; + } + } else if (state_.tab == ActiveTab::Logs) { + int max_idx = static_cast(state_.status.logs.size()) - 1; + if (state_.log_scroll < max_idx) { + ++state_.log_scroll; + } + } + return action; + } + + if (key == KeyCode::Delete) { + if (state_.tab == ActiveTab::Folders && !state_.status.folders.empty()) { + const auto& f = state_.status.folders[static_cast(state_.folder_cursor)]; + state_.confirm_folder_id = f.id; + state_.confirm_folder_path = f.path; + state_.confirm_folder_label = f.label; + state_.modal = ModalKind::ConfirmRemove; + } + return action; + } + + if (key != KeyCode::Char) { + return action; + } + + char lower = static_cast(std::tolower(static_cast(ch))); + switch (lower) { + case '1': + state_.tab = ActiveTab::Status; + break; + case '2': + state_.tab = ActiveTab::Folders; + break; + case '3': + state_.tab = ActiveTab::Logs; + break; + case 't': + state_.theme = toggle_theme(state_.theme); + action.type = ActionType::SetTheme; + action.theme = state_.theme; + break; + case 'q': + action.type = ActionType::Quit; + break; + case 'c': + if (state_.tab == ActiveTab::Status) { + open_target_picker(); + } + break; + case 'a': + if (state_.tab == ActiveTab::Folders) { + open_dir_picker(); + } + break; + case 'd': + if (state_.tab == ActiveTab::Folders && !state_.status.folders.empty()) { + const auto& f = state_.status.folders[static_cast(state_.folder_cursor)]; + state_.confirm_folder_id = f.id; + state_.confirm_folder_path = f.path; + state_.confirm_folder_label = f.label; + state_.modal = ModalKind::ConfirmRemove; + } + break; + case 'r': + if (state_.tab == ActiveTab::Logs) { + action.type = ActionType::RetryFailed; + } + break; + default: + break; + } + + return action; +} + +IpcAction UiController::handle_target_picker_key(char ch, KeyCode key) { + IpcAction action; + + if (key == KeyCode::Escape) { + close_modal(); + return action; + } + + if (key == KeyCode::Up || (key == KeyCode::Char && std::tolower(static_cast(ch)) == 'k')) { + if (state_.peer_cursor > 0) { + --state_.peer_cursor; + } + return action; + } + + if (key == KeyCode::Down || (key == KeyCode::Char && std::tolower(static_cast(ch)) == 'j')) { + int max_idx = static_cast(state_.peers.size()) - 1; + if (state_.peer_cursor < max_idx) { + ++state_.peer_cursor; + } + return action; + } + + if (key == KeyCode::Enter) { + if (!state_.peers.empty() && state_.peer_cursor >= 0 && + state_.peer_cursor < static_cast(state_.peers.size())) { + std::string host = resolve_peer_host(state_.peers[static_cast(state_.peer_cursor)]); + if (!host.empty()) { + action.type = ActionType::SetTarget; + action.target_host = host; + action.target_port = 8765; + close_modal(); + } + } + return action; + } + + if (key == KeyCode::Char && std::tolower(static_cast(ch)) == 't') { + open_text_input(TextInputPurpose::TargetHost); + } + + return action; +} + +IpcAction UiController::handle_dir_picker_key(char ch, KeyCode key) { + IpcAction action; + + if (key == KeyCode::Escape) { + close_modal(); + return action; + } + + if (key == KeyCode::Up || (key == KeyCode::Char && std::tolower(static_cast(ch)) == 'k')) { + if (state_.dir_cursor > 0) { + --state_.dir_cursor; + } + return action; + } + + if (key == KeyCode::Down || (key == KeyCode::Char && std::tolower(static_cast(ch)) == 'j')) { + int max_idx = static_cast(state_.dir_entries.size()) - 1; + if (state_.dir_cursor < max_idx) { + ++state_.dir_cursor; + } + return action; + } + + if (key == KeyCode::Enter) { + if (state_.dir_cursor >= 0 && + state_.dir_cursor < static_cast(state_.dir_entries.size())) { + load_directory(state_.dir_entries[static_cast(state_.dir_cursor)]); + } + return action; + } + + if (key == KeyCode::Backspace) { + fs::path cur(state_.dir_current_path); + fs::path parent = cur.parent_path(); + if (!parent.empty() && parent != cur) { + load_directory(parent.string(), cur.filename().string()); + } + return action; + } + + if (key == KeyCode::Space) { + std::string chosen = state_.dir_current_path; + if (state_.dir_cursor >= 0 && + state_.dir_cursor < static_cast(state_.dir_entries.size())) { + chosen = state_.dir_entries[static_cast(state_.dir_cursor)]; + } + if (!chosen.empty()) { + action.type = ActionType::AddFolder; + action.folder_path = chosen; + close_modal(); + } + return action; + } + + if (key == KeyCode::Char) { + char lower = static_cast(std::tolower(static_cast(ch))); + if (lower == 't') { + open_text_input(TextInputPurpose::FolderPath); + } else if (lower == '.') { + if (!state_.dir_current_path.empty()) { + action.type = ActionType::AddFolder; + action.folder_path = state_.dir_current_path; + close_modal(); + } + } + } + + return action; +} + +IpcAction UiController::handle_confirm_remove_key(char ch, KeyCode key) { + IpcAction action; + + if (key == KeyCode::Escape) { + close_modal(); + return action; + } + + if (key == KeyCode::Char) { + char lower = static_cast(std::tolower(static_cast(ch))); + if (lower == 'y') { + action.type = ActionType::RemoveFolder; + action.folder_id = state_.confirm_folder_id; + close_modal(); + } else if (lower == 'n') { + close_modal(); + } + } + + return action; +} + +IpcAction UiController::handle_text_input_key(char ch, KeyCode key) { + IpcAction action; + + if (key == KeyCode::Escape || (key == KeyCode::Char && static_cast(ch) == 0x1b)) { + close_modal(); + return action; + } + + if (key == KeyCode::Backspace || + (key == KeyCode::Char && (ch == '\b' || static_cast(ch) == 0x7f))) { + if (!state_.text_buffer.empty()) { + state_.text_buffer.pop_back(); + state_.modal_error.clear(); + } + return action; + } + + if (key == KeyCode::Enter || (key == KeyCode::Char && (ch == '\n' || ch == '\r'))) { + if (state_.text_purpose == TextInputPurpose::TargetHost) { + std::string host; + int port = 8765; + std::string err; + if (!parse_host_port(state_.text_buffer, host, port, err)) { + state_.modal_error = err; + return action; + } + action.type = ActionType::SetTarget; + action.target_host = host; + action.target_port = port; + close_modal(); + } else if (state_.text_purpose == TextInputPurpose::FolderPath) { + std::string path = expand_tilde(trim_ascii(state_.text_buffer)); + if (path.empty()) { + state_.modal_error = "Path cannot be empty"; + return action; + } + action.type = ActionType::AddFolder; + action.folder_path = path; + close_modal(); + } + return action; + } + + if (key == KeyCode::Space) { + if (state_.text_buffer.size() < 256) { + state_.text_buffer.push_back(' '); + state_.modal_error.clear(); + } + return action; + } + + if (key == KeyCode::Char) { + unsigned char uch = static_cast(ch); + if (uch >= 0x20 && uch <= 0x7e && state_.text_buffer.size() < 256) { + state_.text_buffer.push_back(ch); + state_.modal_error.clear(); + } + } + + return action; +} + +} // namespace cp0 diff --git a/device-ui/src/ui_controller.hpp b/device-ui/src/ui_controller.hpp new file mode 100644 index 0000000..9a45e04 --- /dev/null +++ b/device-ui/src/ui_controller.hpp @@ -0,0 +1,145 @@ +#pragma once + +#include "ipc_client.hpp" +#include "theme.hpp" + +#include +#include + +namespace cp0 { + +/// Top-level segmented tab views on the 320x170 UI. +enum class ActiveTab { + Status = 0, + Folders = 1, + Logs = 2, +}; + +/// Active overlay modal state. +enum class ModalKind { + None, + TargetPicker, + DirPicker, + ConfirmRemove, + TextInput, +}; + +/// Purpose of the shared TextInput modal. +enum class TextInputPurpose { + None, + TargetHost, + FolderPath, +}; + +/// Normalized physical/simulator key events handled by UiController. +enum class KeyCode { + Char, + Enter, + Escape, + Up, + Down, + Left, + Right, + Backspace, + Delete, + Space, +}; + +/// Side-effect actions emitted by UiController for the event loop / IPC client. +enum class ActionType { + None, + Quit, + SyncNow, + AddFolder, + RemoveFolder, + SetTarget, + SetTheme, + RetryFailed, +}; + +/// Structured command emitted by UiController::handle_key. +struct IpcAction { + ActionType type = ActionType::None; + std::string target_host; + int target_port = 8765; + std::string folder_path; + std::string folder_label; + std::string folder_id; + ThemeMode theme = ThemeMode::Dark; +}; + +/// Complete view-model state rendered by LvglAppView. +struct UiState { + ActiveTab tab = ActiveTab::Status; + ThemeMode theme = ThemeMode::Dark; + ModalKind modal = ModalKind::None; + TextInputPurpose text_purpose = TextInputPurpose::None; + + DaemonStatus status; + std::vector peers; + int peer_cursor = 0; + + int folder_cursor = 0; + int log_scroll = 0; + + std::string dir_current_path; + std::vector dir_entries; + int dir_cursor = -1; + + std::string confirm_folder_id; + std::string confirm_folder_path; + std::string confirm_folder_label; + + std::string text_buffer; + std::string modal_error; + std::string feedback_banner; + + bool needs_peer_refresh = false; +}; + +/// Pure keyboard-first UI state machine decoupled from graphics/display backends. +class UiController { +public: + UiController() = default; + + const UiState& state() const { return state_; } + + /// Apply a freshly polled DaemonStatus snapshot, preserving active cursors safely. + void update_status(const DaemonStatus& status); + + /// Populate Tailscale peers for TargetPicker. + void set_peers(const std::vector& peers); + + /// Override starting directory for DirPicker (defaults to $HOME or /). + void set_dir_picker_start_path(const std::string& path); + + /// Set or clear transient status feedback displayed in the UI. + void set_feedback(const std::string& message); + void clear_feedback(); + + /// Return true once when TargetPicker was opened and needs peer discovery. + bool consume_peer_refresh(); + + /// Process a normalized key event and return any resulting IPC/lifecycle action. + IpcAction handle_key(char ch, KeyCode key = KeyCode::Char); + +private: + void open_target_picker(); + void open_dir_picker(); + void load_directory(const std::string& path, const std::string& select_name = ""); + void open_text_input(TextInputPurpose purpose); + void close_modal(); + + IpcAction handle_global_key(char ch, KeyCode key); + IpcAction handle_target_picker_key(char ch, KeyCode key); + IpcAction handle_dir_picker_key(char ch, KeyCode key); + IpcAction handle_confirm_remove_key(char ch, KeyCode key); + IpcAction handle_text_input_key(char ch, KeyCode key); + + UiState state_; + std::string dir_picker_start_path_; + bool initial_status_applied_ = false; + std::string last_daemon_theme_; +}; + +} // namespace cp0 diff --git a/device-ui/tests/test_ui_navigation.cpp b/device-ui/tests/test_ui_navigation.cpp new file mode 100644 index 0000000..0c56df6 --- /dev/null +++ b/device-ui/tests/test_ui_navigation.cpp @@ -0,0 +1,446 @@ +#include "ui_controller.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; + +namespace { + +struct TempDir { + fs::path path; + explicit TempDir(const std::string& prefix) { + auto base = fs::temp_directory_path(); + auto stamp = std::chrono::steady_clock::now().time_since_epoch().count(); + path = base / (prefix + "_" + std::to_string(getpid()) + "_" + std::to_string(stamp)); + fs::create_directories(path); + } + ~TempDir() { + std::error_code ec; + fs::remove_all(path, ec); + } +}; + +void type_text(cp0::UiController& ctrl, const std::string& text) { + for (char ch : text) { + auto act = ctrl.handle_key(ch, cp0::KeyCode::Char); + assert(act.type == cp0::ActionType::None); + } +} + +void test_initial_state_and_global_navigation() { + cp0::UiController ctrl; + assert(ctrl.state().tab == cp0::ActiveTab::Status); + assert(ctrl.state().theme == cp0::ThemeMode::Dark); + assert(ctrl.state().modal == cp0::ModalKind::None); + + // Direct tab jumps: 1 / 2 / 3 + assert(ctrl.handle_key('2', cp0::KeyCode::Char).type == cp0::ActionType::None); + assert(ctrl.state().tab == cp0::ActiveTab::Folders); + assert(ctrl.handle_key('3', cp0::KeyCode::Char).type == cp0::ActionType::None); + assert(ctrl.state().tab == cp0::ActiveTab::Logs); + assert(ctrl.handle_key('1', cp0::KeyCode::Char).type == cp0::ActionType::None); + assert(ctrl.state().tab == cp0::ActiveTab::Status); + + // Left / Right cycle tabs + ctrl.handle_key(0, cp0::KeyCode::Right); + assert(ctrl.state().tab == cp0::ActiveTab::Folders); + ctrl.handle_key(0, cp0::KeyCode::Right); + assert(ctrl.state().tab == cp0::ActiveTab::Logs); + ctrl.handle_key(0, cp0::KeyCode::Right); + assert(ctrl.state().tab == cp0::ActiveTab::Status); + ctrl.handle_key(0, cp0::KeyCode::Left); + assert(ctrl.state().tab == cp0::ActiveTab::Logs); + ctrl.handle_key(0, cp0::KeyCode::Left); + assert(ctrl.state().tab == cp0::ActiveTab::Folders); + ctrl.handle_key(0, cp0::KeyCode::Left); + assert(ctrl.state().tab == cp0::ActiveTab::Status); + + // Enter triggers SyncNow on any main tab + auto sync1 = ctrl.handle_key(0, cp0::KeyCode::Enter); + assert(sync1.type == cp0::ActionType::SyncNow); + ctrl.handle_key('2', cp0::KeyCode::Char); + auto sync2 = ctrl.handle_key(0, cp0::KeyCode::Enter); + assert(sync2.type == cp0::ActionType::SyncNow); + + // Esc and Q emit Quit when no modal is open + assert(ctrl.handle_key(0, cp0::KeyCode::Escape).type == cp0::ActionType::Quit); + assert(ctrl.handle_key('q', cp0::KeyCode::Char).type == cp0::ActionType::Quit); + assert(ctrl.handle_key('Q', cp0::KeyCode::Char).type == cp0::ActionType::Quit); +} + +void test_theme_toggle_outside_vs_inside_modals() { + cp0::UiController ctrl; + + // Initial daemon status seeds theme once + cp0::DaemonStatus st; + st.ok = true; + st.theme = "light"; + cp0::FolderStatus f; + f.id = "cam1"; + f.path = "/tmp/cam1"; + f.label = "Camera"; + st.folders.push_back(f); + ctrl.update_status(st); + assert(ctrl.state().theme == cp0::ThemeMode::Light); + + // 'T' toggles theme on main tab and emits SetTheme + auto act1 = ctrl.handle_key('t', cp0::KeyCode::Char); + assert(act1.type == cp0::ActionType::SetTheme); + assert(act1.theme == cp0::ThemeMode::Dark); + assert(ctrl.state().theme == cp0::ThemeMode::Dark); + + // Stale daemon status with unchanged "light" does not clobber optimistic toggle + ctrl.update_status(st); + assert(ctrl.state().theme == cp0::ThemeMode::Dark); + + // Uppercase 'T' toggles back to Light + auto act2 = ctrl.handle_key('T', cp0::KeyCode::Char); + assert(act2.type == cp0::ActionType::SetTheme); + assert(act2.theme == cp0::ThemeMode::Light); + assert(ctrl.state().theme == cp0::ThemeMode::Light); + + // Inside DirPicker, 'T' opens TextInput instead of toggling theme + ctrl.handle_key('2', cp0::KeyCode::Char); + ctrl.handle_key('a', cp0::KeyCode::Char); + assert(ctrl.state().modal == cp0::ModalKind::DirPicker); + auto modal_t = ctrl.handle_key('t', cp0::KeyCode::Char); + assert(modal_t.type == cp0::ActionType::None); + assert(ctrl.state().modal == cp0::ModalKind::TextInput); + assert(ctrl.state().theme == cp0::ThemeMode::Light); + + // Inside TextInput, 't' appends 't' instead of toggling theme or opening another modal + auto text_t = ctrl.handle_key('t', cp0::KeyCode::Char); + assert(text_t.type == cp0::ActionType::None); + assert(ctrl.state().text_buffer == "t"); + assert(ctrl.state().theme == cp0::ThemeMode::Light); + + // Esc closes TextInput without toggling theme or quitting + auto esc1 = ctrl.handle_key(0, cp0::KeyCode::Escape); + assert(esc1.type == cp0::ActionType::None); + assert(ctrl.state().modal == cp0::ModalKind::None); + assert(ctrl.state().theme == cp0::ThemeMode::Light); + + // Esc again (modal == None) emits Quit + auto esc2 = ctrl.handle_key(0, cp0::KeyCode::Escape); + assert(esc2.type == cp0::ActionType::Quit); + + // Inside TargetPicker, 'T' opens TextInput without toggling theme + ctrl.handle_key('1', cp0::KeyCode::Char); + ctrl.handle_key('c', cp0::KeyCode::Char); + assert(ctrl.state().modal == cp0::ModalKind::TargetPicker); + ctrl.handle_key('T', cp0::KeyCode::Char); + assert(ctrl.state().modal == cp0::ModalKind::TextInput); + assert(ctrl.state().theme == cp0::ThemeMode::Light); + ctrl.handle_key(0, cp0::KeyCode::Escape); + assert(ctrl.state().modal == cp0::ModalKind::None); + + // Inside ConfirmRemove, 'T' does not toggle theme + ctrl.handle_key('2', cp0::KeyCode::Char); + ctrl.handle_key('d', cp0::KeyCode::Char); + assert(ctrl.state().modal == cp0::ModalKind::ConfirmRemove); + ctrl.handle_key('t', cp0::KeyCode::Char); + assert(ctrl.state().theme == cp0::ThemeMode::Light); + assert(ctrl.state().modal == cp0::ModalKind::ConfirmRemove); + ctrl.handle_key('n', cp0::KeyCode::Char); + assert(ctrl.state().modal == cp0::ModalKind::None); +} + +void test_target_picker_and_manual_host() { + cp0::UiController ctrl; + + std::vector peers; + cp0::TailscalePeer p1; + p1.id = "1"; + p1.hostname = "macbook"; + p1.dns_name = "macbook.ts.net"; + p1.os = "macOS"; + p1.online = true; + p1.tailscale_ips = {"100.64.0.10"}; + peers.push_back(p1); + + cp0::TailscalePeer p2; + p2.id = "2"; + p2.hostname = "studio"; + p2.dns_name = ""; + p2.os = "macOS"; + p2.online = false; + p2.tailscale_ips = {"100.64.0.11"}; + peers.push_back(p2); + + // 'c' on Status tab opens TargetPicker and requests peer refresh + ctrl.handle_key('c', cp0::KeyCode::Char); + assert(ctrl.state().modal == cp0::ModalKind::TargetPicker); + assert(ctrl.consume_peer_refresh() == true); + assert(ctrl.consume_peer_refresh() == false); + + ctrl.set_peers(peers); + assert(ctrl.state().peers.size() == 2); + assert(ctrl.state().peer_cursor == 0); + + // Navigate with j/k and Up/Down (clamped at ends) + ctrl.handle_key('j', cp0::KeyCode::Char); + assert(ctrl.state().peer_cursor == 1); + ctrl.handle_key(0, cp0::KeyCode::Down); + assert(ctrl.state().peer_cursor == 1); + ctrl.handle_key('k', cp0::KeyCode::Char); + assert(ctrl.state().peer_cursor == 0); + ctrl.handle_key(0, cp0::KeyCode::Up); + assert(ctrl.state().peer_cursor == 0); + + // Select first peer (uses dns_name + default port 8765) + auto sel1 = ctrl.handle_key(0, cp0::KeyCode::Enter); + assert(sel1.type == cp0::ActionType::SetTarget); + assert(sel1.target_host == "macbook.ts.net"); + assert(sel1.target_port == 8765); + assert(ctrl.state().modal == cp0::ModalKind::None); + + // Select second peer (falls back to IP when dns_name empty) + ctrl.handle_key('c', cp0::KeyCode::Char); + ctrl.set_peers(peers); + ctrl.handle_key(0, cp0::KeyCode::Down); + auto sel2 = ctrl.handle_key(0, cp0::KeyCode::Enter); + assert(sel2.type == cp0::ActionType::SetTarget); + assert(sel2.target_host == "100.64.0.11"); + assert(sel2.target_port == 8765); + assert(ctrl.state().modal == cp0::ModalKind::None); + + // Manual host[:port] via TextInput with Backspace editing + ctrl.handle_key('c', cp0::KeyCode::Char); + ctrl.handle_key('t', cp0::KeyCode::Char); + assert(ctrl.state().modal == cp0::ModalKind::TextInput); + type_text(ctrl, "imac.ts.net:9000"); + ctrl.handle_key(0, cp0::KeyCode::Backspace); + type_text(ctrl, "1"); + auto manual_port = ctrl.handle_key(0, cp0::KeyCode::Enter); + assert(manual_port.type == cp0::ActionType::SetTarget); + assert(manual_port.target_host == "imac.ts.net"); + assert(manual_port.target_port == 9001); + assert(ctrl.state().modal == cp0::ModalKind::None); + + // Manual host without port defaults to 8765 + ctrl.handle_key('c', cp0::KeyCode::Char); + ctrl.handle_key('t', cp0::KeyCode::Char); + type_text(ctrl, "100.64.0.42"); + auto manual_default_port = ctrl.handle_key(0, cp0::KeyCode::Enter); + assert(manual_default_port.type == cp0::ActionType::SetTarget); + assert(manual_default_port.target_host == "100.64.0.42"); + assert(manual_default_port.target_port == 8765); + + // Empty host stays in TextInput without emitting SetTarget + ctrl.handle_key('c', cp0::KeyCode::Char); + ctrl.handle_key('t', cp0::KeyCode::Char); + type_text(ctrl, " "); + auto empty_submit = ctrl.handle_key(0, cp0::KeyCode::Enter); + assert(empty_submit.type == cp0::ActionType::None); + assert(ctrl.state().modal == cp0::ModalKind::TextInput); + assert(!ctrl.state().modal_error.empty()); + ctrl.handle_key(0, cp0::KeyCode::Escape); + assert(ctrl.state().modal == cp0::ModalKind::None); + + // Invalid port stays in TextInput with error + ctrl.handle_key('c', cp0::KeyCode::Char); + ctrl.handle_key('t', cp0::KeyCode::Char); + type_text(ctrl, "mac.ts.net:99999"); + auto bad_port = ctrl.handle_key(0, cp0::KeyCode::Enter); + assert(bad_port.type == cp0::ActionType::None); + assert(ctrl.state().modal == cp0::ModalKind::TextInput); + assert(!ctrl.state().modal_error.empty()); + ctrl.handle_key(0, cp0::KeyCode::Escape); + + // TargetPicker with empty peers ignores Enter + ctrl.handle_key('c', cp0::KeyCode::Char); + ctrl.set_peers({}); + auto no_peer_enter = ctrl.handle_key(0, cp0::KeyCode::Enter); + assert(no_peer_enter.type == cp0::ActionType::None); + assert(ctrl.state().modal == cp0::ModalKind::TargetPicker); + ctrl.handle_key(0, cp0::KeyCode::Escape); +} + +void test_dir_picker_traversal_and_manual_path() { + TempDir tmp("cp0_dirpicker"); + fs::path root = tmp.path; + fs::create_directories(root / "alpha"); + fs::create_directories(root / "beta" / "sub1"); + fs::create_directories(root / "gamma"); + { + std::ofstream f(root / "IMG_0001.JPG"); + f << "not a directory"; + } + + cp0::UiController ctrl; + ctrl.set_dir_picker_start_path(root.string()); + ctrl.handle_key('2', cp0::KeyCode::Char); + + // 'a' opens DirPicker at configured start path + ctrl.handle_key('a', cp0::KeyCode::Char); + assert(ctrl.state().modal == cp0::ModalKind::DirPicker); + assert(fs::path(ctrl.state().dir_current_path) == fs::weakly_canonical(root)); + assert(ctrl.state().dir_entries.size() == 3); + assert(fs::path(ctrl.state().dir_entries[0]).filename() == "alpha"); + assert(fs::path(ctrl.state().dir_entries[1]).filename() == "beta"); + assert(fs::path(ctrl.state().dir_entries[2]).filename() == "gamma"); + assert(ctrl.state().dir_cursor == 0); + + // Move down to 'beta' and drill in with Enter + ctrl.handle_key('j', cp0::KeyCode::Char); + assert(ctrl.state().dir_cursor == 1); + ctrl.handle_key(0, cp0::KeyCode::Enter); + assert(fs::path(ctrl.state().dir_current_path) == fs::weakly_canonical(root / "beta")); + assert(ctrl.state().dir_entries.size() == 1); + assert(fs::path(ctrl.state().dir_entries[0]).filename() == "sub1"); + + // Backspace goes up to parent ('root') and restores cursor on 'beta' + ctrl.handle_key(0, cp0::KeyCode::Backspace); + assert(fs::path(ctrl.state().dir_current_path) == fs::weakly_canonical(root)); + assert(ctrl.state().dir_entries.size() == 3); + assert(ctrl.state().dir_cursor == 1); + + // Drill back into beta and press Space on highlighted subdir 'sub1' + ctrl.handle_key(0, cp0::KeyCode::Enter); + auto add_highlighted = ctrl.handle_key(0, cp0::KeyCode::Space); + assert(add_highlighted.type == cp0::ActionType::AddFolder); + assert(fs::path(add_highlighted.folder_path) == fs::weakly_canonical(root / "beta" / "sub1")); + assert(ctrl.state().modal == cp0::ModalKind::None); + + // Drill into empty leaf dir 'sub1' and press Space (' ' char) to watch current dir + ctrl.handle_key('a', cp0::KeyCode::Char); + ctrl.handle_key('j', cp0::KeyCode::Char); // beta + ctrl.handle_key(0, cp0::KeyCode::Enter); + ctrl.handle_key(0, cp0::KeyCode::Enter); // sub1 (empty) + assert(ctrl.state().dir_entries.empty()); + assert(ctrl.state().dir_cursor == -1); + auto add_current = ctrl.handle_key(' ', cp0::KeyCode::Char); + assert(add_current.type == cp0::ActionType::AddFolder); + assert(fs::path(add_current.folder_path) == fs::weakly_canonical(root / "beta" / "sub1")); + assert(ctrl.state().modal == cp0::ModalKind::None); + + // Manual folder path via [T] inside DirPicker + ctrl.handle_key('a', cp0::KeyCode::Char); + ctrl.handle_key('t', cp0::KeyCode::Char); + assert(ctrl.state().modal == cp0::ModalKind::TextInput); + type_text(ctrl, "/media/sd/DCIM"); + ctrl.handle_key(0, cp0::KeyCode::Backspace); + type_text(ctrl, "M2"); + auto add_manual = ctrl.handle_key(0, cp0::KeyCode::Enter); + assert(add_manual.type == cp0::ActionType::AddFolder); + assert(add_manual.folder_path == "/media/sd/DCIM2"); + assert(ctrl.state().modal == cp0::ModalKind::None); +} + +void test_folders_selection_and_confirm_remove() { + cp0::UiController ctrl; + ctrl.handle_key('2', cp0::KeyCode::Char); + + // Empty folders: 'd' and Delete do not open ConfirmRemove + ctrl.handle_key('d', cp0::KeyCode::Char); + assert(ctrl.state().modal == cp0::ModalKind::None); + ctrl.handle_key(0, cp0::KeyCode::Delete); + assert(ctrl.state().modal == cp0::ModalKind::None); + + cp0::DaemonStatus st; + st.ok = true; + cp0::FolderStatus f1; + f1.id = "cam"; + f1.path = "/home/pi/Pictures/DCIM/Camera"; + f1.label = "Camera"; + f1.exists = true; + cp0::FolderStatus f2; + f2.id = "sd"; + f2.path = "/media/sd/DCIM"; + f2.label = "SD"; + f2.exists = false; + st.folders = {f1, f2}; + ctrl.update_status(st); + + assert(ctrl.state().folder_cursor == 0); + ctrl.handle_key('j', cp0::KeyCode::Char); + assert(ctrl.state().folder_cursor == 1); + ctrl.handle_key(0, cp0::KeyCode::Down); + assert(ctrl.state().folder_cursor == 1); + + // 'd' opens ConfirmRemove, 'n' cancels + ctrl.handle_key('d', cp0::KeyCode::Char); + assert(ctrl.state().modal == cp0::ModalKind::ConfirmRemove); + assert(ctrl.state().confirm_folder_id == "sd"); + auto cancel_n = ctrl.handle_key('n', cp0::KeyCode::Char); + assert(cancel_n.type == cp0::ActionType::None); + assert(ctrl.state().modal == cp0::ModalKind::None); + + // Delete opens ConfirmRemove, Esc cancels + ctrl.handle_key(0, cp0::KeyCode::Delete); + assert(ctrl.state().modal == cp0::ModalKind::ConfirmRemove); + auto cancel_esc = ctrl.handle_key(0, cp0::KeyCode::Escape); + assert(cancel_esc.type == cp0::ActionType::None); + assert(ctrl.state().modal == cp0::ModalKind::None); + + // 'd' -> 'y' emits RemoveFolder + ctrl.handle_key('d', cp0::KeyCode::Char); + assert(ctrl.state().modal == cp0::ModalKind::ConfirmRemove); + auto confirm_y = ctrl.handle_key('y', cp0::KeyCode::Char); + assert(confirm_y.type == cp0::ActionType::RemoveFolder); + assert(confirm_y.folder_id == "sd"); + assert(ctrl.state().modal == cp0::ModalKind::None); +} + +void test_logs_scrolling_and_retry_failed() { + cp0::UiController ctrl; + cp0::DaemonStatus st; + st.ok = true; + for (int i = 0; i < 10; ++i) { + cp0::LogEntry e; + e.id = 100 - i; + e.ts = 1731900000000LL + i * 1000LL; + e.level = (i % 3 == 0) ? "ERROR" : "INFO"; + e.message = "Entry " + std::to_string(i); + st.logs.push_back(e); + } + ctrl.update_status(st); + + // 'r' outside Logs tab does not emit RetryFailed + assert(ctrl.handle_key('r', cp0::KeyCode::Char).type == cp0::ActionType::None); + + // Switch to Logs tab + ctrl.handle_key('3', cp0::KeyCode::Char); + assert(ctrl.state().tab == cp0::ActiveTab::Logs); + assert(ctrl.state().log_scroll == 0); + + ctrl.handle_key('j', cp0::KeyCode::Char); + assert(ctrl.state().log_scroll == 1); + ctrl.handle_key(0, cp0::KeyCode::Down); + assert(ctrl.state().log_scroll == 2); + ctrl.handle_key('k', cp0::KeyCode::Char); + assert(ctrl.state().log_scroll == 1); + ctrl.handle_key(0, cp0::KeyCode::Up); + assert(ctrl.state().log_scroll == 0); + ctrl.handle_key(0, cp0::KeyCode::Up); + assert(ctrl.state().log_scroll == 0); + + for (int i = 0; i < 20; ++i) { + ctrl.handle_key('j', cp0::KeyCode::Char); + } + assert(ctrl.state().log_scroll == 9); + + auto retry = ctrl.handle_key('r', cp0::KeyCode::Char); + assert(retry.type == cp0::ActionType::RetryFailed); +} + +} // namespace + +int main() { + test_initial_state_and_global_navigation(); + test_theme_toggle_outside_vs_inside_modals(); + test_target_picker_and_manual_host(); + test_dir_picker_traversal_and_manual_path(); + test_folders_selection_and_confirm_remove(); + test_logs_scrolling_and_retry_failed(); + std::cout << "All test_ui_navigation assertions passed.\n"; + return 0; +}