diff --git a/AGENTS.md b/AGENTS.md index 50f3d43..0ff8db8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,7 +8,7 @@ It uses a pure **X11 (`Xlibre` + `sxmo-de-dwm`)** stack (no Wayland) optimized f ## 2. Repository layout - `src/sxmo-dwm/`: patched `dwm` window manager (`240x320` vertical `bstack` layout, 24px Pango status bar, desktop `"Menu"`/`"Names"` softkey bar, C-level `SW_LID` slider and locked-key wake handling, live `.Xresources` reload, and `.so` plugin loader via `dwm_plugin.h`). - `src/sxmo-dmenu/`: zero-lag resident DWM menu plugin (`dmenu.so`) and `/tmp/dwm_plugin_dmenu.sock` client (`dmenu` / `xdmenu`), featuring built-in Sxmo menus (`sys`, `applications`, `scripts`, `modem`, `config`, `power`, `audio`, `notifications`, `wm`, `timezone`, `games`, `st`, `nano`, `sthotkeys`) and `fcitx5-t9` XIM input. -- `src/neoui/`: **NeoUI** `240x320` UI SDK (`neoui.h` -> `/usr/include/neoui.h`, `neoui.cpp` -> `/usr/lib/libneoui.so`) providing both a C-compatible FFI (`neoui_*`) and C++20 classes (`ThemeSpec`, `PluginTheme`, `NeoWindow`) for `.Xresources` / `~/.xthemes/*.xth` theme resolution, Xlib/Xft/Pango window and offscreen `Pixmap` double buffering, standardized OS shell widgets, keypad/softkey chord handling, and multi-tap input. +- `src/neoui/`: **NeoUI** `240x320` UI SDK (`neoui.h` -> `/usr/include/neoui.h`, `neoui.cpp` -> `/usr/lib/libneoui.so`) providing both a C-compatible FFI (`neoui_*`) and C++20 classes (`ThemeSpec`, `PluginTheme`, `NeoWindow`) for `.Xresources` / `~/.xthemes/*.xth` theme resolution, Xlib/Xft/Pango window and offscreen `Pixmap` double buffering, standardized OS shell widgets, keypad/softkey chord handling, and multi-tap input (paired with Yabasic FFI libraries `neoui.yab` and `neonet.yab` + demos `neoui_demo.yab` and `neonet_demo.yab` in `overlay/rootfs/home/user/Projects/`). - `src/dwm-plugins/`: preloaded C++20 `240x320` DWM plugins linked against `libneoui.so` and shared headers: - `theme.h`: header forwarding to `../neoui/neoui.h` for unified `.Xresources` / `~/.xthemes/*.xth` parsing, proportional font sizing (`theme.baseFontSize`), automatic shade derivation, and live Xft/Pango theme reloading (`PluginTheme`). - `phone_data.h`: shared X11 geometry (`240x296` below the 24px bar), FIFO IPC (`/tmp/dwm_plugin_.fifo`), softkey chord detection, Sxmo TSV contact/call/SMS parsers, and `libjpeg`/`libpng` helpers. diff --git a/CHANGELOG.md b/CHANGELOG.md index 06f63dc..0356f8a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -21,16 +21,18 @@ Release versions follow the `
` format (where `2026` is `a`, - 10 built-in DMG color palettes, 4 screen scaling modes (`Fit 240x216` 1.5x area-interpolated, `1:1 160x144`, `Fill 240x246`, `Full 240x296`), 10 save-state slots (`.st0`–`.st9`), automatic battery SRAM/RTC persistence, seamless `Xdrawer` focus handoff, and direct low-latency `libasound` (`hw:0,0`) audio with hardware volume synchronization and analog-stage low-pass filtering. - Preinstalled open-source / public-domain GB and GBC games in `/usr/share/games/gb/` and `~/Games/` (`2048.gb`, `adjustris.gb`, `blastah.gb`, `brickster.gbc`, `geometrix.gbc`, `ucity.gbc`). - **Preinstalled scripting, calculation tools, and file manager (`xfiles`) integration**: - - Added **Lua** (`lua5.5` and `lua5.4` with `/usr/bin/lua` and `/usr/bin/luac`), **GNU `bc` / `dc`**, and **Yabasic (`yabasic`)** to the default system image. + - Added **Lua** (`lua5.5` and `lua5.4` with `/usr/bin/lua` and `/usr/bin/luac`), **GNU `bc` / `dc`**, **`mandoc`**, and **Yabasic (`yabasic` and `yabasic-doc`)** to the default system image. - Selecting any `.yab` file in **file manager (`xfiles`)** (or choosing `Run in Yabasic (Terminal)` in its actions menu) runs `yabasic` inside the `st` terminal and pauses on exit so output can be inspected. - Added an **integrated GUI text editor (`Edit in Text Editor`)** inside `xfiles`, available as an action on any file (and automatically opened when creating a new file or pressing `Edit` in the text viewer), featuring line numbers, 2D cursor navigation, 5 multi-tap input modes (`[abc]`, `[Abc]`, `[ABC]`, `[123]`, `[Sym]`), a scrolling bottom candidate bar for long symbol tables (`1` key), and an editor menu (`Save File`, `Save & Close`, `Insert New Line`, `Insert Space`, `Duplicate Line`, `Delete Line`, `Close Without Saving`). -- **NeoUI `240x320` UI SDK (`libneoui.so` + `/usr/include/neoui.h` + `neoui.yab`)**: +- **NeoUI `240x320` UI SDK (`libneoui.so` + `/usr/include/neoui.h` + `neoui.yab`) and NeoNet (`neonet.yab`)**: - Standardized all Bananarchy `240x320` X11/Xft/Pango UI components, `.Xresources` / `~/.xthemes/*.xth` live theme resolution, offscreen `Pixmap` double buffering, FIFO IPC, softkey chord detection (`xdrawer`), and multi-tap input into a shared library (`/usr/lib/libneoui.so`) and header (`/usr/include/neoui.h`) with both C++20 classes and a C-compatible FFI (`neoui_*`). - Migrated all 14 custom GUI plugins (`xdrawer`, `dialer`, `calllog`, `callscreen`, `contacts`, `sms`, `files`, `camera`, `themes`, `modem`, `networks`, `ringtones`, `wallpapers`, `music`) to use `NeoUI`. - - Added a complete Yabasic native C FFI wrapper (`~/Projects/neoui.yab`, symlinked at `/usr/lib/neoui.yab`), an interactive 3-tab showcase program (`~/Projects/neoui_demo.yab`), and full SDK documentation in `SDK.md`. + - Added a complete Yabasic native C FFI wrapper (`~/Projects/neoui.yab`, symlinked at `/usr/lib/neoui.yab`), an interactive 3-tab UI showcase program (`~/Projects/neoui_demo.yab`), a `libcurl` + socket FFI networking library for Yabasic (`~/Projects/neonet.yab`, symlinked at `/usr/lib/neonet.yab`) supporting HTTP/HTTPS requests with custom headers and raw TCP/TLS/UDP socket data exchange, a combined NeoNet + NeoUI demo (`~/Projects/neonet_demo.yab`), and full SDK documentation in `SDK.md`. - **Camera viewfinder and capture orientation fix (`xcamera` and `bananarchy-photo`)**: - Rotated the raw `800x600` `GC2395` sensor frames 90 degrees clockwise in both the live `240x180` 4:3 viewfinder (`downscaleViewfinder800x600To240x180`) and captured JPEG photos (`600x800` portrait output in `xcamera` and `bananarchy-photo`). -- **Menu refinements**: +- **Window management, context menu, and `fcitx5` XIM stability fixes**: + - Added direct C-level `_BANANARCHY_DWM_CMD` IPC between `dmenu` and `dwm` for instant window management (`Kill window`, `Close Terminal`, `Move to WS 1..4`, `Go to WS 1..4`, `Shift stack`, `Swap stack`, `Toggle Layout`) and restored application context menus (`Right softkey` inside `st`, `nano`, and X11 apps). + - Updated the `fcitx5` `superd` service wrapper (`bananarchy-fcitx5.sh`) and XIM environment propagation across `st`, `dmenu`, and `dwm-plugin` so T9 keypad input stays supervised and active across all terminal and menu sessions. - Removed the non-applicable `Toggle Bar` entry from the `Config` menu. --- diff --git a/MANUAL.md b/MANUAL.md index 3ab711e..be13407 100644 --- a/MANUAL.md +++ b/MANUAL.md @@ -26,7 +26,7 @@ This manual covers flashing, operating, and customizing **Bananarchy Linux** (`2 - **Patched `dwm`** provides a `240x320` vertical bottom-stack (`bstack`) layout, a 24px top status bar, a transparent `"Menu"` / `"Names"` desktop softkey bar, a Conky desktop clock and status widget (which refreshes automatically when changing time, timezone, or wallpaper, or when logging out), and `< 2 ms` handling of physical slider (`SW_LID`) and wake keys. 2. **Preloaded resident DWM plugins (`< 2 ms` wakeup)**: - Core phone applications (`dmenu`, `xdrawer`, `dialer`, `calllog`, `callscreen`, `contacts`, `sms`, `files`, `camera`, `themes`, `modem`, `networks`, `ringtones`, `wallpapers`, `music`) run as preloaded resident daemons (`dwm-plugin --preload`) that sleep at 0% CPU and open instantaneously over FIFO/socket IPC. - - All UI elements share the **NeoUI SDK (`libneoui.so` + `/usr/include/neoui.h`)** and a single **XRDB theming engine** (`~/.xthemes/*.xth` -> `~/.Xresources`) with 20 preinstalled color schemes, proportional font sizing (`theme.baseFontSize`), and live reload without restarting X11. NeoUI exposes both C++20 classes and a C-compatible FFI (`neoui_*`) for building custom native or scripted (`yabasic` via `~/Projects/neoui.yab`, etc.) `240x320` GUI applications — see [SDK.md](./SDK.md) for the complete API reference and examples. + - All UI elements share the **NeoUI SDK (`libneoui.so` + `/usr/include/neoui.h`)** and a single **XRDB theming engine** (`~/.xthemes/*.xth` -> `~/.Xresources`) with 20 preinstalled color schemes, proportional font sizing (`theme.baseFontSize`), and live reload without restarting X11. NeoUI exposes both C++20 classes and a C-compatible FFI (`neoui_*`) for building custom native or scripted (`yabasic` via `~/Projects/neoui.yab` and `~/Projects/neoui_demo.yab`, paired with **NeoNet** in `~/Projects/neonet.yab` and `~/Projects/neonet_demo.yab` for `libcurl` HTTP/HTTPS and TCP/TLS/UDP socket networking) `240x320` GUI applications — see [SDK.md](./SDK.md) for the complete API reference and examples. 3. **First-class terminal (`st`) and 6-mode `fcitx5-t9` keypad input**: - `st` is patched with HarfBuzz OpenType ligature shaping (`Fira Code` default) and live `.Xresources` reload. - `fcitx5-t9` provides 6 keypad input modes (`abc`, `Abc`, `ABC`, `Sym`, `Ctl`, `123` + `*` long-press `Ctrl+` latch) in a fixed bottom candidate bar (`Y = 290, H = 30`). @@ -105,7 +105,8 @@ sudo dd if=./images/bananarchy-nokia-argon.img of=/dev/sdX bs=4M status=progress #### 3.1.1 Window tiling modes and switching combos By default, `dwm` uses the **vertical bottom-stack (`bstack`, `TTT`)** layout so multiple `st` terminals stack **vertically (one under another)** to preserve full line width on the `240x320` portrait screen. -You can switch layouts and focus using either physical keypad multi-presses or an external keyboard (`Mod4` / `Super`): +You can switch layouts, focus, and workspaces using the **Window management menu (`Windows`)** (accessible via `Left softkey -> Windows`, or by pressing **Right softkey** inside non-terminal applications, or selecting `Windows` from the `st` terminal context menu), physical keypad multi-presses, or an external keyboard (`Mod4` / `Super`): +- **Window management menu (`WM Menu`)**: provides instant C-level window actions (`Move to WS 1`..`4`, `Shift stack`, `Swap stack`, `Toggle Layout`, `Kill window`, and `Go to WS 1`..`4`), plus `Close Terminal` in the `st` context menu. - **Triple-press Call (green) (`3x Call`)**: cycle the active layout (`TTT` -> `[]=` -> `[D]` -> `[M]` -> `TTT`). - **Double-press Call (green) (`2x Call`)**: move focus to the next open window (`Super+j`). - **Triple-press End / Power (red) (`3x End`)**: launch a new `st` terminal in the active workspace. diff --git a/README.md b/README.md index f35ca40..8055dc7 100644 --- a/README.md +++ b/README.md @@ -8,7 +8,7 @@ - **Download the recent images for your device from this link**: https://cloud.disroot.org/s/dB7bM7sRTScetDJ - **Project philosophy**: read [The Bananarchy Manifesto](./MANIFESTO.md) for the background and goals behind the distribution. - **User and flashing guide**: see the [user manual](./MANUAL.md) for installation, keypad navigation, and hardware details. -- **UI SDK reference**: see the [NeoUI SDK guide](./SDK.md) for building native C, C++, and Yabasic `240x320` GUI applications. +- **UI and networking SDK reference**: see the [NeoUI and NeoNet SDK guide](./SDK.md) for building native C, C++, and Yabasic `240x320` GUI and networked applications. --- @@ -33,8 +33,8 @@ Instead of spawning slow shell scripts for everyday phone tasks, Bananarchy runs ### Input, terminal, and developer tools - **6-mode `fcitx5-t9` keypad input**: press `#` to cycle between `abc`, `Abc`, `ABC`, `Sym` (all 32 ASCII punctuation symbols), `Ctl` (`Ctrl` sequences, arrows, `PageUp`/`PageDown`, `F1`–`F12`), and `123` numeric modes with a fixed bottom candidate bar. - **First-class Linux terminal (`st`)**: patched with HarfBuzz OpenType ligatures (`Fira Code` as the default system and terminal font), XIM T9 input, and live theme reloading. -- **On-device development, scripting, and gaming**: preinstalled `gcc`/`g++`, `make`, `git`, GNU `coreutils`, GNU `bc`/`dc`, `nano`, `ed`, `sqlite3`, `lua` (`5.5` and `5.4`), `yabasic`, `perl`, `tcl`, the [Janet](https://janet-lang.org/) language and `jpm`, the [Bantam](https://bantam.luxferre.top/) coding agent, `frotz` (interactive fiction), standalone X11 keypad games (`Snake` and `Tetris`), and a full-featured Gambatte-based Game Boy / Game Boy Color emulator (`gambatte` / `gbemu`) with readjustable keypad controls (`B=8`, `Turbo B=5`, `A=9`, `Turbo A=6`, `D-pad`, `Start=2`, `Select=3`, `Palette=*`), 10 color palettes, save states, and file manager `.gb`/`.gbc` integration. -- **NeoUI 240x320 UI SDK (`libneoui.so` + `/usr/include/neoui.h` + `neoui.yab`)**: unified C-compatible FFI and C++20 UI SDK wrapping Xlib, Xft, Pango, `libjpeg`/`libpng`, `.Xresources` / `~/.xthemes/*.xth` live theme resolution, offscreen `Pixmap` double buffering, standardized OS shell widgets (headers, tabs, softkey bars, list/toggle/slider rows, input boxes, progress bars, scrollbars, modals, popup menus, and toasts), keypad/softkey chord handling, and multi-tap text entry—usable from C, C++, or Yabasic (`~/Projects/neoui.yab` and `~/Projects/neoui_demo.yab`). See [SDK.md](./SDK.md) for full documentation. +- **On-device development, scripting, and gaming**: preinstalled `gcc`/`g++`, `make`, `git`, GNU `coreutils`, GNU `bc`/`dc`, `mandoc`, `nano`, `ed`, `sqlite3`, `lua` (`5.5` and `5.4`), `yabasic` (with full `yabasic-doc` manual and HTML documentation), `perl`, `tcl`, the [Janet](https://janet-lang.org/) language and `jpm`, the [Bantam](https://bantam.luxferre.top/) coding agent, `frotz` (interactive fiction), standalone X11 keypad games (`Snake` and `Tetris`), and a full-featured Gambatte-based Game Boy / Game Boy Color emulator (`gambatte` / `gbemu`) with readjustable keypad controls (`B=8`, `Turbo B=5`, `A=9`, `Turbo A=6`, `D-pad`, `Start=2`, `Select=3`, `Palette=*`), 10 color palettes, save states, and file manager `.gb`/`.gbc` integration. +- **NeoUI `240x320` UI SDK (`libneoui.so` + `/usr/include/neoui.h` + `neoui.yab`) and NeoNet (`neonet.yab`)**: unified C-compatible FFI and C++20 UI SDK wrapping Xlib, Xft, Pango, `libjpeg`/`libpng`, `.Xresources` / `~/.xthemes/*.xth` live theme resolution, offscreen `Pixmap` double buffering, standardized OS shell widgets (headers, tabs, softkey bars, list/toggle/slider rows, input boxes, progress bars, scrollbars, modals, popup menus, and toasts), keypad/softkey chord handling, and multi-tap text entry—usable from C, C++, or Yabasic (`~/Projects/neoui.yab` and `~/Projects/neoui_demo.yab`), paired with **NeoNet (`~/Projects/neonet.yab` and `~/Projects/neonet_demo.yab`)** for `libcurl`-based HTTP/HTTPS requests with custom headers and TCP/TLS/UDP socket exchange in Yabasic. See [SDK.md](./SDK.md) for full documentation. --- diff --git a/SDK.md b/SDK.md index 9d98bb9..c88cdec 100644 --- a/SDK.md +++ b/SDK.md @@ -1,11 +1,12 @@ -# Bananarchy NeoUI SDK reference (`SDK.md`) +# Bananarchy NeoUI and NeoNet SDK reference (`SDK.md`) -**NeoUI** (`libneoui.so` + `/usr/include/neoui.h`) is the native `240x320` QVGA graphical user interface SDK for **Bananarchy Linux**. +**NeoUI** (`libneoui.so` + `/usr/include/neoui.h`) is the native `240x320` QVGA graphical user interface SDK for **Bananarchy Linux**, paired with **NeoNet** (`neonet.yab`), a `libcurl` + POSIX socket C FFI networking library for Yabasic. -It encapsulates all low-level X11 (`Xlib`), `Xft`, `Pango`, `libjpeg-turbo`, `libpng`, `.Xresources` / `~/.xthemes/*.xth` live theme resolution, offscreen `Pixmap` double buffering, standardized OS shell widgets, FIFO IPC, softkey chord handling (`Left+Right` softkey -> `xdrawer`), and multi-tap T9 keypad input behind: +They encapsulate all low-level X11 (`Xlib`), `Xft`, `Pango`, `libjpeg-turbo`, `libpng`, `.Xresources` / `~/.xthemes/*.xth` live theme resolution, offscreen `Pixmap` double buffering, standardized OS shell widgets, FIFO IPC, softkey chord handling (`Left+Right` softkey -> `xdrawer`), multi-tap T9 keypad input, and HTTP/HTTPS/TCP/TLS/UDP networking behind: 1. A **C-compatible FFI (`neoui_*`)** designed for both C programs and foreign-function interfaces (such as **Yabasic** `frnfn_call` / `frnfn_call$`, LuaJIT FFI, Janet, Python `ctypes`, etc.). 2. A **C++20 SDK (`namespace bananarchy`)** providing `ThemeSpec`, `PluginTheme`, `NeoWindow`, and direct Pango/Xft/image helpers used across all 14 built-in Bananarchy DWM plugins. -3. A **Yabasic wrapper library (`neoui.yab`)** preinstalled in `/home/user/Projects/neoui.yab` (and symlinked at `/usr/lib/neoui.yab`), paired with a full showcase application (`/home/user/Projects/neoui_demo.yab`). +3. A **Yabasic UI wrapper library (`neoui.yab`)** preinstalled in `/home/user/Projects/neoui.yab` (and symlinked at `/usr/lib/neoui.yab`), paired with a full showcase application (`/home/user/Projects/neoui_demo.yab`). +4. A **Yabasic networking wrapper library (`neonet.yab`)** preinstalled in `/home/user/Projects/neonet.yab` (and symlinked at `/usr/lib/neonet.yab`), wrapping `libcurl.so.4` and musl `libc` via `libffi` for one-line HTTP/HTTPS requests with custom headers as well as raw TCP, TLS, and UDP socket data exchange, paired with a combined NeoNet + NeoUI demo application (`/home/user/Projects/neonet_demo.yab`). --- @@ -15,9 +16,12 @@ It encapsulates all low-level X11 (`Xlib`), `Xft`, `Pango`, `libjpeg-turbo`, `li | :--- | :--- | :--- | | `/usr/lib/libneoui.so` | `src/neoui/neoui.cpp` | Shared library (`armv7` hard-float) implementing the C FFI and C++20 SDK | | `/usr/include/neoui.h` | `src/neoui/neoui.h` | Unified C99 and C++20 header file | -| `/home/user/Projects/neoui.yab` | `overlay/rootfs/home/user/Projects/neoui.yab` | Yabasic native C FFI wrapper module (`import neoui`) | +| `/home/user/Projects/neoui.yab` | `overlay/rootfs/home/user/Projects/neoui.yab` | Yabasic native C FFI wrapper module for NeoUI (`import neoui`) | | `/usr/lib/neoui.yab` | `overlay/rootfs/usr/lib/neoui.yab` | Symlink to `/home/user/Projects/neoui.yab` so `import neoui` works from any working directory | | `/home/user/Projects/neoui_demo.yab` | `overlay/rootfs/home/user/Projects/neoui_demo.yab` | Interactive 3-tab Yabasic showcase demonstrating all NeoUI widgets, multi-tap input, custom drawing, modals, and live theme reload | +| `/home/user/Projects/neonet.yab` | `overlay/rootfs/home/user/Projects/neonet.yab` | Yabasic native `libcurl` + socket FFI wrapper module for NeoNet (`import neonet`) | +| `/usr/lib/neonet.yab` | `overlay/rootfs/usr/lib/neonet.yab` | Symlink to `/home/user/Projects/neonet.yab` so `import neonet` works from any working directory | +| `/home/user/Projects/neonet_demo.yab` | `overlay/rootfs/home/user/Projects/neonet_demo.yab` | Interactive 3-tab Yabasic showcase combining NeoNet and NeoUI (`1:HTTP/S`, `2:Sockets`, `3:Tools`) | ### Key design principles - **Zero-flicker offscreen double buffering**: every NeoUI window (`240x296` at `X=0, Y=24`, directly below the 24px `dwm` top status bar) renders into an offscreen X11 `Pixmap` during `neoui_begin_frame()` .. `neoui_end_frame()` and copies the completed frame to the visible window in a single `XCopyArea` call. @@ -526,3 +530,127 @@ wend neoui_shutdown() ``` + +--- + +## 6. NeoNet networking SDK reference for Yabasic (`neonet.yab`) + +**NeoNet** (`/home/user/Projects/neonet.yab`, symlinked at `/usr/lib/neonet.yab`) is the native networking library for Yabasic on Bananarchy Linux. It wraps `/usr/lib/libcurl.so.4` (`OpenSSL`, `nghttp2`, `zlib`, `brotli`, `zstd`, `c-ares`) and musl `libc` (`open_memstream`, `getaddrinfo`, `socket`, `connect`, `send`, `recv`, `poll`) via Yabasic's native `libffi` interface (`frnfn_call`, `frnfn_call$`, and `frnbf_*`). + +### 6.1 Importing `neonet.yab` and running the demo +Because `/usr/lib/neonet.yab` is symlinked to `/home/user/Projects/neonet.yab`, any Yabasic program can import both `neoui` and `neonet`: +```yabasic +import neoui +import neonet +``` +- **From the file manager (`xfiles`)**: navigate to `/home/user/Projects/`, highlight `neonet_demo.yab`, and press **Center `OK` (`Return`)**. +- **From a terminal or SSH**: + ```bash + DISPLAY=:0 yabasic ~/Projects/neonet_demo.yab + ``` + +### 6.2 Module constants (`neonet.*`) + +| Yabasic constant | Value | Description | +| :--- | :--- | :--- | +| `neonet.PROTO_TCP` | `1` | Raw TCP socket via `libcurl` (`CURLOPT_CONNECT_ONLY`) | +| `neonet.PROTO_TLS` | `2` | TLS-encrypted socket via `libcurl` (`CURLOPT_CONNECT_ONLY` with ALPN disabled for raw TLS protocols) | +| `neonet.PROTO_UDP` | `3` | Connectionless UDP datagram socket via musl `libc` (`SOCK_DGRAM`) | +| `neonet.CURLE_OK` | `0` | Operation succeeded | +| `neonet.CURLE_COULDNT_RESOLVE_HOST` | `6` | DNS resolution failed | +| `neonet.CURLE_COULDNT_CONNECT` | `7` | TCP/UDP connection refused or unreachable | +| `neonet.CURLE_OPERATION_TIMEDOUT` | `28` | Transfer or socket operation timed out | +| `neonet.CURLE_SSL_CONNECT_ERROR` | `35` | TLS handshake failed | +| `neonet.CURLE_PEER_FAILED_VERIFICATION` | `60` | Remote TLS certificate verification failed | +| `neonet.CURLE_AGAIN` | `81` | Non-blocking socket would block | + +### 6.3 Exported Yabasic functions in `neonet.yab` + +#### 1. Lifecycle, version, and configuration +- `neonet_init()`: initializes `libcurl` (`curl_global_init`) and resets the socket table; returns `1` on success (`0` on error). Automatically called on first use if omitted. +- `neonet_cleanup()`: closes all active sockets, clears queued custom headers, and calls `curl_global_cleanup()`. +- `neonet_version$()`: returns the `libcurl` and TLS/compression runtime version string (e.g. `"libcurl/8.23.0 OpenSSL/3.5.9 ..."`). +- `neonet_strerror$(curl_code)`: returns the human-readable error message for `curl_code`. +- `neonet_set_timeout(timeout_ms)`: sets the overall transfer timeout in milliseconds (default `15000`). +- `neonet_set_connect_timeout(connect_timeout_ms)`: sets the connection timeout in milliseconds (default `8000`). +- `neonet_set_user_agent(ua$)`: sets the default `User-Agent` header (default `"Bananarchy-NeoNet/1.0 (libcurl)"`). +- `neonet_set_follow_redirects(enabled)`: enables (`1`, default) or disables (`0`) automatic HTTP `3xx` redirect following. +- `neonet_set_max_redirects(max_redirs)`: sets the maximum number of redirects to follow (default `10`). +- `neonet_set_insecure(insecure)`: when `1`, disables TLS peer and hostname certificate checks (`CURLOPT_SSL_VERIFYPEER = 0`, `CURLOPT_SSL_VERIFYHOST = 0`); when `0` (default), enforces strict verification. +- `neonet_set_proxy(proxy_url$)`: sets an HTTP or SOCKS proxy URL (e.g. `"socks5h://127.0.0.1:9050"`, or `""` to disable). +- `neonet_set_basic_auth(user_pwd$)`: sets HTTP Basic authentication credentials (`"user:password"`, or `""` to disable). + +#### 2. Custom request headers and URL encoding +- `neonet_clear_headers()`: clears all persistent custom HTTP headers added via `neonet_add_header()`. +- `neonet_add_header(header_line$)`: appends a persistent custom header (e.g. `"Authorization: Bearer my_token"` or `"X-Api-Key: 12345"`) sent with subsequent HTTP/HTTPS requests. +- `neonet_url_encode$(text$)`: percent-encodes `text$` via `curl_easy_escape`. +- `neonet_url_decode$(text$)`: decodes percent-encoded `text$` via `curl_easy_unescape`. + +#### 3. HTTP and HTTPS request functions +*(Inline `headers$` arguments accept `""` for none, or multiple headers separated by `|` or `\n`, e.g. `"Accept: application/json|X-Client: Bananarchy"`, which are merged with any persistent headers from `neonet_add_header()`.)* +- `neonet_get$(url$)`: performs an HTTP/HTTPS `GET` request and returns the response body string. +- `neonet_get_ex$(url$, headers$)`: performs an HTTP/HTTPS `GET` request with inline custom headers and returns the response body string. +- `neonet_post$(url$, body$, content_type$, headers$)`: performs an HTTP/HTTPS `POST` request with `body$`, optional `content_type$` (e.g. `"application/json"`), and optional `headers$`, returning the response body string. +- `neonet_put$(url$, body$, content_type$, headers$)`: performs an HTTP/HTTPS `PUT` request and returns the response body string. +- `neonet_patch$(url$, body$, content_type$, headers$)`: performs an HTTP/HTTPS `PATCH` request and returns the response body string. +- `neonet_delete$(url$, headers$)`: performs an HTTP/HTTPS `DELETE` request and returns the response body string. +- `neonet_head(url$, headers$)`: performs an HTTP/HTTPS `HEAD` request (`CURLOPT_NOBODY = 1`) and returns the HTTP status code (`200`, `404`, etc.), populating `neonet_response_headers$()`. +- `neonet_request$(method$, url$, body$, headers$)`: general-purpose HTTP/HTTPS request for any verb (`"GET"`, `"POST"`, `"PUT"`, `"PATCH"`, `"DELETE"`, `"HEAD"`, `"OPTIONS"`), request body, and custom headers. +- `neonet_download(url$, dest_path$, headers$)`: downloads `url$` directly to `dest_path$` on disk; returns `1` on HTTP `2xx`/`3xx` success or `0` on error. + +#### 4. HTTP response metadata and header inspection +- `neonet_status()`: returns the HTTP status code from the last transfer (e.g. `200`, `201`, `404`, `500`, or `0` on transport failure). +- `neonet_last_code()`: returns the `CURLcode` from the last operation (`0` = `CURLE_OK`). +- `neonet_error$()`: returns `""` on success, or the human-readable error string on failure. +- `neonet_body$()`: returns the last response body string. +- `neonet_body_len()`: returns the byte length of the last response body. +- `neonet_response_headers$()`: returns the raw HTTP response header block from the last transfer. +- `neonet_header$(name$)`: performs a case-insensitive lookup of a response header from the last transfer (e.g. `neonet_header$("content-type")`, `neonet_header$("server")`, `neonet_header$("date")`). +- `neonet_content_type$()`: returns `CURLINFO_CONTENT_TYPE` from `libcurl`. +- `neonet_effective_url$()`: returns the final effective URL after redirects (`CURLINFO_EFFECTIVE_URL`). +- `neonet_primary_ip$()`: returns the remote server IP address (`CURLINFO_PRIMARY_IP`). + +#### 5. TCP, TLS, and UDP socket data exchange +- **Session-based socket functions**: + - `neonet_connect(proto, host$, port)`: opens a socket with protocol `neonet.PROTO_TCP`, `neonet.PROTO_TLS`, or `neonet.PROTO_UDP` to `host$:port`; returns a socket handle `sock_id >= 0` on success or `-1` on error. + - `neonet_tcp_connect(host$, port)`: shorthand for `neonet_connect(neonet.PROTO_TCP, host$, port)`. + - `neonet_tls_connect(host$, port)`: shorthand for `neonet_connect(neonet.PROTO_TLS, host$, port)`. + - `neonet_udp_open(host$, port)`: shorthand for `neonet_connect(neonet.PROTO_UDP, host$, port)`. + - `neonet_send(sock_id, data$)`: sends string `data$` over `sock_id`; returns the number of bytes sent (`>= 0`) or `-1` on error. + - `neonet_send_bytes(sock_id, frn_buf$, byte_len)`: sends `byte_len` raw bytes from a Yabasic foreign buffer (`frnbf_alloc$`) over `sock_id`; returns bytes sent or `-1` on error. + - `neonet_recv$(sock_id, max_bytes, timeout_ms)`: waits up to `timeout_ms` and reads up to `max_bytes` bytes as a string (`neonet_last_len()` returns the byte count). + - `neonet_recv_all$(sock_id, max_bytes, timeout_ms)`: reads chunks from a TCP/TLS stream until EOF, `max_bytes`, or idle timeout, and returns the combined string. + - `neonet_recv_bytes(sock_id, frn_buf$, max_bytes, timeout_ms)`: waits up to `timeout_ms` and reads up to `max_bytes` raw bytes into foreign buffer `frn_buf$`, returning the number of bytes read (`> 0`), `0` on EOF/timeout, or `-1` on error. + - `neonet_last_len()`: returns the byte count transferred by the most recent socket or HTTP operation. + - `neonet_close(sock_id)`: closes socket `sock_id` and releases its slot. +- **One-shot socket exchange and DNS helpers**: + - `neonet_tcp_exchange$(host$, port, payload$, timeout_ms)`: connects via TCP, sends `payload$`, reads the response, closes the socket, and returns the response string. + - `neonet_tls_exchange$(host$, port, payload$, timeout_ms)`: connects via TLS, sends `payload$`, reads the response, closes the socket, and returns the response string. + - `neonet_udp_exchange$(host$, port, payload$, timeout_ms)`: sends a UDP datagram `payload$` to `host$:port`, waits up to `timeout_ms` for a reply datagram, closes the socket, and returns the reply string. + - `neonet_system_dns$()`: returns the primary `nameserver` IP address from `/etc/resolv.conf` (fallback `"1.1.1.1"`). + - `neonet_udp_dns_a$(dns_server$, domain$, timeout_ms)`: sends a binary RFC 1035 UDP DNS A-record query to `dns_server$:53` (or the system DNS if `dns_server$ = ""`) and returns the resolved IPv4 address string. + +### 6.4 Minimal Yabasic NeoNet + NeoUI example +```yabasic +#!/usr/bin/yabasic +import neoui +import neonet + +r = neonet_init() + +// 1. HTTPS GET with custom headers +body$ = neonet_get_ex$("https://example.com/", "X-Bananarchy: NeoNet-1.0|Accept: text/html") +print "HTTP status: ", neonet_status(), " (", neonet_body_len(), " bytes from ", neonet_primary_ip$(), ")" +print "Server header: ", neonet_header$("server") + +// 2. One-shot TCP WHOIS query (port 43) +whois$ = neonet_tcp_exchange$("whois.iana.org", 43, "example.com" + chr$(13) + chr$(10), 4000) +print "WHOIS bytes: ", neonet_last_len() + +// 3. Binary UDP DNS A-record lookup (port 53) +ip$ = neonet_udp_dns_a$("", "example.com", 3000) +print "UDP DNS resolved example.com -> ", ip$ + +r = neonet_cleanup() +``` + diff --git a/overlay/rootfs/home/user/Projects/neonet.yab b/overlay/rootfs/home/user/Projects/neonet.yab new file mode 100644 index 0000000..3e62e72 --- /dev/null +++ b/overlay/rootfs/home/user/Projects/neonet.yab @@ -0,0 +1,1361 @@ +// ============================================================================ +// neonet.yab - Yabasic Native C FFI Wrapper for Bananarchy NeoNet (libcurl) +// ============================================================================ +// Exposes easy HTTP/HTTPS requests (GET, POST, PUT, PATCH, DELETE, HEAD, +// custom methods, custom headers, file downloads, URL encode/decode, and +// response header inspection) as well as raw TCP, TLS, and UDP socket data +// exchange to Yabasic programs via libffi (frnfn_call / frnfn_call$). +// +// Usage in your Yabasic program: +// import neonet +// body$ = neonet_get$("https://example.com/") +// print "HTTP ", neonet_status(), " (", neonet_body_len(), " bytes)" +// ============================================================================ + +CURL_LIB$ = "/usr/lib/libcurl.so.4" +LIBC_SO$ = "/lib/ld-musl-armhf.so.1" + +// ---------------------------------------------------------------------------- +// Socket Protocol Constants for neonet_connect(proto, host$, port) +// ---------------------------------------------------------------------------- +PROTO_TCP = 1 +PROTO_TLS = 2 +PROTO_UDP = 3 + +// ---------------------------------------------------------------------------- +// Common libcurl Error Codes (CURLcode) +// ---------------------------------------------------------------------------- +CURLE_OK = 0 +CURLE_UNSUPPORTED_PROTOCOL = 1 +CURLE_FAILED_INIT = 2 +CURLE_URL_MALFORMAT = 3 +CURLE_COULDNT_RESOLVE_PROXY = 5 +CURLE_COULDNT_RESOLVE_HOST = 6 +CURLE_COULDNT_CONNECT = 7 +CURLE_HTTP_RETURNED_ERROR = 22 +CURLE_WRITE_ERROR = 23 +CURLE_OPERATION_TIMEDOUT = 28 +CURLE_SSL_CONNECT_ERROR = 35 +CURLE_TOO_MANY_REDIRECTS = 47 +CURLE_GOT_NOTHING = 52 +CURLE_SEND_ERROR = 55 +CURLE_RECV_ERROR = 56 +CURLE_PEER_FAILED_VERIFICATION = 60 +CURLE_AGAIN = 81 + +// ---------------------------------------------------------------------------- +// Internal libcurl Option & Info Constants +// ---------------------------------------------------------------------------- +CURLOPT_WRITEDATA = 10001 +CURLOPT_URL = 10002 +CURLOPT_PORT = 3 +CURLOPT_PROXY = 10004 +CURLOPT_USERPWD = 10005 +CURLOPT_USERAGENT = 10018 +CURLOPT_HTTPHEADER = 10023 +CURLOPT_HEADERDATA = 10029 +CURLOPT_CUSTOMREQUEST = 10036 +CURLOPT_NOBODY = 44 +CURLOPT_POST = 47 +CURLOPT_FOLLOWLOCATION = 52 +CURLOPT_POSTFIELDSIZE = 60 +CURLOPT_SSL_VERIFYPEER = 64 +CURLOPT_MAXREDIRS = 68 +CURLOPT_HTTPGET = 80 +CURLOPT_SSL_VERIFYHOST = 81 +CURLOPT_HTTP_VERSION = 84 +CURLOPT_NOSIGNAL = 99 +CURLOPT_ACCEPT_ENCODING = 10102 +CURLOPT_TCP_NODELAY = 121 +CURLOPT_CONNECT_ONLY = 141 +CURLOPT_TIMEOUT_MS = 155 +CURLOPT_CONNECTTIMEOUT_MS = 156 +CURLOPT_COPYPOSTFIELDS = 10165 +CURLOPT_SSL_ENABLE_ALPN = 226 + +CURL_HTTP_VERSION_1_1 = 2 + +CURLINFO_EFFECTIVE_URL = 1048577 +CURLINFO_RESPONSE_CODE = 2097154 +CURLINFO_CONTENT_TYPE = 1048594 +CURLINFO_PRIMARY_IP = 1048608 +CURLINFO_ACTIVESOCKET = 5242924 + +// ---------------------------------------------------------------------------- +// Internal Module State +// ---------------------------------------------------------------------------- +INITIALIZED = 0 +TIMEOUT_MS = 15000 +CONNECT_TIMEOUT_MS = 8000 +FOLLOW_REDIRECTS = 1 +MAX_REDIRECTS = 10 +INSECURE_TLS = 0 +USER_AGENT$ = "Bananarchy-NeoNet/1.0 (libcurl)" +PROXY_URL$ = "" +BASIC_AUTH$ = "" + +MAX_HEADERS = 64 +CUSTOM_HDR_COUNT = 0 +dim CUSTOM_HDRS$(MAX_HEADERS) + +LAST_STATUS = 0 +LAST_CODE = 0 +LAST_ERROR$ = "" +LAST_BODY$ = "" +LAST_BODY_LEN = 0 +LAST_HEADERS$ = "" +LAST_CONTENT_TYPE$ = "" +LAST_EFFECTIVE_URL$ = "" +LAST_PRIMARY_IP$ = "" +LAST_IO_LEN = 0 + +MAX_SOCKETS = 16 +dim SOCK_ACTIVE(MAX_SOCKETS) +dim SOCK_PROTO(MAX_SOCKETS) +dim SOCK_FD(MAX_SOCKETS) +dim SOCK_CURL$(MAX_SOCKETS) + +// ============================================================================ +// Internal Helpers +// ============================================================================ + +sub _neonet_trim$(s$) + local n, a, b, c$ + n = len(s$) + a = 1 + while a <= n + c$ = mid$(s$, a, 1) + if c$ <> " " and c$ <> "\t" and c$ <> chr$(13) and c$ <> chr$(10) then + break + fi + a = a + 1 + wend + b = n + while b >= a + c$ = mid$(s$, b, 1) + if c$ <> " " and c$ <> "\t" and c$ <> chr$(13) and c$ <> chr$(10) then + break + fi + b = b - 1 + wend + if b < a then + return "" + fi + return mid$(s$, a, b - a + 1) +end sub + +sub _neonet_append_hdr_block$(slist$, hdr_block$, has_slist) + local norm$, n, i, ch$, start_pos, line$, null_ptr$ + if hdr_block$ = "" then + return slist$ + fi + norm$ = "" + n = len(hdr_block$) + for i = 1 to n + ch$ = mid$(hdr_block$, i, 1) + if ch$ = chr$(10) then + norm$ = norm$ + "|" + elsif ch$ <> chr$(13) then + norm$ = norm$ + ch$ + fi + next i + start_pos = 1 + n = len(norm$) + while start_pos <= n + i = instr(norm$, "|", start_pos) + if i = 0 then + line$ = _neonet_trim$(mid$(norm$, start_pos, n - start_pos + 1)) + start_pos = n + 1 + else + line$ = _neonet_trim$(mid$(norm$, start_pos, i - start_pos)) + start_pos = i + 1 + fi + if line$ <> "" then + if has_slist = 0 and slist$ = "" then + null_ptr$ = frnbf_alloc$(-1) + slist$ = frnfn_call$(CURL_LIB$, "buffer", "curl_slist_append", "buffer", null_ptr$, "string", line$) + else + slist$ = frnfn_call$(CURL_LIB$, "buffer", "curl_slist_append", "buffer", slist$, "string", line$) + fi + fi + wend + return slist$ +end sub + +sub _neonet_get_info_str$(curl$, info_id) + local box$, r, addr, p$, val$ + box$ = frnbf_alloc$(4) + r = frnfn_call(CURL_LIB$, "int", "curl_easy_getinfo", "buffer", curl$, "int", info_id, "buffer", box$) + val$ = "" + if r = 0 then + addr = frnbf_get(box$, 0, "uint32") + if addr <> 0 then + p$ = frnbf_get_buffer$(box$, 0) + val$ = frnfn_call$(LIBC_SO$, "string", "strdup", "buffer", p$) + fi + fi + frnbf_free box$ + return val$ +end sub + +sub _neonet_poll_fd(fd, events, timeout_ms) + local pfd$, pr + if fd < 0 then + return -1 + fi + pfd$ = frnbf_alloc$(8) + frnbf_set pfd$, 0, "int", fd + frnbf_set pfd$, 4, "short", events + frnbf_set pfd$, 6, "short", 0 + pr = frnfn_call(LIBC_SO$, "int", "poll", "buffer", pfd$, "int", 1, "int", timeout_ms) + frnbf_free pfd$ + return pr +end sub + +// ============================================================================ +// 1. Lifecycle, Version & Configuration +// ============================================================================ + +export sub neonet_init() + local rc, i + if INITIALIZED = 1 then + return 1 + fi + rc = frnfn_call(CURL_LIB$, "int", "curl_global_init", "int", 3) + if rc <> 0 then + LAST_CODE = rc + LAST_ERROR$ = "curl_global_init failed (" + str$(rc) + ")" + return 0 + fi + for i = 0 to MAX_SOCKETS - 1 + SOCK_ACTIVE(i) = 0 + SOCK_PROTO(i) = 0 + SOCK_FD(i) = -1 + SOCK_CURL$(i) = "" + next i + INITIALIZED = 1 + LAST_CODE = 0 + LAST_ERROR$ = "" + return 1 +end sub + +export sub neonet_cleanup() + local i, r + if INITIALIZED = 0 then + return 1 + fi + for i = 0 to MAX_SOCKETS - 1 + if SOCK_ACTIVE(i) = 1 then + r = neonet_close(i) + fi + next i + CUSTOM_HDR_COUNT = 0 + r = frnfn_call(CURL_LIB$, "int", "curl_global_cleanup") + INITIALIZED = 0 + return 1 +end sub + +export sub neonet_version$() + return frnfn_call$(CURL_LIB$, "string", "curl_version", "options", "copy_string_result") +end sub + +export sub neonet_strerror$(curl_code) + return frnfn_call$(CURL_LIB$, "string", "curl_easy_strerror", "int", curl_code, "options", "copy_string_result") +end sub + +export sub neonet_set_timeout(timeout_ms) + if timeout_ms > 0 then + TIMEOUT_MS = timeout_ms + fi + return TIMEOUT_MS +end sub + +export sub neonet_set_connect_timeout(connect_timeout_ms) + if connect_timeout_ms > 0 then + CONNECT_TIMEOUT_MS = connect_timeout_ms + fi + return CONNECT_TIMEOUT_MS +end sub + +export sub neonet_set_user_agent(ua$) + USER_AGENT$ = ua$ + return 1 +end sub + +export sub neonet_set_follow_redirects(enabled) + if enabled <> 0 then + FOLLOW_REDIRECTS = 1 + else + FOLLOW_REDIRECTS = 0 + fi + return FOLLOW_REDIRECTS +end sub + +export sub neonet_set_max_redirects(max_redirs) + if max_redirs >= 0 then + MAX_REDIRECTS = max_redirs + fi + return MAX_REDIRECTS +end sub + +export sub neonet_set_insecure(insecure) + if insecure <> 0 then + INSECURE_TLS = 1 + else + INSECURE_TLS = 0 + fi + return INSECURE_TLS +end sub + +export sub neonet_set_proxy(proxy_url$) + PROXY_URL$ = proxy_url$ + return 1 +end sub + +export sub neonet_set_basic_auth(user_pwd$) + BASIC_AUTH$ = user_pwd$ + return 1 +end sub + +// ============================================================================ +// 2. Custom Request Headers & URL Encoding +// ============================================================================ + +export sub neonet_clear_headers() + CUSTOM_HDR_COUNT = 0 + return 1 +end sub + +export sub neonet_add_header(header_line$) + local clean$ + clean$ = _neonet_trim$(header_line$) + if clean$ = "" then + return CUSTOM_HDR_COUNT + fi + if CUSTOM_HDR_COUNT < MAX_HEADERS then + CUSTOM_HDR_COUNT = CUSTOM_HDR_COUNT + 1 + CUSTOM_HDRS$(CUSTOM_HDR_COUNT) = clean$ + fi + return CUSTOM_HDR_COUNT +end sub + +export sub neonet_url_encode$(text$) + local r, curl$, res$ + if INITIALIZED = 0 then + r = neonet_init() + fi + if text$ = "" then + return "" + fi + curl$ = frnfn_call$(CURL_LIB$, "buffer", "curl_easy_init") + res$ = frnfn_call$(CURL_LIB$, "string", "curl_easy_escape", "buffer", curl$, "string", text$, "int", len(text$)) + r = frnfn_call(CURL_LIB$, "int", "curl_easy_cleanup", "buffer", curl$) + return res$ +end sub + +export sub neonet_url_decode$(text$) + local r, curl$, outlen$, res$ + if INITIALIZED = 0 then + r = neonet_init() + fi + if text$ = "" then + return "" + fi + curl$ = frnfn_call$(CURL_LIB$, "buffer", "curl_easy_init") + outlen$ = frnbf_alloc$(4) + res$ = frnfn_call$(CURL_LIB$, "string", "curl_easy_unescape", "buffer", curl$, "string", text$, "int", len(text$), "buffer", outlen$) + frnbf_free outlen$ + r = frnfn_call(CURL_LIB$, "int", "curl_easy_cleanup", "buffer", curl$) + return res$ +end sub + +// ============================================================================ +// 3. HTTP / HTTPS Request Execution +// ============================================================================ + +export sub neonet_request$(method$, url$, body$, headers$) + local r, i, verb$, curl$, slist$, null_ptr$ + local body_ptr_box$, body_len_box$, body_fp$, body_buf$ + local hdr_ptr_box$, hdr_len_box$, hdr_fp$, hdr_buf$, hdr_len + local code_box$ + + if INITIALIZED = 0 then + r = neonet_init() + fi + + LAST_STATUS = 0 + LAST_CODE = 0 + LAST_ERROR$ = "" + LAST_BODY$ = "" + LAST_BODY_LEN = 0 + LAST_HEADERS$ = "" + LAST_CONTENT_TYPE$ = "" + LAST_EFFECTIVE_URL$ = "" + LAST_PRIMARY_IP$ = "" + LAST_IO_LEN = 0 + + verb$ = upper$(_neonet_trim$(method$)) + if verb$ = "" then + verb$ = "GET" + fi + + curl$ = frnfn_call$(CURL_LIB$, "buffer", "curl_easy_init") + if curl$ = "" then + LAST_CODE = CURLE_FAILED_INIT + LAST_ERROR$ = "curl_easy_init failed" + return "" + fi + + body_ptr_box$ = frnbf_alloc$(4) + body_len_box$ = frnbf_alloc$(4) + body_fp$ = frnfn_call$(LIBC_SO$, "buffer", "open_memstream", "buffer", body_ptr_box$, "buffer", body_len_box$) + + hdr_ptr_box$ = frnbf_alloc$(4) + hdr_len_box$ = frnbf_alloc$(4) + hdr_fp$ = frnfn_call$(LIBC_SO$, "buffer", "open_memstream", "buffer", hdr_ptr_box$, "buffer", hdr_len_box$) + + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_URL, "string", url$) + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_NOSIGNAL, "int", 1) + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_TIMEOUT_MS, "int", TIMEOUT_MS) + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_CONNECTTIMEOUT_MS, "int", CONNECT_TIMEOUT_MS) + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_FOLLOWLOCATION, "int", FOLLOW_REDIRECTS) + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_MAXREDIRS, "int", MAX_REDIRECTS) + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_ACCEPT_ENCODING, "string", "") + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_WRITEDATA, "buffer", body_fp$) + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_HEADERDATA, "buffer", hdr_fp$) + + if USER_AGENT$ <> "" then + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_USERAGENT, "string", USER_AGENT$) + fi + if PROXY_URL$ <> "" then + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_PROXY, "string", PROXY_URL$) + fi + if BASIC_AUTH$ <> "" then + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_USERPWD, "string", BASIC_AUTH$) + fi + if INSECURE_TLS <> 0 then + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_SSL_VERIFYPEER, "int", 0) + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_SSL_VERIFYHOST, "int", 0) + else + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_SSL_VERIFYPEER, "int", 1) + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_SSL_VERIFYHOST, "int", 2) + fi + + // Build curl_slist from queued headers and inline headers$ + slist$ = "" + for i = 1 to CUSTOM_HDR_COUNT + if slist$ = "" then + null_ptr$ = frnbf_alloc$(-1) + slist$ = frnfn_call$(CURL_LIB$, "buffer", "curl_slist_append", "buffer", null_ptr$, "string", CUSTOM_HDRS$(i)) + else + slist$ = frnfn_call$(CURL_LIB$, "buffer", "curl_slist_append", "buffer", slist$, "string", CUSTOM_HDRS$(i)) + fi + next i + if headers$ <> "" then + slist$ = _neonet_append_hdr_block$(slist$, headers$, slist$ <> "") + fi + if slist$ <> "" then + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_HTTPHEADER, "buffer", slist$) + fi + + // Configure HTTP verb and body + if verb$ = "GET" and body$ = "" then + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_HTTPGET, "int", 1) + elsif verb$ = "HEAD" then + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_NOBODY, "int", 1) + elsif verb$ = "POST" then + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_POST, "int", 1) + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_POSTFIELDSIZE, "int", len(body$)) + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_COPYPOSTFIELDS, "string", body$) + else + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_CUSTOMREQUEST, "string", verb$) + if body$ <> "" or verb$ = "PUT" or verb$ = "PATCH" then + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_POSTFIELDSIZE, "int", len(body$)) + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_COPYPOSTFIELDS, "string", body$) + fi + fi + + LAST_CODE = frnfn_call(CURL_LIB$, "int", "curl_easy_perform", "buffer", curl$) + r = frnfn_call(LIBC_SO$, "int", "fclose", "buffer", body_fp$) + r = frnfn_call(LIBC_SO$, "int", "fclose", "buffer", hdr_fp$) + + if LAST_CODE = 0 then + code_box$ = frnbf_alloc$(4) + r = frnfn_call(CURL_LIB$, "int", "curl_easy_getinfo", "buffer", curl$, "int", CURLINFO_RESPONSE_CODE, "buffer", code_box$) + LAST_STATUS = frnbf_get(code_box$, 0, "int") + frnbf_free code_box$ + + LAST_CONTENT_TYPE$ = _neonet_get_info_str$(curl$, CURLINFO_CONTENT_TYPE) + LAST_EFFECTIVE_URL$ = _neonet_get_info_str$(curl$, CURLINFO_EFFECTIVE_URL) + LAST_PRIMARY_IP$ = _neonet_get_info_str$(curl$, CURLINFO_PRIMARY_IP) + else + LAST_ERROR$ = neonet_strerror$(LAST_CODE) + fi + + LAST_BODY_LEN = frnbf_get(body_len_box$, 0, "int") + LAST_IO_LEN = LAST_BODY_LEN + body_buf$ = frnbf_get_buffer$(body_ptr_box$, 0) + if LAST_BODY_LEN > 0 then + LAST_BODY$ = frnbf_get$(body_buf$, 0, LAST_BODY_LEN) + fi + r = frnfn_call(LIBC_SO$, "int", "free", "buffer", body_buf$) + + hdr_len = frnbf_get(hdr_len_box$, 0, "int") + hdr_buf$ = frnbf_get_buffer$(hdr_ptr_box$, 0) + if hdr_len > 0 then + LAST_HEADERS$ = frnbf_get$(hdr_buf$, 0, hdr_len) + fi + r = frnfn_call(LIBC_SO$, "int", "free", "buffer", hdr_buf$) + + frnbf_free body_ptr_box$ + frnbf_free body_len_box$ + frnbf_free hdr_ptr_box$ + frnbf_free hdr_len_box$ + + if slist$ <> "" then + r = frnfn_call(CURL_LIB$, "int", "curl_slist_free_all", "buffer", slist$) + fi + r = frnfn_call(CURL_LIB$, "int", "curl_easy_cleanup", "buffer", curl$) + + return LAST_BODY$ +end sub + +export sub neonet_get$(url$) + return neonet_request$("GET", url$, "", "") +end sub + +export sub neonet_get_ex$(url$, headers$) + return neonet_request$("GET", url$, "", headers$) +end sub + +export sub neonet_post$(url$, body$, content_type$, headers$) + local hdrs$ + hdrs$ = headers$ + if content_type$ <> "" then + if hdrs$ <> "" then + hdrs$ = "Content-Type: " + content_type$ + "|" + hdrs$ + else + hdrs$ = "Content-Type: " + content_type$ + fi + fi + return neonet_request$("POST", url$, body$, hdrs$) +end sub + +export sub neonet_put$(url$, body$, content_type$, headers$) + local hdrs$ + hdrs$ = headers$ + if content_type$ <> "" then + if hdrs$ <> "" then + hdrs$ = "Content-Type: " + content_type$ + "|" + hdrs$ + else + hdrs$ = "Content-Type: " + content_type$ + fi + fi + return neonet_request$("PUT", url$, body$, hdrs$) +end sub + +export sub neonet_patch$(url$, body$, content_type$, headers$) + local hdrs$ + hdrs$ = headers$ + if content_type$ <> "" then + if hdrs$ <> "" then + hdrs$ = "Content-Type: " + content_type$ + "|" + hdrs$ + else + hdrs$ = "Content-Type: " + content_type$ + fi + fi + return neonet_request$("PATCH", url$, body$, hdrs$) +end sub + +export sub neonet_delete$(url$, headers$) + return neonet_request$("DELETE", url$, "", headers$) +end sub + +export sub neonet_head(url$, headers$) + local unused$ + unused$ = neonet_request$("HEAD", url$, "", headers$) + return LAST_STATUS +end sub + +export sub neonet_download(url$, dest_path$, headers$) + local r, i, curl$, fp$, slist$, null_ptr$, code_box$, addr + local hdr_ptr_box$, hdr_len_box$, hdr_fp$, hdr_buf$, hdr_len + + if INITIALIZED = 0 then + r = neonet_init() + fi + + LAST_STATUS = 0 + LAST_CODE = 0 + LAST_ERROR$ = "" + LAST_BODY$ = "" + LAST_BODY_LEN = 0 + LAST_HEADERS$ = "" + + fp$ = frnfn_call$(LIBC_SO$, "buffer", "fopen", "string", dest_path$, "string", "wb") + if fp$ = "frnbf:-1:(nil)" or fp$ = "frnbf:-1:0x0" or fp$ = "frnbf:-1:0" then + LAST_CODE = CURLE_WRITE_ERROR + LAST_ERROR$ = "Cannot open file for writing: " + dest_path$ + return 0 + fi + + curl$ = frnfn_call$(CURL_LIB$, "buffer", "curl_easy_init") + hdr_ptr_box$ = frnbf_alloc$(4) + hdr_len_box$ = frnbf_alloc$(4) + hdr_fp$ = frnfn_call$(LIBC_SO$, "buffer", "open_memstream", "buffer", hdr_ptr_box$, "buffer", hdr_len_box$) + + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_URL, "string", url$) + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_NOSIGNAL, "int", 1) + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_TIMEOUT_MS, "int", TIMEOUT_MS) + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_CONNECTTIMEOUT_MS, "int", CONNECT_TIMEOUT_MS) + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_FOLLOWLOCATION, "int", FOLLOW_REDIRECTS) + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_MAXREDIRS, "int", MAX_REDIRECTS) + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_ACCEPT_ENCODING, "string", "") + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_WRITEDATA, "buffer", fp$) + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_HEADERDATA, "buffer", hdr_fp$) + + if USER_AGENT$ <> "" then + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_USERAGENT, "string", USER_AGENT$) + fi + if PROXY_URL$ <> "" then + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_PROXY, "string", PROXY_URL$) + fi + if BASIC_AUTH$ <> "" then + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_USERPWD, "string", BASIC_AUTH$) + fi + if INSECURE_TLS <> 0 then + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_SSL_VERIFYPEER, "int", 0) + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_SSL_VERIFYHOST, "int", 0) + fi + + slist$ = "" + for i = 1 to CUSTOM_HDR_COUNT + if slist$ = "" then + null_ptr$ = frnbf_alloc$(-1) + slist$ = frnfn_call$(CURL_LIB$, "buffer", "curl_slist_append", "buffer", null_ptr$, "string", CUSTOM_HDRS$(i)) + else + slist$ = frnfn_call$(CURL_LIB$, "buffer", "curl_slist_append", "buffer", slist$, "string", CUSTOM_HDRS$(i)) + fi + next i + if headers$ <> "" then + slist$ = _neonet_append_hdr_block$(slist$, headers$, slist$ <> "") + fi + if slist$ <> "" then + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_HTTPHEADER, "buffer", slist$) + fi + + LAST_CODE = frnfn_call(CURL_LIB$, "int", "curl_easy_perform", "buffer", curl$) + r = frnfn_call(LIBC_SO$, "int", "fclose", "buffer", fp$) + r = frnfn_call(LIBC_SO$, "int", "fclose", "buffer", hdr_fp$) + + if LAST_CODE = 0 then + code_box$ = frnbf_alloc$(4) + r = frnfn_call(CURL_LIB$, "int", "curl_easy_getinfo", "buffer", curl$, "int", CURLINFO_RESPONSE_CODE, "buffer", code_box$) + LAST_STATUS = frnbf_get(code_box$, 0, "int") + frnbf_free code_box$ + LAST_CONTENT_TYPE$ = _neonet_get_info_str$(curl$, CURLINFO_CONTENT_TYPE) + LAST_EFFECTIVE_URL$ = _neonet_get_info_str$(curl$, CURLINFO_EFFECTIVE_URL) + LAST_PRIMARY_IP$ = _neonet_get_info_str$(curl$, CURLINFO_PRIMARY_IP) + else + LAST_ERROR$ = neonet_strerror$(LAST_CODE) + fi + + hdr_len = frnbf_get(hdr_len_box$, 0, "int") + hdr_buf$ = frnbf_get_buffer$(hdr_ptr_box$, 0) + if hdr_len > 0 then + LAST_HEADERS$ = frnbf_get$(hdr_buf$, 0, hdr_len) + fi + r = frnfn_call(LIBC_SO$, "int", "free", "buffer", hdr_buf$) + frnbf_free hdr_ptr_box$ + frnbf_free hdr_len_box$ + + if slist$ <> "" then + r = frnfn_call(CURL_LIB$, "int", "curl_slist_free_all", "buffer", slist$) + fi + r = frnfn_call(CURL_LIB$, "int", "curl_easy_cleanup", "buffer", curl$) + + if LAST_CODE = 0 and LAST_STATUS >= 200 and LAST_STATUS < 400 then + return 1 + fi + return 0 +end sub + +// ============================================================================ +// 4. HTTP Response Metadata & Header Inspection +// ============================================================================ + +export sub neonet_status() + return LAST_STATUS +end sub + +export sub neonet_last_code() + return LAST_CODE +end sub + +export sub neonet_error$() + return LAST_ERROR$ +end sub + +export sub neonet_body$() + return LAST_BODY$ +end sub + +export sub neonet_body_len() + return LAST_BODY_LEN +end sub + +export sub neonet_last_len() + return LAST_IO_LEN +end sub + +export sub neonet_response_headers$() + return LAST_HEADERS$ +end sub + +export sub neonet_content_type$() + return LAST_CONTENT_TYPE$ +end sub + +export sub neonet_effective_url$() + return LAST_EFFECTIVE_URL$ +end sub + +export sub neonet_primary_ip$() + return LAST_PRIMARY_IP$ +end sub + +export sub neonet_header$(name$) + local target$, tlen, pos, nl, line$, colon, k$, matched$ + target$ = lower$(_neonet_trim$(name$)) + tlen = len(target$) + if tlen = 0 or LAST_HEADERS$ = "" then + return "" + fi + matched$ = "" + pos = 1 + while pos <= len(LAST_HEADERS$) + nl = instr(LAST_HEADERS$, chr$(10), pos) + if nl = 0 then + line$ = _neonet_trim$(mid$(LAST_HEADERS$, pos, len(LAST_HEADERS$) - pos + 1)) + pos = len(LAST_HEADERS$) + 1 + else + line$ = _neonet_trim$(mid$(LAST_HEADERS$, pos, nl - pos)) + pos = nl + 1 + fi + colon = instr(line$, ":") + if colon > 1 then + k$ = lower$(_neonet_trim$(left$(line$, colon - 1))) + if k$ = target$ then + matched$ = _neonet_trim$(mid$(line$, colon + 1, len(line$) - colon)) + fi + fi + wend + return matched$ +end sub + +// ============================================================================ +// 5. TCP, TLS & UDP Socket Data Exchange +// ============================================================================ + +export sub neonet_connect(proto, host$, port) + local r, slot, i, url$, curl$, sock_box$, fd + local hints$, res_box$, ai$, fam, stype, iproto, addrlen, addr$ + + if INITIALIZED = 0 then + r = neonet_init() + fi + + LAST_CODE = 0 + LAST_ERROR$ = "" + LAST_IO_LEN = 0 + + slot = -1 + for i = 0 to MAX_SOCKETS - 1 + if SOCK_ACTIVE(i) = 0 then + slot = i + break + fi + next i + if slot < 0 then + LAST_ERROR$ = "No free NeoNet socket slots available" + return -1 + fi + + if proto = PROTO_TCP or proto = PROTO_TLS then + if proto = PROTO_TLS then + url$ = "https://" + host$ + ":" + str$(port) + else + url$ = "http://" + host$ + ":" + str$(port) + fi + + curl$ = frnfn_call$(CURL_LIB$, "buffer", "curl_easy_init") + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_URL, "string", url$) + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_NOSIGNAL, "int", 1) + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_CONNECTTIMEOUT_MS, "int", CONNECT_TIMEOUT_MS) + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_TIMEOUT_MS, "int", TIMEOUT_MS) + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_TCP_NODELAY, "int", 1) + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_HTTP_VERSION, "int", CURL_HTTP_VERSION_1_1) + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_SSL_ENABLE_ALPN, "int", 0) + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_CONNECT_ONLY, "int", 1) + + if PROXY_URL$ <> "" then + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_PROXY, "string", PROXY_URL$) + fi + if INSECURE_TLS <> 0 then + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_SSL_VERIFYPEER, "int", 0) + r = frnfn_call(CURL_LIB$, "int", "curl_easy_setopt", "buffer", curl$, "int", CURLOPT_SSL_VERIFYHOST, "int", 0) + fi + + LAST_CODE = frnfn_call(CURL_LIB$, "int", "curl_easy_perform", "buffer", curl$) + if LAST_CODE <> 0 then + LAST_ERROR$ = neonet_strerror$(LAST_CODE) + r = frnfn_call(CURL_LIB$, "int", "curl_easy_cleanup", "buffer", curl$) + return -1 + fi + + sock_box$ = frnbf_alloc$(4) + r = frnfn_call(CURL_LIB$, "int", "curl_easy_getinfo", "buffer", curl$, "int", CURLINFO_ACTIVESOCKET, "buffer", sock_box$) + fd = frnbf_get(sock_box$, 0, "int") + frnbf_free sock_box$ + + LAST_PRIMARY_IP$ = _neonet_get_info_str$(curl$, CURLINFO_PRIMARY_IP) + SOCK_ACTIVE(slot) = 1 + SOCK_PROTO(slot) = proto + SOCK_FD(slot) = fd + SOCK_CURL$(slot) = curl$ + return slot + elsif proto = PROTO_UDP then + hints$ = frnbf_alloc$(32) + frnbf_set hints$, 4, "int", 0 // AF_UNSPEC (IPv4 or IPv6) + frnbf_set hints$, 8, "int", 2 // SOCK_DGRAM + frnbf_set hints$, 12, "int", 17 // IPPROTO_UDP + + res_box$ = frnbf_alloc$(4) + r = frnfn_call(LIBC_SO$, "int", "getaddrinfo", "string", host$, "string", str$(port), "buffer", hints$, "buffer", res_box$) + frnbf_free hints$ + if r <> 0 then + frnbf_free res_box$ + LAST_CODE = CURLE_COULDNT_RESOLVE_HOST + LAST_ERROR$ = "UDP getaddrinfo failed for " + host$ + ":" + str$(port) + return -1 + fi + + ai$ = frnbf_get_buffer$(res_box$, 0) + fam = frnbf_get(ai$, 4, "int") + stype = frnbf_get(ai$, 8, "int") + iproto = frnbf_get(ai$, 12, "int") + addrlen = frnbf_get(ai$, 16, "int") + addr$ = frnbf_get_buffer$(ai$, 20) + + fd = frnfn_call(LIBC_SO$, "int", "socket", "int", fam, "int", stype, "int", iproto) + if fd < 0 then + r = frnfn_call(LIBC_SO$, "int", "freeaddrinfo", "buffer", ai$) + frnbf_free res_box$ + LAST_CODE = CURLE_COULDNT_CONNECT + LAST_ERROR$ = "UDP socket() creation failed" + return -1 + fi + + r = frnfn_call(LIBC_SO$, "int", "connect", "int", fd, "buffer", addr$, "int", addrlen) + r2 = frnfn_call(LIBC_SO$, "int", "freeaddrinfo", "buffer", ai$) + frnbf_free res_box$ + if r <> 0 then + r2 = frnfn_call(LIBC_SO$, "int", "close", "int", fd) + LAST_CODE = CURLE_COULDNT_CONNECT + LAST_ERROR$ = "UDP connect() failed" + return -1 + fi + + SOCK_ACTIVE(slot) = 1 + SOCK_PROTO(slot) = PROTO_UDP + SOCK_FD(slot) = fd + SOCK_CURL$(slot) = "" + return slot + fi + + LAST_ERROR$ = "Invalid socket protocol: " + str$(proto) + return -1 +end sub + +export sub neonet_tcp_connect(host$, port) + return neonet_connect(PROTO_TCP, host$, port) +end sub + +export sub neonet_tls_connect(host$, port) + return neonet_connect(PROTO_TLS, host$, port) +end sub + +export sub neonet_udp_open(host$, port) + return neonet_connect(PROTO_UDP, host$, port) +end sub + +export sub neonet_send(sock_id, data$) + local total, slen, rem$, sent_box$, rc, n, pr + if sock_id < 0 or sock_id >= MAX_SOCKETS then + LAST_ERROR$ = "Invalid socket handle" + return -1 + fi + if SOCK_ACTIVE(sock_id) = 0 then + LAST_ERROR$ = "Socket is not open" + return -1 + fi + slen = len(data$) + if slen = 0 then + return 0 + fi + + if SOCK_PROTO(sock_id) = PROTO_UDP then + n = frnfn_call(LIBC_SO$, "int", "send", "int", SOCK_FD(sock_id), "string", data$, "int", slen, "int", 0) + if n < 0 then + LAST_CODE = CURLE_SEND_ERROR + LAST_ERROR$ = "UDP send() failed" + return -1 + fi + LAST_IO_LEN = n + return n + fi + + sent_box$ = frnbf_alloc$(4) + total = 0 + rem$ = data$ + while total < slen + rc = frnfn_call(CURL_LIB$, "int", "curl_easy_send", "buffer", SOCK_CURL$(sock_id), "string", rem$, "int", len(rem$), "buffer", sent_box$) + if rc = 0 then + n = frnbf_get(sent_box$, 0, "int") + total = total + n + if total < slen then + rem$ = right$(data$, slen - total) + fi + elsif rc = CURLE_AGAIN then + pr = _neonet_poll_fd(SOCK_FD(sock_id), 4, TIMEOUT_MS) + if pr <= 0 then + frnbf_free sent_box$ + LAST_CODE = CURLE_OPERATION_TIMEDOUT + LAST_ERROR$ = "Socket send timed out" + return -1 + fi + else + frnbf_free sent_box$ + LAST_CODE = rc + LAST_ERROR$ = neonet_strerror$(rc) + return -1 + fi + wend + frnbf_free sent_box$ + LAST_IO_LEN = total + return total +end sub + +export sub neonet_send_bytes(sock_id, frn_buf$, byte_len) + local sent_box$, rc, n, pr + if sock_id < 0 or sock_id >= MAX_SOCKETS then + LAST_ERROR$ = "Invalid socket handle" + return -1 + fi + if SOCK_ACTIVE(sock_id) = 0 then + LAST_ERROR$ = "Socket is not open" + return -1 + fi + if byte_len <= 0 then + return 0 + fi + + if SOCK_PROTO(sock_id) = PROTO_UDP then + n = frnfn_call(LIBC_SO$, "int", "send", "int", SOCK_FD(sock_id), "buffer", frn_buf$, "int", byte_len, "int", 0) + if n < 0 then + LAST_CODE = CURLE_SEND_ERROR + LAST_ERROR$ = "UDP send_bytes() failed" + return -1 + fi + LAST_IO_LEN = n + return n + fi + + sent_box$ = frnbf_alloc$(4) + while 1 + rc = frnfn_call(CURL_LIB$, "int", "curl_easy_send", "buffer", SOCK_CURL$(sock_id), "buffer", frn_buf$, "int", byte_len, "buffer", sent_box$) + if rc = 0 then + n = frnbf_get(sent_box$, 0, "int") + frnbf_free sent_box$ + LAST_IO_LEN = n + return n + elsif rc = CURLE_AGAIN then + pr = _neonet_poll_fd(SOCK_FD(sock_id), 4, TIMEOUT_MS) + if pr <= 0 then + frnbf_free sent_box$ + LAST_CODE = CURLE_OPERATION_TIMEDOUT + LAST_ERROR$ = "Socket send_bytes timed out" + return -1 + fi + else + frnbf_free sent_box$ + LAST_CODE = rc + LAST_ERROR$ = neonet_strerror$(rc) + return -1 + fi + wend +end sub + +export sub neonet_recv_bytes(sock_id, frn_buf$, max_bytes, timeout_ms) + local rx_box$, rc, n, pr, wait_ms, elapsed, step_ms + LAST_IO_LEN = 0 + if sock_id < 0 or sock_id >= MAX_SOCKETS then + LAST_ERROR$ = "Invalid socket handle" + return -1 + fi + if SOCK_ACTIVE(sock_id) = 0 then + LAST_ERROR$ = "Socket is not open" + return -1 + fi + if max_bytes <= 0 then + return 0 + fi + wait_ms = timeout_ms + if wait_ms < 0 then + wait_ms = TIMEOUT_MS + fi + + if SOCK_PROTO(sock_id) = PROTO_UDP then + pr = _neonet_poll_fd(SOCK_FD(sock_id), 1, wait_ms) + if pr <= 0 then + LAST_CODE = CURLE_OPERATION_TIMEDOUT + return 0 + fi + n = frnfn_call(LIBC_SO$, "int", "recv", "int", SOCK_FD(sock_id), "buffer", frn_buf$, "int", max_bytes, "int", 0) + if n < 0 then + LAST_CODE = CURLE_RECV_ERROR + LAST_ERROR$ = "UDP recv() failed" + return -1 + fi + LAST_IO_LEN = n + return n + fi + + rx_box$ = frnbf_alloc$(4) + elapsed = 0 + step_ms = 200 + while 1 + rc = frnfn_call(CURL_LIB$, "int", "curl_easy_recv", "buffer", SOCK_CURL$(sock_id), "buffer", frn_buf$, "int", max_bytes, "buffer", rx_box$) + if rc = 0 then + n = frnbf_get(rx_box$, 0, "int") + frnbf_free rx_box$ + LAST_IO_LEN = n + LAST_CODE = 0 + return n + elsif rc = CURLE_AGAIN then + if elapsed >= wait_ms then + frnbf_free rx_box$ + LAST_CODE = CURLE_AGAIN + return 0 + fi + if wait_ms - elapsed < step_ms then + step_ms = wait_ms - elapsed + fi + pr = _neonet_poll_fd(SOCK_FD(sock_id), 1, step_ms) + elapsed = elapsed + step_ms + if pr < 0 then + frnbf_free rx_box$ + LAST_CODE = CURLE_RECV_ERROR + return -1 + fi + else + frnbf_free rx_box$ + LAST_CODE = rc + LAST_ERROR$ = neonet_strerror$(rc) + return -1 + fi + wend +end sub + +export sub neonet_recv$(sock_id, max_bytes, timeout_ms) + local cap, rx_buf$, n, out$ + cap = max_bytes + if cap <= 0 then + cap = 4096 + fi + rx_buf$ = frnbf_alloc$(cap) + n = neonet_recv_bytes(sock_id, rx_buf$, cap, timeout_ms) + out$ = "" + if n > 0 then + out$ = frnbf_get$(rx_buf$, 0, n) + fi + frnbf_free rx_buf$ + return out$ +end sub + +export sub neonet_recv_all$(sock_id, max_bytes, timeout_ms) + local cap, chunk_sz, rx_buf$, n, out$, wait_ms + cap = max_bytes + if cap <= 0 then + cap = 65536 + fi + chunk_sz = 4096 + if cap < chunk_sz then + chunk_sz = cap + fi + rx_buf$ = frnbf_alloc$(chunk_sz) + out$ = "" + wait_ms = timeout_ms + if wait_ms <= 0 then + wait_ms = TIMEOUT_MS + fi + + while len(out$) < cap + n = neonet_recv_bytes(sock_id, rx_buf$, chunk_sz, wait_ms) + if n <= 0 then + break + fi + out$ = out$ + frnbf_get$(rx_buf$, 0, n) + // After receiving the first chunk, use a shorter idle window for remaining chunks + if wait_ms > 800 then + wait_ms = 800 + fi + wend + frnbf_free rx_buf$ + LAST_IO_LEN = len(out$) + return out$ +end sub + +export sub neonet_close(sock_id) + local r + if sock_id < 0 or sock_id >= MAX_SOCKETS then + return 0 + fi + if SOCK_ACTIVE(sock_id) = 0 then + return 0 + fi + if SOCK_PROTO(sock_id) = PROTO_UDP then + if SOCK_FD(sock_id) >= 0 then + r = frnfn_call(LIBC_SO$, "int", "close", "int", SOCK_FD(sock_id)) + fi + else + if SOCK_CURL$(sock_id) <> "" then + r = frnfn_call(CURL_LIB$, "int", "curl_easy_cleanup", "buffer", SOCK_CURL$(sock_id)) + fi + fi + SOCK_ACTIVE(sock_id) = 0 + SOCK_PROTO(sock_id) = 0 + SOCK_FD(sock_id) = -1 + SOCK_CURL$(sock_id) = "" + return 1 +end sub + +// ============================================================================ +// 6. One-Shot TCP, TLS & UDP Exchange Helpers +// ============================================================================ + +export sub neonet_tcp_exchange$(host$, port, payload$, timeout_ms) + local s, r, resp$ + s = neonet_tcp_connect(host$, port) + if s < 0 then + return "" + fi + if payload$ <> "" then + r = neonet_send(s, payload$) + if r < 0 then + r = neonet_close(s) + return "" + fi + fi + resp$ = neonet_recv_all$(s, 32768, timeout_ms) + r = neonet_close(s) + return resp$ +end sub + +export sub neonet_tls_exchange$(host$, port, payload$, timeout_ms) + local s, r, resp$ + s = neonet_tls_connect(host$, port) + if s < 0 then + return "" + fi + if payload$ <> "" then + r = neonet_send(s, payload$) + if r < 0 then + r = neonet_close(s) + return "" + fi + fi + resp$ = neonet_recv_all$(s, 32768, timeout_ms) + r = neonet_close(s) + return resp$ +end sub + +export sub neonet_udp_exchange$(host$, port, payload$, timeout_ms) + local s, r, resp$ + s = neonet_udp_open(host$, port) + if s < 0 then + return "" + fi + if payload$ <> "" then + r = neonet_send(s, payload$) + if r < 0 then + r = neonet_close(s) + return "" + fi + fi + resp$ = neonet_recv$(s, 4096, timeout_ms) + r = neonet_close(s) + return resp$ +end sub + +export sub neonet_system_dns$() + local fp$, buf$, p$, line$, ns$, r + fp$ = frnfn_call$(LIBC_SO$, "buffer", "fopen", "string", "/etc/resolv.conf", "string", "r") + if fp$ = "frnbf:-1:(nil)" or fp$ = "frnbf:-1:0x0" or fp$ = "frnbf:-1:0" then + return "1.1.1.1" + fi + buf$ = frnbf_alloc$(256) + ns$ = "1.1.1.1" + while 1 + p$ = frnfn_call$(LIBC_SO$, "buffer", "fgets", "buffer", buf$, "int", 255, "buffer", fp$) + if p$ = "frnbf:-1:(nil)" or p$ = "frnbf:-1:0x0" or p$ = "frnbf:-1:0" then + break + fi + line$ = _neonet_trim$(frnbf_get$(buf$, 0, 255)) + if left$(line$, 10) = "nameserver" then + ns$ = _neonet_trim$(mid$(line$, 11, len(line$) - 10)) + if ns$ <> "" then + break + fi + fi + wend + frnbf_free buf$ + r = frnfn_call(LIBC_SO$, "int", "fclose", "buffer", fp$) + return ns$ +end sub + +export sub neonet_udp_dns_a$(dns_server$, domain$, timeout_ms) + local srv$, clean_dom$, s, tx$, rx$, pos, i, n, ch$, lbl_start, lbl_len + local sent, recvd, ancount, qdcount, rcode, b, rtype, rdlen, ip$, r + + srv$ = _neonet_trim$(dns_server$) + if srv$ = "" then + srv$ = neonet_system_dns$() + fi + clean_dom$ = _neonet_trim$(domain$) + if clean_dom$ = "" then + LAST_ERROR$ = "Empty domain name" + return "" + fi + + s = neonet_udp_open(srv$, 53) + if s < 0 then + return "" + fi + + tx$ = frnbf_alloc$(512) + // DNS Header: ID=0x424e ("BN"), Flags=0x0100 (Standard query, RD=1), QDCOUNT=1 + frnbf_set tx$, 0, "uint8", 66 + frnbf_set tx$, 1, "uint8", 78 + frnbf_set tx$, 2, "uint8", 1 + frnbf_set tx$, 3, "uint8", 0 + frnbf_set tx$, 4, "uint8", 0 + frnbf_set tx$, 5, "uint8", 1 + + pos = 12 + lbl_start = 1 + n = len(clean_dom$) + for i = 1 to n + 1 + if i <= n then + ch$ = mid$(clean_dom$, i, 1) + else + ch$ = "." + fi + if ch$ = "." then + lbl_len = i - lbl_start + if lbl_len > 0 and lbl_len < 64 and pos + lbl_len + 1 < 500 then + frnbf_set tx$, pos, "uint8", lbl_len + frnbf_set tx$, pos + 1, mid$(clean_dom$, lbl_start, lbl_len) + pos = pos + 1 + lbl_len + fi + lbl_start = i + 1 + fi + next i + // Root label (0) + QTYPE=1 (A) + QCLASS=1 (IN) + frnbf_set tx$, pos, "uint8", 0 + frnbf_set tx$, pos + 1, "uint8", 0 + frnbf_set tx$, pos + 2, "uint8", 1 + frnbf_set tx$, pos + 3, "uint8", 0 + frnbf_set tx$, pos + 4, "uint8", 1 + pos = pos + 5 + + sent = neonet_send_bytes(s, tx$, pos) + frnbf_free tx$ + if sent < 0 then + r = neonet_close(s) + return "" + fi + + rx$ = frnbf_alloc$(512) + recvd = neonet_recv_bytes(s, rx$, 512, timeout_ms) + r = neonet_close(s) + if recvd < 12 then + frnbf_free rx$ + if LAST_ERROR$ = "" then + LAST_ERROR$ = "UDP DNS query timed out (" + srv$ + ":53)" + fi + return "" + fi + + rcode = mod(frnbf_get(rx$, 3, "uint8"), 16) + qdcount = frnbf_get(rx$, 4, "uint8") * 256 + frnbf_get(rx$, 5, "uint8") + ancount = frnbf_get(rx$, 6, "uint8") * 256 + frnbf_get(rx$, 7, "uint8") + if rcode <> 0 or ancount <= 0 then + frnbf_free rx$ + LAST_ERROR$ = "DNS RCODE=" + str$(rcode) + " ANCOUNT=" + str$(ancount) + return "" + fi + + pos = 12 + for i = 1 to qdcount + while pos < recvd + b = frnbf_get(rx$, pos, "uint8") + if b = 0 then + pos = pos + 1 + break + elsif b >= 192 then + pos = pos + 2 + break + else + pos = pos + 1 + b + fi + wend + pos = pos + 4 + next i + + ip$ = "" + for i = 1 to ancount + if pos >= recvd then + break + fi + while pos < recvd + b = frnbf_get(rx$, pos, "uint8") + if b = 0 then + pos = pos + 1 + break + elsif b >= 192 then + pos = pos + 2 + break + else + pos = pos + 1 + b + fi + wend + if pos + 10 > recvd then + break + fi + rtype = frnbf_get(rx$, pos, "uint8") * 256 + frnbf_get(rx$, pos + 1, "uint8") + rdlen = frnbf_get(rx$, pos + 8, "uint8") * 256 + frnbf_get(rx$, pos + 9, "uint8") + pos = pos + 10 + if rtype = 1 and rdlen = 4 and pos + 4 <= recvd then + ip$ = str$(frnbf_get(rx$, pos, "uint8")) + "." + str$(frnbf_get(rx$, pos + 1, "uint8")) + "." + str$(frnbf_get(rx$, pos + 2, "uint8")) + "." + str$(frnbf_get(rx$, pos + 3, "uint8")) + break + fi + pos = pos + rdlen + next i + + frnbf_free rx$ + if ip$ = "" and LAST_ERROR$ = "" then + LAST_ERROR$ = "No IPv4 A record in DNS response" + fi + return ip$ +end sub diff --git a/overlay/rootfs/home/user/Projects/neonet_demo.yab b/overlay/rootfs/home/user/Projects/neonet_demo.yab new file mode 100755 index 0000000..1c92388 --- /dev/null +++ b/overlay/rootfs/home/user/Projects/neonet_demo.yab @@ -0,0 +1,629 @@ +#!/usr/bin/yabasic +// ============================================================================ +// neonet_demo.yab - Bananarchy NeoNet + NeoUI Showcase for Yabasic +// ============================================================================ +// Demonstrates combining NeoNet (libcurl + socket FFI) with NeoUI (240x320 UI): +// - Tab 1 (1:HTTP/S): HTTP/HTTPS GET, POST, and HEAD requests with custom +// headers, status code badge, server/IP inspection, and scrollable output +// - Tab 2 (2:Sockets): Raw TLS (port 443), TCP (port 43 WHOIS), and binary +// UDP (port 53 DNS A-record) socket data exchange +// - Tab 3 (3:Tools): URL encode/decode, file download to /tmp, TLS verify +// toggle, and libcurl version/capability inspection +// +// Controls: +// - 1 / 2 / 3 (when not typing in an input box): Switch tabs +// - Up / Down: Navigate controls or scroll response viewer +// - Left / Right: Cycle HTTP method / socket protocol or switch tabs +// - OK (Enter): Execute request / toggle option / edit input +// - Left Softkey (F1): Open Presets & Actions menu +// - Right Softkey (F2) / Backspace: Delete char (in input) or Quit +// - Both Softkeys together: Open Bananarchy XDrawer overlay +// ============================================================================ + +import neoui +import neonet + +if neoui_init("neonet_demo", 0) = 0 then + print "Failed to initialize NeoUI X11 window" + exit 1 +fi + +r = neonet_init() +r = neonet_set_timeout(10000) +r = neonet_set_connect_timeout(6000) + +// Active tab: 0 = HTTP/S, 1 = Sockets, 2 = Tools & Info +active_tab = 0 + +// Tab 0 (HTTP/S) state +http_focus = 2 +http_url$ = "https://example.com/" +http_method_idx = 0 +dim http_methods$(3) +http_methods$(0) = "GET" +http_methods$(1) = "POST" +http_methods$(2) = "HEAD" +custom_hdr_on = 1 +custom_hdr$ = "X-Bananarchy: NeoNet-1.0|Accept: */*" +show_raw_headers = 0 +http_status_str$ = "Ready (press OK on Send)" +http_meta_str$ = "Custom Header: X-Bananarchy" +http_output$ = "Press OK on [Send] or open Left Softkey Menu for presets." +http_scroll = 0 + +// Tab 1 (Sockets) state +sock_focus = 2 +sock_proto_idx = 0 +dim sock_protos$(3) +sock_protos$(0) = "TLS :443 (HTTPS Raw)" +sock_protos$(1) = "TCP :43 (IANA WHOIS)" +sock_protos$(2) = "UDP :53 (DNS Query)" +sock_host$ = "example.com" +sock_status_str$ = "Ready (select protocol & Run)" +sock_output$ = "Supports raw TLS, TCP, and UDP socket data exchange." +sock_scroll = 0 + +// Tab 2 (Tools) state +tool_focus = 0 +tls_insecure = 0 +sample_raw$ = "Bananarchy 240x320 & NeoNet!" +sample_enc$ = neonet_url_encode$(sample_raw$) +dl_status$ = "Not downloaded yet" + +// Modal state: 0 = None, 1 = Presets Menu +modal_mode = 0 +menu_sel = 0 + +// Track which input box owns multi-tap buffer (0 = http_url$, 1 = sock_host$) +active_input_owner = -1 + +sub sync_input_box(owner_id) + if active_input_owner = owner_id then + return + fi + active_input_owner = owner_id + if owner_id = 0 then + neoui_input_reset(http_url$) + elsif owner_id = 1 then + neoui_input_reset(sock_host$) + fi +end sub + +sub save_input_box() + if active_input_owner = 0 then + neoui_input_commit_tap() + http_url$ = neoui_input_get_text$() + elsif active_input_owner = 1 then + neoui_input_commit_tap() + sock_host$ = neoui_input_get_text$() + fi +end sub + +sub sanitize_display_text$(s$, max_chars) + local out$, n, i, ch$, code + n = len(s$) + if n > max_chars then + n = max_chars + fi + out$ = "" + for i = 1 to n + ch$ = mid$(s$, i, 1) + code = asc(ch$) + if code = 10 or (code >= 32 and code <= 126) then + out$ = out$ + ch$ + elsif code = 9 then + out$ = out$ + " " + fi + next i + return out$ +end sub + +sub run_http_request() + local m$, hdrs$, body$, st, blen, srv$, ip$ + save_input_box() + m$ = http_methods$(http_method_idx) + if custom_hdr_on then + hdrs$ = custom_hdr$ + else + hdrs$ = "" + fi + + neoui_show_toast(m$ + " " + http_url$ + " ...", 500) + render_all() + neoui_flush() + + if m$ = "GET" then + body$ = neonet_get_ex$(http_url$, hdrs$) + elsif m$ = "POST" then + body$ = neonet_post$(http_url$, "{\"device\":\"nokia-argon\",\"sdk\":\"NeoNet\"}", "application/json", hdrs$) + else + st = neonet_head(http_url$, hdrs$) + body$ = neonet_response_headers$() + fi + + st = neonet_status() + blen = neonet_body_len() + http_scroll = 0 + + if neonet_last_code() <> 0 then + http_status_str$ = "ERR (" + str$(neonet_last_code()) + "): " + neonet_error$() + http_meta_str$ = "URL: " + http_url$ + http_output$ = "Request failed: " + neonet_error$() + neoui_show_toast("HTTP error!", 1600) + else + srv$ = neonet_header$("server") + if srv$ = "" then + srv$ = "n/a" + fi + ip$ = neonet_primary_ip$() + http_status_str$ = m$ + " -> HTTP " + str$(st) + " (" + str$(blen) + " B)" + http_meta_str$ = "IP: " + ip$ + " Srv: " + srv$ + if show_raw_headers or m$ = "HEAD" then + http_output$ = sanitize_display_text$(neonet_response_headers$(), 1800) + else + http_output$ = sanitize_display_text$(body$, 1800) + fi + neoui_show_toast("HTTP " + str$(st) + " (" + str$(blen) + " B)", 1500) + fi +end sub + +sub run_socket_exchange() + local crlf$, req$, rx$, ip$, dns_srv$ + save_input_box() + crlf$ = chr$(13) + chr$(10) + sock_scroll = 0 + + if sock_proto_idx = 0 then + neoui_show_toast("TLS connect " + sock_host$ + ":443 ...", 500) + render_all() + neoui_flush() + + req$ = "HEAD / HTTP/1.1" + crlf$ + "Host: " + sock_host$ + crlf$ + "User-Agent: NeoNet-TLS/1.0" + crlf$ + "Connection: close" + crlf$ + crlf$ + rx$ = neonet_tls_exchange$(sock_host$, 443, req$, 4000) + if rx$ = "" and neonet_error$() <> "" then + sock_status_str$ = "TLS Error: " + neonet_error$() + sock_output$ = "Could not complete TLS exchange with " + sock_host$ + ":443" + neoui_show_toast("TLS failed", 1500) + else + sock_status_str$ = "TLS :443 OK (" + str$(neonet_last_len()) + " B recv)" + sock_output$ = sanitize_display_text$(rx$, 1800) + neoui_show_toast("TLS recv " + str$(neonet_last_len()) + " B", 1500) + fi + + elsif sock_proto_idx = 1 then + neoui_show_toast("TCP connect whois.iana.org:43 ...", 500) + render_all() + neoui_flush() + + rx$ = neonet_tcp_exchange$("whois.iana.org", 43, sock_host$ + crlf$, 4000) + if rx$ = "" and neonet_error$() <> "" then + sock_status_str$ = "TCP Error: " + neonet_error$() + sock_output$ = "Could not query whois.iana.org:43" + neoui_show_toast("TCP failed", 1500) + else + sock_status_str$ = "TCP :43 OK (" + str$(neonet_last_len()) + " B recv)" + sock_output$ = sanitize_display_text$(rx$, 1800) + neoui_show_toast("TCP recv " + str$(neonet_last_len()) + " B", 1500) + fi + + else + dns_srv$ = neonet_system_dns$() + neoui_show_toast("UDP DNS @" + dns_srv$ + ":53 ...", 500) + render_all() + neoui_flush() + + ip$ = neonet_udp_dns_a$(dns_srv$, sock_host$, 3000) + if ip$ = "" then + sock_status_str$ = "UDP DNS Error: " + neonet_error$() + sock_output$ = "Resolver: " + dns_srv$ + ":53\nQuery: " + sock_host$ + "\nError: " + neonet_error$() + neoui_show_toast("UDP DNS failed", 1500) + else + sock_status_str$ = "UDP :53 -> " + ip$ + sock_output$ = "Protocol: RFC 1035 Binary UDP Datagram\nServer: " + dns_srv$ + ":53\nQuestion: " + sock_host$ + " (IN A)\nResolved IPv4: " + ip$ + "\nPacket Size: " + str$(neonet_last_len()) + " bytes" + neoui_show_toast(sock_host$ + " -> " + ip$, 1800) + fi + fi +end sub + +sub render_http_tab() + local url_disp$, hdr_state$, view_lbl$ + if http_focus = 0 then + sync_input_box(0) + url_disp$ = neoui_input_get_text$() + else + url_disp$ = http_url$ + fi + + neoui_draw_input_box(6, 60, 228, 36, http_focus = 0, "Target URL [" + http_methods$(http_method_idx) + "]", url_disp$, "https://...", 0) + + if custom_hdr_on then + hdr_state$ = "ON" + else + hdr_state$ = "OFF" + fi + neoui_draw_toggle_row(0, 98, 28, http_focus = 1, neoui_icon$("edit"), neoui.TEXT_BLUE, "Hdr: X-Bananarchy", custom_hdr_on, hdr_state$) + + if show_raw_headers then + view_lbl$ = "Show:Hdrs" + else + view_lbl$ = "Show:Body" + fi + neoui_draw_button(6, 128, 72, 22, http_focus = 2, 0, neoui_icon$("globe"), "Send") + neoui_draw_button(84, 128, 72, 22, http_focus = 3, 0, neoui_icon$("sort"), "Method") + neoui_draw_button(162, 128, 72, 22, http_focus = 4, 0, neoui_icon$("eye"), view_lbl$) + + neoui_fill_rect(6, 153, 228, 114, neoui_color(neoui.COLOR_BG_ALT_ODD)) + if http_focus = 5 then + neoui_draw_rect(6, 153, 228, 114, neoui_color(neoui.COLOR_ACCENT)) + else + neoui_draw_rect(6, 153, 228, 114, neoui_color(neoui.COLOR_BORDER)) + fi + + neoui_draw_text(neoui.FONT_SMALL, neoui.TEXT_GREEN, 10, 155, 14, http_status_str$, 220) + neoui_draw_text(neoui.FONT_SMALL, neoui.TEXT_YELLOW, 10, 169, 14, http_meta_str$, 220) + neoui_draw_line(8, 184, 232, 184, neoui_color(neoui.COLOR_DIVIDER)) + neoui_draw_text_wrapped(neoui.FONT_SMALL, neoui.TEXT_LIGHT, 10, 186, 220, 78, http_output$, http_scroll) + + if http_focus = 0 then + neoui_draw_multitap_bar(0, 248, 240, 22, "0-9:Type 1:Sym #:Mode OK:Send") + fi +end sub + +sub render_sockets_tab() + local host_disp$ + if sock_focus = 1 then + sync_input_box(1) + host_disp$ = neoui_input_get_text$() + else + host_disp$ = sock_host$ + fi + + neoui_draw_list_row(0, 60, 30, sock_focus = 0, neoui_icon$("wifi"), neoui.TEXT_YELLOW, sock_protos$(sock_proto_idx), "", "< >") + neoui_draw_input_box(6, 92, 228, 36, sock_focus = 1, "Host / Domain", host_disp$, "example.com", 0) + + neoui_draw_button(6, 130, 140, 22, sock_focus = 2, 0, neoui_icon$("check"), "Run Exchange") + neoui_draw_button(152, 130, 82, 22, sock_focus = 3, 0, neoui_icon$("refresh"), "Clear") + + neoui_fill_rect(6, 155, 228, 112, neoui_color(neoui.COLOR_BG_ALT_ODD)) + if sock_focus = 4 then + neoui_draw_rect(6, 155, 228, 112, neoui_color(neoui.COLOR_ACCENT)) + else + neoui_draw_rect(6, 155, 228, 112, neoui_color(neoui.COLOR_BORDER)) + fi + + neoui_draw_text(neoui.FONT_SMALL, neoui.TEXT_GREEN, 10, 157, 15, sock_status_str$, 220) + neoui_draw_line(8, 173, 232, 173, neoui_color(neoui.COLOR_DIVIDER)) + neoui_draw_text_wrapped(neoui.FONT_SMALL, neoui.TEXT_LIGHT, 10, 175, 220, 90, sock_output$, sock_scroll) + + if sock_focus = 1 then + neoui_draw_multitap_bar(0, 248, 240, 22, "0-9:Type 1:Sym #:Mode OK:Run") + fi +end sub + +sub render_tools_tab() + local tls_lbl$ + if tls_insecure then + tls_lbl$ = "Insecure" + else + tls_lbl$ = "Strict" + fi + + neoui_draw_toggle_row(0, 62, 32, tool_focus = 0, neoui_icon$("lock"), neoui.TEXT_GREEN, "TLS Cert Check", 1 - tls_insecure, tls_lbl$) + neoui_draw_list_row(1, 96, 32, tool_focus = 1, neoui_icon$("folder"), neoui.TEXT_BLUE, "Download example.com", dl_status$, "Run") + + neoui_fill_rect(6, 132, 228, 134, neoui_color(neoui.COLOR_BG_ALT_ODD)) + neoui_draw_rect(6, 132, 228, 134, neoui_color(neoui.COLOR_BORDER)) + + neoui_draw_text(neoui.FONT_SMALL, neoui.TEXT_YELLOW, 10, 135, 15, "URL Encode / Decode FFI:", 220) + neoui_draw_text(neoui.FONT_SMALL, neoui.TEXT_LIGHT, 10, 150, 14, "In : " + sample_raw$, 220) + neoui_draw_text(neoui.FONT_SMALL, neoui.TEXT_MUTED, 10, 164, 14, "Enc: " + sample_enc$, 220) + neoui_draw_line(8, 181, 232, 181, neoui_color(neoui.COLOR_DIVIDER)) + neoui_draw_text(neoui.FONT_SMALL, neoui.TEXT_YELLOW, 10, 184, 15, "System DNS: " + neonet_system_dns$(), 220) + neoui_draw_text_wrapped(neoui.FONT_SMALL, neoui.TEXT_MUTED, 10, 200, 220, 62, "Engine: " + neonet_version$(), 0) +end sub + +sub render_all() + local badge$, mid_lbl$, right_lbl$ + neoui_begin_frame() + + if (active_tab = 0 and http_focus = 0) or (active_tab = 1 and sock_focus = 1) then + badge$ = neoui_input_mode_badge$() + else + badge$ = "libcurl" + fi + + neoui_draw_header(neoui_icon$("globe"), neoui.TEXT_YELLOW, "NeoNet + NeoUI", badge$) + neoui_draw_tabs("1:HTTP/S|2:Sockets|3:Tools", active_tab, 34, 24) + + mid_lbl$ = "Select" + right_lbl$ = "Quit" + + if active_tab = 0 then + render_http_tab() + if http_focus = 0 and len(neoui_input_get_text$()) > 0 then + right_lbl$ = "Del" + fi + if http_focus = 0 or http_focus = 2 then + mid_lbl$ = "Send" + elsif http_focus = 5 then + mid_lbl$ = "Hdr/Body" + fi + elsif active_tab = 1 then + render_sockets_tab() + if sock_focus = 1 and len(neoui_input_get_text$()) > 0 then + right_lbl$ = "Del" + fi + if sock_focus = 1 or sock_focus = 2 then + mid_lbl$ = "Run" + fi + else + render_tools_tab() + fi + + if modal_mode = 1 then + neoui_draw_menu_popup("HTTPS GET example.com|HTTPS HEAD example.com|TLS :443 Raw Exchange|TCP :43 WHOIS Lookup|UDP :53 DNS Resolve|Reload Theme|Quit Demo", neoui_icon$("globe") + "|" + neoui_icon$("info") + "|" + neoui_icon$("lock") + "|" + neoui_icon$("term") + "|" + neoui_icon$("wifi") + "|" + neoui_icon$("theme") + "|" + neoui_icon$("close"), menu_sel, 7) + neoui_draw_softkeys("Close", "Run", "Back") + else + neoui_draw_softkeys("Presets", mid_lbl$, right_lbl$) + fi + + neoui_end_frame() +end sub + +render_all() + +running = 1 +while running + ev = neoui_poll_event(250) + + if ev = neoui.EV_CLOSE_REQ then + running = 0 + elsif ev = neoui.EV_EXPOSE or ev = neoui.EV_THEME_RELOAD then + render_all() + elsif ev = neoui.EV_SOFTKEY_LEFT then + save_input_box() + if modal_mode = 0 then + modal_mode = 1 + menu_sel = 0 + else + modal_mode = 0 + fi + render_all() + elsif ev = neoui.EV_SOFTKEY_RIGHT then + if modal_mode <> 0 then + modal_mode = 0 + render_all() + elsif active_tab = 0 and http_focus = 0 and len(neoui_input_get_text$()) > 0 then + neoui_input_backspace() + http_url$ = neoui_input_get_text$() + render_all() + elsif active_tab = 1 and sock_focus = 1 and len(neoui_input_get_text$()) > 0 then + neoui_input_backspace() + sock_host$ = neoui_input_get_text$() + render_all() + else + running = 0 + fi + elsif ev = neoui.EV_KEY_PRESS then + k = neoui_event_key() + + if modal_mode = 1 then + if k = neoui.KEY_UP then + menu_sel = mod(menu_sel + 6, 7) + elsif k = neoui.KEY_DOWN then + menu_sel = mod(menu_sel + 1, 7) + elsif k = neoui.KEY_BACK then + modal_mode = 0 + elsif k = neoui.KEY_OK then + modal_mode = 0 + if menu_sel = 0 then + active_tab = 0 + http_focus = 2 + http_url$ = "https://example.com/" + http_method_idx = 0 + show_raw_headers = 0 + run_http_request() + elsif menu_sel = 1 then + active_tab = 0 + http_focus = 2 + http_url$ = "https://example.com/" + http_method_idx = 2 + show_raw_headers = 1 + run_http_request() + elsif menu_sel = 2 then + active_tab = 1 + sock_focus = 2 + sock_proto_idx = 0 + sock_host$ = "example.com" + run_socket_exchange() + elsif menu_sel = 3 then + active_tab = 1 + sock_focus = 2 + sock_proto_idx = 1 + sock_host$ = "example.com" + run_socket_exchange() + elsif menu_sel = 4 then + active_tab = 1 + sock_focus = 2 + sock_proto_idx = 2 + sock_host$ = "example.com" + run_socket_exchange() + elsif menu_sel = 5 then + neoui_reload_theme() + neoui_show_toast("Theme reloaded!", 1400) + elsif menu_sel = 6 then + running = 0 + fi + fi + render_all() + + elsif active_tab = 0 and http_focus = 0 then + sync_input_box(0) + if k = neoui.KEY_UP then + save_input_box() + http_focus = 5 + elsif k = neoui.KEY_DOWN then + save_input_box() + http_focus = 1 + elsif k = neoui.KEY_OK then + run_http_request() + else + neoui_input_feed_key(k) + http_url$ = neoui_input_get_text$() + fi + render_all() + + elsif active_tab = 1 and sock_focus = 1 then + sync_input_box(1) + if k = neoui.KEY_UP then + save_input_box() + sock_focus = 0 + elsif k = neoui.KEY_DOWN then + save_input_box() + sock_focus = 2 + elsif k = neoui.KEY_OK then + run_socket_exchange() + else + neoui_input_feed_key(k) + sock_host$ = neoui_input_get_text$() + fi + render_all() + + else + if k = neoui.KEY_1 then + save_input_box() + active_tab = 0 + elsif k = neoui.KEY_2 then + save_input_box() + active_tab = 1 + elsif k = neoui.KEY_3 then + save_input_box() + active_tab = 2 + elsif k = neoui.KEY_BACK then + running = 0 + elsif active_tab = 0 then + if k = neoui.KEY_UP then + if http_focus = 5 and http_scroll > 0 then + http_scroll = http_scroll - 1 + else + http_focus = mod(http_focus + 5, 6) + fi + elsif k = neoui.KEY_DOWN then + if http_focus = 5 then + http_scroll = http_scroll + 1 + else + http_focus = mod(http_focus + 1, 6) + fi + elsif k = neoui.KEY_LEFT then + if http_focus = 3 then + http_method_idx = mod(http_method_idx + 2, 3) + elsif http_focus = 4 then + http_focus = 3 + elsif http_focus = 5 and http_scroll > 0 then + http_scroll = 0 + http_focus = 2 + else + active_tab = 2 + fi + elsif k = neoui.KEY_RIGHT then + if http_focus = 2 then + http_focus = 3 + elsif http_focus = 3 then + http_focus = 4 + else + active_tab = 1 + fi + elsif k = neoui.KEY_OK then + if http_focus = 1 then + custom_hdr_on = 1 - custom_hdr_on + elsif http_focus = 2 then + run_http_request() + elsif http_focus = 3 then + http_method_idx = mod(http_method_idx + 1, 3) + elsif http_focus = 4 or http_focus = 5 then + show_raw_headers = 1 - show_raw_headers + http_scroll = 0 + if show_raw_headers then + http_output$ = sanitize_display_text$(neonet_response_headers$(), 1800) + else + http_output$ = sanitize_display_text$(neonet_body$(), 1800) + fi + fi + fi + elsif active_tab = 1 then + if k = neoui.KEY_UP then + if sock_focus = 4 and sock_scroll > 0 then + sock_scroll = sock_scroll - 1 + else + sock_focus = mod(sock_focus + 4, 5) + fi + elsif k = neoui.KEY_DOWN then + if sock_focus = 4 then + sock_scroll = sock_scroll + 1 + else + sock_focus = mod(sock_focus + 1, 5) + fi + elsif k = neoui.KEY_LEFT then + if sock_focus = 0 then + sock_proto_idx = mod(sock_proto_idx + 2, 3) + elsif sock_focus = 3 then + sock_focus = 2 + else + active_tab = 0 + fi + elsif k = neoui.KEY_RIGHT then + if sock_focus = 0 then + sock_proto_idx = mod(sock_proto_idx + 1, 3) + elsif sock_focus = 2 then + sock_focus = 3 + else + active_tab = 2 + fi + elsif k = neoui.KEY_OK then + if sock_focus = 0 then + sock_proto_idx = mod(sock_proto_idx + 1, 3) + elsif sock_focus = 2 then + run_socket_exchange() + elsif sock_focus = 3 then + sock_output$ = "" + sock_status_str$ = "Cleared" + sock_scroll = 0 + fi + fi + elsif active_tab = 2 then + if k = neoui.KEY_UP or k = neoui.KEY_DOWN then + tool_focus = 1 - tool_focus + elsif k = neoui.KEY_LEFT then + active_tab = 1 + elsif k = neoui.KEY_RIGHT then + active_tab = 0 + elsif k = neoui.KEY_OK then + if tool_focus = 0 then + tls_insecure = 1 - tls_insecure + r = neonet_set_insecure(tls_insecure) + if tls_insecure then + neoui_show_toast("TLS cert check disabled", 1400) + else + neoui_show_toast("TLS cert check enabled", 1400) + fi + elsif tool_focus = 1 then + neoui_show_toast("Downloading to /tmp/neonet_dl.html ...", 500) + render_all() + neoui_flush() + if neonet_download("https://example.com/", "/tmp/neonet_dl.html", "") then + dl_status$ = "Saved /tmp/neonet_dl.html (HTTP " + str$(neonet_status()) + ")" + neoui_show_toast("Saved /tmp/neonet_dl.html!", 1600) + else + dl_status$ = "Error: " + neonet_error$() + neoui_show_toast("Download failed", 1600) + fi + fi + fi + fi + render_all() + fi + fi +wend + +r = neonet_cleanup() +neoui_shutdown() diff --git a/overlay/rootfs/usr/bin/bananarchy-fcitx5.sh b/overlay/rootfs/usr/bin/bananarchy-fcitx5.sh new file mode 100755 index 0000000..033a477 --- /dev/null +++ b/overlay/rootfs/usr/bin/bananarchy-fcitx5.sh @@ -0,0 +1,38 @@ +#!/bin/sh +export HOME="${HOME:-/home/user}" +export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/10000}" +export XDG_CONFIG_HOME="${XDG_CONFIG_HOME:-$HOME/.config}" +export XDG_DATA_HOME="${XDG_DATA_HOME:-$HOME/.local/share}" +export XDG_CACHE_HOME="${XDG_CACHE_HOME:-$HOME/.cache}" +export DISPLAY="${DISPLAY:-:0}" +export LANG=C.UTF-8 +export LC_ALL=C.UTF-8 +export CHARSET=UTF-8 +export XMODIFIERS=@im=fcitx +export GTK_IM_MODULE=fcitx +export QT_IM_MODULE=fcitx + +if [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ] && [ -r "$XDG_RUNTIME_DIR/dbus.bus" ]; then + read -r DBUS_SESSION_BUS_ADDRESS < "$XDG_RUNTIME_DIR/dbus.bus" 2>/dev/null || true + export DBUS_SESSION_BUS_ADDRESS +fi + +if [ -d /home/user/.local/x11 ]; then + export FCITX_ADDON_DIRS=/home/user/.local/lib/fcitx5:/home/user/.local/x11:/usr/lib/fcitx5 +else + export FCITX_ADDON_DIRS=/home/user/.local/lib/fcitx5:/usr/lib/fcitx5 +fi + +for p in $(pidof fcitx5 2>/dev/null || true); do + if [ "$p" != "$$" ] && [ "$p" != "$PPID" ]; then + kill "$p" 2>/dev/null || true + fi +done +sleep 0.05 +for p in $(pidof fcitx5 2>/dev/null || true); do + if [ "$p" != "$$" ] && [ "$p" != "$PPID" ]; then + kill -9 "$p" 2>/dev/null || true + fi +done + +exec /usr/bin/fcitx5 -D --disable=wayland >/tmp/fcitx5.log 2>&1 diff --git a/overlay/rootfs/usr/bin/bananarchy-x11-session.sh b/overlay/rootfs/usr/bin/bananarchy-x11-session.sh index 69a5055..6e8651f 100755 --- a/overlay/rootfs/usr/bin/bananarchy-x11-session.sh +++ b/overlay/rootfs/usr/bin/bananarchy-x11-session.sh @@ -93,7 +93,6 @@ trap 'rm -f "$SESSION_PID_FILE"; pkill -P $$ >/dev/null 2>&1 || true; exit 0' IN pkill -9 -x conky >/dev/null 2>&1 || true rm -rf /tmp/sxmo_conky_time_state /tmp/sxmo_conky_restart.lock DISPLAY=:0 CONKY_DPY=:0 conky -c /home/user/.config/sxmo/conky.conf -d >/dev/null 2>&1 /dev/null 2>&1 || fcitx5 -d >/tmp/fcitx5.log 2>&1 /tmp/sxmo_hook_start.log 2>&1 /dev/null)" = "$$" ]; do pkill -9 -x conky >/dev/null 2>&1 || true rm -rf /tmp/sxmo_conky_time_state /tmp/sxmo_conky_restart.lock DISPLAY=:0 CONKY_DPY=:0 conky -c /home/user/.config/sxmo/conky.conf -d >/dev/null 2>&1 /dev/null 2>&1 || fcitx5 -d >/tmp/fcitx5.log 2>&1 /dev/null 2>&1 || superctl start fcitx5 >/dev/null 2>&1 || /usr/bin/bananarchy-fcitx5.sh /tmp/dwm.log 2>&1 || true diff --git a/overlay/rootfs/usr/bin/dwm b/overlay/rootfs/usr/bin/dwm index fbc60c0..088d451 100755 Binary files a/overlay/rootfs/usr/bin/dwm and b/overlay/rootfs/usr/bin/dwm differ diff --git a/overlay/rootfs/usr/bin/dwm-plugin b/overlay/rootfs/usr/bin/dwm-plugin index ca67f48..9127587 100755 Binary files a/overlay/rootfs/usr/bin/dwm-plugin and b/overlay/rootfs/usr/bin/dwm-plugin differ diff --git a/overlay/rootfs/usr/bin/st b/overlay/rootfs/usr/bin/st index b7cdf18..3a58522 100755 Binary files a/overlay/rootfs/usr/bin/st and b/overlay/rootfs/usr/bin/st differ diff --git a/overlay/rootfs/usr/bin/sxmo_common.sh b/overlay/rootfs/usr/bin/sxmo_common.sh new file mode 100755 index 0000000..212fc42 --- /dev/null +++ b/overlay/rootfs/usr/bin/sxmo_common.sh @@ -0,0 +1,78 @@ +#!/bin/sh +# SPDX-License-Identifier: AGPL-3.0-only +# Copyright 2022 Sxmo Contributors + +# This script is meant to be sourced by various sxmo scripts +# and defines some common settings + +export HOME="${HOME:-/home/user}" +export DISPLAY="${DISPLAY:-:0}" +export SXMO_WM="${SXMO_WM:-dwm}" +export SXMO_MENU="${SXMO_MENU:-dmenu}" +export SXMO_TERMINAL="${SXMO_TERMINAL:-st}" +export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/10000}" +export XDG_CONFIG_HOME="${XDG_CONFIG_HOME:-$HOME/.config}" +export XDG_DATA_HOME="${XDG_DATA_HOME:-$HOME/.local/share}" +export XDG_CACHE_HOME="${XDG_CACHE_HOME:-$HOME/.cache}" +export XDG_STATE_HOME="${XDG_STATE_HOME:-$HOME/.local/state}" +export LANG="${LANG:-C.UTF-8}" +export LC_ALL="${LC_ALL:-C.UTF-8}" +export XMODIFIERS="${XMODIFIERS:-@im=fcitx}" +export GTK_IM_MODULE="${GTK_IM_MODULE:-fcitx}" +export QT_IM_MODULE="${QT_IM_MODULE:-fcitx}" + +if [ -z "${DBUS_SESSION_BUS_ADDRESS:-}" ] && [ -r "$XDG_RUNTIME_DIR/dbus.bus" ]; then + read -r DBUS_SESSION_BUS_ADDRESS < "$XDG_RUNTIME_DIR/dbus.bus" 2>/dev/null || true + export DBUS_SESSION_BUS_ADDRESS +fi + +# aliases aren't expanded in bash +# shellcheck disable=SC2039,SC3044 +command -v shopt > /dev/null && shopt -s expand_aliases + +alias dmenu="sxmo_dmenu.sh" +alias bemenu="sxmo_dmenu.sh" + +if ! command -v sxmobar > /dev/null; then + sxmobar() { + sxmo_status.sh "$@" + } +fi + +confirm_menu() { + printf "No\nYes\n" | \ + dmenu "$@" | \ + grep -q "Yes" +} + +sxmo_log() { + printf "%s %s: %s\n" "$(date +%H:%M:%S)" "${0##*/}" "$*" | tee -a "${XDG_STATE_HOME:-$HOME}"/sxmo.log 1>&2 +} + +sxmo_debug() { + if [ -n "$SXMO_DEBUG" ]; then + printf "%s %s DEBUG: %s\n" "$(date +%H:%M:%S)" "${0##*/}" "$*" | tee -a "${XDG_STATE_HOME:-$HOME}"/sxmo.log 1>&2 + fi +} + +xdg_data_path() { + filepath=$1 + instance_count=${2:-1} + sep=${3:-" "} + + IFS=':' + instance=0 + for dir in ${XDG_DATA_DIRS:-/usr/local/share:/usr/share} + do + if [ -e "$dir/$filepath" ]; then + if [ "$instance" -ge "$instance_count" ] && [ "$instance_count" != "0" ]; then + break + fi + if [ $instance -gt 0 ]; then + printf '%b' "${sep}" + fi + printf '%s' "${dir}/${filepath}" + instance=$((instance+1)) + fi + done +} diff --git a/overlay/rootfs/usr/bin/sxmo_killwindow.sh b/overlay/rootfs/usr/bin/sxmo_killwindow.sh new file mode 100755 index 0000000..1724b5d --- /dev/null +++ b/overlay/rootfs/usr/bin/sxmo_killwindow.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# SPDX-License-Identifier: AGPL-3.0-only +# Copyright 2022 Sxmo Contributors + +# include common definitions +# shellcheck source=scripts/core/sxmo_common.sh +. sxmo_common.sh + +if [ -e /tmp/dwm_plugin_dmenu.active ] && [ -p /tmp/dwm_plugin_dmenu.fifo ]; then + printf "CLOSE\n" > /tmp/dwm_plugin_dmenu.fifo 2>/dev/null || true + sleep 0.04 +fi + +for _pair in \ + "xdrawer.pid:/tmp/dwm_plugin_xdrawer.fifo" \ + "xdialer.pid:/tmp/dwm_plugin_dialer.fifo" \ + "xcalllog.pid:/tmp/dwm_plugin_calllog.fifo" \ + "xcontacts.pid:/tmp/dwm_plugin_contacts.fifo" \ + "xsms.pid:/tmp/dwm_plugin_sms.fifo" \ + "xfiles.pid:/tmp/dwm_plugin_files.fifo" \ + "xcamera.pid:/tmp/dwm_plugin_camera.fifo" \ + "xthemes.pid:/tmp/dwm_plugin_themes.fifo" \ + "xmodem.pid:/tmp/dwm_plugin_modem.fifo" \ + "xnetworks.pid:/tmp/dwm_plugin_networks.fifo" \ + "xringtones.pid:/tmp/dwm_plugin_ringtones.fifo" \ + "xwallpapers.pid:/tmp/dwm_plugin_wallpapers.fifo" \ + "xmusic.pid:/tmp/dwm_plugin_music.fifo"; do + _pf="${_pair%%:*}" + _ff="${_pair#*:}" + if [ -f "${XDG_RUNTIME_DIR:-/run/user/10000}/$_pf" ] || [ -f "/tmp/$_pf" ]; then + if [ -p "$_ff" ]; then + printf "CLOSE\n" > "$_ff" 2>/dev/null || true + exit 0 + fi + fi +done + +case "${SXMO_WM:-dwm}" in + i3) i3-msg kill ;; + sway) swaymsg kill ;; + river) riverctl close ;; + dwm|*) + _wid="$(xdotool getactivewindow 2>/dev/null || true)" + xdotool key --clearmodifiers Super+Shift+c 2>/dev/null || true + if [ -n "$_wid" ]; then + sleep 0.1 + if xprop -id "$_wid" WM_STATE >/dev/null 2>&1; then + xdotool windowkill "$_wid" 2>/dev/null || true + fi + fi + ;; +esac diff --git a/overlay/rootfs/usr/bin/sxmo_wm.sh b/overlay/rootfs/usr/bin/sxmo_wm.sh index 4ba6fd8..c114acd 100755 --- a/overlay/rootfs/usr/bin/sxmo_wm.sh +++ b/overlay/rootfs/usr/bin/sxmo_wm.sh @@ -7,6 +7,19 @@ # shellcheck source=scripts/core/sxmo_common.sh . sxmo_common.sh +export DISPLAY="${DISPLAY:-:0}" +export SXMO_WM="${SXMO_WM:-dwm}" + +_dwm_prep() { + if [ -z "$DISPLAY" ]; then + export DISPLAY=:0 + fi + if [ -e /tmp/dwm_plugin_dmenu.active ] && [ -p /tmp/dwm_plugin_dmenu.fifo ]; then + printf "CLOSE\n" > /tmp/dwm_plugin_dmenu.fifo 2>/dev/null || true + sleep 0.04 + fi +} + swi3msg() { case "$SXMO_WM" in sway) swaymsg "$@" ;; @@ -328,10 +341,8 @@ swi3togglelayout() { } dwmtogglelayout() { - if [ -z "$DISPLAY" ]; then - export DISPLAY=:0 - fi - xdotool key --clearmodifiers key Super+space + _dwm_prep + xdotool key --clearmodifiers Super+space } rivertogglelayout() { @@ -349,9 +360,7 @@ swayswitchfocus() { } dwmswitchfocus() { - if [ -z "$DISPLAY" ]; then - export DISPLAY=:0 - fi + _dwm_prep xdotool key --clearmodifiers Super+x } # }}} @@ -392,9 +401,7 @@ rivernextworkspace() { } dwmnextworkspace() { - if [ -z "$DISPLAY" ]; then - export DISPLAY=:0 - fi + _dwm_prep xdotool key --clearmodifiers Super+Shift+r } @@ -403,9 +410,7 @@ swi3previousworkspace() { } dwmpreviousworkspace() { - if [ -z "$DISPLAY" ]; then - export DISPLAY=:0 - fi + _dwm_prep xdotool key --clearmodifiers Super+Shift+e } @@ -418,9 +423,7 @@ swi3movenextworkspace() { } dwmmovenextworkspace() { - if [ -z "$DISPLAY" ]; then - export DISPLAY=:0 - fi + _dwm_prep xdotool key --clearmodifiers Super+r } @@ -429,9 +432,7 @@ swi3movepreviousworkspace() { } dwmmovepreviousworkspace() { - if [ -z "$DISPLAY" ]; then - export DISPLAY=:0 - fi + _dwm_prep xdotool key --clearmodifiers Super+e } @@ -445,9 +446,7 @@ riverworkspace() { } dwmworkspace() { - if [ -z "$DISPLAY" ]; then - export DISPLAY=:0 - fi + _dwm_prep xdotool key --clearmodifiers "Super+$1" } @@ -461,9 +460,7 @@ rivermoveworkspace() { } dwmmoveworkspace() { - if [ -z "$DISPLAY" ]; then - export DISPLAY=:0 - fi + _dwm_prep xdotool key --clearmodifiers "Super+shift+$1" } # }}} diff --git a/overlay/rootfs/usr/lib/dwm/plugins/dmenu.so b/overlay/rootfs/usr/lib/dwm/plugins/dmenu.so index 75b035b..adca216 100755 Binary files a/overlay/rootfs/usr/lib/dwm/plugins/dmenu.so and b/overlay/rootfs/usr/lib/dwm/plugins/dmenu.so differ diff --git a/overlay/rootfs/usr/lib/dwm/plugins/xdrawer.so b/overlay/rootfs/usr/lib/dwm/plugins/xdrawer.so index d1acc6a..2dbb52b 100755 Binary files a/overlay/rootfs/usr/lib/dwm/plugins/xdrawer.so and b/overlay/rootfs/usr/lib/dwm/plugins/xdrawer.so differ diff --git a/overlay/rootfs/usr/lib/libneoui.so b/overlay/rootfs/usr/lib/libneoui.so index ea11450..da4872a 100755 Binary files a/overlay/rootfs/usr/lib/libneoui.so and b/overlay/rootfs/usr/lib/libneoui.so differ diff --git a/overlay/rootfs/usr/lib/neonet.yab b/overlay/rootfs/usr/lib/neonet.yab new file mode 120000 index 0000000..1cf1428 --- /dev/null +++ b/overlay/rootfs/usr/lib/neonet.yab @@ -0,0 +1 @@ +/home/user/Projects/neonet.yab \ No newline at end of file diff --git a/overlay/rootfs/usr/share/superd/services/fcitx5.service b/overlay/rootfs/usr/share/superd/services/fcitx5.service new file mode 100644 index 0000000..55a0cb7 --- /dev/null +++ b/overlay/rootfs/usr/share/superd/services/fcitx5.service @@ -0,0 +1,7 @@ +[Unit] +Description=fcitx5 input support + +[Service] +Type=simple +ExecStart=/usr/bin/bananarchy-fcitx5.sh +Restart=always diff --git a/overlay/rootfs/usr/share/sxmo/default_hooks/sxmo_hook_start.sh b/overlay/rootfs/usr/share/sxmo/default_hooks/sxmo_hook_start.sh index 1d0579c..20c9bf2 100755 --- a/overlay/rootfs/usr/share/sxmo/default_hooks/sxmo_hook_start.sh +++ b/overlay/rootfs/usr/share/sxmo/default_hooks/sxmo_hook_start.sh @@ -78,7 +78,7 @@ superctl start dunst [ "$(command -v sxmo_xob)" ] && superctl start sxmo_xob pidof -s sxmo_status_xsetroot.sh >/dev/null 2>&1 || superctl start sxmo-x11-status [ "$(command -v bonsaid)" ] && superctl start bonsaid -if ! pidof -s fcitx5 >/dev/null 2>&1 && [ "$(command -v fcitx5)" ]; then +if [ "$(command -v fcitx5)" ]; then superctl start fcitx5 fi [ -n "$SXMO_MONITOR" ] && xrandr --output "$SXMO_MONITOR" --primary diff --git a/prebuilt/sxmo-x11/usr/bin/dwm b/prebuilt/sxmo-x11/usr/bin/dwm index fbc60c0..088d451 100755 Binary files a/prebuilt/sxmo-x11/usr/bin/dwm and b/prebuilt/sxmo-x11/usr/bin/dwm differ diff --git a/prebuilt/sxmo-x11/usr/bin/dwm-plugin b/prebuilt/sxmo-x11/usr/bin/dwm-plugin index ca67f48..9127587 100755 Binary files a/prebuilt/sxmo-x11/usr/bin/dwm-plugin and b/prebuilt/sxmo-x11/usr/bin/dwm-plugin differ diff --git a/prebuilt/sxmo-x11/usr/bin/st b/prebuilt/sxmo-x11/usr/bin/st index b7cdf18..3a58522 100755 Binary files a/prebuilt/sxmo-x11/usr/bin/st and b/prebuilt/sxmo-x11/usr/bin/st differ diff --git a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/dmenu.so b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/dmenu.so index 75b035b..adca216 100755 Binary files a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/dmenu.so and b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/dmenu.so differ diff --git a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/xdrawer.so b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/xdrawer.so index d1acc6a..2dbb52b 100755 Binary files a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/xdrawer.so and b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/xdrawer.so differ diff --git a/prebuilt/sxmo-x11/usr/lib/libneoui.so b/prebuilt/sxmo-x11/usr/lib/libneoui.so index ea11450..da4872a 100755 Binary files a/prebuilt/sxmo-x11/usr/lib/libneoui.so and b/prebuilt/sxmo-x11/usr/lib/libneoui.so differ diff --git a/src/dwm-plugins/dwm_plugin_runner.c b/src/dwm-plugins/dwm_plugin_runner.c index 239a36a..e02b83b 100644 --- a/src/dwm-plugins/dwm_plugin_runner.c +++ b/src/dwm-plugins/dwm_plugin_runner.c @@ -322,6 +322,44 @@ static int list_plugins(void) { int main(int argc, char **argv) { signal(SIGPIPE, SIG_IGN); + if (!getenv("DISPLAY")) + setenv("DISPLAY", ":0", 0); + if (!getenv("XDG_RUNTIME_DIR")) + setenv("XDG_RUNTIME_DIR", "/run/user/10000", 0); + if (!getenv("SXMO_WM")) + setenv("SXMO_WM", "dwm", 0); + if (!getenv("SXMO_MENU")) + setenv("SXMO_MENU", "dmenu", 0); + if (!getenv("SXMO_TERMINAL")) + setenv("SXMO_TERMINAL", "st", 0); + setenv("LANG", "C.UTF-8", 1); + setenv("LC_ALL", "C.UTF-8", 1); + setenv("XMODIFIERS", "@im=fcitx", 1); + setenv("GTK_IM_MODULE", "fcitx", 1); + setenv("QT_IM_MODULE", "fcitx", 1); + if (!getenv("FCITX_ADDON_DIRS")) { + if (access("/home/user/.local/x11", F_OK) == 0) + setenv("FCITX_ADDON_DIRS", "/home/user/.local/lib/fcitx5:/home/user/.local/x11:/usr/lib/fcitx5", 0); + else + setenv("FCITX_ADDON_DIRS", "/home/user/.local/lib/fcitx5:/usr/lib/fcitx5", 0); + } + if (!getenv("DBUS_SESSION_BUS_ADDRESS")) { + const char *rdir = getenv("XDG_RUNTIME_DIR"); + char bpath[256], bbuf[256]; + snprintf(bpath, sizeof(bpath), "%s/dbus.bus", + (rdir && rdir[0]) ? rdir : "/run/user/10000"); + FILE *bf = fopen(bpath, "r"); + if (bf) { + if (fgets(bbuf, sizeof(bbuf), bf)) { + char *nl = strpbrk(bbuf, "\r\n"); + if (nl) + *nl = '\0'; + if (bbuf[0]) + setenv("DBUS_SESSION_BUS_ADDRESS", bbuf, 1); + } + fclose(bf); + } + } const char *plugin_name = resolve_plugin_name_from_argv0(argv[0]); int sub_argc = argc; char **sub_argv = argv; diff --git a/src/neoui/neoui.cpp b/src/neoui/neoui.cpp index 8442e84..6c8b416 100644 --- a/src/neoui/neoui.cpp +++ b/src/neoui/neoui.cpp @@ -1393,6 +1393,8 @@ bool NeoWindow::create(const char* resName, const char* resClass, 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); @@ -2660,6 +2662,14 @@ int neoui_poll_event(int timeout_ms) { 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); diff --git a/src/sxmo-dmenu/dmenu.c b/src/sxmo-dmenu/dmenu.c index 16d2c8c..0bc8320 100644 --- a/src/sxmo-dmenu/dmenu.c +++ b/src/sxmo-dmenu/dmenu.c @@ -816,6 +816,26 @@ trigger_plugin_open(const char *plugin_spec) spawn_detached_sh(cmd); } +static void +send_dwm_cmd(long op, long argval) +{ + if (!dpy) + return; + Atom cmd_atom = XInternAtom(dpy, "_BANANARCHY_DWM_CMD", False); + XClientMessageEvent cme; + memset(&cme, 0, sizeof(cme)); + cme.type = ClientMessage; + cme.display = dpy; + cme.window = root; + cme.message_type = cmd_atom; + cme.format = 32; + cme.data.l[0] = op; + cme.data.l[1] = argval; + XSetErrorHandler(ignore_xerror); + XSendEvent(dpy, root, False, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent *)&cme); + XSync(dpy, False); +} + static void send_key_to_window(Window target, KeySym ksym, unsigned int mod_state) { @@ -1208,6 +1228,29 @@ activate_selection(unsigned int ev_state) } return; } + if (strncmp(act, "@wm:", 4) == 0) { + const char *wm_act = act + 4; + hide_menu(); + menu_mode = MODE_NONE; + if (strncmp(wm_act, "move:", 5) == 0) { + send_dwm_cmd(1, atoi(wm_act + 5)); + } else if (strncmp(wm_act, "view:", 5) == 0) { + send_dwm_cmd(2, atoi(wm_act + 5)); + } else if (strcmp(wm_act, "focusnext") == 0) { + send_dwm_cmd(3, 1); + } else if (strcmp(wm_act, "togglelayout") == 0) { + send_dwm_cmd(4, 1); + } else if (strcmp(wm_act, "kill") == 0) { + send_dwm_cmd(5, (long)target_win); + } else if (strcmp(wm_act, "pushstack") == 0) { + send_dwm_cmd(6, 1); + } else if (strncmp(wm_act, "shiftview:", 10) == 0) { + send_dwm_cmd(7, atoi(wm_act + 10)); + } else if (strncmp(wm_act, "tagpush:", 8) == 0) { + send_dwm_cmd(8, atoi(wm_act + 8)); + } + return; + } if (loop) { spawn_detached_sh(act); @@ -2212,12 +2255,12 @@ open_builtin_menu(const char *menu_name, int keep_idx) if (!cls[0] || strcmp(cls, "sys") == 0) { menu_name = "sys"; } else if (strcmp(cls, "st") == 0 || strncmp(cls, "st-", 3) == 0) { - /* launched from a terminal: also show the exact same Sys menu */ - menu_name = "sys"; - } - else { - /* launched from an app: show the exact same Sys menu as the desktop */ - menu_name = "sys"; + if (strstr(ttl, "nano")) + menu_name = "nano"; + else + menu_name = "st"; + } else { + menu_name = "wm"; } } @@ -2454,15 +2497,22 @@ open_builtin_menu(const char *menu_name, int keep_idx) reset_session_defaults(1, "WM Menu"); for (int ws = 1; ws <= 4; ws++) { snprintf(label, sizeof(label), "%d Move to WS %d", ws, ws); - snprintf(cmd, sizeof(cmd), "sxmo_wm.sh moveworkspace %d", ws); - add_menu_item(label, cmd, 1); + snprintf(cmd, sizeof(cmd), "@wm:move:%d", ws); + add_menu_item(label, cmd, 0); } snprintf(label, sizeof(label), "%s Shift stack", ICON_RLD); - add_menu_item(label, "sxmo_wm.sh switchfocus", 1); + add_menu_item(label, "@wm:focusnext", 0); + snprintf(label, sizeof(label), "%s Swap stack", ICON_A2X); + add_menu_item(label, "@wm:pushstack", 0); snprintf(label, sizeof(label), "%s Toggle Layout", ICON_GRD); - add_menu_item(label, "sxmo_wm.sh togglelayout", 1); + add_menu_item(label, "@wm:togglelayout", 0); snprintf(label, sizeof(label), "%s Kill window", ICON_CLS); - add_menu_item(label, "sxmo_killwindow.sh", 0); + add_menu_item(label, "@wm:kill", 0); + for (int ws = 1; ws <= 4; ws++) { + snprintf(label, sizeof(label), "%s Go to WS %d", ICON_WIN, ws); + snprintf(cmd, sizeof(cmd), "@wm:view:%d", ws); + add_menu_item(label, cmd, 0); + } snprintf(label, sizeof(label), "%s System Menu", ICON_MNU); add_menu_item(label, "@menu:sys", 1); snprintf(label, sizeof(label), "%s Close Menu", ICON_CLS); @@ -2556,7 +2606,9 @@ open_builtin_menu(const char *menu_name, int keep_idx) snprintf(label, sizeof(label), "%s New Terminal", ICON_TRM); add_menu_item(label, "sxmo_terminal.sh", 0); snprintf(label, sizeof(label), "%s Close Terminal", ICON_CLS); - add_menu_item(label, "sxmo_killwindow.sh", 0); + add_menu_item(label, "@wm:kill", 0); + snprintf(label, sizeof(label), "%s Windows", ICON_WIN); + add_menu_item(label, "@menu:wm", 1); snprintf(label, sizeof(label), "%s Type complete", ICON_ITM); add_menu_item(label, "@key:ctrl_shift:u", 0); snprintf(label, sizeof(label), "%s Toggle Selmode", ICON_ITM); @@ -2606,6 +2658,8 @@ open_builtin_menu(const char *menu_name, int keep_idx) add_menu_item(label, "@key:none:Next", 1); snprintf(label, sizeof(label), "%s Terminal menu", ICON_MNU); add_menu_item(label, "@menu:st", 1); + snprintf(label, sizeof(label), "%s Windows", ICON_WIN); + add_menu_item(label, "@menu:wm", 1); snprintf(label, sizeof(label), "%s System Menu", ICON_MNU); add_menu_item(label, "@menu:sys", 1); snprintf(label, sizeof(label), "%s Close Menu", ICON_CLS); @@ -2655,6 +2709,7 @@ any_other_plugin_active(void) "xnetworks.pid", "xringtones.pid", "xwallpapers.pid", + "xmusic.pid", }; const char *rdir = getenv("XDG_RUNTIME_DIR"); const char *base = (rdir && rdir[0]) ? rdir : "/run/user/10000"; @@ -2698,6 +2753,7 @@ close_other_active_plugins(void) { "xnetworks.pid", "/tmp/dwm_plugin_networks.fifo" }, { "xringtones.pid", "/tmp/dwm_plugin_ringtones.fifo" }, { "xwallpapers.pid", "/tmp/dwm_plugin_wallpapers.fifo" }, + { "xmusic.pid", "/tmp/dwm_plugin_music.fifo" }, }; const char *rdir = getenv("XDG_RUNTIME_DIR"); const char *base = (rdir && rdir[0]) ? rdir : "/run/user/10000"; @@ -2942,8 +2998,24 @@ show_menu(void) Window fw = None; int rev = 0; XGetInputFocus(dpy, &fw, &rev); - if (fw != None && fw != PointerRoot && fw != win) + if (fw != None && fw != PointerRoot && fw != root && fw != win) prevfocuswin = fw; + if (prevfocuswin == None) { + Atom net_active = XInternAtom(dpy, "_NET_ACTIVE_WINDOW", False); + Atom actual_type = None; + int actual_fmt = 0; + unsigned long nitems = 0, bytes_after = 0; + unsigned char *prop = NULL; + if (XGetWindowProperty(dpy, root, net_active, 0L, 1L, False, XA_WINDOW, + &actual_type, &actual_fmt, &nitems, &bytes_after, &prop) == Success && prop) { + if (actual_type == XA_WINDOW && actual_fmt == 32 && nitems >= 1) { + Window aw = *(Window *)prop; + if (aw != None && aw != PointerRoot && aw != root && aw != win) + prevfocuswin = aw; + } + XFree(prop); + } + } XEvent ev; while (XPending(dpy)) @@ -2996,13 +3068,13 @@ hide_menu(void) XUnsetICFocus(xic); } XUngrabKeyboard(dpy, CurrentTime); - XUnmapWindow(dpy, win); XSetErrorHandler(ignore_xerror); - if (!daemon_mode && prevfocuswin && prevfocuswin != win && prevfocuswin != PointerRoot) { + if (prevfocuswin && prevfocuswin != win && prevfocuswin != PointerRoot) { XWindowAttributes wa; if (XGetWindowAttributes(dpy, prevfocuswin, &wa) && wa.map_state == IsViewable) XSetInputFocus(dpy, prevfocuswin, RevertToParent, CurrentTime); } + XUnmapWindow(dpy, win); prevfocuswin = None; XSync(dpy, False); @@ -3722,6 +3794,29 @@ dmenu_run_main(int argc, char *argv[]) (cur_path && cur_path[0]) ? cur_path : "/usr/local/bin:/usr/bin:/bin:/sbin:/usr/sbin"); setenv("PATH", new_path, 1); } + if (!getenv("DISPLAY")) + setenv("DISPLAY", ":0", 0); + if (!getenv("XDG_RUNTIME_DIR")) + setenv("XDG_RUNTIME_DIR", "/run/user/10000", 0); + if (!getenv("SXMO_WM")) + setenv("SXMO_WM", "dwm", 0); + if (!getenv("SXMO_MENU")) + setenv("SXMO_MENU", "dmenu", 0); + if (!getenv("SXMO_TERMINAL")) + setenv("SXMO_TERMINAL", "st", 0); + setenv("LANG", "C.UTF-8", 1); + setenv("LC_ALL", "C.UTF-8", 1); + setenv("XMODIFIERS", "@im=fcitx", 1); + setenv("GTK_IM_MODULE", "fcitx", 1); + setenv("QT_IM_MODULE", "fcitx", 1); + if (!getenv("DBUS_SESSION_BUS_ADDRESS")) { + const char *rdir = getenv("XDG_RUNTIME_DIR"); + char bpath[256], bbuf[256]; + snprintf(bpath, sizeof(bpath), "%s/dbus.bus", + (rdir && rdir[0]) ? rdir : "/run/user/10000"); + if (read_first_line(bpath, bbuf, sizeof(bbuf)) && bbuf[0]) + setenv("DBUS_SESSION_BUS_ADDRESS", bbuf, 1); + } int lock_fd = -1; int fifo_fd = -1; diff --git a/src/sxmo-dwm/dwm.c b/src/sxmo-dwm/dwm.c index 9070564..1fadc61 100644 --- a/src/sxmo-dwm/dwm.c +++ b/src/sxmo-dwm/dwm.c @@ -73,7 +73,7 @@ enum { CurNormal, CurResize, CurMove, CurLast }; /* cursor */ enum { SchemeNorm, SchemeSel, SchemeTabActive, SchemeTabInactive }; /* color schemes */ enum { NetSupported, NetWMName, NetWMState, NetWMCheck, NetWMFullscreen, NetActiveWindow, NetWMWindowType, - NetWMWindowTypeDialog, NetClientList, NetLast }; /* EWMH atoms */ + NetWMWindowTypeDialog, NetClientList, NetDwmCmd, NetLast }; /* EWMH atoms */ enum { WMProtocols, WMDelete, WMState, WMTakeFocus, WMLast }; /* default atoms */ enum { ClkTagBar, ClkLtSymbol, ClkStatusText, ClkWinTitle, ClkClientWin, ClkRootWin, ClkLast }; /* clicks */ @@ -276,6 +276,7 @@ static void readxresources(void); static void reload_dwm_theme(void); static void load_plugins(void); static void unload_plugins(void); +static long long dwm_now_ms(void); static pid_t getparentprocess(pid_t p); static int isdescprocess(pid_t p, pid_t c); @@ -784,8 +785,73 @@ void clientmessage(XEvent *e) { XClientMessageEvent *cme = &e->xclient; - Client *c = wintoclient(cme->window); + Client *c; + if (cme->message_type == netatom[NetDwmCmd]) { + long op = cme->data.l[0]; + long argval = cme->data.l[1]; + if (op == 1 && argval >= 1 && argval <= 9) { + Arg a = { .ui = 1U << (argval - 1) }; + tag(&a); + } else if (op == 2 && argval >= 1 && argval <= 9) { + Arg a = { .ui = 1U << (argval - 1) }; + view(&a); + } else if (op == 3) { + Arg a = { .i = (argval != 0) ? (int)argval : +1 }; + focusstack(&a); + } else if (op == 4) { + Arg a = { .i = +1 }; + cyclelayout(&a); + } else if (op == 5) { + static Window last_kill_win = None; + static long long last_kill_ms = 0; + Client *tc = (argval != 0) ? wintoclient((Window)argval) : NULL; + if (!tc && selmon) + tc = selmon->sel; + if (tc) { + if (selmon && selmon->sel != tc) + focus(tc); + long long now = dwm_now_ms(); + int force = (tc->win == last_kill_win && (now - last_kill_ms) < 3000LL); + last_kill_win = tc->win; + last_kill_ms = now; + if (force || !sendevent(tc, wmatom[WMDelete])) { + XGrabServer(dpy); + XSetErrorHandler(xerrordummy); + XSetCloseDownMode(dpy, DestroyAll); + XKillClient(dpy, tc->win); + XSync(dpy, False); + XSetErrorHandler(xerror); + XUngrabServer(dpy); + } + } else if (argval != 0 && (Window)argval != root && + (!selmon || ((Window)argval != selmon->barwin && + (Window)argval != selmon->softwin))) { + XGrabServer(dpy); + XSetErrorHandler(xerrordummy); + XSetCloseDownMode(dpy, DestroyAll); + XKillClient(dpy, (Window)argval); + XSync(dpy, False); + XSetErrorHandler(xerror); + XUngrabServer(dpy); + } + } else if (op == 6) { + Arg a = { .i = +1 }; + if (argval < 0) + pushup(&a); + else + pushdown(&a); + } else if (op == 7) { + Arg a = { .i = (argval < 0) ? -1 : +1 }; + shiftview(&a); + } else if (op == 8) { + Arg a = { .i = (argval < 0) ? -1 : +1 }; + clienttagpush(&a); + } + return; + } + + c = wintoclient(cme->window); if (!c) return; if (cme->message_type == netatom[NetWMState]) { @@ -2694,6 +2760,7 @@ setup(void) netatom[NetWMWindowType] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE", False); netatom[NetWMWindowTypeDialog] = XInternAtom(dpy, "_NET_WM_WINDOW_TYPE_DIALOG", False); netatom[NetClientList] = XInternAtom(dpy, "_NET_CLIENT_LIST", False); + netatom[NetDwmCmd] = XInternAtom(dpy, "_BANANARCHY_DWM_CMD", False); /* init cursors */ cursor[CurNormal] = drw_cur_create(drw, XC_left_ptr); cursor[CurResize] = drw_cur_create(drw, XC_sizing); diff --git a/src/sxmo-st/x.c b/src/sxmo-st/x.c index 2c54876..ecd839a 100644 --- a/src/sxmo-st/x.c +++ b/src/sxmo-st/x.c @@ -2029,6 +2029,11 @@ run(void) while (XPending(xw.dpy)) { xev = 1; XNextEvent(xw.dpy, &ev); + if (ev.type == ClientMessage && + (Atom)ev.xclient.data.l[0] == xw.wmdeletewin) { + cmessage(&ev); + continue; + } if (XFilterEvent(&ev, None)) continue; if (handler[ev.type]) @@ -2254,6 +2259,35 @@ run: if (!opt_title) opt_title = (opt_line || !opt_cmd) ? "st" : opt_cmd[0]; + if (!getenv("DISPLAY")) + setenv("DISPLAY", ":0", 0); + if (!getenv("XDG_RUNTIME_DIR")) + setenv("XDG_RUNTIME_DIR", "/run/user/10000", 0); + if (!getenv("SXMO_WM")) + setenv("SXMO_WM", "dwm", 0); + setenv("LANG", "C.UTF-8", 1); + setenv("LC_ALL", "C.UTF-8", 1); + setenv("XMODIFIERS", "@im=fcitx", 1); + setenv("GTK_IM_MODULE", "fcitx", 1); + setenv("QT_IM_MODULE", "fcitx", 1); + if (!getenv("DBUS_SESSION_BUS_ADDRESS")) { + const char *rdir = getenv("XDG_RUNTIME_DIR"); + char bpath[256], bbuf[256]; + snprintf(bpath, sizeof(bpath), "%s/dbus.bus", + (rdir && rdir[0]) ? rdir : "/run/user/10000"); + FILE *bf = fopen(bpath, "r"); + if (bf) { + if (fgets(bbuf, sizeof(bbuf), bf)) { + char *nl = strpbrk(bbuf, "\r\n"); + if (nl) + *nl = '\0'; + if (bbuf[0]) + setenv("DBUS_SESSION_BUS_ADDRESS", bbuf, 1); + } + fclose(bf); + } + } + setlocale(LC_CTYPE, ""); XSetLocaleModifiers(""); diff --git a/src/xdrawer/xdrawer.cpp b/src/xdrawer/xdrawer.cpp index ec3ae27..0102c4d 100644 --- a/src/xdrawer/xdrawer.cpp +++ b/src/xdrawer/xdrawer.cpp @@ -31,6 +31,7 @@ #include #include #include +#include #include #include @@ -108,18 +109,24 @@ bool writeIntFile(const std::string& path, int value) { void runAsyncCmd(const std::string& cmd) { pid_t pid = ::fork(); if (pid == 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); + 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); + } } + execl("/bin/sh", "sh", "-c", cmd.c_str(), static_cast(nullptr)); + _exit(0); } - execl("/bin/sh", "sh", "-c", cmd.c_str(), static_cast(nullptr)); _exit(0); + } else if (pid > 0) { + int st = 0; + (void)::waitpid(pid, &st, 0); } } @@ -674,6 +681,8 @@ static int xdrawer_run_main(int argc, char** argv) { sigemptyset(&sa.sa_mask); sigaction(SIGTERM, &sa, nullptr); sigaction(SIGINT, &sa, nullptr); + signal(SIGCHLD, SIG_IGN); + signal(SIGPIPE, SIG_IGN); bananarchy::NeoWindow neo; if (!neo.create("xdrawer", "XDrawer", "XDrawer", kWinX, kWinY, kWinWidth, @@ -863,6 +872,7 @@ static int xdrawer_run_main(int argc, char** argv) { "xdialer.pid", "xcalllog.pid", "xcallscreen.pid", "xcontacts.pid", "xsms.pid", "xfiles.pid", "xcamera.pid", "xthemes.pid", "xmodem.pid", "xnetworks.pid", "xringtones.pid", "xwallpapers.pid", + "xmusic.pid", }; for (const char* pf : kPids) { int p = readIntFile(getRuntimeFile(pf), -1); @@ -893,6 +903,7 @@ static int xdrawer_run_main(int argc, char** argv) { closeOtherPlugin("xnetworks.pid", "/tmp/dwm_plugin_networks.fifo"); closeOtherPlugin("xringtones.pid", "/tmp/dwm_plugin_ringtones.fifo"); closeOtherPlugin("xwallpapers.pid", "/tmp/dwm_plugin_wallpapers.fifo"); + closeOtherPlugin("xmusic.pid", "/tmp/dwm_plugin_music.fifo"); if (::access("/tmp/dwm_plugin_dmenu.active", F_OK) == 0) { int dfd = ::open("/tmp/dwm_plugin_dmenu.fifo", O_WRONLY | O_NONBLOCK | O_CLOEXEC); if (dfd >= 0) {