#ifndef _GNU_SOURCE #define _GNU_SOURCE #endif /* Compiled idle cover IPC/renderer for nokia-beatles. No Python in the idle path. * * Behaviour contract for the 2720 Flip external panel: * - flip open: the panel is fully off (black frame and backlight 0); * - flip closed: the panel stays off until an external side button is pressed; * - BUTTON shows the clock, date and the compact network/battery indicators; * - the same Screen blank timeout as dwm (~/.config/sxmo/idle_blank_timeout, * default 300 s, 0 = never) blanks the cover again when no button arrives; * - all other events (network, SMS, battery, calls, theme) only update the * frame while the cover is visible, so an idle daemon stays at 0% CPU. * * The 2720's two GC9305 panels share one QUP5 SPI bus through a gpio13 mux. * Registering both panels in the DT darkens the main panel, so the shipping * DTB keeps one panel and this daemon drives the external panel from userspace * on /dev/spidev0.1 ONLY while the flip is closed (the main panel is blanked * and DPMS-off then). On open it restores the mux to the internal panel and * releases every GPIO/SPIDEV handle before Xorg can flush another frame. * If the opt-in two-panel DT is installed, /dev/fb1 takes precedence instead. */ #include #include #include #include #include #include #include #include /* The armv7 cross sysroot does not always ship linux/fb.h. These UAPI * values are stable; use the header when it exists, otherwise the numeric * definitions from linux/fb.h (FBIOBLANK = _IO('F', 0x11) = 0x4611). */ #if defined(__has_include) #if __has_include() #include #endif #endif #ifndef FBIOBLANK #define FBIOBLANK 0x4611 #endif #ifndef FB_BLANK_UNBLANK #define FB_BLANK_UNBLANK 0 #endif #ifndef FB_BLANK_POWERDOWN #define FB_BLANK_POWERDOWN 4 #endif #include "common.h" #define COVER_LOCK "/run/bananarchy-cover-idle.lock" #define DEFAULT_SOCKET "/run/bananarchy/cover.sock" #define DEFAULT_FB "/dev/fb1" #define MAIN_BLANK_CFG "/home/user/.config/sxmo/idle_blank_timeout" #define MAIN_NOIDLE_PATH "/home/user/.cache/sxmo/sxmo.noidle" #define DEFAULT_BLANK_SECS 300 #define HELPER_TIMEOUT_MS 2500 #define CLOCK_REDRAW_MS 30000 #define KERNEL_REDRAW_MS 1000 #define COVER_SPI_WIDTH 240 #define COVER_SPI_HEIGHT 240 #define COVER_SPI_CHUNK 2048 #define MAIN_DPMS_PATH "/sys/class/drm/card0-SPI-1/dpms" #define COVER_RUNTIME_CONF "/run/bananarchy/cover-runtime.conf" /* Self-contained linux/gpio.h (v1 ABI) and linux/spi/spidev.h UAPI values. * The armv7 cross sysroot does not always ship these headers. The layouts are * fixed by the kernel ABI; a compile-time size check guards the cross build. */ #define BA_GPIO_IOC_MAGIC 0xb4u #define BA_IOC_WR 1u #define BA_IOC_RD 2u #define BA_IOC_RDWR 3u #define BA_IOC(dir, type, nr, size) \ (((unsigned int)(dir) << 30) | ((unsigned int)(type) << 8) | \ ((unsigned int)(nr) << 0) | ((unsigned int)(size) << 16)) #define BA_SPI_IOC_MESSAGE(n) \ BA_IOC(BA_IOC_WR, 'k', 0u, (unsigned int)(n) * 32u) #define BA_SPI_IOC_WR_MODE BA_IOC(BA_IOC_WR, 'k', 1u, 1u) #define BA_SPI_IOC_WR_BITS BA_IOC(BA_IOC_WR, 'k', 3u, 1u) #define BA_SPI_IOC_WR_SPEED BA_IOC(BA_IOC_WR, 'k', 4u, 4u) #define BA_GPIO_GET_CHIPINFO BA_IOC(BA_IOC_RD, BA_GPIO_IOC_MAGIC, 1u, 68u) #define BA_GPIO_GET_LINEHANDLE BA_IOC(BA_IOC_RDWR, BA_GPIO_IOC_MAGIC, 3u, 364u) #define BA_GPIO_GET_VALUES BA_IOC(BA_IOC_RDWR, BA_GPIO_IOC_MAGIC, 8u, 64u) #define BA_GPIO_SET_VALUES BA_IOC(BA_IOC_RDWR, BA_GPIO_IOC_MAGIC, 9u, 64u) #define BA_GPIOHANDLE_REQUEST_OUTPUT (1u << 1) struct ba_gpiochip_info { char name[32]; char label[32]; uint32_t lines; }; struct ba_gpiohandle_request { uint32_t lineoffsets[64]; uint32_t flags; uint8_t default_values[64]; char consumer_label[32]; uint32_t lines; int32_t fd; }; struct ba_gpiohandle_data { uint8_t values[64]; }; struct ba_spi_ioc_transfer { uint64_t tx_buf; uint64_t rx_buf; uint32_t len; uint32_t speed_hz; uint16_t delay_usecs; uint8_t bits_per_word; uint8_t cs_change; uint8_t tx_nbits; uint8_t rx_nbits; uint8_t word_delay_usecs; uint8_t pad; }; _Static_assert(sizeof(struct ba_gpiochip_info) == 68, "gpiochip v1 chipinfo ABI size"); _Static_assert(sizeof(struct ba_gpiohandle_request) == 364, "gpiochip v1 linehandle ABI size"); _Static_assert(sizeof(struct ba_spi_ioc_transfer) == 32, "spidev transfer ABI size"); static char *const session_env[] = { (char *)"PATH=/home/user/.local/bin:/home/user/.config/sxmo/hooks:/usr/share/sxmo/default_hooks:/usr/local/bin:/usr/bin:/bin:/sbin:/usr/sbin", (char *)"HOME=/home/user", (char *)"USER=user", (char *)"DISPLAY=:0", (char *)"XDG_RUNTIME_DIR=/run/user/10000", (char *)"SHELL=/bin/sh", NULL }; struct cover_x11_swa { unsigned long background_pixmap; unsigned long background_pixel; unsigned long border_pixmap; unsigned long border_pixel; int bit_gravity; int win_gravity; int backing_store; unsigned long backing_planes; unsigned long backing_pixel; int save_under; long event_mask; long do_not_propagate_mask; int override_redirect; unsigned long colormap; unsigned long cursor; }; struct cover_x11 { void *lib; void *dpy; void *visual; void *gc; unsigned long win; unsigned long black; int screen; int depth; int mapped; int grabbed; int load_failed; void *(*open_display)(const char *); int (*close_display)(void *); int (*conn_number)(void *); int (*default_screen)(void *); unsigned long (*root_window)(void *, int); void *(*default_visual)(void *, int); int (*default_depth)(void *, int); void *(*default_gc)(void *, int); unsigned long (*black_pixel)(void *, int); unsigned long (*create_simple_window)(void *, unsigned long, int, int, unsigned int, unsigned int, unsigned int, unsigned long, unsigned long); int (*change_window_attr)(void *, unsigned long, unsigned long, struct cover_x11_swa *); int (*map_raised)(void *, unsigned long); int (*raise_window)(void *, unsigned long); int (*unmap_window)(void *, unsigned long); int (*destroy_window)(void *, unsigned long); int (*set_foreground)(void *, void *, unsigned long); int (*fill_rectangle)(void *, unsigned long, void *, int, int, unsigned int, unsigned int); void *(*create_image)(void *, void *, unsigned int, int, int, char *, unsigned int, unsigned int, int, int); int (*put_image)(void *, unsigned long, void *, void *, int, int, int, int, unsigned int, unsigned int); int (*xfree)(void *); int (*sync)(void *, int); int (*pending)(void *); int (*next_event)(void *, void *); int (*grab_keyboard)(void *, unsigned long, int, int, int, unsigned long); int (*ungrab_keyboard)(void *, unsigned long); void *(*set_error_handler)(int (*)(void *, void *)); }; struct cover_hw { char backend[16]; char spi_path[128]; char gpio_path[128]; char firmware[128]; char sim_path[128]; unsigned int mux_gpio; unsigned int dc_gpio; unsigned int reset_gpio; int mux_closed_level; int mux_open_level; int dc_command_level; int dc_data_level; int reset_assert_level; int reset_idle_level; unsigned int speed_hz; int word_bits; int panel_lines; int probe_index; char probe_desc[96]; char kernel_fb[128]; char kernel_dpms[128]; char kernel_sync[128]; char kernel_cmd[128]; char kernel_bl[128]; char kernel_bl_power[128]; char kernel_marker[128]; unsigned int kernel_bl_level; int kernel_bl_invert; int kernel_internal_sleep; int kernel_lit; int kernel_owned; int kernel_restored; int sim; int spi_enabled; int fd_spi; int fd_chip; int fd_mux; int fd_panel; int fd_sim; int mux_claimed; int claimed; int initialized; struct cover_x11 x11; }; /* Hardware sign-off cases for the external GC9305. The KaiOS downstream DTS * calls gpio21 "TE", not D/C, and Qualcomm MDSS SPI sends D/C as the ninth * bit, so both 8-bit (D/C on a GPIO) and 9-bit (D/C in bit 8) are plausible. * PROBE walks these while drawing TEST bars; the working case is written to * /etc/bananarchy/cover-display.conf afterwards. */ struct probe_case { int bits; int mux; int reset; int dc; unsigned int speed; }; static const struct probe_case probe_cases[] = { /* 9-bit first: the downstream DTS labels gpio21 TE and MDSS SPI carries * D/C in bit 8, so this is the best-supported wiring. */ {9, 1, 0, 0, 25000000}, {9, 1, 1, 0, 25000000}, {9, 0, 0, 0, 25000000}, {9, 0, 1, 0, 25000000}, {9, 1, 0, 0, 5000000}, {9, 0, 1, 0, 5000000}, {8, 1, 0, 0, 25000000}, {8, 1, 1, 0, 25000000}, {8, 1, 0, 1, 25000000}, {8, 1, 1, 1, 25000000}, {8, 0, 0, 0, 25000000}, {8, 1, 0, 0, 5000000}, }; struct glyph { char ch; unsigned char col[5]; }; static const struct glyph font[] = { {'A', {0x7e, 0x11, 0x11, 0x11, 0x7e}}, {'B', {0x7f, 0x49, 0x49, 0x49, 0x36}}, {'C', {0x3e, 0x41, 0x41, 0x41, 0x22}}, {'D', {0x7f, 0x41, 0x41, 0x22, 0x1c}}, {'E', {0x7f, 0x49, 0x49, 0x49, 0x41}}, {'F', {0x7f, 0x09, 0x09, 0x09, 0x01}}, {'G', {0x3e, 0x41, 0x49, 0x49, 0x7a}}, {'H', {0x7f, 0x08, 0x08, 0x08, 0x7f}}, {'I', {0x00, 0x41, 0x7f, 0x41, 0x00}}, {'J', {0x20, 0x40, 0x41, 0x3f, 0x01}}, {'K', {0x7f, 0x08, 0x14, 0x22, 0x41}}, {'L', {0x7f, 0x40, 0x40, 0x40, 0x40}}, {'M', {0x7f, 0x02, 0x0c, 0x02, 0x7f}}, {'N', {0x7f, 0x04, 0x08, 0x10, 0x7f}}, {'O', {0x3e, 0x41, 0x41, 0x41, 0x3e}}, {'P', {0x7f, 0x09, 0x09, 0x09, 0x06}}, {'Q', {0x3e, 0x41, 0x51, 0x21, 0x5e}}, {'R', {0x7f, 0x09, 0x19, 0x29, 0x46}}, {'S', {0x46, 0x49, 0x49, 0x49, 0x31}}, {'T', {0x01, 0x01, 0x7f, 0x01, 0x01}}, {'U', {0x3f, 0x40, 0x40, 0x40, 0x3f}}, {'V', {0x1f, 0x20, 0x40, 0x20, 0x1f}}, {'W', {0x3f, 0x40, 0x38, 0x40, 0x3f}}, {'X', {0x63, 0x14, 0x08, 0x14, 0x63}}, {'Y', {0x07, 0x08, 0x70, 0x08, 0x07}}, {'Z', {0x61, 0x51, 0x49, 0x45, 0x43}}, {'0', {0x3e, 0x51, 0x49, 0x45, 0x3e}}, {'1', {0x00, 0x42, 0x7f, 0x40, 0x00}}, {'2', {0x42, 0x61, 0x51, 0x49, 0x46}}, {'3', {0x21, 0x41, 0x45, 0x4b, 0x31}}, {'4', {0x18, 0x14, 0x12, 0x7f, 0x10}}, {'5', {0x27, 0x45, 0x45, 0x45, 0x39}}, {'6', {0x3c, 0x4a, 0x49, 0x49, 0x30}}, {'7', {0x01, 0x71, 0x09, 0x05, 0x03}}, {'8', {0x36, 0x49, 0x49, 0x49, 0x36}}, {'9', {0x06, 0x49, 0x49, 0x29, 0x1e}}, {':', {0x00, 0x36, 0x36, 0x00, 0x00}}, {'-', {0x08, 0x08, 0x08, 0x08, 0x08}}, {'.', {0x00, 0x60, 0x60, 0x00, 0x00}}, {'/', {0x20, 0x10, 0x08, 0x04, 0x02}}, {'%', {0x23, 0x13, 0x08, 0x64, 0x62}}, {'|', {0x00, 0x00, 0x7f, 0x00, 0x00}}, {'+', {0x08, 0x08, 0x3e, 0x08, 0x08}}, {'(', {0x00, 0x1c, 0x22, 0x41, 0x00}}, {')', {0x00, 0x41, 0x22, 0x1c, 0x00}}, {'*', {0x14, 0x08, 0x3e, 0x08, 0x14}}, {'#', {0x14, 0x7f, 0x14, 0x7f, 0x14}}, {',', {0x00, 0x50, 0x30, 0x00, 0x00}}, {'!', {0x00, 0x00, 0x5f, 0x00, 0x00}}, {'?', {0x02, 0x01, 0x51, 0x09, 0x06}}, {'_', {0x40, 0x40, 0x40, 0x40, 0x40}}, {'[', {0x00, 0x7f, 0x41, 0x41, 0x00}}, {']', {0x00, 0x41, 0x41, 0x7f, 0x00}}, {'\'', {0x00, 0x05, 0x03, 0x00, 0x00}}, {'@', {0x32, 0x49, 0x79, 0x41, 0x3e}}, {'$', {0x24, 0x2a, 0x7f, 0x2a, 0x12}}, {'&', {0x36, 0x49, 0x55, 0x22, 0x50}}, {'=', {0x14, 0x14, 0x14, 0x14, 0x14}}, {'"', {0x00, 0x07, 0x00, 0x07, 0x00}}, {';', {0x00, 0x56, 0x36, 0x00, 0x00}}, {'<', {0x08, 0x14, 0x22, 0x41, 0x00}}, {'>', {0x00, 0x41, 0x22, 0x14, 0x08}}, {'~', {0x08, 0x04, 0x08, 0x10, 0x08}}, {'^', {0x04, 0x02, 0x01, 0x02, 0x04}}, {'`', {0x00, 0x01, 0x02, 0x04, 0x00}}, {'\\', {0x02, 0x04, 0x08, 0x10, 0x20}}, {'{', {0x00, 0x08, 0x36, 0x41, 0x00}}, {'}', {0x00, 0x41, 0x36, 0x08, 0x00}}, {' ', {0x00, 0x00, 0x00, 0x00, 0x00}}, }; static uint32_t rgb888(unsigned int r, unsigned int g, unsigned int b) { return ((uint32_t)(r & 0xff) << 16) | ((uint32_t)(g & 0xff) << 8) | (uint32_t)(b & 0xff); } static uint16_t rgb565_from_rgb888(uint32_t color) { unsigned int r = (color >> 16) & 0xff; unsigned int g = (color >> 8) & 0xff; unsigned int b = color & 0xff; return (uint16_t)(((r >> 3) << 11) | ((g >> 2) << 5) | (b >> 3)); } struct frame { unsigned char *pixels; unsigned int width; unsigned int height; unsigned int stride; unsigned int bpp; }; static void frame_pixel(struct frame *fb, int x, int y, uint32_t color) { size_t offset; if(x < 0 || y < 0 || (unsigned int)x >= fb->width || (unsigned int)y >= fb->height) return; offset = (size_t)y * fb->stride + (size_t)x * (fb->bpp / 8); if(fb->bpp == 32) { memcpy(fb->pixels + offset, &color, 4); } else { uint16_t pixel = rgb565_from_rgb888(color); memcpy(fb->pixels + offset, &pixel, 2); } } static void frame_rect(struct frame *fb, int x0, int y0, int x1, int y1, uint32_t color) { int x; int y; for(y = y0; y < y1; y++) for(x = x0; x < x1; x++) frame_pixel(fb, x, y, color); } static const unsigned char *glyph_for(char ch) { size_t i; ch = (char)toupper((unsigned char)ch); for(i = 0; i < sizeof(font) / sizeof(font[0]); i++) { if(font[i].ch == ch) return font[i].col; } return font[sizeof(font) / sizeof(font[0]) - 1].col; } static void frame_text(struct frame *fb, const char *text, int x, int y, int scale, uint32_t color) { while(*text) { const unsigned char *cols = glyph_for(*text++); int cx; int cy; for(cx = 0; cx < 5; cx++) { for(cy = 0; cy < 7; cy++) { if(cols[cx] & (1u << cy)) { frame_rect(fb, x + cx * scale, y + cy * scale, x + (cx + 1) * scale, y + (cy + 1) * scale, color); } } } x += 6 * scale; } } static void frame_text_bounds(const char *text, int scale, int *ink_offset, int *ink_width) { int first = -1; int last = -1; int cursor = 0; if(!text || scale <= 0) { *ink_offset = 0; *ink_width = 0; return; } while(*text) { const unsigned char *cols = glyph_for(*text++); int cx; for(cx = 0; cx < 5; cx++) { if(cols[cx]) { int col = cursor + cx; if(first < 0) first = col; last = col; } } cursor += 6; } if(first < 0) { *ink_offset = 0; *ink_width = 0; return; } *ink_offset = first * scale; *ink_width = (last - first + 1) * scale; } static void frame_text_centered(struct frame *fb, const char *text, int y, int scale, uint32_t color) { int offset = 0; int width = 0; int x; frame_text_bounds(text, scale, &offset, &width); if(width <= 0) return; x = ((int)fb->width - width) / 2 - offset; frame_text(fb, text, x, y, scale, color); } /* Transliterate basic Cyrillic UTF-8 and sanitize caller labels to 5x7 ASCII. */ static void sanitize_cover_text(const char *src, char *dst, size_t dstlen) { static const char *const cyr_map[32] = { "A", "B", "V", "G", "D", "E", "ZH", "Z", "I", "Y", "K", "L", "M", "N", "O", "P", "R", "S", "T", "U", "F", "KH", "TS", "CH", "SH", "SHCH", "", "Y", "", "E", "YU", "YA" }; const unsigned char *p = (const unsigned char *)(src ? src : ""); size_t out = 0; if(!dst || dstlen == 0) return; while(*p && out + 1 < dstlen) { unsigned char b = *p; if(b < 0x80) { char ch = (b >= 0x20 && b < 0x7f) ? (char)toupper(b) : ' '; if(ch == ' ' && (out == 0 || dst[out - 1] == ' ')) { p++; continue; } dst[out++] = ch; p++; continue; } if((b == 0xd0 || b == 0xd1 || b == 0xd2) && p[1] >= 0x80 && p[1] <= 0xbf) { unsigned char b2 = p[1]; const char *rep = NULL; if(b == 0xd0 && b2 == 0x81) rep = "YO"; else if(b == 0xd1 && b2 == 0x91) rep = "YO"; else if((b == 0xd0 && b2 == 0x84) || (b == 0xd1 && b2 == 0x94)) rep = "YE"; else if((b == 0xd0 && b2 == 0x86) || (b == 0xd1 && b2 == 0x96)) rep = "I"; else if((b == 0xd0 && b2 == 0x87) || (b == 0xd1 && b2 == 0x97)) rep = "YI"; else if(b == 0xd2 && (b2 == 0x90 || b2 == 0x91)) rep = "G"; else if(b == 0xd0 && b2 >= 0x90 && b2 <= 0xbf) rep = cyr_map[(b2 - 0x90) % 32]; else if(b == 0xd1 && b2 >= 0x80 && b2 <= 0x8f) rep = cyr_map[(b2 - 0x80 + 16) % 32]; if(rep) { while(*rep && out + 1 < dstlen) dst[out++] = *rep++; } p += 2; continue; } p++; while((*p & 0xc0) == 0x80) p++; } while(out > 0 && dst[out - 1] == ' ') out--; dst[out] = '\0'; } static void draw_fit_centered(struct frame *fb, const char *text, int y, int pref_scale, uint32_t color) { char buf[64]; int max_chars; int scale = pref_scale; size_t len; if(!text || !*text) return; sanitize_cover_text(text, buf, sizeof(buf)); if(!buf[0]) return; len = strlen(buf); max_chars = ((int)fb->width - 8) / (6 * scale); if(max_chars < 1) max_chars = 1; if((int)len > max_chars && scale > 1) { scale = 1; max_chars = ((int)fb->width - 8) / 6; } if((int)len > max_chars) buf[max_chars] = '\0'; frame_text_centered(fb, buf, y, scale, color); } static void draw_wrapped_centered(struct frame *fb, const char *text, int area_top, int area_bottom, int pref_scale, uint32_t color) { char clean[192]; char lines[6][48]; int scale = pref_scale > 0 ? pref_scale : 2; int max_lines; int line_count = 0; int i; if(!text || !*text) return; sanitize_cover_text(text, clean, sizeof(clean)); if(!clean[0]) return; for(;; scale = 1) { int max_chars = ((int)fb->width - 16) / (6 * scale); int row_h = 7 * scale + (scale > 1 ? 8 : 5); const char *p = clean; if(max_chars < 1) max_chars = 1; if(max_chars >= (int)sizeof(lines[0])) max_chars = (int)sizeof(lines[0]) - 1; max_lines = (area_bottom - area_top) / row_h; if(max_lines < 1) max_lines = 1; if(max_lines > 6) max_lines = 6; line_count = 0; while(*p && line_count < max_lines) { int rem = (int)strlen(p); int take = rem <= max_chars ? rem : max_chars; if(rem > max_chars) { int sp = -1; int k; for(k = take; k > 0; k--) { if(p[k] == ' ') { sp = k; break; } } if(sp > 0) take = sp; } memcpy(lines[line_count], p, (size_t)take); lines[line_count][take] = '\0'; while(take > 0 && lines[line_count][take - 1] == ' ') lines[line_count][--take] = '\0'; line_count++; p += take; while(*p == ' ') p++; } if(*p == '\0' || scale <= 1) break; } { int row_h = 7 * scale + (scale > 1 ? 8 : 5); int total_h = line_count * row_h - (scale > 1 ? 8 : 5); int start_y = area_top + ((area_bottom - area_top) - total_h) / 2; if(start_y < area_top) start_y = area_top; for(i = 0; i < line_count; i++) frame_text_centered(fb, lines[i], start_y + i * row_h, scale, color); } } static int read_uint_file(const char *path, unsigned int *value) { FILE *handle = fopen(path, "r"); if(!handle) return 0; if(fscanf(handle, "%u", value) != 1) { fclose(handle); return 0; } fclose(handle); return *value > 0; } static int fb_geometry(const char *fb_path, unsigned int *width, unsigned int *height, unsigned int *bpp, unsigned int *stride) { char sysfs[128]; int index = 0; FILE *handle; const char *p = strstr(fb_path, "fb"); unsigned int bytes_per_pixel; const char *sim = getenv("BANANARCHY_COVER_FB_GEOM"); if(sim && sscanf(sim, "%u,%u,%u", width, height, bpp) == 3 && *width > 0 && *height > 0 && (*bpp == 16 || *bpp == 32)) { *stride = *width * (*bpp / 8); return 1; } if(p) index = atoi(p + 2); snprintf(sysfs, sizeof(sysfs), "/sys/class/graphics/fb%d/virtual_size", index); handle = fopen(sysfs, "r"); if(!handle) return 0; if(fscanf(handle, "%u,%u", width, height) != 2) { fclose(handle); return 0; } fclose(handle); snprintf(sysfs, sizeof(sysfs), "/sys/class/graphics/fb%d/bits_per_pixel", index); if(!read_uint_file(sysfs, bpp)) *bpp = 16; if(*bpp != 16 && *bpp != 32) return 0; bytes_per_pixel = *bpp / 8; snprintf(sysfs, sizeof(sysfs), "/sys/class/graphics/fb%d/stride", index); if(!read_uint_file(sysfs, stride) || *stride < *width * bytes_per_pixel) *stride = *width * bytes_per_pixel; return *width > 0 && *height > 0; } static int write_all(int fd, const unsigned char *buffer, size_t length) { size_t written = 0; while(written < length) { ssize_t n = write(fd, buffer + written, length - written); if(n < 0) { if(errno == EINTR) continue; return 0; } if(n == 0) return 0; written += (size_t)n; } return 1; } static void write_cover_text(const char *path, const char *value) { int fd = open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); if(fd < 0) return; (void)!write(fd, value, strlen(value)); close(fd); } struct state { char lid[16]; char backend[16]; char call[64]; char call_num[64]; char call_name[64]; char call_sim[16]; char message[128]; char network[96]; int quagr_active; char quagr_msg[128]; char quagr_time[16]; int enabled; int battery; int sms; int test; int visible; long long last_input_ms; long long closed_since_ms; long long quagr_dismissed_ms; long long blank_ms; long long wake_blank_ms; int wake_capped; char blank_cfg[32]; char backlight_path[128]; int backlight_level; }; static int call_hold_awake(const struct state *state) { return strcmp(state->call, "incoming") == 0 || strcmp(state->call, "muted") == 0; } static int cover_hold_awake(const struct state *state) { return call_hold_awake(state) || state->quagr_active; } /* A lit cover needs a lit framebuffer, a lit backlight and an unblanked fbdev; * everything else is "fully off". TEST modes are diagnostic overrides. */ static int cover_is_lit(const struct state *state) { if(state->test == 4) return 0; if(state->test == 1 || state->test == 2 || state->test == 3) return 1; return state->enabled && state->visible && strcmp(state->lid, "closed") == 0; } /* Fully off means a black framebuffer, a zeroed backlight and an fbdev * FB_BLANK_POWERDOWN. An empty backlight_path is normal on hardware without * a separate cover backlight sysfs node; fbdev blanking still powers it down. */ static void set_backlight(const struct state *state, int on) { char value[32]; int fd; if(!state->backlight_path[0]) return; snprintf(value, sizeof(value), "%d", on ? state->backlight_level : 0); /* O_TRUNC matters for regular files (host tests and future sysfs shims): * a shorter "0" must not leave the tail of the previous "160" behind. */ fd = open(state->backlight_path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); if(fd < 0) return; (void)!write(fd, value, strlen(value)); close(fd); } static void render_frame(struct frame *fb, const struct state *state) { char clock[16]; char date[32]; char battery[32]; time_t now; struct tm tm; unsigned int width = fb->width; unsigned int height = fb->height; ba_refresh_tz(); now = time(NULL); localtime_r(&now, &tm); strftime(clock, sizeof(clock), "%H:%M", &tm); strftime(date, sizeof(date), "%d.%m.%Y", &tm); if(state->test == 2) { frame_rect(fb, 0, 0, (int)width / 4, (int)height, rgb888(250, 40, 40)); frame_rect(fb, (int)width / 4, 0, (int)width / 2, (int)height, rgb888(40, 230, 80)); frame_rect(fb, (int)width / 2, 0, (int)width * 3 / 4, (int)height, rgb888(60, 110, 250)); frame_rect(fb, (int)width * 3 / 4, 0, (int)width, (int)height, rgb888(245, 245, 245)); } else if(state->test == 3) { frame_rect(fb, 0, 0, (int)width, (int)height, rgb888(245, 245, 245)); } else if(!cover_is_lit(state)) { frame_rect(fb, 0, 0, (int)width, (int)height, rgb888(0, 0, 0)); } else if(call_hold_awake(state)) { int muted = strcmp(state->call, "muted") == 0; char subhdr[48]; char name_san[64]; char num_san[64]; uint32_t accent = muted ? rgb888(250, 210, 60) : rgb888(80, 220, 120); frame_rect(fb, 0, 0, (int)width, (int)height, rgb888(8, 12, 26)); frame_rect(fb, 0, 0, (int)width, 4, accent); frame_text_centered(fb, muted ? "RING MUTED" : "INCOMING CALL", 18, 2, accent); if(state->call_sim[0]) snprintf(subhdr, sizeof(subhdr), "%s %s", state->call_sim, clock); else snprintf(subhdr, sizeof(subhdr), "%s", clock); frame_text_centered(fb, subhdr, 44, 1, rgb888(140, 180, 240)); sanitize_cover_text(state->call_name, name_san, sizeof(name_san)); sanitize_cover_text(state->call_num, num_san, sizeof(num_san)); if(name_san[0] && num_san[0] && strcmp(name_san, num_san) != 0) { draw_fit_centered(fb, name_san, 78, 2, rgb888(245, 248, 255)); draw_fit_centered(fb, num_san, 112, 2, rgb888(160, 210, 250)); } else if(name_san[0]) { draw_fit_centered(fb, name_san, 96, 2, rgb888(245, 248, 255)); } else { if(!num_san[0]) safe_copy(num_san, sizeof(num_san), "UNKNOWN"); draw_fit_centered(fb, num_san, 96, 2, rgb888(245, 248, 255)); } if(state->battery >= 0) { snprintf(battery, sizeof(battery), "BAT %d%%", state->battery); frame_text_centered(fb, battery, (int)height - 52, 1, rgb888(250, 210, 60)); } frame_text_centered(fb, muted ? "RINGER MUTED" : "VOL: MUTE RING", (int)height - 34, 1, rgb888(250, 210, 60)); frame_text_centered(fb, "PWR: HANG UP", (int)height - 18, 1, rgb888(255, 110, 110)); } else if(state->quagr_active) { uint32_t accent = rgb888(0, 220, 245); frame_rect(fb, 0, 0, (int)width, (int)height, rgb888(8, 12, 26)); frame_rect(fb, 0, 0, (int)width, 4, accent); frame_text_centered(fb, "QUAGR PAGE", 16, 2, accent); frame_text_centered(fb, state->quagr_time[0] ? state->quagr_time : clock, 38, 1, rgb888(140, 180, 240)); draw_wrapped_centered(fb, state->quagr_msg, 58, (int)height - 48, 2, rgb888(245, 248, 255)); if(state->battery >= 0) { snprintf(battery, sizeof(battery), "BAT %d%%", state->battery); frame_text_centered(fb, battery, (int)height - 34, 1, rgb888(250, 210, 60)); } frame_text_centered(fb, "ANY KEY: DISMISS", (int)height - 18, 1, rgb888(250, 210, 60)); } else { int clock_scale = width >= 220 ? 5 : 3; int clock_h = 7 * clock_scale; int date_h = 7 * 2; int gap = 14; int block_y = ((int)height - (clock_h + gap + date_h)) / 2; frame_rect(fb, 0, 0, (int)width, (int)height, rgb888(8, 12, 26)); frame_rect(fb, 0, 0, (int)width, 3, rgb888(250, 210, 60)); frame_text_centered(fb, "BANANARCHY", 22, 2, rgb888(250, 210, 60)); frame_text_centered(fb, clock, block_y, clock_scale, rgb888(235, 240, 248)); frame_text_centered(fb, date, block_y + clock_h + gap, 2, rgb888(90, 150, 240)); /* Compact network / battery indicators, pushed by the event bridge. */ if(state->network[0]) frame_text_centered(fb, state->network, (int)height - 46, 1, rgb888(120, 230, 160)); if(state->battery >= 0) { snprintf(battery, sizeof(battery), "BAT %d%%", state->battery); frame_text_centered(fb, battery, (int)height - 30, 1, rgb888(250, 210, 60)); } if(state->message[0]) frame_text_centered(fb, state->message, (int)height - 14, 1, rgb888(235, 240, 248)); } } static int draw_frame(const char *fb_path, const struct state *state) { int fd = open(fb_path, O_RDWR | O_CLOEXEC); unsigned int width = 0; unsigned int height = 0; unsigned int bpp = 0; unsigned int stride = 0; size_t size; unsigned char *mem; struct frame fb; if(fd < 0) return 0; if(!fb_geometry(fb_path, &width, &height, &bpp, &stride)) { close(fd); return 0; } size = (size_t)stride * height; mem = calloc(1, size); if(!mem) { close(fd); return 0; } fb.pixels = mem; fb.width = width; fb.height = height; fb.stride = stride; fb.bpp = bpp; render_frame(&fb, state); if(lseek(fd, 0, SEEK_SET) < 0 || !write_all(fd, mem, size)) { free(mem); close(fd); return 0; } fsync(fd); /* DRM fbdev emulation turns FB_BLANK_POWERDOWN into a DPMS-off on the * external connector, so the cover is electrically dark as well as black. * Unblank before drawing a lit frame; blank after writing the black one. * Regular files (host tests / sim backends) simply ignore the ioctl. */ (void)ioctl(fd, FBIOBLANK, cover_is_lit(state) ? FB_BLANK_UNBLANK : FB_BLANK_POWERDOWN); free(mem); close(fd); return 1; } /* --- Closed-flip-only userspace GC9305 backend (/dev/spidev0.1) --------- */ static void hw_event(struct cover_hw *hw, const char *line) { if(hw->fd_sim < 0) return; (void)!write(hw->fd_sim, line, strlen(line)); (void)!write(hw->fd_sim, "\n", 1); } static int hw_gpio_set(struct cover_hw *hw, int fd, const unsigned char *values, unsigned int count) { struct ba_gpiohandle_data data; char line[64]; unsigned int i; snprintf(line, sizeof(line), "gpio"); for(i = 0; i < count; i++) snprintf(line + strlen(line), sizeof(line) - strlen(line), " %u", values[i]); hw_event(hw, line); if(hw->sim) return 1; memset(&data, 0, sizeof(data)); for(i = 0; i < count && i < sizeof(data.values); i++) data.values[i] = values[i]; return ioctl(fd, BA_GPIO_SET_VALUES, &data) >= 0; } static int hw_ensure_gpiochip(struct cover_hw *hw) { unsigned int min_lines; glob_t gl; size_t i; int best_fd = -1; char best_path[128] = ""; if(hw->sim || hw->fd_chip >= 0) return 1; min_lines = (hw->mux_gpio > hw->reset_gpio ? hw->mux_gpio : hw->reset_gpio) + 1; if(hw->word_bits != 9 && hw->dc_gpio < 1024 && hw->dc_gpio + 1 > min_lines) min_lines = hw->dc_gpio + 1; if(hw->gpio_path[0] && strcasecmp(hw->gpio_path, "auto") != 0) { int fd = open(hw->gpio_path, O_RDWR | O_CLOEXEC); if(fd >= 0) { struct ba_gpiochip_info info; memset(&info, 0, sizeof(info)); if(ioctl(fd, BA_GPIO_GET_CHIPINFO, &info) == 0) { info.label[sizeof(info.label) - 1] = '\0'; if(info.lines >= min_lines && (strstr(info.label, "pinctrl") != NULL || strstr(info.label, "tlmm") != NULL)) { hw->fd_chip = fd; return 1; } close(fd); } else if(errno == ENOTTY) { hw->fd_chip = fd; return 1; } else { close(fd); } } } if(glob("/dev/gpiochip*", 0, NULL, &gl) == 0) { for(i = 0; i < gl.gl_pathc; i++) { struct ba_gpiochip_info info; int fd = open(gl.gl_pathv[i], O_RDWR | O_CLOEXEC); if(fd < 0) continue; memset(&info, 0, sizeof(info)); if(ioctl(fd, BA_GPIO_GET_CHIPINFO, &info) == 0 && info.lines >= min_lines) { info.label[sizeof(info.label) - 1] = '\0'; if(strstr(info.label, "pinctrl") != NULL || strstr(info.label, "tlmm") != NULL) { if(best_fd >= 0) close(best_fd); best_fd = fd; safe_copy(best_path, sizeof(best_path), gl.gl_pathv[i]); fd = -1; break; } if(best_fd < 0) { best_fd = fd; safe_copy(best_path, sizeof(best_path), gl.gl_pathv[i]); fd = -1; } } if(fd >= 0) close(fd); } globfree(&gl); } if(best_fd >= 0) { hw->fd_chip = best_fd; safe_copy(hw->gpio_path, sizeof(hw->gpio_path), best_path); return 1; } return 0; } static int hw_gpio_request(struct cover_hw *hw, const unsigned int *offsets, const unsigned char *defaults, unsigned int count) { struct ba_gpiohandle_request req; unsigned int i; if(hw->sim) { hw_event(hw, "claim"); return 1; } if(!hw_ensure_gpiochip(hw)) return -1; memset(&req, 0, sizeof(req)); for(i = 0; i < count && i < 64; i++) { req.lineoffsets[i] = offsets[i]; req.default_values[i] = defaults[i]; } req.flags = BA_GPIOHANDLE_REQUEST_OUTPUT; snprintf(req.consumer_label, sizeof(req.consumer_label), "bananarchy-cover"); req.lines = count; req.fd = -1; if(ioctl(hw->fd_chip, BA_GPIO_GET_LINEHANDLE, &req) < 0) return -1; hw_event(hw, "claim"); return req.fd; } static int hw_xfer(struct cover_hw *hw, const unsigned char *tx, size_t len, int cs_change) { struct ba_spi_ioc_transfer tr; if(hw->sim) return 1; memset(&tr, 0, sizeof(tr)); tr.tx_buf = (uint64_t)(uintptr_t)tx; tr.len = (uint32_t)len; tr.bits_per_word = 8; tr.cs_change = (uint8_t)(cs_change ? 1 : 0); return ioctl(hw->fd_spi, BA_SPI_IOC_MESSAGE(1), &tr) >= 0; } static int hw_dc(struct cover_hw *hw, int level) { unsigned char values[2]; if(hw->word_bits == 9) return 1; values[0] = (unsigned char)level; values[1] = (unsigned char)hw->reset_idle_level; return hw_gpio_set(hw, hw->fd_panel, values, 2); } static int hw_reset_set(struct cover_hw *hw, int level) { unsigned char values[2]; if(hw->panel_lines == 1) { values[0] = (unsigned char)level; return hw_gpio_set(hw, hw->fd_panel, values, 1); } values[0] = (unsigned char)hw->dc_data_level; values[1] = (unsigned char)level; return hw_gpio_set(hw, hw->fd_panel, values, 2); } static int hw_command(struct cover_hw *hw, unsigned char cmd, const unsigned char *params, size_t n) { char line[64]; snprintf(line, sizeof(line), "cmd %02x %zu bits=%d", cmd, n, hw->word_bits); hw_event(hw, line); if(hw->sim) return 1; if(hw->word_bits == 9) { /* MIPI DBI Type C: D/C is bit 8 of each little-endian 9-bit word. */ unsigned char buf[64]; size_t used = 0; size_t i; if((n + 1) * 2 > sizeof(buf)) return 0; buf[used++] = cmd; buf[used++] = 0; for(i = 0; i < n; i++) { buf[used++] = params[i]; buf[used++] = 1; } return hw_xfer(hw, buf, used, 1); } if(!hw_dc(hw, hw->dc_command_level)) return 0; if(!hw_xfer(hw, &cmd, 1, n ? 0 : 1)) return 0; if(!n) return 1; if(!hw_dc(hw, hw->dc_data_level)) return 0; while(n) { size_t chunk = n > COVER_SPI_CHUNK ? COVER_SPI_CHUNK : n; if(!hw_xfer(hw, params, chunk, chunk == n)) return 0; params += chunk; n -= chunk; } return 1; } static int hw_init_panel(struct cover_hw *hw) { unsigned char blob[4096]; unsigned char blank[2] = {0, 0}; size_t len = 0; size_t p; ssize_t got; int fd = open(hw->firmware, O_RDONLY | O_CLOEXEC); if(fd < 0) return 0; got = read(fd, blob, sizeof(blob)); close(fd); if(got < 17) return 0; len = (size_t)got; if(memcmp(blob, "MIPI DBI", 8) != 0) return 0; p = 16; while(p + 2 <= len) { unsigned char cmd = blob[p]; size_t n = blob[p + 1]; p += 2; if(p + n > len) break; if(cmd == 0x00 && n == 1) { /* Vendor "delay ms" record. Host simulation skips the wait. */ if(!hw->sim) poll(NULL, 0, (int)blob[p] > 0 ? (int)blob[p] : 1); } else if(cmd == 0x2c && n == 0) { /* Memory-write marker: every command gets its own CS framing, so a * bare 0x2c is not part of the init sequence. */ hw_event(hw, "skip 2c"); } else { hw_command(hw, cmd, n ? blob + p : blank, n); } p += n; } return 1; } static int hw_activate(struct cover_hw *hw) { unsigned int mux_offset[1]; unsigned int panel_offsets[2]; unsigned char mux_default[1]; unsigned char panel_default[2]; int fd; if(!hw->spi_enabled) return 0; if(!hw_ensure_gpiochip(hw)) return 0; if(!hw->mux_claimed) { mux_offset[0] = hw->mux_gpio; mux_default[0] = (unsigned char)hw->mux_open_level; fd = hw_gpio_request(hw, mux_offset, mux_default, 1); if(fd < 0) return 0; hw->fd_mux = fd; hw->mux_claimed = 1; } { unsigned char mux_value[1]; mux_value[0] = (unsigned char)hw->mux_closed_level; hw_gpio_set(hw, hw->fd_mux, mux_value, 1); } if(!hw->claimed) { hw->panel_lines = hw->word_bits == 9 ? 1 : 2; if(hw->panel_lines == 1) { panel_offsets[0] = hw->reset_gpio; panel_default[0] = (unsigned char)hw->reset_idle_level; } else { panel_offsets[0] = hw->dc_gpio; panel_offsets[1] = hw->reset_gpio; panel_default[0] = (unsigned char)hw->dc_data_level; panel_default[1] = (unsigned char)hw->reset_idle_level; } fd = hw_gpio_request(hw, panel_offsets, panel_default, (unsigned int)hw->panel_lines); if(fd < 0) return 0; hw->fd_panel = fd; hw->claimed = 1; hw->initialized = 0; if(hw->fd_spi < 0 && !hw->sim) { unsigned char mode = 0; unsigned char bits = 8; uint32_t speed = hw->speed_hz; hw->fd_spi = open(hw->spi_path, O_RDWR | O_CLOEXEC); if(hw->fd_spi < 0) return 0; bits = (unsigned char)hw->word_bits; if(ioctl(hw->fd_spi, BA_SPI_IOC_WR_MODE, &mode) < 0 || ioctl(hw->fd_spi, BA_SPI_IOC_WR_BITS, &bits) < 0 || ioctl(hw->fd_spi, BA_SPI_IOC_WR_SPEED, &speed) < 0) return 0; } } if(!hw->initialized) { /* Reset pulse on the external panel, then replay its firmware stream. */ hw_reset_set(hw, hw->reset_assert_level); if(!hw->sim) poll(NULL, 0, 20); hw_reset_set(hw, hw->reset_idle_level); if(!hw->sim) poll(NULL, 0, 150); if(!hw_init_panel(hw)) return 0; hw->initialized = 1; } return 1; } static int hw_frame(struct cover_hw *hw, const struct frame *fb, int lit) { unsigned char cmd = 0x2c; size_t size = (size_t)fb->stride * fb->height; size_t left = size; const unsigned char *pixels = fb->pixels; char line[96]; snprintf(line, sizeof(line), "frame lit=%d size=%zu", lit, size); hw_event(hw, line); if(hw->sim) return 1; if(hw->word_bits == 9) { unsigned char start[2]; unsigned char *words; size_t i; size_t left; const unsigned char *p; start[0] = 0x2c; start[1] = 0; if(!hw_xfer(hw, start, 2, 0)) return 0; words = malloc(size * 2); if(!words) return 0; for(i = 0; i < size; i++) { words[i * 2] = fb->pixels[i]; words[i * 2 + 1] = 1; } p = words; left = size * 2; while(left) { size_t chunk = left > COVER_SPI_CHUNK ? COVER_SPI_CHUNK : left; if(!hw_xfer(hw, p, chunk, chunk == left)) { free(words); return 0; } p += chunk; left -= chunk; } free(words); return 1; } if(!hw_dc(hw, hw->dc_command_level)) return 0; if(!hw_xfer(hw, &cmd, 1, 0)) return 0; if(!hw_dc(hw, hw->dc_data_level)) return 0; while(left) { size_t chunk = left > COVER_SPI_CHUNK ? COVER_SPI_CHUNK : left; if(!hw_xfer(hw, pixels, chunk, chunk == left)) return 0; pixels += chunk; left -= chunk; } return 1; } static int cover_spi_draw(struct cover_hw *hw, const struct state *state) { size_t size = COVER_SPI_WIDTH * COVER_SPI_HEIGHT * 2; unsigned char *mem; struct frame fb; int lit = cover_is_lit(state); if(!hw_activate(hw)) return 0; mem = calloc(1, size); if(!mem) return 0; fb.pixels = mem; fb.width = COVER_SPI_WIDTH; fb.height = COVER_SPI_HEIGHT; fb.stride = COVER_SPI_WIDTH * 2; fb.bpp = 16; render_frame(&fb, state); if(lit) hw_command(hw, 0x29, NULL, 0); if(!hw_frame(hw, &fb, lit)) { free(mem); return 0; } if(!lit) hw_command(hw, 0x28, NULL, 0); free(mem); return 1; } static void cover_kernel_release(struct cover_hw *hw, int open); /* On an open flip the daemon must not own the shared QUP5 bus at all. The * mux line stays claimed for the daemon's lifetime (so it is always driven * back to the internal panel), while the DC/reset handle is released. */ static void cover_hw_release(struct cover_hw *hw) { unsigned char mux_value[1]; if(hw->kernel_owned) { cover_kernel_release(hw, 0); return; } if(!hw->mux_claimed) return; if(hw->initialized) hw_command(hw, 0x28, NULL, 0); mux_value[0] = (unsigned char)hw->mux_open_level; hw_gpio_set(hw, hw->fd_mux, mux_value, 1); hw_event(hw, "release"); if(hw->claimed && !hw->sim) close(hw->fd_panel); hw->fd_panel = -1; hw->claimed = 0; hw->initialized = 0; } static int cover_x11_ignore_error(void *dpy, void *err) { (void)dpy; (void)err; return 0; } static void cover_x11_drop(struct cover_hw *hw) { hw->x11.dpy = NULL; hw->x11.visual = NULL; hw->x11.gc = NULL; hw->x11.win = 0; hw->x11.mapped = 0; hw->x11.grabbed = 0; } static int cover_x11_ensure(struct cover_hw *hw) { struct cover_x11 *x = &hw->x11; struct cover_x11_swa swa; unsigned long root; if(hw->sim || x->load_failed) return 0; if(!x->lib) { x->lib = dlopen("libX11.so.6", RTLD_LAZY | RTLD_LOCAL); if(!x->lib) { x->load_failed = 1; return 0; } *(void **)(&x->open_display) = dlsym(x->lib, "XOpenDisplay"); *(void **)(&x->close_display) = dlsym(x->lib, "XCloseDisplay"); *(void **)(&x->conn_number) = dlsym(x->lib, "XConnectionNumber"); *(void **)(&x->default_screen) = dlsym(x->lib, "XDefaultScreen"); *(void **)(&x->root_window) = dlsym(x->lib, "XRootWindow"); *(void **)(&x->default_visual) = dlsym(x->lib, "XDefaultVisual"); *(void **)(&x->default_depth) = dlsym(x->lib, "XDefaultDepth"); *(void **)(&x->default_gc) = dlsym(x->lib, "XDefaultGC"); *(void **)(&x->black_pixel) = dlsym(x->lib, "XBlackPixel"); *(void **)(&x->create_simple_window) = dlsym(x->lib, "XCreateSimpleWindow"); *(void **)(&x->change_window_attr) = dlsym(x->lib, "XChangeWindowAttributes"); *(void **)(&x->map_raised) = dlsym(x->lib, "XMapRaised"); *(void **)(&x->raise_window) = dlsym(x->lib, "XRaiseWindow"); *(void **)(&x->unmap_window) = dlsym(x->lib, "XUnmapWindow"); *(void **)(&x->destroy_window) = dlsym(x->lib, "XDestroyWindow"); *(void **)(&x->set_foreground) = dlsym(x->lib, "XSetForeground"); *(void **)(&x->fill_rectangle) = dlsym(x->lib, "XFillRectangle"); *(void **)(&x->create_image) = dlsym(x->lib, "XCreateImage"); *(void **)(&x->put_image) = dlsym(x->lib, "XPutImage"); *(void **)(&x->xfree) = dlsym(x->lib, "XFree"); *(void **)(&x->sync) = dlsym(x->lib, "XSync"); *(void **)(&x->pending) = dlsym(x->lib, "XPending"); *(void **)(&x->next_event) = dlsym(x->lib, "XNextEvent"); *(void **)(&x->grab_keyboard) = dlsym(x->lib, "XGrabKeyboard"); *(void **)(&x->ungrab_keyboard) = dlsym(x->lib, "XUngrabKeyboard"); *(void **)(&x->set_error_handler) = dlsym(x->lib, "XSetErrorHandler"); if(!x->open_display || !x->close_display || !x->conn_number || !x->default_screen || !x->root_window || !x->default_visual || !x->default_depth || !x->default_gc || !x->black_pixel || !x->create_simple_window || !x->change_window_attr || !x->map_raised || !x->raise_window || !x->unmap_window || !x->destroy_window || !x->set_foreground || !x->fill_rectangle || !x->create_image || !x->put_image || !x->xfree || !x->sync || !x->pending || !x->next_event || !x->grab_keyboard || !x->ungrab_keyboard || !x->set_error_handler) { x->load_failed = 1; return 0; } x->set_error_handler(cover_x11_ignore_error); } if(!x->dpy) { x->dpy = x->open_display(":0"); if(!x->dpy) return 0; x->screen = x->default_screen(x->dpy); root = x->root_window(x->dpy, x->screen); x->visual = x->default_visual(x->dpy, x->screen); x->depth = x->default_depth(x->dpy, x->screen); x->gc = x->default_gc(x->dpy, x->screen); x->black = x->black_pixel(x->dpy, x->screen); x->win = x->create_simple_window(x->dpy, root, 0, 0, 240, 320, 0, x->black, x->black); memset(&swa, 0, sizeof(swa)); swa.background_pixel = x->black; swa.override_redirect = 1; swa.event_mask = (1L << 15) | (1L << 0) | (1L << 1); x->change_window_attr(x->dpy, x->win, (1UL << 1) | (1UL << 9) | (1UL << 11), &swa); x->mapped = 0; x->grabbed = 0; } return 1; } static void cover_x11_drain(struct cover_hw *hw) { struct cover_x11 *x = &hw->x11; long ev[64]; if(!x->dpy) return; while(x->pending(x->dpy) > 0) x->next_event(x->dpy, ev); } static void cover_x11_grab(struct cover_hw *hw) { struct cover_x11 *x = &hw->x11; if(!x->dpy || !x->mapped) return; if(!x->grabbed) { if(x->grab_keyboard(x->dpy, x->win, 1, 1, 1, 0UL) == 0) x->grabbed = 1; x->sync(x->dpy, 0); } cover_x11_drain(hw); } static int cover_x11_show_black(struct cover_hw *hw) { struct cover_x11 *x = &hw->x11; if(!cover_x11_ensure(hw)) return 0; if(!x->mapped) { x->map_raised(x->dpy, x->win); x->mapped = 1; } else { x->raise_window(x->dpy, x->win); } x->set_foreground(x->dpy, x->gc, x->black); x->fill_rectangle(x->dpy, x->win, x->gc, 0, 0, 240, 320); x->sync(x->dpy, 0); cover_x11_grab(hw); return 1; } static int cover_x11_present(struct cover_hw *hw, unsigned char *pixels, unsigned int width, unsigned int height, unsigned int stride) { struct cover_x11 *x = &hw->x11; void *img; if(!cover_x11_ensure(hw)) return 0; if(!x->mapped) { x->map_raised(x->dpy, x->win); x->set_foreground(x->dpy, x->gc, x->black); x->fill_rectangle(x->dpy, x->win, x->gc, 0, 0, 240, 320); x->mapped = 1; } else { x->raise_window(x->dpy, x->win); x->set_foreground(x->dpy, x->gc, x->black); x->fill_rectangle(x->dpy, x->win, x->gc, 0, 240, 240, 80); } img = x->create_image(x->dpy, x->visual, (unsigned int)x->depth, 2, 0, (char *)pixels, width, height, 32, (int)stride); if(img) { x->put_image(x->dpy, x->win, x->gc, img, 0, 0, 0, 0, width, height); x->xfree(img); } x->sync(x->dpy, 0); cover_x11_grab(hw); return 1; } static void cover_x11_hide(struct cover_hw *hw) { struct cover_x11 *x = &hw->x11; if(!x->dpy) return; if(x->grabbed) { x->ungrab_keyboard(x->dpy, 0UL); x->grabbed = 0; } if(x->mapped) { x->unmap_window(x->dpy, x->win); x->mapped = 0; } x->sync(x->dpy, 0); cover_x11_drain(hw); } static void cover_x11_close(struct cover_hw *hw) { struct cover_x11 *x = &hw->x11; if(x->dpy) { cover_x11_hide(hw); if(x->win) x->destroy_window(x->dpy, x->win); x->close_display(x->dpy); } cover_x11_drop(hw); } static void cover_hw_shutdown(struct cover_hw *hw) { cover_x11_close(hw); cover_hw_release(hw); cover_kernel_release(hw, 0); if(!hw->sim) { if(hw->fd_mux >= 0) close(hw->fd_mux); if(hw->fd_spi >= 0) close(hw->fd_spi); if(hw->fd_chip >= 0) close(hw->fd_chip); } hw->fd_mux = -1; hw->fd_spi = -1; hw->fd_chip = -1; if(hw->fd_sim >= 0) { hw_event(hw, "close"); close(hw->fd_sim); hw->fd_sim = -1; } hw->mux_claimed = 0; } /* The cover may only own QUP5 while the main panel is DPMS-off. This is the * real closed-flip state and also rejects a transient lid-state flap at lid * daemon startup, when Xorg is still flushing frames to the internal panel. */ static int cover_main_panel_is_off(void) { const char *path = getenv("BANANARCHY_COVER_DPMS_PATH"); char buf[16]; ssize_t got; int fd; if(!path || !*path) path = MAIN_DPMS_PATH; fd = open(path, O_RDONLY | O_CLOEXEC); if(fd < 0) return 1; got = read(fd, buf, sizeof(buf) - 1); close(fd); if(got <= 0) return 1; buf[got] = '\0'; return strncmp(buf, "Off", 3) == 0; } /* --- Kernel-owned cover path ---------------------------------------------- * The KaiOS 3.10 DTS shows that both GC9305s share CS0, gpio110 D/C and one * PMIC MPP2 PWM backlight; gpio13 selects the panel, gpio23 is the external * reset and gpio21 is TE. Live probing showed the cover backlight is * active-low: duty 0 lights it, while duty 14 is the OFF level. The internal * panel uses the opposite polarity and needs duty 14 to light. * * Therefore the dark closed state must NOT park the mux on the cover: it * parks gpio13 low (internal), disables the PWM with bl_power=4 and sends * display-off/sleep-in to both controllers. Only a real BUTTON/WAKE selects * the cover, re-inits the external GC9305 and enables duty 0. */ static void cover_kernel_release(struct cover_hw *hw, int open); /* Run DPMS and power-sync helpers synchronously as the daemon's own UID * (root on target) so xset/sysfs/marker transitions never race gpio13 mux * switches or fail to write /run/bananarchy guard files. */ static void cover_run_helper(char *const argv[], int timeout_ms) { long long deadline = now_ms() + timeout_ms; pid_t pid = fork(); if(pid < 0) return; if(pid == 0) { int nullfd = open("/dev/null", O_RDWR); if(nullfd >= 0) { dup2(nullfd, STDIN_FILENO); dup2(nullfd, STDOUT_FILENO); dup2(nullfd, STDERR_FILENO); if(nullfd > STDERR_FILENO) close(nullfd); } execve(argv[0], argv, (char *const *)session_env); _exit(127); } while(1) { pid_t got = waitpid(pid, NULL, WNOHANG); if(got == pid || (got < 0 && errno == ECHILD)) return; if(now_ms() >= deadline) { kill(pid, SIGKILL); poll(NULL, 0, 10); (void)waitpid(pid, NULL, WNOHANG); return; } poll(NULL, 0, 10); } } static void hw_dpms(struct cover_hw *hw, const char *mode) { char line[64]; if(hw->sim) { snprintf(line, sizeof(line), "dpms %s", mode); hw_event(hw, line); return; } if(!hw->kernel_dpms[0]) return; { char *const argv[] = { hw->kernel_dpms, (char *)mode, NULL }; cover_run_helper(argv, HELPER_TIMEOUT_MS); } } static void cover_kernel_power_sync(struct cover_hw *hw) { char line[64]; if(hw->sim) { snprintf(line, sizeof(line), "kernel power sync"); hw_event(hw, line); return; } if(!hw->kernel_sync[0]) return; { char *const argv[] = { hw->kernel_sync, (char *)"force", NULL }; cover_run_helper(argv, HELPER_TIMEOUT_MS); } } static int cover_text_equals(const char *path, const char *value) { char buf[64]; ssize_t got; size_t len; int fd = open(path, O_RDONLY | O_CLOEXEC); if(fd < 0) return 0; got = read(fd, buf, sizeof(buf) - 1); close(fd); if(got <= 0) return 0; buf[got] = '\0'; while(got > 0 && (buf[got - 1] == '\n' || buf[got - 1] == '\r' || buf[got - 1] == ' ')) buf[--got] = '\0'; len = strlen(value); return strlen(buf) == len && memcmp(buf, value, len) == 0; } static void write_cover_text_once(const char *path, const char *value) { if(!cover_text_equals(path, value)) write_cover_text(path, value); } static int cover_kernel_command(struct cover_hw *hw, unsigned char cmd, const unsigned char *params, unsigned int count) { char line[256]; char event[320]; size_t used; unsigned int i; int flags = O_WRONLY | O_CLOEXEC; int fd; used = (size_t)snprintf(line, sizeof(line), "%02x", cmd); for(i = 0; i < count && used + 4 < sizeof(line); i++) used += (size_t)snprintf(line + used, sizeof(line) - used, " %02x", params[i]); snprintf(event, sizeof(event), "kernel cmd %s", line); hw_event(hw, event); if(hw->sim) flags |= O_TRUNC; fd = open(hw->kernel_cmd, flags); if(fd < 0) return hw->sim; if(!write_all(fd, (const unsigned char *)line, strlen(line))) { close(fd); return 0; } close(fd); return 1; } static int cover_kernel_replay_firmware(struct cover_hw *hw) { unsigned char buf[256]; size_t len; size_t i = 16; FILE *handle = fopen(hw->firmware, "rb"); if(!handle) return 0; len = fread(buf, 1, sizeof(buf), handle); fclose(handle); if(len < 18 || memcmp(buf, "MIPI DBI", 8) != 0 || buf[15] != 1) return 0; while(i + 1 < len) { unsigned char cmd = buf[i++]; unsigned char count = buf[i++]; if(i + count > len) return 0; if(cmd == 0x00 && count == 1) { char line[64]; snprintf(line, sizeof(line), "kernel delay %u", (unsigned int)buf[i]); hw_event(hw, line); if(!hw->sim) poll(NULL, 0, (int)buf[i]); } else if(!cover_kernel_command(hw, cmd, buf + i, count)) { return 0; } i += count; } return i == len; } static void cover_kernel_reset(struct cover_hw *hw) { unsigned char values[2]; values[0] = (unsigned char)hw->mux_closed_level; values[1] = (unsigned char)hw->reset_idle_level; hw_gpio_set(hw, hw->fd_mux, values, 2); if(!hw->sim) poll(NULL, 0, 1); values[1] = (unsigned char)hw->reset_assert_level; hw_gpio_set(hw, hw->fd_mux, values, 2); if(!hw->sim) poll(NULL, 0, 10); values[1] = (unsigned char)hw->reset_idle_level; hw_gpio_set(hw, hw->fd_mux, values, 2); if(!hw->sim) poll(NULL, 0, 10); hw_event(hw, "kernel reset"); } static int cover_kernel_mux(struct cover_hw *hw, int closed) { unsigned char values[2]; values[0] = (unsigned char)(closed ? hw->mux_closed_level : hw->mux_open_level); values[1] = (unsigned char)hw->reset_idle_level; return hw_gpio_set(hw, hw->fd_mux, values, 2); } static void cover_kernel_display_off(struct cover_hw *hw, int external, int delay_ms) { cover_kernel_mux(hw, external); cover_kernel_command(hw, 0x28, NULL, 0); if(!hw->sim && delay_ms > 0) poll(NULL, 0, delay_ms); cover_kernel_command(hw, 0x10, NULL, 0); } static void cover_kernel_clear_fb(struct cover_hw *hw) { unsigned int width = COVER_SPI_WIDTH; unsigned int height = 320; unsigned int bpp = 32; unsigned int stride = width * 4; size_t size; unsigned char *mem; int fd; (void)fb_geometry(hw->kernel_fb, &width, &height, &bpp, &stride); if(width < COVER_SPI_WIDTH) width = COVER_SPI_WIDTH; if(height < 320) height = 320; if(stride < width * 4) stride = width * 4; size = (size_t)stride * height; mem = calloc(1, size); if(!mem) return; hw_event(hw, "kernel clear fb"); cover_x11_show_black(hw); fd = open(hw->kernel_fb, O_RDWR | O_CLOEXEC); if(fd >= 0) { if(lseek(fd, 0, SEEK_SET) >= 0) (void)write_all(fd, mem, size); fsync(fd); close(fd); } free(mem); if(!hw->sim) poll(NULL, 0, 70); } static void cover_kernel_marker(struct cover_hw *hw, const char *value) { char line[64]; if(value) { char nl[32]; snprintf(nl, sizeof(nl), "%s\n", value); write_cover_text_once(hw->kernel_marker, nl); } else { unlink(hw->kernel_marker); } snprintf(line, sizeof(line), "kernel marker %s", value ? value : "absent"); hw_event(hw, line); } static void cover_kernel_backlight(struct cover_hw *hw, int lit) { char value[32]; char line[64]; unsigned int level; const char *power; if(lit) { level = hw->kernel_bl_invert ? 0 : hw->kernel_bl_level; power = "0"; cover_kernel_marker(hw, "1"); } else { level = 0; power = "4"; cover_kernel_marker(hw, NULL); } snprintf(value, sizeof(value), "%u", level); write_cover_text_once(hw->kernel_bl_power, power); write_cover_text(hw->kernel_bl, value); snprintf(line, sizeof(line), "kernel backlight %u power=%s", level, power); hw_event(hw, line); cover_kernel_power_sync(hw); } static void cover_kernel_open_backlight(struct cover_hw *hw) { char value[32]; unlink(hw->kernel_marker); snprintf(value, sizeof(value), "%u", hw->kernel_bl_level); write_cover_text_once(hw->kernel_bl_power, "0"); write_cover_text(hw->kernel_bl, value); hw_event(hw, "kernel restore internal"); cover_kernel_power_sync(hw); } static int cover_kernel_claim(struct cover_hw *hw) { unsigned int offsets[2]; unsigned char defaults[2]; int fd; if(hw->fd_mux >= 0 || hw->mux_claimed) return 1; offsets[0] = hw->mux_gpio; offsets[1] = hw->reset_gpio; defaults[0] = (unsigned char)hw->mux_open_level; defaults[1] = (unsigned char)hw->reset_idle_level; fd = hw_gpio_request(hw, offsets, defaults, 2); if(fd < 0) return 0; hw->fd_mux = fd; hw->mux_claimed = 1; hw->kernel_owned = 1; hw->kernel_restored = 0; return cover_kernel_mux(hw, 0); } static void cover_kernel_release(struct cover_hw *hw, int open) { if(!hw->kernel_owned) return; if(hw->kernel_lit > 0) cover_kernel_display_off(hw, 1, open ? 10 : 120); cover_kernel_mux(hw, 0); unlink(hw->kernel_marker); hw_event(hw, "release"); if(!hw->sim && hw->fd_mux >= 0) close(hw->fd_mux); hw->fd_mux = -1; hw->mux_claimed = 0; hw->kernel_owned = 0; hw->kernel_lit = -1; if(open) { cover_x11_hide(hw); hw_dpms(hw, "reinit"); cover_kernel_open_backlight(hw); hw_dpms(hw, "on"); hw->kernel_restored = 1; } else { write_cover_text_once(hw->kernel_bl_power, "4"); write_cover_text(hw->kernel_bl, "0"); hw_dpms(hw, "off"); cover_kernel_power_sync(hw); hw->kernel_restored = 0; } } static void cover_bus_release(struct cover_hw *hw) { if(hw->kernel_owned) { cover_kernel_release(hw, 0); return; } if(!hw->mux_claimed) return; cover_hw_release(hw); if(!hw->sim && hw->fd_mux >= 0) close(hw->fd_mux); hw->fd_mux = -1; hw->mux_claimed = 0; hw->kernel_restored = 0; } static void cover_kernel_restore_internal(struct cover_hw *hw) { unsigned int offsets[1]; unsigned char defaults[1]; unsigned char values[1]; int fd; if(hw->kernel_restored) return; if(hw->kernel_owned) { cover_kernel_release(hw, 1); return; } if(hw->mux_claimed || hw->fd_mux >= 0) { cover_bus_release(hw); } else { offsets[0] = hw->mux_gpio; defaults[0] = (unsigned char)hw->mux_open_level; fd = hw_gpio_request(hw, offsets, defaults, 1); if(fd >= 0) { values[0] = (unsigned char)hw->mux_open_level; hw_gpio_set(hw, fd, values, 1); if(!hw->sim) close(fd); } } cover_x11_hide(hw); hw_dpms(hw, "reinit"); cover_kernel_open_backlight(hw); hw_dpms(hw, "on"); hw->kernel_restored = 1; } static int cover_kernel_frame(struct cover_hw *hw, const struct state *state) { unsigned int width = COVER_SPI_WIDTH; unsigned int height = COVER_SPI_HEIGHT; unsigned int stride = width * 4; char sysfs[128]; unsigned int parsed = 0; size_t size; unsigned char *mem; struct frame fb; int fd; char line[96]; snprintf(sysfs, sizeof(sysfs), "/sys/class/graphics/fb0/stride"); if(read_uint_file(sysfs, &parsed) && parsed >= width * 4) stride = parsed; size = (size_t)stride * height; mem = calloc(1, size); if(!mem) return 0; fb.pixels = mem; fb.width = width; fb.height = height; fb.stride = stride; fb.bpp = 32; render_frame(&fb, state); snprintf(line, sizeof(line), "kernel frame lit=%d size=%zu", cover_is_lit(state), size); hw_event(hw, line); (void)cover_x11_present(hw, mem, width, height, stride); fd = open(hw->kernel_fb, O_RDWR | O_CLOEXEC); if(fd < 0) { free(mem); return hw->sim || hw->x11.mapped; } if(lseek(fd, 0, SEEK_SET) < 0 || !write_all(fd, mem, size)) { free(mem); close(fd); return hw->x11.mapped; } fsync(fd); close(fd); free(mem); return 1; } static const char *cover_kernel_draw(struct cover_hw *hw, const struct state *state) { int lit = cover_is_lit(state); if(!cover_kernel_claim(hw)) return "none"; if(lit != hw->kernel_lit) { if(lit) { /* Wake DRM while gpio13 still selects the internal panel so any * kernel gpio25 reset and init completes cleanly on the internal * controller, paint Xorg's active scanout BO solid black and leave the * normally-white internal GC9305 scanning opaque black in DISPON (unless * kernel_internal_sleep=1 is requested), then switch gpio13 to the * external cover panel. */ cover_kernel_mux(hw, 0); cover_kernel_marker(hw, "0"); cover_x11_show_black(hw); hw_dpms(hw, "on"); /* Keep the shared MPP2 PWM off while clearing the internal panel and * resetting/initializing the external GC9305: marker="0" tells * bananarchy-display-power-sync to hold DPMS On with brightness=0 and * bl_power=4 until both GRAMs are ready. */ if(!hw->sim) { write_cover_text_once(hw->kernel_bl_power, "4"); write_cover_text(hw->kernel_bl, "0"); } cover_kernel_clear_fb(hw); if(hw->kernel_internal_sleep) cover_kernel_display_off(hw, 0, 120); cover_kernel_mux(hw, 1); cover_kernel_reset(hw); if(!cover_kernel_replay_firmware(hw)) return "none"; /* Stock external firmware places its 120 ms delay before SLPOUT (0x11) * and immediately sends DISPON (0x29). Allow 120 ms after SLPOUT for * the GC9305 boost converter to settle, push the 240x240 frame, and * re-latch DISPON before turning the shared backlight on. */ if(!hw->sim) poll(NULL, 0, 120); if(!cover_kernel_frame(hw, state)) return "none"; if(!hw->sim) poll(NULL, 0, 40); cover_kernel_command(hw, 0x29, NULL, 0); cover_kernel_backlight(hw, 1); hw->kernel_lit = 1; return "kernel"; } cover_kernel_backlight(hw, 0); if(hw->kernel_lit > 0) cover_kernel_display_off(hw, 1, 120); cover_kernel_display_off(hw, 0, 120); hw_dpms(hw, "off"); cover_kernel_power_sync(hw); hw->kernel_lit = 0; return "kernel-dark"; } if(lit) { char expect_bl[32]; if(!cover_kernel_frame(hw, state)) return "none"; snprintf(expect_bl, sizeof(expect_bl), "%u", hw->kernel_bl_invert ? 0 : hw->kernel_bl_level); if(!hw->sim && (!cover_text_equals(hw->kernel_bl, expect_bl) || !cover_text_equals(hw->kernel_bl_power, "0"))) { cover_kernel_backlight(hw, 1); } } return lit ? "kernel" : "kernel-dark"; } static const char *cover_draw(struct cover_hw *hw, const char *fb_path, const struct state *state) { int flip_open = strcmp(state->lid, "open") == 0; int fb_present = access(fb_path, W_OK) == 0; int prefer_fb = strcmp(hw->backend, "spidev") != 0 && strcmp(hw->backend, "none") != 0 && fb_present; if(flip_open) { if(strcmp(hw->backend, "kernel") == 0) { cover_kernel_restore_internal(hw); cover_x11_hide(hw); } else { cover_x11_hide(hw); cover_hw_release(hw); cover_kernel_release(hw, 0); } if(prefer_fb) return draw_frame(fb_path, state) ? "fb" : "none"; return "idle"; } if(strcmp(hw->backend, "none") == 0) { cover_bus_release(hw); return "none"; } if(strcmp(hw->backend, "kernel") == 0) { /* A runtime backend switch must hand over the spidev linehandle first. */ if(hw->mux_claimed && !hw->kernel_owned) cover_bus_release(hw); /* Take the shared bus only after the lid daemon has stopped Xorg's * main-panel flushes. Once the cover owns it, DPMS is intentionally On * so the kernel driver can send frames. */ if(hw->kernel_lit < 0 && !cover_main_panel_is_off()) { cover_kernel_release(hw, 0); return "pending"; } return cover_kernel_draw(hw, state); } if(prefer_fb) { cover_hw_release(hw); return draw_frame(fb_path, state) ? "fb" : "none"; } if(hw->spi_enabled) { if(!cover_main_panel_is_off()) { cover_hw_release(hw); return "pending"; } return cover_spi_draw(hw, state) ? "spidev" : "none"; } cover_hw_release(hw); return "none"; } static void mkdir_p(const char *path) { char buf[256]; char *p; snprintf(buf, sizeof(buf), "%s", path); for(p = buf + 1; *p; p++) { if(*p != '/') continue; *p = '\0'; mkdir(buf, 0755); *p = '/'; } } static void trim(char *value) { size_t len; while(*value == ' ' || *value == '\t') memmove(value, value + 1, strlen(value)); len = strlen(value); while(len > 0 && (value[len - 1] == ' ' || value[len - 1] == '\t' || value[len - 1] == '\r' || value[len - 1] == '\n')) { value[--len] = '\0'; } } static long long blank_timeout_ms(const char *configured) { const char *path = getenv("BANANARCHY_COVER_MAIN_BLANK_CFG"); const char *noidle = getenv("BANANARCHY_COVER_NOIDLE_PATH"); const char *env = getenv("SXMO_UNLOCK_IDLE_TIME"); char buf[32]; long secs = DEFAULT_BLANK_SECS; long value; if(!path || !path[0]) path = MAIN_BLANK_CFG; if(!noidle || !noidle[0]) noidle = MAIN_NOIDLE_PATH; if(configured && strcasecmp(configured, "auto") != 0 && configured[0]) { char *end = NULL; value = strtol(configured, &end, 10); if(end != configured) { if(value < 0) value = 0; if(value > 86400) value = 86400; return (long long)value * 1000LL; } } /* "auto" (the default) follows Config -> Screen blank and sxmo.noidle * identically to dwm, dynamically reloading when the user changes it. */ if(access(noidle, F_OK) == 0) return 0; FILE *handle = fopen(path, "r"); if(handle) { if(fscanf(handle, "%31s", buf) == 1) { char *end = NULL; value = strtol(buf, &end, 10); if(end != buf && value >= 0 && value <= 86400) secs = value; } fclose(handle); } else if(env && atoi(env) > 0) { secs = atoi(env); } return (long long)secs * 1000LL; } static void refresh_blank_timeout(struct state *state) { state->blank_ms = blank_timeout_ms(state->blank_cfg); } static long long effective_blank_ms(const struct state *state) { const char *noidle = getenv("BANANARCHY_COVER_NOIDLE_PATH"); if(!noidle || !noidle[0]) noidle = MAIN_NOIDLE_PATH; if(state->wake_capped && state->wake_blank_ms > 0 && access(noidle, F_OK) != 0 && (state->blank_ms == 0 || state->blank_ms > state->wake_blank_ms)) { return state->wake_blank_ms; } return state->blank_ms; } static int config_level(const char *value, int fallback) { long v = strtol(value, NULL, 10); if(v < 0 || v > 1) return fallback; return (int)v; } static void cover_hw_init(struct cover_hw *hw) { const char *sim; memset(hw, 0, sizeof(*hw)); safe_copy(hw->backend, sizeof(hw->backend), "auto"); hw->mux_gpio = 13; hw->dc_gpio = 21; hw->reset_gpio = 23; /* The live phone holds gpio13 low while the 240x320 main panel is active, * so low selects the internal panel and high must select the cover. */ hw->mux_open_level = 0; hw->mux_closed_level = 1; hw->dc_command_level = 0; hw->dc_data_level = 1; hw->reset_assert_level = 0; hw->reset_idle_level = 1; hw->speed_hz = 25000000; hw->word_bits = 9; hw->panel_lines = 1; hw->probe_index = -1; hw->kernel_lit = -1; hw->kernel_restored = 0; safe_copy(hw->spi_path, sizeof(hw->spi_path), "/dev/spidev0.1"); safe_copy(hw->gpio_path, sizeof(hw->gpio_path), "auto"); safe_copy(hw->firmware, sizeof(hw->firmware), "/lib/firmware/nokia,beatles-gc9305-ext-panel.bin"); safe_copy(hw->kernel_fb, sizeof(hw->kernel_fb), "/dev/fb0"); safe_copy(hw->kernel_dpms, sizeof(hw->kernel_dpms), "/usr/bin/bananarchy-cover-dpms.sh"); safe_copy(hw->kernel_sync, sizeof(hw->kernel_sync), "/usr/bin/bananarchy-display-power-sync"); safe_copy(hw->kernel_cmd, sizeof(hw->kernel_cmd), "/sys/kernel/debug/dri/0/command"); safe_copy(hw->kernel_bl, sizeof(hw->kernel_bl), "/sys/class/backlight/backlight/brightness"); safe_copy(hw->kernel_bl_power, sizeof(hw->kernel_bl_power), "/sys/class/backlight/backlight/bl_power"); safe_copy(hw->kernel_marker, sizeof(hw->kernel_marker), "/run/bananarchy/cover-backlight"); hw->kernel_bl_level = 14; hw->kernel_bl_invert = 0; hw->kernel_internal_sleep = 0; safe_copy(hw->probe_desc, sizeof(hw->probe_desc), "none"); hw->fd_spi = -1; hw->fd_chip = -1; hw->fd_mux = -1; hw->fd_panel = -1; hw->fd_sim = -1; { const char *fb = getenv("BANANARCHY_COVER_MAIN_FB"); const char *dp = getenv("BANANARCHY_COVER_DPMS_HELPER"); const char *sync = getenv("BANANARCHY_COVER_KERNEL_POWER_SYNC"); const char *cmd = getenv("BANANARCHY_COVER_KERNEL_CMD"); const char *bl = getenv("BANANARCHY_COVER_KERNEL_BL"); const char *power = getenv("BANANARCHY_COVER_KERNEL_BL_POWER"); const char *marker = getenv("BANANARCHY_COVER_KERNEL_MARKER"); const char *level = getenv("BANANARCHY_COVER_KERNEL_BL_LEVEL"); const char *invert = getenv("BANANARCHY_COVER_KERNEL_BL_INVERT"); const char *isleep = getenv("BANANARCHY_COVER_KERNEL_INTERNAL_SLEEP"); if(fb && *fb) safe_copy(hw->kernel_fb, sizeof(hw->kernel_fb), fb); if(dp && *dp) safe_copy(hw->kernel_dpms, sizeof(hw->kernel_dpms), dp); if(sync && *sync) safe_copy(hw->kernel_sync, sizeof(hw->kernel_sync), sync); if(cmd && *cmd) safe_copy(hw->kernel_cmd, sizeof(hw->kernel_cmd), cmd); if(bl && *bl) safe_copy(hw->kernel_bl, sizeof(hw->kernel_bl), bl); if(power && *power) safe_copy(hw->kernel_bl_power, sizeof(hw->kernel_bl_power), power); if(marker && *marker) safe_copy(hw->kernel_marker, sizeof(hw->kernel_marker), marker); if(level && *level) { unsigned long parsed = strtoul(level, NULL, 10); if(parsed > 0 && parsed <= 255) hw->kernel_bl_level = (unsigned int)parsed; } if(invert && *invert) hw->kernel_bl_invert = strtol(invert, NULL, 10) != 0; if(isleep && *isleep) hw->kernel_internal_sleep = strtol(isleep, NULL, 10) != 0; } sim = getenv("BANANARCHY_COVER_SPI_SIM"); if(sim && *sim) { safe_copy(hw->sim_path, sizeof(hw->sim_path), sim); hw->fd_sim = open(sim, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); if(hw->fd_sim >= 0) hw->sim = 1; else hw->sim_path[0] = '\0'; } } static void read_config(const char *path, char *socket_path, size_t splen, char *fb_path, size_t fblen, struct state *state, struct cover_hw *hw) { char line[256]; FILE *handle = fopen(path, "r"); safe_copy(socket_path, splen, DEFAULT_SOCKET); safe_copy(fb_path, fblen, DEFAULT_FB); safe_copy(state->blank_cfg, sizeof(state->blank_cfg), "auto"); state->wake_blank_ms = 0; state->wake_capped = 0; state->backlight_path[0] = '\0'; state->backlight_level = 160; if(!handle) { refresh_blank_timeout(state); return; } while(fgets(line, sizeof(line), handle)) { char *comment = strchr(line, '#'); char *eq; char *key; char *value; long v; if(comment) *comment = '\0'; eq = strchr(line, '='); if(!eq) continue; *eq = '\0'; key = line; value = eq + 1; trim(key); trim(value); if(strcmp(key, "socket_path") == 0) safe_copy(socket_path, splen, value); else if(strcmp(key, "fb_device") == 0) safe_copy(fb_path, fblen, value); else if(strcmp(key, "backlight_path") == 0) safe_copy(state->backlight_path, sizeof(state->backlight_path), value); else if(strcmp(key, "brightness") == 0) { v = strtol(value, NULL, 10); if(v > 0 && v <= 255) state->backlight_level = (int)v; } else if(strcmp(key, "blank_timeout") == 0) safe_copy(state->blank_cfg, sizeof(state->blank_cfg), value); else if(strcmp(key, "wake_blank_timeout") == 0) { char *end = NULL; v = strtol(value, &end, 10); if(end != value && v >= 0 && v <= 86400) state->wake_blank_ms = (long long)v * 1000LL; } else if(strcmp(key, "backend") == 0) safe_copy(hw->backend, sizeof(hw->backend), value); else if(strcmp(key, "spi_device") == 0) safe_copy(hw->spi_path, sizeof(hw->spi_path), value); else if(strcmp(key, "main_fb_device") == 0) safe_copy(hw->kernel_fb, sizeof(hw->kernel_fb), value); else if(strcmp(key, "kernel_dpms_helper") == 0) safe_copy(hw->kernel_dpms, sizeof(hw->kernel_dpms), value); else if(strcmp(key, "kernel_power_sync_helper") == 0) safe_copy(hw->kernel_sync, sizeof(hw->kernel_sync), value); else if(strcmp(key, "kernel_command_path") == 0) safe_copy(hw->kernel_cmd, sizeof(hw->kernel_cmd), value); else if(strcmp(key, "kernel_backlight_path") == 0) safe_copy(hw->kernel_bl, sizeof(hw->kernel_bl), value); else if(strcmp(key, "kernel_backlight_power_path") == 0) safe_copy(hw->kernel_bl_power, sizeof(hw->kernel_bl_power), value); else if(strcmp(key, "kernel_backlight_marker") == 0) safe_copy(hw->kernel_marker, sizeof(hw->kernel_marker), value); else if(strcmp(key, "kernel_backlight_level") == 0) { v = strtol(value, NULL, 10); if(v > 0 && v <= 255) hw->kernel_bl_level = (unsigned int)v; } else if(strcmp(key, "kernel_backlight_invert") == 0) { v = strtol(value, NULL, 10); if(v == 0 || v == 1) hw->kernel_bl_invert = (int)v; } else if(strcmp(key, "kernel_internal_sleep") == 0) { v = strtol(value, NULL, 10); if(v == 0 || v == 1) hw->kernel_internal_sleep = (int)v; } else if(strcmp(key, "gpiochip_device") == 0) safe_copy(hw->gpio_path, sizeof(hw->gpio_path), value); else if(strcmp(key, "panel_firmware") == 0) safe_copy(hw->firmware, sizeof(hw->firmware), value); else if(strcmp(key, "spi_mux_gpio") == 0) { v = strtol(value, NULL, 10); if(v >= 0 && v < 1024) hw->mux_gpio = (unsigned int)v; } else if(strcmp(key, "spi_dc_gpio") == 0) { v = strtol(value, NULL, 10); if(v >= 0 && v < 1024) hw->dc_gpio = (unsigned int)v; } else if(strcmp(key, "spi_reset_gpio") == 0) { v = strtol(value, NULL, 10); if(v >= 0 && v < 1024) hw->reset_gpio = (unsigned int)v; } else if(strcmp(key, "mux_closed_level") == 0) hw->mux_closed_level = config_level(value, hw->mux_closed_level); else if(strcmp(key, "mux_open_level") == 0) hw->mux_open_level = config_level(value, hw->mux_open_level); else if(strcmp(key, "dc_command_level") == 0) hw->dc_command_level = config_level(value, hw->dc_command_level); else if(strcmp(key, "dc_data_level") == 0) hw->dc_data_level = config_level(value, hw->dc_data_level); else if(strcmp(key, "reset_assert_level") == 0) hw->reset_assert_level = config_level(value, hw->reset_assert_level); else if(strcmp(key, "reset_idle_level") == 0) hw->reset_idle_level = config_level(value, hw->reset_idle_level); else if(strcmp(key, "spi_speed_hz") == 0) { v = strtol(value, NULL, 10); if(v >= 1000000 && v <= 50000000) hw->speed_hz = (unsigned int)v; } else if(strcmp(key, "spi_word_bits") == 0) { v = strtol(value, NULL, 10); if(v == 8 || v == 9) hw->word_bits = (int)v; } } fclose(handle); refresh_blank_timeout(state); if(strcmp(hw->backend, "none") == 0 || strcmp(hw->backend, "fb") == 0 || !hw->spi_path[0] || !hw->gpio_path[0] || !hw->firmware[0]) return; if(!hw_ensure_gpiochip(hw)) return; hw->spi_enabled = 1; } static void lower_string(char *value) { while(*value) { *value = (char)tolower((unsigned char)*value); value++; } } static void upper_string(char *value) { while(*value) { *value = (char)toupper((unsigned char)*value); value++; } } static int test_value(const char *mode) { if(!mode) return 0; if(strcmp(mode, "bars") == 0) return 2; if(strcmp(mode, "clock") == 0) return 1; if(strcmp(mode, "solid") == 0) return 3; if(strcmp(mode, "off") == 0) return 4; return 0; } static void spawn_cover_event(const char *action, const char *arg) { const char *cmd = getenv("BANANARCHY_COVER_EVENT_CMD"); const char *bin = (cmd && *cmd) ? cmd : "/usr/bin/bananarchy-cover-event.sh"; char *const argv_with_arg[] = { (char *)bin, (char *)action, (char *)arg, NULL }; char *const argv_no_arg[] = { (char *)bin, (char *)action, NULL }; if(!action || !*action) return; spawn_async_cmd((arg && *arg) ? argv_with_arg : argv_no_arg); } /* A closed flip lights the outer panel only. Status updates (NETWORK, * BATTERY) refresh an already visible cover but never wake it; real events * (BUTTON, WAKE, CALL, NOTIFY, SMS) do. */ static void cover_wake(struct state *state, int *redraw) { refresh_blank_timeout(state); if(strcmp(state->lid, "closed") == 0 && state->enabled && !state->test) { state->visible = 1; state->wake_capped = cover_hold_awake(state) ? 0 : 1; state->last_input_ms = now_ms(); *redraw = 1; } } /* On nokia-beatles, gpio36 (SW_KEYPAD_SLIDE) asserts 1 when the flip closes, * which the shipped dwm binary misreads as a slider-open event and forwards as * a bogus "LID OPEN" datagram. Trust bananarchy-lid's authoritative state file * whenever it reports "closed". */ static int authoritative_lid_closed(const struct cover_hw *hw) { const char *path = getenv("BANANARCHY_COVER_LID_STATE"); if(!path || !*path) { if(hw->sim || getenv("BANANARCHY_COVER_FB_GEOM")) return 0; path = "/run/bananarchy/lid-state"; } return cover_text_equals(path, "closed"); } static void write_runtime_backlight_conf(const struct cover_hw *hw) { char text[128]; if(hw->sim) return; mkdir_p(COVER_RUNTIME_CONF); snprintf(text, sizeof(text), "kernel_backlight_level = %u\nkernel_backlight_invert = %d\n", hw->kernel_bl_level, hw->kernel_bl_invert); write_cover_text(COVER_RUNTIME_CONF, text); } static void handle_command(char *buffer, struct state *state, struct cover_hw *hw, int *redraw) { char command[32]; char *save = NULL; char *token = strtok_r(buffer, " \t\r\n", &save); if(!token) return; safe_copy(command, sizeof(command), token); upper_string(command); if(strcmp(command, "LID") == 0) { char *value = strtok_r(NULL, " \t\r\n", &save); int new_closed = value && strcasecmp(value, "CLOSED") == 0; int old_closed = strcmp(state->lid, "closed") == 0; if(!new_closed && authoritative_lid_closed(hw)) new_closed = 1; safe_copy(state->lid, sizeof(state->lid), new_closed ? "closed" : "open"); /* The lid daemon rebroadcasts its state every 2 s. Only a real * transition blanks the cover; a repeating LID CLOSED must not undo a * WAKE from an incoming call or an external side button. */ if(new_closed != old_closed) { long long now = now_ms(); refresh_blank_timeout(state); state->visible = 0; state->wake_capped = 0; state->last_input_ms = now; state->closed_since_ms = new_closed ? now : 0; if(!new_closed) { state->quagr_active = 0; state->quagr_msg[0] = '\0'; state->quagr_time[0] = '\0'; } *redraw = 1; } } else if(strcmp(command, "BUTTON") == 0 || strcmp(command, "WAKE") == 0) { char *sub = strtok_r(NULL, " \t\r\n", &save); /* Trusted external side button, or a main-panel wake request that the * closed-lid gate forwarded to the cover display. Ignore WAKE (never * BUTTON) during the 450 ms close-settle window so dwm's spurious * SW_KEYPAD_SLIDE wake on close does not light the cover by itself, or * right after dismissing a held Quagr page. */ if(strcmp(command, "WAKE") == 0) { long long now = now_ms(); if(!hw->sim && state->closed_since_ms > 0 && now - state->closed_since_ms < 450) return; if(state->quagr_dismissed_ms > 0 && now - state->quagr_dismissed_ms < 600) return; } if(strcmp(command, "BUTTON") == 0 && strcmp(state->lid, "closed") == 0) { if(sub && call_hold_awake(state)) { upper_string(sub); if(strcmp(sub, "VOLUP") == 0 || strcmp(sub, "VOLDOWN") == 0) { if(strcmp(state->call, "incoming") == 0) { safe_copy(state->call, sizeof(state->call), "muted"); spawn_cover_event("mute-ring", state->call_num); } cover_wake(state, redraw); *redraw = 1; return; } if(strcmp(sub, "POWER") == 0) { safe_copy(state->call, sizeof(state->call), "none"); state->call_num[0] = '\0'; state->call_name[0] = '\0'; state->call_sim[0] = '\0'; spawn_cover_event("hangup-call", ""); cover_wake(state, redraw); *redraw = 1; return; } } else if(state->quagr_active) { state->quagr_active = 0; state->quagr_msg[0] = '\0'; state->quagr_time[0] = '\0'; state->quagr_dismissed_ms = now_ms(); state->visible = 0; state->wake_capped = 0; *redraw = 1; return; } } cover_wake(state, redraw); } else if(strcmp(command, "QUAGR") == 0) { char *rest = save; while(rest && (*rest == ' ' || *rest == '\t')) rest++; if(!rest || !*rest) { state->quagr_active = 0; state->quagr_msg[0] = '\0'; state->quagr_time[0] = '\0'; if(state->visible) *redraw = 1; } else { time_t now_t; struct tm tm_now; ba_refresh_tz(); now_t = time(NULL); localtime_r(&now_t, &tm_now); strftime(state->quagr_time, sizeof(state->quagr_time), "%H:%M", &tm_now); safe_copy(state->quagr_msg, sizeof(state->quagr_msg), rest); trim(state->quagr_msg); if(state->quagr_msg[0]) { state->quagr_active = 1; state->quagr_dismissed_ms = 0; cover_wake(state, redraw); if(state->visible) *redraw = 1; } } } else if(strcmp(command, "QUAGR_CLEAR") == 0) { state->quagr_active = 0; state->quagr_msg[0] = '\0'; state->quagr_time[0] = '\0'; if(state->visible) *redraw = 1; } else if(strcmp(command, "NETWORK") == 0) { char *rest = save; while(rest && (*rest == ' ' || *rest == '\t')) rest++; safe_copy(state->network, sizeof(state->network), rest ? rest : ""); trim(state->network); if(state->visible) *redraw = 1; } else if(strcmp(command, "NOTIFY") == 0) { char *rest = save; while(rest && (*rest == ' ' || *rest == '\t')) rest++; safe_copy(state->message, sizeof(state->message), rest ? rest : ""); trim(state->message); cover_wake(state, redraw); if(state->visible) *redraw = 1; } else if(strcmp(command, "CALL") == 0) { char *rest = save; char status[64] = ""; char num[64] = ""; char name[64] = ""; char sim[16] = ""; while(rest && (*rest == ' ' || *rest == '\t')) rest++; if(rest && *rest) { trim(rest); if(strchr(rest, '|')) { char *parts[4] = { NULL, NULL, NULL, NULL }; int idx = 0; char *p = rest; parts[idx++] = p; while((p = strchr(p, '|')) != NULL && idx < 4) { *p++ = '\0'; parts[idx++] = p; } if(parts[0]) safe_copy(status, sizeof(status), parts[0]); if(parts[1]) safe_copy(num, sizeof(num), parts[1]); if(parts[2]) safe_copy(name, sizeof(name), parts[2]); if(parts[3]) safe_copy(sim, sizeof(sim), parts[3]); } else { char *t0 = strtok_r(rest, " \t\r\n", &save); char *t1 = t0 ? strtok_r(NULL, " \t\r\n", &save) : NULL; char *t2 = t1 ? strtok_r(NULL, " \t\r\n", &save) : NULL; char *t3 = t2 ? strtok_r(NULL, " \t\r\n", &save) : NULL; if(t0) safe_copy(status, sizeof(status), t0); if(t1) safe_copy(num, sizeof(num), t1); if(t2) safe_copy(name, sizeof(name), t2); if(t3) safe_copy(sim, sizeof(sim), t3); } trim(status); lower_string(status); trim(num); trim(name); trim(sim); if(strcmp(num, "-") == 0) num[0] = '\0'; if(strcmp(name, "-") == 0) name[0] = '\0'; if(strcmp(sim, "-") == 0) sim[0] = '\0'; if(strcmp(status, "none") == 0) { safe_copy(state->call, sizeof(state->call), "none"); state->call_num[0] = '\0'; state->call_name[0] = '\0'; state->call_sim[0] = '\0'; state->last_input_ms = now_ms(); if(state->visible) *redraw = 1; } else if(strcmp(status, "muted") == 0) { if(strcmp(state->call, "incoming") != 0 && strcmp(state->call, "muted") != 0) return; safe_copy(state->call, sizeof(state->call), "muted"); if(num[0]) safe_copy(state->call_num, sizeof(state->call_num), num); if(name[0]) safe_copy(state->call_name, sizeof(state->call_name), name); if(sim[0]) safe_copy(state->call_sim, sizeof(state->call_sim), sim); cover_wake(state, redraw); *redraw = 1; } else if(strcmp(status, "incoming") == 0) { if(num[0] && strcmp(state->call_num, num) != 0) { safe_copy(state->call_num, sizeof(state->call_num), num); state->call_name[0] = '\0'; } if(name[0]) safe_copy(state->call_name, sizeof(state->call_name), name); if(sim[0]) safe_copy(state->call_sim, sizeof(state->call_sim), sim); safe_copy(state->call, sizeof(state->call), "incoming"); cover_wake(state, redraw); *redraw = 1; } else if(strcmp(status, "missed") == 0) { const char *who = name[0] ? name : (num[0] ? num : (state->call_name[0] ? state->call_name : state->call_num)); if(who && *who) { char clean_who[64]; sanitize_cover_text(who, clean_who, sizeof(clean_who)); if(clean_who[0]) snprintf(state->message, sizeof(state->message), "MISSED: %s", clean_who); else snprintf(state->message, sizeof(state->message), "MISSED CALL"); } else { snprintf(state->message, sizeof(state->message), "MISSED CALL"); } safe_copy(state->call, sizeof(state->call), "missed"); state->call_num[0] = '\0'; state->call_name[0] = '\0'; state->call_sim[0] = '\0'; cover_wake(state, redraw); *redraw = 1; } else if(strcmp(status, "active") == 0) { safe_copy(state->call, sizeof(state->call), "active"); state->last_input_ms = now_ms(); if(state->visible) *redraw = 1; } else if(status[0]) { safe_copy(state->call, sizeof(state->call), status); cover_wake(state, redraw); } } } else if(strcmp(command, "SMS") == 0) { char *value = strtok_r(NULL, " \t\r\n", &save); if(value) state->sms = (int)strtol(value, NULL, 10); cover_wake(state, redraw); } else if(strcmp(command, "BATTERY") == 0) { char *value = strtok_r(NULL, " \t\r\n", &save); if(value) state->battery = (int)strtol(value, NULL, 10); if(state->visible) *redraw = 1; } else if(strcmp(command, "SET") == 0) { char *key = strtok_r(NULL, " \t\r\n", &save); char *value = strtok_r(NULL, " \t\r\n", &save); if(!key || !value) return; if(strcmp(key, "enabled") == 0) { state->enabled = (int)strtol(value, NULL, 10); *redraw = 1; return; } if(strcmp(key, "blank_timeout") == 0) { safe_copy(state->blank_cfg, sizeof(state->blank_cfg), value); refresh_blank_timeout(state); return; } if(strcmp(key, "wake_blank_timeout") == 0) { char *end = NULL; long wv = strtol(value, &end, 10); if(end != value && wv >= 0 && wv <= 86400) state->wake_blank_ms = (long long)wv * 1000LL; return; } /* Runtime polarity knobs and a one-command rollback for the physical * sign-off. Releasing forces the next draw to re-init the panel. */ if(strcmp(key, "backend") == 0) { safe_copy(hw->backend, sizeof(hw->backend), value); hw->spi_enabled = strcmp(hw->backend, "none") != 0 && strcmp(hw->backend, "fb") != 0 && hw->spi_path[0] && hw->gpio_path[0] && hw->firmware[0] && hw_ensure_gpiochip(hw); } else if(strcmp(key, "mux_closed_level") == 0) hw->mux_closed_level = config_level(value, hw->mux_closed_level); else if(strcmp(key, "mux_open_level") == 0) hw->mux_open_level = config_level(value, hw->mux_open_level); else if(strcmp(key, "dc_command_level") == 0) hw->dc_command_level = config_level(value, hw->dc_command_level); else if(strcmp(key, "dc_data_level") == 0) hw->dc_data_level = config_level(value, hw->dc_data_level); else if(strcmp(key, "reset_assert_level") == 0) hw->reset_assert_level = config_level(value, hw->reset_assert_level); else if(strcmp(key, "reset_idle_level") == 0) hw->reset_idle_level = config_level(value, hw->reset_idle_level); else if(strcmp(key, "spi_word_bits") == 0) { long bits = strtol(value, NULL, 10); if(bits == 8 || bits == 9) hw->word_bits = (int)bits; else return; } else if(strcmp(key, "kernel_backlight_level") == 0) { long level = strtol(value, NULL, 10); if(level > 0 && level <= 255) { hw->kernel_bl_level = (unsigned int)level; write_runtime_backlight_conf(hw); } else return; } else if(strcmp(key, "kernel_backlight_invert") == 0) { long invert = strtol(value, NULL, 10); if(invert == 0 || invert == 1) { hw->kernel_bl_invert = (int)invert; write_runtime_backlight_conf(hw); } else return; } else if(strcmp(key, "kernel_internal_sleep") == 0) { long sleep_internal = strtol(value, NULL, 10); if(sleep_internal == 0 || sleep_internal == 1) hw->kernel_internal_sleep = (int)sleep_internal; else return; } else return; cover_bus_release(hw); hw->kernel_restored = 0; *redraw = 1; } else if(strcmp(command, "PROBE") == 0) { const struct probe_case *p; hw->probe_index = (hw->probe_index + 1) % (int)(sizeof(probe_cases) / sizeof(probe_cases[0])); p = &probe_cases[hw->probe_index]; hw->word_bits = p->bits; hw->mux_closed_level = p->mux; hw->mux_open_level = p->mux ? 0 : 1; hw->reset_assert_level = p->reset; hw->reset_idle_level = p->reset ? 0 : 1; hw->dc_command_level = p->dc; hw->dc_data_level = p->dc ? 0 : 1; hw->speed_hz = p->speed; snprintf(hw->probe_desc, sizeof(hw->probe_desc), "case %d/%d bits=%d mux=%d reset=%d dc=%d speed=%u", hw->probe_index + 1, (int)(sizeof(probe_cases) / sizeof(probe_cases[0])), p->bits, p->mux, p->reset, p->dc, p->speed); /* PROBE is the legacy userspace sign-off path; it owns its own D/C. */ safe_copy(hw->backend, sizeof(hw->backend), "spidev"); hw->spi_enabled = hw->spi_path[0] && hw->gpio_path[0] && hw->firmware[0]; cover_bus_release(hw); state->test = 2; state->visible = 1; state->wake_capped = 0; state->last_input_ms = now_ms(); *redraw = 1; } else if(strcmp(command, "TEST") == 0) { char *mode = strtok_r(NULL, " \t\r\n", &save); if(mode) lower_string(mode); state->test = test_value(mode); *redraw = 1; } else if(strcmp(command, "BLANK") == 0) { state->visible = 0; state->wake_capped = 0; *redraw = 1; } else if(strcmp(command, "UNBLANK") == 0) { refresh_blank_timeout(state); if(strcmp(state->lid, "closed") == 0) { state->visible = 1; state->wake_capped = 0; state->last_input_ms = now_ms(); } *redraw = 1; } else if(strcmp(command, "REFRESH") == 0 || strcmp(command, "RELOAD_THEME") == 0 || strcmp(command, "STATUS") == 0) { ba_refresh_tz(); refresh_blank_timeout(state); if(state->visible && strcmp(command, "STATUS") != 0) *redraw = 1; } } static void reply_for(char *buffer, const struct state *state, const struct cover_hw *hw, char *reply, size_t len) { char command[32]; char *save = NULL; char *token = strtok_r(buffer, " \t\r\n", &save); if(!token) { snprintf(reply, len, "OK\n"); return; } safe_copy(command, sizeof(command), token); upper_string(command); if(strcmp(command, "PING") == 0) { snprintf(reply, len, "OK pong\n"); } else if(strcmp(command, "STATUS") == 0) { const char *mux = "free"; if(hw->mux_claimed) mux = strcmp(hw->backend, "kernel") == 0 ? "cover" : (hw->claimed ? "closed" : "open"); snprintf(reply, len, "OK lid=%s backend=%s enabled=%d visible=%d blank_ms=%lld " "battery=%d call=%s sms=%d network=%s spi=%d mux=%s " "bits=%d quagr=%d probe=%s\n", state->lid, state->backend, state->enabled, state->visible, state->blank_ms, state->battery, state->call, state->sms, state->network, hw->spi_enabled, mux, hw->word_bits, state->quagr_active, hw->probe_desc); } else if(strcmp(command, "LID") == 0) { snprintf(reply, len, "OK lid=%s\n", state->lid); } else if(strcmp(command, "TEST") == 0) { snprintf(reply, len, "OK test=%d\n", state->test); } else { snprintf(reply, len, "OK\n"); } } static volatile sig_atomic_t g_stop_requested = 0; static void handle_stop_signal(int sig) { (void)sig; g_stop_requested = 1; } static void install_stop_handlers(void) { struct sigaction sa; memset(&sa, 0, sizeof(sa)); sa.sa_handler = handle_stop_signal; sigemptyset(&sa.sa_mask); sigaction(SIGTERM, &sa, NULL); sigaction(SIGINT, &sa, NULL); } int main(int argc, char **argv) { const char *lock_path = getenv("BANANARCHY_COVER_LOCK"); int lock_fd; const char *config = "/etc/bananarchy/cover-display.conf"; char socket_path[256]; char fb_path[128]; struct sockaddr_un local; int server; struct state state; struct cover_hw hw; long long last_draw = 0; long long pending_until = 0; int redraw = 1; if(is_non_flip_profile()) return 0; lock_fd = lock_singleton(lock_path ? lock_path : COVER_LOCK); if(lock_fd < 0) return 1; (void)lock_fd; install_reaper(); install_stop_handlers(); if(argc > 2 && strcmp(argv[1], "--config") == 0) config = argv[2]; memset(&state, 0, sizeof(state)); snprintf(state.lid, sizeof(state.lid), "open"); snprintf(state.backend, sizeof(state.backend), "none"); snprintf(state.call, sizeof(state.call), "none"); state.enabled = 1; state.battery = -1; cover_hw_init(&hw); if(!hw.sim) unlink(COVER_RUNTIME_CONF); read_config(config, socket_path, sizeof(socket_path), fb_path, sizeof(fb_path), &state, &hw); if(authoritative_lid_closed(&hw)) { snprintf(state.lid, sizeof(state.lid), "closed"); state.closed_since_ms = now_ms(); } mkdir_p(socket_path); unlink(socket_path); server = socket(AF_UNIX, SOCK_DGRAM | SOCK_CLOEXEC, 0); if(server < 0) return 1; if(strlen(socket_path) >= sizeof(local.sun_path)) return 1; memset(&local, 0, sizeof(local)); local.sun_family = AF_UNIX; strncpy(local.sun_path, socket_path, sizeof(local.sun_path) - 1); if(bind(server, (struct sockaddr *)&local, sizeof(local)) < 0) return 1; chmod(socket_path, 0660); chown(socket_path, 0, SESSION_GID); while(!g_stop_requested) { struct pollfd pfds[2]; nfds_t nfds = 1; char buffer[512]; char original[512]; char reply[512]; struct sockaddr_un peer; socklen_t peer_len = sizeof(peer); ssize_t nread; long long now = now_ms(); int pr; /* With the cover off there is no timer at all: poll blocks until IPC. */ int timeout_ms = -1; if(state.visible) { long long interval = strcmp(hw.backend, "kernel") == 0 ? KERNEL_REDRAW_MS : CLOCK_REDRAW_MS; long long next = interval - (now - last_draw); refresh_blank_timeout(&state); if(next < 1) next = 1; long long eff_blank = effective_blank_ms(&state); if(cover_hold_awake(&state)) { state.last_input_ms = now; } else if(eff_blank > 0) { long long remaining = eff_blank - (now - state.last_input_ms); if(remaining <= 0) { state.visible = 0; state.wake_capped = 0; redraw = 1; } else if(remaining < next) { next = remaining; } } timeout_ms = (int)(next > 1000000 ? 1000000 : next); if(state.visible && now - last_draw >= interval) redraw = 1; } if(redraw) { set_backlight(&state, cover_is_lit(&state)); snprintf(state.backend, sizeof(state.backend), "%s", cover_draw(&hw, fb_path, &state)); /* The lid daemon forces DPMS off asynchronously. Retry a pending draw * for a bounded window so the cover lights even if the first draw ran * before Xorg stopped flushing the main panel. */ now = now_ms(); pending_until = strcmp(state.backend, "pending") == 0 ? now + 3000 : 0; last_draw = now; redraw = 0; if(state.visible) { long long interval = strcmp(hw.backend, "kernel") == 0 ? KERNEL_REDRAW_MS : CLOCK_REDRAW_MS; long long next = interval; long long eff_blank = effective_blank_ms(&state); if(cover_hold_awake(&state)) { state.last_input_ms = now; } else if(eff_blank > 0) { long long remaining = eff_blank - (now - state.last_input_ms); if(remaining < 1) remaining = 1; if(remaining < next) next = remaining; } timeout_ms = (int)(next > 1000000 ? 1000000 : next); } else { timeout_ms = -1; } } if(pending_until > now) timeout_ms = 50; pfds[0].fd = server; pfds[0].events = POLLIN; pfds[0].revents = 0; if(hw.x11.dpy) { pfds[1].fd = hw.x11.conn_number(hw.x11.dpy); pfds[1].events = POLLIN; pfds[1].revents = 0; nfds = 2; } pr = poll(pfds, nfds, timeout_ms); if(pr < 0) { if(errno == EINTR && g_stop_requested) break; continue; } if(g_stop_requested) break; if(pr == 0 && pending_until > now && strcmp(state.backend, "pending") == 0) { redraw = 1; } if(nfds == 2) { if(pfds[1].revents & (POLLHUP | POLLERR | POLLNVAL)) cover_x11_drop(&hw); else if(pfds[1].revents & POLLIN) cover_x11_drain(&hw); } if(pfds[0].revents & POLLIN) { nread = recvfrom(server, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &peer_len); if(nread > 0) { buffer[nread] = '\0'; snprintf(original, sizeof(original), "%s", buffer); handle_command(buffer, &state, &hw, &redraw); reply_for(original, &state, &hw, reply, sizeof(reply)); sendto(server, reply, strlen(reply), 0, (struct sockaddr *)&peer, peer_len); if(strncasecmp(original, "QUIT", 4) == 0) { g_stop_requested = 1; break; } } } } state.visible = 0; state.test = 0; set_backlight(&state, 0); if(strcmp(state.lid, "closed") == 0 && (hw.kernel_lit > 0 || hw.mux_claimed)) cover_draw(&hw, fb_path, &state); cover_hw_shutdown(&hw); close(server); unlink(socket_path); return 0; }