diff --git a/app/CMakeLists.txt b/app/CMakeLists.txt index 398092b..0020e0e 100644 --- a/app/CMakeLists.txt +++ b/app/CMakeLists.txt @@ -10,9 +10,9 @@ option(CZ_TARGET_DEVICE "Build for CardputerZero Linux fbdev/evdev target" OFF) option(CZ_BUILD_TESTS "Build czcamera unit tests" ON) option(CZ_ENABLE_LVGL "Enable optional LVGL UI hook if available" OFF) +find_package(PkgConfig QUIET) find_package(JPEG QUIET) if(NOT JPEG_FOUND) - find_package(PkgConfig QUIET) if(PkgConfig_FOUND) pkg_check_modules(LIBJPEG IMPORTED_TARGET libjpeg) endif() @@ -22,7 +22,17 @@ if(NOT JPEG_FOUND) find_package(JPEG REQUIRED) endif() endif() + +set(CZ_FREETYPE_TARGET "") find_package(Freetype QUIET) +if(TARGET Freetype::Freetype) + set(CZ_FREETYPE_TARGET Freetype::Freetype) +elseif(PkgConfig_FOUND) + pkg_check_modules(FREETYPE QUIET IMPORTED_TARGET freetype2) + if(TARGET PkgConfig::FREETYPE) + set(CZ_FREETYPE_TARGET PkgConfig::FREETYPE) + endif() +endif() find_package(Threads REQUIRED) if(CZ_ENABLE_LVGL) @@ -41,6 +51,8 @@ add_library(czcamera_core STATIC src/timelapse_engine.cpp src/gallery_model.cpp src/video_player.cpp + src/ui_controller.cpp + src/app_ui.cpp ) target_include_directories(czcamera_core @@ -61,9 +73,12 @@ target_link_libraries(czcamera_core JPEG::JPEG ) -if(Freetype_FOUND) +if(CZ_FREETYPE_TARGET) target_compile_definitions(czcamera_core PUBLIC CZ_HAS_FREETYPE=1) - target_link_libraries(czcamera_core PUBLIC Freetype::Freetype) + target_link_libraries(czcamera_core PUBLIC ${CZ_FREETYPE_TARGET}) + message(STATUS "FreeType2 enabled via ${CZ_FREETYPE_TARGET}") +else() + message(STATUS "FreeType2 not found: using built-in 5x7 bitmap fallback") endif() if(CZ_ENABLE_LVGL AND lvgl_FOUND) @@ -82,10 +97,34 @@ if(CZ_BUILD_APP) add_executable(czcamera src/main.cpp) target_compile_options(czcamera PRIVATE -Wall -Wextra -Wpedantic) target_link_libraries(czcamera PRIVATE czcamera_core JPEG::JPEG) - if(NOT CZ_TARGET_DEVICE) - find_package(SDL2 REQUIRED) - target_link_libraries(czcamera PRIVATE SDL2::SDL2) + if(CZ_TARGET_DEVICE) + if(NOT CMAKE_SYSTEM_NAME STREQUAL "Linux") + message(FATAL_ERROR "CZ_TARGET_DEVICE=ON requires Linux (fbdev/evdev); got CMAKE_SYSTEM_NAME=${CMAKE_SYSTEM_NAME}") + endif() + message(STATUS "Target backend: Linux fbdev + evdev") + else() + set(CZ_SDL2_TARGET "") + if(PkgConfig_FOUND) + pkg_check_modules(SDL2 QUIET IMPORTED_TARGET sdl2) + if(TARGET PkgConfig::SDL2) + set(CZ_SDL2_TARGET PkgConfig::SDL2) + endif() + endif() + if(NOT CZ_SDL2_TARGET) + find_package(SDL2 REQUIRED) + if(TARGET SDL2::SDL2) + set(CZ_SDL2_TARGET SDL2::SDL2) + endif() + endif() + if(CZ_SDL2_TARGET) + target_link_libraries(czcamera PRIVATE ${CZ_SDL2_TARGET}) + else() + target_include_directories(czcamera PRIVATE ${SDL2_INCLUDE_DIRS}) + target_link_libraries(czcamera PRIVATE ${SDL2_LIBRARIES}) + endif() + message(STATUS "Target backend: SDL2 320x170 simulator") endif() + install(TARGETS czcamera RUNTIME DESTINATION bin) endif() if(CZ_BUILD_TESTS) @@ -112,4 +151,9 @@ if(CZ_BUILD_TESTS) target_compile_options(test_timelapse_and_gallery PRIVATE -Wall -Wextra -Wpedantic) target_link_libraries(test_timelapse_and_gallery PRIVATE czcamera_core) add_test(NAME test_timelapse_and_gallery COMMAND test_timelapse_and_gallery) + + add_executable(test_ui_controller tests/test_ui_controller.cpp) + target_compile_options(test_ui_controller PRIVATE -Wall -Wextra -Wpedantic) + target_link_libraries(test_ui_controller PRIVATE czcamera_core) + add_test(NAME test_ui_controller COMMAND test_ui_controller) endif() diff --git a/app/src/app_ui.cpp b/app/src/app_ui.cpp new file mode 100644 index 0000000..77a890c --- /dev/null +++ b/app/src/app_ui.cpp @@ -0,0 +1,1601 @@ +#include "app_ui.hpp" + +#include "filters.hpp" +#include "video_player.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(CP0_HAS_LVGL) +#include +#endif + +#if defined(CZ_HAS_FREETYPE) +#include +#include FT_FREETYPE_H +#endif + +namespace cz { + +namespace { + +// --------------------------------------------------------------------------- +// Formatting helpers +// --------------------------------------------------------------------------- + +std::string format_bytes_short(uint64_t bytes) { + std::ostringstream oss; + if (bytes < 1024ULL) { + oss << bytes << "B"; + } else if (bytes < 1024ULL * 1024ULL) { + oss << std::fixed << std::setprecision(0) + << (static_cast(bytes) / 1024.0) << "K"; + } else if (bytes < 1024ULL * 1024ULL * 1024ULL) { + oss << std::fixed << std::setprecision(1) + << (static_cast(bytes) / (1024.0 * 1024.0)) << "M"; + } else { + oss << std::fixed << std::setprecision(1) + << (static_cast(bytes) / (1024.0 * 1024.0 * 1024.0)) << "G"; + } + return oss.str(); +} + +std::string format_mmss(int total_sec) { + if (total_sec < 0) total_sec = 0; + const int mins = total_sec / 60; + const int secs = total_sec % 60; + char buf[24]; + std::snprintf(buf, sizeof(buf), "%02d:%02d", mins, secs); + return std::string(buf); +} + +std::string format_interval_short(int sec) { + if (sec >= 60 && (sec % 60) == 0) { + return std::to_string(sec / 60) + "m"; + } + return std::to_string(sec) + "s"; +} + +std::string format_zoom_str(float z) { + char buf[16]; + std::snprintf(buf, sizeof(buf), "%.1fx", static_cast(z)); + return std::string(buf); +} + +std::string format_ev_str(double ev) { + char buf[16]; + std::snprintf(buf, sizeof(buf), "%+.1f", ev); + return std::string(buf); +} + +std::string format_res_upper(const std::string& res) { + if (res == "8mp") return "8MP"; + if (res == "2mp") return "2MP"; + return res; +} + +std::string format_orient_display(const std::string& t) { + if (t == "0") return "0 deg"; + if (t == "180") return "180 deg"; + if (t == "hflip") return "H-Flip"; + if (t == "vflip") return "V-Flip"; + return "Auto"; +} + +std::string format_stop_short(const std::string& mode, int val) { + if (mode == "shots") return std::to_string(val) + "#"; + if (mode == "duration") { + if (val >= 3600 && (val % 3600) == 0) return std::to_string(val / 3600) + "h"; + if (val >= 60) return std::to_string(val / 60) + "m"; + return std::to_string(val) + "s"; + } + return "Man"; +} + +std::string pad3(int n) { + char buf[16]; + std::snprintf(buf, sizeof(buf), "%03d", std::max(0, n)); + return std::string(buf); +} + +// --------------------------------------------------------------------------- +// Built-in 5x7 ASCII bitmap font (0x20..0x7E) fallback +// --------------------------------------------------------------------------- + +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(CZ_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 / 5x7 Fallback +// --------------------------------------------------------------------------- + +class ShadcnCanvas { + public: + static constexpr int kW = AppView::kWidth; + static constexpr int kH = AppView::kHeight; + + ShadcnCanvas() : buf_(static_cast(kW * kH), 0xff09090bU) { + init_fonts(); + } + + ~ShadcnCanvas() { +#if defined(CZ_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) { + const 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) { + const int x0 = std::max(0, x); + const int y0 = std::max(0, y); + const int x1 = std::min(kW, x + w); + const 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) { + const int x0 = std::max(0, x); + const int y0 = std::max(0, y); + const int x1 = std::min(kW, x + w); + const int y1 = std::min(kH, y + h); + const 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_hline_alpha(int x, int y, int w, uint32_t rgb, uint8_t alpha) { + if (y < 0 || y >= kH) return; + const int x0 = std::max(0, x); + const int x1 = std::min(kW, x + w); + for (int px = x0; px < x1; ++px) { + blend_pixel(px, y, rgb, alpha); + } + } + + void draw_vline_alpha(int x, int y, int h, uint32_t rgb, uint8_t alpha) { + if (x < 0 || x >= kW) return; + const int y0 = std::max(0, y); + const int y1 = std::min(kH, y + h); + for (int py = y0; py < y1; ++py) { + blend_pixel(x, py, rgb, alpha); + } + } + + void draw_rgb24(int dst_x, + int dst_y, + int src_w, + int src_h, + const uint8_t* rgb24) { + if (!rgb24 || src_w <= 0 || src_h <= 0) return; + const int x0 = std::max(0, dst_x); + const int y0 = std::max(0, dst_y); + const int x1 = std::min(kW, dst_x + src_w); + const int y1 = std::min(kH, dst_y + src_h); + for (int py = y0; py < y1; ++py) { + const int sy = py - dst_y; + const uint8_t* srow = rgb24 + static_cast(sy * src_w) * 3u; + for (int px = x0; px < x1; ++px) { + const int sx = px - dst_x; + const uint8_t* sp = srow + static_cast(sx) * 3u; + buf_[static_cast(py * kW + px)] = + 0xff000000U | (static_cast(sp[0]) << 16) | + (static_cast(sp[1]) << 8) | + static_cast(sp[2]); + } + } + } + + 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; + } + const float r = + static_cast(std::max(0, std::min(radius, std::min(w, h) / 2))); + const float hx = static_cast(w) * 0.5f; + const float hy = static_cast(h) * 0.5f; + const float cx = static_cast(x) + hx; + const float cy = static_cast(y) + hy; + const float bw = static_cast(std::max(0, border_w)); + + const int x0 = std::max(0, x); + const int y0 = std::max(0, y); + const int x1 = std::min(kW, x + w); + const int y1 = std::min(kH, y + h); + + for (int py = y0; py < y1; ++py) { + for (int px = x0; px < x1; ++px) { + const float dx = + std::abs((static_cast(px) + 0.5f) - cx) - (hx - r); + const float dy = + std::abs((static_cast(py) + 0.5f) - cy) - (hy - r); + const float ox = std::max(dx, 0.0f); + const float oy = std::max(dy, 0.0f); + const float dist = + std::hypot(ox, oy) + std::min(std::max(dx, dy), 0.0f) - r; + + const float outer = std::clamp(0.5f - dist, 0.0f, 1.0f); + if (outer <= 0.001f) { + continue; + } + if (bw <= 0.0f) { + const uint8_t a = static_cast(std::lround(outer * 255.0f)); + blend_pixel(px, py, fill_rgb, a); + continue; + } + const float inner = std::clamp(0.5f - (dist + bw), 0.0f, 1.0f); + const float edge = std::max(0.0f, outer - inner); + if (inner > 0.001f) { + const uint8_t ia = static_cast(std::lround(inner * 255.0f)); + blend_pixel(px, py, fill_rgb, ia); + } + if (edge > 0.001f) { + const 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, + uint8_t max_alpha = 255) { + const int x0 = std::max(0, static_cast(std::floor(cx - radius - 1.0f))); + const int y0 = std::max(0, static_cast(std::floor(cy - radius - 1.0f))); + const int x1 = std::min(kW, static_cast(std::ceil(cx + radius + 1.0f))); + const 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) { + const float d = std::hypot((static_cast(px) + 0.5f) - cx, + (static_cast(py) + 0.5f) - cy); + float alpha_f = 0.0f; + if (hollow) { + const 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) { + const uint8_t a = static_cast( + std::lround(alpha_f * static_cast(max_alpha))); + blend_pixel(px, py, rgb, a); + } + } + } + } + + void draw_play_triangle(int cx, int cy, int half_h, uint32_t rgb) { + const int left_x = cx - half_h / 2; + const int width = half_h + 2; + for (int col = 0; col <= width; ++col) { + const float t = static_cast(col) / static_cast(width); + const int span = static_cast(std::lround((1.0f - t) * half_h)); + for (int dy = -span; dy <= span; ++dy) { + blend_pixel(left_x + col, cy + dy, rgb, 245); + } + } + } + + int measure_text(FontRole role, int px_size, const std::string& text) { +#if defined(CZ_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 + const int scale = (px_size >= 14) ? 2 : 1; + return static_cast(text.size()) * 6 * 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 = "..."; + if (measure_text(role, px_size, ell) > 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(CZ_HAS_FREETYPE) + FT_Face face = select_face(role); + if (face != nullptr) { + FT_Set_Pixel_Sizes(face, 0, static_cast(px_size)); + const int ascender = static_cast(face->size->metrics.ascender >> 6); + const 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; + } + const int gx = pen_x + g->left; + const int gy = baseline_y - g->top; + for (int r = 0; r < g->rows; ++r) { + for (int c = 0; c < g->width; ++c) { + const 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 + const 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) { + const 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(CZ_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("CZCAMERA_FONT_SANS")) { + sans_candidates.emplace_back(env_sans); + } else { + sans_candidates = { + "/usr/share/czcamera/fonts/Inter-Regular.ttf", + "/usr/share/czcamera/fonts/Inter.ttf", + "assets/fonts/Inter-Regular.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("CZCAMERA_FONT_MONO")) { + mono_candidates.emplace_back(env_mono); + } else { + mono_candidates = { + "/usr/share/czcamera/fonts/JetBrainsMono-Regular.ttf", + "/usr/share/czcamera/fonts/JetBrainsMono.ttf", + "assets/fonts/JetBrainsMono-Regular.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(CZ_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) { + const uint64_t key = + (static_cast(role == FontRole::Mono ? 1 : 0) << 48) | + (static_cast(px_size & 0xffff) << 32) | + static_cast(codepoint); + const 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) { + const uint8_t byte = src[c >> 3]; + const bool on = (byte & (0x80U >> (c & 7))) != 0; + cg.alpha[static_cast(r * cg.width + c)] = on ? 255 : 0; + } + } + } + + auto [ins_it, inserted] = glyph_cache_.emplace(key, std::move(cg)); + (void)inserted; + 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; + } + const size_t idx = static_cast(y * kW + x); + if (alpha == 255) { + buf_[idx] = 0xff000000U | (fg_rgb & 0x00ffffffU); + return; + } + const uint32_t bg = buf_[idx]; + const uint32_t a = alpha; + const uint32_t inv = 255U - a; + const uint32_t fr = (fg_rgb >> 16) & 0xffU; + const uint32_t fg = (fg_rgb >> 8) & 0xffU; + const uint32_t fb = fg_rgb & 0xffU; + const uint32_t br = (bg >> 16) & 0xffU; + const uint32_t bg_c = (bg >> 8) & 0xffU; + const uint32_t bb = bg & 0xffU; + const uint32_t rr = (fr * a + br * inv + 127U) / 255U; + const uint32_t rg = (fg * a + bg_c * inv + 127U) / 255U; + const 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(CZ_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 +// --------------------------------------------------------------------------- + +void draw_kbd_hint(ShadcnCanvas& canvas, + const ShadcnPalette& pal, + int& cursor_x, + int y, + const std::string& key_text, + const std::string& label, + int px_size = 9, + int gap_after = 6) { + const int kw = canvas.measure_text(FontRole::Mono, px_size, key_text) + 5; + const int chip_h = (px_size <= 8) ? 11 : 13; + canvas.draw_round_box(cursor_x, y, kw, chip_h, 3, pal.card, pal.border, 1); + canvas.draw_text(FontRole::Mono, px_size, cursor_x + 3, y + 1, key_text, + pal.foreground); + cursor_x += kw + 2; + canvas.draw_text(FontRole::Sans, px_size, cursor_x, y + 1, label, + pal.muted_foreground); + cursor_x += + canvas.measure_text(FontRole::Sans, px_size, label) + gap_after; +} + +int measure_pill_badge_w(ShadcnCanvas& canvas, + const std::string& text, + bool with_dot) { + const int text_w = canvas.measure_text(FontRole::Sans, 9, text); + return (with_dot ? 9 : 0) + text_w + 10; +} + +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) { + const int w = measure_pill_badge_w(canvas, text, with_dot); + 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, false); + tx += 8; + } + canvas.draw_text(FontRole::Sans, 9, tx, y + (h - 10) / 2, text, fg_rgb); +} + +struct RailCardSpec { + std::string label; + std::string value; + uint32_t value_color = 0; + bool custom_color = false; +}; + +} // namespace + +struct AppView::Impl { + ThemeMode theme = ThemeMode::Dark; + ShadcnPalette pal = get_palette(ThemeMode::Dark); + ShadcnCanvas canvas; + std::vector scaled_vf; + std::vector scaled_gal; + +#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; + + void sync_lvgl_styles() { + if (!lv_is_initialized()) { + lv_init(); + } + 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 + + ~Impl() { +#if defined(CP0_HAS_LVGL) + if (lvgl_styles_inited) { + lv_style_reset(&style_bg); + lv_style_reset(&style_card); + lvgl_styles_inited = false; + } +#endif + } + + void render_viewfinder(const UiState& state, + const PreviewFrame* live_frame, + int vf_x) { + constexpr int kVfW = 226; + constexpr int kVfH = 170; + canvas.fill_rect(vf_x, 0, kVfW, kVfH, pal.viewfinder_surround); + + const bool is_16_9 = + (state.mode == AppMode::Video) || + (state.mode == AppMode::Timelapse && + state.config.timelapse_resolution == "1080p") || + (live_frame != nullptr && live_frame->is_16_9); + + const int feed_w = kVfW; + const int feed_h = is_16_9 ? 127 : kVfH; + const int feed_y = is_16_9 ? 21 : 0; + + if (live_frame != nullptr && !live_frame->rgb24.empty() && + live_frame->width > 0 && live_frame->height > 0) { + scaled_vf.resize(static_cast(feed_w) * static_cast(feed_h) * + 3u); + const float loupe = + (state.mode == AppMode::Photo && state.loupe_enabled) ? 2.0f : 1.0f; + scale_crop_rgb24(live_frame->rgb24.data(), live_frame->width, + live_frame->height, scaled_vf.data(), feed_w, feed_h, + loupe); + if (state.mode == AppMode::Photo && state.filter != FilterId::None) { + apply_filter_rgb24(scaled_vf.data(), feed_w, feed_h, state.filter); + } + canvas.draw_rgb24(vf_x, feed_y, feed_w, feed_h, scaled_vf.data()); + } else { + const std::string msg = state.backend_paused + ? "Camera Paused" + : (state.backend_ready ? "Waiting for frame..." + : "Camera Offline [R]"); + const int mw = canvas.measure_text(FontRole::Sans, 9, msg); + canvas.draw_text(FontRole::Sans, 9, vf_x + (kVfW - mw) / 2, 79, msg, + pal.muted_foreground); + } + + // Rule-of-thirds overlay + if (state.config.grid_enabled) { + const int vx1 = vf_x + feed_w / 3; + const int vx2 = vf_x + (feed_w * 2) / 3; + const int hy1 = feed_y + feed_h / 3; + const int hy2 = feed_y + (feed_h * 2) / 3; + canvas.draw_vline_alpha(vx1, feed_y, feed_h, 0xffffff, 72); + canvas.draw_vline_alpha(vx2, feed_y, feed_h, 0xffffff, 72); + canvas.draw_hline_alpha(vf_x, hy1, feed_w, 0xffffff, 72); + canvas.draw_hline_alpha(vf_x, hy2, feed_w, 0xffffff, 72); + } + + // Top-left active modifier / recording badge + const int badge_y = is_16_9 ? 4 : 5; + if (state.mode == AppMode::Video && state.video_recording) { + const std::string rec = "REC " + format_mmss(state.video_elapsed_sec); + draw_pill_badge(canvas, vf_x + 5, badge_y, 16, rec, pal.status_error_bg, + pal.status_error, pal.status_error, true); + } else if (state.mode == AppMode::Timelapse && state.timelapse.running) { + const std::string tl = "TL " + pad3(state.timelapse.shots_taken); + draw_pill_badge(canvas, vf_x + 5, badge_y, 16, tl, pal.status_online_bg, + pal.status_online, pal.status_online, true); + } else if (state.mode == AppMode::Photo && state.filter != FilterId::None) { + const std::string flt = filter_display_name(state.filter); + draw_pill_badge(canvas, vf_x + 5, badge_y, 16, flt, + pal.status_sleeping_bg, pal.status_sleeping, + pal.status_sleeping, false); + } + + // Top-right Zoom / Loupe badge + int right_edge = vf_x + kVfW - 5; + if (state.mode == AppMode::Photo && state.loupe_enabled) { + const std::string ltext = "LOUPE 2x"; + const int lw = measure_pill_badge_w(canvas, ltext, false); + draw_pill_badge(canvas, right_edge - lw, badge_y, 16, ltext, + pal.status_sleeping_bg, pal.status_sleeping, + pal.status_sleeping, false); + right_edge -= lw + 4; + } + if (state.zoom > 1.05f) { + const std::string ztext = format_zoom_str(state.zoom); + const int zw = measure_pill_badge_w(canvas, ztext, false); + draw_pill_badge(canvas, right_edge - zw, badge_y, 16, ztext, pal.card, + pal.ring, pal.foreground, false); + } + + // Self-timer countdown overlay + if (state.mode == AppMode::Photo && state.timer_active) { + canvas.draw_round_box(vf_x + 83, 55, 60, 54, 8, pal.card, + pal.status_sleeping, 2); + const std::string num = std::to_string(state.timer_remaining_sec); + const int nw = canvas.measure_text(FontRole::Mono, 18, num); + canvas.draw_text(FontRole::Mono, 18, vf_x + 83 + (60 - nw) / 2, 62, num, + pal.status_sleeping); + const std::string hint = "Esc cancel"; + const int hw = canvas.measure_text(FontRole::Sans, 8, hint); + canvas.draw_text(FontRole::Sans, 8, vf_x + 83 + (60 - hw) / 2, 93, hint, + pal.muted_foreground); + } + + // Capture flash white border + if (state.capture_flash_active) { + canvas.fill_rect(vf_x, 0, kVfW, 3, 0xffffff); + canvas.fill_rect(vf_x, kVfH - 3, kVfW, 3, 0xffffff); + canvas.fill_rect(vf_x, 0, 3, kVfH, 0xffffff); + canvas.fill_rect(vf_x + kVfW - 3, 0, 3, kVfH, 0xffffff); + } + + // Non-blocking bottom toast inside viewfinder + if (state.modal == OverlayModal::None && !state.toast_message.empty()) { + const uint32_t bg = + state.toast_is_error ? pal.status_error_bg : pal.status_online_bg; + const uint32_t fg = + state.toast_is_error ? pal.status_error : pal.status_online; + canvas.draw_round_box(vf_x + 6, 146, kVfW - 12, 18, 4, bg, fg, 1); + canvas.draw_circle(static_cast(vf_x + 15), 155.0f, 2.5f, fg, + false); + const std::string fit = + canvas.truncate_right(FontRole::Mono, 9, state.toast_message, + kVfW - 32); + canvas.draw_text(FontRole::Mono, 9, vf_x + 22, 150, fit, fg); + } + } + + void render_control_rail(const UiState& state, int rail_x) { + constexpr int kRailW = 94; + const bool rail_left = (state.config.rail_side == "left"); + canvas.fill_rect(rail_x, 0, kRailW, AppView::kHeight, pal.background); + + // 1px divider border between viewfinder and rail + const int div_x = rail_left ? (rail_x + kRailW - 1) : rail_x; + canvas.fill_rect(div_x, 0, 1, AppView::kHeight, pal.border); + + const int inner_x = rail_left ? (rail_x + 4) : (rail_x + 5); + constexpr int kInnerW = 85; + + // 1. Segmented TabsList Mode Switcher: 1P · 2V · 3T + canvas.draw_round_box(inner_x, 4, kInnerW, 18, 5, pal.muted, pal.border, 1); + const char* tabs[3] = {"1P", "2V", "3T"}; + constexpr int kSegW = 27; + for (int i = 0; i < 3; ++i) { + const int sx = inner_x + 2 + i * kSegW; + const bool active = (static_cast(state.mode) == i); + if (active) { + const uint32_t border = + (pal.active_tab != pal.muted) ? pal.border : pal.active_tab; + const int bw = (pal.active_tab != pal.muted) ? 1 : 0; + canvas.draw_round_box(sx, 6, kSegW, 14, 4, pal.active_tab, border, bw); + } + const uint32_t fg = + active ? pal.active_tab_foreground : pal.muted_foreground; + const int tw = canvas.measure_text(FontRole::Sans, 9, tabs[i]); + canvas.draw_text(FontRole::Sans, 9, sx + (kSegW - tw) / 2, 8, tabs[i], + fg); + } + + // 2. 4 Focusable Telemetry / Setting Cards + std::array cards; + switch (state.mode) { + case AppMode::Photo: + cards[0] = {"RES", format_res_upper(state.config.photo_resolution), 0, + false}; + cards[1] = {"EV", format_ev_str(state.config.ev), 0, false}; + cards[2] = {"FLT", filter_display_name(state.filter), + pal.status_sleeping, state.filter != FilterId::None}; + cards[3] = { + "TMR", + state.config.photo_timer_sec > 0 + ? (std::to_string(state.config.photo_timer_sec) + "s") + : "Off", + pal.status_sleeping, state.config.photo_timer_sec > 0}; + break; + case AppMode::Video: + cards[0] = {"VID", state.config.video_resolution, 0, false}; + cards[1] = {"MIC", state.config.video_audio ? "ON" : "MUTE", + state.config.video_audio ? pal.status_online + : pal.status_sleeping, + true}; + cards[2] = {"ZOOM", format_zoom_str(state.zoom), 0, false}; + cards[3] = {"FREE", format_bytes_short(state.free_bytes), 0, false}; + break; + case AppMode::Timelapse: + if (state.timelapse.running) { + std::string shot_str = pad3(state.timelapse.shots_taken); + if (state.timelapse.stop_mode == "shots" && + state.timelapse.stop_value > 0) { + shot_str += "/" + std::to_string(state.timelapse.stop_value); + } + cards[0] = {"SHOT", shot_str, pal.status_online, true}; + cards[1] = { + "NEXT", + std::to_string(state.timelapse.next_shot_in_sec) + "s", + 0, + false}; + cards[2] = {"TIME", format_mmss(state.timelapse.elapsed_sec), 0, + false}; + cards[3] = {"FREE", format_bytes_short(state.free_bytes), 0, false}; + } else { + cards[0] = { + "INT", + format_interval_short(state.config.timelapse_interval_sec), + 0, + false}; + cards[1] = { + "OUT", + state.config.timelapse_output_mode == "photos" ? "JPG" : "MP4", + 0, + false}; + cards[2] = {"RES", + format_res_upper(state.config.timelapse_resolution), 0, + false}; + cards[3] = { + "STOP", + format_stop_short(state.config.timelapse_stop_mode, + state.config.timelapse_stop_value), + 0, + false}; + } + break; + } + + for (int i = 0; i < 4; ++i) { + const int cy = 25 + i * 29; + const bool focused = (!state.timelapse.running && state.rail_cursor == i); + canvas.draw_round_box(inner_x, cy, kInnerW, 26, 4, + focused ? pal.card : pal.muted, + focused ? pal.ring : pal.border, 1); + if (focused) { + canvas.fill_rect(inner_x + 2, cy + 5, 2, 16, pal.ring); + } + const int text_x = inner_x + (focused ? 7 : 5); + canvas.draw_text(FontRole::Sans, 8, text_x, cy + 2, cards[i].label, + pal.muted_foreground); + const uint32_t vcol = + cards[i].custom_color ? cards[i].value_color : pal.foreground; + const std::string vfit = + canvas.truncate_right(FontRole::Mono, 10, cards[i].value, + kInnerW - (focused ? 10 : 8)); + canvas.draw_text(FontRole::Mono, 10, text_x, cy + 12, vfit, vcol); + } + + // 3. Compact Footer Hints + const int fx = rail_left ? rail_x : (rail_x + 1); + canvas.fill_rect(fx, 139, kRailW - 1, 1, pal.border); + canvas.fill_rect(fx, 140, kRailW - 1, 30, pal.muted); + + int hx1 = inner_x; + int hx2 = inner_x; + if (state.mode == AppMode::Photo) { + draw_kbd_hint(canvas, pal, hx1, 143, "Ent", "Shot", 8, 3); + draw_kbd_hint(canvas, pal, hx1, 143, "8", "Gal", 8, 2); + draw_kbd_hint(canvas, pal, hx2, 156, "5/7", "Zm", 8, 3); + draw_kbd_hint(canvas, pal, hx2, 156, "S", "Set", 8, 2); + } else if (state.mode == AppMode::Video) { + if (state.video_recording) { + draw_kbd_hint(canvas, pal, hx1, 143, "Esc", "Stop Rec", 8, 2); + draw_kbd_hint(canvas, pal, hx2, 156, "5/7", "Zoom", 8, 2); + } else { + draw_kbd_hint(canvas, pal, hx1, 143, "Ent", "Rec", 8, 4); + draw_kbd_hint(canvas, pal, hx1, 143, "M", "Mic", 8, 2); + draw_kbd_hint(canvas, pal, hx2, 156, "5/7", "Zm", 8, 3); + draw_kbd_hint(canvas, pal, hx2, 156, "S", "Set", 8, 2); + } + } else { + if (state.timelapse.running) { + draw_kbd_hint(canvas, pal, hx1, 143, "Esc", "Stop", 8, 2); + canvas.draw_text(FontRole::Sans, 8, inner_x, 157, "Capturing...", + pal.status_online); + } else { + draw_kbd_hint(canvas, pal, hx1, 143, "Ent", "Go", 8, 4); + draw_kbd_hint(canvas, pal, hx1, 143, "C", "Cust", 8, 2); + draw_kbd_hint(canvas, pal, hx2, 156, "8", "Gal", 8, 4); + draw_kbd_hint(canvas, pal, hx2, 156, "S", "Set", 8, 2); + } + } + } + + void render_gallery(const UiState& state, const PreviewFrame* gallery_frame) { + // Top bar (22 px) + canvas.fill_rect(0, 0, AppView::kWidth, 22, pal.muted); + canvas.fill_rect(0, 21, AppView::kWidth, 1, pal.border); + + const std::string title = + state.gallery_in_session ? state.gallery_session_name : "Gallery"; + const int total = static_cast(state.gallery_items.size()); + const int cur_num = (total > 0) ? (state.gallery_cursor + 1) : 0; + const std::string idx_str = + std::to_string(cur_num) + "/" + std::to_string(total); + const std::string left_title = + canvas.truncate_right(FontRole::Sans, 10, title, 105); + canvas.draw_text(FontRole::Sans, 10, 6, 5, left_title, pal.foreground); + const int tw = canvas.measure_text(FontRole::Sans, 10, left_title); + canvas.draw_text(FontRole::Mono, 9, 10 + tw, 6, idx_str, + pal.muted_foreground); + const int left_used = 10 + tw + canvas.measure_text(FontRole::Mono, 9, idx_str); + + if (total > 0 && state.gallery_cursor >= 0 && + state.gallery_cursor < total) { + const auto& item = + state.gallery_items[static_cast(state.gallery_cursor)]; + std::string meta = item.filename; + if (item.type == GalleryItemType::Photo) { + if (item.width >= 3000) { + meta += " | 8MP"; + } else if (item.width > 0) { + meta += " | 2MP"; + } + meta += " | " + format_bytes_short(item.size_bytes); + } else if (item.type == GalleryItemType::Video) { + if (item.duration_sec > 0.0) { + meta += " | " + format_mmss(static_cast(std::lround(item.duration_sec))); + } + meta += " | " + format_bytes_short(item.size_bytes); + } else { + meta += " | " + std::to_string(item.photo_count) + "p"; + } + const int max_meta_w = std::max(40, AppView::kWidth - 8 - left_used - 6); + const std::string meta_fit = + canvas.truncate_left_path(FontRole::Mono, 9, meta, max_meta_w); + const int mw = canvas.measure_text(FontRole::Mono, 9, meta_fit); + canvas.draw_text(FontRole::Mono, 9, AppView::kWidth - 6 - mw, 6, meta_fit, + pal.muted_foreground); + } + + // Center viewport (y=22..149, h=128) + canvas.fill_rect(0, 22, AppView::kWidth, 128, pal.viewfinder_surround); + if (total == 0) { + const std::string empty = "No captures yet"; + const int ew = canvas.measure_text(FontRole::Sans, 11, empty); + canvas.draw_text(FontRole::Sans, 11, (AppView::kWidth - ew) / 2, 72, + empty, pal.muted_foreground); + const std::string sub = "Press [Esc] to return to camera"; + const int sw = canvas.measure_text(FontRole::Sans, 9, sub); + canvas.draw_text(FontRole::Sans, 9, (AppView::kWidth - sw) / 2, 90, sub, + pal.muted_foreground); + } else { + if (gallery_frame != nullptr && !gallery_frame->rgb24.empty() && + gallery_frame->width > 0 && gallery_frame->height > 0) { + int draw_w = gallery_frame->width; + int draw_h = gallery_frame->height; + const uint8_t* draw_ptr = gallery_frame->rgb24.data(); + if (draw_w > AppView::kWidth || draw_h > 128) { + if (media_detail::aspect_scale_rgb24(draw_ptr, draw_w, draw_h, + AppView::kWidth, 128, scaled_gal, + draw_w, draw_h)) { + draw_ptr = scaled_gal.data(); + } + } + const int dx = (AppView::kWidth - draw_w) / 2; + const int dy = 22 + (128 - draw_h) / 2; + canvas.draw_rgb24(dx, dy, draw_w, draw_h, draw_ptr); + } else { + const std::string noprev = "Preview unavailable"; + const int nw = canvas.measure_text(FontRole::Sans, 9, noprev); + canvas.draw_text(FontRole::Sans, 9, (AppView::kWidth - nw) / 2, 80, + noprev, pal.muted_foreground); + } + + const auto& item = + state.gallery_items[static_cast(state.gallery_cursor)]; + if (item.type == GalleryItemType::Video) { + if (!state.video_player.playing) { + canvas.draw_circle(160.0f, 80.0f, 15.0f, pal.background, false, 185); + canvas.draw_circle(160.0f, 80.0f, 15.0f, pal.ring, true, 220); + canvas.draw_play_triangle(159, 80, 7, pal.foreground); + } + + // Seek progress bar + time pill + const double dur = + std::max(state.video_player.duration_sec, item.duration_sec); + const double frac = + (dur > 0.01) + ? std::clamp(state.video_player.position_sec / dur, 0.0, 1.0) + : 0.0; + const std::string tstr = + format_mmss(static_cast(std::floor(state.video_player.position_sec))) + + " / " + format_mmss(static_cast(std::lround(dur))); + draw_pill_badge(canvas, 8, 122, 15, tstr, pal.card, pal.border, + pal.foreground, false); + if (state.video_player.muted) { + const std::string mtxt = "MUTE"; + const int mw = measure_pill_badge_w(canvas, mtxt, false); + draw_pill_badge(canvas, AppView::kWidth - 8 - mw, 122, 15, mtxt, + pal.status_sleeping_bg, pal.status_sleeping, + pal.status_sleeping, false); + } + + canvas.draw_round_box(8, 141, 304, 5, 2, pal.muted, pal.border, 1); + const int fill_w = + static_cast(std::lround(frac * 302.0)); + if (fill_w > 0) { + canvas.fill_rect(9, 142, fill_w, 3, pal.status_online); + } + } else if (item.type == GalleryItemType::TimelapseFolder) { + const std::string tag = + "FOLDER | " + std::to_string(item.photo_count) + + " photos | [Ent] Open"; + const int tw2 = measure_pill_badge_w(canvas, tag, false); + draw_pill_badge(canvas, (AppView::kWidth - tw2) / 2, 128, 16, tag, + pal.card, pal.ring, pal.foreground, false); + } + } + + if (!state.toast_message.empty()) { + const uint32_t bg = + state.toast_is_error ? pal.status_error_bg : pal.status_online_bg; + const uint32_t fg = + state.toast_is_error ? pal.status_error : pal.status_online; + canvas.draw_round_box(16, 26, 288, 17, 4, bg, fg, 1); + const std::string fit = + canvas.truncate_right(FontRole::Mono, 9, state.toast_message, 274); + canvas.draw_text(FontRole::Mono, 9, 23, 30, fit, fg); + } + + // Bottom bar (y=150..169) + if (state.gallery_delete_confirm && total > 0) { + const auto& item = + state.gallery_items[static_cast(state.gallery_cursor)]; + canvas.fill_rect(0, 150, AppView::kWidth, 20, pal.status_error_bg); + canvas.fill_rect(0, 150, AppView::kWidth, 1, pal.status_error); + std::string prompt; + if (item.type == GalleryItemType::TimelapseFolder) { + prompt = "Delete folder (" + std::to_string(item.photo_count) + + " photos)? [Y] Del [N] Cancel"; + } else { + prompt = "Delete " + + canvas.truncate_right(FontRole::Mono, 9, item.filename, 110) + + "? [Y] Del [N] Cancel"; + } + const std::string pfit = + canvas.truncate_right(FontRole::Mono, 9, prompt, 308); + canvas.draw_text(FontRole::Mono, 9, 6, 155, pfit, pal.status_error); + return; + } + + canvas.fill_rect(0, 150, AppView::kWidth, 20, pal.muted); + canvas.fill_rect(0, 150, AppView::kWidth, 1, pal.border); + int x = 6; + const int y = 154; + if (total > 0) { + const auto& item = + state.gallery_items[static_cast(state.gallery_cursor)]; + if (item.type == GalleryItemType::Video) { + draw_kbd_hint(canvas, pal, x, y, "", "Nav", 9, 4); + draw_kbd_hint(canvas, pal, x, y, "Spc", + state.video_player.playing ? "Pause" : "Play", 9, 4); + draw_kbd_hint(canvas, pal, x, y, "M", "Mute", 9, 4); + draw_kbd_hint(canvas, pal, x, y, "D", "Del", 9, 4); + draw_kbd_hint(canvas, pal, x, y, "Esc", "Back", 9, 2); + } else if (item.type == GalleryItemType::TimelapseFolder) { + draw_kbd_hint(canvas, pal, x, y, "", "Nav", 9, 5); + draw_kbd_hint(canvas, pal, x, y, "Ent", "Open", 9, 5); + draw_kbd_hint(canvas, pal, x, y, "D", "Del", 9, 5); + draw_kbd_hint(canvas, pal, x, y, "Esc", "Back", 9, 2); + } else if (state.gallery_in_session) { + draw_kbd_hint(canvas, pal, x, y, "", "Nav", 9, 5); + draw_kbd_hint(canvas, pal, x, y, "D", "Del", 9, 5); + draw_kbd_hint(canvas, pal, x, y, "Bksp", "Root", 9, 5); + draw_kbd_hint(canvas, pal, x, y, "Esc", "Back", 9, 2); + } else { + draw_kbd_hint(canvas, pal, x, y, "", "Nav", 9, 5); + draw_kbd_hint(canvas, pal, x, y, "D", "Del", 9, 5); + draw_kbd_hint(canvas, pal, x, y, "T", "Theme", 9, 5); + draw_kbd_hint(canvas, pal, x, y, "Esc", "Back", 9, 2); + } + } else { + draw_kbd_hint(canvas, pal, x, y, "T", "Theme", 9, 6); + draw_kbd_hint(canvas, pal, x, y, "Esc", "Back to Camera", 9, 4); + } + } + + void render_modal(const UiState& state) { + if (state.modal == OverlayModal::None || + state.modal == OverlayModal::Gallery) { + return; + } + + canvas.dim_rect(0, 0, AppView::kWidth, 150, 0x000000, 155); + + if (state.modal == OverlayModal::Settings) { + canvas.draw_round_box(12, 8, 296, 138, 6, pal.card, pal.ring, 1); + canvas.draw_text(FontRole::Sans, 10, 20, 13, "Settings", pal.foreground); + const std::string esc_hint = "[Esc] Save"; + const int ew = canvas.measure_text(FontRole::Mono, 9, esc_hint); + canvas.draw_text(FontRole::Mono, 9, 300 - ew, 14, esc_hint, + pal.muted_foreground); + canvas.fill_rect(18, 27, 284, 1, pal.border); + + struct SettingRow { + std::string label; + std::string value; + bool is_path = false; + }; + const std::string dim_val = + state.config.timelapse_dim_sec > 0 + ? (std::to_string(state.config.timelapse_dim_sec) + "s") + : "Off"; + const std::array rows = {{ + {"Output Dir", state.config.output_dir, true}, + {"Control Rail", + state.config.rail_side == "left" ? "Left" : "Right", false}, + {"Theme", state.theme == ThemeMode::Light ? "Light" : "Dark", false}, + {"Grid Overlay", state.config.grid_enabled ? "On" : "Off", false}, + {"Timelapse Dim", dim_val, false}, + {"Camera Orient", + format_orient_display(state.config.camera_transform), false}, + }}; + + for (int i = 0; i < 6; ++i) { + const int ry = 30 + i * 19; + const bool sel = (state.settings_cursor == i); + canvas.draw_round_box(18, ry, 284, 17, 4, + sel ? pal.muted : pal.card, + sel ? pal.ring : pal.border, 1); + canvas.draw_text(FontRole::Sans, 9, 24, ry + 4, rows[i].label, + sel ? pal.foreground : pal.muted_foreground); + const std::string val_fit = + rows[i].is_path + ? canvas.truncate_left_path(FontRole::Mono, 9, rows[i].value, + 175) + : canvas.truncate_right(FontRole::Mono, 9, rows[i].value, 140); + const int vw = canvas.measure_text(FontRole::Mono, 9, val_fit); + canvas.draw_text(FontRole::Mono, 9, 296 - vw, ry + 4, val_fit, + pal.foreground); + } + } else if (state.modal == OverlayModal::DirPicker) { + canvas.draw_round_box(12, 12, 296, 134, 6, pal.card, pal.ring, 1); + canvas.draw_text(FontRole::Sans, 10, 20, 17, "Select Output Directory", + pal.foreground); + const std::string manual_hint = "[T] Manual"; + const int hw = canvas.measure_text(FontRole::Mono, 9, manual_hint); + canvas.draw_text(FontRole::Mono, 9, 300 - hw, 18, manual_hint, + pal.muted_foreground); + + canvas.draw_round_box(18, 32, 284, 16, 3, pal.muted, pal.border, 1); + const std::string cur_fit = canvas.truncate_left_path( + FontRole::Mono, 9, state.dir_current_path, 272); + canvas.draw_text(FontRole::Mono, 9, 24, 35, cur_fit, pal.foreground); + + if (state.dir_entries.empty()) { + canvas.draw_text(FontRole::Sans, 9, 22, 72, + "(No subdirs - Space selects current dir)", + pal.muted_foreground); + } else { + constexpr int kRows = 4; + const 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) { + const int idx = start + r; + const bool sel = (idx == state.dir_cursor); + const int ry = 52 + 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)]; + const size_t slash = full.rfind('/'); + const std::string name = + (slash != std::string::npos) ? full.substr(slash + 1) : full; + const std::string fit = + canvas.truncate_right(FontRole::Mono, 9, "> " + name + "/", 268); + canvas.draw_text(FontRole::Mono, 9, 24, ry + 5, fit, pal.foreground); + } + } + } else if (state.modal == OverlayModal::TextInput) { + canvas.draw_round_box(18, 28, 284, 96, 6, pal.card, pal.ring, 1); + canvas.draw_text(FontRole::Sans, 10, 28, 38, "Enter Output Directory", + pal.foreground); + canvas.draw_round_box(28, 56, 264, 24, 4, pal.muted, pal.ring, 1); + const std::string shown = canvas.truncate_left_path( + FontRole::Mono, 10, state.text_buffer + "_", 250); + canvas.draw_text(FontRole::Mono, 10, 35, 63, shown, pal.foreground); + + if (!state.modal_error.empty()) { + const std::string err = + canvas.truncate_right(FontRole::Sans, 9, state.modal_error, 264); + canvas.draw_text(FontRole::Sans, 9, 28, 90, err, pal.status_error); + } else { + canvas.draw_text(FontRole::Mono, 9, 28, 90, + "Example: ~/Pictures/czcamera", pal.muted_foreground); + } + } else if (state.modal == OverlayModal::TimelapseCustomInput) { + canvas.draw_round_box(18, 16, 284, 124, 6, pal.card, pal.ring, 1); + canvas.draw_text(FontRole::Sans, 10, 26, 22, "Timelapse Setup", + pal.foreground); + canvas.fill_rect(24, 36, 272, 1, pal.border); + + std::string stop_val_str = "Off"; + if (state.tl_custom_stop_mode == "shots") { + stop_val_str = std::to_string(state.tl_custom_stop_value) + " shots"; + } else if (state.tl_custom_stop_mode == "duration") { + stop_val_str = + std::to_string(std::max(1, state.tl_custom_stop_value / 60)) + " min"; + } + + const std::array, 4> rows = {{ + {"Interval (s)", + std::to_string(state.tl_custom_interval_sec) + "s"}, + {"Video FPS", std::to_string(state.tl_custom_fps) + " fps"}, + {"Stop Mode", state.tl_custom_stop_mode}, + {"Stop Value", stop_val_str}, + }}; + for (int i = 0; i < 4; ++i) { + const int ry = 42 + i * 22; + const bool sel = (state.tl_custom_cursor == i); + canvas.draw_round_box(24, ry, 272, 19, 4, + sel ? pal.muted : pal.card, + sel ? pal.ring : pal.border, 1); + canvas.draw_text(FontRole::Sans, 9, 30, ry + 5, rows[i].first, + sel ? pal.foreground : pal.muted_foreground); + const int vw = + canvas.measure_text(FontRole::Mono, 9, rows[i].second); + canvas.draw_text(FontRole::Mono, 9, 290 - vw, ry + 5, rows[i].second, + pal.foreground); + } + } else if (state.modal == OverlayModal::TimelapseRecovery) { + canvas.draw_round_box(16, 22, 288, 114, 6, pal.card, pal.ring, 1); + canvas.draw_text(FontRole::Sans, 10, 26, 30, "Unfinished Timelapse Found", + pal.status_sleeping); + canvas.fill_rect(24, 46, 272, 1, pal.border); + + const std::string line1 = + "Session: " + + canvas.truncate_right(FontRole::Mono, 9, + state.recovery_manifest.session_id, 185); + const std::string line2 = + "Frames: " + std::to_string(state.recovery_manifest.frame_count) + + " (" + format_res_upper(state.recovery_manifest.resolution) + ")"; + canvas.draw_text(FontRole::Mono, 9, 26, 54, line1, pal.foreground); + canvas.draw_text(FontRole::Mono, 9, 26, 70, line2, pal.muted_foreground); + canvas.draw_text(FontRole::Mono, 9, 26, 94, + "[C] Compile MP4 [K] Keep Photos", pal.status_online); + canvas.draw_text(FontRole::Mono, 9, 26, 110, + "[D] Discard [Esc] Later", pal.status_error); + } else if (state.modal == OverlayModal::TimelapseStopConfirm) { + canvas.draw_round_box(26, 32, 268, 92, 6, pal.card, pal.ring, 1); + canvas.draw_text(FontRole::Sans, 10, 38, 42, "Stop Active Timelapse?", + pal.foreground); + const std::string info = + "Shots: " + std::to_string(state.timelapse.shots_taken) + + " Elapsed: " + format_mmss(state.timelapse.elapsed_sec); + canvas.draw_text(FontRole::Mono, 9, 38, 62, info, pal.muted_foreground); + const std::string out_line = + (state.config.timelapse_output_mode == "photos") + ? "Output: Keep Photos Folder" + : "Output: Compile MP4 Video"; + canvas.draw_text(FontRole::Sans, 9, 38, 78, out_line, pal.status_online); + canvas.draw_text(FontRole::Mono, 9, 38, 100, + "[Y] Stop & Finish [N / Esc] Resume", pal.foreground); + } else if (state.modal == OverlayModal::TimelapseCompiling) { + canvas.draw_round_box(22, 32, 276, 92, 6, pal.card, pal.ring, 1); + canvas.draw_text(FontRole::Sans, 10, 34, 42, "Compiling Timelapse MP4", + pal.foreground); + const std::string prog = + "Compiling " + std::to_string(state.timelapse.compile_current) + "/" + + std::to_string(state.timelapse.compile_total) + " frames..."; + canvas.draw_text(FontRole::Mono, 9, 34, 62, prog, pal.muted_foreground); + + canvas.draw_round_box(34, 80, 252, 12, 4, pal.muted, pal.border, 1); + const int fw = static_cast( + std::lround(std::clamp(state.timelapse.compile_progress, 0.0f, 1.0f) * + 250.0f)); + if (fw > 0) { + canvas.fill_rect(35, 81, fw, 10, pal.status_online); + } + canvas.draw_text(FontRole::Mono, 9, 34, 102, + "[Esc] Cancel & Keep Photos", pal.muted_foreground); + } + + // Modal footer bar + canvas.fill_rect(0, 150, AppView::kWidth, 20, pal.muted); + canvas.fill_rect(0, 150, AppView::kWidth, 1, pal.border); + int x = 6; + const int y = 154; + switch (state.modal) { + case OverlayModal::Settings: + draw_kbd_hint(canvas, pal, x, y, "j/k", "Move"); + draw_kbd_hint(canvas, pal, x, y, "Ent/", "Change"); + draw_kbd_hint(canvas, pal, x, y, "Esc", "Close"); + break; + case OverlayModal::DirPicker: + draw_kbd_hint(canvas, pal, x, y, "Ent", "Open", 9, 5); + draw_kbd_hint(canvas, pal, x, y, "Bksp", "Up", 9, 5); + draw_kbd_hint(canvas, pal, x, y, "Spc", "Select", 9, 5); + draw_kbd_hint(canvas, pal, x, y, "T", "Type", 9, 2); + break; + case OverlayModal::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"); + break; + case OverlayModal::TimelapseCustomInput: + draw_kbd_hint(canvas, pal, x, y, "j/k", "Row", 9, 5); + draw_kbd_hint(canvas, pal, x, y, "/0-9", "Edit", 9, 5); + draw_kbd_hint(canvas, pal, x, y, "Ent", "Apply", 9, 5); + draw_kbd_hint(canvas, pal, x, y, "Esc", "Back", 9, 2); + break; + case OverlayModal::TimelapseRecovery: + draw_kbd_hint(canvas, pal, x, y, "C", "Compile"); + draw_kbd_hint(canvas, pal, x, y, "K", "Keep"); + draw_kbd_hint(canvas, pal, x, y, "D", "Discard"); + draw_kbd_hint(canvas, pal, x, y, "Esc", "Later"); + break; + case OverlayModal::TimelapseStopConfirm: + draw_kbd_hint(canvas, pal, x, y, "Y", "Stop & Finish"); + draw_kbd_hint(canvas, pal, x, y, "N/Esc", "Resume"); + break; + case OverlayModal::TimelapseCompiling: + draw_kbd_hint(canvas, pal, x, y, "Esc", "Cancel & Keep Photos"); + break; + case OverlayModal::None: + case OverlayModal::Gallery: + break; + } + } + + void render(const UiState& state, + const PreviewFrame* live_frame, + const PreviewFrame* gallery_frame) { + if (state.theme != theme) { + theme = state.theme; + pal = get_palette(theme); + } + + if (state.timelapse_dimmed && !state.has_hardware_backlight) { + canvas.clear(0x000000); + return; + } + + canvas.clear(pal.background); + + if (state.modal == OverlayModal::Gallery) { + render_gallery(state, gallery_frame); + } else { + const bool rail_left = (state.config.rail_side == "left"); + const int rail_x = rail_left ? 0 : 226; + const int vf_x = rail_left ? 94 : 0; + render_viewfinder(state, live_frame, vf_x); + render_control_rail(state, rail_x); + render_modal(state); + } + +#if defined(CP0_HAS_LVGL) + sync_lvgl_styles(); +#endif + } +}; + +AppView::AppView() : impl_(std::make_unique()) {} +AppView::~AppView() = default; + +void AppView::apply_theme(ThemeMode mode) { + impl_->theme = mode; + impl_->pal = get_palette(mode); +#if defined(CP0_HAS_LVGL) + impl_->sync_lvgl_styles(); +#endif +} + +void AppView::render(const UiState& state, + const PreviewFrame* live_frame, + const PreviewFrame* gallery_frame) { + impl_->render(state, live_frame, gallery_frame); +} + +const uint32_t* AppView::pixels() const { return impl_->canvas.pixels(); } + +bool AppView::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) { + const 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 AppView::using_freetype() const { + return impl_->canvas.using_freetype(); +} + +ThemeMode AppView::active_theme() const { return impl_->theme; } + +} // namespace cz diff --git a/app/src/app_ui.hpp b/app/src/app_ui.hpp new file mode 100644 index 0000000..821f41c --- /dev/null +++ b/app/src/app_ui.hpp @@ -0,0 +1,52 @@ +#pragma once + +#include "camera_backend.hpp" +#include "theme.hpp" +#include "ui_controller.hpp" + +#include +#include +#include + +namespace cz { + +/// 320x170 shadcn/ui Zinc Option A Split View & Modal Renderer. +/// Supports optional FreeType2 / LVGL hooks and built-in anti-aliased +/// software framebuffer + 5x7 bitmap fallback. +class AppView { + public: + static constexpr int kWidth = 320; + static constexpr int kHeight = 170; + + AppView(); + ~AppView(); + + AppView(const AppView&) = delete; + AppView& operator=(const AppView&) = delete; + + /// Swap active Zinc Dark / Zinc Light palette tokens without recreating view objects. + void apply_theme(ThemeMode mode); + + /// Re-render the 320x170 framebuffer from UiState and optional preview frames. + void render(const UiState& state, + const PreviewFrame* live_frame = nullptr, + const PreviewFrame* gallery_frame = nullptr); + + /// 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 cz diff --git a/app/src/main.cpp b/app/src/main.cpp new file mode 100644 index 0000000..9eb1d27 --- /dev/null +++ b/app/src/main.cpp @@ -0,0 +1,865 @@ +#include "app_ui.hpp" +#include "camera_backend.hpp" +#include "fb_blit.hpp" +#include "storage.hpp" +#include "ui_controller.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(CZ_TARGET_DEVICE) && defined(__linux__) +#include +#include +#include +#include +#include +#include +#include +#else +#include +#endif + +namespace fs = std::filesystem; + +namespace { + +volatile std::sig_atomic_t g_signal_stop = 0; + +void handle_signal(int /*sig*/) { g_signal_stop = 1; } + +uint64_t steady_now_ms() { + return static_cast( + std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()) + .count()); +} + +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: 2)\n" + << " --mock-cam Force procedural SimCameraBackend\n" + << " --output-dir Override media output directory\n" + << " --render-test Render 320x170 snapshot to PPM and exit\n" + << " --theme Theme override (dark or light)\n" + << " --mode \n" + << " Initial mode or modal\n" + << " --rail Control rail side (right or left)\n" + << " --help Show this help message\n"; +} + +struct ScopedTempDir { + std::string path; + ~ScopedTempDir() { + if (!path.empty()) { + std::error_code ec; + fs::remove_all(path, ec); + } + } +}; + +struct CliOptions { + int scale = 2; + bool mock_cam = false; + std::string output_dir; + std::string render_test_path; + std::string theme_override; + std::string mode_override; + std::string rail_override; +}; + +int run_render_test(const CliOptions& cli) { + ScopedTempDir temp_dir; + std::string eff_out = cli.output_dir; + if (eff_out.empty()) { + temp_dir.path = "/tmp/czcamera_render_" + std::to_string(::getpid()); + std::error_code ec; + fs::remove_all(temp_dir.path, ec); + if (!cz::mkdir_p(temp_dir.path)) { + std::cerr << "Failed to prepare temporary render directory\n"; + return 1; + } + eff_out = temp_dir.path; + } + + cz::UiControllerOptions opts; + opts.output_dir_override = eff_out; + opts.mock_backend = true; + opts.persist_config = false; + opts.skip_startup_recovery_scan = true; + + cz::UiController ctrl(nullptr, opts); + uint64_t now = 1000; + if (!ctrl.init(now)) { + std::cerr << "Failed to initialize controller for render-test\n"; + return 1; + } + + if (!cli.theme_override.empty()) { + const cz::ThemeMode target_theme = cz::theme_from_string(cli.theme_override); + if (ctrl.state().theme != target_theme) { + ctrl.handle_key('t', cz::KeyCode::Char, now); + } + } + + if (!cli.rail_override.empty()) { + const std::string target_rail = + (cli.rail_override == "left") ? "left" : "right"; + if (ctrl.state().config.rail_side != target_rail) { + ctrl.handle_key('w', cz::KeyCode::Char, now); + } + } + + if (cli.mode_override == "video") { + ctrl.handle_key('2', cz::KeyCode::Char, now); + } else if (cli.mode_override == "timelapse") { + ctrl.handle_key('3', cz::KeyCode::Char, now); + } else if (cli.mode_override == "gallery") { + // Capture a realistic sample photo if the target directory has no media yet + cz::GalleryStore probe; + probe.refresh(ctrl.state().effective_output_dir); + if (probe.items().empty()) { + ctrl.handle_key(0, cz::KeyCode::Enter, now); + (void)ctrl.consume_capture_flash(); + now += 4000; + ctrl.tick(now); + } + ctrl.handle_key('8', cz::KeyCode::Char, now); + } else if (cli.mode_override == "settings") { + ctrl.handle_key('s', cz::KeyCode::Char, now); + } + + cz::PreviewFrame live_frame; + if (ctrl.backend()) { + ctrl.backend()->copy_latest_preview(0, live_frame); + } + + cz::AppView view; + view.apply_theme(ctrl.state().theme); + view.render(ctrl.state(), &live_frame, ctrl.gallery_preview()); + const bool ok = view.save_ppm(cli.render_test_path); + + ctrl.shutdown(); + if (!ok) { + std::cerr << "Failed to write PPM to " << cli.render_test_path << "\n"; + return 1; + } + return 0; +} + +#if defined(CZ_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 ? '|' : '\\'; + case KEY_GRAVE: return shift ? '~' : '`'; + default: return 0; + } +} + +void blit_fbdev(uint8_t* fb_mem, + size_t map_size, + const fb_var_screeninfo& vinfo, + const fb_fix_screeninfo& finfo, + const uint32_t* pixels) { + cz::FbBlitSpec spec; + spec.xres = vinfo.xres; + spec.yres = vinfo.yres; + spec.xres_virtual = vinfo.xres_virtual; + spec.yres_virtual = vinfo.yres_virtual; + spec.xoffset = vinfo.xoffset; + spec.yoffset = vinfo.yoffset; + spec.bits_per_pixel = vinfo.bits_per_pixel; + spec.line_length = finfo.line_length; + spec.red = {vinfo.red.offset, vinfo.red.length}; + spec.green = {vinfo.green.offset, vinfo.green.length}; + spec.blue = {vinfo.blue.offset, vinfo.blue.length}; + spec.transp = {vinfo.transp.offset, vinfo.transp.length}; + cz::blit_framebuffer(fb_mem, map_size, spec, pixels, cz::AppView::kWidth, + cz::AppView::kHeight); +} + +std::vector open_keyboard_evdevs() { + std::vector fds; + if (const char* override_dev = std::getenv("CZCAMERA_EVDEV_DEVICE")) { + const 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; + } + const std::string dev_path = std::string("/dev/input/") + ent->d_name; + const 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(cz::UiController& ctrl, cz::AppView& view) { + const char* fb_dev = std::getenv("CZCAMERA_FB_DEVICE"); + if (fb_dev == nullptr || fb_dev[0] == '\0') { + fb_dev = "/dev/fb0"; + } + const 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; + } + + const size_t map_size = finfo.smem_len; + if (map_size == 0) { + std::cerr << "Framebuffer reports zero memory length\n"; + ::close(fb_fd); + return 1; + } + 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}); + } + + cz::PreviewFrame live_frame; + uint64_t last_live_seq = 0; + uint64_t last_gal_seq = 0; + double last_vp_pos = -1.0; + bool last_vp_playing = false; + + view.apply_theme(ctrl.state().theme); + if (ctrl.backend()) { + if (ctrl.backend()->copy_latest_preview(last_live_seq, live_frame)) { + last_live_seq = live_frame.seq; + } + } + view.render(ctrl.state(), &live_frame, ctrl.gallery_preview()); + blit_fbdev(fb_mem, map_size, vinfo, finfo, view.pixels()); + + bool shift_down = false; + bool prev_flash = ctrl.state().capture_flash_active; + bool prev_dimmed = ctrl.state().timelapse_dimmed; + int prev_tl_shots = ctrl.state().timelapse.shots_taken; + int prev_tl_next = ctrl.state().timelapse.next_shot_in_sec; + int prev_tl_elapsed = ctrl.state().timelapse.elapsed_sec; + int prev_vid_sec = ctrl.state().video_elapsed_sec; + int prev_timer_sec = ctrl.state().timer_remaining_sec; + int prev_comp_cur = ctrl.state().timelapse.compile_current; + std::string prev_toast = ctrl.state().toast_message; + cz::OverlayModal prev_modal = ctrl.state().modal; + + while (!ctrl.should_quit() && !g_signal_stop) { + bool dirty = false; + if (!pfds.empty()) { + const int prc = ::poll(pfds.data(), static_cast(pfds.size()), 16); + if (prc < 0) { + if (errno != EINTR) { + ::usleep(16000); + } + } else if (prc > 0) { + std::vector dead_indices; + for (size_t idx = 0; + idx < pfds.size() && !ctrl.should_quit() && !g_signal_stop; ++idx) { + const auto& p = pfds[idx]; + bool remove_fd = (p.revents & (POLLERR | POLLHUP | POLLNVAL)) != 0; + if ((p.revents & POLLIN) != 0) { + while (!ctrl.should_quit() && !g_signal_stop) { + struct input_event ev {}; + const ssize_t n = ::read(p.fd, &ev, sizeof(ev)); + if (n < 0) { + if (errno == EINTR) continue; + if (errno == EAGAIN || errno == EWOULDBLOCK) break; + remove_fd = true; + break; + } + if (n == 0) { + remove_fd = true; + break; + } + if (n != static_cast(sizeof(ev))) { + break; + } + 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; + } + const uint64_t now = steady_now_ms(); + bool handled = false; + switch (ev.code) { + case KEY_UP: + handled = ctrl.handle_key(0, cz::KeyCode::Up, now); + break; + case KEY_DOWN: + handled = ctrl.handle_key(0, cz::KeyCode::Down, now); + break; + case KEY_LEFT: + handled = ctrl.handle_key(0, cz::KeyCode::Left, now); + break; + case KEY_RIGHT: + handled = ctrl.handle_key(0, cz::KeyCode::Right, now); + break; + case KEY_ENTER: + case KEY_KPENTER: + handled = ctrl.handle_key(0, cz::KeyCode::Enter, now); + break; + case KEY_ESC: + handled = ctrl.handle_key(0, cz::KeyCode::Esc, now); + break; + case KEY_BACKSPACE: + handled = ctrl.handle_key(0, cz::KeyCode::Backspace, now); + break; + case KEY_DELETE: + handled = ctrl.handle_key(0, cz::KeyCode::Delete, now); + break; + case KEY_SPACE: + handled = ctrl.handle_key(' ', cz::KeyCode::Space, now); + break; + default: { + const char c = map_evdev_code(ev.code, shift_down); + if (c != 0) { + handled = ctrl.handle_key(c, cz::KeyCode::Char, now); + } + break; + } + } + if (handled) { + dirty = true; + } + } + } + if (remove_fd) { + ::close(p.fd); + dead_indices.push_back(idx); + } + } + for (auto it = dead_indices.rbegin(); it != dead_indices.rend(); ++it) { + pfds.erase(pfds.begin() + static_cast(*it)); + } + } + } else { + ::usleep(16000); + } + + if (ctrl.should_quit() || g_signal_stop) { + break; + } + + const uint64_t now = steady_now_ms(); + ctrl.tick(now); + + if (ctrl.backend() && ctrl.state().modal != cz::OverlayModal::Gallery) { + if (ctrl.backend()->copy_latest_preview(last_live_seq, live_frame)) { + last_live_seq = live_frame.seq; + dirty = true; + } + } + + const cz::PreviewFrame* gp = ctrl.gallery_preview(); + const uint64_t gal_seq = gp ? gp->seq : 0; + const auto& st = ctrl.state(); + if (gal_seq != last_gal_seq || st.video_player.position_sec != last_vp_pos || + st.video_player.playing != last_vp_playing || + st.capture_flash_active != prev_flash || + st.timelapse_dimmed != prev_dimmed || + st.timelapse.shots_taken != prev_tl_shots || + st.timelapse.next_shot_in_sec != prev_tl_next || + st.timelapse.elapsed_sec != prev_tl_elapsed || + st.video_elapsed_sec != prev_vid_sec || + st.timer_remaining_sec != prev_timer_sec || + st.timelapse.compile_current != prev_comp_cur || + st.toast_message != prev_toast || st.modal != prev_modal) { + dirty = true; + } + + if (dirty) { + last_gal_seq = gal_seq; + last_vp_pos = st.video_player.position_sec; + last_vp_playing = st.video_player.playing; + prev_flash = st.capture_flash_active; + prev_dimmed = st.timelapse_dimmed; + prev_tl_shots = st.timelapse.shots_taken; + prev_tl_next = st.timelapse.next_shot_in_sec; + prev_tl_elapsed = st.timelapse.elapsed_sec; + prev_vid_sec = st.video_elapsed_sec; + prev_timer_sec = st.timer_remaining_sec; + prev_comp_cur = st.timelapse.compile_current; + prev_toast = st.toast_message; + prev_modal = st.modal; + + view.render(st, &live_frame, gp); + blit_fbdev(fb_mem, map_size, vinfo, finfo, view.pixels()); + } + } + + for (const auto& p : pfds) { + ::close(p.fd); + } + ::munmap(mapped, map_size); + ::close(fb_fd); + return 0; +} + +#else + +int run_sdl_loop(cz::UiController& ctrl, cz::AppView& view, int scale) { + if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) != 0) { + std::cerr << "SDL_Init failed: " << SDL_GetError() << "\n"; + return 1; + } + + SDL_AudioDeviceID audio_dev = 0; + if (SDL_InitSubSystem(SDL_INIT_AUDIO) == 0) { + SDL_AudioSpec want{}; + SDL_AudioSpec have{}; + want.freq = 44100; + want.format = AUDIO_S16SYS; + want.channels = 1; + want.samples = 1024; + audio_dev = SDL_OpenAudioDevice(nullptr, 0, &want, &have, 0); + if (audio_dev != 0) { + SDL_PauseAudioDevice(audio_dev, 0); + ctrl.video_player().set_pcm_sink( + [audio_dev](const int16_t* samples, size_t count) { + if (samples != nullptr && count > 0) { + SDL_QueueAudio(audio_dev, samples, + static_cast(count * sizeof(int16_t))); + } + }); + } + } + + SDL_Window* window = SDL_CreateWindow( + "czcamera", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, + cz::AppView::kWidth * scale, cz::AppView::kHeight * scale, + SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE); + if (window == nullptr) { + std::cerr << "SDL_CreateWindow failed: " << SDL_GetError() << "\n"; + ctrl.video_player().set_pcm_sink(nullptr); + if (audio_dev != 0) SDL_CloseAudioDevice(audio_dev); + 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); + ctrl.video_player().set_pcm_sink(nullptr); + if (audio_dev != 0) SDL_CloseAudioDevice(audio_dev); + SDL_Quit(); + return 1; + } + + SDL_RenderSetLogicalSize(renderer, cz::AppView::kWidth, + cz::AppView::kHeight); + SDL_Texture* texture = SDL_CreateTexture( + renderer, SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STREAMING, + cz::AppView::kWidth, cz::AppView::kHeight); + if (texture == nullptr) { + std::cerr << "SDL_CreateTexture failed: " << SDL_GetError() << "\n"; + SDL_DestroyRenderer(renderer); + SDL_DestroyWindow(window); + ctrl.video_player().set_pcm_sink(nullptr); + if (audio_dev != 0) SDL_CloseAudioDevice(audio_dev); + SDL_Quit(); + return 1; + } + + SDL_StartTextInput(); + + cz::PreviewFrame live_frame; + uint64_t last_live_seq = 0; + uint64_t last_gal_seq = 0; + double last_vp_pos = -1.0; + bool last_vp_playing = false; + + view.apply_theme(ctrl.state().theme); + if (ctrl.backend()) { + if (ctrl.backend()->copy_latest_preview(last_live_seq, live_frame)) { + last_live_seq = live_frame.seq; + } + } + view.render(ctrl.state(), &live_frame, ctrl.gallery_preview()); + + auto present = [&]() { + SDL_UpdateTexture(texture, nullptr, view.pixels(), + cz::AppView::kWidth * static_cast(sizeof(uint32_t))); + SDL_RenderClear(renderer); + SDL_RenderCopy(renderer, texture, nullptr, nullptr); + SDL_RenderPresent(renderer); + }; + present(); + + bool running = true; + bool prev_flash = ctrl.state().capture_flash_active; + bool prev_dimmed = ctrl.state().timelapse_dimmed; + int prev_tl_shots = ctrl.state().timelapse.shots_taken; + int prev_tl_next = ctrl.state().timelapse.next_shot_in_sec; + int prev_tl_elapsed = ctrl.state().timelapse.elapsed_sec; + int prev_vid_sec = ctrl.state().video_elapsed_sec; + int prev_timer_sec = ctrl.state().timer_remaining_sec; + int prev_comp_cur = ctrl.state().timelapse.compile_current; + std::string prev_toast = ctrl.state().toast_message; + cz::OverlayModal prev_modal = ctrl.state().modal; + + while (running && !ctrl.should_quit() && !g_signal_stop) { + bool dirty = false; + SDL_Event ev; + if (SDL_WaitEventTimeout(&ev, 16) != 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) { + const uint64_t now = steady_now_ms(); + for (int i = 0; + running && !ctrl.should_quit() && !g_signal_stop && + ev.text.text[i] != '\0'; + ++i) { + if (ctrl.handle_key(ev.text.text[i], cz::KeyCode::Char, now)) { + dirty = true; + } + } + continue; + } + if (ev.type == SDL_KEYDOWN) { + const SDL_Keycode sym = ev.key.keysym.sym; + const uint16_t mod = ev.key.keysym.mod; + if ((mod & (KMOD_CTRL | KMOD_GUI)) != 0 && sym == SDLK_q) { + running = false; + break; + } + const uint64_t now = steady_now_ms(); + bool handled = false; + switch (sym) { + case SDLK_UP: + handled = ctrl.handle_key(0, cz::KeyCode::Up, now); + break; + case SDLK_DOWN: + handled = ctrl.handle_key(0, cz::KeyCode::Down, now); + break; + case SDLK_LEFT: + handled = ctrl.handle_key(0, cz::KeyCode::Left, now); + break; + case SDLK_RIGHT: + handled = ctrl.handle_key(0, cz::KeyCode::Right, now); + break; + case SDLK_RETURN: + case SDLK_KP_ENTER: + handled = ctrl.handle_key(0, cz::KeyCode::Enter, now); + break; + case SDLK_ESCAPE: + handled = ctrl.handle_key(0, cz::KeyCode::Esc, now); + break; + case SDLK_BACKSPACE: + handled = ctrl.handle_key(0, cz::KeyCode::Backspace, now); + break; + case SDLK_DELETE: + handled = ctrl.handle_key(0, cz::KeyCode::Delete, now); + break; + default: + break; + } + if (handled) { + dirty = true; + } + } + } while (running && !ctrl.should_quit() && SDL_PollEvent(&ev) != 0); + } + + if (!running || ctrl.should_quit() || g_signal_stop) { + break; + } + + const uint64_t now = steady_now_ms(); + ctrl.tick(now); + + if (ctrl.backend() && ctrl.state().modal != cz::OverlayModal::Gallery) { + if (ctrl.backend()->copy_latest_preview(last_live_seq, live_frame)) { + last_live_seq = live_frame.seq; + dirty = true; + } + } + + const auto& st = ctrl.state(); + if (audio_dev != 0) { + if ((!st.video_player.playing && last_vp_playing) || + (st.video_player.playing && + std::abs(st.video_player.position_sec - last_vp_pos) > 0.45)) { + SDL_ClearQueuedAudio(audio_dev); + } + } + + const cz::PreviewFrame* gp = ctrl.gallery_preview(); + const uint64_t gal_seq = gp ? gp->seq : 0; + if (gal_seq != last_gal_seq || st.video_player.position_sec != last_vp_pos || + st.video_player.playing != last_vp_playing || + st.capture_flash_active != prev_flash || + st.timelapse_dimmed != prev_dimmed || + st.timelapse.shots_taken != prev_tl_shots || + st.timelapse.next_shot_in_sec != prev_tl_next || + st.timelapse.elapsed_sec != prev_tl_elapsed || + st.video_elapsed_sec != prev_vid_sec || + st.timer_remaining_sec != prev_timer_sec || + st.timelapse.compile_current != prev_comp_cur || + st.toast_message != prev_toast || st.modal != prev_modal) { + dirty = true; + } + + if (dirty) { + last_gal_seq = gal_seq; + last_vp_pos = st.video_player.position_sec; + last_vp_playing = st.video_player.playing; + prev_flash = st.capture_flash_active; + prev_dimmed = st.timelapse_dimmed; + prev_tl_shots = st.timelapse.shots_taken; + prev_tl_next = st.timelapse.next_shot_in_sec; + prev_tl_elapsed = st.timelapse.elapsed_sec; + prev_vid_sec = st.video_elapsed_sec; + prev_timer_sec = st.timer_remaining_sec; + prev_comp_cur = st.timelapse.compile_current; + prev_toast = st.toast_message; + prev_modal = st.modal; + + view.render(st, &live_frame, gp); + present(); + } + } + + ctrl.video_player().set_pcm_sink(nullptr); + ctrl.shutdown(); + if (audio_dev != 0) { + SDL_CloseAudioDevice(audio_dev); + } + 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); + + CliOptions cli; + + for (int i = 1; i < argc; ++i) { + const std::string arg = argv[i]; + if (arg == "--help" || arg == "-h") { + print_usage(argv[0]); + return 0; + } + if (arg == "--sim") { + continue; + } + if (arg == "--mock-cam") { + cli.mock_cam = true; + continue; + } + if (arg == "--scale" && i + 1 < argc) { + const int parsed = std::atoi(argv[++i]); + if (parsed < 1 || parsed > 4) { + std::cerr << "Invalid --scale value (expected 1..4)\n"; + return 2; + } + cli.scale = parsed; + continue; + } + if (arg == "--output-dir" && i + 1 < argc) { + cli.output_dir = argv[++i]; + continue; + } + if (arg == "--render-test" && i + 1 < argc) { + cli.render_test_path = argv[++i]; + continue; + } + if (arg == "--theme" && i + 1 < argc) { + cli.theme_override = argv[++i]; + if (cli.theme_override != "dark" && cli.theme_override != "light") { + std::cerr << "Invalid --theme value: " << cli.theme_override << "\n"; + return 2; + } + continue; + } + if (arg == "--mode" && i + 1 < argc) { + cli.mode_override = argv[++i]; + if (cli.mode_override != "photo" && cli.mode_override != "video" && + cli.mode_override != "timelapse" && cli.mode_override != "gallery" && + cli.mode_override != "settings") { + std::cerr << "Invalid --mode value: " << cli.mode_override << "\n"; + return 2; + } + continue; + } + if (arg == "--rail" && i + 1 < argc) { + cli.rail_override = argv[++i]; + if (cli.rail_override != "right" && cli.rail_override != "left") { + std::cerr << "Invalid --rail value: " << cli.rail_override << "\n"; + return 2; + } + continue; + } + std::cerr << "Unknown or incomplete option: " << arg << "\n"; + print_usage(argv[0]); + return 2; + } + + if (!cli.render_test_path.empty()) { + return run_render_test(cli); + } + + cz::UiControllerOptions opts; + opts.output_dir_override = cli.output_dir; + opts.mock_backend = cli.mock_cam; + + cz::UiController ctrl(nullptr, opts); + const uint64_t now = steady_now_ms(); + ctrl.init(now); + + if (!cli.theme_override.empty()) { + const cz::ThemeMode target_theme = cz::theme_from_string(cli.theme_override); + if (ctrl.state().theme != target_theme) { + ctrl.handle_key('t', cz::KeyCode::Char, now); + } + } + if (!cli.rail_override.empty() && + ctrl.state().config.rail_side != cli.rail_override) { + ctrl.handle_key('w', cz::KeyCode::Char, now); + } + if (cli.mode_override == "video") { + ctrl.handle_key('2', cz::KeyCode::Char, now); + } else if (cli.mode_override == "timelapse") { + ctrl.handle_key('3', cz::KeyCode::Char, now); + } else if (cli.mode_override == "gallery") { + ctrl.handle_key('8', cz::KeyCode::Char, now); + } else if (cli.mode_override == "settings") { + ctrl.handle_key('s', cz::KeyCode::Char, now); + } + + cz::AppView view; +#if defined(CZ_TARGET_DEVICE) && defined(__linux__) + (void)cli.scale; + const int rc = run_device_loop(ctrl, view); + ctrl.shutdown(); + return rc; +#else + return run_sdl_loop(ctrl, view, cli.scale); +#endif +} diff --git a/app/src/ui_controller.cpp b/app/src/ui_controller.cpp new file mode 100644 index 0000000..76104ff --- /dev/null +++ b/app/src/ui_controller.cpp @@ -0,0 +1,1959 @@ +#include "ui_controller.hpp" + +#include "jpeg_pipeline.hpp" +#include "storage.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; + +namespace cz { + +namespace { + +constexpr uint64_t kMinStorageBytes = 104857600ULL; // 100 MB +constexpr uint64_t kCaptureFlashMs = 150ULL; +constexpr uint64_t kToastDurationMs = 3000ULL; +constexpr std::array kZoomSteps = {1.0f, 1.5f, 2.0f, 3.0f, 4.0f}; +constexpr std::array kIntervalPresets = {2, 5, 10, 30, 60, 300}; +constexpr std::array kFpsPresets = {15, 24, 30}; +constexpr std::array kDimPresets = {15, 30, 60, 0}; +constexpr std::array kOrientPresets = {"auto", "0", "180", + "hflip", "vflip"}; + +struct StopPreset { + const char* mode; + int value; +}; +constexpr std::array kStopPresets = {{ + {"manual", 0}, + {"shots", 60}, + {"shots", 120}, + {"shots", 300}, + {"duration", 900}, + {"duration", 1800}, + {"duration", 3600}, +}}; + +std::string to_lower_ascii(std::string s) { + for (char& ch : s) { + ch = static_cast(std::tolower(static_cast(ch))); + } + return s; +} + +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 base_name(const std::string& path) { + if (path.empty()) return ""; + std::string p = path; + while (p.size() > 1 && p.back() == '/') { + p.pop_back(); + } + const size_t slash = p.find_last_of('/'); + return (slash == std::string::npos) ? p : p.substr(slash + 1); +} + +std::string parent_dir_of(const std::string& path) { + std::string p = path; + while (p.size() > 1 && p.back() == '/') { + p.pop_back(); + } + const size_t slash = p.find_last_of('/'); + if (slash == std::string::npos) return "."; + if (slash == 0) return "/"; + return p.substr(0, slash); +} + +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); +} + +void remove_silent(const std::string& path) { + if (path.empty()) return; + std::error_code ec; + fs::remove(path, ec); +} + +KeyCode normalize_key(char ch, KeyCode code) { + if (code != KeyCode::Char) { + return code; + } + 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::Esc; + return KeyCode::Char; +} + +void photo_dims(const std::string& res, int& w, int& h) { + if (to_lower_ascii(res) == "2mp") { + w = 1640; + h = 1232; + } else { + w = 3280; + h = 2464; + } +} + +void video_params(const std::string& res, int& w, int& h, int& bitrate) { + const std::string r = to_lower_ascii(res); + if (r == "1080p") { + w = 1920; + h = 1080; + bitrate = 8000000; + } else if (r == "480p") { + w = 854; + h = 480; + bitrate = 2000000; + } else { + w = 1280; + h = 720; + bitrate = 4000000; + } +} + +void timelapse_dims(const std::string& res, int& w, int& h, bool& is_16_9) { + const std::string r = to_lower_ascii(res); + if (r == "8mp") { + w = 3280; + h = 2464; + is_16_9 = false; + } else if (r == "1080p") { + w = 1920; + h = 1080; + is_16_9 = true; + } else { + w = 1640; + h = 1232; + is_16_9 = false; + } +} + +template +int find_index_str(const std::array& arr, + const std::string& val) { + const std::string low = to_lower_ascii(val); + for (size_t i = 0; i < N; ++i) { + if (low == arr[i]) { + return static_cast(i); + } + } + return 0; +} + +template +int find_index_int(const std::array& arr, int val) { + for (size_t i = 0; i < N; ++i) { + if (arr[i] == val) { + return static_cast(i); + } + } + return 0; +} + +TimelapseSessionPaths session_paths_from_manifest( + const TimelapseManifest& manifest) { + std::string work_dir = manifest.work_dir; + while (work_dir.size() > 1 && work_dir.back() == '/') { + work_dir.pop_back(); + } + const std::string out_dir = parent_dir_of(work_dir); + std::string session_id = manifest.session_id; + if (session_id.empty()) { + const std::string base = base_name(work_dir); + if (base.rfind(".tl_work_", 0) == 0) { + session_id = base.substr(9); + } else { + session_id = "recovered"; + } + } + TimelapseSessionPaths paths; + paths.session_id = session_id; + paths.work_dir = work_dir; + paths.photos_dir = out_dir + "/TL_" + session_id; + paths.manifest_path = work_dir + "/session.json"; + paths.mp4_tmp_path = out_dir + "/.TL_" + session_id + ".mp4.part"; + paths.mp4_final_path = out_dir + "/TL_" + session_id + ".mp4"; + return paths; +} + +} // namespace + +UiController::UiController(std::unique_ptr backend, + const UiControllerOptions& opts) + : opts_(opts), + backend_(std::move(backend)), + backlight_(opts.backlight_sysfs_root) { + if (!backend_) { + backend_ = create_camera_backend(opts_.mock_backend); + } + timelapse_engine_.set_backend(backend_.get()); +} + +UiController::~UiController() { shutdown(); } + +bool UiController::init(uint64_t now_ms) { + if (initialized_) { + return true; + } + + state_.config = load_config(opts_.config_path); + persisted_output_dir_ = state_.config.output_dir; + + if (!opts_.output_dir_override.empty()) { + state_.config.output_dir = opts_.output_dir_override; + output_dir_override_active_ = true; + } else { + output_dir_override_active_ = false; + } + + state_.effective_output_dir = expand_user_path(state_.config.output_dir); + state_.theme = theme_from_string(state_.config.theme); + state_.filter = filter_from_string(state_.config.photo_filter); + state_.has_hardware_backlight = backlight_.has_hardware_backlight(); + state_.timelapse_dimmed = backlight_.is_dimmed(); + state_.zoom = 1.0f; + state_.loupe_enabled = false; + state_.rail_cursor = 1; + + if (!mkdir_p(state_.effective_output_dir)) { + set_toast("Output dir unavailable", true, now_ms); + } + refresh_storage_stats(); + + std::string err; + if (backend_ && !backend_->start(build_stream_spec(), err)) { + state_.backend_error = err; + set_toast(err.empty() ? "Camera start failed" : err, true, now_ms); + } + sync_backend_status(); + + last_activity_ms_ = now_ms; + initialized_ = true; + + if (!opts_.skip_startup_recovery_scan) { + orphaned_timelapses_ = scan_orphaned_timelapses(state_.effective_output_dir); + if (!orphaned_timelapses_.empty()) { + state_.recovery_manifest = orphaned_timelapses_.front(); + state_.recovery_remaining = static_cast(orphaned_timelapses_.size()); + state_.modal = OverlayModal::TimelapseRecovery; + } + } + + return true; +} + +void UiController::shutdown() { + video_player_.stop(); + if (timelapse_engine_.state().running) { + timelapse_engine_.request_stop(); + } + timelapse_engine_.cancel_compile(); + join_compile_thread(); + backlight_.restore(); + state_.timelapse_dimmed = false; + if (backend_) { + backend_->stop(); + } + initialized_ = false; +} + +CameraStreamSpec UiController::build_stream_spec() const { + CameraStreamSpec spec; + spec.fps = 30; + spec.zoom = state_.zoom; + spec.ev = static_cast(state_.config.ev); + spec.camera_transform = state_.config.camera_transform; + + switch (state_.mode) { + case AppMode::Photo: { + spec.mode = "photo"; + photo_dims(state_.config.photo_resolution, spec.main_width, + spec.main_height); + spec.preview_width = 226; + spec.preview_height = 170; + break; + } + case AppMode::Video: { + spec.mode = "video"; + int unused_br = 0; + video_params(state_.config.video_resolution, spec.main_width, + spec.main_height, unused_br); + spec.preview_width = 226; + spec.preview_height = 128; + break; + } + case AppMode::Timelapse: { + spec.mode = "timelapse"; + bool is_16_9 = false; + timelapse_dims(state_.config.timelapse_resolution, spec.main_width, + spec.main_height, is_16_9); + spec.preview_width = 226; + spec.preview_height = is_16_9 ? 128 : 170; + break; + } + } + return spec; +} + +AppConfig UiController::effective_engine_config() const { + AppConfig cfg = state_.config; + cfg.output_dir = state_.effective_output_dir; + return cfg; +} + +void UiController::persist_config() { + if (!opts_.persist_config) { + return; + } + AppConfig to_save = state_.config; + if (output_dir_override_active_) { + to_save.output_dir = persisted_output_dir_; + } + save_config(to_save, opts_.config_path); +} + +bool UiController::reconfigure_backend(std::string& out_err) { + out_err.clear(); + if (!backend_) { + out_err = "No camera backend"; + return false; + } + const bool ok = backend_->reconfigure(build_stream_spec(), out_err); + if (!ok) { + state_.backend_error = out_err; + } + sync_backend_status(); + return ok; +} + +void UiController::sync_backend_status() { + if (!backend_) { + state_.backend_ready = false; + state_.backend_paused = false; + return; + } + const BackendHealth h = backend_->status(); + state_.backend_ready = h.ready; + state_.backend_paused = h.paused; + if (!h.last_error.empty()) { + state_.backend_error = h.last_error; + } else if (h.ready) { + state_.backend_error.clear(); + } +} + +void UiController::set_toast(const std::string& message, + bool is_error, + uint64_t now_ms) { + state_.toast_message = message; + state_.toast_is_error = is_error && !message.empty(); + toast_until_ms_ = now_ms + kToastDurationMs; +} + +void UiController::refresh_storage_stats() { + uint64_t free_b = 0; + has_sufficient_storage(state_.effective_output_dir, kMinStorageBytes, &free_b); + state_.free_bytes = free_b; +} + +bool UiController::consume_capture_flash() { + const bool was = capture_flash_pending_; + capture_flash_pending_ = false; + return was; +} + +void UiController::join_compile_thread() { + if (compile_thread_.joinable()) { + compile_thread_.join(); + } +} + +void UiController::start_compile_async( + const TimelapseSessionPaths& paths, + int fps, + const std::string& resolution, + const TimelapseManifest& fallback_manifest, + bool from_recovery) { + join_compile_thread(); + + if (backlight_.is_dimmed()) { + backlight_.restore(); + state_.timelapse_dimmed = false; + } + + std::string err; + if (backend_ && !state_.backend_paused) { + backend_->pause(err); + sync_backend_status(); + } + + compile_fallback_manifest_ = fallback_manifest; + compile_from_recovery_ = from_recovery; + compile_cancelled_by_user_ = false; + compile_ok_ = false; + compile_result_msg_.clear(); + compile_finished_.store(false, std::memory_order_release); + compile_in_flight_.store(true, std::memory_order_release); + + state_.modal = OverlayModal::TimelapseCompiling; + state_.timelapse.compiling = true; + state_.timelapse.compile_current = 0; + state_.timelapse.compile_total = std::max(1, fallback_manifest.frame_count); + state_.timelapse.compile_progress = 0.0f; + + compile_thread_ = std::thread([this, paths, fps, resolution]() { + const bool ok = timelapse_engine_.compile_session(paths, fps, resolution); + { + std::lock_guard lk(compile_result_mutex_); + compile_ok_ = ok; + if (ok) { + compile_result_msg_ = "Compiled " + base_name(paths.mp4_final_path); + } else { + compile_result_msg_ = timelapse_engine_.state().last_error; + } + } + compile_finished_.store(true, std::memory_order_release); + compile_in_flight_.store(false, std::memory_order_release); + }); +} + +void UiController::finish_compile_if_ready(uint64_t now_ms) { + if (!compile_finished_.load(std::memory_order_acquire)) { + return; + } + + join_compile_thread(); + compile_finished_.store(false, std::memory_order_release); + + bool ok = false; + std::string msg; + { + std::lock_guard lk(compile_result_mutex_); + ok = compile_ok_; + msg = compile_result_msg_; + } + + if (ok) { + set_toast(msg, false, now_ms); + } else if (compile_cancelled_by_user_) { + std::string rec_msg; + if (timelapse_engine_.recover_session(compile_fallback_manifest_, + RecoveryAction::KeepPhotos, rec_msg)) { + set_toast(rec_msg, false, now_ms); + } else { + set_toast(rec_msg.empty() ? "Compile cancelled" : rec_msg, true, now_ms); + } + } else { + set_toast(msg.empty() ? "Compile failed" : msg, true, now_ms); + } + + std::string err; + if (backend_) { + backend_->resume(err); + sync_backend_status(); + } + refresh_storage_stats(); + state_.timelapse = timelapse_engine_.state(); + + if (compile_from_recovery_) { + advance_recovery_queue(); + } else { + state_.modal = OverlayModal::None; + } +} + +void UiController::advance_recovery_queue() { + if (!orphaned_timelapses_.empty()) { + orphaned_timelapses_.erase(orphaned_timelapses_.begin()); + } + if (!orphaned_timelapses_.empty()) { + state_.recovery_manifest = orphaned_timelapses_.front(); + state_.recovery_remaining = static_cast(orphaned_timelapses_.size()); + state_.modal = OverlayModal::TimelapseRecovery; + } else { + state_.recovery_manifest = TimelapseManifest{}; + state_.recovery_remaining = 0; + state_.modal = OverlayModal::None; + } +} + +void UiController::tick(uint64_t now_ms) { + if (!initialized_) { + init(now_ms); + } + + if (state_.capture_flash_active && now_ms >= flash_until_ms_) { + state_.capture_flash_active = false; + } + + if (!state_.toast_message.empty() && now_ms >= toast_until_ms_) { + state_.toast_message.clear(); + state_.toast_is_error = false; + } + + if (state_.timer_active) { + if (now_ms >= timer_target_ms_) { + state_.timer_active = false; + state_.timer_remaining_sec = 0; + capture_photo_now(now_ms); + } else { + const uint64_t rem = timer_target_ms_ - now_ms; + state_.timer_remaining_sec = static_cast((rem + 999ULL) / 1000ULL); + } + } + + if (state_.video_recording) { + state_.video_elapsed_sec = + (now_ms >= video_start_ms_) + ? static_cast((now_ms - video_start_ms_) / 1000ULL) + : 0; + const BackendHealth h = backend_ ? backend_->status() : BackendHealth{}; + if (h.audio_warning && !warned_audio_) { + warned_audio_ = true; + set_toast("Mic unavailable - muted", true, now_ms); + } + if (!h.recording) { + state_.video_recording = false; + remove_silent(video_tmp_path_); + set_toast(h.last_error.empty() ? "Video stopped unexpectedly" : h.last_error, + true, now_ms); + } else if (now_ms - last_storage_check_ms_ >= 2000ULL) { + last_storage_check_ms_ = now_ms; + if (!has_sufficient_storage(state_.effective_output_dir, kMinStorageBytes, + &state_.free_bytes)) { + stop_video_recording(true, now_ms); + } + } + } + + if (timelapse_engine_.state().running) { + timelapse_engine_.tick(now_ms, effective_engine_config()); + state_.timelapse = timelapse_engine_.state(); + + if (!state_.timelapse.running) { + backlight_.restore(); + state_.timelapse_dimmed = false; + refresh_storage_stats(); + + if (state_.timelapse.needs_compile && !compile_in_flight_.load()) { + if (state_.timelapse.stopped_by_low_storage) { + set_toast("Low Storage - Compiling", true, now_ms); + } + const TimelapseSessionPaths sp = timelapse_engine_.session_paths(); + TimelapseManifest fb; + fb.session_id = sp.session_id; + fb.work_dir = sp.work_dir; + fb.resolution = state_.config.timelapse_resolution; + fb.fps = state_.config.timelapse_fps; + fb.frame_count = state_.timelapse.shots_taken; + start_compile_async(sp, state_.config.timelapse_fps, + state_.config.timelapse_resolution, fb, false); + } else if (state_.timelapse.stopped_by_low_storage) { + set_toast("Low Storage - Saved", true, now_ms); + } else if (!state_.timelapse.last_error.empty()) { + set_toast(state_.timelapse.last_error, true, now_ms); + } else if (!state_.timelapse.result_path.empty()) { + set_toast("Saved " + base_name(state_.timelapse.result_path), false, + now_ms); + } + } else if (state_.modal == OverlayModal::None && + state_.config.timelapse_dim_sec > 0 && + !backlight_.is_dimmed()) { + const uint64_t dim_ms = + static_cast(state_.config.timelapse_dim_sec) * 1000ULL; + if (now_ms >= last_activity_ms_ && (now_ms - last_activity_ms_) >= dim_ms) { + backlight_.dim(); + state_.timelapse_dimmed = backlight_.is_dimmed(); + } + } + } + + if (state_.modal == OverlayModal::TimelapseCompiling) { + state_.timelapse = timelapse_engine_.state(); + finish_compile_if_ready(now_ms); + } + + if (state_.modal == OverlayModal::Gallery) { + PreviewFrame vf; + if (video_player_.poll_frame(vf)) { + gallery_frame_ = std::move(vf); + has_gallery_preview_ = true; + } + state_.video_player = video_player_.state(); + } + + sync_backend_status(); +} + +void UiController::switch_mode(AppMode target) { + if (state_.mode == target) { + return; + } + state_.timer_active = false; + state_.timer_remaining_sec = 0; + state_.mode = target; + state_.rail_cursor = 1; + std::string err; + reconfigure_backend(err); +} + +void UiController::adjust_zoom(int delta_step) { + int cur_idx = 0; + float best_diff = 1e9f; + for (size_t i = 0; i < kZoomSteps.size(); ++i) { + const float d = std::abs(state_.zoom - kZoomSteps[i]); + if (d < best_diff) { + best_diff = d; + cur_idx = static_cast(i); + } + } + const int next_idx = + std::clamp(cur_idx + delta_step, 0, static_cast(kZoomSteps.size()) - 1); + if (next_idx == cur_idx && state_.zoom == kZoomSteps[static_cast(cur_idx)]) { + return; + } + state_.zoom = kZoomSteps[static_cast(next_idx)]; + if (backend_) { + std::string err; + backend_->set_controls(state_.zoom, static_cast(state_.config.ev), err); + } +} + +void UiController::adjust_ev(int delta_step) { + double next_ev = state_.config.ev + static_cast(delta_step) * 0.5; + next_ev = std::clamp(std::round(next_ev * 2.0) / 2.0, -2.0, 2.0); + if (std::abs(next_ev - state_.config.ev) < 1e-6) { + return; + } + state_.config.ev = next_ev; + if (backend_) { + std::string err; + backend_->set_controls(state_.zoom, static_cast(state_.config.ev), err); + } + persist_config(); +} + +void UiController::adjust_rail_setting(int delta) { + const int step = (delta >= 0) ? 1 : -1; + switch (state_.mode) { + case AppMode::Photo: { + if (state_.rail_cursor == 0) { + state_.config.photo_resolution = + (state_.config.photo_resolution == "8mp") ? "2mp" : "8mp"; + std::string err; + reconfigure_backend(err); + persist_config(); + } else if (state_.rail_cursor == 1) { + adjust_ev(step); + } else if (state_.rail_cursor == 2) { + state_.filter = next_filter(state_.filter, step); + state_.config.photo_filter = filter_to_string(state_.filter); + persist_config(); + } else if (state_.rail_cursor == 3) { + static constexpr std::array kTimers = {0, 3, 10}; + const int idx = find_index_int(kTimers, state_.config.photo_timer_sec); + state_.config.photo_timer_sec = + kTimers[static_cast((idx + step + 3) % 3)]; + persist_config(); + } + break; + } + case AppMode::Video: { + if (state_.rail_cursor == 0 && !state_.video_recording) { + static constexpr std::array kVidRes = {"480p", "720p", + "1080p"}; + const int idx = + find_index_str(kVidRes, state_.config.video_resolution); + state_.config.video_resolution = + kVidRes[static_cast((idx + step + 3) % 3)]; + std::string err; + reconfigure_backend(err); + persist_config(); + } else if (state_.rail_cursor == 1 && !state_.video_recording) { + state_.config.video_audio = !state_.config.video_audio; + persist_config(); + } else if (state_.rail_cursor == 2) { + adjust_zoom(step); + } else if (state_.rail_cursor == 3) { + adjust_ev(step); + } + break; + } + case AppMode::Timelapse: { + if (state_.timelapse.running) { + return; + } + if (state_.rail_cursor == 0) { + int idx = 0; + int best = 1000000; + for (size_t i = 0; i < kIntervalPresets.size(); ++i) { + const int d = + std::abs(state_.config.timelapse_interval_sec - kIntervalPresets[i]); + if (d < best) { + best = d; + idx = static_cast(i); + } + } + const int next = + (idx + step + static_cast(kIntervalPresets.size())) % + static_cast(kIntervalPresets.size()); + state_.config.timelapse_interval_sec = + kIntervalPresets[static_cast(next)]; + persist_config(); + } else if (state_.rail_cursor == 1) { + state_.config.timelapse_output_mode = + (state_.config.timelapse_output_mode == "video") ? "photos" + : "video"; + persist_config(); + } else if (state_.rail_cursor == 2) { + static constexpr std::array kTlRes = {"2mp", "1080p", + "8mp"}; + const int idx = + find_index_str(kTlRes, state_.config.timelapse_resolution); + state_.config.timelapse_resolution = + kTlRes[static_cast((idx + step + 3) % 3)]; + std::string err; + reconfigure_backend(err); + persist_config(); + } else if (state_.rail_cursor == 3) { + int idx = 0; + for (size_t i = 0; i < kStopPresets.size(); ++i) { + if (state_.config.timelapse_stop_mode == kStopPresets[i].mode && + state_.config.timelapse_stop_value == kStopPresets[i].value) { + idx = static_cast(i); + break; + } + } + const int next = (idx + step + static_cast(kStopPresets.size())) % + static_cast(kStopPresets.size()); + state_.config.timelapse_stop_mode = + kStopPresets[static_cast(next)].mode; + state_.config.timelapse_stop_value = + kStopPresets[static_cast(next)].value; + persist_config(); + } + break; + } + } +} + +void UiController::trigger_photo_shutter(uint64_t now_ms) { + if (state_.timer_active) { + return; + } + if (state_.config.photo_timer_sec > 0) { + state_.timer_active = true; + state_.timer_remaining_sec = state_.config.photo_timer_sec; + timer_target_ms_ = + now_ms + static_cast(state_.config.photo_timer_sec) * 1000ULL; + return; + } + capture_photo_now(now_ms); +} + +void UiController::capture_photo_now(uint64_t now_ms) { + if (!backend_ || !state_.backend_ready || state_.backend_paused) { + set_toast("Camera not ready", true, now_ms); + return; + } + if (!mkdir_p(state_.effective_output_dir)) { + set_toast("Output dir unavailable", true, now_ms); + return; + } + if (!has_sufficient_storage(state_.effective_output_dir, kMinStorageBytes, + &state_.free_bytes)) { + set_toast("Low Storage (<100MB)", true, now_ms); + return; + } + + int w = 3280; + int h = 2464; + photo_dims(state_.config.photo_resolution, w, h); + const StagedPaths paths = next_photo_paths(state_.effective_output_dir); + + const StillCaptureResult cap = backend_->capture_still(paths.tmp_path, w, h); + if (!cap.ok) { + remove_silent(paths.tmp_path); + set_toast(cap.error.empty() ? "Capture failed" : cap.error, true, now_ms); + sync_backend_status(); + return; + } + + std::string err; + if (!finalize_still_photo(paths.tmp_path, paths.final_path, state_.filter, + err)) { + remove_silent(paths.tmp_path); + set_toast(err.empty() ? "Save failed" : err, true, now_ms); + return; + } + + capture_flash_pending_ = true; + state_.capture_flash_active = true; + flash_until_ms_ = now_ms + kCaptureFlashMs; + refresh_storage_stats(); + set_toast("Saved " + base_name(paths.final_path), false, now_ms); +} + +void UiController::start_video_recording(uint64_t now_ms) { + if (state_.video_recording) { + return; + } + if (!backend_ || !state_.backend_ready || state_.backend_paused) { + set_toast("Camera not ready", true, now_ms); + return; + } + if (!mkdir_p(state_.effective_output_dir)) { + set_toast("Output dir unavailable", true, now_ms); + return; + } + if (!has_sufficient_storage(state_.effective_output_dir, kMinStorageBytes, + &state_.free_bytes)) { + set_toast("Low Storage (<100MB)", true, now_ms); + return; + } + + const StagedPaths paths = next_video_paths(state_.effective_output_dir); + VideoSpec spec; + video_params(state_.config.video_resolution, spec.width, spec.height, + spec.bitrate_bps); + spec.fps = 30; + spec.audio_enabled = state_.config.video_audio; + spec.tmp_path = paths.tmp_path; + + std::string err; + if (!backend_->start_video(spec, err)) { + remove_silent(paths.tmp_path); + set_toast(err.empty() ? "Video start failed" : err, true, now_ms); + sync_backend_status(); + return; + } + + state_.video_recording = true; + state_.video_elapsed_sec = 0; + video_start_ms_ = now_ms; + last_storage_check_ms_ = now_ms; + video_tmp_path_ = paths.tmp_path; + video_final_path_ = paths.final_path; + warned_audio_ = false; + sync_backend_status(); +} + +void UiController::stop_video_recording(bool low_storage, uint64_t now_ms) { + if (!state_.video_recording) { + return; + } + const VideoStopResult res = backend_->stop_video(); + state_.video_recording = false; + state_.video_elapsed_sec = 0; + + std::string err; + if (!res.ok) { + remove_silent(video_tmp_path_); + set_toast(res.error.empty() ? "Video stop failed" : res.error, true, now_ms); + } else if (!commit_staged_file(video_tmp_path_, video_final_path_, err)) { + remove_silent(video_tmp_path_); + set_toast(err.empty() ? "Video commit failed" : err, true, now_ms); + } else { + set_toast(low_storage ? "Low Storage - Saved" + : ("Saved " + base_name(video_final_path_)), + low_storage, now_ms); + } + + video_tmp_path_.clear(); + video_final_path_.clear(); + refresh_storage_stats(); + sync_backend_status(); +} + +void UiController::start_timelapse(uint64_t now_ms) { + if (timelapse_engine_.state().running || compile_in_flight_.load()) { + return; + } + if (!timelapse_engine_.start(effective_engine_config(), now_ms)) { + set_toast(timelapse_engine_.state().last_error, true, now_ms); + return; + } + state_.timelapse = timelapse_engine_.state(); + last_activity_ms_ = now_ms; +} + +void UiController::open_gallery(uint64_t now_ms) { + std::string err; + if (backend_ && !state_.backend_paused) { + backend_->pause(err); + sync_backend_status(); + } + gallery_store_.refresh(state_.effective_output_dir); + state_.gallery_items = gallery_store_.items(); + state_.gallery_in_session = gallery_store_.in_session(); + state_.gallery_session_name = gallery_store_.session_name(); + state_.gallery_cursor = 0; + state_.gallery_delete_confirm = false; + state_.modal = OverlayModal::Gallery; + load_current_gallery_preview(); + if (state_.gallery_items.empty() && !err.empty()) { + set_toast(err, true, now_ms); + } +} + +void UiController::close_gallery(bool resume_camera) { + video_player_.stop(); + state_.video_player = video_player_.state(); + gallery_frame_ = PreviewFrame{}; + has_gallery_preview_ = false; + state_.gallery_delete_confirm = false; + state_.modal = OverlayModal::None; + if (resume_camera && backend_) { + std::string err; + backend_->resume(err); + sync_backend_status(); + } +} + +void UiController::load_current_gallery_preview() { + video_player_.stop(); + state_.video_player = video_player_.state(); + gallery_frame_ = PreviewFrame{}; + has_gallery_preview_ = false; + + if (state_.gallery_items.empty()) { + state_.gallery_cursor = 0; + return; + } + state_.gallery_cursor = std::clamp( + state_.gallery_cursor, 0, static_cast(state_.gallery_items.size()) - 1); + + RgbImage img; + std::string err; + if (gallery_store_.load_preview_rgb24(state_.gallery_cursor, 320, 128, img, + err)) { + gallery_frame_.seq = 1; + gallery_frame_.width = img.width; + gallery_frame_.height = img.height; + gallery_frame_.rgb24 = std::move(img.rgb24); + has_gallery_preview_ = true; + } + // Sync metadata populated by load_preview_rgb24 (dimensions / video duration) + state_.gallery_items = gallery_store_.items(); + + const auto& item = + state_.gallery_items[static_cast(state_.gallery_cursor)]; + if (item.type == GalleryItemType::Video) { + video_player_.open(item.abs_path, 320, 128); + if (gallery_muted_) { + video_player_.toggle_mute(); + } + state_.video_player = video_player_.state(); + } +} + +void UiController::open_settings() { + state_.modal = OverlayModal::Settings; + state_.settings_cursor = 0; + state_.modal_error.clear(); +} + +void UiController::apply_settings_row(int delta) { + const int step = (delta >= 0) ? 1 : -1; + switch (state_.settings_cursor) { + case 0: + if (delta >= 0) { + open_dir_picker(); + } + break; + case 1: + state_.config.rail_side = + (state_.config.rail_side == "right") ? "left" : "right"; + persist_config(); + break; + case 2: + state_.theme = toggle_theme(state_.theme); + state_.config.theme = theme_to_string(state_.theme); + persist_config(); + break; + case 3: + state_.config.grid_enabled = !state_.config.grid_enabled; + persist_config(); + break; + case 4: { + const int idx = find_index_int(kDimPresets, state_.config.timelapse_dim_sec); + const int next = + (idx + step + static_cast(kDimPresets.size())) % + static_cast(kDimPresets.size()); + state_.config.timelapse_dim_sec = kDimPresets[static_cast(next)]; + persist_config(); + break; + } + case 5: { + const int idx = + find_index_str(kOrientPresets, state_.config.camera_transform); + const int next = + (idx + step + static_cast(kOrientPresets.size())) % + static_cast(kOrientPresets.size()); + state_.config.camera_transform = + kOrientPresets[static_cast(next)]; + std::string err; + reconfigure_backend(err); + persist_config(); + break; + } + default: + break; + } +} + +void UiController::open_dir_picker() { + std::string start = "/"; + if (is_valid_dir(state_.effective_output_dir)) { + start = state_.effective_output_dir; + } else { + const char* home = std::getenv("HOME"); + if (home != nullptr && is_valid_dir(home)) { + start = home; + } + } + state_.modal = OverlayModal::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(); + + for (fs::directory_iterator + it(resolved, fs::directory_options::skip_permission_denied, ec), + end; + !ec && it != end; it.increment(ec)) { + const auto& entry = *it; + std::error_code entry_ec; + if (!entry.is_directory(entry_ec) || entry_ec) { + continue; + } + const 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) { + const std::string na = fs::path(a).filename().string(); + const std::string nb = fs::path(b).filename().string(); + const std::string la = to_lower_ascii(na); + const 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() { + state_.modal = OverlayModal::TextInput; + state_.text_buffer.clear(); + state_.modal_error.clear(); +} + +void UiController::open_timelapse_custom_input() { + state_.modal = OverlayModal::TimelapseCustomInput; + state_.tl_custom_cursor = 0; + state_.tl_custom_interval_sec = state_.config.timelapse_interval_sec; + state_.tl_custom_fps = state_.config.timelapse_fps; + state_.tl_custom_stop_mode = state_.config.timelapse_stop_mode; + state_.tl_custom_stop_value = state_.config.timelapse_stop_value; + state_.tl_custom_text.clear(); + state_.modal_error.clear(); +} + +bool UiController::handle_key(char ch, KeyCode code, uint64_t now_ms) { + if (!initialized_) { + init(now_ms); + } + + last_activity_ms_ = now_ms; + + // Safe Wake Rule (Review Focus #2): any key while dimmed ONLY wakes backlight. + if (backlight_.is_dimmed()) { + backlight_.restore(); + state_.timelapse_dimmed = backlight_.is_dimmed(); + return true; + } + + if (state_.modal == OverlayModal::TextInput) { + return handle_text_input_key(ch, code, now_ms); + } + if (state_.modal == OverlayModal::TimelapseCustomInput) { + return handle_tl_custom_key(ch, code, now_ms); + } + + const KeyCode norm = normalize_key(ch, code); + switch (state_.modal) { + case OverlayModal::None: + return handle_none_modal_key(ch, norm, now_ms); + case OverlayModal::Gallery: + return handle_gallery_key(ch, norm, now_ms); + case OverlayModal::Settings: + return handle_settings_key(ch, norm, now_ms); + case OverlayModal::DirPicker: + return handle_dir_picker_key(ch, norm, now_ms); + case OverlayModal::TimelapseRecovery: + return handle_tl_recovery_key(ch, norm, now_ms); + case OverlayModal::TimelapseStopConfirm: + return handle_tl_stop_confirm_key(ch, norm, now_ms); + case OverlayModal::TimelapseCompiling: + return handle_tl_compiling_key(ch, norm, now_ms); + case OverlayModal::TextInput: + case OverlayModal::TimelapseCustomInput: + break; + } + return false; +} + +bool UiController::handle_none_modal_key(char ch, + KeyCode code, + uint64_t now_ms) { + const bool tl_running = state_.timelapse.running; + const bool vid_recording = state_.video_recording; + const char lower = + (code == KeyCode::Char) + ? static_cast(std::tolower(static_cast(ch))) + : 0; + + // Active Timelapse running locks all mode/settings switches + if (tl_running) { + if (code == KeyCode::Enter || code == KeyCode::Esc || lower == '6' || + lower == 'q') { + state_.modal = OverlayModal::TimelapseStopConfirm; + return true; + } + if (lower == 'g') { + state_.config.grid_enabled = !state_.config.grid_enabled; + persist_config(); + return true; + } + return false; + } + + // Active Video recording locks transitions while keeping zoom and stop active + if (vid_recording) { + if (code == KeyCode::Enter || code == KeyCode::Space || + code == KeyCode::Esc || lower == '6') { + stop_video_recording(false, now_ms); + return true; + } + if (lower == '5') { + adjust_zoom(-1); + return true; + } + if (lower == '7') { + adjust_zoom(+1); + return true; + } + if (lower == 'g') { + state_.config.grid_enabled = !state_.config.grid_enabled; + persist_config(); + return true; + } + return false; + } + + // Photo countdown active: Esc cancels countdown without quitting + if (state_.timer_active) { + if (code == KeyCode::Esc) { + state_.timer_active = false; + state_.timer_remaining_sec = 0; + set_toast("Timer cancelled", false, now_ms); + return true; + } + return false; + } + + // Idle global actions across Photo / Video / Timelapse + if (code == KeyCode::Esc || lower == 'q') { + quit_ = true; + return true; + } + + if (code == KeyCode::Enter || code == KeyCode::Space || lower == '6') { + switch (state_.mode) { + case AppMode::Photo: + trigger_photo_shutter(now_ms); + break; + case AppMode::Video: + start_video_recording(now_ms); + break; + case AppMode::Timelapse: + start_timelapse(now_ms); + break; + } + return true; + } + + if (code == KeyCode::Up || lower == 'k') { + if (state_.rail_cursor > 0) --state_.rail_cursor; + return true; + } + if (code == KeyCode::Down || lower == 'j') { + if (state_.rail_cursor < 3) ++state_.rail_cursor; + return true; + } + if (code == KeyCode::Left || lower == 'h') { + adjust_rail_setting(-1); + return true; + } + if (code == KeyCode::Right || lower == 'l') { + // Note: lowercase 'l' toggles Loupe in Photo mode per spec §5.4/§5.8! + if (lower == 'l' && state_.mode == AppMode::Photo) { + state_.loupe_enabled = !state_.loupe_enabled; + return true; + } + adjust_rail_setting(+1); + return true; + } + + if (code != KeyCode::Char) { + return false; + } + + switch (lower) { + case '1': + switch_mode(AppMode::Photo); + return true; + case '2': + switch_mode(AppMode::Video); + return true; + case '3': + switch_mode(AppMode::Timelapse); + return true; + case '5': + adjust_zoom(-1); + return true; + case '7': + adjust_zoom(+1); + return true; + case 'l': + if (state_.mode == AppMode::Photo) { + state_.loupe_enabled = !state_.loupe_enabled; + return true; + } + return false; + case 'f': + if (state_.mode == AppMode::Photo) { + state_.filter = next_filter(state_.filter, +1); + state_.config.photo_filter = filter_to_string(state_.filter); + persist_config(); + return true; + } + return false; + case 'g': + state_.config.grid_enabled = !state_.config.grid_enabled; + persist_config(); + return true; + case 'r': + if (!state_.backend_ready && backend_) { + std::string err; + if (backend_->start(build_stream_spec(), err)) { + set_toast("Camera recovered", false, now_ms); + } else { + set_toast(err.empty() ? "Retry failed" : err, true, now_ms); + } + sync_backend_status(); + return true; + } + if (state_.mode == AppMode::Photo) { + state_.config.photo_resolution = + (state_.config.photo_resolution == "8mp") ? "2mp" : "8mp"; + } else if (state_.mode == AppMode::Video) { + if (state_.config.video_resolution == "720p") { + state_.config.video_resolution = "1080p"; + } else if (state_.config.video_resolution == "1080p") { + state_.config.video_resolution = "480p"; + } else { + state_.config.video_resolution = "720p"; + } + } else { + if (state_.config.timelapse_resolution == "2mp") { + state_.config.timelapse_resolution = "1080p"; + } else if (state_.config.timelapse_resolution == "1080p") { + state_.config.timelapse_resolution = "8mp"; + } else { + state_.config.timelapse_resolution = "2mp"; + } + } + { + std::string err; + reconfigure_backend(err); + } + persist_config(); + return true; + case 'c': + if (state_.mode == AppMode::Photo) { + if (state_.config.photo_timer_sec == 0) { + state_.config.photo_timer_sec = 3; + } else if (state_.config.photo_timer_sec == 3) { + state_.config.photo_timer_sec = 10; + } else { + state_.config.photo_timer_sec = 0; + } + persist_config(); + return true; + } + if (state_.mode == AppMode::Timelapse) { + open_timelapse_custom_input(); + return true; + } + return false; + case 'p': + if (state_.mode == AppMode::Timelapse) { + open_timelapse_custom_input(); + return true; + } + return false; + case 'm': + if (state_.mode == AppMode::Video) { + state_.config.video_audio = !state_.config.video_audio; + persist_config(); + return true; + } + return false; + case 'w': + state_.config.rail_side = + (state_.config.rail_side == "right") ? "left" : "right"; + persist_config(); + return true; + case 't': + state_.theme = toggle_theme(state_.theme); + state_.config.theme = theme_to_string(state_.theme); + persist_config(); + return true; + case '8': + open_gallery(now_ms); + return true; + case 's': + open_settings(); + return true; + default: + return false; + } +} + +bool UiController::handle_gallery_key(char ch, KeyCode code, uint64_t now_ms) { + const char lower = + (code == KeyCode::Char) + ? static_cast(std::tolower(static_cast(ch))) + : 0; + + if (state_.gallery_delete_confirm) { + if (lower == 'y') { + if (!state_.gallery_items.empty()) { + const std::string deleted_name = + state_.gallery_items[static_cast(state_.gallery_cursor)] + .filename; + video_player_.stop(); + std::string err; + if (gallery_store_.delete_item(state_.gallery_cursor, err)) { + state_.gallery_items = gallery_store_.items(); + if (state_.gallery_cursor >= + static_cast(state_.gallery_items.size())) { + state_.gallery_cursor = + std::max(0, static_cast(state_.gallery_items.size()) - 1); + } + state_.gallery_delete_confirm = false; + load_current_gallery_preview(); + refresh_storage_stats(); + set_toast("Deleted " + deleted_name, false, now_ms); + } else { + state_.gallery_delete_confirm = false; + set_toast(err.empty() ? "Delete failed" : err, true, now_ms); + } + } else { + state_.gallery_delete_confirm = false; + } + return true; + } + if (lower == 'n' || code == KeyCode::Esc) { + state_.gallery_delete_confirm = false; + return true; + } + return true; + } + + if (lower == 'q') { + close_gallery(true); + return true; + } + if (code == KeyCode::Esc) { + if (gallery_store_.in_session()) { + video_player_.stop(); + gallery_store_.exit_session(); + state_.gallery_items = gallery_store_.items(); + state_.gallery_in_session = gallery_store_.in_session(); + state_.gallery_session_name = gallery_store_.session_name(); + state_.gallery_cursor = 0; + load_current_gallery_preview(); + return true; + } + close_gallery(true); + return true; + } + if (code == KeyCode::Backspace) { + if (gallery_store_.in_session()) { + video_player_.stop(); + gallery_store_.exit_session(); + state_.gallery_items = gallery_store_.items(); + state_.gallery_in_session = gallery_store_.in_session(); + state_.gallery_session_name = gallery_store_.session_name(); + state_.gallery_cursor = 0; + load_current_gallery_preview(); + return true; + } + return false; + } + + if (lower == '1' || lower == '2' || lower == '3') { + close_gallery(true); + if (lower == '1') switch_mode(AppMode::Photo); + if (lower == '2') switch_mode(AppMode::Video); + if (lower == '3') switch_mode(AppMode::Timelapse); + return true; + } + + if (lower == 't') { + state_.theme = toggle_theme(state_.theme); + state_.config.theme = theme_to_string(state_.theme); + persist_config(); + return true; + } + + if (state_.gallery_items.empty()) { + return false; + } + + const auto& cur_item = + state_.gallery_items[static_cast(state_.gallery_cursor)]; + + if (code == KeyCode::Left || lower == 'h') { + if (cur_item.type == GalleryItemType::Video && + video_player_.state().playing) { + video_player_.seek_delta(-5.0); + state_.video_player = video_player_.state(); + return true; + } + if (state_.gallery_cursor > 0) { + --state_.gallery_cursor; + load_current_gallery_preview(); + } + return true; + } + + if (code == KeyCode::Right || lower == 'l') { + if (cur_item.type == GalleryItemType::Video && + video_player_.state().playing) { + video_player_.seek_delta(+5.0); + state_.video_player = video_player_.state(); + return true; + } + if (state_.gallery_cursor + 1 < + static_cast(state_.gallery_items.size())) { + ++state_.gallery_cursor; + load_current_gallery_preview(); + } + return true; + } + + if (code == KeyCode::Up || lower == 'k') { + if (state_.gallery_cursor > 0) { + --state_.gallery_cursor; + load_current_gallery_preview(); + } + return true; + } + if (code == KeyCode::Down || lower == 'j') { + if (state_.gallery_cursor + 1 < + static_cast(state_.gallery_items.size())) { + ++state_.gallery_cursor; + load_current_gallery_preview(); + } + return true; + } + + if (code == KeyCode::Space || code == KeyCode::Enter) { + if (cur_item.type == GalleryItemType::TimelapseFolder) { + if (gallery_store_.enter_session(state_.gallery_cursor)) { + state_.gallery_items = gallery_store_.items(); + state_.gallery_in_session = gallery_store_.in_session(); + state_.gallery_session_name = gallery_store_.session_name(); + state_.gallery_cursor = 0; + load_current_gallery_preview(); + } + return true; + } + if (cur_item.type == GalleryItemType::Video) { + const VideoPlayerState vst = video_player_.state(); + if (vst.playing) { + video_player_.pause(); + } else { + video_player_.play(!gallery_muted_); + } + state_.video_player = video_player_.state(); + return true; + } + return false; + } + + if (lower == 'm' && cur_item.type == GalleryItemType::Video) { + gallery_muted_ = !gallery_muted_; + video_player_.toggle_mute(); + state_.video_player = video_player_.state(); + return true; + } + + if (code == KeyCode::Delete || lower == 'd') { + if (video_player_.state().playing) { + video_player_.pause(); + state_.video_player = video_player_.state(); + } + state_.gallery_delete_confirm = true; + return true; + } + + return false; +} + +bool UiController::handle_settings_key(char ch, KeyCode code, uint64_t /*now_ms*/) { + const char lower = + (code == KeyCode::Char) + ? static_cast(std::tolower(static_cast(ch))) + : 0; + + if (code == KeyCode::Esc) { + persist_config(); + state_.modal = OverlayModal::None; + return true; + } + if (code == KeyCode::Up || lower == 'k') { + if (state_.settings_cursor > 0) --state_.settings_cursor; + return true; + } + if (code == KeyCode::Down || lower == 'j') { + if (state_.settings_cursor < 5) ++state_.settings_cursor; + return true; + } + if (code == KeyCode::Left || lower == 'h') { + apply_settings_row(-1); + return true; + } + if (code == KeyCode::Right || lower == 'l' || code == KeyCode::Enter || + code == KeyCode::Space) { + apply_settings_row(+1); + return true; + } + return false; +} + +bool UiController::handle_dir_picker_key(char ch, + KeyCode code, + uint64_t now_ms) { + const char lower = + (code == KeyCode::Char) + ? static_cast(std::tolower(static_cast(ch))) + : 0; + + if (code == KeyCode::Esc) { + state_.modal = OverlayModal::Settings; + return true; + } + if (code == KeyCode::Up || lower == 'k') { + if (state_.dir_cursor > 0) --state_.dir_cursor; + return true; + } + if (code == KeyCode::Down || lower == 'j') { + const int max_idx = static_cast(state_.dir_entries.size()) - 1; + if (state_.dir_cursor < max_idx) ++state_.dir_cursor; + return true; + } + if (code == 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 true; + } + if (code == KeyCode::Backspace) { + const fs::path cur(state_.dir_current_path); + const fs::path parent = cur.parent_path(); + if (!parent.empty() && parent != cur) { + load_directory(parent.string(), cur.filename().string()); + } + return true; + } + if (code == KeyCode::Space || ch == '.') { + std::string chosen = state_.dir_current_path; + if (code == KeyCode::Space && 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()) { + if (!mkdir_p(chosen)) { + set_toast("Cannot access folder", true, now_ms); + return true; + } + state_.config.output_dir = chosen; + state_.effective_output_dir = expand_user_path(chosen); + output_dir_override_active_ = false; + persist_config(); + refresh_storage_stats(); + state_.modal = OverlayModal::Settings; + set_toast("Output: " + base_name(chosen), false, now_ms); + } + return true; + } + if (lower == 't') { + open_text_input(); + return true; + } + if (ch == '/') { + load_directory("/"); + return true; + } + if (ch == '~') { + const char* home = std::getenv("HOME"); + if (home != nullptr && is_valid_dir(home)) { + load_directory(home); + } + return true; + } + return false; +} + +bool UiController::handle_text_input_key(char ch, + KeyCode code, + uint64_t now_ms) { + if (code == KeyCode::Esc || + (code == KeyCode::Char && static_cast(ch) == 0x1b)) { + state_.modal_error.clear(); + state_.modal = OverlayModal::DirPicker; + return true; + } + if (code == KeyCode::Backspace || + (code == KeyCode::Char && + (ch == '\b' || static_cast(ch) == 0x7f))) { + if (!state_.text_buffer.empty()) { + state_.text_buffer.pop_back(); + state_.modal_error.clear(); + } + return true; + } + if (code == KeyCode::Enter || + (code == KeyCode::Char && (ch == '\n' || ch == '\r'))) { + const std::string raw = trim_ascii(state_.text_buffer); + if (raw.empty()) { + state_.modal_error = "Path cannot be empty"; + return true; + } + const std::string expanded = expand_user_path(raw); + if (!mkdir_p(expanded)) { + state_.modal_error = "Cannot create or access directory"; + return true; + } + state_.config.output_dir = raw; + state_.effective_output_dir = expanded; + output_dir_override_active_ = false; + persist_config(); + refresh_storage_stats(); + state_.modal_error.clear(); + state_.modal = OverlayModal::Settings; + set_toast("Output: " + base_name(expanded), false, now_ms); + return true; + } + if (code == KeyCode::Space) { + if (state_.text_buffer.size() < 256) { + state_.text_buffer.push_back(' '); + state_.modal_error.clear(); + } + return true; + } + if (code == KeyCode::Char) { + const 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 true; + } + return false; +} + +bool UiController::handle_tl_custom_key(char ch, + KeyCode code, + uint64_t /*now_ms*/) { + if (code == KeyCode::Esc || + (code == KeyCode::Char && static_cast(ch) == 0x1b)) { + state_.modal_error.clear(); + state_.tl_custom_text.clear(); + state_.modal = OverlayModal::None; + return true; + } + + if (code == KeyCode::Enter || + (code == KeyCode::Char && (ch == '\n' || ch == '\r'))) { + state_.config.timelapse_interval_sec = + std::clamp(state_.tl_custom_interval_sec, 1, 3600); + state_.config.timelapse_fps = state_.tl_custom_fps; + state_.config.timelapse_stop_mode = state_.tl_custom_stop_mode; + state_.config.timelapse_stop_value = + (state_.tl_custom_stop_mode == "manual") + ? 0 + : std::max(1, state_.tl_custom_stop_value); + persist_config(); + state_.tl_custom_text.clear(); + state_.modal = OverlayModal::None; + return true; + } + + const char lower = + (code == KeyCode::Char) + ? static_cast(std::tolower(static_cast(ch))) + : 0; + + if (code == KeyCode::Up || lower == 'k') { + if (state_.tl_custom_cursor > 0) { + --state_.tl_custom_cursor; + state_.tl_custom_text.clear(); + } + return true; + } + if (code == KeyCode::Down || lower == 'j') { + if (state_.tl_custom_cursor < 3) { + ++state_.tl_custom_cursor; + state_.tl_custom_text.clear(); + } + return true; + } + + // Numeric entry for Interval (row 0) or Stop Value (row 3) + if (code == KeyCode::Char && std::isdigit(static_cast(ch))) { + if (state_.tl_custom_cursor == 0 || + (state_.tl_custom_cursor == 3 && + state_.tl_custom_stop_mode != "manual")) { + if (state_.tl_custom_text.size() < 4) { + state_.tl_custom_text.push_back(ch); + const int val = std::atoi(state_.tl_custom_text.c_str()); + if (state_.tl_custom_cursor == 0) { + state_.tl_custom_interval_sec = std::clamp(val, 1, 3600); + } else if (state_.tl_custom_stop_mode == "shots") { + state_.tl_custom_stop_value = std::clamp(val, 1, 9999); + } else { + state_.tl_custom_stop_value = std::clamp(val, 1, 1440) * 60; + } + } + return true; + } + } + + if (code == KeyCode::Backspace || + (code == KeyCode::Char && + (ch == '\b' || static_cast(ch) == 0x7f))) { + if (!state_.tl_custom_text.empty()) { + state_.tl_custom_text.pop_back(); + const int val = + state_.tl_custom_text.empty() ? 1 + : std::atoi(state_.tl_custom_text.c_str()); + if (state_.tl_custom_cursor == 0) { + state_.tl_custom_interval_sec = std::clamp(val, 1, 3600); + } else if (state_.tl_custom_stop_mode == "shots") { + state_.tl_custom_stop_value = std::clamp(val, 1, 9999); + } else if (state_.tl_custom_stop_mode == "duration") { + state_.tl_custom_stop_value = std::clamp(val, 1, 1440) * 60; + } + return true; + } + } + + if (code == KeyCode::Left || code == KeyCode::Right || lower == 'h' || + lower == 'l') { + const int delta = (code == KeyCode::Left || lower == 'h') ? -1 : +1; + state_.tl_custom_text.clear(); + if (state_.tl_custom_cursor == 0) { + const int step = (state_.tl_custom_interval_sec >= 20) ? 5 : 1; + state_.tl_custom_interval_sec = + std::clamp(state_.tl_custom_interval_sec + delta * step, 1, 3600); + } else if (state_.tl_custom_cursor == 1) { + const int idx = find_index_int(kFpsPresets, state_.tl_custom_fps); + state_.tl_custom_fps = + kFpsPresets[static_cast((idx + delta + 3) % 3)]; + } else if (state_.tl_custom_cursor == 2) { + static constexpr std::array kStopModes = { + "manual", "shots", "duration"}; + const int idx = find_index_str(kStopModes, state_.tl_custom_stop_mode); + state_.tl_custom_stop_mode = + kStopModes[static_cast((idx + delta + 3) % 3)]; + if (state_.tl_custom_stop_mode == "manual") { + state_.tl_custom_stop_value = 0; + } else if (state_.tl_custom_stop_mode == "shots" && + state_.tl_custom_stop_value <= 0) { + state_.tl_custom_stop_value = 60; + } else if (state_.tl_custom_stop_mode == "duration" && + state_.tl_custom_stop_value < 60) { + state_.tl_custom_stop_value = 900; + } + } else if (state_.tl_custom_cursor == 3) { + if (state_.tl_custom_stop_mode == "shots") { + state_.tl_custom_stop_value = + std::clamp(state_.tl_custom_stop_value + delta * 10, 10, 9999); + } else if (state_.tl_custom_stop_mode == "duration") { + const int mins = std::max(1, state_.tl_custom_stop_value / 60); + state_.tl_custom_stop_value = + std::clamp(mins + delta * 5, 1, 1440) * 60; + } + } + return true; + } + + return false; +} + +bool UiController::handle_tl_recovery_key(char ch, + KeyCode code, + uint64_t now_ms) { + if (code == KeyCode::Esc) { + state_.modal = OverlayModal::None; + return true; + } + if (code != KeyCode::Char) { + return false; + } + const char lower = + static_cast(std::tolower(static_cast(ch))); + if (lower == 'c') { + const TimelapseManifest m = state_.recovery_manifest; + const TimelapseSessionPaths paths = session_paths_from_manifest(m); + const int fps = (m.fps > 0) ? m.fps : state_.config.timelapse_fps; + const std::string res = + m.resolution.empty() ? state_.config.timelapse_resolution : m.resolution; + start_compile_async(paths, fps, res, m, true); + return true; + } + if (lower == 'k') { + std::string msg; + const bool ok = timelapse_engine_.recover_session( + state_.recovery_manifest, RecoveryAction::KeepPhotos, msg); + set_toast(msg, !ok, now_ms); + refresh_storage_stats(); + advance_recovery_queue(); + return true; + } + if (lower == 'd') { + std::string msg; + const bool ok = timelapse_engine_.recover_session( + state_.recovery_manifest, RecoveryAction::Discard, msg); + set_toast(msg, !ok, now_ms); + refresh_storage_stats(); + advance_recovery_queue(); + return true; + } + return false; +} + +bool UiController::handle_tl_stop_confirm_key(char ch, + KeyCode code, + uint64_t now_ms) { + const char lower = + (code == KeyCode::Char) + ? static_cast(std::tolower(static_cast(ch))) + : 0; + + if (code == KeyCode::Esc || lower == 'n') { + state_.modal = OverlayModal::None; + return true; + } + + if (lower == 'y') { + state_.modal = OverlayModal::None; + timelapse_engine_.request_stop(); + state_.timelapse = timelapse_engine_.state(); + refresh_storage_stats(); + + if (state_.timelapse.needs_compile) { + const TimelapseSessionPaths sp = timelapse_engine_.session_paths(); + TimelapseManifest fb; + fb.session_id = sp.session_id; + fb.work_dir = sp.work_dir; + fb.resolution = state_.config.timelapse_resolution; + fb.fps = state_.config.timelapse_fps; + fb.frame_count = state_.timelapse.shots_taken; + start_compile_async(sp, state_.config.timelapse_fps, + state_.config.timelapse_resolution, fb, false); + } else if (!state_.timelapse.result_path.empty()) { + set_toast("Saved " + base_name(state_.timelapse.result_path), false, + now_ms); + } else { + set_toast("Timelapse stopped", false, now_ms); + } + return true; + } + + return false; +} + +bool UiController::handle_tl_compiling_key(char /*ch*/, + KeyCode code, + uint64_t now_ms) { + if (code == KeyCode::Esc) { + compile_cancelled_by_user_ = true; + timelapse_engine_.cancel_compile(); + join_compile_thread(); + compile_finished_.store(true, std::memory_order_release); + finish_compile_if_ready(now_ms); + return true; + } + return false; +} + +} // namespace cz diff --git a/app/src/ui_controller.hpp b/app/src/ui_controller.hpp new file mode 100644 index 0000000..d2a10c6 --- /dev/null +++ b/app/src/ui_controller.hpp @@ -0,0 +1,248 @@ +#pragma once + +#include "backlight.hpp" +#include "camera_backend.hpp" +#include "config.hpp" +#include "filters.hpp" +#include "gallery_model.hpp" +#include "theme.hpp" +#include "timelapse_engine.hpp" +#include "video_player.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace cz { + +enum class KeyCode { + Char, + Enter, + Space, + Backspace, + Delete, + Esc, + Up, + Down, + Left, + Right, +}; + +enum class AppMode { + Photo = 0, + Video = 1, + Timelapse = 2, +}; + +enum class OverlayModal { + None, + Gallery, + Settings, + DirPicker, + TextInput, + TimelapseCustomInput, + TimelapseRecovery, + TimelapseStopConfirm, + TimelapseCompiling, +}; + +struct UiControllerOptions { + std::string config_path; + std::string output_dir_override; + std::string backlight_sysfs_root = "/sys/class/backlight"; + bool mock_backend = false; + bool persist_config = true; + bool skip_startup_recovery_scan = false; +}; + +struct UiState { + AppMode mode = AppMode::Photo; + OverlayModal modal = OverlayModal::None; + ThemeMode theme = ThemeMode::Dark; + AppConfig config; + std::string effective_output_dir; + + // Rail & camera live controls + int rail_cursor = 1; // 0..3 + float zoom = 1.0f; + bool loupe_enabled = false; + FilterId filter = FilterId::None; + + // Photo countdown & flash + bool timer_active = false; + int timer_remaining_sec = 0; + bool capture_flash_active = false; + + // Video recording + bool video_recording = false; + int video_elapsed_sec = 0; + + // Timelapse runtime & dimming + TimelapseState timelapse; + bool timelapse_dimmed = false; + bool has_hardware_backlight = false; + + // Timelapse custom input modal + int tl_custom_cursor = 0; // 0: interval, 1: fps, 2: stop_mode, 3: stop_value + int tl_custom_interval_sec = 5; + int tl_custom_fps = 24; + std::string tl_custom_stop_mode = "manual"; + int tl_custom_stop_value = 0; + std::string tl_custom_text; + + // Timelapse orphan recovery modal + TimelapseManifest recovery_manifest; + int recovery_remaining = 0; + + // Settings modal + int settings_cursor = 0; // 0..5 + + // Directory picker & manual path input + std::string dir_current_path; + std::vector dir_entries; + int dir_cursor = -1; + std::string text_buffer; + std::string modal_error; + + // Gallery modal + std::vector gallery_items; + int gallery_cursor = 0; + bool gallery_in_session = false; + std::string gallery_session_name; + bool gallery_delete_confirm = false; + VideoPlayerState video_player; + + // Status / storage / toast + uint64_t free_bytes = 0; + bool backend_ready = false; + bool backend_paused = false; + std::string backend_error; + std::string toast_message; + bool toast_is_error = false; +}; + +class UiController { + public: + explicit UiController(std::unique_ptr backend = nullptr, + const UiControllerOptions& opts = UiControllerOptions{}); + ~UiController(); + + UiController(const UiController&) = delete; + UiController& operator=(const UiController&) = delete; + + bool init(uint64_t now_ms); + void shutdown(); + + void tick(uint64_t now_ms); + bool handle_key(char ch, KeyCode code, uint64_t now_ms); + + const UiState& state() const { return state_; } + bool should_quit() const { return quit_; } + bool consume_capture_flash(); + + ICameraBackend* backend() { return backend_.get(); } + const BacklightController& backlight() const { return backlight_; } + BacklightController& backlight() { return backlight_; } + VideoPlayer& video_player() { return video_player_; } + const PreviewFrame* gallery_preview() const { + return has_gallery_preview_ ? &gallery_frame_ : nullptr; + } + + void set_toast(const std::string& message, bool is_error, uint64_t now_ms); + void refresh_storage_stats(); + + private: + CameraStreamSpec build_stream_spec() const; + AppConfig effective_engine_config() const; + void persist_config(); + bool reconfigure_backend(std::string& out_err); + void sync_backend_status(); + + void switch_mode(AppMode target); + void adjust_zoom(int delta_step); + void adjust_ev(int delta_step); + void adjust_rail_setting(int delta); + void trigger_photo_shutter(uint64_t now_ms); + void capture_photo_now(uint64_t now_ms); + + void start_video_recording(uint64_t now_ms); + void stop_video_recording(bool low_storage, uint64_t now_ms); + + void start_timelapse(uint64_t now_ms); + void start_compile_async(const TimelapseSessionPaths& paths, + int fps, + const std::string& resolution, + const TimelapseManifest& fallback_manifest, + bool from_recovery); + void join_compile_thread(); + void finish_compile_if_ready(uint64_t now_ms); + void advance_recovery_queue(); + + void open_gallery(uint64_t now_ms); + void close_gallery(bool resume_camera); + void load_current_gallery_preview(); + + void open_settings(); + void apply_settings_row(int delta); + void open_dir_picker(); + void load_directory(const std::string& path, const std::string& select_name = ""); + void open_text_input(); + void open_timelapse_custom_input(); + + bool handle_none_modal_key(char ch, KeyCode code, uint64_t now_ms); + bool handle_gallery_key(char ch, KeyCode code, uint64_t now_ms); + bool handle_settings_key(char ch, KeyCode code, uint64_t now_ms); + bool handle_dir_picker_key(char ch, KeyCode code, uint64_t now_ms); + bool handle_text_input_key(char ch, KeyCode code, uint64_t now_ms); + bool handle_tl_custom_key(char ch, KeyCode code, uint64_t now_ms); + bool handle_tl_recovery_key(char ch, KeyCode code, uint64_t now_ms); + bool handle_tl_stop_confirm_key(char ch, KeyCode code, uint64_t now_ms); + bool handle_tl_compiling_key(char ch, KeyCode code, uint64_t now_ms); + + UiControllerOptions opts_; + std::unique_ptr backend_; + BacklightController backlight_; + TimelapseEngine timelapse_engine_; + GalleryStore gallery_store_; + VideoPlayer video_player_; + + UiState state_; + std::string persisted_output_dir_; + bool output_dir_override_active_ = false; + bool initialized_ = false; + bool quit_ = false; + bool capture_flash_pending_ = false; + + uint64_t last_activity_ms_ = 0; + uint64_t timer_target_ms_ = 0; + uint64_t flash_until_ms_ = 0; + uint64_t toast_until_ms_ = 0; + + uint64_t video_start_ms_ = 0; + uint64_t last_storage_check_ms_ = 0; + std::string video_tmp_path_; + std::string video_final_path_; + bool warned_audio_ = false; + + PreviewFrame gallery_frame_; + bool has_gallery_preview_ = false; + bool gallery_muted_ = false; + + std::vector orphaned_timelapses_; + + std::thread compile_thread_; + std::atomic compile_in_flight_{false}; + std::atomic compile_finished_{false}; + std::mutex compile_result_mutex_; + bool compile_ok_ = false; + bool compile_cancelled_by_user_ = false; + bool compile_from_recovery_ = false; + std::string compile_result_msg_; + TimelapseManifest compile_fallback_manifest_; +}; + +} // namespace cz diff --git a/app/tests/test_ui_controller.cpp b/app/tests/test_ui_controller.cpp new file mode 100644 index 0000000..a856d61 --- /dev/null +++ b/app/tests/test_ui_controller.cpp @@ -0,0 +1,770 @@ +#include "app_ui.hpp" +#include "config.hpp" +#include "sim_backend.hpp" +#include "storage.hpp" +#include "ui_controller.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace fs = std::filesystem; + +namespace { + +struct TempDir { + std::string path; + explicit TempDir(const std::string& name) { + const std::string base = + "/tmp/czcamera_test_t6_" + name + "_" + std::to_string(::getpid()); + std::error_code ec; + fs::remove_all(base, ec); + fs::create_directories(base, ec); + assert(!ec); + path = base; + } + ~TempDir() { + std::error_code ec; + fs::remove_all(path, ec); + } +}; + +void write_text(const std::string& path, const std::string& content) { + std::ofstream out(path, std::ios::binary | std::ios::trunc); + assert(out.is_open()); + out.write(content.data(), static_cast(content.size())); + out.close(); + assert(out.good()); +} + +std::string read_text(const std::string& path) { + std::ifstream in(path, std::ios::binary); + assert(in.is_open()); + return std::string((std::istreambuf_iterator(in)), + std::istreambuf_iterator()); +} + +int count_files_with_ext(const std::string& dir, const std::string& ext) { + int count = 0; + std::error_code ec; + for (const auto& entry : fs::directory_iterator(dir, ec)) { + if (!entry.is_regular_file(ec)) continue; + const std::string name = entry.path().filename().string(); + if (name.empty() || name[0] == '.') continue; + if (name.size() >= ext.size() && + name.compare(name.size() - ext.size(), ext.size(), ext) == 0) { + ++count; + } + } + return count; +} + +int count_hidden_files(const std::string& dir) { + int count = 0; + std::error_code ec; + for (const auto& entry : fs::directory_iterator(dir, ec)) { + const std::string name = entry.path().filename().string(); + if (!name.empty() && name[0] == '.') { + ++count; + } + } + return count; +} + +class SpyCameraBackend final : public cz::ICameraBackend { + public: + bool start(const cz::CameraStreamSpec& initial_spec, + std::string& out_err) override { + start_specs.push_back(initial_spec); + last_zoom = initial_spec.zoom; + last_ev = initial_spec.ev; + return inner_.start(initial_spec, out_err); + } + + void stop() override { inner_.stop(); } + + bool reconfigure(const cz::CameraStreamSpec& spec, + std::string& out_err) override { + reconfigure_specs.push_back(spec); + last_zoom = spec.zoom; + last_ev = spec.ev; + return inner_.reconfigure(spec, out_err); + } + + bool set_controls(float zoom, float ev, std::string& out_err) override { + last_zoom = zoom; + last_ev = ev; + ++set_controls_calls; + return inner_.set_controls(zoom, ev, out_err); + } + + bool pause(std::string& out_err) override { + ++pause_calls; + return inner_.pause(out_err); + } + + bool resume(std::string& out_err) override { + ++resume_calls; + return inner_.resume(out_err); + } + + bool copy_latest_preview(uint64_t last_seen_seq, + cz::PreviewFrame& out_frame) override { + return inner_.copy_latest_preview(last_seen_seq, out_frame); + } + + cz::StillCaptureResult capture_still(const std::string& tmp_jpeg_path, + int width, + int height) override { + ++capture_still_calls; + return inner_.capture_still(tmp_jpeg_path, width, height); + } + + bool start_video(const cz::VideoSpec& spec, std::string& out_err) override { + return inner_.start_video(spec, out_err); + } + + cz::VideoStopResult stop_video() override { return inner_.stop_video(); } + + cz::BackendHealth status() const override { return inner_.status(); } + + std::vector start_specs; + std::vector reconfigure_specs; + float last_zoom = 1.0f; + float last_ev = 0.0f; + int set_controls_calls = 0; + int pause_calls = 0; + int resume_calls = 0; + int capture_still_calls = 0; + + private: + cz::SimCameraBackend inner_; +}; + +void test_photo_controls_zoom_loupe_filters_and_timer() { + TempDir tmp("photo"); + const std::string cfg_path = tmp.path + "/config.json"; + const std::string out_dir = tmp.path + "/out"; + assert(cz::mkdir_p(out_dir)); + + cz::AppConfig cfg; + cfg.output_dir = out_dir; + assert(cz::save_config(cfg, cfg_path)); + + auto spy_owned = std::make_unique(); + SpyCameraBackend* spy = spy_owned.get(); + + cz::UiControllerOptions opts; + opts.config_path = cfg_path; + opts.backlight_sysfs_root = tmp.path + "/no_backlight"; + + cz::UiController ctrl(std::move(spy_owned), opts); + uint64_t now = 1000; + assert(ctrl.init(now)); + assert(ctrl.state().mode == cz::AppMode::Photo); + assert(ctrl.state().zoom == 1.0f); + assert(!ctrl.state().loupe_enabled); + assert(ctrl.state().filter == cz::FilterId::None); + assert(ctrl.state().config.photo_resolution == "8mp"); + assert(ctrl.state().config.photo_timer_sec == 0); + + // Crop zoom 5/7 steps through 1.0 -> 1.5 -> 2.0 -> 3.0 -> 4.0 and back + ctrl.handle_key('7', cz::KeyCode::Char, now); + assert(ctrl.state().zoom == 1.5f); + assert(spy->last_zoom == 1.5f); + ctrl.handle_key('7', cz::KeyCode::Char, now); + assert(ctrl.state().zoom == 2.0f); + ctrl.handle_key('7', cz::KeyCode::Char, now); + assert(ctrl.state().zoom == 3.0f); + ctrl.handle_key('7', cz::KeyCode::Char, now); + assert(ctrl.state().zoom == 4.0f); + ctrl.handle_key('7', cz::KeyCode::Char, now); + assert(ctrl.state().zoom == 4.0f); + + ctrl.handle_key('5', cz::KeyCode::Char, now); + assert(ctrl.state().zoom == 3.0f); + ctrl.handle_key('5', cz::KeyCode::Char, now); + assert(ctrl.state().zoom == 2.0f); + ctrl.handle_key('5', cz::KeyCode::Char, now); + assert(ctrl.state().zoom == 1.5f); + ctrl.handle_key('5', cz::KeyCode::Char, now); + assert(ctrl.state().zoom == 1.0f); + ctrl.handle_key('5', cz::KeyCode::Char, now); + assert(ctrl.state().zoom == 1.0f); + + // Loupe L toggles 2x viewfinder magnification without changing sensor zoom + ctrl.handle_key('7', cz::KeyCode::Char, now); + assert(ctrl.state().zoom == 1.5f); + const int calls_before_loupe = spy->set_controls_calls; + ctrl.handle_key('l', cz::KeyCode::Char, now); + assert(ctrl.state().loupe_enabled); + assert(ctrl.state().zoom == 1.5f); + assert(spy->last_zoom == 1.5f); + assert(spy->set_controls_calls == calls_before_loupe); + ctrl.handle_key('L', cz::KeyCode::Char, now); + assert(!ctrl.state().loupe_enabled); + + // F cycles through all 9 filters and wraps back to None + const cz::FilterId expected_filters[9] = { + cz::FilterId::BW, cz::FilterId::HiCon, cz::FilterId::Sepia, + cz::FilterId::Cool, cz::FilterId::Vivid, cz::FilterId::Invert, + cz::FilterId::Retro, cz::FilterId::GameBoy, cz::FilterId::None, + }; + for (cz::FilterId ef : expected_filters) { + ctrl.handle_key('f', cz::KeyCode::Char, now); + assert(ctrl.state().filter == ef); + } + + // R toggles 8MP <-> 2MP and reconfigures backend + const size_t reconf_before = spy->reconfigure_specs.size(); + ctrl.handle_key('r', cz::KeyCode::Char, now); + assert(ctrl.state().config.photo_resolution == "2mp"); + assert(spy->reconfigure_specs.size() == reconf_before + 1); + assert(spy->reconfigure_specs.back().main_width == 1640); + assert(spy->reconfigure_specs.back().main_height == 1232); + ctrl.handle_key('R', cz::KeyCode::Char, now); + assert(ctrl.state().config.photo_resolution == "8mp"); + assert(spy->reconfigure_specs.back().main_width == 3280); + assert(spy->reconfigure_specs.back().main_height == 2464); + + // C cycles Off -> 3s -> 10s -> Off; Esc cancels an active countdown + ctrl.handle_key('c', cz::KeyCode::Char, now); + assert(ctrl.state().config.photo_timer_sec == 3); + ctrl.handle_key('c', cz::KeyCode::Char, now); + assert(ctrl.state().config.photo_timer_sec == 10); + ctrl.handle_key('c', cz::KeyCode::Char, now); + assert(ctrl.state().config.photo_timer_sec == 0); + + ctrl.handle_key('c', cz::KeyCode::Char, now); // 3s + ctrl.handle_key(0, cz::KeyCode::Enter, now); + assert(ctrl.state().timer_active); + assert(ctrl.state().timer_remaining_sec == 3); + now += 1500; + ctrl.tick(now); + assert(ctrl.state().timer_active); + assert(ctrl.state().timer_remaining_sec == 2); + ctrl.handle_key(0, cz::KeyCode::Esc, now); + assert(!ctrl.state().timer_active); + assert(!ctrl.should_quit()); + assert(count_files_with_ext(out_dir, ".jpg") == 0); + + // Set timer back to Off, switch to Invert filter, and shoot via Enter and '6' + ctrl.handle_key('c', cz::KeyCode::Char, now); // 10 + ctrl.handle_key('c', cz::KeyCode::Char, now); // 0 + assert(ctrl.state().config.photo_timer_sec == 0); + ctrl.handle_key('f', cz::KeyCode::Char, now); // BW + + ctrl.handle_key(0, cz::KeyCode::Enter, now); + assert(ctrl.consume_capture_flash()); + assert(!ctrl.consume_capture_flash()); + assert(count_files_with_ext(out_dir, ".jpg") == 1); + assert(count_hidden_files(out_dir) == 0); + + now += 1000; + ctrl.handle_key('6', cz::KeyCode::Char, now); + assert(ctrl.consume_capture_flash()); + assert(count_files_with_ext(out_dir, ".jpg") == 2); + assert(count_hidden_files(out_dir) == 0); +} + +void test_rail_side_and_theme_toggles_persist() { + TempDir tmp("rail_theme"); + const std::string cfg_path = tmp.path + "/config.json"; + const std::string out_dir = tmp.path + "/out"; + assert(cz::mkdir_p(out_dir)); + + cz::AppConfig cfg; + cfg.output_dir = out_dir; + assert(cz::save_config(cfg, cfg_path)); + + cz::UiControllerOptions opts; + opts.config_path = cfg_path; + opts.backlight_sysfs_root = tmp.path + "/no_backlight"; + + cz::UiController ctrl(std::make_unique(), opts); + assert(ctrl.init(1000)); + assert(ctrl.state().config.rail_side == "right"); + assert(ctrl.state().theme == cz::ThemeMode::Dark); + + ctrl.handle_key('w', cz::KeyCode::Char, 1010); + assert(ctrl.state().config.rail_side == "left"); + assert(cz::load_config(cfg_path).rail_side == "left"); + + ctrl.handle_key('t', cz::KeyCode::Char, 1020); + assert(ctrl.state().theme == cz::ThemeMode::Light); + assert(ctrl.state().config.theme == "light"); + assert(cz::load_config(cfg_path).theme == "light"); + + // Render check: Dark+Right vs Light+Left must differ + cz::PreviewFrame live; + assert(ctrl.backend()->copy_latest_preview(0, live)); + + cz::AppView view; + view.apply_theme(ctrl.state().theme); + view.render(ctrl.state(), &live, nullptr); + std::vector light_left( + view.pixels(), + view.pixels() + cz::AppView::kWidth * cz::AppView::kHeight); + + ctrl.handle_key('W', cz::KeyCode::Char, 1030); + assert(ctrl.state().config.rail_side == "right"); + assert(cz::load_config(cfg_path).rail_side == "right"); + + ctrl.handle_key('T', cz::KeyCode::Char, 1040); + assert(ctrl.state().theme == cz::ThemeMode::Dark); + assert(cz::load_config(cfg_path).theme == "dark"); + + view.apply_theme(ctrl.state().theme); + view.render(ctrl.state(), &live, nullptr); + std::vector dark_right( + view.pixels(), + view.pixels() + cz::AppView::kWidth * cz::AppView::kHeight); + assert(light_left != dark_right); +} + +void test_video_mode_locks_transitions_while_recording() { + TempDir tmp("video"); + const std::string cfg_path = tmp.path + "/config.json"; + const std::string out_dir = tmp.path + "/out"; + assert(cz::mkdir_p(out_dir)); + + cz::AppConfig cfg; + cfg.output_dir = out_dir; + assert(cz::save_config(cfg, cfg_path)); + + cz::UiControllerOptions opts; + opts.config_path = cfg_path; + opts.backlight_sysfs_root = tmp.path + "/no_backlight"; + + cz::UiController ctrl(std::make_unique(), opts); + uint64_t now = 1000; + assert(ctrl.init(now)); + + ctrl.handle_key('2', cz::KeyCode::Char, now); + assert(ctrl.state().mode == cz::AppMode::Video); + assert(ctrl.state().config.video_audio); + + ctrl.handle_key('m', cz::KeyCode::Char, now); + assert(!ctrl.state().config.video_audio); + ctrl.handle_key('M', cz::KeyCode::Char, now); + assert(ctrl.state().config.video_audio); + + // Start recording with Enter + ctrl.handle_key(0, cz::KeyCode::Enter, now); + assert(ctrl.state().video_recording); + + // Locked keys while recording must be ignored cleanly + const char locked_keys[] = {'1', '3', '8', 's', 'w', 'm', 'r', 't', 'q'}; + for (char ch : locked_keys) { + ctrl.handle_key(ch, cz::KeyCode::Char, now); + assert(ctrl.state().mode == cz::AppMode::Video); + assert(ctrl.state().modal == cz::OverlayModal::None); + assert(ctrl.state().config.rail_side == "right"); + assert(ctrl.state().config.video_audio); + assert(ctrl.state().config.video_resolution == "720p"); + assert(ctrl.state().theme == cz::ThemeMode::Dark); + assert(ctrl.state().video_recording); + assert(!ctrl.should_quit()); + } + + // Zoom 5/7 still works live during recording + ctrl.handle_key('7', cz::KeyCode::Char, now); + assert(ctrl.state().zoom == 1.5f); + + now += 1500; + ctrl.tick(now); + assert(ctrl.state().video_elapsed_sec >= 1); + + // Esc stops recording without quitting + ctrl.handle_key(0, cz::KeyCode::Esc, now); + assert(!ctrl.state().video_recording); + assert(!ctrl.should_quit()); + assert(count_files_with_ext(out_dir, ".mp4") == 1); + assert(count_hidden_files(out_dir) == 0); + + // Enter also starts & stops recording cleanly + now += 500; + ctrl.handle_key(0, cz::KeyCode::Enter, now); + assert(ctrl.state().video_recording); + now += 500; + ctrl.handle_key(0, cz::KeyCode::Enter, now); + assert(!ctrl.state().video_recording); + assert(count_files_with_ext(out_dir, ".mp4") == 2); +} + +void test_timelapse_dimmed_safe_wake() { + auto run_wake_case = [](const std::string& label, + char wake_ch, + cz::KeyCode wake_code, + bool finish_with_stop_confirm) { + TempDir tmp("tl_wake_" + label); + const std::string cfg_path = tmp.path + "/config.json"; + const std::string out_dir = tmp.path + "/out"; + const std::string bl_root = tmp.path + "/backlight"; + const std::string lcd0 = bl_root + "/lcd0"; + assert(cz::mkdir_p(out_dir)); + assert(cz::mkdir_p(lcd0)); + write_text(lcd0 + "/brightness", "128\n"); + write_text(lcd0 + "/max_brightness", "255\n"); + + cz::AppConfig cfg; + cfg.output_dir = out_dir; + cfg.timelapse_dim_sec = 5; + cfg.timelapse_interval_sec = 4; + cfg.timelapse_output_mode = "video"; + cfg.timelapse_resolution = "2mp"; + assert(cz::save_config(cfg, cfg_path)); + + cz::UiControllerOptions opts; + opts.config_path = cfg_path; + opts.backlight_sysfs_root = bl_root; + + cz::UiController ctrl(std::make_unique(), opts); + uint64_t now = 1000; + assert(ctrl.init(now)); + assert(ctrl.backlight().has_hardware_backlight()); + + ctrl.handle_key('3', cz::KeyCode::Char, now); + assert(ctrl.state().mode == cz::AppMode::Timelapse); + + ctrl.handle_key(0, cz::KeyCode::Enter, now); + ctrl.tick(now); + assert(ctrl.state().timelapse.running); + assert(ctrl.state().timelapse.shots_taken >= 1); + assert(!ctrl.backlight().is_dimmed()); + + // Advance 6s (> 5s dim threshold) + now += 6000; + ctrl.tick(now); + assert(ctrl.backlight().is_dimmed()); + assert(ctrl.state().timelapse_dimmed); + assert(std::stoi(read_text(lcd0 + "/brightness")) == 0); + + // First keypress while dimmed ONLY wakes backlight + ctrl.handle_key(wake_ch, wake_code, now); + assert(!ctrl.backlight().is_dimmed()); + assert(!ctrl.state().timelapse_dimmed); + assert(std::stoi(read_text(lcd0 + "/brightness")) == 128); + assert(ctrl.state().modal == cz::OverlayModal::None); + assert(ctrl.state().timelapse.running); + assert(!ctrl.should_quit()); + + if (finish_with_stop_confirm) { + // Pressing Esc while awake opens TimelapseStopConfirm + now += 50; + ctrl.handle_key(0, cz::KeyCode::Esc, now); + assert(ctrl.state().modal == cz::OverlayModal::TimelapseStopConfirm); + assert(ctrl.state().timelapse.running); + + // [N] resumes capture + now += 50; + ctrl.handle_key('n', cz::KeyCode::Char, now); + assert(ctrl.state().modal == cz::OverlayModal::None); + assert(ctrl.state().timelapse.running); + + // Esc again -> [Y] stops & compiles MP4 + now += 50; + ctrl.handle_key(0, cz::KeyCode::Esc, now); + assert(ctrl.state().modal == cz::OverlayModal::TimelapseStopConfirm); + now += 50; + ctrl.handle_key('y', cz::KeyCode::Char, now); + assert(!ctrl.state().timelapse.running); + + const auto dl = + std::chrono::steady_clock::now() + std::chrono::seconds(8); + while (ctrl.state().modal == cz::OverlayModal::TimelapseCompiling && + std::chrono::steady_clock::now() < dl) { + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + now += 20; + ctrl.tick(now); + } + assert(ctrl.state().modal == cz::OverlayModal::None); + assert(!ctrl.state().timelapse.compiling); + assert(count_files_with_ext(out_dir, ".mp4") == 1); + assert(count_hidden_files(out_dir) == 0); + } else { + // Clean stop before teardown + now += 50; + ctrl.handle_key(0, cz::KeyCode::Esc, now); + ctrl.handle_key('y', cz::KeyCode::Char, now); + const auto dl = + std::chrono::steady_clock::now() + std::chrono::seconds(8); + while (ctrl.state().modal == cz::OverlayModal::TimelapseCompiling && + std::chrono::steady_clock::now() < dl) { + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + now += 20; + ctrl.tick(now); + } + } + }; + + run_wake_case("enter", 0, cz::KeyCode::Enter, false); + run_wake_case("6", '6', cz::KeyCode::Char, false); + run_wake_case("esc", 0, cz::KeyCode::Esc, false); + run_wake_case("q", 'q', cz::KeyCode::Char, true); +} + +void test_settings_dir_picker_camera_orient_and_gallery_delete() { + TempDir tmp("settings_gallery"); + const std::string cfg_path = tmp.path + "/config.json"; + const std::string out1 = tmp.path + "/out1"; + const std::string alt_parent = tmp.path + "/alt_dir"; + const std::string picked_sub = alt_parent + "/picked_sub"; + assert(cz::mkdir_p(out1)); + assert(cz::mkdir_p(picked_sub)); + + cz::AppConfig cfg; + cfg.output_dir = out1; + assert(cz::save_config(cfg, cfg_path)); + + auto spy_owned = std::make_unique(); + SpyCameraBackend* spy = spy_owned.get(); + + cz::UiControllerOptions opts; + opts.config_path = cfg_path; + opts.backlight_sysfs_root = tmp.path + "/no_backlight"; + + cz::UiController ctrl(std::move(spy_owned), opts); + uint64_t now = 1000; + assert(ctrl.init(now)); + + // [S] opens Settings + ctrl.handle_key('s', cz::KeyCode::Char, now); + assert(ctrl.state().modal == cz::OverlayModal::Settings); + assert(ctrl.state().settings_cursor == 0); + + // Navigate to Camera Orient (row 5) and cycle auto -> 0 -> 180 -> hflip -> vflip + for (int i = 0; i < 5; ++i) { + ctrl.handle_key(0, cz::KeyCode::Down, now); + } + assert(ctrl.state().settings_cursor == 5); + + const std::string expected_orients[] = {"0", "180", "hflip", "vflip", "auto"}; + for (const std::string& exp : expected_orients) { + const size_t n_before = spy->reconfigure_specs.size(); + ctrl.handle_key(0, cz::KeyCode::Enter, now); + assert(ctrl.state().config.camera_transform == exp); + assert(spy->reconfigure_specs.size() == n_before + 1); + assert(spy->reconfigure_specs.back().camera_transform == exp); + } + + // Navigate back to Output Dir (row 0) and open DirPicker + for (int i = 0; i < 5; ++i) { + ctrl.handle_key(0, cz::KeyCode::Up, now); + } + assert(ctrl.state().settings_cursor == 0); + ctrl.handle_key(0, cz::KeyCode::Enter, now); + assert(ctrl.state().modal == cz::OverlayModal::DirPicker); + assert(ctrl.state().dir_current_path == fs::weakly_canonical(out1).string()); + + // Up to tmp.path, find alt_dir, Enter into alt_dir, select picked_sub with Space + ctrl.handle_key(0, cz::KeyCode::Backspace, now); + assert(ctrl.state().dir_current_path == fs::weakly_canonical(tmp.path).string()); + + int alt_idx = -1; + for (size_t i = 0; i < ctrl.state().dir_entries.size(); ++i) { + if (fs::path(ctrl.state().dir_entries[i]).filename().string() == "alt_dir") { + alt_idx = static_cast(i); + break; + } + } + assert(alt_idx >= 0); + while (ctrl.state().dir_cursor < alt_idx) { + ctrl.handle_key(0, cz::KeyCode::Down, now); + } + while (ctrl.state().dir_cursor > alt_idx) { + ctrl.handle_key(0, cz::KeyCode::Up, now); + } + ctrl.handle_key(0, cz::KeyCode::Enter, now); + assert(ctrl.state().dir_current_path == + fs::weakly_canonical(alt_parent).string()); + assert(ctrl.state().dir_entries.size() == 1); + assert(fs::path(ctrl.state().dir_entries[0]).filename().string() == + "picked_sub"); + + ctrl.handle_key(' ', cz::KeyCode::Space, now); + assert(ctrl.state().modal == cz::OverlayModal::Settings); + assert(ctrl.state().effective_output_dir == + fs::weakly_canonical(picked_sub).string()); + assert(cz::load_config(cfg_path).output_dir == + fs::weakly_canonical(picked_sub).string()); + + // Close Settings + ctrl.handle_key(0, cz::KeyCode::Esc, now); + assert(ctrl.state().modal == cz::OverlayModal::None); + + // Capture a photo into picked_sub + ctrl.handle_key(0, cz::KeyCode::Enter, now); + assert(count_files_with_ext(picked_sub, ".jpg") == 1); + + // [8] pauses backend and opens Gallery + assert(spy->pause_calls == 0); + ctrl.handle_key('8', cz::KeyCode::Char, now); + assert(ctrl.state().modal == cz::OverlayModal::Gallery); + assert(spy->pause_calls == 1); + assert(ctrl.state().gallery_items.size() == 1); + assert(ctrl.gallery_preview() != nullptr); + assert(!ctrl.gallery_preview()->rgb24.empty()); + + // [D] requires [Y] before deleting + ctrl.handle_key('d', cz::KeyCode::Char, now); + assert(ctrl.state().gallery_delete_confirm); + assert(count_files_with_ext(picked_sub, ".jpg") == 1); + + ctrl.handle_key('n', cz::KeyCode::Char, now); + assert(!ctrl.state().gallery_delete_confirm); + assert(count_files_with_ext(picked_sub, ".jpg") == 1); + + ctrl.handle_key('d', cz::KeyCode::Char, now); + assert(ctrl.state().gallery_delete_confirm); + ctrl.handle_key('y', cz::KeyCode::Char, now); + assert(!ctrl.state().gallery_delete_confirm); + assert(ctrl.state().gallery_items.empty()); + assert(count_files_with_ext(picked_sub, ".jpg") == 0); + + // Esc exits Gallery and resumes backend + assert(spy->resume_calls == 0); + ctrl.handle_key(0, cz::KeyCode::Esc, now); + assert(ctrl.state().modal == cz::OverlayModal::None); + assert(spy->resume_calls == 1); +} + +void test_text_input_timelapse_custom_recovery_and_modal_renders() { + TempDir tmp("modals"); + const std::string cfg_path = tmp.path + "/config.json"; + const std::string out_dir = tmp.path + "/out"; + const std::string typed_dir = tmp.path + "/typed_out"; + assert(cz::mkdir_p(out_dir)); + + cz::AppConfig cfg; + cfg.output_dir = out_dir; + assert(cz::save_config(cfg, cfg_path)); + + // Create an orphaned timelapse work directory to exercise TimelapseRecovery + const cz::TimelapseSessionPaths orphan_paths = + cz::create_timelapse_session(out_dir, true); + { + cz::SimCameraBackend sim; + cz::CameraStreamSpec sp; + std::string err; + assert(sim.start(sp, err)); + const cz::StagedPaths f1 = + cz::next_timelapse_frame_paths(orphan_paths.work_dir, 1); + assert(sim.capture_still(f1.tmp_path, 320, 240).ok); + assert(cz::commit_staged_file(f1.tmp_path, f1.final_path, err)); + sim.stop(); + } + cz::TimelapseManifest m; + m.session_id = orphan_paths.session_id; + m.work_dir = orphan_paths.work_dir; + m.resolution = "2mp"; + m.interval_sec = 5; + m.fps = 24; + m.frame_count = 1; + m.status = "recording"; + assert(cz::write_timelapse_manifest(orphan_paths.manifest_path, m)); + + cz::UiControllerOptions opts; + opts.config_path = cfg_path; + opts.backlight_sysfs_root = tmp.path + "/no_backlight"; + + cz::UiController ctrl(std::make_unique(), opts); + uint64_t now = 1000; + assert(ctrl.init(now)); + + // Startup detects orphan and opens TimelapseRecovery modal + assert(ctrl.state().modal == cz::OverlayModal::TimelapseRecovery); + cz::AppView view; + cz::PreviewFrame live; + assert(ctrl.backend()->copy_latest_preview(0, live)); + view.render(ctrl.state(), &live, nullptr); + + // [K] Keep as Photos Folder -> moves to TL_/ and closes recovery modal + ctrl.handle_key('k', cz::KeyCode::Char, now); + assert(ctrl.state().modal == cz::OverlayModal::None); + assert(fs::is_directory(orphan_paths.photos_dir)); + assert(!fs::exists(orphan_paths.work_dir)); + + // Gallery drill-down into TL_/ and Backspace back to root + ctrl.handle_key('8', cz::KeyCode::Char, now); + assert(ctrl.state().modal == cz::OverlayModal::Gallery); + assert(ctrl.state().gallery_items.size() == 1); + assert(ctrl.state().gallery_items[0].type == cz::GalleryItemType::TimelapseFolder); + view.render(ctrl.state(), &live, ctrl.gallery_preview()); + ctrl.handle_key(0, cz::KeyCode::Enter, now); + assert(ctrl.state().gallery_in_session); + assert(ctrl.state().gallery_items.size() == 1); + view.render(ctrl.state(), &live, ctrl.gallery_preview()); + ctrl.handle_key(0, cz::KeyCode::Backspace, now); + assert(!ctrl.state().gallery_in_session); + ctrl.handle_key(0, cz::KeyCode::Esc, now); + assert(ctrl.state().modal == cz::OverlayModal::None); + + // TimelapseCustomInput [C] editing interval/fps/stop mode + ctrl.handle_key('3', cz::KeyCode::Char, now); + ctrl.handle_key('c', cz::KeyCode::Char, now); + assert(ctrl.state().modal == cz::OverlayModal::TimelapseCustomInput); + ctrl.handle_key('1', cz::KeyCode::Char, now); + ctrl.handle_key('2', cz::KeyCode::Char, now); + assert(ctrl.state().tl_custom_interval_sec == 12); + ctrl.handle_key(0, cz::KeyCode::Down, now); + ctrl.handle_key(0, cz::KeyCode::Right, now); // 24 -> 30 fps + assert(ctrl.state().tl_custom_fps == 30); + ctrl.handle_key(0, cz::KeyCode::Down, now); + ctrl.handle_key(0, cz::KeyCode::Right, now); // manual -> shots + assert(ctrl.state().tl_custom_stop_mode == "shots"); + view.render(ctrl.state(), &live, nullptr); + ctrl.handle_key(0, cz::KeyCode::Enter, now); + assert(ctrl.state().modal == cz::OverlayModal::None); + assert(ctrl.state().config.timelapse_interval_sec == 12); + assert(ctrl.state().config.timelapse_fps == 30); + assert(ctrl.state().config.timelapse_stop_mode == "shots"); + + // Settings -> DirPicker -> [T] TextInput manual directory entry + ctrl.handle_key('s', cz::KeyCode::Char, now); + ctrl.handle_key(0, cz::KeyCode::Enter, now); + assert(ctrl.state().modal == cz::OverlayModal::DirPicker); + view.render(ctrl.state(), &live, nullptr); + ctrl.handle_key('t', cz::KeyCode::Char, now); + assert(ctrl.state().modal == cz::OverlayModal::TextInput); + for (char c : typed_dir) { + ctrl.handle_key(c, cz::KeyCode::Char, now); + } + view.render(ctrl.state(), &live, nullptr); + ctrl.handle_key(0, cz::KeyCode::Enter, now); + assert(ctrl.state().modal == cz::OverlayModal::Settings); + assert(ctrl.state().effective_output_dir == typed_dir); + assert(fs::is_directory(typed_dir)); + ctrl.handle_key(0, cz::KeyCode::Esc, now); + + // Software black screen when dimmed without hardware backlight + cz::UiState dimmed_sw = ctrl.state(); + dimmed_sw.timelapse_dimmed = true; + dimmed_sw.has_hardware_backlight = false; + view.render(dimmed_sw, &live, nullptr); + const uint32_t* px = view.pixels(); + for (int i = 0; i < cz::AppView::kWidth * cz::AppView::kHeight; ++i) { + assert(px[i] == 0xff000000U); + } +} + +} // namespace + +int main() { + test_photo_controls_zoom_loupe_filters_and_timer(); + test_rail_side_and_theme_toggles_persist(); + test_video_mode_locks_transitions_while_recording(); + test_timelapse_dimmed_safe_wake(); + test_settings_dir_picker_camera_orient_and_gallery_delete(); + test_text_input_timelapse_custom_recovery_and_modal_renders(); + std::cout << "test_ui_controller: ALL PASSED\n"; + return 0; +}