// SPDX-License-Identifier: GPL-2.0-only // NeoUI - Bananarchy 240x320 X11 + Pango/Xft + .Xresources/.xth UI SDK #include "neoui.h" #include #include #ifndef _EVDEVK #define _EVDEVK(_v) (0x10081000 + (_v)) #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace bananarchy { namespace { int64_t monotonicMs() { struct timespec ts {}; clock_gettime(CLOCK_MONOTONIC, &ts); return static_cast(ts.tv_sec) * 1000 + ts.tv_nsec / 1000000; } void popUtf8Char(std::string& s) { if (s.empty()) return; while (!s.empty() && (static_cast(s.back()) & 0xC0) == 0x80) { s.pop_back(); } if (!s.empty()) s.pop_back(); } std::vector splitPipeList(const char* raw) { std::vector out; if (!raw || !raw[0]) return out; std::string s(raw); size_t start = 0; while (start <= s.size()) { size_t bar = s.find('|', start); if (bar == std::string::npos) { out.push_back(s.substr(start)); break; } out.push_back(s.substr(start, bar - start)); start = bar + 1; } return out; } constexpr const char* kMultiTapPunct1 = ".,-_!?/@:;'\"+=*#$%^&()[]{}<>|\\~`1"; constexpr const char* kMultiTapStar = "*#+-=_/\\|~`@$%^&()[]{}<>'\".,!?:;"; const char* kAlphaTapTable[11] = { " 0+", kMultiTapPunct1, "abc2", "def3", "ghi4", "jkl5", "mno6", "pqrs7", "tuv8", "wxyz9", kMultiTapStar }; const char* kSymTapTable[11] = { " _0", ".,:;!?-_1", "\"'`~@#2", "()[]{}<>3", "+-*/=%4", "|&^#$5", "_\\/$@6", "=<>!~7", "();,\"8", "{}[]#9", kMultiTapStar }; int querySoftkeysMask(Display* d) { if (!d) return 0; char km[32]; if (!XQueryKeymap(d, km)) return 0; int mask = 0; if (km[135 / 8] & (1 << (135 % 8))) mask |= 1; if (km[166 / 8] & (1 << (166 % 8))) mask |= 2; return mask; } void writeSoftkeySuppressFile(int64_t untilMs) { int fd = ::open("/tmp/sxmo_softkey_suppress", O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); if (fd >= 0) { char buf[32]; int len = std::snprintf(buf, sizeof(buf), "%lld\n", static_cast(untilMs)); (void)::write(fd, buf, len); ::close(fd); } } bool sendPluginFifoMsg(const char* name, const std::string& cmdLine) { if (!name || !name[0]) return false; std::string pidPath = std::string("/tmp/dwm_plugin_") + name + ".pid"; int pfd = ::open(pidPath.c_str(), O_RDONLY | O_CLOEXEC); if (pfd < 0) return false; char pbuf[32]; ssize_t n = ::read(pfd, pbuf, sizeof(pbuf) - 1); ::close(pfd); if (n <= 0) return false; pbuf[n] = '\0'; int pid = std::atoi(pbuf); if (pid <= 0 || pid == static_cast(::getpid()) || ::kill(pid, 0) != 0) { return false; } std::string fifoPath = std::string("/tmp/dwm_plugin_") + name + ".fifo"; int fd = -1; for (int attempt = 0; attempt < 6; ++attempt) { fd = ::open(fifoPath.c_str(), O_WRONLY | O_NONBLOCK | O_CLOEXEC); if (fd >= 0) break; ::usleep(20000); } if (fd < 0) return false; std::string msg = cmdLine + "\n"; ssize_t w = ::write(fd, msg.data(), msg.size()); ::close(fd); return w == static_cast(msg.size()); } int mapHardwareKey(KeySym sym, unsigned int keycode, unsigned int state) { if (keycode == 135 || sym == XK_Super_L || sym == XK_Menu || static_cast(sym) == _EVDEVK(0x8b)) { return NEO_KEY_SOFT_LEFT; } if (keycode == 166 || sym == XF86XK_Back || static_cast(sym) == _EVDEVK(0x9e)) { return NEO_KEY_SOFT_RIGHT; } if (sym == XK_Up || sym == XK_KP_Up) return NEO_KEY_UP; if (sym == XK_Down || sym == XK_KP_Down) return NEO_KEY_DOWN; if (sym == XK_Left || sym == XK_KP_Left) return NEO_KEY_LEFT; if (sym == XK_Right || sym == XK_KP_Right) return NEO_KEY_RIGHT; if (sym == XK_Return || sym == XK_KP_Enter || sym == XK_ISO_Enter) { return NEO_KEY_OK; } if (sym == XK_BackSpace || sym == XK_Delete || sym == XK_KP_Delete) { return NEO_KEY_BACK; } if (keycode == 239 || keycode == 172 || sym == XF86XK_Send || sym == XF86XK_Phone || sym == XF86XK_AudioPlay || sym == XK_F1 || static_cast(sym) == _EVDEVK(0xe7)) { return NEO_KEY_CALL; } if (sym == XK_Escape || sym == XF86XK_PowerOff || sym == XF86XK_HangupPhone || sym == XK_F4 || static_cast(sym) == _EVDEVK(0x6b)) { return NEO_KEY_END; } if (!(state & (ControlMask | Mod1Mask | Mod4Mask))) { if (keycode == 63 || keycode == 530 || sym == XK_asterisk || sym == XK_KP_Multiply || static_cast(sym) == 0x1008ffaa) { return NEO_KEY_STAR; } if (keycode == 106 || keycode == 531 || sym == XK_numbersign || sym == XK_KP_Divide || static_cast(sym) == 0x1008ffab) { return NEO_KEY_HASH; } if (sym == XK_plus || sym == XK_KP_Add) { return NEO_KEY_PLUS; } if (sym >= XK_0 && sym <= XK_9) { return static_cast('0' + (sym - XK_0)); } if (sym >= XK_KP_0 && sym <= XK_KP_9) { return static_cast('0' + (sym - XK_KP_0)); } if (keycode >= 10 && keycode <= 18) { return static_cast('1' + (keycode - 10)); } if (keycode == 19) { return static_cast('0'); } } return NEO_KEY_NONE; } } // namespace // --------------------------------------------------------------------------- // ThemeSpec & PluginTheme implementation // --------------------------------------------------------------------------- std::string themeTrim(const std::string& s) { size_t b = 0; while (b < s.size() && std::isspace(static_cast(s[b]))) { ++b; } size_t e = s.size(); while (e > b && std::isspace(static_cast(s[e - 1]))) { --e; } if (e >= b + 2 && ((s[b] == '"' && s[e - 1] == '"') || (s[b] == '\'' && s[e - 1] == '\''))) { return s.substr(b + 1, e - b - 2); } return s.substr(b, e - b); } int themeHexNibble(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return 10 + (c - 'a'); if (c >= 'A' && c <= 'F') return 10 + (c - 'A'); return -1; } bool parseHexRgb(const std::string& raw, uint32_t* outRgb) { if (!outRgb) return false; std::string s = themeTrim(raw); if (s.rfind("0x", 0) == 0 || s.rfind("0X", 0) == 0) { s = "#" + s.substr(2); } if (s.size() == 7 && s[0] == '#') { uint32_t v = 0; for (int i = 1; i < 7; ++i) { int n = themeHexNibble(s[i]); if (n < 0) return false; v = (v << 4) | static_cast(n); } *outRgb = v; return true; } if (s.size() == 4 && s[0] == '#') { int r = themeHexNibble(s[1]); int g = themeHexNibble(s[2]); int b = themeHexNibble(s[3]); if (r < 0 || g < 0 || b < 0) return false; *outRgb = static_cast(((r * 17) << 16) | ((g * 17) << 8) | (b * 17)); return true; } return false; } std::string formatHexRgb(uint32_t rgb) { char buf[16]; std::snprintf(buf, sizeof(buf), "#%06x", static_cast(rgb & 0xffffffu)); return buf; } uint32_t adjustRgb(uint32_t rgb, int delta) { int r = std::clamp(static_cast((rgb >> 16) & 0xff) + delta, 0, 255); int g = std::clamp(static_cast((rgb >> 8) & 0xff) + delta, 0, 255); int b = std::clamp(static_cast(rgb & 0xff) + delta, 0, 255); return static_cast((r << 16) | (g << 8) | b); } uint32_t blendRgb(uint32_t c1, uint32_t c2, int weight2Pct) { int w2 = std::clamp(weight2Pct, 0, 100); int w1 = 100 - w2; int r = (((c1 >> 16) & 0xff) * w1 + ((c2 >> 16) & 0xff) * w2) / 100; int g = (((c1 >> 8) & 0xff) * w1 + ((c2 >> 8) & 0xff) * w2) / 100; int b = ((c1 & 0xff) * w1 + (c2 & 0xff) * w2) / 100; return static_cast((std::clamp(r, 0, 255) << 16) | (std::clamp(g, 0, 255) << 8) | std::clamp(b, 0, 255)); } std::string getHomeDirPath() { if (::access("/tmp/bananarchy_duress_mode", F_OK) == 0) { return "/tmp/duress_home"; } const char* h = std::getenv("HOME"); return (h && h[0]) ? h : "/home/user"; } std::string getXresourcesPath() { return getHomeDirPath() + "/.Xresources"; } std::string getThemesDirPath() { return getHomeDirPath() + "/.xthemes"; } int ThemeSpec::sizeSmall() const { return std::max(8, static_cast(std::lround(baseFontSize * 12.0 / 15.0))); } int ThemeSpec::sizeMain() const { return std::clamp(baseFontSize, 10, 24); } int ThemeSpec::sizeIcon() const { return std::max(10, static_cast(std::lround(baseFontSize * 16.0 / 15.0))); } int ThemeSpec::sizeLarge() const { return std::max(11, static_cast(std::lround(baseFontSize * 18.0 / 15.0))); } std::string ThemeSpec::pangoMainFontStr() const { return fontFace + ", " + iconFontFace + " " + std::to_string(sizeMain()) + "px"; } std::string ThemeSpec::pangoSmallFontStr() const { return fontFace + ", " + iconFontFace + " " + std::to_string(sizeSmall()) + "px"; } std::string ThemeSpec::pangoIconFontStr() const { return iconFontFace + ", " + fontFace + " " + std::to_string(sizeIcon()) + "px"; } std::string ThemeSpec::pangoLargeBoldFontStr() const { return fontFace + ", " + iconFontFace + " Bold " + std::to_string(sizeLarge()) + "px"; } std::string ThemeSpec::xftFontStr(int pxSize) const { return fontFace + ":pixelsize=" + std::to_string(pxSize) + ":style=Regular:antialias=true:autohint=true"; } std::string ThemeSpec::xftIconFontStr(int pxSize) const { return iconFontFace + ":pixelsize=" + std::to_string(pxSize) + ":style=Regular:antialias=true:autohint=true"; } void ThemeSpec::recomputeDerivedFromCore() { int luma = (((bgMain >> 16) & 0xff) * 299 + ((bgMain >> 8) & 0xff) * 587 + (bgMain & 0xff) * 114) / 1000; int dir = (luma > 140) ? -1 : 1; bgBar = bgMain; bgHeader = adjustRgb(bgMain, -dir * 6); bgFooter = adjustRgb(bgMain, -dir * 10); bgOverlay = adjustRgb(bgMain, -dir * 12); bgAltEven = adjustRgb(bgMain, dir * 6); bgAltOdd = adjustRgb(bgMain, dir * 12); bgInput = adjustRgb(bgMain, -dir * 8); bgInputFocus = blendRgb(bgMain, selBg, 40); bgButton = adjustRgb(bgMain, dir * 8); bgSearch = adjustRgb(bgMain, dir * 22); bgBubbleIn = blendRgb(bgMain, success, 14); bgBubbleOut = blendRgb(bgMain, selBg, 26); bgToast = blendRgb(bgOverlay, selBg, 35); int fgLuma = (((fgMain >> 16) & 0xff) * 299 + ((fgMain >> 8) & 0xff) * 587 + (fgMain & 0xff) * 114) / 1000; fgBright = (fgLuma > 128) ? 0xffffff : 0x000000; fgMuted = blendRgb(fgMain, bgMain, 45); accentAlt = adjustRgb(selBg, 48); highlight = blendRgb(accent, 0xffffff, 30); border = adjustRgb(bgMain, dir * 34); divider = adjustRgb(bgMain, dir * 68); } void ThemeSpec::parseFromMap( const std::unordered_map& kv) { auto getStr = [&](const char* k1, const char* k2 = nullptr, const char* k3 = nullptr) -> std::string { auto it = kv.find(k1); if (it != kv.end() && !it->second.empty()) return it->second; if (k2) { it = kv.find(k2); if (it != kv.end() && !it->second.empty()) return it->second; } if (k3) { it = kv.find(k3); if (it != kv.end() && !it->second.empty()) return it->second; } return ""; }; std::string nm = getStr("theme.name", "*themeName"); if (!nm.empty()) name = nm; std::string ff = getStr("theme.fontFace", "*fontFace"); if (!ff.empty()) { fontFace = ff; } else { std::string dwmFont = getStr("dwm.font"); if (!dwmFont.empty()) { size_t comma = dwmFont.find(','); if (comma != std::string::npos) { fontFace = themeTrim(dwmFont.substr(0, comma)); } } } std::string iff = getStr("theme.iconFontFace", "*iconFontFace"); if (!iff.empty()) iconFontFace = iff; std::string bfs = getStr("theme.baseFontSize", "*baseFontSize"); if (!bfs.empty()) { int sz = std::atoi(bfs.c_str()); if (sz >= 10 && sz <= 24) baseFontSize = sz; } else { std::string dwmFont = getStr("dwm.font"); size_t pxPos = dwmFont.rfind("px"); if (pxPos != std::string::npos && pxPos > 0) { size_t sp = pxPos; while (sp > 0 && std::isdigit(static_cast(dwmFont[sp - 1]))) { --sp; } if (sp < pxPos) { int sz = std::atoi(dwmFont.substr(sp, pxPos - sp).c_str()); if (sz >= 10 && sz <= 24) baseFontSize = sz; } } } auto getCol = [&](uint32_t* dst, const char* k1, const char* k2 = nullptr, const char* k3 = nullptr) -> bool { std::string s = getStr(k1, k2, k3); if (s.empty()) return false; uint32_t v = 0; if (parseHexRgb(s, &v)) { *dst = v; return true; } return false; }; (void)getCol(&bgMain, "theme.bgMain", "*background", "dmenu.background"); (void)getCol(&fgMain, "theme.fgMain", "*foreground", "dwm.normfgcolor"); (void)getCol(&selBg, "theme.selBg", "dmenu.selbackground", "dwm.selbgcolor"); (void)getCol(&selFg, "theme.selFg", "dmenu.selforeground", "dwm.selfgcolor"); (void)getCol(&accent, "theme.accent", "*accentColor", "st.cursorColor"); recomputeDerivedFromCore(); getCol(&bgBar, "theme.bgBar", "dwm.background", "dwm.normbgcolor"); getCol(&bgHeader, "theme.bgHeader", "dmenu.background", "st.background"); getCol(&bgFooter, "theme.bgFooter"); getCol(&bgOverlay, "theme.bgOverlay"); getCol(&bgAltEven, "theme.bgAltEven"); getCol(&bgAltOdd, "theme.bgAltOdd"); getCol(&bgInput, "theme.bgInput"); getCol(&bgInputFocus, "theme.bgInputFocus"); getCol(&bgButton, "theme.bgButton"); getCol(&bgSearch, "theme.bgSearch", "dmenu.outbackground"); getCol(&bgBubbleIn, "theme.bgBubbleIn"); getCol(&bgBubbleOut, "theme.bgBubbleOut"); getCol(&bgToast, "theme.bgToast"); getCol(&fgBright, "theme.fgBright", "dmenu.selforeground"); getCol(&fgMuted, "theme.fgMuted"); getCol(&accentAlt, "theme.accentAlt"); getCol(&highlight, "theme.highlight", "dmenu.highlight"); getCol(&border, "theme.border", "dwm.border", "dwm.normbordercolor"); getCol(÷r, "theme.divider"); getCol(&success, "theme.success"); getCol(&info, "theme.info"); getCol(&warning, "theme.warning"); getCol(&danger, "theme.danger"); getCol(&dangerBg, "theme.dangerBg"); } void ThemeSpec::parseLinesIntoMap( const std::string& content, std::unordered_map& kv) { std::istringstream ss(content); std::string line; while (std::getline(ss, line)) { std::string t = themeTrim(line); if (t.empty() || t[0] == '!' || t[0] == '#') continue; size_t colon = t.find(':'); if (colon == std::string::npos) continue; std::string key = themeTrim(t.substr(0, colon)); std::string val = themeTrim(t.substr(colon + 1)); if (!key.empty() && !val.empty()) { kv[key] = val; } } } bool ThemeSpec::loadFromFile(const std::string& path) { std::ifstream in(path); if (!in.is_open()) return false; std::ostringstream ss; ss << in.rdbuf(); std::unordered_map kv; parseLinesIntoMap(ss.str(), kv); parseFromMap(kv); return true; } void ThemeSpec::loadActive(Display* dpy, int screen) { std::unordered_map kv; if (dpy) { Atom actualType = None; int actualFormat = 0; unsigned long nitems = 0, bytesAfter = 0; unsigned char* prop = nullptr; if (XGetWindowProperty(dpy, RootWindow(dpy, screen), XA_RESOURCE_MANAGER, 0L, 65536L, False, XA_STRING, &actualType, &actualFormat, &nitems, &bytesAfter, &prop) == Success && prop) { if (actualType == XA_STRING && actualFormat == 8 && nitems > 0) { std::string resStr(reinterpret_cast(prop), nitems); parseLinesIntoMap(resStr, kv); } XFree(prop); } } std::ifstream in(getXresourcesPath()); if (in.is_open()) { std::ostringstream ss; ss << in.rdbuf(); parseLinesIntoMap(ss.str(), kv); } if (!kv.empty()) { parseFromMap(kv); } } std::string ThemeSpec::serializeXresources() const { std::ostringstream out; out << "! Space to setup configversion\n"; out << "! configversion: 7bff124b2de16292fe6e7a7e5d3322ae\n"; out << "! Bananarchy Unified Theme: " << name << "\n\n"; out << "theme.name: " << name << "\n"; out << "theme.fontFace: " << fontFace << "\n"; out << "theme.iconFontFace: " << iconFontFace << "\n"; out << "theme.baseFontSize: " << sizeMain() << "\n\n"; out << "theme.bgMain: " << formatHexRgb(bgMain) << "\n"; out << "theme.bgBar: " << formatHexRgb(bgBar) << "\n"; out << "theme.bgHeader: " << formatHexRgb(bgHeader) << "\n"; out << "theme.bgFooter: " << formatHexRgb(bgFooter) << "\n"; out << "theme.bgOverlay: " << formatHexRgb(bgOverlay) << "\n"; out << "theme.bgAltEven: " << formatHexRgb(bgAltEven) << "\n"; out << "theme.bgAltOdd: " << formatHexRgb(bgAltOdd) << "\n"; out << "theme.bgInput: " << formatHexRgb(bgInput) << "\n"; out << "theme.bgInputFocus: " << formatHexRgb(bgInputFocus) << "\n"; out << "theme.bgButton: " << formatHexRgb(bgButton) << "\n"; out << "theme.bgSearch: " << formatHexRgb(bgSearch) << "\n"; out << "theme.bgBubbleIn: " << formatHexRgb(bgBubbleIn) << "\n"; out << "theme.bgBubbleOut: " << formatHexRgb(bgBubbleOut) << "\n"; out << "theme.bgToast: " << formatHexRgb(bgToast) << "\n\n"; out << "theme.fgMain: " << formatHexRgb(fgMain) << "\n"; out << "theme.fgBright: " << formatHexRgb(fgBright) << "\n"; out << "theme.fgMuted: " << formatHexRgb(fgMuted) << "\n\n"; out << "theme.selBg: " << formatHexRgb(selBg) << "\n"; out << "theme.selFg: " << formatHexRgb(selFg) << "\n"; out << "theme.accent: " << formatHexRgb(accent) << "\n"; out << "theme.accentAlt: " << formatHexRgb(accentAlt) << "\n"; out << "theme.highlight: " << formatHexRgb(highlight) << "\n"; out << "theme.border: " << formatHexRgb(border) << "\n"; out << "theme.divider: " << formatHexRgb(divider) << "\n\n"; out << "theme.success: " << formatHexRgb(success) << "\n"; out << "theme.info: " << formatHexRgb(info) << "\n"; out << "theme.warning: " << formatHexRgb(warning) << "\n"; out << "theme.danger: " << formatHexRgb(danger) << "\n"; out << "theme.dangerBg: " << formatHexRgb(dangerBg) << "\n\n"; out << "dmenu.font: " << xftFontStr(sizeLarge()) << "\n"; out << "dmenu.background: " << formatHexRgb(bgHeader) << "\n"; out << "dmenu.foreground: " << formatHexRgb(fgBright) << "\n"; out << "dmenu.selbackground: " << formatHexRgb(selBg) << "\n"; out << "dmenu.selforeground: " << formatHexRgb(selFg) << "\n"; out << "dmenu.outbackground: " << formatHexRgb(bgSearch) << "\n"; out << "dmenu.outforeground: " << formatHexRgb(fgBright) << "\n"; out << "dmenu.highlight: " << formatHexRgb(highlight) << "\n\n"; out << "dwm.font: " << pangoMainFontStr() << "\n"; out << "dwm.background: " << formatHexRgb(bgBar) << "\n"; out << "dwm.foreground: " << formatHexRgb(fgMain) << "\n"; out << "dwm.border: " << formatHexRgb(border) << "\n"; out << "dwm.selbackground: " << formatHexRgb(selBg) << "\n"; out << "dwm.selforeground: " << formatHexRgb(selFg) << "\n"; out << "dwm.selborder: " << formatHexRgb(selBg) << "\n"; out << "dwm.normbgcolor: " << formatHexRgb(bgBar) << "\n"; out << "dwm.normbordercolor: " << formatHexRgb(border) << "\n"; out << "dwm.normfgcolor: " << formatHexRgb(fgMain) << "\n"; out << "dwm.selbgcolor: " << formatHexRgb(selBg) << "\n"; out << "dwm.selbordercolor: " << formatHexRgb(selBg) << "\n"; out << "dwm.selfgcolor: " << formatHexRgb(selFg) << "\n\n"; out << "st.font: " << xftFontStr(sizeLarge()) << "\n"; out << "st.termname: xterm-256color\n"; out << "st.background: " << formatHexRgb(bgHeader) << "\n"; out << "st.foreground: " << formatHexRgb(fgMain) << "\n"; out << "st.cursorColor: " << formatHexRgb(accent) << "\n\n"; out << "svkbd.font: " << fontFace << ":pixelsize=" << sizeSmall() << "\n"; return out.str(); } bool ThemeSpec::saveToFile(const std::string& path) const { std::ofstream out(path, std::ios::trunc); if (!out.is_open()) return false; out << serializeXresources(); return true; } uint32_t ThemeSpec::colorById(int colorId) const { switch (colorId) { case NEO_COLOR_BG_MAIN: return bgMain; case NEO_COLOR_BG_BAR: return bgBar; case NEO_COLOR_BG_HEADER: return bgHeader; case NEO_COLOR_BG_FOOTER: return bgFooter; case NEO_COLOR_BG_OVERLAY: return bgOverlay; case NEO_COLOR_BG_ALT_EVEN: return bgAltEven; case NEO_COLOR_BG_ALT_ODD: return bgAltOdd; case NEO_COLOR_BG_INPUT: return bgInput; case NEO_COLOR_BG_INPUT_FOCUS: return bgInputFocus; case NEO_COLOR_BG_BUTTON: return bgButton; case NEO_COLOR_BG_SEARCH: return bgSearch; case NEO_COLOR_BG_BUBBLE_IN: return bgBubbleIn; case NEO_COLOR_BG_BUBBLE_OUT: return bgBubbleOut; case NEO_COLOR_BG_TOAST: return bgToast; case NEO_COLOR_FG_MAIN: return fgMain; case NEO_COLOR_FG_BRIGHT: return fgBright; case NEO_COLOR_FG_MUTED: return fgMuted; case NEO_COLOR_SEL_BG: return selBg; case NEO_COLOR_SEL_FG: return selFg; case NEO_COLOR_ACCENT: return accent; case NEO_COLOR_ACCENT_ALT: return accentAlt; case NEO_COLOR_HIGHLIGHT: return highlight; case NEO_COLOR_BORDER: return border; case NEO_COLOR_DIVIDER: return divider; case NEO_COLOR_SUCCESS: return success; case NEO_COLOR_INFO: return info; case NEO_COLOR_WARNING: return warning; case NEO_COLOR_DANGER: return danger; case NEO_COLOR_DANGER_BG: return dangerBg; default: return bgMain; } } ThemeSpec loadThemeSpec(Display* dpy, int screen) { ThemeSpec spec; spec.loadActive(dpy, screen); return spec; } void PluginTheme::allocXft(Display* dpy, Visual* visual, Colormap cmap, uint32_t rgb, XftColor* dst) { std::string hex = formatHexRgb(rgb); XftColorAllocName(dpy, visual, cmap, hex.c_str(), dst); } void PluginTheme::init(Display* dpy, int screen, Visual* visual, Colormap cmap, Window win) { dpy_ = dpy; screen_ = screen; visual_ = visual; cmap_ = cmap; win_ = win; if (!pangoCtx && dpy) { PangoFontMap* fontMap = pango_xft_get_font_map(dpy, screen); pangoCtx = pango_font_map_create_context(fontMap); layoutMain = pango_layout_new(pangoCtx); layoutSmall = pango_layout_new(pangoCtx); layoutIcon = pango_layout_new(pangoCtx); layoutNum = pango_layout_new(pangoCtx); } reload(); } void PluginTheme::reload() { if (dpy_ && visual_) { load(dpy_, screen_, visual_, cmap_, layoutMain, layoutSmall, layoutIcon, layoutNum, win_); } } void PluginTheme::load(Display* dpy, int screen, Visual* visual, Colormap cmap, PangoLayout* lMain, PangoLayout* lSmall, PangoLayout* lIcon, PangoLayout* lNum, Window win) { dpy_ = dpy; screen_ = screen; visual_ = visual; cmap_ = cmap; if (win != None) win_ = win; if (lMain) layoutMain = lMain; if (lSmall) layoutSmall = lSmall; if (lIcon) layoutIcon = lIcon; if (lNum) layoutNum = lNum; struct stat st {}; if (::stat(getXresourcesPath().c_str(), &st) == 0) { lastXresMtime = st.st_mtim.tv_sec; lastXresSize = st.st_size; } spec = ThemeSpec{}; spec.loadActive(dpy, screen); if (colorsAllocated) { XftColorFree(dpy, visual, cmap, &colWhite); XftColorFree(dpy, visual, cmap, &colLight); XftColorFree(dpy, visual, cmap, &colMuted); XftColorFree(dpy, visual, cmap, &colYellow); XftColorFree(dpy, visual, cmap, &colGreen); XftColorFree(dpy, visual, cmap, &colBlue); XftColorFree(dpy, visual, cmap, &colOrange); XftColorFree(dpy, visual, cmap, &colRed); } allocXft(dpy, visual, cmap, spec.fgBright, &colWhite); allocXft(dpy, visual, cmap, spec.fgMain, &colLight); allocXft(dpy, visual, cmap, spec.fgMuted, &colMuted); allocXft(dpy, visual, cmap, spec.accent, &colYellow); allocXft(dpy, visual, cmap, spec.success, &colGreen); allocXft(dpy, visual, cmap, spec.info, &colBlue); allocXft(dpy, visual, cmap, spec.warning, &colOrange); allocXft(dpy, visual, cmap, spec.danger, &colRed); colorsAllocated = true; if (layoutMain) { PangoFontDescription* d = pango_font_description_from_string(spec.pangoMainFontStr().c_str()); pango_layout_set_font_description(layoutMain, d); pango_font_description_free(d); } if (layoutSmall) { PangoFontDescription* d = pango_font_description_from_string(spec.pangoSmallFontStr().c_str()); pango_layout_set_font_description(layoutSmall, d); pango_font_description_free(d); } if (layoutIcon) { PangoFontDescription* d = pango_font_description_from_string(spec.pangoIconFontStr().c_str()); pango_layout_set_font_description(layoutIcon, d); pango_font_description_free(d); } if (layoutNum) { PangoFontDescription* d = pango_font_description_from_string( spec.pangoLargeBoldFontStr().c_str()); pango_layout_set_font_description(layoutNum, d); pango_font_description_free(d); } if (win_ != None) { XSetWindowBackground(dpy, win_, spec.bgMain); XSetWindowBorder(dpy, win_, spec.selBg); } } bool PluginTheme::checkAndReload() { if (!dpy_ || !visual_) return false; return checkAndReload(dpy_, screen_, visual_, cmap_, layoutMain, layoutSmall, layoutIcon, layoutNum, win_); } bool PluginTheme::checkAndReload(Display* dpy, int screen, Visual* visual, Colormap cmap, PangoLayout* lMain, PangoLayout* lSmall, PangoLayout* lIcon, PangoLayout* lNum, Window win) { struct stat st {}; if (::stat(getXresourcesPath().c_str(), &st) == 0) { if (st.st_mtim.tv_sec != lastXresMtime || st.st_size != lastXresSize) { load(dpy, screen, visual, cmap, lMain, lSmall, lIcon, lNum, win); return true; } } return false; } XftColor* PluginTheme::colorByRole(int role) { switch (role) { case NEO_TEXT_WHITE: return &colWhite; case NEO_TEXT_LIGHT: return &colLight; case NEO_TEXT_MUTED: return &colMuted; case NEO_TEXT_YELLOW: return &colYellow; case NEO_TEXT_GREEN: return &colGreen; case NEO_TEXT_BLUE: return &colBlue; case NEO_TEXT_ORANGE: return &colOrange; case NEO_TEXT_RED: return &colRed; default: return &colLight; } } PangoLayout* PluginTheme::layoutByRole(int role) { switch (role) { case NEO_FONT_SMALL: return layoutSmall; case NEO_FONT_MAIN: return layoutMain; case NEO_FONT_ICON: return layoutIcon; case NEO_FONT_LARGE: return layoutNum ? layoutNum : layoutMain; default: return layoutMain; } } // --------------------------------------------------------------------------- // Shared Pango, Widget & Multi-Tap Helpers // --------------------------------------------------------------------------- int neoDrawPango(XftDraw* xftDraw, PangoLayout* layout, XftColor* color, int x, int y, int h, const std::string& text, int maxW, int align) { if (!xftDraw || !layout || !color) return 0; pango_layout_set_text(layout, text.c_str(), static_cast(text.size())); if (maxW > 0) { pango_layout_set_width(layout, maxW * PANGO_SCALE); pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_END); } else { pango_layout_set_width(layout, -1); pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_NONE); } PangoRectangle ink{}, logical{}; pango_layout_get_pixel_extents(layout, &ink, &logical); int ty = y + (h - logical.height) / 2; int tx = x; if (align == 1 && maxW > 0) { tx = x + (maxW - logical.width) / 2; } else if (align == 2 && maxW > 0) { tx = x + maxW - logical.width; } pango_xft_render_layout(xftDraw, color, layout, tx * PANGO_SCALE, ty * PANGO_SCALE); return logical.width; } int neoPangoWidth(PangoLayout* layout, const std::string& text) { if (!layout) return 0; pango_layout_set_width(layout, -1); pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_NONE); pango_layout_set_text(layout, text.c_str(), static_cast(text.size())); PangoRectangle ink{}, logical{}; pango_layout_get_pixel_extents(layout, &ink, &logical); return logical.width; } void neoDrawSoftbar(Display* dpy, Pixmap pix, GC gc, XftDraw* xftDraw, PluginTheme& theme, int winW, int winH, int softbarH, const std::string& leftLabel, const std::string& centerLabel, const std::string& rightLabel, XftColor* centerCol) { if (!dpy || pix == None || !gc || !xftDraw) return; int sbY = winH - softbarH; XSetForeground(dpy, gc, theme.spec.bgFooter); XFillRectangle(dpy, pix, gc, 0, sbY, winW, softbarH); XSetForeground(dpy, gc, theme.spec.border); XFillRectangle(dpy, pix, gc, 0, sbY, winW, 1); if (!leftLabel.empty()) { neoDrawPango(xftDraw, theme.layoutMain, &theme.colLight, 6, sbY + 1, softbarH - 1, leftLabel); } if (!centerLabel.empty()) { int cw = neoPangoWidth(theme.layoutMain, centerLabel); neoDrawPango(xftDraw, theme.layoutMain, centerCol ? centerCol : &theme.colGreen, (winW - cw) / 2, sbY + 1, softbarH - 1, centerLabel); } if (!rightLabel.empty()) { int rw = neoPangoWidth(theme.layoutMain, rightLabel); neoDrawPango(xftDraw, theme.layoutMain, &theme.colLight, winW - rw - 6, sbY + 1, softbarH - 1, rightLabel); } } void neoDrawScrollbar(Display* dpy, Pixmap pix, GC gc, const PluginTheme& theme, int x, int y, int h, int totalItems, int visibleItems, int scrollOffset) { if (!dpy || pix == None || !gc || totalItems <= visibleItems || visibleItems <= 0 || h <= 0) { return; } int sbH = std::max(14, (h * visibleItems) / totalItems); int maxOff = std::max(1, totalItems - visibleItems); int clampedOff = std::clamp(scrollOffset, 0, maxOff); int sbY = y + ((h - sbH) * clampedOff) / maxOff; XSetForeground(dpy, gc, theme.spec.divider); XFillRectangle(dpy, pix, gc, x, sbY, 3, sbH); } void neoDrawToast(Display* dpy, Pixmap pix, GC gc, XftDraw* xftDraw, PluginTheme& theme, int winW, int winH, int softbarH, const std::string& msg) { if (!dpy || pix == None || !gc || !xftDraw || msg.empty()) return; int ty = winH - softbarH - 26; XSetForeground(dpy, gc, theme.spec.bgToast); XFillRectangle(dpy, pix, gc, 6, ty, winW - 12, 22); XSetForeground(dpy, gc, theme.spec.accent); XDrawRectangle(dpy, pix, gc, 6, ty, winW - 13, 21); neoDrawPango(xftDraw, theme.layoutSmall, &theme.colWhite, 12, ty, 22, msg, winW - 24); } std::string formatMultiTapBar(const std::string& prefix, const char* table, int activeIdx, bool makeUpper, int maxItems, size_t maxChars) { if (!table || !table[0]) return ""; int total = static_cast(std::strlen(table)); if (total <= 0) return ""; activeIdx = std::clamp(activeIdx, 0, total - 1); std::vector labels; labels.reserve(total); for (int i = 0; i < total; ++i) { char c = table[i]; if (c == ' ') { labels.push_back("SPC"); } else if (c == '\n') { labels.push_back("NL"); } else if (c == '\t') { labels.push_back("TAB"); } else { if (makeUpper && std::isalpha(static_cast(c))) { c = static_cast(std::toupper(static_cast(c))); } labels.push_back(std::string(1, c)); } } int halfWin = std::max(1, maxItems / 2); int start = std::max(0, activeIdx - halfWin); int end = start; size_t width = 0; int count = 0; while (start <= activeIdx) { width = 0; count = 0; end = start; while (end < total && count < maxItems) { size_t iw = labels[end].size() + 2; if (count > 0 && width + iw > maxChars) break; width += iw; ++end; ++count; } if (activeIdx < end) break; ++start; } while (start > 0 && count < maxItems) { size_t iw = labels[start - 1].size() + 2; if (width + iw > maxChars) break; --start; width += iw; ++count; } std::string out = prefix; out += (start > 0) ? "<" : " "; for (int i = start; i < end; ++i) { if (i == activeIdx) { out += "[" + labels[i] + "]"; } else { out += " " + labels[i] + " "; } } if (end < total) { out += ">"; } return out; } std::string tailFitPangoText(PangoLayout* layout, const std::string& text, int maxWidthPx) { if (!layout || text.empty() || maxWidthPx <= 0) return text; pango_layout_set_width(layout, -1); pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_NONE); pango_layout_set_text(layout, text.c_str(), static_cast(text.size())); int w = 0, h = 0; pango_layout_get_pixel_size(layout, &w, &h); if (w <= maxWidthPx) return text; size_t pos = 0; while (pos < text.size()) { pos++; while (pos < text.size() && (static_cast(text[pos]) & 0xC0) == 0x80) { pos++; } std::string candidate = ".." + text.substr(pos); pango_layout_set_text(layout, candidate.c_str(), static_cast(candidate.size())); pango_layout_get_pixel_size(layout, &w, &h); if (w <= maxWidthPx) { return candidate; } } return text; } // --------------------------------------------------------------------------- // Shared Image & Media Helpers // --------------------------------------------------------------------------- struct JpegErrMgr { struct jpeg_error_mgr pub; jmp_buf setjmpBuf; }; static void jpegErrorExit(j_common_ptr cinfo) { JpegErrMgr* myerr = reinterpret_cast(cinfo->err); longjmp(myerr->setjmpBuf, 1); } bool saveRgb24AsJpeg(const std::string& path, const uint8_t* rgb, int width, int height, int quality) { if (!rgb || width <= 0 || height <= 0) return false; FILE* fp = std::fopen(path.c_str(), "wb"); if (!fp) return false; struct jpeg_compress_struct cinfo {}; JpegErrMgr jerr {}; cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = jpegErrorExit; if (setjmp(jerr.setjmpBuf)) { jpeg_destroy_compress(&cinfo); std::fclose(fp); return false; } jpeg_create_compress(&cinfo); jpeg_stdio_dest(&cinfo, fp); cinfo.image_width = static_cast(width); cinfo.image_height = static_cast(height); cinfo.input_components = 3; cinfo.in_color_space = JCS_RGB; jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, quality, TRUE); jpeg_start_compress(&cinfo, TRUE); int rowStride = width * 3; while (cinfo.next_scanline < cinfo.image_height) { JSAMPROW rowPtr = const_cast(rgb + cinfo.next_scanline * rowStride); jpeg_write_scanlines(&cinfo, &rowPtr, 1); } jpeg_finish_compress(&cinfo); jpeg_destroy_compress(&cinfo); std::fclose(fp); return true; } bool loadJpegRgb24(const std::string& path, std::vector* outRgb, int* outW, int* outH) { if (!outRgb || !outW || !outH) return false; FILE* fp = std::fopen(path.c_str(), "rb"); if (!fp) return false; struct jpeg_decompress_struct cinfo {}; JpegErrMgr jerr {}; cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = jpegErrorExit; if (setjmp(jerr.setjmpBuf)) { jpeg_destroy_decompress(&cinfo); std::fclose(fp); return false; } jpeg_create_decompress(&cinfo); jpeg_stdio_src(&cinfo, fp); if (jpeg_read_header(&cinfo, TRUE) != JPEG_HEADER_OK) { jpeg_destroy_decompress(&cinfo); std::fclose(fp); return false; } if (cinfo.image_width > 960 || cinfo.image_height > 960) { cinfo.scale_num = 1; cinfo.scale_denom = 2; } cinfo.out_color_space = JCS_RGB; jpeg_start_decompress(&cinfo); int w = static_cast(cinfo.output_width); int h = static_cast(cinfo.output_height); if (w <= 0 || h <= 0 || w > 8192 || h > 8192) { jpeg_destroy_decompress(&cinfo); std::fclose(fp); return false; } outRgb->resize(static_cast(w) * h * 3); int rowStride = w * 3; while (cinfo.output_scanline < cinfo.output_height) { JSAMPROW rowPtr = outRgb->data() + cinfo.output_scanline * rowStride; jpeg_read_scanlines(&cinfo, &rowPtr, 1); } jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); std::fclose(fp); *outW = w; *outH = h; return true; } bool loadPngRgb24(const std::string& path, std::vector* outRgb, int* outW, int* outH) { if (!outRgb || !outW || !outH) return false; png_image image {}; image.version = PNG_IMAGE_VERSION; if (!png_image_begin_read_from_file(&image, path.c_str())) { return false; } image.format = PNG_FORMAT_RGB; int w = static_cast(image.width); int h = static_cast(image.height); if (w <= 0 || h <= 0 || w > 8192 || h > 8192) { png_image_free(&image); return false; } outRgb->resize(PNG_IMAGE_SIZE(image)); if (!png_image_finish_read(&image, nullptr, outRgb->data(), 0, nullptr)) { png_image_free(&image); return false; } png_image_free(&image); *outW = w; *outH = h; return true; } bool loadFfmpegImageRgb24(const std::string& path, std::vector* outRgb, int* outW, int* outH) { if (!outRgb || !outW || !outH) return false; int pipefd[2]; if (::pipe(pipefd) != 0) return false; pid_t pid = ::fork(); if (pid < 0) { ::close(pipefd[0]); ::close(pipefd[1]); return false; } if (pid == 0) { ::close(pipefd[0]); ::dup2(pipefd[1], STDOUT_FILENO); if (pipefd[1] != STDOUT_FILENO) ::close(pipefd[1]); int devnull = ::open("/dev/null", O_RDWR); if (devnull >= 0) { ::dup2(devnull, STDIN_FILENO); ::dup2(devnull, STDERR_FILENO); if (devnull > 2) ::close(devnull); } ::execlp("ffmpeg", "ffmpeg", "-v", "error", "-i", path.c_str(), "-frames:v", "1", "-f", "image2pipe", "-vcodec", "png", "-", static_cast(nullptr)); ::_exit(127); } ::close(pipefd[1]); std::vector pngBuf; uint8_t chunk[4096]; ssize_t n = 0; while ((n = ::read(pipefd[0], chunk, sizeof(chunk))) > 0) { if (pngBuf.size() + static_cast(n) > 16 * 1024 * 1024) break; pngBuf.insert(pngBuf.end(), chunk, chunk + n); } ::close(pipefd[0]); int status = 0; ::waitpid(pid, &status, 0); if (pngBuf.empty()) return false; png_image image {}; image.version = PNG_IMAGE_VERSION; if (!png_image_begin_read_from_memory(&image, pngBuf.data(), pngBuf.size())) { return false; } image.format = PNG_FORMAT_RGB; int w = static_cast(image.width); int h = static_cast(image.height); if (w <= 0 || h <= 0 || w > 8192 || h > 8192) { png_image_free(&image); return false; } outRgb->resize(PNG_IMAGE_SIZE(image)); if (!png_image_finish_read(&image, nullptr, outRgb->data(), 0, nullptr)) { png_image_free(&image); return false; } png_image_free(&image); *outW = w; *outH = h; return true; } bool loadImageRgb24(const std::string& path, std::vector* outRgb, int* outW, int* outH) { std::string low = path; for (char& c : low) { c = static_cast(std::tolower(static_cast(c))); } if (low.size() >= 4 && low.substr(low.size() - 4) == ".png") { if (loadPngRgb24(path, outRgb, outW, outH)) return true; } if (loadJpegRgb24(path, outRgb, outW, outH)) return true; if (loadPngRgb24(path, outRgb, outW, outH)) return true; if (loadFfmpegImageRgb24(path, outRgb, outW, outH)) return true; return false; } void scaleRgb24ToBgrxCanvas(const uint8_t* srcRgb, int srcW, int srcH, uint32_t* dstBgrx, int canvasW, int canvasH, uint32_t bgPixel, int scaleMode) { for (int i = 0; i < canvasW * canvasH; ++i) { dstBgrx[i] = bgPixel; } if (!srcRgb || srcW <= 0 || srcH <= 0 || canvasW <= 0 || canvasH <= 0) { return; } if (scaleMode == NEO_SCALE_STRETCH) { for (int dy = 0; dy < canvasH; ++dy) { int sy = std::min(srcH - 1, (dy * srcH) / canvasH); const uint8_t* srow = srcRgb + static_cast(sy) * srcW * 3; uint32_t* drow = dstBgrx + static_cast(dy) * canvasW; for (int dx = 0; dx < canvasW; ++dx) { int sx = std::min(srcW - 1, (dx * srcW) / canvasW); const uint8_t* px = srow + sx * 3; drow[dx] = (static_cast(px[0]) << 16) | (static_cast(px[1]) << 8) | static_cast(px[2]); } } return; } if (scaleMode == NEO_SCALE_FILL) { int cropW = srcW; int cropH = (srcW * canvasH) / canvasW; if (cropH > srcH) { cropH = srcH; cropW = (srcH * canvasW) / canvasH; } cropW = std::max(1, cropW); cropH = std::max(1, cropH); int startX = (srcW - cropW) / 2; int startY = (srcH - cropH) / 2; for (int dy = 0; dy < canvasH; ++dy) { int sy = std::min(srcH - 1, startY + (dy * cropH) / canvasH); const uint8_t* srow = srcRgb + static_cast(sy) * srcW * 3; uint32_t* drow = dstBgrx + static_cast(dy) * canvasW; for (int dx = 0; dx < canvasW; ++dx) { int sx = std::min(srcW - 1, startX + (dx * cropW) / canvasW); const uint8_t* px = srow + sx * 3; drow[dx] = (static_cast(px[0]) << 16) | (static_cast(px[1]) << 8) | static_cast(px[2]); } } return; } int drawW = canvasW; int drawH = (srcH * canvasW) / srcW; if (drawH > canvasH) { drawH = canvasH; drawW = (srcW * canvasH) / srcH; } drawW = std::max(1, drawW); drawH = std::max(1, drawH); int offX = (canvasW - drawW) / 2; int offY = (canvasH - drawH) / 2; for (int dy = 0; dy < drawH; ++dy) { int sy = std::min(srcH - 1, (dy * srcH) / drawH); const uint8_t* srow = srcRgb + static_cast(sy) * srcW * 3; uint32_t* drow = dstBgrx + static_cast(offY + dy) * canvasW + offX; for (int dx = 0; dx < drawW; ++dx) { int sx = std::min(srcW - 1, (dx * srcW) / drawW); const uint8_t* px = srow + sx * 3; drow[dx] = (static_cast(px[0]) << 16) | (static_cast(px[1]) << 8) | static_cast(px[2]); } } } void downscaleViewfinder800x600To240x180(const uint8_t* srcRgb, uint32_t* dstBgrx, int zoomFactor) { if (!srcRgb || !dstBgrx) return; zoomFactor = std::clamp(zoomFactor, 1, 4); // The GC2395 800x600 sensor is mounted 90 deg CCW relative to portrait phone // orientation. After a 90 deg CW rotation, the upright frame is 600x800; // take its centered 4:3 region (600x450) to fill the 240x180 viewfinder // without aspect-ratio distortion. int cropRotW = 600 / zoomFactor; int cropRotH = 450 / zoomFactor; int startRotX = (600 - cropRotW) / 2; int startRotY = (800 - cropRotH) / 2; for (int dy = 0; dy < 180; ++dy) { int rotY = std::clamp(startRotY + (dy * cropRotH) / 180, 0, 799); int sx = rotY; uint32_t* drow = dstBgrx + static_cast(dy) * 240; for (int dx = 0; dx < 240; ++dx) { int rotX = std::clamp(startRotX + (dx * cropRotW) / 240, 0, 599); int sy = 599 - rotX; const uint8_t* px = srcRgb + (static_cast(sy) * 800 + sx) * 3; drow[dx] = (static_cast(px[0]) << 16) | (static_cast(px[1]) << 8) | static_cast(px[2]); } } } std::string formatFileSize(off_t bytes) { char buf[32]; if (bytes >= 1024LL * 1024LL * 1024LL) { std::snprintf(buf, sizeof(buf), "%.1fG", static_cast(bytes) / (1024.0 * 1024.0 * 1024.0)); } else if (bytes >= 1024LL * 1024LL) { std::snprintf(buf, sizeof(buf), "%.1fM", static_cast(bytes) / (1024.0 * 1024.0)); } else if (bytes >= 1024LL) { std::snprintf(buf, sizeof(buf), "%.1fK", static_cast(bytes) / 1024.0); } else { std::snprintf(buf, sizeof(buf), "%lldB", static_cast(bytes)); } return buf; } // --------------------------------------------------------------------------- // NeoWindow C++ Class Implementation // --------------------------------------------------------------------------- NeoWindow::~NeoWindow() { destroy(); } bool NeoWindow::create(const char* resName, const char* resClass, const char* title, int winX, int winY, int winW, int winH, bool overrideRedirect, long eventMask) { destroy(); std::setlocale(LC_ALL, ""); XSetLocaleModifiers(""); dpy = XOpenDisplay(nullptr); if (!dpy) return false; screen = DefaultScreen(dpy); root = RootWindow(dpy, screen); visual = DefaultVisual(dpy, screen); cmap = DefaultColormap(dpy, screen); x = winX; y = winY; width = winW; height = winH; XSetWindowAttributes swa{}; swa.override_redirect = overrideRedirect ? True : False; swa.background_pixel = 0x222222; swa.border_pixel = 0x005577; swa.event_mask = eventMask; win = XCreateWindow( dpy, root, x, y, width, height, 0, DefaultDepth(dpy, screen), CopyFromParent, visual, CWOverrideRedirect | CWBackPixel | CWBorderPixel | CWEventMask, &swa); XClassHint ch{}; std::string rName = (resName && resName[0]) ? resName : "neoui"; std::string rClass = (resClass && resClass[0]) ? resClass : "NeoUI"; ch.res_name = const_cast(rName.c_str()); ch.res_class = const_cast(rClass.c_str()); XSetClassHint(dpy, win, &ch); XStoreName(dpy, win, (title && title[0]) ? title : rClass.c_str()); Atom wmDelete = XInternAtom(dpy, "WM_DELETE_WINDOW", False); XSetWMProtocols(dpy, win, &wmDelete, 1); pix = XCreatePixmap(dpy, win, width, height, DefaultDepth(dpy, screen)); gc = XCreateGC(dpy, pix, 0, nullptr); xftDraw = XftDrawCreate(dpy, pix, visual, cmap); PangoFontMap* fontMap = pango_xft_get_font_map(dpy, screen); pangoCtx = pango_font_map_create_context(fontMap); layoutMain = pango_layout_new(pangoCtx); layoutSmall = pango_layout_new(pangoCtx); layoutIcon = pango_layout_new(pangoCtx); layoutNum = pango_layout_new(pangoCtx); theme.load(dpy, screen, visual, cmap, layoutMain, layoutSmall, layoutIcon, layoutNum, win); bindAsActiveContext(); return true; } void NeoWindow::destroy() { if (!dpy) return; if (layoutMain) { g_object_unref(layoutMain); layoutMain = nullptr; } if (layoutSmall) { g_object_unref(layoutSmall); layoutSmall = nullptr; } if (layoutIcon) { g_object_unref(layoutIcon); layoutIcon = nullptr; } if (layoutNum) { g_object_unref(layoutNum); layoutNum = nullptr; } if (pangoCtx) { g_object_unref(pangoCtx); pangoCtx = nullptr; } if (xftDraw) { XftDrawDestroy(xftDraw); xftDraw = nullptr; } if (gc) { XFreeGC(dpy, gc); gc = nullptr; } if (pix != None) { XFreePixmap(dpy, pix); pix = None; } if (win != None) { XDestroyWindow(dpy, win); win = None; } XCloseDisplay(dpy); dpy = nullptr; } } // namespace bananarchy // --------------------------------------------------------------------------- // Internal C FFI Context State // --------------------------------------------------------------------------- struct NeoContext { bananarchy::NeoWindow ownedWin; bananarchy::NeoWindow* w = nullptr; std::string appName; std::string fifoPath; int fifoFd = -1; bool visible = false; bool chordXdrawer = true; // Softkey chord & startup debounce int64_t startupIgnoreUntilMs = 0; bool initialSoftkeysReleased = true; int softkeyPending = 0; int64_t softkeyDeadlineMs = 0; // Last polled event int lastEventType = NEO_EV_NONE; int lastEventKey = NEO_KEY_NONE; int lastEventKeycode = 0; int lastEventKeysym = 0; std::string lastEventCmd; std::vector pendingFifoCmds; // Toast overlay std::string toastMsg; int64_t toastUntilMs = 0; // Multi-tap state machine std::string inputText; int inputMode = NEO_INPUT_ABC_TITLE; int lastTapKey = -1; int tapCycleIdx = 0; int64_t lastTapMs = 0; bool tapActive = false; // Persistent string buffers for C / Yabasic FFI returns std::string retHexBuf; std::string retTailBuf; std::string retCandBuf; std::string retThemeNameBuf; std::string retFontFaceBuf; std::string retIconFontFaceBuf; // Cached decoded image for neoui_draw_image_file std::string cachedImgPath; std::vector cachedImgRgb; int cachedImgW = 0; int cachedImgH = 0; }; namespace { NeoContext* gCtx = nullptr; NeoContext* ensureCtx() { if (!gCtx) { gCtx = new NeoContext(); gCtx->w = &gCtx->ownedWin; } return gCtx; } const char* tapTableForKey(int inputMode, int key) { int idx = -1; if (key >= '0' && key <= '9') { idx = key - '0'; } else if (key == '*') { idx = 10; } if (idx < 0 || idx > 10) return nullptr; if (inputMode == NEO_INPUT_SYM) { return bananarchy::kSymTapTable[idx]; } return bananarchy::kAlphaTapTable[idx]; } bool shouldCapitalizeNext(const std::string& text, int inputMode, int key) { if (key < '2' || key > '9') return false; if (inputMode == NEO_INPUT_ABC_UPPER) return true; if (inputMode != NEO_INPUT_ABC_TITLE) return false; if (text.empty()) return true; for (size_t i = text.size(); i > 0; --i) { char prev = text[i - 1]; if (prev == ' ' || prev == '\n' || prev == '\t' || prev == '-' || prev == '.' || prev == '_' || prev == '/') { return true; } return false; } return true; } } // namespace namespace bananarchy { void NeoWindow::bindAsActiveContext() { NeoContext* ctx = ensureCtx(); ctx->w = this; } } // namespace bananarchy // --------------------------------------------------------------------------- // Extern "C" FFI Implementation // --------------------------------------------------------------------------- extern "C" { int neoui_init(const char* app_name, int preload_mode) { std::string name = (app_name && app_name[0]) ? app_name : "neoui"; std::string resName = name; for (char& c : resName) { if (std::isalnum(static_cast(c))) { c = static_cast(std::tolower(static_cast(c))); } else { c = '_'; } } return neoui_init_ex(resName.c_str(), resName.c_str(), name.c_str(), name.c_str(), NEO_WIN_X, NEO_WIN_Y, NEO_WIN_W, NEO_WIN_H, 1, preload_mode); } int neoui_init_ex(const char* app_name, const char* res_name, const char* res_class, const char* win_title, int x, int y, int w, int h, int override_redirect, int preload_mode) { NeoContext* ctx = ensureCtx(); ctx->w = &ctx->ownedWin; ctx->appName = (app_name && app_name[0]) ? app_name : "neoui"; if (!ctx->ownedWin.create(res_name, res_class, win_title, x, y, w, h, override_redirect != 0)) { return 0; } if (ctx->fifoFd >= 0) { ::close(ctx->fifoFd); ctx->fifoFd = -1; } std::string fifoPath = "/tmp/dwm_plugin_" + ctx->appName + ".fifo"; ::mkfifo(fifoPath.c_str(), 0666); ::chmod(fifoPath.c_str(), 0666); ctx->fifoFd = ::open(fifoPath.c_str(), O_RDWR | O_NONBLOCK | O_CLOEXEC); if (! preload_mode) { neoui_show(); } else { ctx->visible = false; } return 1; } int neoui_shutdown(void) { if (!gCtx) return 1; if (gCtx->visible) { neoui_hide(); } if (gCtx->fifoFd >= 0) { ::close(gCtx->fifoFd); gCtx->fifoFd = -1; } if (!gCtx->appName.empty()) { std::string fifoPath = "/tmp/dwm_plugin_" + gCtx->appName + ".fifo"; ::unlink(fifoPath.c_str()); } gCtx->ownedWin.destroy(); delete gCtx; gCtx = nullptr; return 1; } int neoui_show(void) { NeoContext* ctx = ensureCtx(); if (!ctx->w || !ctx->w->dpy || ctx->w->win == None) return 0; XMapRaised(ctx->w->dpy, ctx->w->win); XRaiseWindow(ctx->w->dpy, ctx->w->win); neoui_raise_and_grab(); ctx->visible = true; ctx->startupIgnoreUntilMs = bananarchy::monotonicMs() + 180; ctx->initialSoftkeysReleased = (bananarchy::querySoftkeysMask(ctx->w->dpy) == 0); ctx->softkeyPending = 0; XFlush(ctx->w->dpy); return 1; } int neoui_hide(void) { NeoContext* ctx = ensureCtx(); if (!ctx->w || !ctx->w->dpy || ctx->w->win == None) return 0; if (ctx->visible) { bananarchy::writeSoftkeySuppressFile(bananarchy::monotonicMs() + 450); } neoui_ungrab(); XUnmapWindow(ctx->w->dpy, ctx->w->win); ctx->visible = false; ctx->softkeyPending = 0; XSync(ctx->w->dpy, True); return 1; } int neoui_is_visible(void) { if (!gCtx || !gCtx->w || !gCtx->w->dpy) return 0; return gCtx->visible ? 1 : 0; } int neoui_raise_and_grab(void) { NeoContext* ctx = ensureCtx(); if (!ctx->w || !ctx->w->dpy || ctx->w->win == None) return 0; XRaiseWindow(ctx->w->dpy, ctx->w->win); XSetInputFocus(ctx->w->dpy, ctx->w->win, RevertToPointerRoot, CurrentTime); for (int i = 0; i < 8; ++i) { if (XGrabKeyboard(ctx->w->dpy, ctx->w->win, True, GrabModeAsync, GrabModeAsync, CurrentTime) == GrabSuccess) { break; } ::usleep(12000); } return 1; } int neoui_ungrab(void) { NeoContext* ctx = ensureCtx(); if (!ctx->w || !ctx->w->dpy) return 0; XUngrabKeyboard(ctx->w->dpy, CurrentTime); XSetInputFocus(ctx->w->dpy, PointerRoot, RevertToPointerRoot, CurrentTime); return 1; } int neoui_width(void) { if (!gCtx || !gCtx->w) return NEO_WIN_W; return gCtx->w->width; } int neoui_height(void) { if (!gCtx || !gCtx->w) return NEO_WIN_H; return gCtx->w->height; } int neoui_begin_frame(void) { NeoContext* ctx = ensureCtx(); if (!ctx->w || !ctx->w->dpy) return 0; ctx->w->checkReloadTheme(); neoui_reset_clip(); ctx->w->clearBg(); return 1; } int neoui_end_frame(void) { NeoContext* ctx = ensureCtx(); if (!ctx->w || !ctx->w->dpy) return 0; neoui_reset_clip(); if (!ctx->toastMsg.empty() && bananarchy::monotonicMs() < ctx->toastUntilMs) { ctx->w->drawToast(ctx->toastMsg); } ctx->w->present(); return 1; } int neoui_flush(void) { if (!gCtx || !gCtx->w || !gCtx->w->dpy) return 0; XFlush(gCtx->w->dpy); return 1; } // --------------------------------------------------------------------------- // 2. Theme & Color Resolution // --------------------------------------------------------------------------- int neoui_reload_theme(void) { NeoContext* ctx = ensureCtx(); if (!ctx->w || !ctx->w->dpy) return 0; ctx->w->reloadTheme(); return 1; } int neoui_check_reload_theme(void) { NeoContext* ctx = ensureCtx(); if (!ctx->w || !ctx->w->dpy) return 0; return ctx->w->checkReloadTheme() ? 1 : 0; } int neoui_apply_theme_file(const char* xth_path) { if (!xth_path || !xth_path[0]) return 0; bananarchy::ThemeSpec spec; if (!spec.loadFromFile(xth_path)) return 0; std::string xres = spec.serializeXresources(); if (!spec.saveToFile(bananarchy::getXresourcesPath())) return 0; Display* dpy = (gCtx && gCtx->w && gCtx->w->dpy) ? gCtx->w->dpy : XOpenDisplay(nullptr); if (dpy) { Window root = DefaultRootWindow(dpy); XChangeProperty(dpy, root, XA_RESOURCE_MANAGER, XA_STRING, 8, PropModeReplace, reinterpret_cast(xres.data()), static_cast(xres.size())); XFlush(dpy); if (!gCtx || !gCtx->w || gCtx->w->dpy != dpy) { XCloseDisplay(dpy); } } if (gCtx && gCtx->w && gCtx->w->dpy) { gCtx->w->reloadTheme(); } neoui_broadcast_theme_reload(""); return 1; } int neoui_broadcast_theme_reload(const char* skip_plugin) { const char* kPlugins[] = { "dmenu", "locker", "xdrawer", "dialer", "calllog", "callscreen", "contacts", "sms", "files", "camera", "themes", "modem", "networks", "ringtones", "wallpapers", "music", "sip", "email", "irc", "tox", "smallweb", "gps", "passcode", "engmenu" }; std::string skip = (skip_plugin && skip_plugin[0]) ? skip_plugin : ""; for (const char* p : kPlugins) { if (skip == p) continue; bananarchy::sendPluginFifoMsg(p, "RELOAD_THEME"); } (void)std::system("/usr/bin/bananarchy-sync-dunst-theme >/dev/null 2>&1 &"); return 1; } const char* neoui_theme_name(void) { NeoContext* ctx = ensureCtx(); if (ctx->w && ctx->w->dpy) { ctx->retThemeNameBuf = ctx->w->theme.spec.name; } else { ctx->retThemeNameBuf = bananarchy::loadThemeSpec().name; } return ctx->retThemeNameBuf.c_str(); } const char* neoui_font_face(void) { NeoContext* ctx = ensureCtx(); if (ctx->w && ctx->w->dpy) { ctx->retFontFaceBuf = ctx->w->theme.spec.fontFace; } else { ctx->retFontFaceBuf = bananarchy::loadThemeSpec().fontFace; } return ctx->retFontFaceBuf.c_str(); } const char* neoui_icon_font_face(void) { NeoContext* ctx = ensureCtx(); if (ctx->w && ctx->w->dpy) { ctx->retIconFontFaceBuf = ctx->w->theme.spec.iconFontFace; } else { ctx->retIconFontFaceBuf = bananarchy::loadThemeSpec().iconFontFace; } return ctx->retIconFontFaceBuf.c_str(); } int neoui_base_font_size(void) { if (gCtx && gCtx->w && gCtx->w->dpy) { return gCtx->w->theme.spec.sizeMain(); } return bananarchy::loadThemeSpec().sizeMain(); } int neoui_font_size(int font_role) { const bananarchy::ThemeSpec spec = (gCtx && gCtx->w && gCtx->w->dpy) ? gCtx->w->theme.spec : bananarchy::loadThemeSpec(); switch (font_role) { case NEO_FONT_SMALL: return spec.sizeSmall(); case NEO_FONT_MAIN: return spec.sizeMain(); case NEO_FONT_ICON: return spec.sizeIcon(); case NEO_FONT_LARGE: return spec.sizeLarge(); default: return spec.sizeMain(); } } uint32_t neoui_color(int color_id) { if (gCtx && gCtx->w && gCtx->w->dpy) { return gCtx->w->theme.spec.colorById(color_id); } return bananarchy::loadThemeSpec().colorById(color_id); } uint32_t neoui_adjust_rgb(uint32_t rgb, int delta) { return bananarchy::adjustRgb(rgb, delta); } uint32_t neoui_blend_rgb(uint32_t c1, uint32_t c2, int weight2_pct) { return bananarchy::blendRgb(c1, c2, weight2_pct); } uint32_t neoui_parse_hex_rgb(const char* hex_str, uint32_t fallback_rgb) { if (!hex_str || !hex_str[0]) return fallback_rgb; uint32_t v = fallback_rgb; if (bananarchy::parseHexRgb(hex_str, &v)) return v; return fallback_rgb; } const char* neoui_format_hex_rgb(uint32_t rgb) { NeoContext* ctx = ensureCtx(); ctx->retHexBuf = bananarchy::formatHexRgb(rgb); return ctx->retHexBuf.c_str(); } const char* neoui_icon(const char* icon_name) { if (!icon_name || !icon_name[0]) return ""; struct IconPair { const char* key; const char* utf8; }; static const IconPair kIcons[] = { {"phone", "\xef\x82\x95"}, {"phonelog", "\xef\x82\x98"}, {"user", "\xef\x80\x87"}, {"book", "\xef\x83\x80"}, {"contacts", "\xef\x83\x80"}, {"clock", "\xef\x80\x97"}, {"outcall", "\xef\x85\xb8"}, {"incall", "\xef\x85\xb5"}, {"missedcall", "\xef\x81\xb1"}, {"warning", "\xef\x81\xb1"}, {"backspace", "\xef\x86\x90"}, {"search", "\xef\x80\x82"}, {"plus", "\xef\x81\xa7"}, {"add", "\xef\x81\xa7"}, {"edit", "\xef\x81\x84"}, {"trash", "\xef\x87\xb8"}, {"delete", "\xef\x87\xb8"}, {"sms", "\xef\x83\xa0"}, {"mail", "\xef\x83\xa0"}, {"list", "\xef\x80\xba"}, {"check", "\xef\x80\x8c"}, {"ok", "\xef\x80\x8c"}, {"folder", "\xef\x81\xbb"}, {"folder_open", "\xef\x81\xbc"}, {"file", "\xef\x80\x96"}, {"file_text", "\xef\x85\x9c"}, {"image", "\xef\x80\xbe"}, {"music", "\xef\x80\x81"}, {"audio", "\xef\x80\x81"}, {"term", "\xef\x84\xa0"}, {"terminal", "\xef\x84\xa0"}, {"camera", "\xef\x80\xb0"}, {"flash", "\xef\x83\xa7"}, {"bolt", "\xef\x83\xa7"}, {"send", "\xef\x87\x98"}, {"copy", "\xef\x83\x85"}, {"info", "\xef\x81\x9a"}, {"refresh", "\xef\x80\xa1"}, {"sort", "\xef\x83\x9c"}, {"eye", "\xef\x81\xae"}, {"palette", "\xef\x87\xbc"}, {"theme", "\xef\x87\xbc"}, {"speaker", "\xef\x80\xa8"}, {"earpiece", "\xef\x8a\xa0"}, {"sound_on", "\xf3\xb0\x8e\x88"}, {"sound_off", "\xef\x91\xa6"}, {"mute", "\xef\x91\xa6"}, {"mic_on", "\xf3\xb0\x8d\xac"}, {"mic_off", "\xf3\xb0\x8d\xad"}, {"record", "\xef\x84\x91"}, {"lock", "\xef\x80\xa3"}, {"unlock", "\xef\x82\x9c"}, {"signal", "\xef\x80\x92"}, {"wifi", "\xef\x87\xab"}, {"bluetooth", "\xef\x8a\x94"}, {"globe", "\xef\x82\xac"}, {"network", "\xef\x82\xac"}, {"sliders", "\xef\x87\x9e"}, {"settings", "\xef\x87\x9e"}, {"toggle_on", "\xef\x88\x85"}, {"toggle_off", "\xef\x88\x84"}, {"key", "\xef\x82\x84"}, {"sim", "\xf3\xb0\x99\x95"}, {"bell", "\xef\x83\xb3"}, {"bell_slash", "\xef\x87\xb6"}, {"ban", "\xef\x81\x9e"}, {"shield", "\xef\x84\xb2"}, {"gamepad", "\xef\x84\x9b"}, {"flashlight", "\xf3\xb0\x89\x84"}, {"brightness", "\xf3\xb0\x83\x9d"}, {"keyboard", "\xef\x84\x9c"}, }; for (const auto& item : kIcons) { if (strcasecmp(icon_name, item.key) == 0) { return item.utf8; } } return icon_name; } // --------------------------------------------------------------------------- // 3. Drawing Primitives & Text Rendering // --------------------------------------------------------------------------- int neoui_clear(uint32_t rgb) { if (!gCtx || !gCtx->w || !gCtx->w->dpy) return 0; XSetForeground(gCtx->w->dpy, gCtx->w->gc, rgb); XFillRectangle(gCtx->w->dpy, gCtx->w->pix, gCtx->w->gc, 0, 0, gCtx->w->width, gCtx->w->height); return 1; } int neoui_fill_rect(int x, int y, int w, int h, uint32_t rgb) { if (!gCtx || !gCtx->w || !gCtx->w->dpy || w <= 0 || h <= 0) return 0; XSetForeground(gCtx->w->dpy, gCtx->w->gc, rgb); XFillRectangle(gCtx->w->dpy, gCtx->w->pix, gCtx->w->gc, x, y, w, h); return 1; } int neoui_draw_rect(int x, int y, int w, int h, uint32_t rgb) { if (!gCtx || !gCtx->w || !gCtx->w->dpy || w <= 1 || h <= 1) return 0; XSetForeground(gCtx->w->dpy, gCtx->w->gc, rgb); XDrawRectangle(gCtx->w->dpy, gCtx->w->pix, gCtx->w->gc, x, y, w - 1, h - 1); return 1; } int neoui_draw_line(int x1, int y1, int x2, int y2, uint32_t rgb) { if (!gCtx || !gCtx->w || !gCtx->w->dpy) return 0; XSetForeground(gCtx->w->dpy, gCtx->w->gc, rgb); XDrawLine(gCtx->w->dpy, gCtx->w->pix, gCtx->w->gc, x1, y1, x2, y2); return 1; } int neoui_set_clip(int x, int y, int w, int h) { if (!gCtx || !gCtx->w || !gCtx->w->dpy || w <= 0 || h <= 0) return 0; XRectangle r{}; r.x = static_cast(x); r.y = static_cast(y); r.width = static_cast(w); r.height = static_cast(h); XSetClipRectangles(gCtx->w->dpy, gCtx->w->gc, 0, 0, &r, 1, YXBanded); XftDrawSetClipRectangles(gCtx->w->xftDraw, 0, 0, &r, 1); return 1; } int neoui_reset_clip(void) { if (!gCtx || !gCtx->w || !gCtx->w->dpy) return 0; XSetClipMask(gCtx->w->dpy, gCtx->w->gc, None); XftDrawSetClip(gCtx->w->xftDraw, nullptr); return 1; } int neoui_draw_text(int font_role, int color_role, int x, int y, int h, const char* text, int max_w) { if (!gCtx || !gCtx->w || !gCtx->w->dpy || !text || !text[0]) return 0; PangoLayout* layout = gCtx->w->theme.layoutByRole(font_role); XftColor* col = gCtx->w->theme.colorByRole(color_role); bananarchy::neoDrawPango(gCtx->w->xftDraw, layout, col, x, y, h, text, max_w); return 1; } int neoui_draw_text_centered(int font_role, int color_role, int x, int y, int w, int h, const char* text) { if (!gCtx || !gCtx->w || !gCtx->w->dpy || !text || !text[0]) return 0; PangoLayout* layout = gCtx->w->theme.layoutByRole(font_role); XftColor* col = gCtx->w->theme.colorByRole(color_role); int tw = bananarchy::neoPangoWidth(layout, text); int tx = x + std::max(0, (w - tw) / 2); bananarchy::neoDrawPango(gCtx->w->xftDraw, layout, col, tx, y, h, text, w); return 1; } int neoui_draw_text_right(int font_role, int color_role, int right_x, int y, int h, const char* text, int max_w) { if (!gCtx || !gCtx->w || !gCtx->w->dpy || !text || !text[0]) return 0; PangoLayout* layout = gCtx->w->theme.layoutByRole(font_role); XftColor* col = gCtx->w->theme.colorByRole(color_role); int tw = bananarchy::neoPangoWidth(layout, text); if (max_w > 0 && tw > max_w) tw = max_w; bananarchy::neoDrawPango(gCtx->w->xftDraw, layout, col, right_x - tw, y, h, text, max_w); return 1; } int neoui_draw_text_wrapped(int font_role, int color_role, int x, int y, int w, int h, const char* text, int scroll_line) { if (!gCtx || !gCtx->w || !gCtx->w->dpy || !text || w <= 0 || h <= 0) return 0; PangoLayout* layout = gCtx->w->theme.layoutByRole(font_role); XftColor* col = gCtx->w->theme.colorByRole(color_role); if (!layout || !col) return 0; pango_layout_set_width(layout, w * PANGO_SCALE); pango_layout_set_wrap(layout, PANGO_WRAP_WORD_CHAR); pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_NONE); pango_layout_set_text(layout, text, static_cast(std::strlen(text))); int lineCount = pango_layout_get_line_count(layout); int startLine = std::clamp(scroll_line, 0, std::max(0, lineCount - 1)); int curY = y; int maxY = y + h; for (int li = startLine; li < lineCount; ++li) { PangoLayoutLine* pl = pango_layout_get_line_readonly(layout, li); if (!pl) continue; PangoRectangle ink{}, logical{}; pango_layout_line_get_pixel_extents(pl, &ink, &logical); int lineH = std::max(16, logical.height + 2); if (curY + lineH > maxY) break; pango_xft_render_layout_line(gCtx->w->xftDraw, col, pl, x * PANGO_SCALE, (curY - logical.y) * PANGO_SCALE); curY += lineH; } pango_layout_set_width(layout, -1); return lineCount; } int neoui_text_width(int font_role, const char* text) { if (!gCtx || !gCtx->w || !gCtx->w->dpy || !text || !text[0]) return 0; PangoLayout* layout = gCtx->w->theme.layoutByRole(font_role); return bananarchy::neoPangoWidth(layout, text); } const char* neoui_tail_fit_text(int font_role, const char* text, int max_w) { NeoContext* ctx = ensureCtx(); if (!text) { ctx->retTailBuf.clear(); return ctx->retTailBuf.c_str(); } if (!ctx->w || !ctx->w->dpy) { ctx->retTailBuf = text; return ctx->retTailBuf.c_str(); } PangoLayout* layout = ctx->w->theme.layoutByRole(font_role); ctx->retTailBuf = bananarchy::tailFitPangoText(layout, text, max_w); return ctx->retTailBuf.c_str(); } int neoui_draw_image_file(const char* path, int x, int y, int w, int h, int scale_mode) { if (!gCtx || !gCtx->w || !gCtx->w->dpy || !path || !path[0] || w <= 0 || h <= 0) { return 0; } if (gCtx->cachedImgPath != path || gCtx->cachedImgRgb.empty()) { gCtx->cachedImgRgb.clear(); gCtx->cachedImgW = 0; gCtx->cachedImgH = 0; if (!bananarchy::loadImageRgb24(path, &gCtx->cachedImgRgb, &gCtx->cachedImgW, &gCtx->cachedImgH)) { return 0; } gCtx->cachedImgPath = path; } std::vector canvas(static_cast(w) * h); bananarchy::scaleRgb24ToBgrxCanvas( gCtx->cachedImgRgb.data(), gCtx->cachedImgW, gCtx->cachedImgH, canvas.data(), w, h, gCtx->w->theme.spec.bgMain, scale_mode); XImage* ximg = XCreateImage( gCtx->w->dpy, gCtx->w->visual, DefaultDepth(gCtx->w->dpy, gCtx->w->screen), ZPixmap, 0, reinterpret_cast(canvas.data()), w, h, 32, w * 4); if (!ximg) return 0; XPutImage(gCtx->w->dpy, gCtx->w->pix, gCtx->w->gc, ximg, 0, 0, x, y, w, h); ximg->data = nullptr; XDestroyImage(ximg); return 1; } // --------------------------------------------------------------------------- // 4. Standardized OS Shell UI Components (Widgets) // --------------------------------------------------------------------------- int neoui_draw_header(const char* icon_str, int icon_color_role, const char* title, const char* right_badge) { return neoui_draw_header_ex(NEO_HEADER_H, icon_str, icon_color_role, title, NEO_TEXT_WHITE, right_badge, NEO_TEXT_YELLOW); } int neoui_draw_header_ex(int h, const char* icon_str, int icon_color_role, const char* title, int title_color_role, const char* right_badge, int right_color_role) { if (!gCtx || !gCtx->w || !gCtx->w->dpy || h <= 0) return 0; int winW = gCtx->w->width; neoui_fill_rect(0, 0, winW, h, gCtx->w->theme.spec.bgHeader); neoui_fill_rect(0, h - 1, winW, 1, gCtx->w->theme.spec.border); int titleX = 8; if (icon_str && icon_str[0]) { const char* resolved = neoui_icon(icon_str); neoui_draw_text(NEO_FONT_ICON, icon_color_role, 8, 0, h - 1, resolved, -1); titleX = 30; } int rightW = 0; if (right_badge && right_badge[0]) { rightW = neoui_text_width(NEO_FONT_SMALL, right_badge); neoui_draw_text(NEO_FONT_SMALL, right_color_role, winW - rightW - 6, 0, h - 1, right_badge, rightW + 4); rightW += 10; } if (title && title[0]) { neoui_draw_text(NEO_FONT_MAIN, title_color_role, titleX, 0, h - 1, title, std::max(20, winW - titleX - rightW - 6)); } return 1; } int neoui_draw_tabs(const char* pipe_labels, int active_idx, int y, int h) { if (!gCtx || !gCtx->w || !gCtx->w->dpy || h <= 0) return 0; std::vector tabs = bananarchy::splitPipeList(pipe_labels); int count = static_cast(tabs.size()); if (count <= 0) return 0; int winW = gCtx->w->width; neoui_fill_rect(0, y, winW, h, gCtx->w->theme.spec.bgHeader); for (int i = 0; i < count; ++i) { int tx = (i * winW) / count; int tw = ((i + 1) * winW) / count - tx; bool active = (i == active_idx); if (active) { neoui_fill_rect(tx, y, tw, h - 1, gCtx->w->theme.spec.selBg); neoui_fill_rect(tx, y + h - 3, tw, 3, gCtx->w->theme.spec.accent); } neoui_draw_text_centered(NEO_FONT_SMALL, active ? NEO_TEXT_WHITE : NEO_TEXT_MUTED, tx, y, tw, h - 2, tabs[i].c_str()); } neoui_fill_rect(0, y + h - 1, winW, 1, gCtx->w->theme.spec.border); return 1; } int neoui_draw_softkeys(const char* left_label, const char* center_label, const char* right_label) { return neoui_draw_softkeys_ex(left_label, center_label, right_label, NEO_TEXT_GREEN); } int neoui_draw_softkeys_ex(const char* left_label, const char* center_label, const char* right_label, int center_color_role) { if (!gCtx || !gCtx->w || !gCtx->w->dpy) return 0; XftColor* cCol = gCtx->w->theme.colorByRole(center_color_role); gCtx->w->drawSoftbar(left_label ? left_label : "", center_label ? center_label : "", right_label ? right_label : "", cCol); return 1; } int neoui_draw_list_row(int row_index, int y, int h, int is_selected, const char* icon_str, int icon_color_role, const char* title, const char* subtitle, const char* right_text) { if (!gCtx || !gCtx->w || !gCtx->w->dpy || h <= 0) return 0; int winW = gCtx->w->width; const auto& spec = gCtx->w->theme.spec; uint32_t bg = is_selected ? spec.selBg : ((row_index % 2 == 0) ? spec.bgAltEven : spec.bgAltOdd); neoui_fill_rect(0, y, winW, h, bg); if (is_selected) { neoui_fill_rect(0, y, 4, h, spec.accent); } int textX = 8; if (icon_str && icon_str[0]) { const char* resolved = neoui_icon(icon_str); neoui_draw_text(NEO_FONT_ICON, is_selected ? NEO_TEXT_YELLOW : icon_color_role, 8, y, h, resolved, -1); textX = 30; } int rightW = 0; if (right_text && right_text[0]) { rightW = neoui_text_width(NEO_FONT_SMALL, right_text); neoui_draw_text(NEO_FONT_SMALL, is_selected ? NEO_TEXT_YELLOW : NEO_TEXT_MUTED, winW - rightW - 6, y, (subtitle && subtitle[0]) ? 20 : h, right_text, rightW + 4); rightW += 8; } int availW = std::max(20, winW - textX - rightW - 6); if (subtitle && subtitle[0]) { int topH = std::max(18, (h * 55) / 100); int botH = std::max(14, h - topH); if (title && title[0]) { neoui_draw_text(NEO_FONT_MAIN, is_selected ? NEO_TEXT_WHITE : NEO_TEXT_LIGHT, textX, y + 1, topH, title, availW); } neoui_draw_text(NEO_FONT_SMALL, is_selected ? NEO_TEXT_YELLOW : NEO_TEXT_MUTED, textX, y + topH - 1, botH, subtitle, winW - textX - 6); } else if (title && title[0]) { neoui_draw_text(NEO_FONT_MAIN, is_selected ? NEO_TEXT_WHITE : NEO_TEXT_LIGHT, textX, y, h, title, availW); } return 1; } int neoui_draw_slider_row(int row_index, int y, int h, int is_selected, const char* icon_str, int icon_color_role, const char* label, int pct, const char* value_text) { if (!gCtx || !gCtx->w || !gCtx->w->dpy || h <= 0) return 0; int winW = gCtx->w->width; const auto& spec = gCtx->w->theme.spec; uint32_t bg = is_selected ? spec.selBg : ((row_index % 2 == 0) ? spec.bgAltEven : spec.bgAltOdd); neoui_fill_rect(0, y, winW, h, bg); if (is_selected) { neoui_fill_rect(0, y, 4, h, spec.accent); } int textX = 8; if (icon_str && icon_str[0]) { const char* resolved = neoui_icon(icon_str); neoui_draw_text(NEO_FONT_ICON, is_selected ? NEO_TEXT_YELLOW : icon_color_role, 8, y, h, resolved, -1); textX = 28; } if (label && label[0]) { neoui_draw_text(NEO_FONT_MAIN, is_selected ? NEO_TEXT_WHITE : NEO_TEXT_LIGHT, textX, y, h, label, 108); } int barX = 136; int barW = 54; int barH = 8; int barY = y + (h - barH) / 2; neoui_fill_rect(barX, barY, barW, barH, spec.bgInput); neoui_draw_rect(barX, barY, barW, barH, spec.border); int clamped = std::clamp(pct, 0, 100); int fillW = ((barW - 2) * clamped) / 100; if (fillW > 0) { neoui_fill_rect(barX + 1, barY + 1, fillW, barH - 2, is_selected ? spec.accent : spec.success); } std::string vStr; if (value_text && value_text[0]) { vStr = value_text; } else { vStr = std::to_string(clamped) + "%"; } neoui_draw_text_right(NEO_FONT_SMALL, is_selected ? NEO_TEXT_YELLOW : NEO_TEXT_WHITE, winW - 6, y, h, vStr.c_str(), 44); return 1; } int neoui_draw_toggle_row(int row_index, int y, int h, int is_selected, const char* icon_str, int icon_color_role, const char* label, int is_on, const char* state_text) { if (!gCtx || !gCtx->w || !gCtx->w->dpy || h <= 0) return 0; int winW = gCtx->w->width; const auto& spec = gCtx->w->theme.spec; uint32_t bg = is_selected ? spec.selBg : ((row_index % 2 == 0) ? spec.bgAltEven : spec.bgAltOdd); neoui_fill_rect(0, y, winW, h, bg); if (is_selected) { neoui_fill_rect(0, y, 4, h, spec.accent); } int textX = 8; if (icon_str && icon_str[0]) { const char* resolved = neoui_icon(icon_str); neoui_draw_text(NEO_FONT_ICON, is_selected ? NEO_TEXT_YELLOW : icon_color_role, 8, y, h, resolved, -1); textX = 30; } if (label && label[0]) { neoui_draw_text(NEO_FONT_MAIN, is_selected ? NEO_TEXT_WHITE : NEO_TEXT_LIGHT, textX, y, h, label, 136); } const char* tIcon = neoui_icon(is_on ? "toggle_on" : "toggle_off"); neoui_draw_text(NEO_FONT_ICON, is_on ? NEO_TEXT_GREEN : NEO_TEXT_MUTED, winW - 24, y, h, tIcon, -1); std::string sTxt = (state_text && state_text[0]) ? state_text : (is_on ? "ON" : "OFF"); neoui_draw_text_right(NEO_FONT_SMALL, is_on ? NEO_TEXT_GREEN : NEO_TEXT_MUTED, winW - 28, y, h, sTxt.c_str(), 46); return 1; } int neoui_draw_button(int x, int y, int w, int h, int is_selected, int is_danger, const char* icon_str, const char* label) { if (!gCtx || !gCtx->w || !gCtx->w->dpy || w <= 0 || h <= 0) return 0; const auto& spec = gCtx->w->theme.spec; uint32_t bg = is_selected ? (is_danger ? spec.dangerBg : spec.selBg) : spec.bgButton; uint32_t bdr = is_selected ? (is_danger ? spec.danger : spec.accent) : spec.border; neoui_fill_rect(x, y, w, h, bg); neoui_draw_rect(x, y, w, h, bdr); std::string lbl = (label && label[0]) ? label : ""; if (icon_str && icon_str[0]) { const char* resolved = neoui_icon(icon_str); int iw = neoui_text_width(NEO_FONT_ICON, resolved); int lw = lbl.empty() ? 0 : neoui_text_width(NEO_FONT_MAIN, lbl.c_str()); int totalW = iw + (lw > 0 ? (6 + lw) : 0); int startX = x + std::max(4, (w - totalW) / 2); neoui_draw_text(NEO_FONT_ICON, is_selected ? NEO_TEXT_YELLOW : (is_danger ? NEO_TEXT_RED : NEO_TEXT_GREEN), startX, y, h, resolved, -1); if (!lbl.empty()) { neoui_draw_text(NEO_FONT_MAIN, is_selected ? NEO_TEXT_WHITE : NEO_TEXT_LIGHT, startX + iw + 6, y, h, lbl.c_str(), std::max(10, x + w - (startX + iw + 10))); } } else if (!lbl.empty()) { neoui_draw_text_centered(NEO_FONT_MAIN, is_selected ? NEO_TEXT_WHITE : NEO_TEXT_LIGHT, x, y, w, h, lbl.c_str()); } return 1; } int neoui_draw_input_box(int x, int y, int w, int h, int is_focused, const char* label, const char* value, const char* placeholder, int password_mask) { if (!gCtx || !gCtx->w || !gCtx->w->dpy || w <= 0 || h <= 0) return 0; const auto& spec = gCtx->w->theme.spec; int boxY = y; int boxH = h; if (label && label[0]) { neoui_draw_text(NEO_FONT_SMALL, is_focused ? NEO_TEXT_YELLOW : NEO_TEXT_MUTED, x, y, 16, label, w); boxY += 17; boxH = std::max(22, h - 17); } neoui_fill_rect(x, boxY, w, boxH, is_focused ? spec.bgInputFocus : spec.bgInput); neoui_draw_rect(x, boxY, w, boxH, is_focused ? spec.accent : spec.border); std::string val = (value && value[0]) ? value : ""; if (val.empty() && !is_focused) { if (placeholder && placeholder[0]) { neoui_draw_text(NEO_FONT_MAIN, NEO_TEXT_MUTED, x + 6, boxY, boxH, placeholder, w - 12); } return 1; } std::string disp = val; if (password_mask && !disp.empty()) { size_t charCount = 0; for (unsigned char c : disp) { if ((c & 0xC0) != 0x80) ++charCount; } disp.assign(charCount, '*'); } if (is_focused) { disp.push_back('_'); } const char* fitted = neoui_tail_fit_text(NEO_FONT_MAIN, disp.c_str(), w - 12); neoui_draw_text(NEO_FONT_MAIN, NEO_TEXT_WHITE, x + 6, boxY, boxH, fitted, -1); return 1; } int neoui_draw_progress_bar(int x, int y, int w, int h, int pct, uint32_t fill_rgb) { if (!gCtx || !gCtx->w || !gCtx->w->dpy || w <= 2 || h <= 2) return 0; const auto& spec = gCtx->w->theme.spec; neoui_fill_rect(x, y, w, h, spec.bgInput); neoui_draw_rect(x, y, w, h, spec.border); int clamped = std::clamp(pct, 0, 100); int fw = ((w - 2) * clamped) / 100; if (fw > 0) { uint32_t col = (fill_rgb != 0) ? fill_rgb : spec.success; neoui_fill_rect(x + 1, y + 1, fw, h - 2, col); } return 1; } int neoui_draw_scrollbar(int x, int y, int h, int total_items, int visible_items, int scroll_offset) { if (!gCtx || !gCtx->w || !gCtx->w->dpy) return 0; gCtx->w->drawScrollbar(x, y, h, total_items, visible_items, scroll_offset); return 1; } int neoui_draw_modal_box(int x, int y, int w, int h, const char* icon_str, int icon_color_role, const char* title) { if (!gCtx || !gCtx->w || !gCtx->w->dpy || w <= 0 || h <= 0) return 0; const auto& spec = gCtx->w->theme.spec; neoui_fill_rect(x, y, w, h, spec.bgOverlay); neoui_draw_rect(x, y, w, h, spec.accent); if ((icon_str && icon_str[0]) || (title && title[0])) { int tx = x + 8; if (icon_str && icon_str[0]) { const char* resolved = neoui_icon(icon_str); neoui_draw_text(NEO_FONT_ICON, icon_color_role, tx, y + 3, 24, resolved, -1); tx += 22; } if (title && title[0]) { neoui_draw_text(NEO_FONT_MAIN, NEO_TEXT_YELLOW, tx, y + 3, 24, title, std::max(20, x + w - tx - 8)); } neoui_fill_rect(x + 6, y + 28, w - 12, 1, spec.divider); } return 1; } int neoui_draw_confirm_dialog(const char* title, const char* line1, const char* line2, const char* no_label, const char* yes_label, int selected_yes) { if (!gCtx || !gCtx->w || !gCtx->w->dpy) return 0; int winW = gCtx->w->width; int boxX = 12; int boxY = 54; int boxW = winW - 24; int boxH = 154; neoui_draw_modal_box(boxX, boxY, boxW, boxH, "warning", NEO_TEXT_RED, (title && title[0]) ? title : "Confirm"); if (line1 && line1[0]) { neoui_draw_text_centered(NEO_FONT_MAIN, NEO_TEXT_WHITE, boxX + 6, boxY + 38, boxW - 12, 24, line1); } if (line2 && line2[0]) { neoui_draw_text_centered(NEO_FONT_SMALL, NEO_TEXT_MUTED, boxX + 6, boxY + 64, boxW - 12, 22, line2); } int btnW = (boxW - 24) / 2; int btnY = boxY + boxH - 42; neoui_draw_button(boxX + 8, btnY, btnW, 30, selected_yes == 0, 0, nullptr, (no_label && no_label[0]) ? no_label : "Cancel"); neoui_draw_button(boxX + 16 + btnW, btnY, btnW, 30, selected_yes != 0, 1, nullptr, (yes_label && yes_label[0]) ? yes_label : "Confirm"); return 1; } int neoui_draw_menu_popup(const char* pipe_items, const char* pipe_icons, int selected_idx, int max_visible_rows) { if (!gCtx || !gCtx->w || !gCtx->w->dpy) return 0; std::vector items = bananarchy::splitPipeList(pipe_items); std::vector icons = bananarchy::splitPipeList(pipe_icons); int optCount = static_cast(items.size()); if (optCount <= 0) return 0; int maxVis = (max_visible_rows > 0) ? max_visible_rows : 6; int visCount = std::min(optCount, maxVis); int optScroll = 0; if (selected_idx >= visCount) { optScroll = selected_idx - visCount + 1; } if (optScroll > std::max(0, optCount - visCount)) { optScroll = std::max(0, optCount - visCount); } int winW = gCtx->w->width; int winH = gCtx->w->height; int rowH = 34; int menuH = visCount * rowH + 4; int menuY = winH - NEO_SOFTBAR_H - menuH; const auto& spec = gCtx->w->theme.spec; neoui_fill_rect(8, menuY, winW - 16, menuH, spec.bgFooter); neoui_draw_rect(8, menuY, winW - 16, menuH, spec.selBg); for (int i = 0; i < visCount; ++i) { int idx = optScroll + i; if (idx >= optCount) break; int ry = menuY + 2 + i * rowH; bool isSel = (idx == selected_idx); if (isSel) { neoui_fill_rect(10, ry, winW - 20, rowH, spec.selBg); neoui_fill_rect(10, ry, 4, rowH, spec.accent); } int tx = 16; if (idx < static_cast(icons.size()) && !icons[idx].empty()) { const char* ic = neoui_icon(icons[idx].c_str()); neoui_draw_text(NEO_FONT_ICON, isSel ? NEO_TEXT_YELLOW : NEO_TEXT_GREEN, 18, ry, rowH, ic, -1); tx = 42; } neoui_draw_text(NEO_FONT_MAIN, isSel ? NEO_TEXT_WHITE : NEO_TEXT_LIGHT, tx, ry, rowH, items[idx].c_str(), winW - tx - 16); } if (optCount > visCount) { neoui_draw_scrollbar(winW - 12, menuY + 2, menuH - 4, optCount, visCount, optScroll); } return 1; } int neoui_draw_toast(const char* message) { if (!gCtx || !gCtx->w || !gCtx->w->dpy || !message || !message[0]) return 0; gCtx->w->drawToast(message); return 1; } int neoui_show_toast(const char* message, int duration_ms) { NeoContext* ctx = ensureCtx(); if (!message || !message[0]) { ctx->toastMsg.clear(); ctx->toastUntilMs = 0; return 0; } ctx->toastMsg = message; ctx->toastUntilMs = bananarchy::monotonicMs() + ((duration_ms > 0) ? duration_ms : 1800); return 1; } int neoui_clear_toast(void) { if (!gCtx) return 0; gCtx->toastMsg.clear(); gCtx->toastUntilMs = 0; return 1; } // --------------------------------------------------------------------------- // 5. Event Loop, Keypad & Multi-Tap Input Management // --------------------------------------------------------------------------- int neoui_poll_event(int timeout_ms) { NeoContext* ctx = ensureCtx(); ctx->lastEventType = NEO_EV_NONE; ctx->lastEventKey = NEO_KEY_NONE; ctx->lastEventKeycode = 0; ctx->lastEventKeysym = 0; ctx->lastEventCmd.clear(); if (!ctx->w || !ctx->w->dpy) return NEO_EV_NONE; Display* dpy = ctx->w->dpy; int64_t now = bananarchy::monotonicMs(); // Check if multi-tap timer expired if (ctx->tapActive && (now - ctx->lastTapMs >= 850)) { ctx->tapActive = false; ctx->lastTapKey = -1; ctx->tapCycleIdx = 0; ctx->lastEventType = NEO_EV_EXPOSE; return NEO_EV_EXPOSE; } // Check if pending softkey chord timer expired -> emit single softkey if (ctx->softkeyPending != 0 && now >= ctx->softkeyDeadlineMs) { int pend = ctx->softkeyPending; ctx->softkeyPending = 0; if (pend == 1) { ctx->lastEventType = NEO_EV_SOFTKEY_LEFT; ctx->lastEventKey = NEO_KEY_SOFT_LEFT; return NEO_EV_SOFTKEY_LEFT; } if (pend == 2) { ctx->lastEventType = NEO_EV_SOFTKEY_RIGHT; ctx->lastEventKey = NEO_KEY_SOFT_RIGHT; return NEO_EV_SOFTKEY_RIGHT; } } // Drain any queued FIFO commands first if (!ctx->pendingFifoCmds.empty()) { ctx->lastEventCmd = ctx->pendingFifoCmds.front(); ctx->pendingFifoCmds.erase(ctx->pendingFifoCmds.begin()); if (ctx->lastEventCmd == "RELOAD_THEME") { ctx->w->reloadTheme(); ctx->lastEventType = NEO_EV_THEME_RELOAD; return NEO_EV_THEME_RELOAD; } if (ctx->lastEventCmd == "CLOSE") { ctx->lastEventType = NEO_EV_CLOSE_REQ; return NEO_EV_CLOSE_REQ; } ctx->lastEventType = NEO_EV_FIFO_CMD; return NEO_EV_FIFO_CMD; } auto processNextXEvent = [&]() -> int { while (XPending(dpy) > 0) { XEvent ev; XNextEvent(dpy, &ev); if (ev.type == Expose) { while (XCheckTypedWindowEvent(dpy, ctx->w->win, Expose, &ev)) {} ctx->lastEventType = NEO_EV_EXPOSE; return NEO_EV_EXPOSE; } if (ev.type == ClientMessage) { Atom wmDelete = XInternAtom(dpy, "WM_DELETE_WINDOW", False); if (static_cast(ev.xclient.data.l[0]) == wmDelete) { ctx->lastEventType = NEO_EV_CLOSE_REQ; return NEO_EV_CLOSE_REQ; } continue; } if (ev.type == VisibilityNotify && ctx->visible) { if (ev.xvisibility.state != VisibilityUnobscured) { XRaiseWindow(dpy, ctx->w->win); XFlush(dpy); } continue; } if (ev.type == KeyPress || ev.type == KeyRelease) { KeySym sym = XLookupKeysym(&ev.xkey, 0); unsigned int kc = ev.xkey.keycode; int nkey = bananarchy::mapHardwareKey(sym, kc, ev.xkey.state); ctx->lastEventKey = nkey; ctx->lastEventKeycode = static_cast(kc); ctx->lastEventKeysym = static_cast(sym); int64_t tNow = bananarchy::monotonicMs(); if (!ctx->initialSoftkeysReleased) { if (bananarchy::querySoftkeysMask(dpy) == 0) { ctx->initialSoftkeysReleased = true; } else if (nkey == NEO_KEY_SOFT_LEFT || nkey == NEO_KEY_SOFT_RIGHT) { continue; } } if (tNow < ctx->startupIgnoreUntilMs && (nkey == NEO_KEY_SOFT_LEFT || nkey == NEO_KEY_SOFT_RIGHT)) { continue; } if (ev.type == KeyPress) { if (ctx->chordXdrawer && (nkey == NEO_KEY_SOFT_LEFT || nkey == NEO_KEY_SOFT_RIGHT)) { int curBit = (nkey == NEO_KEY_SOFT_LEFT) ? 1 : 2; int otherBit = (curBit == 1) ? 2 : 1; int kmMask = bananarchy::querySoftkeysMask(dpy); if (ctx->softkeyPending == otherBit || (kmMask & otherBit)) { ctx->softkeyPending = 0; neoui_ungrab(); bananarchy::sendPluginFifoMsg("xdrawer", "TOGGLE"); ctx->lastEventType = NEO_EV_SOFTKEY_CHORD; return NEO_EV_SOFTKEY_CHORD; } ctx->softkeyPending = curBit; ctx->softkeyDeadlineMs = tNow + 35; continue; } ctx->lastEventType = NEO_EV_KEY_PRESS; return NEO_EV_KEY_PRESS; } else { if (ctx->chordXdrawer && (nkey == NEO_KEY_SOFT_LEFT || nkey == NEO_KEY_SOFT_RIGHT)) { int curBit = (nkey == NEO_KEY_SOFT_LEFT) ? 1 : 2; if (ctx->softkeyPending == curBit) { ctx->softkeyPending = 0; ctx->lastEventType = (curBit == 1) ? NEO_EV_SOFTKEY_LEFT : NEO_EV_SOFTKEY_RIGHT; return ctx->lastEventType; } continue; } ctx->lastEventType = NEO_EV_KEY_RELEASE; return NEO_EV_KEY_RELEASE; } } } return NEO_EV_NONE; }; int imm = processNextXEvent(); if (imm != NEO_EV_NONE) return imm; // Calculate effective poll timeout int waitMs = timeout_ms; if (ctx->softkeyPending != 0) { int rem = static_cast( std::max(1, ctx->softkeyDeadlineMs - bananarchy::monotonicMs())); if (waitMs < 0 || rem < waitMs) waitMs = rem; } if (ctx->tapActive) { int rem = static_cast( std::max(1, (ctx->lastTapMs + 850) - bananarchy::monotonicMs())); if (waitMs < 0 || rem < waitMs) waitMs = rem; } struct pollfd pfds[2]; int nfds = 0; pfds[nfds++] = {ConnectionNumber(dpy), POLLIN, 0}; if (ctx->fifoFd >= 0) { pfds[nfds++] = {ctx->fifoFd, POLLIN, 0}; } int pr = ::poll(pfds, nfds, waitMs); if (pr > 0 && ctx->fifoFd >= 0 && (pfds[1].revents & POLLIN)) { char buf[512]; ssize_t n = ::read(ctx->fifoFd, buf, sizeof(buf) - 1); if (n > 0) { buf[n] = '\0'; std::stringstream ss(buf); std::string line; while (std::getline(ss, line)) { if (!line.empty() && line.back() == '\r') line.pop_back(); if (!line.empty()) ctx->pendingFifoCmds.push_back(line); } } } if (!ctx->pendingFifoCmds.empty()) { ctx->lastEventCmd = ctx->pendingFifoCmds.front(); ctx->pendingFifoCmds.erase(ctx->pendingFifoCmds.begin()); if (ctx->lastEventCmd == "RELOAD_THEME") { ctx->w->reloadTheme(); ctx->lastEventType = NEO_EV_THEME_RELOAD; return NEO_EV_THEME_RELOAD; } if (ctx->lastEventCmd == "CLOSE") { ctx->lastEventType = NEO_EV_CLOSE_REQ; return NEO_EV_CLOSE_REQ; } ctx->lastEventType = NEO_EV_FIFO_CMD; return NEO_EV_FIFO_CMD; } now = bananarchy::monotonicMs(); if (ctx->softkeyPending != 0 && now >= ctx->softkeyDeadlineMs) { int pend = ctx->softkeyPending; ctx->softkeyPending = 0; ctx->lastEventKey = (pend == 1) ? NEO_KEY_SOFT_LEFT : NEO_KEY_SOFT_RIGHT; ctx->lastEventType = (pend == 1) ? NEO_EV_SOFTKEY_LEFT : NEO_EV_SOFTKEY_RIGHT; return ctx->lastEventType; } if (ctx->tapActive && (now - ctx->lastTapMs >= 850)) { ctx->tapActive = false; ctx->lastTapKey = -1; ctx->tapCycleIdx = 0; ctx->lastEventType = NEO_EV_EXPOSE; return NEO_EV_EXPOSE; } return processNextXEvent(); } int neoui_event_key(void) { return gCtx ? gCtx->lastEventKey : NEO_KEY_NONE; } int neoui_event_keycode(void) { return gCtx ? gCtx->lastEventKeycode : 0; } int neoui_event_keysym(void) { return gCtx ? gCtx->lastEventKeysym : 0; } const char* neoui_event_command(void) { NeoContext* ctx = ensureCtx(); return ctx->lastEventCmd.c_str(); } int neoui_set_chord_xdrawer(int enabled) { NeoContext* ctx = ensureCtx(); ctx->chordXdrawer = (enabled != 0); return 1; } // --------------------------------------------------------------------------- // Multi-Tap Text Input Engine // --------------------------------------------------------------------------- int neoui_input_reset(const char* initial_text) { NeoContext* ctx = ensureCtx(); ctx->inputText = (initial_text && initial_text[0]) ? initial_text : ""; ctx->lastTapKey = -1; ctx->tapCycleIdx = 0; ctx->lastTapMs = 0; ctx->tapActive = false; return 1; } int neoui_input_set_text(const char* text) { NeoContext* ctx = ensureCtx(); ctx->inputText = (text && text[0]) ? text : ""; ctx->tapActive = false; ctx->lastTapKey = -1; ctx->tapCycleIdx = 0; return 1; } const char* neoui_input_get_text(void) { NeoContext* ctx = ensureCtx(); return ctx->inputText.c_str(); } int neoui_input_set_mode(int mode) { NeoContext* ctx = ensureCtx(); ctx->inputMode = std::clamp(mode, 0, 4); ctx->tapActive = false; ctx->lastTapKey = -1; return ctx->inputMode; } int neoui_input_get_mode(void) { return gCtx ? gCtx->inputMode : NEO_INPUT_ABC_TITLE; } int neoui_input_cycle_mode(void) { NeoContext* ctx = ensureCtx(); ctx->tapActive = false; ctx->lastTapKey = -1; ctx->inputMode = (ctx->inputMode + 1) % 5; return ctx->inputMode; } const char* neoui_input_mode_badge(void) { int mode = gCtx ? gCtx->inputMode : NEO_INPUT_ABC_TITLE; switch (mode) { case NEO_INPUT_ABC_TITLE: return "[Abc]"; case NEO_INPUT_ABC_LOWER: return "[abc]"; case NEO_INPUT_ABC_UPPER: return "[ABC]"; case NEO_INPUT_123: return "[123]"; case NEO_INPUT_SYM: return "[Sym]"; default: return "[Abc]"; } } int neoui_input_commit_tap(void) { if (!gCtx) return 0; gCtx->tapActive = false; gCtx->lastTapKey = -1; gCtx->tapCycleIdx = 0; return 1; } int neoui_input_backspace(void) { NeoContext* ctx = ensureCtx(); ctx->tapActive = false; ctx->lastTapKey = -1; ctx->tapCycleIdx = 0; if (ctx->inputText.empty()) return 0; bananarchy::popUtf8Char(ctx->inputText); return 1; } int neoui_input_is_tap_active(void) { if (!gCtx || !gCtx->tapActive) return 0; if (bananarchy::monotonicMs() - gCtx->lastTapMs >= 850) { gCtx->tapActive = false; gCtx->lastTapKey = -1; return 0; } return 1; } int neoui_input_feed_key(int neo_key) { NeoContext* ctx = ensureCtx(); int64_t now = bananarchy::monotonicMs(); if (ctx->tapActive && (now - ctx->lastTapMs >= 850)) { ctx->tapActive = false; ctx->lastTapKey = -1; ctx->tapCycleIdx = 0; } if (neo_key == NEO_KEY_HASH) { neoui_input_cycle_mode(); return 1; } if (neo_key == NEO_KEY_BACK) { return neoui_input_backspace(); } if (neo_key == NEO_KEY_RIGHT && ctx->tapActive) { return neoui_input_commit_tap(); } if (ctx->inputMode == NEO_INPUT_123) { if ((neo_key >= '0' && neo_key <= '9') || neo_key == '*' || neo_key == '+') { ctx->tapActive = false; ctx->lastTapKey = -1; ctx->inputText.push_back(static_cast(neo_key)); return 1; } return 0; } const char* table = tapTableForKey(ctx->inputMode, neo_key); if (!table || !table[0]) return 0; int tlen = static_cast(std::strlen(table)); if (ctx->tapActive && ctx->lastTapKey == neo_key && !ctx->inputText.empty()) { ctx->tapCycleIdx = (ctx->tapCycleIdx + 1) % tlen; bananarchy::popUtf8Char(ctx->inputText); } else { ctx->lastTapKey = neo_key; ctx->tapCycleIdx = 0; } char ch = table[ctx->tapCycleIdx]; if (shouldCapitalizeNext(ctx->inputText, ctx->inputMode, neo_key) && std::isalpha(static_cast(ch))) { ch = static_cast(std::toupper(static_cast(ch))); } ctx->inputText.push_back(ch); ctx->lastTapMs = now; ctx->tapActive = (tlen > 1); return 1; } const char* neoui_input_candidate_bar(const char* idle_hint) { NeoContext* ctx = ensureCtx(); if (neoui_input_is_tap_active()) { const char* table = tapTableForKey(ctx->inputMode, ctx->lastTapKey); if (table && table[0]) { std::string prefix = std::string(neoui_input_mode_badge()) + " "; std::string preTap = ctx->inputText; bananarchy::popUtf8Char(preTap); bool up = shouldCapitalizeNext(preTap, ctx->inputMode, ctx->lastTapKey); ctx->retCandBuf = bananarchy::formatMultiTapBar( prefix, table, ctx->tapCycleIdx, up, 7, 21); return ctx->retCandBuf.c_str(); } } std::string hint = (idle_hint && idle_hint[0]) ? idle_hint : "0-9 Type | *:Sym | #:Mode | Back:Del"; ctx->retCandBuf = std::string(neoui_input_mode_badge()) + " " + hint; return ctx->retCandBuf.c_str(); } int neoui_draw_multitap_bar(int x, int y, int w, int h, const char* idle_hint) { if (!gCtx || !gCtx->w || !gCtx->w->dpy || w <= 0 || h <= 0) return 0; const auto& spec = gCtx->w->theme.spec; bool active = (neoui_input_is_tap_active() != 0); neoui_fill_rect(x, y, w, h, active ? spec.bgInputFocus : spec.bgHeader); neoui_draw_rect(x, y, w, h, active ? spec.accent : spec.border); const char* barStr = neoui_input_candidate_bar(idle_hint); neoui_draw_text(NEO_FONT_SMALL, active ? NEO_TEXT_YELLOW : NEO_TEXT_MUTED, x + 6, y, h, barStr, w - 12); return 1; } // --------------------------------------------------------------------------- // 6. System & IPC Utilities // --------------------------------------------------------------------------- int neoui_send_plugin_cmd(const char* plugin_name, const char* cmd) { if (!plugin_name || !plugin_name[0] || !cmd) return 0; return bananarchy::sendPluginFifoMsg(plugin_name, cmd) ? 1 : 0; } int neoui_vibrate(int duration_ms) { int ms = std::clamp(duration_ms, 10, 2000); pid_t pid = ::fork(); if (pid == 0) { if (::fork() == 0) { ::setsid(); int nullfd = ::open("/dev/null", O_RDWR); if (nullfd >= 0) { ::dup2(nullfd, STDIN_FILENO); ::dup2(nullfd, STDOUT_FILENO); ::dup2(nullfd, STDERR_FILENO); if (nullfd > 2) ::close(nullfd); } char buf[16]; std::snprintf(buf, sizeof(buf), "%d", ms); ::execlp("sxmo_vibrate", "sxmo_vibrate", buf, static_cast(nullptr)); ::_exit(0); } ::_exit(0); } else if (pid > 0) { int st = 0; (void)::waitpid(pid, &st, 0); } return 1; } int neoui_now_ms(void) { return static_cast(bananarchy::monotonicMs() & 0x7fffffffLL); } } // extern "C"