diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 29dc6dc..4111d8a 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -4,7 +4,7 @@ Geminux combines a custom-patched Linux `7.3.5` kernel, pure-Linux MTK flasher, ## Kernel and MediaTek MT6797X support -- **Kernel tree**: Vanilla Linux `7.3.5` patched via [patches/kernel/](file:///home/lux/proj/geminux/patches/kernel) (`0001-ixoo-gemini-pda-mainline-7.3.5.patch`, `0002-mt6797-ccci-cldma-and-md1-domain.patch`, `0003-arm64-dts-mediatek-geminux-gemini-pda.patch`, `0004-gemini-ssd2092-display-and-touch.patch`, `0005-mt6797-consys-wifi-factory-firmware.patch`, `0006-mt6797-boot-cleanups.patch`). +- **Kernel tree**: Vanilla Linux `7.3.5` patched via [patches/kernel/](file:///home/lux/proj/geminux/patches/kernel) (`0001-ixoo-gemini-pda-mainline-7.3.5.patch`, `0002-mt6797-ccci-cldma-and-md1-domain.patch`, `0003-arm64-dts-mediatek-geminux-gemini-pda.patch`, `0004-gemini-ssd2092-display-and-touch.patch`, `0005-mt6797-consys-wifi-factory-firmware.patch`, `0006-mt6797-boot-cleanups.patch`, `0007-mt6797-wlan-peer-deauth-and-rekey.patch`). - **Graphics & display**: MediaTek DRM (`mediatek-drm`), Solomon Systech `SSD2092` DSI FHD+ panel & touchscreen, early-boot `simpledrm` (`DRM_SIMPLEDRM=y` + rotated `TER16x32` console), Mali-T880 `panfrost` GPU driver, and `sii902x` Slimport/HDMI bridge. - **Wi-Fi / Bluetooth CONSYS**: Staged `mt6797_wlan_core` and `btmt6797` drivers backed by NVRAM/factory firmware provisioning (`geminux-wifi-nvram` and `firmware-cache/mt6797/`). - **Modem / Telephony**: Staged `mt6797-ccci-cldma` driver exposing `/dev/ccci_md_ctl`, `/dev/ccci_fs`, `/dev/ccci_rpc`, `/dev/ttyC0..3`, and `ccmni*` network interfaces with the 16-byte `struct mt6797_ccci_header` UAPI ([mt6797_ccci.h](file:///home/lux/proj/geminux/prebuilt/kernel/include/linux/mt6797_ccci.h)). @@ -14,29 +14,31 @@ Geminux combines a custom-patched Linux `7.3.5` kernel, pure-Linux MTK flasher, - **XLibre (`25.x`)**: Cross-compiled against pure Alpine Edge `aarch64` sysroots with Panfrost Glamor EGL (`libglamoregl.so`), `modesetting_drv.so`, `fbdev_drv.so`, and `libinput_drv.so` ([scripts/build-xlibre.sh](file:///home/lux/proj/geminux/scripts/build-xlibre.sh)). Zero Wayland compositors (`sway`, `weston`, `phosh`, `xwayland`, etc.) are installed. - **Patched suckless desktop**: - - `st` with HarfBuzz font shaping (`hb.c`) supporting Fira Code programming ligatures, Nerd Font fallback, mouse/two-finger wheel scrollback, and `SIGUSR1` live `.Xresources` reload. + - `st` with HarfBuzz font shaping (`hb.c`) supporting Fira Code programming ligatures, Nerd Font fallback, mouse/two-finger wheel scrollback, immediate cursor redraw on `FocusIn`/`FocusOut` (paired with `dwm` `FocusChangeMask`/`NotifyWhileGrabbed` guards and `libgemui` focus restore across grabs), and `SIGUSR1` live `.Xresources` reload. - `dwm` with Pango/HarfBuzz multi-font bar (`drw.c`), EWMH/XEmbed system tray, touch-friendly `>= 68px` status bar, `Mod4 = Fn+Alt` + one-shot `Super_L` tap-latch, and `SIGUSR1` `.Xresources` reload. - - `dmenu` with Pango/HarfBuzz, dynamic full-screen-height item rows (`68px` touch rows), and mouse/touch click selection, paired with `geminux-launcher` pinning the 11 GUI apps alongside `Bantam AI agent` and `Lynx Web Browser` in `st` (and wrapping `Terminal=true` `.desktop` entries in `st -e`). + - `dmenu` with Pango/HarfBuzz, dynamic full-screen-height item rows (`68px` touch rows), and mouse/touch click selection, paired with `geminux-launcher` pinning the 11 GUI apps alongside `Webarchy Browser`, `Bantam AI agent`, and `Lynx Web Browser` in `st` (and wrapping `Terminal=true` `.desktop` entries in `st -e`). - **Zero-Rust notifications**: `dunst v1.12.2` compiled with `WAYLAND=0 DUNSTIFY=0` and custom pure-C PNG (`libpng` + Cairo) / JPEG (`libjpeg-turbo`) icon loader replacing `gdk-pixbuf` ([src/dunst-notify/](file:///home/lux/proj/geminux/src/dunst-notify/)), paired with a lightweight GDBus `notify-send` / `dunstify`. +- **Webarchy & pure-C `gdk-pixbuf`**: [src/webarchy/webarchy.cpp](file:///home/lux/proj/geminux/src/webarchy/webarchy.cpp) provides a standalone C++20 `GTK3` + `WebKit2GTK-4.1` multi-tab browser adapted for the `2160x1080` ultrawide display (`1080x506` logical @ `GDK_SCALE=2`) with a collapsible flush-right vertical tab bar, DPI-scaled `pt` CSS reloaded live from `~/.Xresources` via `SIGUSR1`, persistent SQLite cookies/bookmarks under `~/.local/share/geminux/webarchy` and `~/.config/geminux/webarchy`, single-instance FIFO URL forwarding, and automatic CPU renderer fallback on WebProcess crash. [scripts/build-webarchy.sh](file:///home/lux/proj/geminux/scripts/build-webarchy.sh) also cross-compiles pure-C GNOME `gdk-pixbuf 2.42.12` (`-Dbuiltin_loaders=all`, zero `libglycin`/`librsvg`) so `gtk+3.0` and `gst-plugins-good` install cleanly without Rust, and [scripts/compile-gsettings-schemas.sh](file:///home/lux/proj/geminux/scripts/compile-gsettings-schemas.sh) compiles `/usr/share/glib-2.0/schemas/gschemas.compiled` for `WebKitNetworkProcess`. +- **Zero-Rust media & `yt-dlp` stack**: [scripts/build-mpv.sh](file:///home/lux/proj/geminux/scripts/build-mpv.sh) cross-compiles `libplacebo v7.360.1` (`-Ddovi=disabled`), `FFmpeg n7.1.5` (private `/usr/lib/geminux-mpv` `RUNPATH`, zero `librav1e`), `mpv v0.40.0` (Panfrost X11 EGL + PipeWire/Pulse/ALSA), and `gst-libav 1.28.9` (`libgstlibav.so` linked against private `geminux-mpv` libs for WebKit HTML5 media), paired with `mpg123`, `python3`/`py3-pip`, and `yt-dlp-core` + `yt-dlp-ejs-rt-quickjs` (`quickjs`, avoiding `deno`/`py3-cryptography`). ## Custom UI toolkit and zero-poll C11 daemons - **`libgemui.so`** ([src/libgemui/](file:///home/lux/proj/geminux/src/libgemui)): Double-buffered Cairo + Pango/HarfBuzz Xlib toolkit polling X11 events, `SIGUSR1` self-pipe for instant `.Xresources` reloads, dynamic timers, `MSG_NOSIGNAL`/drained Unix socket IPC (`gemui_unix_cmd`), and non-blocking extra FDs (such as V4L2 or `inotify`). -- **11 landscape HiDPI applications** ([src/geminux-apps/](file:///home/lux/proj/geminux/src/geminux-apps)): `geminux-control`, `geminux-audio`, `geminux-datetime`, `geminux-net`, `geminux-dialer`, `geminux-callscreen`, `geminux-sms`, `geminux-contacts`, `geminux-camera` (MT6797 Media Controller pipeline + 10-bit Bayer demosaic/AWB software ISP), `geminux-themes`, and `geminux-lock`. +- **11 landscape HiDPI applications** ([src/geminux-apps/](file:///home/lux/proj/geminux/src/geminux-apps)): `geminux-control`, `geminux-audio`, `geminux-datetime`, `geminux-net` (5 tabs including active WLAN persistence and `DNS` configuration), `geminux-dialer`, `geminux-callscreen`, `geminux-sms`, `geminux-contacts`, `geminux-camera` (MT6797 Media Controller pipeline + 10-bit Bayer demosaic/AWB software ISP), `geminux-themes`, and `geminux-lock`. - **Zero-poll C11 daemons** ([src/geminux-daemons/](file:///home/lux/proj/geminux/src/geminux-daemons)): - `geminux-powerd` — `epoll` over `/dev/input/event*` (`SW_LID`, `KEY_POWER`, keyboard/touch/pointer activity), `KOBJECT_UEVENT`, `/run/geminux/powerd.sock`, and `timerfd`; drives two-stage screensaver idle dim/lock/suspend timed from the last active user input and resolves the active desktop user dynamically from UID `10000`. - `geminux-statusd` — `epoll` over `signalfd` (`SIGUSR1`), `RTMGRP_LINK`/`RTMGRP_IPV4_IFADDR`, `KOBJECT_UEVENT`, `inotify`, and minute-aligned `timerfd`; updates root `WM_NAME` with zero child shell forks. - `geminux-touchd` — XInput 2.2 multi-touch gesture daemon (2-finger tap/hold right-click, 3-finger middle-click, 2-finger scroll). - `geminux-leds` — AW9120 back cover RGB controller driving `rgb:indicator-1..5` (default off when idle/full; `rgb:indicator-6` amber while charging; persistent manual override; `SIGPIPE`-safe socket server at `/run/geminux/leds.sock`). - `geminux-ccci-daemon` — `epoll` over `/dev/ccci_*`, uevents, and `/run/geminux/ccci.sock`; idles cleanly if MD firmware is absent. - - `geminux-modem-ctl`, `geminux-bt-obex` (GLib `GMainLoop`/GDBus), `geminux-power-ctl`, `geminux-power-audit`, `geminux-tzctl`, `geminux-wifi-nvram`, and `geminux-checkpw`. + - `geminux-modem-ctl`, `geminux-bt-obex` (GLib `GMainLoop`/GDBus), `geminux-dnsctl`, `geminux-power-ctl`, `geminux-power-audit`, `geminux-tzctl`, `geminux-wifi-nvram`, and `geminux-checkpw`. ## APK package pinning and zero-Rust enforcement To keep Alpine Edge `aarch64` userspace freely updatable while locking all hardware-tuned components: 1. Build-time host Docker containers use `postmarketos/v26.06` solely for `gcc-aarch64`, `binutils-aarch64`, and `mkbootimg-osm0sis`. All `$SYSROOT` trees and the target `$ROOTFS` use only pure **Alpine Edge** (`main`, `community`, `testing`) plus the RSA-4096 signed local `@geminux` repository (`/var/lib/geminux/apk-repo`). -2. [scripts/package-local-apks.sh](file:///home/lux/proj/geminux/scripts/package-local-apks.sh) builds eight `.apk` packages via `apk mkpkg` and indexes them into `APKINDEX.tar.gz` via `apk mkndx`: +2. [scripts/package-local-apks.sh](file:///home/lux/proj/geminux/scripts/package-local-apks.sh) builds eleven `.apk` packages via `apk mkpkg` and indexes them into `APKINDEX.tar.gz` via `apk mkndx`: - `geminux-kernel-modules` - `geminux-xlibre` - `geminux-suckless` @@ -44,8 +46,11 @@ To keep Alpine Edge `aarch64` userspace freely updatable while locking all hardw - `geminux-ui` - `geminux-bantam` (`bantam` minimalist C++20 CLI AI agent with `kilo-auto/free` default model, built via [scripts/build-bantam.sh](file:///home/lux/proj/geminux/scripts/build-bantam.sh)) - `geminux-gsocket` (`gs-netcat` / `gsocket` NAT traversal toolkit built via [scripts/build-gsocket.sh](file:///home/lux/proj/geminux/scripts/build-gsocket.sh)) - - `geminux-config` (includes `/etc/htoprc`, `/etc/skel/.config/htop/htoprc`, `/etc/skel/.lynx.cfg`, `/etc/skel/.apexrc`) -3. `/etc/apk/world` pins all eight with `name@geminux=version` and locks out Rust/Wayland/upstream overrides via `!` constraints from [scripts/rootfs-prune-packages.txt](file:///home/lux/proj/geminux/scripts/rootfs-prune-packages.txt). + - `geminux-mpv` (`mpv v0.40.0`, `ffmpeg`, `ffprobe`, private `libplacebo`/FFmpeg shared libs, and `libgstlibav.so` built via [scripts/build-mpv.sh](file:///home/lux/proj/geminux/scripts/build-mpv.sh)) + - `geminux-gdk-pixbuf` (pure-C zero-glycin `gdk-pixbuf 2.42.12` built via [scripts/build-webarchy.sh](file:///home/lux/proj/geminux/scripts/build-webarchy.sh)) + - `geminux-webarchy` (`webarchy` / `xwebarchy` browser built via [scripts/build-webarchy.sh](file:///home/lux/proj/geminux/scripts/build-webarchy.sh)) + - `geminux-config` (includes `/etc/htoprc`, `/etc/skel/.config/htop/htoprc`, `/etc/skel/.lynx.cfg`, `/etc/skel/.apexrc`, `/etc/skel/.bashrc` with `GPG_TTY`) +3. `/etc/apk/world` pins all eleven with `name@geminux=version` and locks out Rust/Wayland/upstream overrides via `!` constraints from [scripts/rootfs-prune-packages.txt](file:///home/lux/proj/geminux/scripts/rootfs-prune-packages.txt). Verified automatically by an ELF binary Rust scan, `apk upgrade --simulate`, and 7 host Python unit suites in [scripts/check-rebuild.sh](file:///home/lux/proj/geminux/scripts/check-rebuild.sh). 4. `/etc/apk/protected_paths.d/geminux.list` shields Geminux configuration directories across upgrades. ## Pure-Linux flasher and eMMC layout diff --git a/MANUAL.md b/MANUAL.md index 0d49a91..dbf9f22 100644 --- a/MANUAL.md +++ b/MANUAL.md @@ -17,7 +17,7 @@ In [src/dwm/config.h](file:///home/lux/proj/geminux/src/dwm/config.h), `MODKEY` | --- | --- | | `Mod4 + Return` | Launch `st` terminal (with Fira Code HarfBuzz ligatures) | | `Mod4 + Shift + Return` | Promote focused window to master (`zoom`) | -| `Mod4 + Space` / `Mod4 + p` | Launch `geminux-launcher` (`dmenu` with Nerd Font icons, pinned GUI apps, `Bantam AI agent`, and `Lynx Web Browser` in `st`) | +| `Mod4 + Space` / `Mod4 + p` | Launch `geminux-launcher` (`dmenu` with Nerd Font icons, pinned GUI apps, `Webarchy Browser`, `Bantam AI agent`, and `Lynx Web Browser` in `st`) | | `Mod4 + c` | Open `geminux-control` (backlight, volume, power profiles, LEDs, suspend) | | `Mod4 + d` | Open `geminux-dialer` | | `Mod4 + s` | Open `geminux-sms` | @@ -53,16 +53,17 @@ geminux-apply-theme # list available themes geminux-apply-theme TokyoNight ``` -`geminux-apply-theme` updates `~/.Xresources`, merges into the X11 resource database via `xrdb`, translates the unified `theme.*` keys into `~/.config/dunst/dunstrc` via `geminux-sync-dunst-theme`, restarts `dunst`, and sends `SIGUSR1` to live `dwm`, `st`, and `libgemui` applications for instant in-place redraw. +`geminux-apply-theme` updates `~/.Xresources`, merges into the X11 resource database via `xrdb`, translates the unified `theme.*` keys into `~/.config/dunst/dunstrc` via `geminux-sync-dunst-theme`, restarts `dunst`, and sends `SIGUSR1` to live `dwm`, `st`, `webarchy`, and `libgemui` applications for instant in-place redraw. ## Applications and daemons +- **Webarchy Browser (`webarchy` / `xwebarchy`)**: Ultrawide `2160x1080` `GTK3` + `WebKit2GTK` browser featuring a collapsible right-side vertical tab bar (`Tabs ◫` or `Ctrl+B` / `Alt+T`), omnibar URL/DuckDuckGo search, persistent SQLite cookies and bookmarks (`~/.config/geminux/webarchy/` and `~/.local/share/geminux/webarchy/`), User-Agent presets, Dark Mode inverter (`Ctrl+Shift+D`), Reader Width Fit, Find in Page (`Ctrl+F`), single-instance URL forwarding via CLI, live `.Xresources` reloading (`SIGUSR1`), and automatic CPU renderer fallback on WebProcess crash (`--software` or `~/.config/geminux/webarchy/software_renderer`). Shortcuts: `Ctrl+T` new tab, `Ctrl+W` close tab, `Ctrl+Shift+T` reopen closed tab, `Ctrl+Tab` / `Alt+Up`/`Down` / `Alt+1..9` switch vertical tabs, `Ctrl+L` / `F6` focus URL bar, `Alt+Left` / `Alt+Right` back/forward, `Ctrl+D` bookmark, `Ctrl++` / `-` / `0` zoom, and `F11` fullscreen. - **Telephony & messaging**: `geminux-dialer`, `geminux-callscreen`, `geminux-sms`, `geminux-contacts` backed by `geminux-modem-ctl` and `geminux-ccci-daemon` (using `alsaucm` UCM2 `VoiceCall` / `HiFi` switching and call suspend inhibitors). - **Audio & date/time**: `geminux-audio` manages PipeWire sink/source routing, mute state, and per-stream volume via `wpctl`/`pactl`. `geminux-datetime` manages the system timezone (`geminux-tzctl`) and shows live Chrony NTP sync status. -- **Connectivity**: `geminux-net` manages Wi-Fi (`nmcli`), 4G/CCCI state (`mmcli` + `/run/geminux/ccci.sock`), Bluetooth (`bluetoothctl` / `rfkill`), and SiI9024 external HDMI output (`xrandr`). +- **Connectivity**: `geminux-net` manages Wi-Fi (`nmcli`, keeping the currently associated WLAN connection pinned at the top with a `Disconnect` control), 4G/CCCI state (`mmcli` + `/run/geminux/ccci.sock`), Bluetooth (`bluetoothctl` / `rfkill`), SiI9024 external HDMI output (`xrandr`), and the **`DNS` tab** (`geminux-dnsctl`, supporting router-provided Default DNS, Cloudflare, Google, RadicalDNS, Quad9, custom IPv4/IPv6 nameservers, and live DNS lookup testing). - **Camera**: `geminux-camera` configures the MT6797 Media Controller pipeline (`ov5670`/`s5k4e6` -> `seninf` -> `camsv`), captures 10-bit Bayer (`SBGGR10`/`SGRBG10`) frames over V4L2 `mmap` with a pure-C demosaic + AWB software ISP, and writes native `libjpeg-turbo` stills to `~/Pictures/` and MJPEG-AVI clips to `~/Videos/`. - **System control, LEDs & lock**: `geminux-control` adjusts display backlight, PipeWire audio volume, MT6797X power profile (`eco`, `balanced`, `performance`), and AW9120 LEDs (`/run/geminux/leds.sock`). `geminux-leds` drives the 5-LED RGB back strip (`rgb:indicator-1..5`, defaulting to off when idle or 100% charged) plus `rgb:indicator-6` (amber while charging), supports calibrated presets including `rgb 160 16 0` ("Amber Warn"), and preserves manual `off` / `rgb` overrides across battery uevents. `geminux-lock` secures the X session using `doas -n /usr/sbin/geminux-checkpw`, resolving the desktop account dynamically from UID `10000` (`--username` or default `user`). `geminux-powerd` implements an input-driven screensaver: on battery it dims then triggers `geminux-lock` + suspend, while on AC / `performance` it triggers `geminux-lock` + backlight blanking (waking back onto the lock screen on key, touch, pointer, or power-button activity), timed strictly from the last active user input. -- **CLI developer & network tools**: `bantam` (`geminux-bantam`, minimalist C++20 OpenAI-compatible terminal AI agent defaulting to `kilo-auto/free`; see [src/bantam/README.md](file:///home/lux/proj/geminux/src/bantam/README.md)), `lynx` (configured via `~/.lynx.cfg` with `http://frogfind.com` start page, UTF-8, vi keys, mouse support, and persistent sessions/cookies), `gsocket` (`gs-netcat` plus `gs-key`/`gs-enter`/`gs-deploy-cmd`), `dtach` (`dmux`), `ovault`, default `htop` layout (`/etc/htoprc` / `~/.config/htop/htoprc`), `/etc/skel/.apexrc` defaults (`EDITOR='nano -FEDSMAGic/max%_T2'`, `PAGER='less -RXF'`, `nn`, `pg`, `l`, `defalias`/`toalias`/`savealias`, `rw`/`ee`, `sshed`, `dl`, `gcm`/`gp`/`gpm`, `sloc`, and `doas`-aware `pkgadd`/`pkgdel`/`pkgsearch`/`sysup`/`sysclean`), and `/etc/skel/.gitconfig` are preinstalled. +- **CLI developer, media & security tools**: Zero-Rust `mpv` (`/etc/mpv/mpv.conf` with Panfrost X11 EGL + PipeWire) & `ffmpeg`/`ffprobe`, `mpg123`, `yt-dlp` (`yt-dlp-ejs-rt-quickjs`), `python3` & `pip3` (`py3-pip`), `gpg` (`gnupg` + `pinentry-curses` + `GPG_TTY`), `pass`, `bantam` (`geminux-bantam`, minimalist C++20 OpenAI-compatible terminal AI agent defaulting to `kilo-auto/free`; see [src/bantam/README.md](file:///home/lux/proj/geminux/src/bantam/README.md)), `lynx` (configured via `~/.lynx.cfg` with `http://frogfind.com` start page, UTF-8, vi keys, mouse support, and persistent sessions/cookies), `gsocket` (`gs-netcat` plus `gs-key`/`gs-enter`/`gs-deploy-cmd`), `dtach` (`dmux`), `ovault`, default `htop` layout (`/etc/htoprc` / `~/.config/htop/htoprc`), `/etc/skel/.apexrc` defaults (`EDITOR='nano -FEDSMAGic/max%_T2'`, `PAGER='less -RXF'`, `nn`, `pg`, `l`, `defalias`/`toalias`/`savealias`, `rw`/`ee`, `sshed`, `dl`, `gcm`/`gp`/`gpm`, `sloc`, and `doas`-aware `pkgadd`/`pkgdel`/`pkgsearch`/`sysup`/`sysclean`), and `/etc/skel/.gitconfig` are preinstalled. ## Maintaining Alpine Edge packages safely @@ -73,4 +74,4 @@ doas apk update doas apk upgrade ``` -Because custom Geminux components (`geminux-kernel-modules`, `geminux-xlibre`, `geminux-suckless`, `geminux-dunst`, `geminux-ui`, `geminux-bantam`, `geminux-gsocket`, `geminux-config`) are exact-version pinned (`name@geminux=version`) in `/etc/apk/world` and Rust/upstream overrides (`!rust`, `!cargo`, `!librsvg`, `!libglycin`, `!gdk-pixbuf`, `!xorg-server`, `!linux-edge`, etc.) are negated in `/etc/apk/world`, normal Alpine Edge upgrades update upstream libraries, CLI tools, NetworkManager, ModemManager, PipeWire, and Mesa without overwriting custom patched binaries or pulling Rust packages. +Because custom Geminux components (`geminux-kernel-modules`, `geminux-xlibre`, `geminux-suckless`, `geminux-dunst`, `geminux-ui`, `geminux-bantam`, `geminux-gsocket`, `geminux-mpv`, `geminux-gdk-pixbuf`, `geminux-webarchy`, `geminux-config`) are exact-version pinned (`name@geminux=version`) in `/etc/apk/world` and Rust/Wayland/upstream overrides (`!rust`, `!cargo`, `!librsvg`, `!libglycin`, `!gdk-pixbuf`, `!deno`, `!py3-cryptography`, `!xorg-server`, `!linux-edge`, etc.) are negated in `/etc/apk/world`, normal Alpine Edge upgrades update upstream libraries, CLI tools, NetworkManager, ModemManager, PipeWire, and Mesa without overwriting custom patched binaries or pulling Rust packages. diff --git a/POWER-OPTIMIZATION.md b/POWER-OPTIMIZATION.md index 1db7649..1f88724 100644 --- a/POWER-OPTIMIZATION.md +++ b/POWER-OPTIMIZATION.md @@ -41,7 +41,7 @@ Closing the Gemini PDA clamshell (`SW_LID = 1`) suspends immediately to RAM (`me - **Audio**: PipeWire uses `default.clock.min-quantum = 1024` and `quantum = 2048` (`10-geminux-power.conf`); WirePlumber suspends idle ALSA and BlueZ nodes after `3` seconds (`50-geminux-suspend.conf`) so audio DSP clocks gate quickly. - **Bluetooth**: `bluetooth` OpenRC service is disabled from default boot (`AutoEnable=false` in `etc/bluetooth/main.conf`); users toggle Bluetooth on demand via `geminux-net`. -- **Wi-Fi**: NetworkManager enforces `wifi.powersave = 3` (`10-geminux-power.conf`). +- **Wi-Fi**: NetworkManager configures `wifi.powersave = 2` (`10-geminux-power.conf`) to keep CONSYS Wi-Fi awake while associated so GTK rekeys, ARP, and DNS never stall; the radio still powers down cleanly on Wi-Fi toggle-off or system S3 suspend. - **Storage**: `noatime,commit=60` in `etc/fstab` alongside `vm.dirty_writeback_centisecs=1500` reduces eMMC write amplification and wakes. ## Auditing on device diff --git a/README.md b/README.md index 4d44ec9..26dc20b 100644 --- a/README.md +++ b/README.md @@ -1,42 +1,44 @@ # Geminux -Geminux is an Alpine Linux (`aarch64`, musl, OpenRC) distribution built specifically for the Planet Computers Gemini PDA (Wi-Fi + 4G, MediaTek MT6797X / Helio X27). It runs a patched Linux `7.3.5-geminux` kernel, XLibre Xorg with Panfrost Glamor 3D acceleration, a custom Pango/HarfBuzz-enabled DWM/st/dmenu desktop with Fira Code ligatures and Noto fonts, zero-poll C11 system daemons, 11 landscape HiDPI applications (`libgemui.so`), the preinstalled `bantam` CLI AI agent (`geminux-bantam`, `kilo-auto/free` default), `lynx`, `gsocket`, and a pure-Linux MediaTek flasher with account provisioning and optional LUKS2 full-disk encryption. +Geminux is an Alpine Linux (`aarch64`, musl, OpenRC) distribution built specifically for the Planet Computers Gemini PDA (Wi-Fi + 4G, MediaTek MT6797X / Helio X27). It runs a patched Linux `7.3.5-geminux` kernel, XLibre Xorg with Panfrost Glamor 3D acceleration, a custom Pango/HarfBuzz-enabled DWM/st/dmenu desktop with Fira Code ligatures and Noto fonts, zero-poll C11 system daemons, 11 landscape HiDPI applications (`libgemui.so`), the ported Webarchy ultrawide `GTK3`/`WebKit2GTK` browser (`geminux-webarchy`, right-side vertical tab bar), zero-Rust `mpv` + `ffmpeg` (`geminux-mpv`), `mpg123`, `yt-dlp`, `python3`/`pip`, `gpg` (`gnupg`), `pass`, the preinstalled `bantam` CLI AI agent (`geminux-bantam`, `kilo-auto/free` default), `lynx`, `gsocket`, and a pure-Linux MediaTek flasher with account provisioning and optional LUKS2 full-disk encryption. ## Key design goals - Pure Alpine Edge userspace updatable via `apk update && apk upgrade` -- Pinned kernel, modules, XLibre, suckless desktop, custom UI, `bantam`, `gsocket`, and device configs in local signed `@geminux` APK packages (`name@geminux=version`) +- Pinned kernel, modules, XLibre, suckless desktop, custom UI, Webarchy browser, pure-C `gdk-pixbuf`, `mpv`/`ffmpeg`, `bantam`, `gsocket`, and device configs across 11 local signed `@geminux` APK packages (`name@geminux=version`) - Zero Rust-dependent packages preinstalled (verified across installed ELF binaries and blocked via `!` pins in `/etc/apk/world`) - Full eMMC occupancy for Linux (`geminux-root`) without Android dual-boot sharing, while strictly preserving the MediaTek protected region (`LBA 0..0x6FFFF`) - Optional LUKS2 + `dm-crypt` full-disk encryption (`--encrypt`, `aes-xts-plain64` with ARMv8 AES-CE, Argon2id) with early-boot `simpledrm` + Gemini matrix keyboard unlock and automatic first-boot ext4 expansion, alongside offline desktop/`root` credential provisioning during flashing -- Aggressive battery optimization from kernel (`HZ_100`, `RCU_LAZY`, `SUSPEND`, LZ4 `zram`, `SCHEDUTIL`) up to userspace (`epoll`-based zero-poll daemons, A72 big-cluster gating, WirePlumber idle suspend, Wi-Fi `powersave = 3`, Bluetooth disabled at boot, default-off cover LEDs, lid-close S3 suspend) +- Aggressive battery optimization from kernel (`HZ_100`, `RCU_LAZY`, `SUSPEND`, LZ4 `zram`, `SCHEDUTIL`) up to userspace (`epoll`-based zero-poll daemons, A72 big-cluster gating, WirePlumber idle suspend, Wi-Fi `powersave = 2` keeping CONSYS awake while associated and gated on toggle-off/suspend, Bluetooth disabled at boot, default-off cover LEDs, lid-close S3 suspend) ## Component stack | Subsystem | Implementation | Source / Script | | --- | --- | --- | -| Kernel & boot | Linux `7.3.5-geminux` + Gemini x27 patches (`SSD2092` DSI/touch, CONSYS Wi-Fi/BT, CCCI/CLDMA, `sii902x`, `dm-crypt` LUKS2 initramfs) | [scripts/build-kernel.sh](file:///home/lux/proj/geminux/scripts/build-kernel.sh) | +| Kernel & boot | Linux `7.3.5-geminux` + Gemini x27 patches (`SSD2092` DSI/touch, CONSYS Wi-Fi/BT + peer deauth/GTK rekey fix, CCCI/CLDMA, `sii902x`, `dm-crypt` LUKS2 initramfs) | [scripts/build-kernel.sh](file:///home/lux/proj/geminux/scripts/build-kernel.sh) | | Flasher & GPT | Vendored GPLv3 `mtkclient` + MT6797 DA + GPT builder + offline credential & LUKS2 provisioning | [flash-mtk.sh](file:///home/lux/proj/geminux/flash-mtk.sh), [flash-mtk.py](file:///home/lux/proj/geminux/flash-mtk.py), [scripts/geminux_accounts.py](file:///home/lux/proj/geminux/scripts/geminux_accounts.py), [scripts/geminux_luks.py](file:///home/lux/proj/geminux/scripts/geminux_luks.py) | | Display server | XLibre Xorg 25.x (`Glamor`, `modesetting`, `fbdev`, `libinput`) | [scripts/build-xlibre.sh](file:///home/lux/proj/geminux/scripts/build-xlibre.sh) | -| Window manager & terminal | Patched `dwm` (Pango, systray, `.Xresources`, `Mod4`), `st` (HarfBuzz ligatures, wheel scrollback), full-height `dmenu` | [scripts/build-suckless.sh](file:///home/lux/proj/geminux/scripts/build-suckless.sh) | +| Window manager & terminal | Patched `dwm` (Pango, systray, `.Xresources`, `Mod4`), `st` (HarfBuzz ligatures, focus cursor sync, wheel scrollback), full-height `dmenu` | [scripts/build-suckless.sh](file:///home/lux/proj/geminux/scripts/build-suckless.sh) | | Notifications | Pure-X11 zero-`gdk-pixbuf` `dunst v1.12.2` + custom GDBus `notify-send` / `dunstify` | [scripts/build-dunst.sh](file:///home/lux/proj/geminux/scripts/build-dunst.sh) | -| UI, daemons & CLI tools | `libgemui.so`, 11 landscape HiDPI apps, zero-poll C11 daemons, `bantam` CLI AI agent, `lynx`, `gsocket`, `.apexrc`, default `htoprc` | [scripts/build-geminux-ui.sh](file:///home/lux/proj/geminux/scripts/build-geminux-ui.sh), [scripts/build-bantam.sh](file:///home/lux/proj/geminux/scripts/build-bantam.sh), [scripts/build-gsocket.sh](file:///home/lux/proj/geminux/scripts/build-gsocket.sh) | -| Local APK repository | 8 signed `@geminux` `.apk` packages + `APKINDEX.tar.gz` | [scripts/package-local-apks.sh](file:///home/lux/proj/geminux/scripts/package-local-apks.sh) | +| Web browser | Webarchy C++20 `GTK3` + `WebKit2GTK-4.1` ultrawide browser (right-side vertical tab bar, DPI-scaled `.Xresources` `SIGUSR1` theming) + pure-C `gdk-pixbuf 2.42.12` | [scripts/build-webarchy.sh](file:///home/lux/proj/geminux/scripts/build-webarchy.sh), [scripts/compile-gsettings-schemas.sh](file:///home/lux/proj/geminux/scripts/compile-gsettings-schemas.sh) | +| UI & system daemons | `libgemui.so`, 11 landscape HiDPI apps (`geminux-net` DNS tab + active WLAN persistence), zero-poll C11 daemons (`geminux-dnsctl`, etc.) | [scripts/build-geminux-ui.sh](file:///home/lux/proj/geminux/scripts/build-geminux-ui.sh) | +| Media & CLI tools | Zero-Rust `mpv v0.40.0` (Panfrost X11 EGL + PipeWire), `ffmpeg`/`ffprobe`, `libgstlibav.so`, `mpg123`, `yt-dlp` (`quickjs`), `python3`/`pip3`, `gpg` (`gnupg`), `pass`, `bantam`, `lynx`, `gsocket`, `.apexrc`, default `htoprc` | [scripts/build-mpv.sh](file:///home/lux/proj/geminux/scripts/build-mpv.sh), [scripts/build-bantam.sh](file:///home/lux/proj/geminux/scripts/build-bantam.sh), [scripts/build-gsocket.sh](file:///home/lux/proj/geminux/scripts/build-gsocket.sh) | +| Local APK repository | 11 signed `@geminux` `.apk` packages + `APKINDEX.tar.gz` | [scripts/package-local-apks.sh](file:///home/lux/proj/geminux/scripts/package-local-apks.sh) | | Full build & checks | Full image assembly + offline verification suite | [rebuild-image.sh](file:///home/lux/proj/geminux/rebuild-image.sh), [scripts/check-rebuild.sh](file:///home/lux/proj/geminux/scripts/check-rebuild.sh) | ## Repository layout - [kernel/](file:///home/lux/proj/geminux/kernel) and [patches/kernel/](file:///home/lux/proj/geminux/patches/kernel) — kernel manifest, MT6797X configuration, and Linux `7.3.5` patch queue -- [src/](file:///home/lux/proj/geminux/src) — initramfs scripts, `st`, `dwm`, `dmenu`, `dunst-notify`, `bantam`, `libgemui`, `geminux-apps`, and `geminux-daemons` +- [src/](file:///home/lux/proj/geminux/src) — initramfs scripts, `st`, `dwm`, `dmenu`, `dunst-notify`, `bantam`, `webarchy`, `libgemui`, `geminux-apps`, and `geminux-daemons` - [overlay/rootfs/](file:///home/lux/proj/geminux/overlay/rootfs) — OpenRC services, ALSA UCM2, XKB layout, console keymap, Xorg drop-ins, 21 `.xth` themes, PipeWire/WirePlumber, udev, and NetworkManager configs - [scripts/](file:///home/lux/proj/geminux/scripts) — cross-compilation builders, APK packager, rootfs bootstrapper, verification suite, and unit tests - [prebuilt/](file:///home/lux/proj/geminux/prebuilt) — cross-compiled `aarch64` staging tree (`images/` holds built boot, recovery, and ext4 rootfs images) ## Verification status vs. on-device testing -All cross-compiled binaries, kernel/DTB artifacts, GPT repartitioning logic, offline credential/LUKS2 builders, XKB keymap compilation, `.Xresources`-to-`dunstrc` theme syncing, MT6797 CCCI framing/handshake unit tests, zero-poll power policy tests, ELF binary Rust scan, and `apk upgrade --simulate` checks are verified automatically via [scripts/check-rebuild.sh](file:///home/lux/proj/geminux/scripts/check-rebuild.sh). +All cross-compiled binaries, kernel/DTB artifacts, GPT repartitioning logic, offline credential/LUKS2 builders, XKB keymap compilation, `.Xresources`-to-`dunstrc` theme syncing, MT6797 CCCI framing/handshake unit tests, zero-poll power policy tests, Webarchy renderer profile & WebKit GSettings schema tests, ELF binary Rust scan, and `apk upgrade --simulate` checks are verified automatically via [scripts/check-rebuild.sh](file:///home/lux/proj/geminux/scripts/check-rebuild.sh). -Live hardware bring-up on a physical Planet Computers Gemini PDA (x27 Wi-Fi + 4G) has been verified for USB BROM/DA flashing, offline account provisioning, LUKS2 full-disk encryption unlock & first-boot ext4 resize, `SSD2092` FHD+ display & multi-touch gestures (`geminux-touchd`), CONSYS Wi-Fi/BT, PipeWire audio, Media Controller + 10-bit Bayer camera ISP, AW9120 RGB back LEDs, Chrony online time sync, and USB NCM networking. Accessory/carrier-dependent checks (such as live cellular calls/SMS with a SIM card and external Slimport/HDMI monitors) are documented in the hardware checklist in [INSTALL.md](file:///home/lux/proj/geminux/INSTALL.md). +Live hardware bring-up on a physical Planet Computers Gemini PDA (x27 Wi-Fi + 4G) has been verified for USB BROM/DA flashing, offline account provisioning, LUKS2 full-disk encryption unlock & first-boot ext4 resize, `SSD2092` FHD+ display & multi-touch gestures (`geminux-touchd`), CONSYS Wi-Fi/BT (`geminux-net` DNS tab & associated WLAN persistence), Webarchy ultrawide Panfrost GPU rendering, PipeWire audio, Media Controller + 10-bit Bayer camera ISP, AW9120 RGB back LEDs, Chrony online time sync, and USB NCM networking. Accessory/carrier-dependent checks (such as live cellular calls/SMS with a SIM card and external Slimport/HDMI monitors) are documented in the hardware checklist in [INSTALL.md](file:///home/lux/proj/geminux/INSTALL.md). ## Quick start (host build and checks) @@ -45,7 +47,7 @@ Live hardware bring-up on a physical Planet Computers Gemini PDA (x27 Wi-Fi + 4G ./scripts/check-rebuild.sh ``` -To rebuild all cross-compiled components from scratch (kernel, XLibre, suckless desktop, dunst, UI apps/daemons, Bantam, gsocket, signed `@geminux` APKs, and rootfs ext4): +To rebuild all cross-compiled components from scratch (kernel, XLibre, suckless desktop, dunst, UI apps/daemons, Bantam, gsocket, mpv/FFmpeg/`gst-libav`, pure-C `gdk-pixbuf`/Webarchy, signed `@geminux` APKs, and rootfs ext4): ```sh ./rebuild-image.sh --rebuild-all --force-bootstrap diff --git a/overlay/rootfs/etc/NetworkManager/conf.d/10-geminux-power.conf b/overlay/rootfs/etc/NetworkManager/conf.d/10-geminux-power.conf index 648e775..400399f 100644 --- a/overlay/rootfs/etc/NetworkManager/conf.d/10-geminux-power.conf +++ b/overlay/rootfs/etc/NetworkManager/conf.d/10-geminux-power.conf @@ -1,6 +1,7 @@ [connection] -# Enable aggressive IEEE 802.11 power save for Wi-Fi radio standby savings. -wifi.powersave = 3 +# Keep Wi-Fi awake while associated so CONSYS GTK rekeys, ARP, and DNS never stall; +# radio still powers down on toggle-off or system suspend. +wifi.powersave = 2 [keyfile] # Allow geminux-usb-gadget init script to manage usb0 (172.16.42.1/24) cleanly. diff --git a/overlay/rootfs/etc/doas.d/10-geminux.conf b/overlay/rootfs/etc/doas.d/10-geminux.conf index 745f1c3..55d2422 100644 --- a/overlay/rootfs/etc/doas.d/10-geminux.conf +++ b/overlay/rootfs/etc/doas.d/10-geminux.conf @@ -2,5 +2,6 @@ permit persist :wheel permit nopass :wheel as root cmd /usr/bin/geminux-power-ctl permit nopass :wheel as root cmd /usr/sbin/geminux-checkpw permit nopass :wheel as root cmd /usr/sbin/geminux-tzctl +permit nopass :wheel as root cmd /usr/sbin/geminux-dnsctl permit nopass :wheel as root cmd /sbin/poweroff permit nopass :wheel as root cmd /sbin/reboot diff --git a/overlay/rootfs/etc/skel/.bashrc b/overlay/rootfs/etc/skel/.bashrc index 42f3282..d744b50 100644 --- a/overlay/rootfs/etc/skel/.bashrc +++ b/overlay/rootfs/etc/skel/.bashrc @@ -4,6 +4,7 @@ if [ -r /etc/profile.d/10-geminux-env.sh ]; then fi export LANG="${LANG:-en_US.UTF-8}" export LC_ALL="${LC_ALL:-en_US.UTF-8}" +[ -t 0 ] && export GPG_TTY="$(tty)" PS1='[\u@\h \W]\$ ' alias ll='ls -la' alias power-audit='geminux-power-audit' diff --git a/overlay/rootfs/usr/bin/geminux-apply-theme b/overlay/rootfs/usr/bin/geminux-apply-theme index c8aa67d..6538749 100755 --- a/overlay/rootfs/usr/bin/geminux-apply-theme +++ b/overlay/rootfs/usr/bin/geminux-apply-theme @@ -31,8 +31,8 @@ fi /usr/bin/geminux-sync-dunst-theme -# Signal live applications (dwm, st, libgemui apps) to reload .Xresources via SIGUSR1 -for proc in dwm st geminux-dialer geminux-callscreen geminux-sms geminux-contacts \ +# Signal live applications (dwm, st, webarchy, libgemui apps) to reload .Xresources via SIGUSR1 +for proc in dwm st webarchy geminux-dialer geminux-callscreen geminux-sms geminux-contacts \ geminux-net geminux-audio geminux-camera geminux-control geminux-datetime geminux-themes geminux-lock; do for pid in $(pidof "$proc" 2>/dev/null || true); do kill -USR1 "$pid" 2>/dev/null || true diff --git a/overlay/rootfs/usr/bin/geminux-launcher b/overlay/rootfs/usr/bin/geminux-launcher index e96fee1..1017d5a 100755 --- a/overlay/rootfs/usr/bin/geminux-launcher +++ b/overlay/rootfs/usr/bin/geminux-launcher @@ -21,6 +21,7 @@ fi LAUNCHER_LIST="  Terminal|st 󰚩 Bantam AI agent|st -t 'Bantam AI agent' -e /bin/bash -lc 'exec bantam' +󰖟 Webarchy Browser|webarchy 󰖟 Lynx Web Browser|st -e sh -c 'exec lynx -cfg="$HOME/.lynx.cfg"'  Dialer|geminux-dialer 󰍩 SMS Messages|geminux-sms diff --git a/patches/kernel/0007-mt6797-wlan-peer-deauth-and-rekey.patch b/patches/kernel/0007-mt6797-wlan-peer-deauth-and-rekey.patch new file mode 100644 index 0000000..65a35e0 --- /dev/null +++ b/patches/kernel/0007-mt6797-wlan-peer-deauth-and-rekey.patch @@ -0,0 +1,212 @@ +--- a/drivers/net/wireless/mediatek/mt6797/mac-priv.h ++++ b/drivers/net/wireless/mediatek/mt6797/mac-priv.h +@@ -832,6 +832,16 @@ void mt6797_ccmp_connection_lost(struct mt6797_mac *mac, const char *source, + + void mt6797_ccmp_receive(struct mt6797_mac *mac, struct sk_buff *skb); + ++bool mt6797_ccmp_rx_ready(struct mt6797_mac *mac); ++ ++bool mt6797_join_peer_deauth(const unsigned char *packet, size_t bytes, ++ unsigned char channel, const unsigned char own[6], ++ const unsigned char ap[6], unsigned char bmc_index, ++ unsigned int *reason_out); ++ ++bool mt6797_ccmp_rx_eapol_rekey(const unsigned char *packet, size_t bytes, ++ const struct mt6797_ccmp_rx_context *context); ++ + int mt6797_mac_join_open_lifetime(struct mt6797_mac *mac); + void mt6797_mac_join_read_bss(struct mt6797_mac *mac, struct ieee80211_vif *vif, + const struct ieee80211_bss_conf *info); +--- a/drivers/net/wireless/mediatek/mt6797/data.c ++++ b/drivers/net/wireless/mediatek/mt6797/data.c +@@ -1174,7 +1174,7 @@ void mt6797_ccmp_withdraw(struct mt6797_mac *mac) + complete_all(&mac->ccmp_key_done); + } + +-static bool mt6797_ccmp_rx_ready(struct mt6797_mac *mac) ++bool mt6797_ccmp_rx_ready(struct mt6797_mac *mac) + { + return !mac->ccmp_closed && mac->ccmp_rx.active && mac->ccmp_rx.authorized && + mac->ccmp_decap && rcu_access_pointer(mac->ccmp_sta) && mac->ccmp_ptk && +@@ -1919,3 +1919,135 @@ void mt6797_mac_eapol_trace(struct mt6797_mac *mac, size_t bytes, + bytes, frame_bytes, eapol_bytes, p[5], !!(p[6] & 0x80), + copied, (int)sizeof(header), header); + } ++ ++bool mt6797_join_peer_deauth(const unsigned char *packet, size_t bytes, ++ unsigned char channel, const unsigned char own[6], ++ const unsigned char ap[6], unsigned char bmc_index, ++ unsigned int *reason_out) ++{ ++ static const unsigned char broadcast[6] = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }; ++ size_t offset = 16; ++ unsigned int type, groups, match, status, fc, subtype; ++ const unsigned char *f; ++ ++ if (!packet || !own || !ap || !channel || bytes < 16 || bytes > 4096 || ++ mt6797_join_le16(packet) != bytes || packet[5] != channel) ++ return false; ++ type = mt6797_join_le16(packet + 2); ++ if ((type & 0xe00f) != 0xe001) ++ return false; ++ if ((packet[6] & 0xbf) != 24 || packet[7] != 0x04) ++ return false; ++ match = packet[4] & 0x3f; ++ if (match == 0x02) { ++ if (packet[8] != 1) ++ return false; ++ } else if (match == 0x08) { ++ if (packet[8] != bmc_index) ++ return false; ++ } else { ++ return false; ++ } ++ status = mt6797_join_le16(packet + 10); ++ if (status != 0xe000 && status != 0xe004) ++ return false; ++ groups = (type >> 9) & 15; ++ if (groups & 8) ++ offset += 16; ++ if (groups & 1) ++ offset += 16; ++ if (groups & 2) ++ offset += 8; ++ if (groups & 4) ++ offset += 24; ++ if (packet[6] & 0x40) ++ offset += 2; ++ if (offset > bytes || bytes - offset < 26) ++ return false; ++ f = packet + offset; ++ fc = mt6797_join_le16(f); ++ subtype = (fc >> 4) & 15; ++ if ((fc & 0xc70f) || (subtype != 10 && subtype != 12) || ++ (mt6797_join_le16(f + 22) & 15)) ++ return false; ++ if (match == 0x02) { ++ if (memcmp(f + 4, own, 6)) ++ return false; ++ } else if (memcmp(f + 4, broadcast, 6)) { ++ return false; ++ } ++ if (memcmp(f + 10, ap, 6) || memcmp(f + 16, ap, 6)) ++ return false; ++ if (reason_out) ++ *reason_out = mt6797_join_le16(f + 24); ++ return true; ++} ++ ++bool mt6797_ccmp_rx_eapol_rekey(const unsigned char *packet, size_t bytes, ++ const struct mt6797_ccmp_rx_context *context) ++{ ++ unsigned char pn[6]; ++ size_t offset = 48; ++ unsigned int groups, fc, i, tid; ++ const unsigned char *last; ++ const unsigned char *ethernet; ++ bool greater = false, own_any = false, ap_any = false, source_any = false; ++ ++ if (!packet || !context || bytes < 16 || bytes > 2352 || ++ !context->authorized || !context->active || !context->seeded || ++ !context->pairwise || context->cipher != 0x000fac04U || ++ context->key_bytes != 16 || context->key_id || ++ context->wlan_index != 1 || context->rxd_bssid > 63 || !context->channel || ++ (context->own[0] & 1) || (context->ap[0] & 1)) ++ return false; ++ for (i = 0; i < 6; i++) { ++ own_any |= context->own[i] != 0; ++ ap_any |= context->ap[i] != 0; ++ } ++ if (!own_any || !ap_any || mt6797_join_le16(packet) != bytes || ++ (mt6797_join_le16(packet + 2) >> 13) != 2 || ++ packet[4] != 0x02 || packet[5] != context->channel || ++ (packet[6] & 0xbf) != 0x8e || ++ packet[7] != (unsigned int)context->rxd_bssid << 2 || ++ packet[8] != context->wlan_index || (packet[9] & 0xf0) != 0x40 || ++ !mt6797_ccmp_rx_status_ok(mt6797_join_le16(packet + 10))) ++ return false; ++ groups = (mt6797_join_le16(packet + 2) >> 9) & 15; ++ if ((groups & 9) != 9) ++ return false; ++ if (groups & 2) ++ offset += 8; ++ if (groups & 4) ++ offset += 24; ++ if (packet[6] & 0x40) ++ offset += 2; ++ if (offset > bytes || bytes - offset <= 14) ++ return false; ++ fc = mt6797_join_le16(packet + 16); ++ if ((fc & ~(0x2800U | MT6797_CCMP_RX_QOS_BIT)) != 0x4208 || ++ (mt6797_join_le16(packet + 24) & 15) || ++ !mt6797_ccmp_rx_tid_ok(packet, fc, 0x40) || ++ mt6797_join_le32(packet + 28)) ++ return false; ++ ethernet = packet + offset; ++ for (i = 0; i < 6; i++) { ++ if (packet[18 + i] != context->ap[i] || ethernet[i] != context->own[i]) ++ return false; ++ source_any |= ethernet[6 + i] != 0; ++ pn[i] = packet[32 + 5 - i]; ++ } ++ if (!source_any || (ethernet[6] & 1) || ++ ethernet[12] != 0x88 || ethernet[13] != 0x8e) ++ return false; ++ tid = packet[9] & 15; ++ last = tid ? context->tid_pn[tid - 1] : context->pn; ++ for (i = 0; i < 6; i++) { ++ if (pn[i] < last[i]) ++ return false; ++ if (pn[i] > last[i]) { ++ greater = true; ++ break; ++ } ++ } ++ return greater; ++} +--- a/drivers/net/wireless/mediatek/mt6797/join.c ++++ b/drivers/net/wireless/mediatek/mt6797/join.c +@@ -2838,6 +2838,7 @@ void mt6797_mac_join_work(struct work_struct *work) + mac->native_diag_bytes }; + bool admitted; + struct mt6797_native_beacon nbcn; ++ unsigned int deauth_reason; + + nb.native_rx = mac->ccmp_queued; + admitted = mac->native_diag_state == MT6797_ND_ACTIVE && +@@ -2861,6 +2862,35 @@ void mt6797_mac_join_work(struct work_struct *work) + goto failed; + continue; + } ++ if (mac->join_assoc_received && !mac->join_assoc_status && ++ !mac->join_cleanup_done && ++ mt6797_join_peer_deauth(mac->join_packet, ++ rx.logical_bytes, ++ mac->join_chan_number, ++ mac->hw->wiphy->perm_addr, ++ mac->join_ap, ++ MT6797_JOIN_BMC_WLAN_INDEX, ++ &deauth_reason)) { ++ if (mac->join_data_phase && !mac->join_data_ended) { ++ dev_info(wiphy_dev(mac->hw->wiphy), ++ "one-shot WLAN peer deauth/disassoc: reason=%u\n", ++ deauth_reason); ++ mt6797_mac_join_end_data(mac, "peer-deauth"); ++ mt6797_ccmp_connection_lost(mac, "peer-deauth", ++ deauth_reason); ++ } ++ continue; ++ } ++ if (admitted && mt6797_ccmp_rx_ready(mac) && ++ mt6797_ccmp_rx_eapol_rekey(mac->join_packet, ++ rx.logical_bytes, ++ &mac->ccmp_rx)) { ++ dev_info(wiphy_dev(mac->hw->wiphy), ++ "one-shot WLAN peer GTK rekey: triggering reassociation\n"); ++ mt6797_mac_join_end_data(mac, "gtk-rekey"); ++ mt6797_ccmp_connection_lost(mac, "gtk-rekey", 0); ++ continue; ++ } + if (admitted) + ret = mt6797_ccmp_queue_rx(mac, rx.logical_bytes, + &received); diff --git a/patches/kernel/series b/patches/kernel/series index 6356d18..a348e50 100644 --- a/patches/kernel/series +++ b/patches/kernel/series @@ -4,3 +4,4 @@ 0004-gemini-ssd2092-display-and-touch.patch 0005-mt6797-consys-wifi-factory-firmware.patch 0006-mt6797-boot-cleanups.patch +0007-mt6797-wlan-peer-deauth-and-rekey.patch diff --git a/prebuilt/gdk-pixbuf/usr/bin/gdk-pixbuf-csource b/prebuilt/gdk-pixbuf/usr/bin/gdk-pixbuf-csource new file mode 100755 index 0000000..98e60f2 Binary files /dev/null and b/prebuilt/gdk-pixbuf/usr/bin/gdk-pixbuf-csource differ diff --git a/prebuilt/gdk-pixbuf/usr/bin/gdk-pixbuf-pixdata b/prebuilt/gdk-pixbuf/usr/bin/gdk-pixbuf-pixdata new file mode 100755 index 0000000..a27109b Binary files /dev/null and b/prebuilt/gdk-pixbuf/usr/bin/gdk-pixbuf-pixdata differ diff --git a/prebuilt/gdk-pixbuf/usr/bin/gdk-pixbuf-query-loaders b/prebuilt/gdk-pixbuf/usr/bin/gdk-pixbuf-query-loaders new file mode 100755 index 0000000..46b256a Binary files /dev/null and b/prebuilt/gdk-pixbuf/usr/bin/gdk-pixbuf-query-loaders differ diff --git a/prebuilt/gdk-pixbuf/usr/lib/gdk-pixbuf-2.0/2.10.0/loaders.cache b/prebuilt/gdk-pixbuf/usr/lib/gdk-pixbuf-2.0/2.10.0/loaders.cache new file mode 100644 index 0000000..ed92def --- /dev/null +++ b/prebuilt/gdk-pixbuf/usr/lib/gdk-pixbuf-2.0/2.10.0/loaders.cache @@ -0,0 +1 @@ +# Pure-C gdk-pixbuf 2.42.12: all standard loaders (png, jpeg, gif, bmp, ico, xpm, xbm, tga, pnm) are built-in. diff --git a/prebuilt/gdk-pixbuf/usr/lib/libgdk_pixbuf-2.0.so.0 b/prebuilt/gdk-pixbuf/usr/lib/libgdk_pixbuf-2.0.so.0 new file mode 120000 index 0000000..fd7f2a9 --- /dev/null +++ b/prebuilt/gdk-pixbuf/usr/lib/libgdk_pixbuf-2.0.so.0 @@ -0,0 +1 @@ +libgdk_pixbuf-2.0.so.0.4200.12 \ No newline at end of file diff --git a/prebuilt/gdk-pixbuf/usr/lib/libgdk_pixbuf-2.0.so.0.4200.12 b/prebuilt/gdk-pixbuf/usr/lib/libgdk_pixbuf-2.0.so.0.4200.12 new file mode 100755 index 0000000..ea052cd Binary files /dev/null and b/prebuilt/gdk-pixbuf/usr/lib/libgdk_pixbuf-2.0.so.0.4200.12 differ diff --git a/prebuilt/geminux/usr/bin/geminux-net b/prebuilt/geminux/usr/bin/geminux-net index b08a0a9..a4434b9 100755 Binary files a/prebuilt/geminux/usr/bin/geminux-net and b/prebuilt/geminux/usr/bin/geminux-net differ diff --git a/prebuilt/geminux/usr/lib/libgemui.so b/prebuilt/geminux/usr/lib/libgemui.so index dae4936..39be64a 100755 Binary files a/prebuilt/geminux/usr/lib/libgemui.so and b/prebuilt/geminux/usr/lib/libgemui.so differ diff --git a/prebuilt/geminux/usr/sbin/geminux-dnsctl b/prebuilt/geminux/usr/sbin/geminux-dnsctl new file mode 100755 index 0000000..62735b8 Binary files /dev/null and b/prebuilt/geminux/usr/sbin/geminux-dnsctl differ diff --git a/prebuilt/kernel/boot/Image.gz b/prebuilt/kernel/boot/Image.gz index ff50962..c10e1a8 100644 Binary files a/prebuilt/kernel/boot/Image.gz and b/prebuilt/kernel/boot/Image.gz differ diff --git a/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/net/wireless/mediatek/mt6797/mac.ko.zst b/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/net/wireless/mediatek/mt6797/mac.ko.zst index 396562c..e3ac98d 100644 Binary files a/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/net/wireless/mediatek/mt6797/mac.ko.zst and b/prebuilt/kernel/lib/modules/7.3.5-geminux/kernel/drivers/net/wireless/mediatek/mt6797/mac.ko.zst differ diff --git a/prebuilt/mpv/etc/mpv/encoding-profiles.conf b/prebuilt/mpv/etc/mpv/encoding-profiles.conf new file mode 100644 index 0000000..77a0d91 --- /dev/null +++ b/prebuilt/mpv/etc/mpv/encoding-profiles.conf @@ -0,0 +1,224 @@ +# +# mpv configuration file +# + +######################### +# encoding profile file # +######################### +# +# Note: by default, this file is installed to /etc/mpv/encoding-profiles.conf +# (or a different location, depending on --prefix). mpv will load it by +# default on program start. If ~/.mpv/encoding-profiles.conf exists, this file +# will be loaded instead. +# +# Then, list all profiles by +# mpv --profile=help | grep enc- +# +# The following kinds of encoding profiles exist: +# enc-a-*: initialize an audio codec including good defaults +# enc-v-*: initialize a video codec including good defaults +# enc-f-*: initialize a file format including good defaults, including +# selecting and initializing a good audio and video codec +# enc-to-*: load known good settings for a target device; this typically +# includes selecting an enc-f-* profile, then adjusting some +# settings like frame rate, resolution and codec parameters +# +# AFTER including a profile of these, you can of course still change +# options, or even switch to another codec. +# +# You can view the exact options a profile sets by +# mpv --show-profile=enc-to-hp-slate-7 +# +# Examples: +# mpv --profile=enc-to-dvdpal --o=outfile.mpg infile.mkv +# mpv --profile=enc-f-avi --vf=fps=30 --o=outfile.avi infile.mkv +# mpv --profile=enc-v-mpeg4 --ovcopts-add=qscale=7 --profile=enc-a-mp3 --oacopts-add=b=320k --o=outfile.avi infile.mkv + +################ +# audio codecs # +################ +[enc-a-aac] +profile-desc = "AAC (libfdk-aac or FFmpeg)" +oac = libfdk_aac,aac +oacopts = b=96k + +[enc-a-ac3] +profile-desc = "AC3 (FFmpeg)" +oac = ac3 +oacopts = b=448k + +[enc-a-mp3] +profile-desc = "MP3 (LAME)" +oac = libmp3lame +oacopts = b=128k + +[enc-a-vorbis] +profile-desc = "Vorbis (libvorbis or FFmpeg)" +oac = libvorbis,vorbis +oacopts = qscale=3 + +[enc-a-opus] +profile-desc = "Opus (libopus or FFmpeg)" +oac = libopus,opus +audio-samplerate = 48000 +oacopts = b=96k + +################ +# video codecs # +################ +[enc-v-h263] +profile-desc = "H.263 (FFmpeg)" +ovc = h263 +ovcopts = qscale=4 + +[enc-v-h264] +profile-desc = "H.264 (x264)" +ovc = libx264 +ovcopts = preset=medium,crf=23,threads=0 +# If you want to restrict the output video to something compatible with most +# hardware and basic decoders, add "profile=high,level=41" to ovcopts above and +# uncomment the following line to avoid errors when source video isn't yuv420p: +#vf-add = format=yuv420p + +[enc-v-mpeg2] +profile-desc = "MPEG-2 Video (FFmpeg)" +ovc = mpeg2video + +[enc-v-mpeg4] +profile-desc = "MPEG-4 Part 2 (FFmpeg)" +ovc = mpeg4 +ovcopts = qscale=4 + +[enc-v-vp8] +profile-desc = "VP8 (libvpx)" +ovc = libvpx +ovcopts = speed=0,lag-in-frames=8,slices=2,threads=0,b=2M,crf=10,qmin=0,qmax=36 + +[enc-v-vp9] +profile-desc = "VP9 (libvpx)" +ovc = libvpx-vp9 +ovcopts = speed=6,lag-in-frames=8,slices=2,threads=0,crf=18,qmin=0,qmax=36 + +########### +# formats # +########### +[enc-f-3gp] +profile-desc = "H.263 + AAC (for 3GP)" +of = 3gp +profile = enc-v-h263 +profile = enc-a-aac +ofopts = "" + +[enc-f-avi] +profile-desc = "MPEG-4 + MP3 (for AVI)" +of = avi +profile = enc-v-mpeg4 +profile = enc-a-mp3 +ofopts = "" + +[enc-f-mp4] +profile-desc = "H.264 + AAC (for MP4)" +of = mp4 +profile = enc-v-h264 +profile = enc-a-aac +## equivalent to using qt-faststart tool +## can be used to speed up seeking when streaming +# ofopts = movflags=+faststart + +[enc-f-webm] +profile-desc = "VP9 + Opus (for WebM)" +of = webm +profile = enc-v-vp9 +profile = enc-a-opus +ofopts = "" + +################## +# target devices # +################## +[enc-to-dvdpal] +profile-desc = "DVD-Video PAL, use dvdauthor -v pal -a ac3+en (MUST be used with 4:3 or 16:9 aspect, and 720x576, 704x576, 352x576 or 352x288 resolution)" +profile = enc-v-mpeg2 +profile = enc-a-ac3 +of = dvd +ofopts-append = packetsize=2048 +ofopts-append = muxrate=10080000 +vf-add = fps=25 +audio-samplerate = 48000 +ovcopts = g=15,b=6000000,maxrate=9000000,minrate=0,bufsize=1835008 + +[enc-to-dvdntsc] +profile-desc = "DVD-Video NTSC, use dvdauthor -v ntsc -a ac3+en (MUST be used with 4:3 or 16:9 aspect, and 720x480, 704x480, 352x480 or 352x240 resolution)" +profile = enc-v-mpeg2 +profile = enc-a-ac3 +of = dvd +ofopts-append = packetsize=2048 +ofopts-append = muxrate=10080000 +vf-add = fps="24000/1001" +audio-samplerate = 48000 +ovcopts = g=18,b=6000000,maxrate=9000000,minrate=0,bufsize=1835008 + +[enc-to-nok-n900] +profile-desc = "MP4 for Nokia N900" +profile = enc-f-mp4 +# DW = 800, DH = 480, SAR = 1 +vf-add = lavfi=graph="scale=floor(min(min(800\,dar*480)\,in_w*max(1\,sar))/2+0.5)*2:floor(min(min(800/dar\,480)\,in_h*max(1/sar\,1))/2+0.5)*2,setsar=sar=1" +ovcopts-append = profile=baseline +ovcopts-append = level=30 +ovcopts-append = maxrate=10000k +ovcopts-append = bufsize=10000k +ovcopts-append = rc_init_occupancy=9000k +ovcopts-append = refs=5 + +[enc-to-nok-6300] +profile-desc = "3GP for Nokia 6300" +profile = enc-f-3gp +vf-add = fps=25 +vf-add = lavfi=graph="scale=176:144" +audio-samplerate = 16000 +audio-channels = 1 +oacopts-add = b=32k + +[enc-to-hp-slate-7] +profile-desc = "MP4 for HP Slate 7 (1024x600, crazy aspect)" +profile = enc-f-mp4 +ovcopts-add = profile=high +# DW = 1024, DH = 600, DAR = 97:54 (=> SAR = 2425:2304) +vf-add = lavfi=graph="scale=floor(min(1024*min(1\,dar/(97/54))\,in_w)/2+0.5)*2:floor(min(600*min((97/54)/dar\,1)\,in_h)/2+0.5)*2,setsar=sar=sar/(2425/2304)" + +# Advanced scaling for specific output devices - how it works: +# DW = display width (px) (1024) +# DH = display height (px) (600) +# SAR = display sample aspect ratio, i.e. DAR * DH / DW (2425:2304) +# DAR = display aspect ratio, i.e. SAR * DW / DH (97:54) +# Variant: zoomed out +# vf-add = lavfi=graph="scale=floor(min(DW*min(1\,dar/DAR)\,in_w*max(1\,sar/SAR))/2+0.5)*2:floor(min(DH*min(DAR/dar\,1)\,in_h*max(SAR/sar\,1))/2+0.5)*2,setsar=sar=1" +# Variant: zoomed in +# vf-add = lavfi=graph="scale=floor(min(DW*max(1\,dar/DAR)\,in_w*max(1\,sar/SAR))/2+0.5)*2:floor(min(DH*max(DAR/dar\,1)\,in_h*max(SAR/sar\,1))/2+0.5)*2,setsar=sar=1" +# How it works: +# 1a: DW, DH*dar/DAR - fit to display width +# 1b: DH*DAR/dar, DH - fit to display height +# 1: the min of 1a and 1b these (i.e. fit inside both width and height); for zoomed in view, use the max +# 2a: in_w, in_h*SAR/sar - fit to original width +# 2b: in_w*sar/SAR, in_h - fit to original height +# 2: the max of 2a and 2b (i.e. avoid enlarging both dimensions - let HW scaling handle this) +# output: the min of 1 and 2 (i.e. fulfill both constraints) +# setsar=sar=1 to prevent scaling on the device (skip this if the device actually wants the proper SAR to be specified for not performing needless scaling) +# +# Simplified special case for SAR == 1, DAR == DW/DH: +# Variant: zoomed out +# vf-add = lavfi=graph="scale=floor(min(min(DW\,dar*DH)\,in_w*max(1\,sar))/2+0.5)*2:floor(min(min(DW/dar\,DH)\,in_h*max(1/sar\,1))/2+0.5)*2,setsar=sar=1" +# Variant: zoomed in +# vf-add = lavfi=graph="scale=floor(min(max(DW\,dar*DH)\,in_w*max(1\,sar))/2+0.5)*2:floor(min(max(DW/dar\,DH)\,in_h*max(1/sar\,1))/2+0.5)*2,setsar=sar=1" +# setsar=sar=1 to prevent nasty almost-1 SAR to be passed to the codec due to the rounding which can fail +# +# If the device supports file SAR properly, we can make use of it to avoid +# upscaling. The setsar=sar=sar/SAR at the end serves to fake the SAR for devices that don't know their own display's SAR. +# Variant: zoomed out +# vf-add = lavfi=graph="scale=floor(min(DW*min(1\,dar/DAR)\,in_w)/2+0.5)*2:floor(min(DH*min(DAR/dar\,1)\,in_h)/2+0.5)*2,setsar=sar=sar/SAR" +# Variant: zoomed in +# vf-add = lavfi=graph="scale=floor(min(DW*max(1\,dar/DAR)\,in_w)/2+0.5)*2:floor(min(DH*max(DAR/dar\,1)\,in_h)/2+0.5)*2,setsar=sar=sar/SAR" +# Simplified special case for SAR == 1, DAR == DW/DH: +# Variant: zoomed out +# vf-add = lavfi=graph="scale=floor(min(min(DW\,dar*DH)\,in_w)/2+0.5)*2:floor(min(min(DW/dar\,DH)\,in_h)/2+0.5)*2" +# Variant: zoomed in +# vf-add = lavfi=graph="scale=floor(min(max(DW\,dar*DH)\,in_w)/2+0.5)*2:floor(min(max(DW/dar\,DH)\,in_h)/2+0.5)*2" diff --git a/prebuilt/mpv/etc/mpv/mpv.conf b/prebuilt/mpv/etc/mpv/mpv.conf new file mode 100644 index 0000000..47d750c --- /dev/null +++ b/prebuilt/mpv/etc/mpv/mpv.conf @@ -0,0 +1,7 @@ +# Geminux defaults (MT6797X + Mali-T880 Panfrost X11 EGL + PipeWire) +vo=gpu +gpu-api=opengl +gpu-context=x11egl +ao=pipewire,pulse,alsa +vd-lavc-threads=4 +osc=yes diff --git a/prebuilt/mpv/usr/bin/ffmpeg b/prebuilt/mpv/usr/bin/ffmpeg new file mode 100755 index 0000000..2329b81 Binary files /dev/null and b/prebuilt/mpv/usr/bin/ffmpeg differ diff --git a/prebuilt/mpv/usr/bin/ffprobe b/prebuilt/mpv/usr/bin/ffprobe new file mode 100755 index 0000000..320457d Binary files /dev/null and b/prebuilt/mpv/usr/bin/ffprobe differ diff --git a/prebuilt/mpv/usr/bin/mpv b/prebuilt/mpv/usr/bin/mpv new file mode 100755 index 0000000..f3317ec Binary files /dev/null and b/prebuilt/mpv/usr/bin/mpv differ diff --git a/prebuilt/mpv/usr/lib/geminux-mpv/libavcodec.so.61 b/prebuilt/mpv/usr/lib/geminux-mpv/libavcodec.so.61 new file mode 120000 index 0000000..4c9502c --- /dev/null +++ b/prebuilt/mpv/usr/lib/geminux-mpv/libavcodec.so.61 @@ -0,0 +1 @@ +libavcodec.so.61.19.101 \ No newline at end of file diff --git a/prebuilt/mpv/usr/lib/geminux-mpv/libavcodec.so.61.19.101 b/prebuilt/mpv/usr/lib/geminux-mpv/libavcodec.so.61.19.101 new file mode 100755 index 0000000..3f122f2 Binary files /dev/null and b/prebuilt/mpv/usr/lib/geminux-mpv/libavcodec.so.61.19.101 differ diff --git a/prebuilt/mpv/usr/lib/geminux-mpv/libavdevice.so.61 b/prebuilt/mpv/usr/lib/geminux-mpv/libavdevice.so.61 new file mode 120000 index 0000000..68dc2c2 --- /dev/null +++ b/prebuilt/mpv/usr/lib/geminux-mpv/libavdevice.so.61 @@ -0,0 +1 @@ +libavdevice.so.61.3.100 \ No newline at end of file diff --git a/prebuilt/mpv/usr/lib/geminux-mpv/libavdevice.so.61.3.100 b/prebuilt/mpv/usr/lib/geminux-mpv/libavdevice.so.61.3.100 new file mode 100755 index 0000000..50f597d Binary files /dev/null and b/prebuilt/mpv/usr/lib/geminux-mpv/libavdevice.so.61.3.100 differ diff --git a/prebuilt/mpv/usr/lib/geminux-mpv/libavfilter.so.10 b/prebuilt/mpv/usr/lib/geminux-mpv/libavfilter.so.10 new file mode 120000 index 0000000..59a4517 --- /dev/null +++ b/prebuilt/mpv/usr/lib/geminux-mpv/libavfilter.so.10 @@ -0,0 +1 @@ +libavfilter.so.10.5.100 \ No newline at end of file diff --git a/prebuilt/mpv/usr/lib/geminux-mpv/libavfilter.so.10.5.100 b/prebuilt/mpv/usr/lib/geminux-mpv/libavfilter.so.10.5.100 new file mode 100755 index 0000000..74054a8 Binary files /dev/null and b/prebuilt/mpv/usr/lib/geminux-mpv/libavfilter.so.10.5.100 differ diff --git a/prebuilt/mpv/usr/lib/geminux-mpv/libavformat.so.61 b/prebuilt/mpv/usr/lib/geminux-mpv/libavformat.so.61 new file mode 120000 index 0000000..5df29f9 --- /dev/null +++ b/prebuilt/mpv/usr/lib/geminux-mpv/libavformat.so.61 @@ -0,0 +1 @@ +libavformat.so.61.7.103 \ No newline at end of file diff --git a/prebuilt/mpv/usr/lib/geminux-mpv/libavformat.so.61.7.103 b/prebuilt/mpv/usr/lib/geminux-mpv/libavformat.so.61.7.103 new file mode 100755 index 0000000..ac06e37 Binary files /dev/null and b/prebuilt/mpv/usr/lib/geminux-mpv/libavformat.so.61.7.103 differ diff --git a/prebuilt/mpv/usr/lib/geminux-mpv/libavutil.so.59 b/prebuilt/mpv/usr/lib/geminux-mpv/libavutil.so.59 new file mode 120000 index 0000000..e5d38e8 --- /dev/null +++ b/prebuilt/mpv/usr/lib/geminux-mpv/libavutil.so.59 @@ -0,0 +1 @@ +libavutil.so.59.39.100 \ No newline at end of file diff --git a/prebuilt/mpv/usr/lib/geminux-mpv/libavutil.so.59.39.100 b/prebuilt/mpv/usr/lib/geminux-mpv/libavutil.so.59.39.100 new file mode 100755 index 0000000..be73ed9 Binary files /dev/null and b/prebuilt/mpv/usr/lib/geminux-mpv/libavutil.so.59.39.100 differ diff --git a/prebuilt/mpv/usr/lib/geminux-mpv/libplacebo.so.360 b/prebuilt/mpv/usr/lib/geminux-mpv/libplacebo.so.360 new file mode 100755 index 0000000..c3a843e Binary files /dev/null and b/prebuilt/mpv/usr/lib/geminux-mpv/libplacebo.so.360 differ diff --git a/prebuilt/mpv/usr/lib/geminux-mpv/libswresample.so.5 b/prebuilt/mpv/usr/lib/geminux-mpv/libswresample.so.5 new file mode 120000 index 0000000..339ac0e --- /dev/null +++ b/prebuilt/mpv/usr/lib/geminux-mpv/libswresample.so.5 @@ -0,0 +1 @@ +libswresample.so.5.3.100 \ No newline at end of file diff --git a/prebuilt/mpv/usr/lib/geminux-mpv/libswresample.so.5.3.100 b/prebuilt/mpv/usr/lib/geminux-mpv/libswresample.so.5.3.100 new file mode 100755 index 0000000..5132d2f Binary files /dev/null and b/prebuilt/mpv/usr/lib/geminux-mpv/libswresample.so.5.3.100 differ diff --git a/prebuilt/mpv/usr/lib/geminux-mpv/libswscale.so.8 b/prebuilt/mpv/usr/lib/geminux-mpv/libswscale.so.8 new file mode 120000 index 0000000..ec9372a --- /dev/null +++ b/prebuilt/mpv/usr/lib/geminux-mpv/libswscale.so.8 @@ -0,0 +1 @@ +libswscale.so.8.3.100 \ No newline at end of file diff --git a/prebuilt/mpv/usr/lib/geminux-mpv/libswscale.so.8.3.100 b/prebuilt/mpv/usr/lib/geminux-mpv/libswscale.so.8.3.100 new file mode 100755 index 0000000..e943cea Binary files /dev/null and b/prebuilt/mpv/usr/lib/geminux-mpv/libswscale.so.8.3.100 differ diff --git a/prebuilt/mpv/usr/lib/gstreamer-1.0/libgstlibav.so b/prebuilt/mpv/usr/lib/gstreamer-1.0/libgstlibav.so new file mode 100755 index 0000000..9c875cb Binary files /dev/null and b/prebuilt/mpv/usr/lib/gstreamer-1.0/libgstlibav.so differ diff --git a/prebuilt/mpv/usr/share/applications/mpv.desktop b/prebuilt/mpv/usr/share/applications/mpv.desktop new file mode 100644 index 0000000..6fba23f --- /dev/null +++ b/prebuilt/mpv/usr/share/applications/mpv.desktop @@ -0,0 +1,51 @@ +[Desktop Entry] +Type=Application +Name=mpv Media Player +Name[ar]=مشغل وسائط mpv +Name[ca]=Reproductor multimèdia mpv +Name[cs]=mpv přehrávač +Name[da]=mpv-medieafspiller +Name[fr]=Lecteur multimédia mpv +Name[it]=Lettore multimediale mpv +Name[ja]=mpv メディアプレイヤー +Name[pl]=Odtwarzacz mpv +Name[ru]=Проигрыватель mpv +Name[tr]=mpv Ortam Oynatıcı +Name[zh_CN]=mpv 媒体播放器 +Name[zh_TW]=mpv 媒體播放器 +GenericName=Multimedia player +GenericName[ar]=مُشَغِّل وسائط متعددة +GenericName[cs]=Multimediální přehrávač +GenericName[da]=Multimedieafspiller +GenericName[fr]=Lecteur multimédia +GenericName[it]=Lettore multimediale +GenericName[ja]=マルチメディアプレイヤー +GenericName[ru]=Мультимедийный проигрыватель +GenericName[tr]=Çoklu ortam oynatıcı +GenericName[zh_CN]=多媒体播放器 +GenericName[zh_TW]=多媒體播放器 +Comment=Play movies and songs +Comment[ar]=شَغِّل الأفلام والأغاني +Comment[ca]=Reproduïu vídeos i cançons +Comment[cs]=Přehrává filmy a hudbu +Comment[da]=Afspil film og sange +Comment[de]=Filme und Musik abspielen +Comment[es]=Reproduzca vídeos y canciones +Comment[fr]=Lire des vidéos et des musiques +Comment[ja]=映画や音楽を再生する +Comment[it]=Riproduci video e canzoni +Comment[pl]=Odtwarzaj filmy i muzykę +Comment[ru]=Воспроизведение фильмов и музыки +Comment[tr]=Filmleri ve şarkıları oynatın +Comment[zh_CN]=播放电影和歌曲 +Comment[zh_TW]=播放電影和歌曲 +Icon=mpv +TryExec=mpv +Exec=mpv --player-operation-mode=pseudo-gui -- %U +Terminal=false +Categories=AudioVideo;Audio;Video;Player;TV; +MimeType=application/ogg;application/x-ogg;application/mxf;application/sdp;application/smil;application/x-smil;application/streamingmedia;application/x-streamingmedia;application/vnd.rn-realmedia;application/vnd.rn-realmedia-vbr;audio/aac;audio/x-aac;audio/vnd.dolby.heaac.1;audio/vnd.dolby.heaac.2;audio/aiff;audio/x-aiff;audio/m4a;audio/x-m4a;application/x-extension-m4a;audio/mp1;audio/x-mp1;audio/mp2;audio/x-mp2;audio/mp3;audio/x-mp3;audio/mpeg;audio/mpeg2;audio/mpeg3;audio/mpegurl;audio/x-mpegurl;audio/mpg;audio/x-mpg;audio/rn-mpeg;audio/musepack;audio/x-musepack;audio/ogg;audio/scpls;audio/x-scpls;audio/vnd.rn-realaudio;audio/wav;audio/x-pn-wav;audio/x-pn-windows-pcm;audio/x-realaudio;audio/x-pn-realaudio;audio/x-ms-wma;audio/x-pls;audio/x-wav;video/mpeg;video/x-mpeg2;video/x-mpeg3;video/mp4v-es;video/x-m4v;video/mp4;application/x-extension-mp4;video/divx;video/vnd.divx;video/msvideo;video/x-msvideo;video/ogg;video/quicktime;video/vnd.rn-realvideo;video/x-ms-afs;video/x-ms-asf;audio/x-ms-asf;application/vnd.ms-asf;video/x-ms-wmv;video/x-ms-wmx;video/x-ms-wvxvideo;video/x-avi;video/avi;video/x-flic;video/fli;video/x-flc;video/flv;video/x-flv;video/x-theora;video/x-theora+ogg;video/x-matroska;video/mkv;audio/x-matroska;application/x-matroska;video/webm;audio/webm;audio/vorbis;audio/x-vorbis;audio/x-vorbis+ogg;video/x-ogm;video/x-ogm+ogg;application/x-ogm;application/x-ogm-audio;application/x-ogm-video;application/x-shorten;audio/x-shorten;audio/x-ape;audio/x-wavpack;audio/x-tta;audio/AMR;audio/ac3;audio/eac3;audio/amr-wb;video/mp2t;audio/flac;audio/mp4;application/x-mpegurl;video/vnd.mpegurl;application/vnd.apple.mpegurl;audio/x-pn-au;video/3gp;video/3gpp;video/3gpp2;audio/3gpp;audio/3gpp2;video/dv;audio/dv;audio/opus;audio/vnd.dts;audio/vnd.dts.hd;audio/x-adpcm;application/x-cue;audio/m3u;audio/vnd.wave;video/vnd.avi; +X-KDE-Protocols=appending,file,ftp,hls,http,https,mms,mpv,rist,rtmp,rtmps,rtmpt,rtmpts,rtp,rtsp,rtsps,sftp,smb,srt,srtp,webdav,webdavs +StartupWMClass=mpv +Keywords=mpv;media;player;video;audio;tv; +Keywords[ar]=mpv;إم بي في;ام بي في;وسائط;مشغل;فيديو;مرئية;صوتي;تلفاز; diff --git a/prebuilt/mpv/usr/share/bash-completion/completions/mpv b/prebuilt/mpv/usr/share/bash-completion/completions/mpv new file mode 100644 index 0000000..ceb6293 --- /dev/null +++ b/prebuilt/mpv/usr/share/bash-completion/completions/mpv @@ -0,0 +1,142 @@ +# +# This file is part of mpv. +# +# mpv is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# mpv is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with mpv. If not, see . +# + +_mpv_options() +{ + if [ -z ${_mpv_options_cache+x} ]; then + _mpv_options_cache=$(mpv --no-config --list-options) + fi + echo "$_mpv_options_cache" +} + +_mpv_get_args() +{ + local doc=$(_mpv_options | grep -E "^\\s*$1\\s") + local partial="$2" + local type=$(echo "$doc" | awk '{print $2;}') + + # We special-case profiles to ensure we read the config + if [ "$1" = "--show-profile" ]; then + type="ShowProfile" + elif [ "$1" = "--profile" ]; then + type="Profile" + fi + + declare -a candidates + case $type in + String) + if echo "$doc" | grep -q '\[file\]' ; then + if [ "$cur" = '=' ]; then + # Without this, _filedir will try and complete files starting with '=' + cur="" + fi + _filedir 2>/dev/null || COMPREPLY=($(compgen -f)) + return 0 + else + candidates=($(mpv --no-config $1=help | grep -v ':' | awk '{print $1;}')) + candidates+=("help") + fi + ;; + Flag) + candidates=("yes" "no" "help") + ;; + Choices:|Object) + candidates=($(mpv --no-config $1=help | grep -v ':' | awk '{print $1;}')) + candidates+=("help") + ;; + Image) + candidates=($(mpv --no-config $1=help)) + candidates=("${candidates[@]:2}") + candidates+=("help") + ;; + Profile) + candidates=($(mpv $1=help | grep -v ':' | awk '{print $1;}')) + candidates+=("help") + ;; + ShowProfile) + candidates=($(mpv $1= | grep -v ':' | awk '{print $1;}')) + ;; + *) + # There are other categories; some of which we could do something smarter + # about, with enough work. + ;; + esac + COMPREPLY=($(compgen -W "${candidates[*]}" -- "${partial}")) + if [ ${#COMPREPLY[@]} -gt 1 ]; then + compopt -o nospace mpv + fi +} + +# This regex detects special options where we don't want an '=' appended +_mpv_special_regex='\s(Flag.*\[not in config files\]|Print)' +_mpv_skip_regex='\sremoved \[deprecated\]' + +_mpv_regular_options() +{ + if [ -z ${_mpv_regular_options_cache+x} ]; then + _mpv_regular_options_cache=($(_mpv_options | grep -vE "$_mpv_skip_regex" | \ + grep -vE "$_mpv_special_regex" | awk '{print "\\"$1;}' | grep '\--')) + _mpv_regular_options_cache="${_mpv_regular_options_cache[*]}" + fi + echo "$_mpv_regular_options_cache" +} + +_mpv_special_options() +{ + if [ -z ${_mpv_special_options_cache+x} ]; then + _mpv_special_options_cache=($(_mpv_options | grep -vE "$_mpv_skip_regex" | \ + grep -E "$_mpv_special_regex" | awk '{print "\\"$1;}' | grep '\--')) + _mpv_special_options_cache="${_mpv_special_options_cache[*]}" + fi + echo "$_mpv_special_options_cache" +} + +_mpv() +{ + compopt +o nospace mpv + + # _filedir requires the current candidate be in $cur + local cur=${COMP_WORDS[COMP_CWORD]} + local prev=${COMP_WORDS[((COMP_CWORD - 1))]} + + if [ "$cur" = '=' ]; then + # If the current word is '=' then we are looking for an argument for the + # option specified by the previous word. + _mpv_get_args "$prev" + elif [ "$prev" = '=' ]; then + # If the previous word is '=' then we are completing an argument for the + # option specified by the word before the '='. + local prevprev=${COMP_WORDS[((COMP_CWORD - 2))]} + _mpv_get_args "$prevprev" "$cur" + else + case $cur in + -*) + COMPREPLY=($(compgen -W "$(_mpv_regular_options)" -S '=' -- "${cur}")) + local normal_count=${#COMPREPLY[@]} + COMPREPLY+=($(compgen -W "$(_mpv_special_options)" -- "${cur}")) + if [ $normal_count -gt 0 -o ${#COMPREPLY[@]} -gt 1 ]; then + compopt -o nospace mpv + fi + ;; + *) + _filedir 2>/dev/null || COMPREPLY=($(compgen -f)) + ;; + esac + fi +} + +complete -F _mpv mpv diff --git a/prebuilt/mpv/usr/share/fish/vendor_completions.d/mpv.fish b/prebuilt/mpv/usr/share/fish/vendor_completions.d/mpv.fish new file mode 100644 index 0000000..7a35e55 --- /dev/null +++ b/prebuilt/mpv/usr/share/fish/vendor_completions.d/mpv.fish @@ -0,0 +1,95 @@ +# +# This file is part of mpv. +# +# mpv is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# mpv is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with mpv. If not, see . +# +# + +# Add the completion for mpv. The first argument is the option with the dash +# included and the rest of the arguments are directly passed to complete +function _complete_mpv + set --local opt $argv[1] + set --local opt_type --short-option + if string match -q -r '--' -- $opt + set opt_type --long-option + end + complete --command mpv $opt_type (string trim --left --chars '-' -- $opt) $argv[2..] +end + +function _complete_mpv_run_help + mpv $argv \ + # Remove the text before the option list + | string match --regex --invert '^\w.*:' \ + | string trim +end + +# Print the possible values for the option +function _complete_mpv_option -a opt + # We insert a tab so that it is recognized as the description of the argument + set --local value_description_rewrite 's/ /\t/' + switch $opt + case "--audio-device" "--vulkan-device" + # The value is enclosed in single quotes and the description in parentheses + set value_description_rewrite 's/\'([^\']+)\'\s+\((.*)\)$/\1\t\2/' + end + + _complete_mpv_run_help $opt=help \ + | sed -E $value_description_rewrite +end + +# Print the possible values for the image option +function _complete_mpv_image_option -a opt + mpv $opt=help | sed -e 's/.*: //' -e 's/ /\n/g' +end + +# Print the possible values for the profile option +function _complete_mpv_profile_option -a opt + _complete_mpv_run_help $opt= +end + +# Cache all the mpv options +set --local mpv_options (mpv --no-config --list-options | string match --entire --regex '^\s*--' | string trim) + +for opt_line in $mpv_options + set --local opt_line_split (string split --max 1 ' ' -- $opt_line | string trim) + set --local opt $opt_line_split[1] + set --local doc $opt_line_split[2] + set --local type (string split --field 1 ' ' $doc) + if test $opt = '--show-profile' + set type 'Profile' + end + switch $type + case String + if string match -q -r '\[file\]' $doc + _complete_mpv $opt --force-files + else + _complete_mpv $opt --exclusive --arguments "help (_complete_mpv_option $opt)" + end + case Flag + if string match -q -r '\[not in config files\]' $doc + _complete_mpv $opt + else + _complete_mpv $opt --exclusive --arguments 'yes no help' + end + case 'Choices:' Object + _complete_mpv $opt --exclusive --arguments "help (_complete_mpv_option $opt)" + case Image + _complete_mpv $opt --exclusive --arguments "help (_complete_mpv_image_option $opt)" + case Profile + _complete_mpv $opt --exclusive --arguments "help (_complete_mpv_profile_option $opt)" + case '*' + # Unimplemented categories + _complete_mpv $opt + end +end diff --git a/prebuilt/mpv/usr/share/icons/hicolor/128x128/apps/mpv.png b/prebuilt/mpv/usr/share/icons/hicolor/128x128/apps/mpv.png new file mode 100644 index 0000000..1840269 Binary files /dev/null and b/prebuilt/mpv/usr/share/icons/hicolor/128x128/apps/mpv.png differ diff --git a/prebuilt/mpv/usr/share/icons/hicolor/16x16/apps/mpv.png b/prebuilt/mpv/usr/share/icons/hicolor/16x16/apps/mpv.png new file mode 100644 index 0000000..ac2cb81 Binary files /dev/null and b/prebuilt/mpv/usr/share/icons/hicolor/16x16/apps/mpv.png differ diff --git a/prebuilt/mpv/usr/share/icons/hicolor/32x32/apps/mpv.png b/prebuilt/mpv/usr/share/icons/hicolor/32x32/apps/mpv.png new file mode 100644 index 0000000..bfb5f9c Binary files /dev/null and b/prebuilt/mpv/usr/share/icons/hicolor/32x32/apps/mpv.png differ diff --git a/prebuilt/mpv/usr/share/icons/hicolor/64x64/apps/mpv.png b/prebuilt/mpv/usr/share/icons/hicolor/64x64/apps/mpv.png new file mode 100644 index 0000000..46bb33d Binary files /dev/null and b/prebuilt/mpv/usr/share/icons/hicolor/64x64/apps/mpv.png differ diff --git a/prebuilt/mpv/usr/share/icons/hicolor/scalable/apps/mpv.svg b/prebuilt/mpv/usr/share/icons/hicolor/scalable/apps/mpv.svg new file mode 100644 index 0000000..c40fe71 --- /dev/null +++ b/prebuilt/mpv/usr/share/icons/hicolor/scalable/apps/mpv.svg @@ -0,0 +1,198 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + image/svg+xml + + + + + + + + + + + + + diff --git a/prebuilt/mpv/usr/share/icons/hicolor/symbolic/apps/mpv-symbolic.svg b/prebuilt/mpv/usr/share/icons/hicolor/symbolic/apps/mpv-symbolic.svg new file mode 100644 index 0000000..a4f9263 --- /dev/null +++ b/prebuilt/mpv/usr/share/icons/hicolor/symbolic/apps/mpv-symbolic.svg @@ -0,0 +1,68 @@ + + + + + + + + + + image/svg+xml + + + + + + + + + + diff --git a/prebuilt/mpv/usr/share/metainfo/mpv.metainfo.xml b/prebuilt/mpv/usr/share/metainfo/mpv.metainfo.xml new file mode 100644 index 0000000..618abd3 --- /dev/null +++ b/prebuilt/mpv/usr/share/metainfo/mpv.metainfo.xml @@ -0,0 +1,29 @@ + + + io.mpv.mpv + mpv + A free, open source, and cross-platform media player + +

mpv is a free (as in freedom) media player for the command line. It supports a wide variety of media file formats, audio and video codecs, and subtitle types.

+

mpv has an OpenGL, Vulkan, and D3D11 based video output that is capable of many features loved by videophiles, such as video scaling with popular high quality algorithms, color management, frame timing, interpolation, HDR, and more.

+

While mpv strives for minimalism and provides no real GUI, it has a small controller on top of the video for basic control.

+

mpv can leverage most hardware decoding APIs on all platforms. Hardware decoding can be enabled at runtime on demand.

+

Powerful scripting capabilities can make the player do almost anything. There is a large selection of user scripts on the wiki.

+

A straightforward C API was designed from the ground up to make mpv usable as a library and facilitate easy integration into other applications.

+
+ CC0-1.0 + GPL-2.0-or-later AND LGPL-2.0-or-later + mpv.io + mpv.desktop + + + + https://mpv.io/images/mpv-screenshot-34cd36ae.jpg + Main window + + + https://mpv.io/ + https://github.com/mpv-player/mpv/issues + https://github.com/mpv-player/mpv/wiki/FAQ + https://mpv.io/manual/stable +
diff --git a/prebuilt/mpv/usr/share/zsh/site-functions/_mpv b/prebuilt/mpv/usr/share/zsh/site-functions/_mpv new file mode 100644 index 0000000..cb3c00e --- /dev/null +++ b/prebuilt/mpv/usr/share/zsh/site-functions/_mpv @@ -0,0 +1,269 @@ +#compdef mpv + +# ZSH completion for mpv +# +# For customization, see: +# https://github.com/mpv-player/mpv/wiki/Zsh-completion-customization + +# +# This file is part of mpv. +# +# mpv is free software; you can redistribute it and/or +# modify it under the terms of the GNU Lesser General Public +# License as published by the Free Software Foundation; either +# version 2.1 of the License, or (at your option) any later version. +# +# mpv is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public +# License along with mpv. If not, see . +# + +local curcontext="$curcontext" state state_descr line +typeset -A opt_args + +local -a match mbegin mend +local MATCH MBEGIN MEND + +# By default, don't complete URLs unless no files match +local -a tag_order +zstyle -a ":completion:*:*:$service:*" tag-order tag_order || + zstyle ":completion:*:*:$service:*" tag-order '!urls' + +local -a urls +zstyle -a ":completion:*:*:$service:*:urls" urls urls || + zstyle ":completion:*:*:$service:*:urls" urls av://lavfi:testsrc av://lavfi:sine + +typeset -ga _mpv_completion_arguments _mpv_completion_protocols + +function _mpv_generate_arguments { + + _mpv_completion_arguments=() + + local -a option_aliases=() + + local list_options_line + for list_options_line in "${(@f)$($~words[1] --no-config --list-options)}"; do + + [[ $list_options_line =~ $'^[ \t]+--([^ \t]+)[ \t]*(.*)' ]] || continue + + local name=$match[1] desc=$match[2] + + if [[ $desc == Flag* ]]; then + + _mpv_completion_arguments+="$name" + if [[ $name != (\{|\}|v|list-options) ]]; then + # Negated version + _mpv_completion_arguments+="no-$name" + fi + + elif [[ -z $desc ]]; then + + # Sub-option for list option + + if [[ $name == *-(clr|help) ]]; then + # Like a flag + _mpv_completion_arguments+="$name" + else + # Find the parent option and use that with this option's name + _mpv_completion_arguments+="${(S)_mpv_completion_arguments[(R)${name%-*}=*]/*=/$name=}" + fi + + elif [[ $desc == Print* ]]; then + + _mpv_completion_arguments+="$name" + + elif [[ $desc =~ $'^alias for (--)?([^ \t]+)' ]]; then + + # Save this for later; we might not have parsed the target option yet + option_aliases+="$name $match[2]" + + elif [[ $desc =~ $'^removed ' ]]; then + + # skip + + else + + # Option takes argument + + local entry="$name=-:${desc//:/\\:}:" + + if [[ $desc =~ '^Choices: ([^(]*)' ]]; then + + local -a choices=(${(s: :)match[1]}) + entry+="($choices)" + # If "no" is one of the choices, it can also be negated like a flag + # (--no-whatever is equivalent to --whatever=no). + if (( ${+choices[(r)no]} )); then + _mpv_completion_arguments+="no-$name" + fi + + elif [[ $desc == *'[file]'* ]]; then + + entry+='->files' + + elif [[ $desc = 'Object settings list'* || $name == (profile|audio-device|vulkan-device) ]]; then + + entry+="->parse-help-$name" + + elif [[ $name == show-profile ]]; then + + entry+="->parse-help-profile" + + elif [[ $name == h(|elp) ]]; then + + entry+="->help-options" + + fi + + _mpv_completion_arguments+="$entry" + + fi + + done + + # Process aliases + local to_from real_name arg_spec + for to_from in $option_aliases; do + # to_from='alias-name real-name' + real_name=${to_from##* } + for arg_spec in "$real_name" "$real_name=*" "no-$real_name"; do + arg_spec=${_mpv_completion_arguments[(r)$arg_spec]} + [[ -n $arg_spec ]] && + _mpv_completion_arguments+="${arg_spec/$real_name/${to_from%% *}}" + done + done + + # Older versions of zsh have a bug where they won't complete an option listed + # after one that's a prefix of it. To work around this, we can sort the + # options by length, longest first, so that any prefix of an option will be + # listed after it. On newer versions of zsh where the bug is fixed, we skip + # this to avoid slowing down the first tab press any more than we have to. + autoload -Uz is-at-least + if ! is-at-least 5.2; then + # If this were a real language, we wouldn't have to sort by prepending the + # length, sorting the whole thing numerically, and then removing it again. + local -a sort_tmp=() + for arg_spec in $_mpv_completion_arguments; do + sort_tmp+=${#arg_spec%%=*}_$arg_spec + done + _mpv_completion_arguments=(${${(On)sort_tmp}/#*_}) + fi + +} + +function _mpv_generate_protocols { + _mpv_completion_protocols=() + local list_protos_line + for list_protos_line in "${(@f)$($~words[1] --no-config --list-protocols)}"; do + if [[ $list_protos_line =~ $'^[ \t]+(.*)' ]]; then + _mpv_completion_protocols+="$match[1]" + fi + done +} + +function _mpv_generate_if_changed { + # Called with $1 = 'arguments' or 'protocols'. Generates the respective list + # on the first run and re-generates it if the executable being completed for + # is different than the one we used to generate the cached list. + typeset -gA _mpv_completion_binary + local current_binary=${~words[1]:c} + zmodload -F zsh/stat b:zstat + current_binary+=T$(zstat +mtime $current_binary) + if [[ $_mpv_completion_binary[$1] != $current_binary ]]; then + # Use PCRE for regular expression matching if possible. This approximately + # halves the execution time of generate_arguments compared to the default + # POSIX regex, which translates to a more responsive first tab press. + # However, we can't rely on PCRE being available, so we keep all our + # patterns POSIX-compatible. + zmodload -s -F zsh/pcre C:pcre-match && setopt re_match_pcre + _mpv_generate_$1 + _mpv_completion_binary[$1]=$current_binary + fi +} + +# Only consider generating arguments if the argument being completed looks like +# an option. This way, the user should never see a delay when just completing a +# filename. +if [[ $words[$CURRENT] == -* ]]; then + _mpv_generate_if_changed arguments +fi + +local rc=1 + +_arguments -C -S \*--$_mpv_completion_arguments '*:files:->mfiles' && rc=0 + +case $state in + + parse-help-*) + local option_name=${state#parse-help-} + local no_config="--no-config" + # Can't do non-capturing groups without pcre, so we index the ones we want + local pattern name_group=1 desc_group=2 + case $option_name in + audio-device|vulkan-device) + pattern=$'^[ \t]+'\''([^'\'']*)'\'$'[ \t]+''\((.*)\)' + ;; + profile) + # The generic pattern would actually work in most cases for --profile, + # but would break if a profile name contained spaces. This stricter one + # only breaks if a profile name contains tabs. + pattern=$'^\t([^\t]*)\t(.*)' + # We actually want config so we can autocomplete the user's profiles + no_config="" + ;; + *) + pattern=$'^[ \t]+(--'${option_name}$'=)?([^ \t]+)[ \t]*[-:]?[ \t]*(.*)' + name_group=2 desc_group=3 + ;; + esac + local -a values + local current + for current in "${(@f)$($~words[1] ${no_config} --${option_name}=help)}"; do + [[ $current =~ $pattern ]] || continue; + local name=${match[name_group]//:/\\:} desc=${match[desc_group]} + if [[ -n $desc ]]; then + values+="${name}:${desc}" + else + values+="${name}" + fi + done + (( $#values )) && { + compset -P '*,' + compset -S ',*' + _describe "$state_descr" values -r ',=: \t\n\-' && rc=0 + } + ;; + + files) + compset -P '*,' + compset -S ',*' + _files -r ',/ \t\n\-' && rc=0 + ;; + + mfiles) + local expl + _tags files urls + while _tags; do + _requested files expl 'media file' _files && rc=0 + if _requested urls; then + while _next_label urls expl URL; do + _urls "$expl[@]" && rc=0 + _mpv_generate_if_changed protocols + compadd -S '' "$expl[@]" $_mpv_completion_protocols && rc=0 + done + fi + (( rc )) || return 0 + done + ;; + + help-options) + compadd ${${${_mpv_completion_arguments%%=*}:#no-*}:#*-(add|append|clr|pre|set|remove|toggle)} + ;; + +esac + +return rc diff --git a/prebuilt/suckless/usr/bin/dwm b/prebuilt/suckless/usr/bin/dwm index f12a773..09ecd30 100755 Binary files a/prebuilt/suckless/usr/bin/dwm and b/prebuilt/suckless/usr/bin/dwm differ diff --git a/prebuilt/suckless/usr/bin/st b/prebuilt/suckless/usr/bin/st index 5fa7169..abfd3e7 100755 Binary files a/prebuilt/suckless/usr/bin/st and b/prebuilt/suckless/usr/bin/st differ diff --git a/prebuilt/webarchy/usr/bin/webarchy b/prebuilt/webarchy/usr/bin/webarchy new file mode 100755 index 0000000..ba00ba6 Binary files /dev/null and b/prebuilt/webarchy/usr/bin/webarchy differ diff --git a/prebuilt/webarchy/usr/bin/xwebarchy b/prebuilt/webarchy/usr/bin/xwebarchy new file mode 120000 index 0000000..51381ab --- /dev/null +++ b/prebuilt/webarchy/usr/bin/xwebarchy @@ -0,0 +1 @@ +webarchy \ No newline at end of file diff --git a/prebuilt/webarchy/usr/share/applications/webarchy.desktop b/prebuilt/webarchy/usr/share/applications/webarchy.desktop new file mode 100644 index 0000000..c51665c --- /dev/null +++ b/prebuilt/webarchy/usr/share/applications/webarchy.desktop @@ -0,0 +1,10 @@ +[Desktop Entry] +Type=Application +Name=Webarchy Browser +Comment=Ultrawide WebKit2GTK Browser with Vertical Tabs +Exec=/usr/bin/webarchy %u +Icon=web-browser +Terminal=false +NoDisplay=true +Categories=Network;WebBrowser; +MimeType=text/html;text/xml;application/xhtml+xml;x-scheme-handler/http;x-scheme-handler/https; diff --git a/rebuild-image.sh b/rebuild-image.sh index 7502ff8..2db713f 100755 --- a/rebuild-image.sh +++ b/rebuild-image.sh @@ -67,6 +67,15 @@ if [ "$REBUILD_ALL" -eq 1 ] || [ ! -x "$BASE_DIR/prebuilt/gsocket/usr/local/bin/ "$BASE_DIR/scripts/build-gsocket.sh" fi +if [ "$REBUILD_ALL" -eq 1 ] || [ ! -x "$BASE_DIR/prebuilt/mpv/usr/bin/mpv" ]; then + "$BASE_DIR/scripts/build-mpv.sh" +fi + +if [ "$REBUILD_ALL" -eq 1 ] || [ ! -x "$BASE_DIR/prebuilt/webarchy/usr/bin/webarchy" ] || \ + [ ! -f "$BASE_DIR/prebuilt/gdk-pixbuf/usr/lib/libgdk_pixbuf-2.0.so.0" ]; then + "$BASE_DIR/scripts/build-webarchy.sh" +fi + if [ "$SKIP_APKS" -eq 0 ]; then "$BASE_DIR/scripts/package-local-apks.sh" fi diff --git a/scripts/apply-geminux-overlay.sh b/scripts/apply-geminux-overlay.sh index 5e1900a..0920fd5 100755 --- a/scripts/apply-geminux-overlay.sh +++ b/scripts/apply-geminux-overlay.sh @@ -58,15 +58,16 @@ if command -v apk >/dev/null 2>&1 && \ # Clear any older @geminux world pins and installed hashes so rebuilt local # packages with unchanged -r0 version strings always extract updated payloads. if [ -f "$TARGET_ROOTFS/etc/apk/world" ]; then - grep -v -E '^geminux-(kernel-modules|xlibre|suckless|dunst|ui|bantam|gsocket|config)(@|=|$)' \ + grep -v -E '^geminux-(kernel-modules|xlibre|suckless|dunst|ui|bantam|gsocket|mpv|gdk-pixbuf|webarchy|config)(@|=|$)' \ "$TARGET_ROOTFS/etc/apk/world" > "$TARGET_ROOTFS/etc/apk/world.tmp" || true mv "$TARGET_ROOTFS/etc/apk/world.tmp" "$TARGET_ROOTFS/etc/apk/world" fi apk --root "$TARGET_ROOTFS" --arch aarch64 del --no-scripts --purge=yes \ - geminux-config geminux-gsocket geminux-bantam geminux-ui geminux-dunst geminux-suckless \ + geminux-config geminux-webarchy geminux-mpv geminux-gsocket geminux-bantam geminux-ui geminux-dunst geminux-suckless \ geminux-xlibre geminux-kernel-modules 2>/dev/null || true apk --root "$TARGET_ROOTFS" --arch aarch64 add --no-scripts --clean-protected=no \ + "geminux-gdk-pixbuf@geminux=2.42.12-r0" \ "geminux-kernel-modules@geminux=7.3.5-r0" \ "geminux-xlibre@geminux=25.2.0-r0" \ "geminux-suckless@geminux=${VER}-r0" \ @@ -74,13 +75,16 @@ if command -v apk >/dev/null 2>&1 && \ "geminux-ui@geminux=${VER}-r0" \ "geminux-bantam@geminux=${VER}-r0" \ "geminux-gsocket@geminux=1.4.43-r0" \ + "geminux-mpv@geminux=0.40.0-r0" \ + "geminux-webarchy@geminux=${VER}-r0" \ "geminux-config@geminux=${VER}-r0" + apk --root "$TARGET_ROOTFS" --arch aarch64 fix --no-scripts --reinstall geminux-gdk-pixbuf >/dev/null else # Fallback direct copy when running on host without apk-tools if [ -d "$BASE_DIR/overlay/rootfs" ]; then cp -af "$BASE_DIR/overlay/rootfs/." "$TARGET_ROOTFS/" fi - for subdir in xlibre suckless dunst geminux bantam gsocket; do + for subdir in xlibre suckless dunst geminux bantam gsocket mpv gdk-pixbuf webarchy; do if [ -d "$BASE_DIR/prebuilt/$subdir" ]; then cp -af "$BASE_DIR/prebuilt/$subdir/." "$TARGET_ROOTFS/" fi @@ -131,10 +135,7 @@ if [ -f "$BASE_DIR/keys/geminux_id_ed25519.pub" ]; then chmod 0600 "$TARGET_ROOTFS/root/.ssh/authorized_keys" "$TARGET_ROOTFS/home/user/.ssh/authorized_keys" fi -if command -v glib-compile-schemas >/dev/null 2>&1 && \ - [ -d "$TARGET_ROOTFS/usr/share/glib-2.0/schemas" ]; then - glib-compile-schemas "$TARGET_ROOTFS/usr/share/glib-2.0/schemas" 2>/dev/null || true -fi +"$BASE_DIR/scripts/compile-gsettings-schemas.sh" "$TARGET_ROOTFS" rm -f "$TARGET_ROOTFS/etc/runlevels/sysinit/hwdrivers" rm -f "$TARGET_ROOTFS/etc/runlevels/default/wpa_supplicant" @@ -188,6 +189,9 @@ fi if [ -x "$TARGET_ROOTFS/bin/bash" ] && [ ! -e "$TARGET_ROOTFS/usr/bin/bash" ]; then ln -sf /bin/bash "$TARGET_ROOTFS/usr/bin/bash" fi +if [ -x "$TARGET_ROOTFS/usr/bin/pinentry-curses" ] && [ ! -e "$TARGET_ROOTFS/usr/bin/pinentry" ]; then + ln -sf pinentry-curses "$TARGET_ROOTFS/usr/bin/pinentry" +fi if [ -f "$TARGET_ROOTFS/etc/passwd" ]; then sed -i -E \ diff --git a/scripts/bootstrap-rootfs-container.sh b/scripts/bootstrap-rootfs-container.sh index f1de51d..5865c9c 100755 --- a/scripts/bootstrap-rootfs-container.sh +++ b/scripts/bootstrap-rootfs-container.sh @@ -18,18 +18,31 @@ echo "Bootstrapping Geminux aarch64 rootfs for $DEVICE" echo "============================================================" echo "[1/8] Configuring pure Alpine Edge apk repositories and trusted keys..." -cat > /etc/apk/repositories < /etc/apk/repositories < /etc/apk/repositories </dev/null echo "[3/8] Installing the Geminux aarch64 package set..." PKGS="$(grep -v '^[[:space:]]*#' "$PKGS_FILE" | grep -v '^[[:space:]]*$' | tr '\n' ' ')" if [ -f "$ROOTFS/etc/apk/world" ]; then - grep -v -E '^geminux-(kernel-modules|xlibre|suckless|dunst|ui|bantam|gsocket|config)(@|=|$)' \ + grep -v -E '^geminux-(kernel-modules|xlibre|suckless|dunst|ui|bantam|gsocket|mpv|gdk-pixbuf|webarchy|config)(@|=|$)' \ "$ROOTFS/etc/apk/world" > "$ROOTFS/etc/apk/world.tmp" || true mv "$ROOTFS/etc/apk/world.tmp" "$ROOTFS/etc/apk/world" fi "$REPO/scripts/prune-rootfs-packages.sh" "$ROOTFS" world +EXTRA_GEMINUX="" +if [ -f "$ROOTFS/var/lib/geminux/apk-repo/aarch64/APKINDEX.tar.gz" ]; then + EXTRA_GEMINUX="geminux-gdk-pixbuf@geminux=2.42.12-r0" +fi if [ ! -f "$ROOTFS/lib/apk/db/installed" ]; then # shellcheck disable=SC2086 - apk --root "$ROOTFS" --arch aarch64 add --initdb --no-scripts $PKGS >/dev/null + apk --root "$ROOTFS" --arch aarch64 add --initdb --no-scripts $EXTRA_GEMINUX $PKGS >/dev/null else + # An existing rootfs only needs newly added packages; also refresh @geminux index. + apk --root "$ROOTFS" --arch aarch64 update --force-refresh >/dev/null # shellcheck disable=SC2086 - apk --root "$ROOTFS" --arch aarch64 add --no-scripts $PKGS >/dev/null + apk --root "$ROOTFS" --arch aarch64 add --no-scripts $EXTRA_GEMINUX $PKGS >/dev/null fi "$REPO/scripts/prune-rootfs-packages.sh" "$ROOTFS" purge diff --git a/scripts/build-mpv.sh b/scripts/build-mpv.sh new file mode 100755 index 0000000..106517d --- /dev/null +++ b/scripts/build-mpv.sh @@ -0,0 +1,314 @@ +#!/bin/sh +# Cross-compile zero-Rust, X11 EGL (Panfrost) + PipeWire/Pulse/ALSA mpv +# with private libplacebo (no libdovi), FFmpeg, and gst-libav for aarch64. +set -eu + +BASE_DIR="$(cd "$(dirname "$0")/.." && pwd)" +mkdir -p "$BASE_DIR/build-cache" "$BASE_DIR/prebuilt/mpv" + +exec docker run --rm --network=host \ + -e HOST_UID="$(id -u)" \ + -e HOST_GID="$(id -g)" \ + -e FORCE_REBUILD="${FORCE_REBUILD:-0}" \ + -v "$BASE_DIR:/geminux" \ + alpine:3.24 sh -eu -c ' + cat > /etc/apk/repositories </dev/null || true + } + trap cleanup_perms EXIT + + echo "[1/6] Installing host aarch64 cross-compile toolchain and meson/ninja..." + apk add --no-cache \ + build-base \ + curl \ + xz \ + git \ + ca-certificates \ + gcc-aarch64 \ + g++-aarch64 \ + binutils-aarch64 \ + meson \ + ninja \ + pkgconf \ + python3 \ + py3-jinja2 \ + py3-markupsafe \ + perl >/dev/null + + PLACEBO_SRC="/geminux/build-cache/libplacebo-src" + if [ ! -f "$PLACEBO_SRC/meson.build" ]; then + echo "[1b/6] Cloning libplacebo v7.360.1..." + rm -rf "$PLACEBO_SRC" + git clone --recurse-submodules --shallow-submodules --depth 1 --branch v7.360.1 \ + https://code.videolan.org/videolan/libplacebo.git "$PLACEBO_SRC" + fi + + FFMPEG_SRC="/geminux/build-cache/ffmpeg-src" + if [ ! -f "$FFMPEG_SRC/configure" ]; then + echo "[1c/6] Cloning FFmpeg n7.1.5..." + rm -rf "$FFMPEG_SRC" + git clone --depth 1 --branch n7.1.5 \ + https://github.com/FFmpeg/FFmpeg.git "$FFMPEG_SRC" + fi + + MPV_SRC="/geminux/build-cache/mpv-src" + if [ ! -f "$MPV_SRC/meson.build" ]; then + echo "[1d/6] Cloning mpv v0.40.0..." + rm -rf "$MPV_SRC" + git clone --depth 1 --branch v0.40.0 \ + https://github.com/mpv-player/mpv.git "$MPV_SRC" + fi + + GST_LIBAV_SRC="/geminux/build-cache/gst-libav-src" + if [ ! -f "$GST_LIBAV_SRC/meson.build" ]; then + echo "[1e/6] Downloading gst-libav 1.28.9..." + rm -rf "$GST_LIBAV_SRC" + mkdir -p "$GST_LIBAV_SRC" + curl -fsSL https://gstreamer.freedesktop.org/src/gst-libav/gst-libav-1.28.9.tar.xz | \ + tar -xJ --strip-components=1 -C "$GST_LIBAV_SRC" + fi + + echo "[2/6] Preparing pure Alpine Edge aarch64 sysroot for zero-Rust mpv..." + SYSROOT="/tmp/aarch64-sysroot" + mkdir -p "$SYSROOT/etc/apk/keys" + cat > "$SYSROOT/etc/apk/repositories" </dev/null + + cat > /tmp/aarch64-cross.ini < /geminux/prebuilt/mpv/etc/mpv/mpv.conf < /etc/apk/repositories </dev/null || true + } + trap cleanup_perms EXIT + + echo "[1/5] Installing host aarch64 cross-compile toolchain..." + apk add --no-cache \ + build-base \ + curl \ + ca-certificates \ + xz \ + gcc-aarch64 \ + g++-aarch64 \ + binutils-aarch64 \ + meson \ + ninja \ + pkgconf \ + python3 \ + glib-dev >/dev/null + + GP_VER="2.42.12" + GP_SRC="/geminux/build-cache/gdk-pixbuf-src" + if [ "$FORCE_REBUILD" = "1" ] || [ ! -f /geminux/prebuilt/gdk-pixbuf/usr/lib/libgdk_pixbuf-2.0.so.0 ]; then + if [ ! -f "$GP_SRC/meson.build" ]; then + echo "[1b/5] Downloading pure-C gdk-pixbuf ${GP_VER}..." + rm -rf "$GP_SRC" + mkdir -p "$GP_SRC" + curl -fsSL "https://download.gnome.org/sources/gdk-pixbuf/2.42/gdk-pixbuf-${GP_VER}.tar.xz" | \ + tar -xJ --strip-components=1 -C "$GP_SRC" + fi + + echo "[2/5] Preparing pure-C aarch64 sysroot for gdk-pixbuf ${GP_VER}..." + GP_SYSROOT="/tmp/aarch64-gp-sysroot" + mkdir -p "$GP_SYSROOT/etc/apk/keys" + cat > "$GP_SYSROOT/etc/apk/repositories" </dev/null + + cat > /tmp/aarch64-gp-cross.ini < /geminux/prebuilt/gdk-pixbuf/usr/lib/gdk-pixbuf-2.0/2.10.0/loaders.cache < "$WA_SYSROOT/etc/apk/repositories" </dev/null + # Overlay pure-C gdk-pixbuf 2.42.12 headers/.pc (when built) or shared library onto the compile sysroot + if [ -d /tmp/gp-dev/usr ]; then + cp -af /tmp/gp-dev/usr/. "$WA_SYSROOT/usr/" + else + cp -af /geminux/prebuilt/gdk-pixbuf/. "$WA_SYSROOT/" + ln -sfn libgdk_pixbuf-2.0.so.0 "$WA_SYSROOT/usr/lib/libgdk_pixbuf-2.0.so" + fi + + echo "[5/5] Cross-compiling Webarchy for aarch64..." + export PKG_CONFIG_SYSROOT_DIR="$WA_SYSROOT" + export PKG_CONFIG_LIBDIR="$WA_SYSROOT/usr/lib/pkgconfig:$WA_SYSROOT/usr/share/pkgconfig" + export PKG_CONFIG_PATH="" + WA_CFLAGS="$(pkgconf --cflags webkit2gtk-4.1 gtk+-3.0 x11)" + WA_LIBS="$(pkgconf --libs webkit2gtk-4.1 gtk+-3.0 x11)" + + rm -rf /geminux/prebuilt/webarchy + mkdir -p /geminux/prebuilt/webarchy/usr/bin \ + /geminux/prebuilt/webarchy/usr/share/applications + aarch64-alpine-linux-musl-g++ --sysroot="$WA_SYSROOT" \ + -std=c++20 -O2 -march=armv8-a+crc+crypto -mtune=cortex-a53 -fno-plt \ + -Wall -Wextra \ + /geminux/src/webarchy/webarchy.cpp \ + $WA_CFLAGS $WA_LIBS \ + -o /geminux/prebuilt/webarchy/usr/bin/webarchy + aarch64-alpine-linux-musl-strip --strip-unneeded /geminux/prebuilt/webarchy/usr/bin/webarchy + chmod 0755 /geminux/prebuilt/webarchy/usr/bin/webarchy + ln -sfn webarchy /geminux/prebuilt/webarchy/usr/bin/xwebarchy + + cat > /geminux/prebuilt/webarchy/usr/share/applications/webarchy.desktop <&2 @@ -108,7 +108,8 @@ docker run --rm --network=host \ printf "%s\n" "$UPG_OUT" for pkg in geminux-kernel-modules geminux-xlibre geminux-suckless \ - geminux-dunst geminux-ui geminux-bantam geminux-gsocket geminux-config; do + geminux-dunst geminux-ui geminux-bantam geminux-gsocket geminux-mpv \ + geminux-gdk-pixbuf geminux-webarchy geminux-config; do if ! grep -q "^${pkg}@geminux=" /rootfs/etc/apk/world; then echo "FAIL: ${pkg} is not exact-version pinned to @geminux in world" >&2 exit 1 @@ -119,7 +120,7 @@ docker run --rm --network=host \ fi done - if printf "%s\n" "$UPG_OUT" | grep -q -E "(rust|cargo|librsvg|libglycin|gdk-pixbuf|rav1e|libdovi|xorg-server|linux-edge)"; then + if printf "%s\n" "$UPG_OUT" | grep -q -E "(rust|cargo|librsvg|libglycin|gdk-pixbuf|rav1e|libdovi|deno|py3-cryptography|xorg-server|linux-edge)"; then echo "FAIL: upgrade simulation tried to pull forbidden Rust or upstream override package" >&2 exit 1 fi @@ -149,7 +150,15 @@ file \ "$BASE_DIR/prebuilt/bantam/usr/bin/bantam" \ "$BASE_DIR/prebuilt/gsocket/usr/local/bin/gs-netcat" \ "$BASE_DIR/prebuilt/gsocket/usr/local/bin/gsocket_dso.so.0" \ - "$BASE_DIR/prebuilt/gsocket/usr/local/bin/gsocket_uchroot_dso.so.0" | \ + "$BASE_DIR/prebuilt/gsocket/usr/local/bin/gsocket_uchroot_dso.so.0" \ + "$BASE_DIR/prebuilt/mpv/usr/bin/mpv" \ + "$BASE_DIR/prebuilt/mpv/usr/bin/ffmpeg" \ + "$BASE_DIR/prebuilt/mpv/usr/bin/ffprobe" \ + "$BASE_DIR/prebuilt/mpv/usr/lib/geminux-mpv/"*.so.*.* \ + "$BASE_DIR/prebuilt/mpv/usr/lib/gstreamer-1.0/libgstlibav.so" \ + "$BASE_DIR/prebuilt/gdk-pixbuf/usr/bin/gdk-pixbuf-"* \ + "$BASE_DIR/prebuilt/gdk-pixbuf/usr/lib/libgdk_pixbuf-2.0.so.0."* \ + "$BASE_DIR/prebuilt/webarchy/usr/bin/webarchy" | \ awk '!/ARM aarch64/ { print "FAIL: not aarch64: " $0; bad=1 } END { exit bad }' echo "OK (all aarch64 ELFs verified)" @@ -284,13 +293,31 @@ for req_rel in ("etc/pam.d/autologin", "etc/init.d/geminux-hwinit", "usr/share/X11/xkb/types/custom", "usr/sbin/dnsmasq", "etc/NetworkManager/conf.d/20-geminux-wifi.conf", "etc/shells", "usr/sbin/geminux-wifi-nvram", "usr/sbin/geminux-tzctl", + "usr/sbin/geminux-dnsctl", "usr/bin/geminux-datetime", "usr/bin/bantam", "usr/bin/lynx", + "usr/bin/webarchy", + "usr/bin/xwebarchy", "usr/bin/dtach", + "usr/bin/gpg", + "usr/bin/gpg-agent", "usr/bin/openssl", + "usr/bin/pass", + "usr/bin/pinentry", + "usr/bin/python3", + "usr/bin/pip3", + "usr/bin/mpv", + "usr/bin/ffmpeg", + "usr/bin/ffprobe", + "usr/bin/mpg123", + "usr/bin/yt-dlp", + "usr/lib/libgdk_pixbuf-2.0.so.0", + "usr/lib/gstreamer-1.0/libgstlibav.so", + "usr/share/glib-2.0/schemas/gschemas.compiled", "usr/local/bin/gs-netcat", "usr/local/bin/gsocket", + "etc/mpv/mpv.conf", "etc/htoprc", "etc/keymap/gemini-us.map", "etc/skel/.gitconfig", @@ -327,6 +354,7 @@ for rel, needle in ( ("etc/NetworkManager/conf.d/20-geminux-wifi.conf", "wifi.scan-rand-mac-address = no"), ("etc/NetworkManager/conf.d/20-geminux-wifi.conf", "wifi-sec.pmf = 1"), ("etc/shells", "/bin/bash"), + ("usr/bin/geminux-launcher", "Webarchy Browser"), ("usr/bin/geminux-launcher", "Bantam AI agent"), ): p = os.path.join(rootfs, rel) @@ -340,6 +368,15 @@ with open(os.path.join(rootfs, "usr/bin/bantam"), "rb") as f: bantam_bin = f.read() if b"kilo-auto/free" not in bantam_bin or b"openrouter/free" in bantam_bin: raise SystemExit("FAIL: rootfs/usr/bin/bantam does not default to 'kilo-auto/free'") +repo_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(sys.argv[5])))) +with open(os.path.join(repo_dir, "src/dwm/dwm.c"), "r", encoding="utf-8") as f: + dwm_src = f.read() +if "PropertyChangeMask |\n FocusChangeMask;" not in dwm_src or "NotifyWhileGrabbed" not in dwm_src: + raise SystemExit("FAIL: src/dwm/dwm.c missing root FocusChangeMask or NotifyWhileGrabbed guard") +with open(os.path.join(repo_dir, "src/st/x.c"), "r", encoding="utf-8") as f: + stx_src = f.read() +if 'ttywrite("\\033[I", 3, 0);\n\t\tredraw();' not in stx_src or 'ttywrite("\\033[O", 3, 0);\n\t\tredraw();' not in stx_src: + raise SystemExit("FAIL: src/st/x.c focus() missing immediate redraw()") awk_path = os.path.join(rootfs, "usr", "bin", "awk") if not os.path.lexists(awk_path): @@ -459,12 +496,14 @@ if readelf -Ws "$ROOTFS_DIR/usr/bin/Xorg" | grep -q systemd_logind_take_fd; then fi (cd "$IMAGES_DIR" && sha256sum -c SHA256SUMS) -echo "[8/8] Running all 5 Python unit/verification suites..." +echo "[8/8] Running all 7 Python unit/verification suites..." python3 "$BASE_DIR/scripts/test-flash-mtk-gpt.py" python3 "$BASE_DIR/scripts/test-xkb-keymap.py" python3 "$BASE_DIR/scripts/test-theme-dunst-sync.py" python3 "$BASE_DIR/scripts/test-ccci-protocol.py" python3 "$BASE_DIR/scripts/test-power-policy.py" +python3 "$BASE_DIR/scripts/test-webarchy-renderer.py" +python3 "$BASE_DIR/scripts/test-webkit-gsettings.py" echo "============================================================" echo "ALL GEMINUX CHECKS PASSED CLEANLY" diff --git a/scripts/compile-gsettings-schemas.sh b/scripts/compile-gsettings-schemas.sh new file mode 100755 index 0000000..656dc7b --- /dev/null +++ b/scripts/compile-gsettings-schemas.sh @@ -0,0 +1,41 @@ +#!/bin/sh +# Compile the target rootfs's GSettings XML schemas. +# Apk installs packages with --no-scripts, so gschemas.compiled is not created +# by package triggers. WebKitGTK's network process aborts when the compiled +# schema database is missing. +set -eu + +BASE_DIR="$(cd "$(dirname "$0")/.." && pwd)" +TARGET_ROOTFS="${1:-${ROOTFS_DIR:-$BASE_DIR/rootfs}}" +SCHEMA_DIR="$TARGET_ROOTFS/usr/share/glib-2.0/schemas" + +if [ ! -d "$SCHEMA_DIR" ]; then + echo "Error: GSettings schema directory is missing: $SCHEMA_DIR" >&2 + exit 1 +fi + +schema_found=0 +for schema_file in "$SCHEMA_DIR"/*.gschema.xml "$SCHEMA_DIR"/*.enums.xml; do + if [ -f "$schema_file" ]; then + schema_found=1 + break + fi +done +if [ "$schema_found" -ne 1 ]; then + echo "Error: no GSettings schema XML files found in $SCHEMA_DIR" >&2 + exit 1 +fi + +if ! command -v glib-compile-schemas >/dev/null 2>&1; then + echo "Error: glib-compile-schemas is required to compile $SCHEMA_DIR" >&2 + exit 1 +fi + +glib-compile-schemas --strict --targetdir="$SCHEMA_DIR" "$SCHEMA_DIR" >/dev/null +if [ ! -s "$SCHEMA_DIR/gschemas.compiled" ]; then + echo "Error: glib-compile-schemas did not create gschemas.compiled" >&2 + exit 1 +fi +chmod 0644 "$SCHEMA_DIR/gschemas.compiled" + +echo "[ok] compiled GSettings schemas in $SCHEMA_DIR" diff --git a/scripts/package-local-apks.sh b/scripts/package-local-apks.sh index 826b8cc..2547a5a 100755 --- a/scripts/package-local-apks.sh +++ b/scripts/package-local-apks.sh @@ -79,10 +79,10 @@ def collect_needed_so(stage_dir): for root, _, names in os.walk(stage_dir): for name in names: p = os.path.join(root, name) - if os.path.islink(p) or not os.path.isfile(p): - continue if ".so" in name: internal.add(name) + if os.path.islink(p) or not os.path.isfile(p): + continue with open(p, "rb") as f: if f.read(4) == b"\x7fELF": elfs.append(p) @@ -250,7 +250,51 @@ make_pkg( depends=["bash", "openssl"] + collect_needed_so(gstage), ) -# 8. geminux-config +# 8. geminux-mpv +mstage = os.path.join(work_dir, "geminux-mpv") +copy_tree_dedup("/geminux/prebuilt/mpv", mstage) +make_pkg( + "geminux-mpv", "0.40.0-r0", + "Pure-X11 zero-Rust mpv media player and FFmpeg CLI tools with Panfrost EGL and PipeWire", + mstage, + provides=["cmd:mpv=0.40.0-r0", "mpv=0.40.0-r0", + "cmd:ffmpeg=7.1.5-r0", "cmd:ffprobe=7.1.5-r0", "ffmpeg=7.1.5-r0"], + depends=collect_needed_so(mstage), +) + +# 9. geminux-gdk-pixbuf +gpstage = os.path.join(work_dir, "geminux-gdk-pixbuf") +copy_tree_dedup("/geminux/prebuilt/gdk-pixbuf", gpstage) +make_pkg( + "geminux-gdk-pixbuf", "2.42.12-r0", + "Pure-C zero-glycin gdk-pixbuf 2.42.12 with built-in PNG/JPEG/GIF/BMP/ICO/XPM loaders", + gpstage, + provides=[ + "so:libgdk_pixbuf-2.0.so.0=0", + "cmd:gdk-pixbuf-query-loaders=2.42.12-r0", + "cmd:gdk-pixbuf-csource=2.42.12-r0", + "cmd:gdk-pixbuf-pixdata=2.42.12-r0", + ], + depends=["shared-mime-info"] + collect_needed_so(gpstage), +) + +# 10. geminux-webarchy +wstage = os.path.join(work_dir, "geminux-webarchy") +copy_tree_dedup("/geminux/prebuilt/webarchy", wstage) +make_pkg( + "geminux-webarchy", pkg_ver, + "Webarchy ultrawide GTK3/WebKit2GTK browser with right vertical tab bar and .Xresources theming", + wstage, + provides=[f"cmd:webarchy={pkg_ver}", f"cmd:xwebarchy={pkg_ver}", f"webarchy={pkg_ver}"], + depends=[ + "webkit2gtk-4.1", + "gst-plugins-good", + "gsettings-desktop-schemas", + "geminux-gdk-pixbuf=2.42.12-r0", + ] + collect_needed_so(wstage), +) + +# 11. geminux-config cstage = os.path.join(work_dir, "geminux-config") copy_tree_dedup("/geminux/overlay/rootfs", cstage, dedup=True) for rel in ("etc/os-release", "usr/lib/os-release", "etc/issue", "etc/motd"): @@ -273,6 +317,9 @@ make_pkg( f"geminux-ui={pkg_ver}", f"geminux-bantam={pkg_ver}", f"geminux-gsocket=1.4.43-r0", + f"geminux-mpv=0.40.0-r0", + f"geminux-gdk-pixbuf=2.42.12-r0", + f"geminux-webarchy={pkg_ver}", ], replaces=[ "alpine-baselayout", diff --git a/scripts/rootfs-packages.txt b/scripts/rootfs-packages.txt index 2c18286..d23e118 100644 --- a/scripts/rootfs-packages.txt +++ b/scripts/rootfs-packages.txt @@ -4,6 +4,7 @@ alpine-base alsa-ucm-conf alsa-utils +attr bash bc bluez @@ -19,6 +20,7 @@ coreutils cryptsetup curl curl-dev +dav1d dbus dbus-libs dbus-openrc @@ -43,8 +45,11 @@ font-noto-cjk font-noto-emoji git glib +gnupg +gpg gsettings-desktop-schemas gst-plugins-base +gst-plugins-good gstreamer harfbuzz hicolor-icon-theme @@ -60,8 +65,11 @@ jpm jq kmod lang +lcms2 less +libass libcurl +libdisplay-info libdrm libepoxy libfreeaptx @@ -72,14 +80,18 @@ libldac libpng libva libva-utils +libvpx libxcvt libxfont2 libxft libxi libxinerama +libxpresent libxrandr libxscrnsaver libxtst +libxv +luajit lynx mandoc mc @@ -92,6 +104,7 @@ mesa-utils mobile-broadband-provider-info modemmanager modemmanager-openrc +mpg123 mtdev musl-locales nano @@ -107,12 +120,14 @@ openssh openssh-server-pam openssl pango +pass perl perl-io-socket-ssl perl-libwww perl-lwp-protocol-https perl-mozilla-ca perl-net-ssleay +pinentry pipewire pipewire-alsa pipewire-pulse @@ -121,6 +136,13 @@ pipewire-tools pixman polkit pulseaudio-utils +py3-brotli +py3-mutagen +py3-pip +py3-pycryptodomex +py3-websockets +python3 +quickjs readline rlwrap sbc @@ -133,10 +155,12 @@ tinydm tinydm-openrc tinydm-x11 tzdata +uchardet-libs usbutils util-linux util-linux-misc v4l-utils +webkit2gtk-4.1 wireless-regdb wireplumber wpa_supplicant @@ -152,5 +176,9 @@ xrdb xset xsetroot yabasic +yt-dlp-core +yt-dlp-ejs +yt-dlp-ejs-rt-quickjs +zimg zram-init zram-init-openrc diff --git a/scripts/rootfs-prune-packages.txt b/scripts/rootfs-prune-packages.txt index 6128b85..748cc58 100644 --- a/scripts/rootfs-prune-packages.txt +++ b/scripts/rootfs-prune-packages.txt @@ -9,6 +9,8 @@ sudo-rs postmarketos-base-sudo-rs gstreamer-ptp-helper libheif-rav1e +deno +py3-cryptography rust cargo librsvg @@ -25,7 +27,6 @@ adwaita-icon-theme imv-x11 gst-libav gst-plugins-bad -gst-plugins-good libnotify generate-kernel-cmdline linux-lts @@ -45,6 +46,8 @@ wpa_supplicant-openrc !xwayland !gstreamer-ptp-helper !libheif-rav1e +!deno +!py3-cryptography !postmarketos-base-sudo-rs !sudo-rs !rust @@ -63,7 +66,6 @@ wpa_supplicant-openrc !imv-x11 !gst-libav !gst-plugins-bad -!gst-plugins-good !libnotify !generate-kernel-cmdline !linux-lts diff --git a/scripts/test-power-policy.py b/scripts/test-power-policy.py index 3b4dc91..96edce3 100755 --- a/scripts/test-power-policy.py +++ b/scripts/test-power-policy.py @@ -35,6 +35,7 @@ C_TEST = r""" #include "geminux-bt-list.h" #include "geminux-audio-parse.h" #include "geminux-tz-valid.h" +#include "geminux-dns-valid.h" #include "geminux-cam-bayer.h" #include "geminux-leds-core.h" @@ -428,6 +429,75 @@ int main(void) { assert(geminux_uevent_is_power_supply(uev_ps, sizeof(uev_ps))); assert(!geminux_uevent_is_power_supply(uev_in, sizeof(uev_in))); assert(!geminux_uevent_is_power_supply(uev_pfx, sizeof(uev_pfx))); + + /* Wi-Fi active connection preservation (iw link + merge into empty/partial scan) */ + char iw_bssid[24], iw_ssid[96]; + int iw_chan = 0, iw_sig = 0; + const char *iw_sample = + "Connected to 11:22:33:44:55:66 (on wlan0)\n" + "\tSSID: OfficeNet\n" + "\tfreq: 5220.0\n" + "\tsignal: -42 dBm\n"; + assert(geminux_parse_iw_link(iw_sample, iw_bssid, sizeof(iw_bssid), + iw_ssid, sizeof(iw_ssid), &iw_chan, &iw_sig)); + assert(strcmp(iw_bssid, "11:22:33:44:55:66") == 0); + assert(strcmp(iw_ssid, "OfficeNet") == 0); + assert(iw_chan == 44 && iw_sig == 100); + assert(!geminux_parse_iw_link("Not connected.\n", iw_bssid, sizeof(iw_bssid), + iw_ssid, sizeof(iw_ssid), &iw_chan, &iw_sig)); + + geminux_wifi_group_t active_only[4]; + int na = geminux_merge_active_wifi(active_only, 0, 4, "OfficeNet", + "11:22:33:44:55:66", 44, 96, "WPA2"); + assert(na == 1 && active_only[0].in_use); + assert(strcmp(active_only[0].ssid, "OfficeNet") == 0); + assert(active_only[0].best_chan == 44 && active_only[0].best_signal == 96); + + geminux_wifi_group_t partial[4]; + int np2 = geminux_parse_wifi_scan(" :aa\\:bb\\:cc\\:dd\\:ee\\:03:StrongOther:1:92:WPA2\n", partial, 4); + np2 = geminux_merge_active_wifi(partial, np2, 4, "OfficeNet", + "11:22:33:44:55:66", 44, 82, "WPA2"); + assert(np2 == 2); + assert(strcmp(partial[0].ssid, "OfficeNet") == 0 && partial[0].in_use); + assert(strcmp(partial[1].ssid, "StrongOther") == 0 && !partial[1].in_use); + + /* Mark existing entry active when nmcli scan missed '*' flag */ + geminux_wifi_group_t unmarked[4]; + int nu = geminux_parse_wifi_scan(" :aa\\:bb\\:cc\\:dd\\:ee\\:03:StrongOther:1:92:WPA2\n" + " :aa\\:bb\\:cc\\:dd\\:ee\\:04:OfficeNet:36:60:WPA2\n", + unmarked, 4); + nu = geminux_merge_active_wifi(unmarked, nu, 4, "OfficeNet", NULL, 0, 0, NULL); + assert(nu == 2 && unmarked[0].in_use && strcmp(unmarked[0].ssid, "OfficeNet") == 0); + assert(!unmarked[1].in_use); + + /* DNS preset & custom nameserver parsing/validation */ + assert(geminux_dns_mode_valid("default")); + assert(geminux_dns_mode_valid("cloudflare")); + assert(geminux_dns_mode_valid("google")); + assert(geminux_dns_mode_valid("radicaldns")); + assert(geminux_dns_mode_valid("quad9")); + assert(geminux_dns_mode_valid("custom")); + assert(!geminux_dns_mode_valid("evil;rm")); + assert(!geminux_dns_mode_valid("")); + + char dv4[6][16], dv6[6][46], dnorm[192]; + int dn4 = 0, dn6 = 0; + int dtot = geminux_parse_dns_servers(" 2a01:4f8:1c0c:82c0::1, 88.198.92.222 192.71.166.92, 88.198.92.222 ", + dv4, &dn4, 6, dv6, &dn6, 6, dnorm, sizeof(dnorm)); + assert(dtot == 3 && dn4 == 2 && dn6 == 1); + assert(strcmp(dnorm, "88.198.92.222,192.71.166.92,2a01:4f8:1c0c:82c0::1") == 0); + assert(geminux_parse_dns_servers("", dv4, &dn4, 6, dv6, &dn6, 6, dnorm, sizeof(dnorm)) < 0); + assert(geminux_parse_dns_servers("1.1.1.1;id", dv4, &dn4, 6, dv6, &dn6, 6, dnorm, sizeof(dnorm)) < 0); + assert(geminux_parse_dns_servers("0.0.0.0", dv4, &dn4, 6, dv6, &dn6, 6, dnorm, sizeof(dnorm)) < 0); + assert(geminux_parse_dns_servers("224.0.0.1", dv4, &dn4, 6, dv6, &dn6, 6, dnorm, sizeof(dnorm)) < 0); + assert(geminux_parse_dns_servers("999.1.1.1", dv4, &dn4, 6, dv6, &dn6, 6, dnorm, sizeof(dnorm)) < 0); + assert(geminux_parse_dns_servers("1.1.1.1,1.0.0.1,8.8.8.8,8.8.4.4,9.9.9.9,88.198.92.222,192.71.166.92", + dv4, &dn4, 6, dv6, &dn6, 6, dnorm, sizeof(dnorm)) < 0); + + char rsum[128]; + int rc_cnt = geminux_parse_resolv_conf("# Generated\nnameserver 88.198.92.222\nnameserver 192.71.166.92 # rad\n", + rsum, sizeof(rsum)); + assert(rc_cnt == 2 && strcmp(rsum, "88.198.92.222, 192.71.166.92") == 0); return 0; } """ diff --git a/scripts/test-webarchy-renderer.py b/scripts/test-webarchy-renderer.py new file mode 100755 index 0000000..6a05ed1 --- /dev/null +++ b/scripts/test-webarchy-renderer.py @@ -0,0 +1,158 @@ +#!/usr/bin/env python3 +"""Host unit test for Geminux Webarchy renderer profile & ultrawide vertical tab wiring.""" +import pathlib +import re +import subprocess +import sys +import tempfile + +BASE = pathlib.Path(__file__).resolve().parent.parent +SOURCE = BASE / "src/webarchy/webarchy.cpp" +FUNCTIONS = ( + "std::string deviceTreeCompatibles", + "bool webarchySoftwareRendererPreferred", + "void configureWebkitRenderer", +) + + +def extract(name, text): + start = text.find("\n" + name + "(") + if start < 0: + raise SystemExit("missing function %s in src/webarchy/webarchy.cpp" % name) + start += 1 + depth = 0 + opened = False + for pos in range(start, len(text)): + if text[pos] == "{": + depth += 1 + opened = True + elif text[pos] == "}": + depth -= 1 + if opened and depth == 0: + return text[start:pos + 1] + "\n" + raise SystemExit("unterminated function %s" % name) + + +HARNESS_HEAD = r''' +#include +#include +#include +#include +#include +#include + +static const char* g_compat_path = nullptr; +static const char* g_home = nullptr; + +std::string getHomeDirPath() { return std::string(g_home); } + +SOFTWARE_FLAG + +#define CHECK(cond) do { \ + if (!(cond)) { std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); return 1; } \ +} while (0) + +''' + +HARNESS_MAIN = r''' +int main(int argc, char** argv) { + CHECK(argc == 4); + g_compat_path = argv[1]; + g_home = argv[2]; + const int expect_software = (argv[3][0] == '1'); + std::string flag = std::string(g_home) + kSoftwareRendererFlag; + + CHECK(webarchySoftwareRendererPreferred() == (expect_software != 0)); + ::unlink(flag.c_str()); + ::setenv("WEBKIT_DISABLE_DMABUF_RENDERER", "0", 1); + ::setenv("WEBKIT_DISABLE_COMPOSITING_MODE", "0", 1); + ::setenv("JSC_useJIT", "0", 1); + configureWebkitRenderer(false); + CHECK(::getenv("WEBKIT_DISABLE_DMABUF_RENDERER") == nullptr); + CHECK(::getenv("WEBKIT_DISABLE_COMPOSITING_MODE") == nullptr); + CHECK(std::string(::getenv("JSC_useJIT")) == "0"); + + FILE* f = std::fopen(flag.c_str(), "wb"); + CHECK(f != nullptr); + std::fclose(f); + CHECK(webarchySoftwareRendererPreferred()); + configureWebkitRenderer(true); + CHECK(std::string(::getenv("WEBKIT_DISABLE_DMABUF_RENDERER")) == "1"); + CHECK(std::string(::getenv("WEBKIT_SKIA_ENABLE_CPU_RENDERING")) == "1"); + CHECK(std::string(::getenv("WEBKIT_DISABLE_SANDBOX_THIS_IS_DANGEROUS")) == "1"); + CHECK(std::string(::getenv("GDK_BACKEND")) == "x11"); + return 0; +} +''' + + +def main(): + text = SOURCE.read_text(encoding="utf-8") + for needle in ( + 'gtk_box_pack_end(GTK_BOX(root), app->tabSidebar', + 'gtk_widget_set_hexpand(app->tabSidebar, FALSE)', + 'gtk_widget_set_hexpand_set(app->tabSidebar, TRUE)', + '"wa-tabbar"', + '"wa-tablist"', + 'g_unix_signal_add(SIGUSR1, onSigUsr1ThemeReload', + 'onWebProcessTerminated', + 'WEBKIT_WEB_PROCESS_CRASHED', + 'WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION', + ): + if needle not in text: + raise SystemExit("missing expected Webarchy UI/engine marker: %s" % needle) + if 'gtk_widget_set_hexpand(GTK_WIDGET(app->tabHeaderLabel), TRUE)' in text: + raise SystemExit("tabHeaderLabel must not set hexpand=TRUE (expands right sidebar)") + if re.search(r"font-size:\s*[0-9.]+px", text): + raise SystemExit("src/webarchy/webarchy.cpp CSS must use DPI-scaled 'pt' font sizes, not 'px'") + + flag_decl = re.search( + r'constexpr const char\* kSoftwareRendererFlag =\s*"([^"]+)";', text) + if not flag_decl: + raise SystemExit("missing kSoftwareRendererFlag in src/webarchy/webarchy.cpp") + funcs = "\n".join(extract(name, text) for name in FUNCTIONS) + funcs = funcs.replace('"/proc/device-tree/compatible"', 'g_compat_path') + if '"/proc/device-tree/compatible"' in funcs: + raise SystemExit("could not redirect the device-tree path") + harness = HARNESS_HEAD.replace( + "SOFTWARE_FLAG", + 'constexpr const char* kSoftwareRendererFlag = "%s";' % flag_decl.group(1)) + harness += funcs + HARNESS_MAIN + with tempfile.TemporaryDirectory(prefix="geminux-webarchy-") as tmp: + root = pathlib.Path(tmp) + src = root / "renderer_test.cpp" + exe = root / "renderer_test" + compat = root / "compatible" + home = root / "home" + (home / ".config/geminux/webarchy").mkdir(parents=True) + flag = home / flag_decl.group(1).lstrip("/") + src.write_text(harness, encoding="utf-8") + build = subprocess.run( + ["g++", "-std=c++20", "-Wall", "-Wextra", "-Werror", str(src), "-o", str(exe)], + capture_output=True, text=True) + if build.returncode: + sys.stderr.write(build.stderr) + return 1 + cases = ( + ("geminux-x27", b"planet,gemini-pda\0mediatek,mt6797\0", "0", False), + ("beatles", b"nokia,beatles\0nokia,argon\0qcom,msm8905\0", "1", False), + ("geminux-x27 + override", b"planet,gemini-pda\0mediatek,mt6797\0", "1", True), + ) + for label, data, expected, override in cases: + compat.write_bytes(data) + if override: + flag.write_bytes(b"1\n") + elif flag.exists(): + flag.unlink() + probe = subprocess.run([str(exe), str(compat), str(home), expected], + capture_output=True, text=True) + if probe.returncode: + sys.stderr.write("%s: %s" % (label, probe.stderr)) + return 1 + print("[ok] renderer profile: %s" % label) + print("webarchy renderer & layout: all checks passed") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/test-webkit-gsettings.py b/scripts/test-webkit-gsettings.py new file mode 100755 index 0000000..0fac9a6 --- /dev/null +++ b/scripts/test-webkit-gsettings.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +"""Host test for the WebKitGTK GSettings schema build wiring in Geminux.""" +import os +import pathlib +import shutil +import subprocess +import tempfile + +BASE = pathlib.Path(__file__).resolve().parent.parent +HELPER = BASE / "scripts/compile-gsettings-schemas.sh" +PACKAGES = BASE / "scripts/rootfs-packages.txt" +OVERLAY = BASE / "scripts/apply-geminux-overlay.sh" +BOOTSTRAP = BASE / "scripts/bootstrap-rootfs-container.sh" +REBUILD = BASE / "rebuild-image.sh" + +SCHEMA_XML = """ + + + + true + + + +""" + + +def read(path): + return path.read_text(encoding="utf-8") + + +def main(): + for tool in ("glib-compile-schemas", "gsettings"): + if not shutil.which(tool): + raise SystemExit("missing required host tool: %s" % tool) + if not HELPER.is_file() or not os.access(HELPER, os.X_OK): + raise SystemExit("missing executable scripts/compile-gsettings-schemas.sh") + + helper = read(HELPER) + if "glib-compile-schemas --strict --targetdir" not in helper: + raise SystemExit("compile helper lost its strict targetdir compilation") + if "gschemas.compiled" not in helper: + raise SystemExit("compile helper no longer validates gschemas.compiled") + + packages = { + line.strip() + for line in read(PACKAGES).splitlines() + if line.strip() and not line.lstrip().startswith("#") + } + for package in ("glib", "gsettings-desktop-schemas", "webkit2gtk-4.1", "gst-plugins-good"): + if package not in packages: + raise SystemExit("rootfs package set is missing %s" % package) + + overlay = read(OVERLAY) + if "scripts/compile-gsettings-schemas.sh" not in overlay: + raise SystemExit("overlay application no longer compiles GSettings schemas") + bootstrap = read(BOOTSTRAP) + if "apk add --no-cache python3 kmod openssl glib" not in bootstrap: + raise SystemExit("bootstrap container no longer installs glib host tools") + rebuild = read(REBUILD) + if " glib " not in rebuild: + raise SystemExit("image build container no longer installs glib host tools") + print("[ok] WebKit GSettings package and build wiring") + + with tempfile.TemporaryDirectory(prefix="geminux-gsettings-") as tmp: + root = pathlib.Path(tmp) + schema_dir = root / "usr/share/glib-2.0/schemas" + schema_dir.mkdir(parents=True) + (schema_dir / "org.geminux.webkit.probe.gschema.xml").write_text( + SCHEMA_XML, encoding="utf-8") + result = subprocess.run( + [str(HELPER), str(root)], capture_output=True, text=True) + if result.returncode != 0: + raise SystemExit("schema compile failed:\n%s" % result.stderr.strip()) + compiled = schema_dir / "gschemas.compiled" + if not compiled.is_file() or compiled.stat().st_size == 0: + raise SystemExit("helper did not produce gschemas.compiled") + env = os.environ.copy() + env["GSETTINGS_SCHEMA_DIR"] = str(schema_dir) + listed = subprocess.run( + ["gsettings", "list-schemas"], env=env, + capture_output=True, text=True) + if listed.returncode != 0 or \ + "org.geminux.webkit.probe" not in listed.stdout: + raise SystemExit("compiled schema database is not readable by gsettings") + print("[ok] WebKit GSettings schema compilation") + + +if __name__ == "__main__": + main() diff --git a/src/dwm/dwm.c b/src/dwm/dwm.c index 8dc77ae..a0d3ce8 100644 --- a/src/dwm/dwm.c +++ b/src/dwm/dwm.c @@ -831,6 +831,8 @@ static void focus(Client *c) { static void focusin(XEvent *e) { XFocusChangeEvent *ev = &e->xfocus; + if (ev->mode == NotifyGrab || ev->mode == NotifyWhileGrabbed) + return; if (selmon->sel && ev->window != selmon->sel->win) setfocus(selmon->sel); } @@ -1752,7 +1754,8 @@ static void setup(void) { wa.cursor = cursor[CurNormal]->cursor; wa.event_mask = SubstructureRedirectMask | SubstructureNotifyMask | ButtonPressMask | PointerMotionMask | EnterWindowMask | - LeaveWindowMask | StructureNotifyMask | PropertyChangeMask; + LeaveWindowMask | StructureNotifyMask | PropertyChangeMask | + FocusChangeMask; XChangeWindowAttributes(dpy, root, CWEventMask | CWCursor, &wa); XSelectInput(dpy, root, wa.event_mask); grabkeys(); diff --git a/src/geminux-apps/Makefile b/src/geminux-apps/Makefile index 47e8c9a..63fdc50 100644 --- a/src/geminux-apps/Makefile +++ b/src/geminux-apps/Makefile @@ -28,7 +28,7 @@ geminux-datetime: geminux-datetime.c ../geminux-daemons/geminux-tz-valid.h ../li geminux-camera: geminux-camera.c geminux-cam-bayer.h ../libgemui/gemui.h $(CC) $(CFLAGS) -o $@ $< $(LIBS) -ljpeg -lm -geminux-net: geminux-net.c geminux-wifi-list.h geminux-bt-list.h ../libgemui/gemui.h +geminux-net: geminux-net.c geminux-wifi-list.h geminux-bt-list.h ../geminux-daemons/geminux-dns-valid.h ../libgemui/gemui.h $(CC) $(CFLAGS) -o $@ $< $(LIBS) geminux-audio: geminux-audio.c geminux-audio-parse.h ../libgemui/gemui.h diff --git a/src/geminux-apps/geminux-net.c b/src/geminux-apps/geminux-net.c index 4f73295..31df4b8 100644 --- a/src/geminux-apps/geminux-net.c +++ b/src/geminux-apps/geminux-net.c @@ -2,33 +2,43 @@ #include "gemui.h" #include "geminux-wifi-list.h" #include "geminux-bt-list.h" +#include "../geminux-daemons/geminux-dns-valid.h" #include #include +#include #include #include #include #include +#include +#include #include #include #include -#define HIT_TAB 1 -#define HIT_TOGGLE 2 -#define HIT_ACTION 3 -#define HIT_ROW 4 -#define HIT_PSK 5 -#define HIT_CONNECT 6 -#define HIT_SHOW_PSK 7 -#define HIT_BT_CONN 8 -#define HIT_BT_DISC 9 -#define HIT_BT_REM 10 -#define HIT_AUDIO 11 +#define HIT_TAB 1 +#define HIT_TOGGLE 2 +#define HIT_ACTION 3 +#define HIT_ROW 4 +#define HIT_PSK 5 +#define HIT_CONNECT 6 +#define HIT_SHOW_PSK 7 +#define HIT_BT_CONN 8 +#define HIT_BT_DISC 9 +#define HIT_BT_REM 10 +#define HIT_AUDIO 11 +#define HIT_WIFI_DISC 12 +#define HIT_DNS_CUSTOM 13 +#define HIT_DNS_APPLY 14 enum { WORK_NONE = 0, WORK_WIFI_CONN, WORK_WIFI_SCAN, + WORK_WIFI_DISC, + WORK_DNS_APPLY, + WORK_DNS_TEST, WORK_BT_PWR, WORK_BT_SCAN, WORK_BT_CONN, @@ -37,19 +47,21 @@ enum { }; typedef struct { - char col1[96]; + char col1[128]; char col2[96]; char col3[48]; } net_row_t; typedef struct { gemui_app_t *app; - int tab; /* 0=Wi-Fi, 1=Cellular/4G, 2=Bluetooth, 3=USB/HDMI */ + int tab; /* 0=Wi-Fi, 1=DNS, 2=Cellular/4G, 3=Bluetooth, 4=USB/HDMI */ bool wifi_on; + bool wifi_connected; bool cellular_on; bool bt_on; bool bt_svc_up; bool hdmi_on; + int dns_mode; net_row_t rows[32]; geminux_wifi_group_t wifi_groups[GEMINUX_MAX_WIFI_GROUPS]; geminux_bt_dev_t bt_devs[GEMINUX_MAX_BT_DEVS]; @@ -58,7 +70,10 @@ typedef struct { int scroll_off; char status_text[256]; char psk[128]; + char active_dns[128]; + char custom_dns[192]; bool focus_psk; + bool focus_dns; bool show_psk; pid_t worker_pid; @@ -79,7 +94,7 @@ static uint64_t net_now_ms(void) { static int net_visible_rows(const net_state_t *st) { int h = st->app ? gemui_height(st->app) : 940; - int foot_h = (st->tab == 0 || st->tab == 2) ? 94 : 0; + int foot_h = (st->tab == 0 || st->tab == 1 || st->tab == 3) ? 94 : 0; int box_h = h - (92 + 82 + 88) - 20 - foot_h; int vis = (box_h - 8) / 72; return vis > 0 ? vis : 1; @@ -96,6 +111,11 @@ static void net_clamp_scroll(net_state_t *st) { } } +static void strip_eol(char *s) { + size_t n = strlen(s); + while (n > 0 && (s[n - 1] == '\n' || s[n - 1] == '\r')) s[--n] = '\0'; +} + static void refresh_wifi(net_state_t *st, const char *prev_ssid) { static char out[16384]; out[0] = '\0'; @@ -104,29 +124,190 @@ static void refresh_wifi(net_state_t *st, const char *prev_ssid) { st->wifi_on = strstr(out, "enabled") != NULL; } + /* Use cached BSS table so periodic UI redraws never vanish on slow HW rescans. */ out[0] = '\0'; - const char *scan[] = {"nmcli", "-t", "-f", "IN-USE,BSSID,SSID,CHAN,SIGNAL,SECURITY", "dev", "wifi", "list", NULL}; - if (gemui_run_cmd_timeout(scan, out, sizeof(out), 1200) == 0) { - int ng = geminux_parse_wifi_scan(out, st->wifi_groups, GEMINUX_MAX_WIFI_GROUPS); - st->num_rows = ng; - for (int i = 0; i < ng; i++) { - const geminux_wifi_group_t *g = &st->wifi_groups[i]; - net_row_t *r = &st->rows[i]; - snprintf(r->col1, sizeof(r->col1), "%s%s", g->in_use ? "* " : "", g->ssid); - if (g->ap_count > 1) { - snprintf(r->col2, sizeof(r->col2), "Mesh (%d) %d%%", g->ap_count, g->best_signal); - } else { - snprintf(r->col2, sizeof(r->col2), "Signal %d%%", g->best_signal); - } - snprintf(r->col3, sizeof(r->col3), "%s", g->security); - if (prev_ssid[0] && strcmp(g->ssid, prev_ssid) == 0) { - st->sel_row = i; + const char *scan[] = {"nmcli", "-t", "-f", "IN-USE,BSSID,SSID,CHAN,SIGNAL,SECURITY", + "dev", "wifi", "list", "--rescan", "no", NULL}; + int ng = 0; + if (gemui_run_cmd_timeout(scan, out, sizeof(out), 2000) == 0) { + ng = geminux_parse_wifi_scan(out, st->wifi_groups, GEMINUX_MAX_WIFI_GROUPS); + } + + char iw_out[1024] = {0}; + char iw_bssid[24] = {0}; + char iw_ssid[96] = {0}; + int iw_chan = 0, iw_sig = 0; + const char *iw_cmd[] = {"iw", "dev", "wlan0", "link", NULL}; + bool iw_ok = (gemui_run_cmd_timeout(iw_cmd, iw_out, sizeof(iw_out), 700) == 0) && + geminux_parse_iw_link(iw_out, iw_bssid, sizeof(iw_bssid), + iw_ssid, sizeof(iw_ssid), &iw_chan, &iw_sig); + + char dev_out[1024] = {0}; + bool nm_conn = false; + char nm_con[96] = {0}; + char ip4[48] = {0}; + const char *dev_cmd[] = {"nmcli", "-t", "-f", "GENERAL.STATE,GENERAL.CONNECTION,IP4.ADDRESS", + "dev", "show", "wlan0", NULL}; + if (gemui_run_cmd_timeout(dev_cmd, dev_out, sizeof(dev_out), 900) == 0) { + char *save = NULL; + for (char *ln = strtok_r(dev_out, "\n", &save); ln; ln = strtok_r(NULL, "\n", &save)) { + strip_eol(ln); + char *sep = strchr(ln, ':'); + if (!sep) continue; + *sep = '\0'; + const char *val = sep + 1; + if (strcmp(ln, "GENERAL.STATE") == 0) { + if (atoi(val) == 100) nm_conn = true; + } else if (strcmp(ln, "GENERAL.CONNECTION") == 0) { + if (val[0] && strcmp(val, "--") != 0) snprintf(nm_con, sizeof(nm_con), "%s", val); + } else if (strncmp(ln, "IP4.ADDRESS", 11) == 0) { + if (val[0] && !ip4[0]) { + snprintf(ip4, sizeof(ip4), "%s", val); + char *slash = strchr(ip4, '/'); + if (slash) *slash = '\0'; + } } } } + + char active_ssid[96] = {0}; + if (iw_ssid[0]) { + snprintf(active_ssid, sizeof(active_ssid), "%s", iw_ssid); + } else if (nm_conn && nm_con[0]) { + char nm_ssid[128] = {0}; + const char *gs[] = {"nmcli", "-g", "802-11-wireless.ssid", + "connection", "show", "id", nm_con, NULL}; + if (gemui_run_cmd_timeout(gs, nm_ssid, sizeof(nm_ssid), 800) == 0) { + strip_eol(nm_ssid); + if (nm_ssid[0]) snprintf(active_ssid, sizeof(active_ssid), "%s", nm_ssid); + } + if (!active_ssid[0]) snprintf(active_ssid, sizeof(active_ssid), "%s", nm_con); + } + + char active_sec[48] = {0}; + if ((iw_ok || nm_conn) && active_ssid[0]) { + for (int i = 0; i < ng; i++) { + if (strcmp(st->wifi_groups[i].ssid, active_ssid) == 0 && + st->wifi_groups[i].security[0] && + strcmp(st->wifi_groups[i].security, "--") != 0) { + snprintf(active_sec, sizeof(active_sec), "%s", st->wifi_groups[i].security); + break; + } + } + if (!active_sec[0] && nm_con[0]) { + char km[64] = {0}; + const char *gk[] = {"nmcli", "-g", "802-11-wireless-security.key-mgmt", + "connection", "show", "id", nm_con, NULL}; + if (gemui_run_cmd_timeout(gk, km, sizeof(km), 800) == 0) { + strip_eol(km); + if (strcmp(km, "wpa-psk") == 0) snprintf(active_sec, sizeof(active_sec), "WPA2"); + else if (strcmp(km, "sae") == 0) snprintf(active_sec, sizeof(active_sec), "WPA3"); + else if (!km[0]) snprintf(active_sec, sizeof(active_sec), "Open"); + } + } + ng = geminux_merge_active_wifi(st->wifi_groups, ng, GEMINUX_MAX_WIFI_GROUPS, + active_ssid, iw_bssid, iw_chan, iw_sig, active_sec); + } + + st->wifi_connected = ((iw_ok || nm_conn) && active_ssid[0] != '\0'); + st->num_rows = ng; + for (int i = 0; i < ng; i++) { + const geminux_wifi_group_t *g = &st->wifi_groups[i]; + net_row_t *r = &st->rows[i]; + snprintf(r->col1, sizeof(r->col1), "%s%s", g->in_use ? "* " : "", g->ssid); + if (g->in_use) { + if (g->ap_count > 1) { + snprintf(r->col2, sizeof(r->col2), "Connected (%d) %d%%", g->ap_count, g->best_signal); + } else if (g->best_signal > 0) { + snprintf(r->col2, sizeof(r->col2), "Connected %d%%", g->best_signal); + } else { + snprintf(r->col2, sizeof(r->col2), "Connected"); + } + } else if (g->ap_count > 1) { + snprintf(r->col2, sizeof(r->col2), "Mesh (%d) %d%%", g->ap_count, g->best_signal); + } else { + snprintf(r->col2, sizeof(r->col2), "Signal %d%%", g->best_signal); + } + snprintf(r->col3, sizeof(r->col3), "%s", g->security); + if (prev_ssid && prev_ssid[0] && strcmp(g->ssid, prev_ssid) == 0) { + st->sel_row = i; + } else if ((!prev_ssid || !prev_ssid[0]) && g->in_use && st->sel_row < 0) { + st->sel_row = i; + } + } net_clamp_scroll(st); - snprintf(st->status_text, sizeof(st->status_text), "Wi-Fi %s (powersave=3)", - st->wifi_on ? "Enabled" : "Disabled"); + + if (st->wifi_connected) { + if (ip4[0]) { + snprintf(st->status_text, sizeof(st->status_text), "Connected: %s (%s)", active_ssid, ip4); + } else { + snprintf(st->status_text, sizeof(st->status_text), "Connected: %s", active_ssid); + } + } else { + snprintf(st->status_text, sizeof(st->status_text), "Wi-Fi %s (Not connected)", + st->wifi_on ? "Enabled" : "Disabled"); + } +} + +static void refresh_dns(net_state_t *st) { + int mode = GEMINUX_DNS_DEFAULT; + char saved_custom[192] = {0}; + + FILE *f = fopen("/etc/geminux/dns.conf", "r"); + if (f) { + char line[256]; + while (fgets(line, sizeof(line), f)) { + strip_eol(line); + if (strncmp(line, "mode=", 5) == 0) { + int m = geminux_dns_mode_index(line + 5); + if (m >= 0) mode = m; + } else if (strncmp(line, "custom=", 7) == 0) { + snprintf(saved_custom, sizeof(saved_custom), "%s", line + 7); + } + } + fclose(f); + } + st->dns_mode = mode; + if (!st->focus_dns && saved_custom[0]) { + snprintf(st->custom_dns, sizeof(st->custom_dns), "%s", saved_custom); + } + + st->active_dns[0] = '\0'; + FILE *rf = fopen("/etc/resolv.conf", "r"); + if (rf) { + char rbuf[1024]; + size_t nr = fread(rbuf, 1, sizeof(rbuf) - 1, rf); + rbuf[nr] = '\0'; + fclose(rf); + geminux_parse_resolv_conf(rbuf, st->active_dns, sizeof(st->active_dns)); + } + + st->num_rows = GEMINUX_DNS_COUNT; + for (int i = 0; i < GEMINUX_DNS_COUNT; i++) { + const geminux_dns_preset_t *p = &GEMINUX_DNS_PRESETS[i]; + net_row_t *r = &st->rows[i]; + bool act = (i == mode); + if (i == GEMINUX_DNS_DEFAULT) { + snprintf(r->col1, sizeof(r->col1), "%s%s", act ? "* " : "", p->label); + snprintf(r->col2, sizeof(r->col2), "Automatic"); + } else if (i == GEMINUX_DNS_CUSTOM) { + const char *shown = st->custom_dns[0] ? st->custom_dns + : (saved_custom[0] ? saved_custom : "Enter below..."); + snprintf(r->col1, sizeof(r->col1), "%s%s: %.64s", act ? "* " : "", p->label, shown); + snprintf(r->col2, sizeof(r->col2), "Custom"); + } else { + snprintf(r->col1, sizeof(r->col1), "%s%s (%s)", act ? "* " : "", p->label, p->v4_csv); + snprintf(r->col2, sizeof(r->col2), p->v6_csv[0] ? "IPv4 + IPv6" : "IPv4"); + } + snprintf(r->col3, sizeof(r->col3), "%s", act ? "Active" : "Select"); + } + if (st->focus_dns) st->sel_row = GEMINUX_DNS_CUSTOM; + else st->sel_row = mode; + net_clamp_scroll(st); + + snprintf(st->status_text, sizeof(st->status_text), "DNS: %s | resolv.conf: %s", + GEMINUX_DNS_PRESETS[mode].label, + st->active_dns[0] ? st->active_dns : "none"); } static void refresh_bt(net_state_t *st, const char *prev_mac) { @@ -192,7 +373,7 @@ static void refresh_tab(net_state_t *st) { char prev_key[96] = {0}; if (st->tab == 0 && st->sel_row >= 0 && st->sel_row < st->num_rows) { snprintf(prev_key, sizeof(prev_key), "%s", st->wifi_groups[st->sel_row].ssid); - } else if (st->tab == 2 && st->sel_row >= 0 && st->sel_row < st->num_rows) { + } else if (st->tab == 3 && st->sel_row >= 0 && st->sel_row < st->num_rows) { snprintf(prev_key, sizeof(prev_key), "%s", st->bt_devs[st->sel_row].mac); } @@ -204,6 +385,8 @@ static void refresh_tab(net_state_t *st) { if (st->tab == 0) { refresh_wifi(st, prev_key); } else if (st->tab == 1) { + refresh_dns(st); + } else if (st->tab == 2) { st->scroll_off = 0; gemui_unix_cmd("/run/geminux/ccci.sock", "status", out, sizeof(out)); st->cellular_on = strstr(out, "READY") != NULL; @@ -221,7 +404,7 @@ static void refresh_tab(net_state_t *st) { st->num_rows++; } } - } else if (st->tab == 2) { + } else if (st->tab == 3) { refresh_bt(st, prev_key); } else { st->scroll_off = 0; @@ -338,6 +521,22 @@ static void on_worker_fd(gemui_app_t *app, int fd, void *ud) { } } else if (kind == WORK_WIFI_SCAN) { gemui_show_toast(app, rc == 0 ? "Wi-Fi scan updated" : "Wi-Fi rescan failed", 1800); + } else if (kind == WORK_WIFI_DISC) { + gemui_show_toast(app, rc == 0 ? "Disconnected Wi-Fi" : "Wi-Fi disconnect failed", 2000); + } else if (kind == WORK_DNS_APPLY) { + if (rc == 0) { + st->focus_dns = false; + gemui_show_toast(app, "DNS settings applied", 2200); + } else { + snprintf(toast, sizeof(toast), err[0] ? "DNS error: %.180s" : "Failed to apply DNS", err); + gemui_show_toast(app, toast, 3200); + } + } else if (kind == WORK_DNS_TEST) { + if (err[0]) { + gemui_show_toast(app, err, 3600); + } else { + gemui_show_toast(app, rc == 0 ? "DNS lookup succeeded" : "DNS lookup failed", 2600); + } } else if (kind == WORK_BT_PWR) { if (rc == 0) gemui_show_toast(app, "Updated Bluetooth power", 1800); else { @@ -375,7 +574,7 @@ static void on_worker_timer(gemui_app_t *app, void *ud) { return; } st->worker_tick++; - if (st->worker_kind == WORK_BT_SCAN && (st->worker_tick % 4) == 0 && st->tab == 2) { + if (st->worker_kind == WORK_BT_SCAN && (st->worker_tick % 4) == 0 && st->tab == 3) { char prev_mac[24] = {0}; if (st->sel_row >= 0 && st->sel_row < st->num_rows) { snprintf(prev_mac, sizeof(prev_mac), "%s", st->bt_devs[st->sel_row].mac); @@ -467,8 +666,7 @@ static void wifi_delete_ssid_profiles(const char *ssid) { char p_ssid[128] = {0}; const char *get_ssid[] = {"nmcli", "-g", "802-11-wireless.ssid", "connection", "show", "uuid", uuid, NULL}; if (gemui_run_cmd_timeout(get_ssid, p_ssid, sizeof(p_ssid), 1200) == 0) { - size_t n = strlen(p_ssid); - while (n > 0 && (p_ssid[n - 1] == '\n' || p_ssid[n - 1] == '\r')) p_ssid[--n] = '\0'; + strip_eol(p_ssid); if (strcmp(p_ssid, ssid) == 0) { const char *del_u[] = {"nmcli", "connection", "delete", "uuid", uuid, NULL}; gemui_run_cmd_timeout(del_u, NULL, 0, 5000); @@ -531,7 +729,10 @@ static int child_wifi_connect(void *ctx) { rc = gemui_run_cmd_timeout(up, out, sizeof(out), 22000); } } - if (rc != 0 && out[0]) { + if (rc == 0) { + const char *dns_apply[] = {"doas", "/usr/sbin/geminux-dnsctl", "apply", NULL}; + gemui_run_cmd_timeout(dns_apply, NULL, 0, 5000); + } else if (out[0]) { fputs(out, stdout); } return rc; @@ -546,6 +747,58 @@ static int child_wifi_rescan(void *ctx) { return rc; } +static int child_wifi_disconnect(void *ctx) { + (void)ctx; + char out[256] = {0}; + const char *argv[] = {"nmcli", "device", "disconnect", "wlan0", NULL}; + int rc = gemui_run_cmd_timeout(argv, out, sizeof(out), 8000); + if (rc != 0 && out[0]) fputs(out, stdout); + return rc; +} + +typedef struct { + int mode; + char custom[192]; +} dns_job_t; + +static int child_dns_apply(void *ctx) { + dns_job_t *j = ctx; + char out[256] = {0}; + const char *mode_str = GEMINUX_DNS_PRESETS[j->mode].mode; + const char *argv_custom[] = {"doas", "/usr/sbin/geminux-dnsctl", "set", mode_str, j->custom, NULL}; + const char *argv_preset[] = {"doas", "/usr/sbin/geminux-dnsctl", "set", mode_str, NULL}; + int rc = gemui_run_cmd_timeout((j->mode == GEMINUX_DNS_CUSTOM) ? argv_custom : argv_preset, + out, sizeof(out), 8000); + if (rc != 0 && out[0]) fputs(out, stdout); + return rc; +} + +static int child_dns_test(void *ctx) { + (void)ctx; + struct timespec t0, t1; + clock_gettime(CLOCK_MONOTONIC, &t0); + + struct addrinfo hints; + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_UNSPEC; + hints.ai_socktype = SOCK_STREAM; + + struct addrinfo *res = NULL; + int rc = getaddrinfo("dl-cdn.alpinelinux.org", NULL, &hints, &res); + clock_gettime(CLOCK_MONOTONIC, &t1); + long ms = (long)((t1.tv_sec - t0.tv_sec) * 1000L + (t1.tv_nsec - t0.tv_nsec) / 1000000L); + if (rc != 0 || !res) { + printf("DNS failed (%ld ms): %s\n", ms, gai_strerror(rc)); + return 1; + } + + char host[64] = {0}; + getnameinfo(res->ai_addr, res->ai_addrlen, host, sizeof(host), NULL, 0, NI_NUMERICHOST); + freeaddrinfo(res); + printf("DNS OK: alpinelinux -> %s (%ld ms)\n", host[0] ? host : "resolved", ms); + return 0; +} + typedef struct { char mac[24]; bool enable; @@ -668,6 +921,50 @@ static void connect_selected_wifi(net_state_t *st) { memset(&job, 0, sizeof(job)); } +static void disconnect_wifi(net_state_t *st) { + if (!st->wifi_connected) { + gemui_show_toast(st->app, "Wi-Fi is not connected", 1600); + return; + } + start_worker(st, WORK_WIFI_DISC, "Disconnecting Wi-Fi...", 10000, child_wifi_disconnect, NULL); +} + +static void apply_dns_mode(net_state_t *st, int mode) { + if (mode < 0 || mode >= GEMINUX_DNS_COUNT) { + gemui_show_toast(st->app, "Select a DNS profile first", 1600); + return; + } + + dns_job_t job; + memset(&job, 0, sizeof(job)); + job.mode = mode; + + if (mode == GEMINUX_DNS_CUSTOM) { + char v4[GEMINUX_DNS_MAX_SERVERS][16]; + char v6[GEMINUX_DNS_MAX_SERVERS][46]; + int n4 = 0, n6 = 0; + char norm[192] = {0}; + if (geminux_parse_dns_servers(st->custom_dns, v4, &n4, GEMINUX_DNS_MAX_SERVERS, + v6, &n6, GEMINUX_DNS_MAX_SERVERS, + norm, sizeof(norm)) <= 0) { + gemui_show_toast(st->app, "Enter valid comma/space IPv4 or IPv6 nameservers", 2600); + st->focus_dns = true; + st->sel_row = GEMINUX_DNS_CUSTOM; + gemui_request_redraw(st->app); + return; + } + snprintf(st->custom_dns, sizeof(st->custom_dns), "%s", norm); + snprintf(job.custom, sizeof(job.custom), "%s", norm); + } + + start_worker(st, WORK_DNS_APPLY, "Applying DNS configuration...", 10000, child_dns_apply, &job); +} + +static void apply_selected_dns(net_state_t *st) { + int mode = st->focus_dns ? GEMINUX_DNS_CUSTOM : st->sel_row; + apply_dns_mode(st, mode); +} + static void start_bt_dev_action(net_state_t *st, int kind) { if (st->sel_row < 0 || st->sel_row >= st->num_rows) { gemui_show_toast(st->app, "Select a Bluetooth device first", 1600); @@ -701,9 +998,9 @@ static void on_draw(gemui_app_t *app, cairo_t *cr, int w, int h, void *ud) { int pad = 20; int top = 92; - int tab_w = (w - pad * 2 - 3 * 12) / 4; - static const char *tabs[4] = {"Wi-Fi", "4G / CCCI", "Bluetooth", "USB & HDMI"}; - for (int i = 0; i < 4; i++) { + int tab_w = (w - pad * 2 - 4 * 12) / 5; + static const char *tabs[5] = {"Wi-Fi", "DNS", "4G / CCCI", "Bluetooth", "USB & HDMI"}; + for (int i = 0; i < 5; i++) { gemui_draw_button(app, cr, (gemui_rect_t){pad + i * (tab_w + 12), top, tab_w, 66}, tabs[i], HIT_TAB, i, false, st->tab == i, false); } @@ -717,31 +1014,38 @@ static void on_draw(gemui_app_t *app, cairo_t *cr, int w, int h, void *ud) { gemui_draw_button(app, cr, (gemui_rect_t){pad + ctrl_w + 12, cy, ctrl_w, 72}, act_lbl, HIT_ACTION, 0, st->worker_pid == 0, st->worker_pid > 0, false); } else if (st->tab == 1) { - gemui_draw_toggle(app, cr, (gemui_rect_t){pad, cy, ctrl_w, 72}, - "MT6797 Modem Active", st->cellular_on, HIT_TOGGLE, 1, false); + gemui_draw_button(app, cr, (gemui_rect_t){pad, cy, ctrl_w, 72}, + "Reset to Router DNS", HIT_TOGGLE, 1, + false, st->dns_mode == GEMINUX_DNS_DEFAULT, false); + const char *dns_act = (st->worker_pid > 0) ? "Cancel Operation" : "Test DNS Lookup"; gemui_draw_button(app, cr, (gemui_rect_t){pad + ctrl_w + 12, cy, ctrl_w, 72}, - "Reset CCCI Modem", HIT_ACTION, 1, false, false, false); + dns_act, HIT_ACTION, 1, st->worker_pid == 0, st->worker_pid > 0, false); } else if (st->tab == 2) { gemui_draw_toggle(app, cr, (gemui_rect_t){pad, cy, ctrl_w, 72}, - "Bluetooth Radio", st->bt_on, HIT_TOGGLE, 2, false); + "MT6797 Modem Active", st->cellular_on, HIT_TOGGLE, 2, false); + gemui_draw_button(app, cr, (gemui_rect_t){pad + ctrl_w + 12, cy, ctrl_w, 72}, + "Reset CCCI Modem", HIT_ACTION, 2, false, false, false); + } else if (st->tab == 3) { + gemui_draw_toggle(app, cr, (gemui_rect_t){pad, cy, ctrl_w, 72}, + "Bluetooth Radio", st->bt_on, HIT_TOGGLE, 3, false); const char *bt_lbl = (st->worker_kind == WORK_BT_SCAN) ? "Stop Scan" : (st->worker_pid > 0) ? "Cancel Operation" : "Scan 12s"; gemui_draw_button(app, cr, (gemui_rect_t){pad + ctrl_w + 12, cy, ctrl_w, 72}, - bt_lbl, HIT_ACTION, 2, st->worker_pid == 0, st->worker_pid > 0, false); + bt_lbl, HIT_ACTION, 3, st->worker_pid == 0, st->worker_pid > 0, false); } else { gemui_draw_toggle(app, cr, (gemui_rect_t){pad, cy, ctrl_w, 72}, - "SiI9024 HDMI Extend", st->hdmi_on, HIT_TOGGLE, 3, false); + "SiI9024 HDMI Extend", st->hdmi_on, HIT_TOGGLE, 4, false); gemui_draw_button(app, cr, (gemui_rect_t){pad + ctrl_w + 12, cy, ctrl_w, 72}, - "Mirror Primary Display", HIT_ACTION, 3, true, false, false); + "Mirror Primary Display", HIT_ACTION, 4, true, false, false); } - int foot_h = (st->tab == 0 || st->tab == 2) ? 94 : 0; + int foot_h = (st->tab == 0 || st->tab == 1 || st->tab == 3) ? 94 : 0; gemui_rect_t box = {pad, cy + 88, w - pad * 2, h - (cy + 88) - pad - foot_h}; gemui_fill_round(cr, box, 12, t->bg_bar); gemui_stroke_round(cr, box, 12, 1.5, t->border); if (st->num_rows == 0) { - const char *empty_msg = (st->tab == 2 && st->bt_svc_up) + const char *empty_msg = (st->tab == 3 && st->bt_svc_up) ? "No Bluetooth devices found — press Scan 12s" : "No interfaces or scan results available"; gemui_draw_text(cr, t, box, empty_msg, 0, false, GEMUI_ALIGN_CENTER, t->fg_muted); @@ -767,18 +1071,29 @@ static void on_draw(gemui_app_t *app, cairo_t *cr, int w, int h, void *ud) { } if (st->tab == 0) { - int cw = 260; - int sw = 200; - int iw = w - pad * 2 - cw - sw - 24; + int cw = 250; + int dw = 210; + int sw = 180; + int iw = w - pad * 2 - cw - dw - sw - 36; gemui_draw_input(app, cr, (gemui_rect_t){pad, h - 92, iw, 72}, "Wi-Fi passphrase (if connecting to secured SSID)...", st->psk, !st->show_psk, st->focus_psk, HIT_PSK, 0); gemui_draw_button(app, cr, (gemui_rect_t){pad + iw + 12, h - 92, sw, 72}, st->show_psk ? "Hide PW" : "Show PW", HIT_SHOW_PSK, 0, false, st->show_psk, false); + gemui_draw_button(app, cr, (gemui_rect_t){pad + iw + sw + 24, h - 92, dw, 72}, + "Disconnect", HIT_WIFI_DISC, 0, false, false, false); gemui_draw_button(app, cr, (gemui_rect_t){w - pad - cw, h - 92, cw, 72}, "Connect Wi-Fi", HIT_CONNECT, 0, true, false, false); - } else if (st->tab == 2) { + } else if (st->tab == 1) { + int aw = 290; + int iw = w - pad * 2 - aw - 12; + gemui_draw_input(app, cr, (gemui_rect_t){pad, h - 92, iw, 72}, + "Custom nameservers (e.g. 88.198.92.222, 1.1.1.1)...", + st->custom_dns, false, st->focus_dns, HIT_DNS_CUSTOM, 0); + gemui_draw_button(app, cr, (gemui_rect_t){w - pad - aw, h - 92, aw, 72}, + "Apply DNS Profile", HIT_DNS_APPLY, 0, true, false, false); + } else if (st->tab == 3) { int bw = (w - pad * 2 - 3 * 12) / 4; gemui_draw_button(app, cr, (gemui_rect_t){pad, h - 92, bw, 72}, "Pair & Connect", HIT_BT_CONN, 0, true, false, false); @@ -796,29 +1111,43 @@ static void on_key(gemui_app_t *app, KeySym ks, unsigned int state, const char * if (ks == XK_Escape) { gemui_quit(app, 0); } else if (ks == XK_Tab) { - st->tab = (st->tab + 1) % 4; + st->tab = (st->tab + 1) % 5; st->focus_psk = false; + st->focus_dns = false; refresh_tab(st); gemui_request_redraw(app); } else if (ks == XK_Up && st->num_rows > 0) { st->sel_row = (st->sel_row > 0) ? st->sel_row - 1 : 0; + if (st->tab == 1) st->focus_dns = (st->sel_row == GEMINUX_DNS_CUSTOM); net_clamp_scroll(st); gemui_request_redraw(app); } else if (ks == XK_Down && st->num_rows > 0) { st->sel_row = (st->sel_row + 1 < st->num_rows) ? st->sel_row + 1 : st->num_rows - 1; + if (st->tab == 1) st->focus_dns = (st->sel_row == GEMINUX_DNS_CUSTOM); net_clamp_scroll(st); gemui_request_redraw(app); } else if (ks == XK_Return || ks == XK_KP_Enter) { if (st->tab == 0) connect_selected_wifi(st); - else if (st->tab == 2) start_bt_dev_action(st, WORK_BT_CONN); + else if (st->tab == 1) apply_selected_dns(st); + else if (st->tab == 3) start_bt_dev_action(st, WORK_BT_CONN); } else if ((ks == XK_BackSpace || ks == XK_Delete) && st->tab == 0 && (st->focus_psk || st->sel_row >= 0)) { st->focus_psk = true; gemui_utf8_pop_char(st->psk); gemui_request_redraw(app); + } else if ((ks == XK_BackSpace || ks == XK_Delete) && st->tab == 1 && (st->focus_dns || st->sel_row == GEMINUX_DNS_CUSTOM)) { + st->focus_dns = true; + st->sel_row = GEMINUX_DNS_CUSTOM; + gemui_utf8_pop_char(st->custom_dns); + gemui_request_redraw(app); } else if ((state & ControlMask) && (ks == XK_u || ks == XK_U) && st->tab == 0) { st->focus_psk = true; memset(st->psk, 0, sizeof(st->psk)); gemui_request_redraw(app); + } else if ((state & ControlMask) && (ks == XK_u || ks == XK_U) && st->tab == 1) { + st->focus_dns = true; + st->sel_row = GEMINUX_DNS_CUSTOM; + memset(st->custom_dns, 0, sizeof(st->custom_dns)); + gemui_request_redraw(app); } else if (st->tab == 0 && (st->focus_psk || st->sel_row >= 0) && utf8 && utf8[0]) { st->focus_psk = true; size_t cur = strlen(st->psk), add = strlen(utf8); @@ -826,6 +1155,14 @@ static void on_key(gemui_app_t *app, KeySym ks, unsigned int state, const char * memcpy(st->psk + cur, utf8, add + 1); gemui_request_redraw(app); } + } else if (st->tab == 1 && (st->focus_dns || st->sel_row == GEMINUX_DNS_CUSTOM) && utf8 && utf8[0]) { + st->focus_dns = true; + st->sel_row = GEMINUX_DNS_CUSTOM; + size_t cur = strlen(st->custom_dns), add = strlen(utf8); + if (cur + add < sizeof(st->custom_dns)) { + memcpy(st->custom_dns + cur, utf8, add + 1); + gemui_request_redraw(app); + } } } @@ -852,18 +1189,29 @@ static void on_ptr(gemui_app_t *app, int type, int x, int y, unsigned int btn, v if (hit->id == HIT_TAB) { st->tab = hit->val; st->focus_psk = false; + st->focus_dns = false; refresh_tab(st); } else if (hit->id == HIT_ROW) { st->sel_row = hit->val; if (st->tab == 0) st->focus_psk = true; + else if (st->tab == 1) st->focus_dns = (hit->val == GEMINUX_DNS_CUSTOM); } else if (hit->id == HIT_PSK) { st->focus_psk = true; } else if (hit->id == HIT_SHOW_PSK) { st->show_psk = !st->show_psk; st->focus_psk = true; + } else if (hit->id == HIT_WIFI_DISC) { + disconnect_wifi(st); + return; } else if (hit->id == HIT_CONNECT) { connect_selected_wifi(st); return; + } else if (hit->id == HIT_DNS_CUSTOM) { + st->focus_dns = true; + st->sel_row = GEMINUX_DNS_CUSTOM; + } else if (hit->id == HIT_DNS_APPLY) { + apply_selected_dns(st); + return; } else if (hit->id == HIT_BT_CONN) { start_bt_dev_action(st, WORK_BT_CONN); return; @@ -883,10 +1231,13 @@ static void on_ptr(gemui_app_t *app, int type, int x, int y, unsigned int btn, v gemui_run_cmd_timeout(argv, NULL, 0, 2000); refresh_tab(st); } else if (hit->val == 1) { + apply_dns_mode(st, GEMINUX_DNS_DEFAULT); + return; + } else if (hit->val == 2) { gemui_unix_cmd("/run/geminux/ccci.sock", st->cellular_on ? "flight on" : "flight off", NULL, 0); refresh_tab(st); - } else if (hit->val == 2) { + } else if (hit->val == 3) { bt_job_t job; memset(&job, 0, sizeof(job)); job.enable = !st->bt_on; @@ -894,7 +1245,7 @@ static void on_ptr(gemui_app_t *app, int type, int x, int y, unsigned int btn, v job.enable ? "Enabling Bluetooth..." : "Disabling Bluetooth...", 10000, child_bt_power, &job); return; - } else if (hit->val == 3) { + } else if (hit->val == 4) { const char *argv[] = {"xrandr", "--output", "HDMI-1", st->hdmi_on ? "--off" : "--auto", NULL}; gemui_run_cmd_timeout(argv, NULL, 0, 2000); st->hdmi_on = !st->hdmi_on; @@ -909,17 +1260,24 @@ static void on_ptr(gemui_app_t *app, int type, int x, int y, unsigned int btn, v } return; } else if (hit->val == 1) { + if (st->worker_pid > 0) { + cancel_worker(st, "Cancelled operation"); + } else { + start_worker(st, WORK_DNS_TEST, "Testing DNS lookup...", 8000, child_dns_test, NULL); + } + return; + } else if (hit->val == 2) { gemui_unix_cmd("/run/geminux/ccci.sock", "reset", NULL, 0); gemui_show_toast(app, "Sent CCCI reset request", 1600); refresh_tab(st); - } else if (hit->val == 2) { + } else if (hit->val == 3) { if (st->worker_pid > 0) { cancel_worker(st, st->worker_kind == WORK_BT_SCAN ? "Bluetooth scan stopped" : "Cancelled"); } else { start_worker(st, WORK_BT_SCAN, "Scanning Bluetooth (12s)...", 15000, child_bt_scan, NULL); } return; - } else if (hit->val == 3) { + } else if (hit->val == 4) { const char *argv[] = {"xrandr", "--output", "HDMI-1", "--same-as", "DSI-1", NULL}; gemui_run_cmd_timeout(argv, NULL, 0, 2000); refresh_tab(st); diff --git a/src/geminux-apps/geminux-wifi-list.h b/src/geminux-apps/geminux-wifi-list.h index be59a5f..b99e50f 100644 --- a/src/geminux-apps/geminux-wifi-list.h +++ b/src/geminux-apps/geminux-wifi-list.h @@ -141,4 +141,122 @@ static inline int geminux_parse_wifi_scan(const char *nmcli_out, return n; } +static inline int geminux_wifi_freq_to_chan(int mhz) { + if (mhz == 2484) return 14; + if (mhz >= 2412 && mhz <= 2472) return (mhz - 2407) / 5; + if (mhz >= 5000 && mhz <= 5895) return (mhz - 5000) / 5; + return 0; +} + +static inline bool geminux_parse_iw_link(const char *iw_out, + char *bssid, size_t bssid_sz, + char *ssid, size_t ssid_sz, + int *chan_out, int *sig_pct_out) { + if (bssid && bssid_sz > 0) bssid[0] = '\0'; + if (ssid && ssid_sz > 0) ssid[0] = '\0'; + if (chan_out) *chan_out = 0; + if (sig_pct_out) *sig_pct_out = 0; + if (!iw_out || !iw_out[0]) return false; + + bool connected = false; + const char *cur = iw_out; + while (*cur) { + const char *nl = strchr(cur, '\n'); + size_t raw_len = nl ? (size_t)(nl - cur) : strlen(cur); + char ln[256]; + size_t l = raw_len < sizeof(ln) - 1 ? raw_len : sizeof(ln) - 1; + memcpy(ln, cur, l); + ln[l] = '\0'; + cur = nl ? nl + 1 : cur + raw_len; + while (l > 0 && ln[l - 1] == '\r') ln[--l] = '\0'; + + const char *p = ln; + while (*p == ' ' || *p == '\t') p++; + if (strncmp(p, "Not connected", 13) == 0) return false; + + if (strncmp(p, "Connected to ", 13) == 0) { + connected = true; + p += 13; + if (bssid && bssid_sz > 0) { + size_t i = 0; + while (p[i] && p[i] != ' ' && p[i] != '\t' && i + 1 < bssid_sz) { + bssid[i] = p[i]; + i++; + } + bssid[i] = '\0'; + } + } else if (strncmp(p, "SSID: ", 6) == 0) { + if (ssid && ssid_sz > 0) snprintf(ssid, ssid_sz, "%s", p + 6); + } else if (strncmp(p, "freq: ", 6) == 0) { + int ch = geminux_wifi_freq_to_chan(atoi(p + 6)); + if (chan_out && ch > 0) *chan_out = ch; + } else if (strncmp(p, "signal: ", 8) == 0) { + int dbm = atoi(p + 8); + int pct = 2 * (dbm + 100); + if (pct < 5) pct = 5; + if (pct > 100) pct = 100; + if (sig_pct_out) *sig_pct_out = pct; + } + } + return connected; +} + +static inline int geminux_merge_active_wifi(geminux_wifi_group_t *groups, + int count, + int max_groups, + const char *active_ssid, + const char *active_bssid, + int active_chan, + int active_signal, + const char *active_security) { + if (!groups || max_groups <= 0) return 0; + if (count < 0) count = 0; + if (count > max_groups) count = max_groups; + if (!active_ssid || !active_ssid[0]) return count; + + int idx = -1; + for (int i = 0; i < count; i++) { + if (strcmp(groups[i].ssid, active_ssid) == 0) { + groups[i].in_use = true; + idx = i; + } else { + groups[i].in_use = false; + } + } + + if (idx >= 0) { + geminux_wifi_group_t *g = &groups[idx]; + if (g->best_signal <= 0 && active_signal > 0) g->best_signal = active_signal; + if (g->best_chan <= 0 && active_chan > 0) { + g->best_chan = active_chan; + g->best_joinable = geminux_wifi_chan_joinable(active_chan); + } + if (!g->best_bssid[0] && active_bssid && active_bssid[0]) { + snprintf(g->best_bssid, sizeof(g->best_bssid), "%s", active_bssid); + } + if ((!g->security[0] || strcmp(g->security, "--") == 0) && + active_security && active_security[0]) { + snprintf(g->security, sizeof(g->security), "%s", active_security); + } + } else { + int pos = (count < max_groups) ? count++ : max_groups - 1; + geminux_wifi_group_t *g = &groups[pos]; + memset(g, 0, sizeof(*g)); + snprintf(g->ssid, sizeof(g->ssid), "%s", active_ssid); + if (active_bssid && active_bssid[0]) { + snprintf(g->best_bssid, sizeof(g->best_bssid), "%s", active_bssid); + } + snprintf(g->security, sizeof(g->security), "%s", + (active_security && active_security[0]) ? active_security : "Connected"); + g->best_signal = (active_signal > 0) ? active_signal : 0; + g->best_chan = active_chan; + g->best_joinable = geminux_wifi_chan_joinable(active_chan); + g->ap_count = 1; + g->in_use = true; + } + + if (count > 1) qsort(groups, (size_t)count, sizeof(groups[0]), geminux_wifi_group_cmp); + return count; +} + #endif /* GEMINUX_WIFI_LIST_H */ diff --git a/src/geminux-daemons/Makefile b/src/geminux-daemons/Makefile index f5a0fa5..2a9261f 100644 --- a/src/geminux-daemons/Makefile +++ b/src/geminux-daemons/Makefile @@ -24,7 +24,8 @@ BINS = \ geminux-power-audit \ geminux-checkpw \ geminux-wifi-nvram \ - geminux-tzctl + geminux-tzctl \ + geminux-dnsctl all: $(BINS) @@ -61,6 +62,9 @@ geminux-checkpw: geminux-checkpw.c geminux-tzctl: geminux-tzctl.c geminux-tz-valid.h $(CC) $(CFLAGS) -o $@ geminux-tzctl.c +geminux-dnsctl: geminux-dnsctl.c geminux-dns-valid.h + $(CC) $(CFLAGS) -o $@ geminux-dnsctl.c + geminux-wifi-nvram: geminux-wifi-nvram.c geminux-wifi-nvram-core.c geminux-wifi-nvram-core.h $(CC) $(CFLAGS) -o $@ geminux-wifi-nvram.c geminux-wifi-nvram-core.c @@ -69,7 +73,7 @@ install: all cp -f geminux-power-ctl geminux-statusd geminux-touchd geminux-modem-ctl \ geminux-bt-obex geminux-power-audit $(DESTDIR)$(PREFIX)/bin/ cp -f geminux-powerd geminux-ccci-daemon geminux-leds \ - geminux-checkpw geminux-wifi-nvram geminux-tzctl $(DESTDIR)$(PREFIX)/sbin/ + geminux-checkpw geminux-wifi-nvram geminux-tzctl geminux-dnsctl $(DESTDIR)$(PREFIX)/sbin/ chmod 0755 $(DESTDIR)$(PREFIX)/bin/geminux-* $(DESTDIR)$(PREFIX)/sbin/geminux-* clean: diff --git a/src/geminux-daemons/geminux-dns-valid.h b/src/geminux-daemons/geminux-dns-valid.h new file mode 100644 index 0000000..632594a --- /dev/null +++ b/src/geminux-daemons/geminux-dns-valid.h @@ -0,0 +1,213 @@ +/* + * Header-only C11 helpers for validating DNS resolver presets and custom nameservers. + */ +#ifndef GEMINUX_DNS_VALID_H +#define GEMINUX_DNS_VALID_H + +#include +#include +#include +#include +#include +#include + +#define GEMINUX_DNS_DEFAULT 0 +#define GEMINUX_DNS_CLOUDFLARE 1 +#define GEMINUX_DNS_GOOGLE 2 +#define GEMINUX_DNS_RADICAL 3 +#define GEMINUX_DNS_QUAD9 4 +#define GEMINUX_DNS_CUSTOM 5 +#define GEMINUX_DNS_COUNT 6 + +#define GEMINUX_DNS_MAX_SERVERS 6 + +typedef struct { + const char *mode; + const char *label; + const char *v4_csv; + const char *v6_csv; +} geminux_dns_preset_t; + +static const geminux_dns_preset_t GEMINUX_DNS_PRESETS[GEMINUX_DNS_COUNT] = { + {"default", "Default (Router / DHCP)", "", ""}, + {"cloudflare", "Cloudflare DNS", "1.1.1.1,1.0.0.1", "2606:4700:4700::1111"}, + {"google", "Google Public DNS", "8.8.8.8,8.8.4.4", "2001:4860:4860::8888"}, + {"radicaldns", "RadicalDNS", "88.198.92.222,192.71.166.92", "2a01:4f8:1c0c:82c0::1"}, + {"quad9", "Quad9 (Filtered)", "9.9.9.9,149.112.112.112", "2620:fe::fe"}, + {"custom", "Custom Nameservers", "", ""}, +}; + +static inline int geminux_dns_mode_index(const char *mode) { + if (!mode || !mode[0]) return -1; + for (int i = 0; i < GEMINUX_DNS_COUNT; i++) { + if (strcmp(mode, GEMINUX_DNS_PRESETS[i].mode) == 0) return i; + } + return -1; +} + +static inline bool geminux_dns_mode_valid(const char *mode) { + return geminux_dns_mode_index(mode) >= 0; +} + +static inline bool geminux_dns_token_chars_ok(const char *tok) { + if (!tok || !tok[0]) return false; + for (const unsigned char *p = (const unsigned char *)tok; *p; p++) { + bool ok = (*p >= '0' && *p <= '9') || + (*p >= 'a' && *p <= 'f') || + (*p >= 'A' && *p <= 'F') || + *p == '.' || *p == ':'; + if (!ok) return false; + } + return true; +} + +static inline bool geminux_dns_v4_valid(const struct in_addr *a) { + uint32_t ip = ntohl(a->s_addr); + if (ip == 0x00000000U || ip == 0xffffffffU) return false; + if ((ip >> 24) == 0U) return false; /* 0.0.0.0/8 unspecified */ + if ((ip & 0xf0000000U) == 0xe0000000U) return false; /* 224.0.0.0/4 multicast */ + return true; +} + +static inline bool geminux_dns_v6_valid(const struct in6_addr *a) { + static const uint8_t z[16] = {0}; + if (memcmp(a->s6_addr, z, 16) == 0) return false; /* :: unspecified */ + if (a->s6_addr[0] == 0xff) return false; /* ff00::/8 multicast */ + return true; +} + +/* + * Parse comma/whitespace-separated IPv4/IPv6 DNS addresses into separate IPv4 and IPv6 + * arrays plus a canonical comma-separated list ordered IPv4-first (for musl's MAXNS=3 + * resolver reliability). Returns total server count (1..GEMINUX_DNS_MAX_SERVERS), or -1 on error. + */ +static inline int geminux_parse_dns_servers(const char *raw, + char v4[][16], int *n_v4, int max_v4, + char v6[][46], int *n_v6, int max_v6, + char *norm_csv, size_t norm_sz) { + int c4 = 0, c6 = 0; + char loc_v4[GEMINUX_DNS_MAX_SERVERS][16]; + char loc_v6[GEMINUX_DNS_MAX_SERVERS][46]; + + if (n_v4) *n_v4 = 0; + if (n_v6) *n_v6 = 0; + if (norm_csv && norm_sz > 0) norm_csv[0] = '\0'; + if (!raw || !raw[0]) return -1; + + const char *p = raw; + while (*p) { + while (*p == ',' || *p == ' ' || *p == '\t' || *p == '\r' || *p == '\n') p++; + if (!*p) break; + const char *start = p; + while (*p && *p != ',' && *p != ' ' && *p != '\t' && *p != '\r' && *p != '\n') p++; + size_t len = (size_t)(p - start); + if (len == 0 || len >= 46) return -1; + + char tok[48]; + memcpy(tok, start, len); + tok[len] = '\0'; + if (!geminux_dns_token_chars_ok(tok)) return -1; + + struct in_addr a4; + struct in6_addr a6; + if (inet_pton(AF_INET, tok, &a4) == 1) { + if (!geminux_dns_v4_valid(&a4)) return -1; + char canon[16]; + if (!inet_ntop(AF_INET, &a4, canon, sizeof(canon))) return -1; + bool dup = false; + for (int i = 0; i < c4; i++) { + if (strcmp(loc_v4[i], canon) == 0) { + dup = true; + break; + } + } + if (!dup) { + if (c4 + c6 >= GEMINUX_DNS_MAX_SERVERS) return -1; + snprintf(loc_v4[c4], sizeof(loc_v4[c4]), "%s", canon); + if (v4 && c4 < max_v4) snprintf(v4[c4], 16, "%s", canon); + c4++; + } + } else if (inet_pton(AF_INET6, tok, &a6) == 1) { + if (!geminux_dns_v6_valid(&a6)) return -1; + char canon[46]; + if (!inet_ntop(AF_INET6, &a6, canon, sizeof(canon))) return -1; + bool dup = false; + for (int i = 0; i < c6; i++) { + if (strcmp(loc_v6[i], canon) == 0) { + dup = true; + break; + } + } + if (!dup) { + if (c4 + c6 >= GEMINUX_DNS_MAX_SERVERS) return -1; + snprintf(loc_v6[c6], sizeof(loc_v6[c6]), "%s", canon); + if (v6 && c6 < max_v6) snprintf(v6[c6], 46, "%s", canon); + c6++; + } + } else { + return -1; + } + } + + int total = c4 + c6; + if (total <= 0) return -1; + if (n_v4) *n_v4 = c4; + if (n_v6) *n_v6 = c6; + + if (norm_csv && norm_sz > 0) { + size_t pos = 0; + for (int i = 0; i < c4; i++) { + int w = snprintf(norm_csv + pos, norm_sz - pos, "%s%s", pos ? "," : "", loc_v4[i]); + if (w < 0 || (size_t)w >= norm_sz - pos) return -1; + pos += (size_t)w; + } + for (int i = 0; i < c6; i++) { + int w = snprintf(norm_csv + pos, norm_sz - pos, "%s%s", pos ? "," : "", loc_v6[i]); + if (w < 0 || (size_t)w >= norm_sz - pos) return -1; + pos += (size_t)w; + } + } + return total; +} + +static inline int geminux_parse_resolv_conf(const char *text, char *summary, size_t summary_sz) { + if (summary && summary_sz > 0) summary[0] = '\0'; + if (!text || !text[0]) return 0; + + int count = 0; + size_t pos = 0; + const char *cur = text; + while (*cur && count < 3) { + const char *nl = strchr(cur, '\n'); + size_t raw_len = nl ? (size_t)(nl - cur) : strlen(cur); + char ln[256]; + size_t cp = raw_len < sizeof(ln) - 1 ? raw_len : sizeof(ln) - 1; + memcpy(ln, cur, cp); + ln[cp] = '\0'; + cur = nl ? nl + 1 : cur + raw_len; + + char *p = ln; + while (*p == ' ' || *p == '\t') p++; + if (strncmp(p, "nameserver", 10) != 0) continue; + p += 10; + if (*p != ' ' && *p != '\t') continue; + while (*p == ' ' || *p == '\t') p++; + char *end = p; + while (*end && *end != ' ' && *end != '\t' && *end != '\r' && *end != '#') end++; + *end = '\0'; + if (!geminux_dns_token_chars_ok(p)) continue; + + struct in_addr a4; + struct in6_addr a6; + if (inet_pton(AF_INET, p, &a4) != 1 && inet_pton(AF_INET6, p, &a6) != 1) continue; + + if (summary && pos + 2 < summary_sz) { + int w = snprintf(summary + pos, summary_sz - pos, "%s%s", count ? ", " : "", p); + if (w > 0 && (size_t)w < summary_sz - pos) pos += (size_t)w; + } + count++; + } + return count; +} + +#endif /* GEMINUX_DNS_VALID_H */ diff --git a/src/geminux-daemons/geminux-dnsctl.c b/src/geminux-daemons/geminux-dnsctl.c new file mode 100644 index 0000000..83e092e --- /dev/null +++ b/src/geminux-daemons/geminux-dnsctl.c @@ -0,0 +1,384 @@ +#define _POSIX_C_SOURCE 200809L +#include "geminux-dns-valid.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define GEMINUX_DNS_CONF_DIR "/etc/geminux" +#define GEMINUX_DNS_CONF_PATH "/etc/geminux/dns.conf" +#define GEMINUX_NM_DNS_DROPIN "/etc/NetworkManager/conf.d/30-geminux-dns.conf" + +static int run_argv(const char *const argv[], char *out, size_t out_sz, bool quiet) { + int pfd[2] = {-1, -1}; + if (out && out_sz > 0) { + out[0] = '\0'; + if (pipe(pfd) < 0) return -1; + } + + pid_t pid = fork(); + if (pid < 0) { + if (pfd[0] >= 0) { + close(pfd[0]); + close(pfd[1]); + } + return -1; + } + if (pid == 0) { + if (pfd[1] >= 0) { + close(pfd[0]); + dup2(pfd[1], STDOUT_FILENO); + if (pfd[1] > 2) close(pfd[1]); + } + if (quiet || pfd[1] >= 0) { + int devnull = open("/dev/null", O_RDWR); + if (devnull >= 0) { + if (quiet && pfd[1] < 0) dup2(devnull, STDOUT_FILENO); + if (quiet) dup2(devnull, STDERR_FILENO); + if (devnull > 2) close(devnull); + } + } + execvp(argv[0], (char *const *)argv); + _exit(127); + } + + if (pfd[1] >= 0) close(pfd[1]); + if (pfd[0] >= 0) { + size_t pos = 0; + while (pos + 1 < out_sz) { + ssize_t n = read(pfd[0], out + pos, out_sz - 1 - pos); + if (n > 0) pos += (size_t)n; + else if (n < 0 && errno == EINTR) continue; + else break; + } + out[pos] = '\0'; + close(pfd[0]); + } + + int status = 0; + while (waitpid(pid, &status, 0) < 0) { + if (errno != EINTR) return -1; + } + if (WIFEXITED(status)) return WEXITSTATUS(status); + return 1; +} + +static int write_file_atomic(const char *path, const char *content, mode_t mode) { + char tmp[512]; + snprintf(tmp, sizeof(tmp), "%s.tmp", path); + int fd = open(tmp, O_WRONLY | O_CREAT | O_TRUNC, mode); + if (fd < 0) return -1; + size_t len = strlen(content); + size_t off = 0; + while (off < len) { + ssize_t w = write(fd, content + off, len - off); + if (w < 0) { + if (errno == EINTR) continue; + close(fd); + unlink(tmp); + return -1; + } + off += (size_t)w; + } + close(fd); + chmod(tmp, mode); + if (rename(tmp, path) != 0) { + unlink(tmp); + return -1; + } + return 0; +} + +static void read_saved_conf(char *mode_out, size_t mode_sz, + char *custom_out, size_t custom_sz) { + snprintf(mode_out, mode_sz, "default"); + custom_out[0] = '\0'; + FILE *f = fopen(GEMINUX_DNS_CONF_PATH, "r"); + if (!f) return; + char line[256]; + while (fgets(line, sizeof(line), f)) { + size_t n = strlen(line); + while (n > 0 && (line[n - 1] == '\n' || line[n - 1] == '\r')) line[--n] = '\0'; + if (strncmp(line, "mode=", 5) == 0 && geminux_dns_mode_valid(line + 5)) { + snprintf(mode_out, mode_sz, "%s", line + 5); + } else if (strncmp(line, "custom=", 7) == 0) { + snprintf(custom_out, custom_sz, "%s", line + 7); + } + } + fclose(f); +} + +static bool ipv6_default_route_present(void) { + FILE *f = fopen("/proc/net/ipv6_route", "r"); + if (!f) return false; + char line[512]; + bool found = false; + while (fgets(line, sizeof(line), f)) { + char dst[64], plen[16], src[64], splen[16], nh[64]; + unsigned int metric, refcnt, use, flags; + char iface[32]; + if (sscanf(line, "%63s %15s %63s %15s %63s %x %x %x %x %31s", + dst, plen, src, splen, nh, &metric, &refcnt, &use, &flags, iface) == 10) { + if (strcmp(dst, "00000000000000000000000000000000") == 0 && + strcmp(plen, "00") == 0 && + strcmp(iface, "lo") != 0 && + (flags & 1U)) { + found = true; + break; + } + } + } + fclose(f); + return found; +} + +static void join_space(char *dst, size_t dst_sz, char arr[][16], int n) { + dst[0] = '\0'; + size_t pos = 0; + for (int i = 0; i < n; i++) { + int w = snprintf(dst + pos, dst_sz - pos, "%s%s", i ? " " : "", arr[i]); + if (w > 0 && (size_t)w < dst_sz - pos) pos += (size_t)w; + } +} + +static void join_space_v6(char *dst, size_t dst_sz, char arr[][46], int n) { + dst[0] = '\0'; + size_t pos = 0; + for (int i = 0; i < n; i++) { + int w = snprintf(dst + pos, dst_sz - pos, "%s%s", i ? " " : "", arr[i]); + if (w > 0 && (size_t)w < dst_sz - pos) pos += (size_t)w; + } +} + +static bool nm_type_managed_dns(const char *type) { + return strcmp(type, "802-11-wireless") == 0 || + strcmp(type, "gsm") == 0 || + strcmp(type, "802-3-ethernet") == 0; +} + +static void update_nm_profiles(const char *v4_space, const char *v6_space, bool reset_default) { + char list[8192]; + const char *show[] = {"nmcli", "-t", "-f", "UUID,TYPE", "connection", "show", NULL}; + if (run_argv(show, list, sizeof(list), true) != 0) return; + + char *save = NULL; + for (char *ln = strtok_r(list, "\n", &save); ln; ln = strtok_r(NULL, "\n", &save)) { + char *sep = strchr(ln, ':'); + if (!sep) continue; + *sep = '\0'; + const char *uuid = ln; + const char *type = sep + 1; + if (!uuid[0] || !nm_type_managed_dns(type)) continue; + + if (reset_default) { + const char *mod[] = { + "nmcli", "connection", "modify", "uuid", uuid, + "ipv4.dns", "", "ipv4.ignore-auto-dns", "no", + "ipv6.dns", "", "ipv6.ignore-auto-dns", "no", NULL + }; + run_argv(mod, NULL, 0, true); + } else { + const char *mod[] = { + "nmcli", "connection", "modify", "uuid", uuid, + "ipv4.dns", v4_space ? v4_space : "", + "ipv4.ignore-auto-dns", "yes", + "ipv6.dns", v6_space ? v6_space : "", + "ipv6.ignore-auto-dns", "yes", NULL + }; + run_argv(mod, NULL, 0, true); + } + } +} + +static void write_resolv_fallback(char v4[][16], int n_v4, char v6[][46], int n_v6, bool use_v6) { + char buf[512]; + size_t pos = 0; + int written = 0; + + int w = snprintf(buf + pos, sizeof(buf) - pos, "# Managed by geminux-dnsctl\n"); + if (w > 0 && (size_t)w < sizeof(buf) - pos) pos += (size_t)w; + + for (int i = 0; i < n_v4 && written < 3; i++) { + w = snprintf(buf + pos, sizeof(buf) - pos, "nameserver %s\n", v4[i]); + if (w > 0 && (size_t)w < sizeof(buf) - pos) pos += (size_t)w; + written++; + } + if (use_v6) { + for (int i = 0; i < n_v6 && written < 3; i++) { + w = snprintf(buf + pos, sizeof(buf) - pos, "nameserver %s\n", v6[i]); + if (w > 0 && (size_t)w < sizeof(buf) - pos) pos += (size_t)w; + written++; + } + } + w = snprintf(buf + pos, sizeof(buf) - pos, "options timeout:2 attempts:2\n"); + if (w > 0 && (size_t)w < sizeof(buf) - pos) pos += (size_t)w; + write_file_atomic("/etc/resolv.conf", buf, 0644); +} + +static bool resolv_has_first_expected(const char *expected_first) { + if (!expected_first || !expected_first[0]) return false; + FILE *f = fopen("/etc/resolv.conf", "r"); + if (!f) return false; + char line[256]; + bool found = false; + while (fgets(line, sizeof(line), f)) { + char ns[64]; + if (sscanf(line, "nameserver %63s", ns) == 1) { + if (strcmp(ns, expected_first) == 0) found = true; + break; + } + } + fclose(f); + return found; +} + +static int apply_dns(const char *mode, const char *custom_arg, bool save_conf) { + int idx = geminux_dns_mode_index(mode); + if (idx < 0) { + fprintf(stderr, "geminux-dnsctl: invalid DNS mode '%s'\n", mode ? mode : ""); + return 1; + } + + char prev_mode[32], prev_custom[256]; + read_saved_conf(prev_mode, sizeof(prev_mode), prev_custom, sizeof(prev_custom)); + + char saved_custom[256]; + snprintf(saved_custom, sizeof(saved_custom), "%s", prev_custom); + + if (idx == GEMINUX_DNS_DEFAULT) { + unlink(GEMINUX_NM_DNS_DROPIN); + if (save_conf) { + mkdir(GEMINUX_DNS_CONF_DIR, 0755); + char cfg[384]; + snprintf(cfg, sizeof(cfg), "mode=default\ncustom=%s\n", saved_custom); + if (write_file_atomic(GEMINUX_DNS_CONF_PATH, cfg, 0644) != 0) { + perror("geminux-dnsctl: write dns.conf"); + return 1; + } + } + update_nm_profiles("", "", true); + const char *rel[] = {"nmcli", "general", "reload", NULL}; + run_argv(rel, NULL, 0, true); + const char *reapp[] = {"nmcli", "device", "reapply", "wlan0", NULL}; + run_argv(reapp, NULL, 0, true); + return 0; + } + + const char *raw_servers = NULL; + char combined_preset[192]; + if (idx == GEMINUX_DNS_CUSTOM) { + raw_servers = (custom_arg && custom_arg[0]) ? custom_arg : prev_custom; + } else { + const geminux_dns_preset_t *p = &GEMINUX_DNS_PRESETS[idx]; + if (p->v6_csv[0]) { + snprintf(combined_preset, sizeof(combined_preset), "%s,%s", p->v4_csv, p->v6_csv); + raw_servers = combined_preset; + } else { + raw_servers = p->v4_csv; + } + } + + char v4[GEMINUX_DNS_MAX_SERVERS][16]; + char v6[GEMINUX_DNS_MAX_SERVERS][46]; + int n_v4 = 0, n_v6 = 0; + char norm_csv[256]; + if (geminux_parse_dns_servers(raw_servers, v4, &n_v4, GEMINUX_DNS_MAX_SERVERS, + v6, &n_v6, GEMINUX_DNS_MAX_SERVERS, + norm_csv, sizeof(norm_csv)) <= 0) { + fprintf(stderr, "geminux-dnsctl: invalid nameserver list '%s'\n", + raw_servers ? raw_servers : ""); + return 1; + } + + if (idx == GEMINUX_DNS_CUSTOM) { + snprintf(saved_custom, sizeof(saved_custom), "%s", norm_csv); + } + + bool has_v6_route = ipv6_default_route_present(); + bool include_v6_global = (idx == GEMINUX_DNS_CUSTOM) ? (n_v6 > 0 && (n_v4 == 0 || has_v6_route)) + : (n_v6 > 0 && has_v6_route); + + char global_servers[256] = {0}; + size_t gpos = 0; + for (int i = 0; i < n_v4; i++) { + int w = snprintf(global_servers + gpos, sizeof(global_servers) - gpos, + "%s%s", gpos ? "," : "", v4[i]); + if (w > 0 && (size_t)w < sizeof(global_servers) - gpos) gpos += (size_t)w; + } + if (include_v6_global) { + for (int i = 0; i < n_v6; i++) { + int w = snprintf(global_servers + gpos, sizeof(global_servers) - gpos, + "%s%s", gpos ? "," : "", v6[i]); + if (w > 0 && (size_t)w < sizeof(global_servers) - gpos) gpos += (size_t)w; + } + } + + if (save_conf) { + mkdir(GEMINUX_DNS_CONF_DIR, 0755); + char cfg[384]; + snprintf(cfg, sizeof(cfg), "mode=%s\ncustom=%s\n", mode, saved_custom); + if (write_file_atomic(GEMINUX_DNS_CONF_PATH, cfg, 0644) != 0) { + perror("geminux-dnsctl: write dns.conf"); + return 1; + } + } + + mkdir("/etc/NetworkManager", 0755); + mkdir("/etc/NetworkManager/conf.d", 0755); + char dropin[512]; + snprintf(dropin, sizeof(dropin), + "# Managed by geminux-dnsctl\n" + "[main]\n" + "dns=default\n\n" + "[global-dns]\n" + "options=timeout:2,attempts:2\n\n" + "[global-dns-domain-*]\n" + "servers=%s\n", + global_servers); + if (write_file_atomic(GEMINUX_NM_DNS_DROPIN, dropin, 0644) != 0) { + perror("geminux-dnsctl: write NM dropin"); + return 1; + } + + char v4_space[128], v6_space[256]; + join_space(v4_space, sizeof(v4_space), v4, n_v4); + join_space_v6(v6_space, sizeof(v6_space), v6, include_v6_global ? n_v6 : 0); + update_nm_profiles(v4_space, v6_space, false); + + const char *rel[] = {"nmcli", "general", "reload", NULL}; + run_argv(rel, NULL, 0, true); + const char *reapp[] = {"nmcli", "device", "reapply", "wlan0", NULL}; + run_argv(reapp, NULL, 0, true); + + const char *first_expected = (n_v4 > 0) ? v4[0] : (n_v6 > 0 ? v6[0] : ""); + if (first_expected[0] && !resolv_has_first_expected(first_expected)) { + write_resolv_fallback(v4, n_v4, v6, n_v6, include_v6_global); + } + return 0; +} + +int main(int argc, char **argv) { + if (argc >= 3 && strcmp(argv[1], "set") == 0) { + const char *mode = argv[2]; + const char *custom = (argc >= 4) ? argv[3] : ""; + if (argc > 4) { + fprintf(stderr, "Usage: %s \n", argv[0]); + return 1; + } + return apply_dns(mode, custom, true); + } + if (argc == 2 && strcmp(argv[1], "apply") == 0) { + char mode[32], custom[256]; + read_saved_conf(mode, sizeof(mode), custom, sizeof(custom)); + if (strcmp(mode, "default") == 0) return 0; + return apply_dns(mode, custom, false); + } + fprintf(stderr, "Usage: %s \n", argv[0]); + return 1; +} diff --git a/src/libgemui/gemui.c b/src/libgemui/gemui.c index ee2c435..7d6951f 100644 --- a/src/libgemui/gemui.c +++ b/src/libgemui/gemui.c @@ -66,6 +66,8 @@ struct gemui_app { char toast_msg[256]; uint64_t toast_until_ms; bool ptr_down; + Window prev_focus_win; + int prev_focus_revert; }; static int g_sig_pipe[2] = {-1, -1}; @@ -302,6 +304,33 @@ static void gemui_ensure_backbuf(gemui_app_t *app) { app->bh = app->h; } +static int gemui_ignore_xerror(Display *dpy, XErrorEvent *ev) { + (void)dpy; + (void)ev; + return 0; +} + +static void gemui_save_prev_focus(gemui_app_t *app) { + if (!app || app->prev_focus_win != None) return; + Window cur = None; + int rev = RevertToPointerRoot; + XGetInputFocus(app->dpy, &cur, &rev); + if (cur != None && cur != app->win) { + app->prev_focus_win = cur; + app->prev_focus_revert = rev; + } +} + +static void gemui_restore_prev_focus(gemui_app_t *app) { + if (!app || app->prev_focus_win == None || app->prev_focus_win == app->win) return; + XSync(app->dpy, False); + int (*old_handler)(Display *, XErrorEvent *) = XSetErrorHandler(gemui_ignore_xerror); + XSetInputFocus(app->dpy, app->prev_focus_win, app->prev_focus_revert, CurrentTime); + XSync(app->dpy, False); + XSetErrorHandler(old_handler); + app->prev_focus_win = None; +} + gemui_app_t *gemui_create(const char *res_name, const char *title, int w, int h, bool fullscreen_override) { setlocale(LC_CTYPE, ""); @@ -386,6 +415,7 @@ gemui_app_t *gemui_create(const char *res_name, const char *title, XMapRaised(dpy, app->win); if (fullscreen_override) { XMoveResizeWindow(dpy, app->win, 0, 0, (unsigned int)sw, (unsigned int)sh); + gemui_save_prev_focus(app); XSetInputFocus(dpy, app->win, RevertToPointerRoot, CurrentTime); } XFlush(dpy); @@ -395,6 +425,7 @@ gemui_app_t *gemui_create(const char *res_name, const char *title, void gemui_destroy(gemui_app_t *app) { if (!app) return; + gemui_restore_prev_focus(app); if (app->xic) XDestroyIC(app->xic); if (app->xim) XCloseIM(app->xim); if (app->backbuf) XFreePixmap(app->dpy, app->backbuf); @@ -492,6 +523,7 @@ bool gemui_grab_input(gemui_app_t *app) { XGrabPointer(app->dpy, app->win, True, ButtonPressMask | ButtonReleaseMask | PointerMotionMask, GrabModeAsync, GrabModeAsync, app->win, None, CurrentTime); + gemui_save_prev_focus(app); XSetInputFocus(app->dpy, app->win, RevertToPointerRoot, CurrentTime); XFlush(app->dpy); return ok_kbd; @@ -501,6 +533,7 @@ void gemui_ungrab_input(gemui_app_t *app) { if (!app) return; XUngrabKeyboard(app->dpy, CurrentTime); XUngrabPointer(app->dpy, CurrentTime); + gemui_restore_prev_focus(app); XFlush(app->dpy); } diff --git a/src/st/x.c b/src/st/x.c index c8a1b08..e2381dc 100644 --- a/src/st/x.c +++ b/src/st/x.c @@ -1901,6 +1901,7 @@ focus(XEvent *ev) xseturgency(0); if (IS_SET(MODE_FOCUS)) ttywrite("\033[I", 3, 0); + redraw(); } else { xshowpointer(); if (xw.ime.xic) @@ -1910,6 +1911,7 @@ focus(XEvent *ev) win.mode &= ~MODE_FOCUSED; if (IS_SET(MODE_FOCUS)) ttywrite("\033[O", 3, 0); + redraw(); } } diff --git a/src/webarchy/webarchy.cpp b/src/webarchy/webarchy.cpp new file mode 100644 index 0000000..46c7e3d --- /dev/null +++ b/src/webarchy/webarchy.cpp @@ -0,0 +1,1914 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Webarchy WebKit2GTK Browser for Geminux (Gemini PDA 2160x1080 Ultrawide) +// +// Ported from Bananarchy's Webarchy with: +// - Right-side collapsible vertical tab bar tailored for the 2160x1080 2:1 panel +// - Multi-tab WebKitWebView stack (Ctrl+T/Ctrl+W/Ctrl+Tab/Alt+1..9, middle-click & target=_blank tabs) +// - Live .Xresources theming + SIGUSR1 live reload (geminux-apply-theme) +// - Omnibar (URL / DuckDuckGo search), persistent SQLite cookies & bookmarks, UA presets, +// dark inverter, reader width fit toggle, find-in-page, zoom controls, and single-instance FIFO +// - GPU/Panfrost profile with automatic CPU renderer fallback on WebProcess crash + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +constexpr const char* kDefaultUserAgent = + "Mozilla/5.0 (X11; Linux aarch64; rv:128.0) Gecko/20100101 Firefox/128.0"; + +constexpr const char* kDefaultHomepage = "https://lite.duckduckgo.com/lite/"; + +// WebKitGTK reads WEBKIT_DISABLE_* / WEBKIT_SKIA_* variables as presence flags, +// not as booleans. Never leave them set to "0" in the environment. +constexpr const char* kSoftwareRendererFlag = + "/.config/geminux/webarchy/software_renderer"; + +std::string getHomeDirPath() { + const char* home = std::getenv("HOME"); + if (home && home[0]) return std::string(home); + return "/home/user"; +} + +std::string deviceTreeCompatibles() { + FILE* f = std::fopen("/proc/device-tree/compatible", "rb"); + if (!f) return {}; + char buf[512]; + size_t n = std::fread(buf, 1, sizeof(buf), f); + std::fclose(f); + std::string raw(buf, n); + std::replace(raw.begin(), raw.end(), '\0', ' '); + return raw; +} + +bool webarchySoftwareRendererPreferred() { + if (deviceTreeCompatibles().find("nokia,beatles") != std::string::npos) + return true; + return ::access((getHomeDirPath() + kSoftwareRendererFlag).c_str(), F_OK) == 0; +} + +void configureWebkitRenderer(bool software) { + // Presence flags: never leave them defined as "0" in the browser's environment. + ::unsetenv("WEBKIT_DISABLE_DMABUF_RENDERER"); + ::unsetenv("WEBKIT_DISABLE_COMPOSITING_MODE"); + ::unsetenv("WEBKIT_SKIA_ENABLE_CPU_RENDERING"); + ::setenv("GDK_BACKEND", "x11", 1); + ::setenv("GTK_THEME", "Adwaita:dark", 1); + ::setenv("NO_AT_BRIDGE", "1", 1); + ::setenv("GTK_A11Y", "none", 1); + ::setenv("WEBKIT_DISABLE_SANDBOX_THIS_IS_DANGEROUS", "1", 1); + if (software) { + ::setenv("WEBKIT_DISABLE_DMABUF_RENDERER", "1", 1); + ::setenv("WEBKIT_SKIA_ENABLE_CPU_RENDERING", "1", 1); + } + // JSC options are value-based and must not override a session setting. + if (!::getenv("JSC_useJIT")) ::setenv("JSC_useJIT", "1", 1); + if (!::getenv("JSC_useDFGJIT")) ::setenv("JSC_useDFGJIT", "1", 1); + if (!::getenv("JSC_useFTLJIT")) ::setenv("JSC_useFTLJIT", "0", 1); +} + +std::string trimStr(const std::string& s) { + size_t b = 0; + while (b < s.size() && std::isspace(static_cast(s[b]))) ++b; + size_t e = s.size(); + while (e > b && std::isspace(static_cast(s[e - 1]))) --e; + return s.substr(b, e - b); +} + +std::string toLowerStr(std::string s) { + for (char& c : s) c = static_cast(std::tolower(static_cast(c))); + return s; +} + +void ensureParentDir(const std::string& filePath) { + size_t pos = 0; + while ((pos = filePath.find('/', pos + 1)) != std::string::npos) { + std::string dir = filePath.substr(0, pos); + if (!dir.empty()) ::mkdir(dir.c_str(), 0755); + } +} + +std::string configDirPath() { + return getHomeDirPath() + "/.config/geminux/webarchy"; +} + +std::string bookmarksPath() { + return configDirPath() + "/bookmarks.tsv"; +} + +std::string userAgentPath() { + return configDirPath() + "/ua.txt"; +} + +std::string fifoRuntimePath() { + std::ostringstream oss; + oss << "/tmp/webarchy-" << static_cast(::getuid()) << ".fifo"; + return oss.str(); +} + +std::string pidRuntimePath() { + std::ostringstream oss; + oss << "/tmp/webarchy-" << static_cast(::getuid()) << ".pid"; + return oss.str(); +} + +struct BookmarkEntry { + std::string title; + std::string url; +}; + +std::vector createDefaultBookmarks() { + return { + {"DuckDuckGo Lite", kDefaultHomepage}, + {"Wikipedia", "https://en.wikipedia.org/"}, + {"Hacker News", "https://news.ycombinator.com/"}, + {"GitHub", "https://github.com/"}, + {"YouTube", "https://www.youtube.com/"}, + {"Lobsters", "https://lobste.rs/"}, + {"NPR Text", "https://text.npr.org/"}, + {"Wttr Weather", "https://wttr.in/"}, + }; +} + +std::vector loadBookmarks() { + std::ifstream in(bookmarksPath()); + if (!in.is_open()) { + return createDefaultBookmarks(); + } + std::vector out; + std::string line; + while (std::getline(in, line)) { + if (!line.empty() && line.back() == '\r') line.pop_back(); + if (line.empty()) continue; + std::vector cols; + std::stringstream ss(line); + std::string col; + while (std::getline(ss, col, '\t')) cols.push_back(col); + if (cols.size() >= 3 && !trimStr(cols[2]).empty()) { + out.push_back({trimStr(cols[1]), trimStr(cols[2])}); + } else if (cols.size() == 2 && !trimStr(cols[1]).empty()) { + out.push_back({trimStr(cols[0]), trimStr(cols[1])}); + } else if (cols.size() == 1 && !trimStr(cols[0]).empty()) { + out.push_back({trimStr(cols[0]), trimStr(cols[0])}); + } + } + if (out.empty()) return createDefaultBookmarks(); + return out; +} + +void saveBookmarks(const std::vector& bm) { + std::string path = bookmarksPath(); + ensureParentDir(path); + std::ofstream out(path, std::ios::trunc); + if (!out.is_open()) return; + for (size_t i = 0; i < bm.size(); ++i) { + out << i << "\t" << bm[i].title << "\t" << bm[i].url << "\n"; + } +} + +std::string loadUserAgent() { + std::ifstream in(userAgentPath()); + std::string line; + if (in.is_open() && std::getline(in, line)) { + line = trimStr(line); + if (!line.empty()) return line; + } + return kDefaultUserAgent; +} + +void saveUserAgent(const std::string& ua) { + std::string path = userAgentPath(); + ensureParentDir(path); + std::ofstream out(path, std::ios::trunc); + if (out.is_open()) out << ua << "\n"; +} + +std::string urlEncodeQuery(const std::string& s) { + std::string out; + char hex[4]; + for (unsigned char c : s) { + if (std::isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') { + out.push_back(static_cast(c)); + } else if (c == ' ') { + out.push_back('+'); + } else { + std::snprintf(hex, sizeof(hex), "%%%02X", c); + out += hex; + } + } + return out; +} + +std::string normalizeInputUrlOrSearch(const std::string& rawInput) { + std::string s = trimStr(rawInput); + if (s.empty()) return kDefaultHomepage; + std::string low = toLowerStr(s); + if (low.rfind("http://", 0) == 0 || + low.rfind("https://", 0) == 0 || + low.rfind("file://", 0) == 0 || + low.rfind("data:", 0) == 0 || + low.rfind("about:", 0) == 0) { + return s; + } + if (s.find(' ') != std::string::npos || + (s.find('.') == std::string::npos && low != "localhost" && + low.rfind("localhost:", 0) != 0)) { + return "https://lite.duckduckgo.com/lite/?q=" + urlEncodeQuery(s); + } + return "https://" + s; +} + +std::string extractHostFromUrl(const std::string& url) { + size_t pos = url.find("://"); + std::string rest = (pos != std::string::npos) ? url.substr(pos + 3) : url; + size_t slash = rest.find('/'); + if (slash != std::string::npos) rest = rest.substr(0, slash); + if (rest.rfind("www.", 0) == 0 && rest.size() > 4) rest = rest.substr(4); + return rest.empty() ? "Webarchy" : rest; +} + +// Engine-level UserStyleSheet (bypasses site Content-Security-Policy) +constexpr const char* kWebarchyInjectedCss = R"CSS( +:root { + color-scheme: light dark; +} +html.__wa_dark__ { + filter: invert(0.92) hue-rotate(180deg) !important; + background: #111 !important; +} +html.__wa_dark__ img, html.__wa_dark__ video { + filter: invert(1) hue-rotate(180deg) !important; +} +html.__wa_fit__, html.__wa_fit__ body { + max-width: 100vw !important; + overflow-x: hidden !important; + word-wrap: break-word !important; +} +html.__wa_fit__ img, html.__wa_fit__ video, html.__wa_fit__ iframe, html.__wa_fit__ table, html.__wa_fit__ pre { + max-width: 100% !important; + height: auto !important; +} +button, input, select, textarea, optgroup { + font-family: "Noto Sans", sans-serif; +} +code, pre, kbd, samp, tt { + font-family: "Fira Code", monospace; + font-variant-ligatures: contextual common-ligatures; + font-feature-settings: "calt" 1, "liga" 1; +} +)CSS"; + +constexpr const char* kWebarchyInjectedJs = R"JS( +(function() { + if (window.__webarchy) return; + const W = { + darkMode: false, + mobileFit: false, + applyVisualFlags: function() { + if (!document.documentElement) return; + document.documentElement.classList.toggle('__wa_dark__', !!this.darkMode); + document.documentElement.classList.toggle('__wa_fit__', !!this.mobileFit); + }, + setFlags: function(dark, fit) { + this.darkMode = !!dark; + this.mobileFit = !!fit; + this.applyVisualFlags(); + } + }; + window.__webarchy = W; + document.addEventListener('DOMContentLoaded', function() { W.applyVisualFlags(); }); + window.addEventListener('load', function() { W.applyVisualFlags(); }); +})(); +)JS"; + +struct UaPreset { + const char* name; + const char* ua; +}; + +static const UaPreset kUaPresets[] = { + { "Firefox Linux Desktop (Default)", + "Mozilla/5.0 (X11; Linux aarch64; rv:128.0) Gecko/20100101 Firefox/128.0" }, + { "Chromium Linux Desktop", + "Mozilla/5.0 (X11; Linux aarch64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36" }, + { "Firefox Android Mobile", + "Mozilla/5.0 (Android 14; Mobile; rv:128.0) Gecko/128.0 Firefox/128.0" }, + { "Safari iPadOS Tablet", + "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.5 Safari/605.1.15" }, + { "KaiOS 4.0 Ultra-Light", + "Mozilla/5.0 (Mobile; rv:123.0) Gecko/123.0 Firefox/123.0 KAIOS/4.0" }, +}; + +struct XresTheme { + std::string fontFace = "Fira Code, Noto Sans"; + std::string bgMain = "#0f1419"; + std::string bgBar = "#0b0e14"; + std::string bgHeader = "#131922"; + std::string bgOverlay = "#161d26"; + std::string bgAltEven = "#121820"; + std::string bgAltOdd = "#18202a"; + std::string bgInput = "#0b0e14"; + std::string bgInputFocus = "#1b2838"; + std::string bgButton = "#1d2633"; + std::string fgMain = "#e6e1cf"; + std::string fgBright = "#ffffff"; + std::string fgMuted = "#7b8898"; + std::string selBg = "#2b5278"; + std::string selFg = "#ffffff"; + std::string accent = "#59c2ff"; + std::string accentAlt = "#ffb454"; + std::string border = "#283444"; + std::string divider = "#364559"; + std::string danger = "#f07178"; + std::string dangerBg = "#4c1d24"; +}; + +XresTheme loadXresourcesTheme() { + XresTheme t; + std::string path = getHomeDirPath() + "/.Xresources"; + std::ifstream in(path); + if (!in.is_open()) { + in.open("/etc/skel/.Xresources"); + } + if (!in.is_open()) return t; + + std::map kv; + std::string line; + while (std::getline(in, line)) { + std::string s = trimStr(line); + if (s.empty() || s[0] == '!' || s[0] == '#') continue; + size_t colon = s.find(':'); + if (colon == std::string::npos) continue; + std::string key = trimStr(s.substr(0, colon)); + std::string val = trimStr(s.substr(colon + 1)); + if (!key.empty() && !val.empty()) kv[key] = val; + } + + auto pick = [&](const char* k, std::string& dst) { + auto it = kv.find(k); + if (it != kv.end() && !it->second.empty()) dst = it->second; + }; + pick("theme.fontFace", t.fontFace); + pick("theme.bgMain", t.bgMain); + pick("theme.bgBar", t.bgBar); + pick("theme.bgHeader", t.bgHeader); + pick("theme.bgOverlay", t.bgOverlay); + pick("theme.bgAltEven", t.bgAltEven); + pick("theme.bgAltOdd", t.bgAltOdd); + pick("theme.bgInput", t.bgInput); + pick("theme.bgInputFocus", t.bgInputFocus); + pick("theme.bgButton", t.bgButton); + pick("theme.fgMain", t.fgMain); + pick("theme.fgBright", t.fgBright); + pick("theme.fgMuted", t.fgMuted); + pick("theme.selBg", t.selBg); + pick("theme.selFg", t.selFg); + pick("theme.accent", t.accent); + pick("theme.accentAlt", t.accentAlt); + pick("theme.border", t.border); + pick("theme.divider", t.divider); + pick("theme.danger", t.danger); + pick("theme.dangerBg", t.dangerBg); + return t; +} + +struct BrowserApp; + +struct TabEntry { + int id = 0; + BrowserApp* app = nullptr; + WebKitWebView* webView = nullptr; + std::string stackName; + std::string url = kDefaultHomepage; + std::string title = "New Tab"; + double progress = 1.0; + bool loading = false; + bool playingAudio = false; + bool darkMode = false; + bool mobileFit = false; + + // Widgets in right-side vertical tab bar + GtkWidget* rowBox = nullptr; + GtkWidget* activateBtn = nullptr; + GtkWidget* idxLabel = nullptr; + GtkWidget* titleLabel = nullptr; + GtkWidget* domainLabel = nullptr; + GtkWidget* closeBtn = nullptr; +}; + +struct BrowserApp { + GtkWidget* window = nullptr; + GtkCssProvider* cssProvider = nullptr; + + WebKitWebContext* webCtx = nullptr; + WebKitUserContentManager* ucm = nullptr; + WebKitSettings* wkSettings = nullptr; + WebKitWebsitePolicies* wkPolicies = nullptr; + + GtkWidget* backBtn = nullptr; + GtkWidget* fwdBtn = nullptr; + GtkWidget* reloadBtn = nullptr; + GtkWidget* homeBtn = nullptr; + GtkEntry* urlEntry = nullptr; + GtkWidget* bookmarkBtn = nullptr; + GtkWidget* menuBtn = nullptr; + GtkWidget* toggleTabsBtn = nullptr; + GtkProgressBar* progressBar = nullptr; + + GtkRevealer* findRevealer = nullptr; + GtkEntry* findEntry = nullptr; + GtkLabel* findCountLabel = nullptr; + + GtkStack* webStack = nullptr; + GtkLabel* statusLabel = nullptr; + GtkLabel* modeBadgeLabel = nullptr; + + // Right-side vertical tab bar (tailored for 2160x1080 ultrawide) + GtkWidget* tabSidebar = nullptr; + GtkLabel* tabHeaderLabel = nullptr; + GtkWidget* tabListBox = nullptr; + GtkWidget* tabDarkBtn = nullptr; + GtkLabel* zoomLabel = nullptr; + + // Menu popover widgets + GtkWidget* toolsPopover = nullptr; + GtkWidget* bookmarksPopover = nullptr; + GtkWidget* bookmarksListBox = nullptr; + GtkWidget* darkCheckBtn = nullptr; + GtkWidget* fitCheckBtn = nullptr; + GtkWidget* swCheckBtn = nullptr; + GtkWidget* uaCombo = nullptr; + + bool softwareRenderer = false; + bool tabBarVisible = true; + bool fullscreen = false; + int nextTabId = 1; + int activeTabIndex = -1; + int fifoFd = -1; + guint fifoWatchId = 0; + + std::string userAgent = kDefaultUserAgent; + std::string statusMsg = "Ready"; + std::string hoveredUri; + std::vector bookmarks; + std::vector> tabs; + std::vector closedTabUrls; + bool syncingUiFlags = false; +}; + +void applyGtkThemeCss(BrowserApp* app) { + if (!app || !app->cssProvider) return; + XresTheme t = loadXresourcesTheme(); + std::string gtkFont = t.fontFace + ", Noto Sans 9"; + if (GtkSettings* gs = gtk_settings_get_default()) { + g_object_set(gs, + "gtk-application-prefer-dark-theme", TRUE, + "gtk-theme-name", "Adwaita:dark", + "gtk-font-name", gtkFont.c_str(), + nullptr); + } + std::ostringstream css; + css << "* { font-family: \"" << t.fontFace << "\", \"Noto Sans\", sans-serif; }\n" + << "window, #wa-root, #wa-main-pane { background-color: " << t.bgMain << "; color: " << t.fgMain << "; }\n" + << "#wa-navbar { background-color: " << t.bgBar << "; border-bottom: 1px solid " << t.border + << "; padding: 5px 8px; }\n" + << "#wa-navbar button, #wa-tabbar button, #wa-findbar button { " + << "background-image: none; background-color: " << t.bgButton << "; color: " << t.fgBright + << "; border: 1px solid " << t.border << "; border-radius: 5px; box-shadow: none; " + << "padding: 4px 9px; font-size: 9pt; min-height: 32px; min-width: 32px; }\n" + << "#wa-navbar button:hover, #wa-tabbar button:hover, #wa-findbar button:hover { " + << "background-color: " << t.bgInputFocus << "; border-color: " << t.accent << "; }\n" + << "#wa-navbar button:disabled { color: " << t.fgMuted << "; background-color: " << t.bgBar << "; }\n" + << "#wa-navbar button.active-accent, #wa-tabbar button.active-accent { " + << "background-color: " << t.selBg << "; color: " << t.selFg << "; border-color: " << t.accent << "; }\n" + << "#wa-urlbar, #wa-findbar entry { background-image: none; background-color: " << t.bgInput + << "; color: " << t.fgBright << "; border: 1px solid " << t.border << "; border-radius: 5px; " + << "padding: 4px 10px; font-size: 9pt; min-height: 32px; caret-color: " << t.accent << "; }\n" + << "#wa-urlbar:focus, #wa-findbar entry:focus { background-color: " << t.bgInputFocus + << "; border-color: " << t.accent << "; }\n" + << "#wa-progress progressbar, #wa-progress { min-height: 2px; background-color: " << t.bgBar << "; border: none; }\n" + << "#wa-progress trough { min-height: 2px; background-color: " << t.bgBar << "; border: none; }\n" + << "#wa-progress progress { min-height: 2px; background-color: " << t.accent << "; }\n" + << "#wa-findbar { background-color: " << t.bgHeader << "; border-bottom: 1px solid " << t.border + << "; padding: 4px 8px; }\n" + << "#wa-tabbar { background-color: " << t.bgBar << "; border-left: 1px solid " << t.border << "; }\n" + << "#wa-tabbar-header { background-color: " << t.bgHeader << "; border-bottom: 1px solid " << t.border + << "; padding: 6px 8px; }\n" + << "#wa-tabbar-header label { font-size: 8.5pt; font-weight: bold; color: " << t.accent << "; }\n" + << "#wa-newtab-btn { background-color: " << t.selBg << "; color: " << t.selFg + << "; border-color: " << t.accent << "; font-weight: bold; font-size: 8.5pt; padding: 4px 9px; min-height: 28px; }\n" + << "#wa-tablist { padding: 5px; background-color: " << t.bgBar << "; }\n" + << ".wa-tab-row { background-color: " << t.bgAltEven << "; border: 1px solid " << t.border + << "; border-radius: 6px; margin-bottom: 4px; }\n" + << ".wa-tab-row.active { background-color: " << t.selBg << "; border: 1px solid " << t.accent << "; }\n" + << ".wa-tab-btn { background: transparent; border: none; box-shadow: none; padding: 5px 6px; min-height: 38px; }\n" + << ".wa-tab-btn:hover { background-color: rgba(255,255,255,0.05); border-color: transparent; }\n" + << ".wa-tab-idx { font-size: 8.5pt; font-weight: bold; color: " << t.accentAlt << "; min-width: 20px; }\n" + << ".wa-tab-row.active .wa-tab-idx { color: " << t.selFg << "; }\n" + << ".wa-tab-title { font-size: 8.5pt; color: " << t.fgMain << "; }\n" + << ".wa-tab-row.active .wa-tab-title { font-weight: bold; color: " << t.selFg << "; }\n" + << ".wa-tab-domain { font-size: 7.2pt; color: " << t.fgMuted << "; }\n" + << ".wa-tab-row.active .wa-tab-domain { color: " << t.fgBright << "; }\n" + << ".wa-tab-close { background: transparent; border: none; color: " << t.fgMuted + << "; padding: 3px 7px; min-width: 28px; min-height: 28px; font-size: 9pt; }\n" + << ".wa-tab-close:hover { background-color: " << t.dangerBg << "; color: " << t.danger << "; }\n" + << "#wa-tabbar-footer { background-color: " << t.bgHeader << "; border-top: 1px solid " << t.border + << "; padding: 5px 8px; }\n" + << "#wa-tabbar-footer button { font-size: 8.5pt; padding: 3px 8px; min-height: 28px; min-width: 28px; }\n" + << "#wa-tabbar-footer label { font-size: 8.5pt; font-weight: bold; color: " << t.fgBright << "; }\n" + << "#wa-statusbar { background-color: " << t.bgBar << "; border-top: 1px solid " << t.border + << "; padding: 3px 8px; }\n" + << "#wa-statusbar label { font-size: 7.5pt; color: " << t.fgMuted << "; }\n" + << "popover, popover box { background-color: " << t.bgOverlay << "; color: " << t.fgMain + << "; border: 1px solid " << t.border << "; }\n" + << "popover checkbutton, popover label, popover button, combobox, menu, menuitem { " + << "color: " << t.fgMain << "; font-size: 8.5pt; }\n"; + + gtk_css_provider_load_from_data(app->cssProvider, css.str().c_str(), -1, nullptr); +} + +TabEntry* currentTab(BrowserApp* app) { + if (!app || app->activeTabIndex < 0 || + app->activeTabIndex >= static_cast(app->tabs.size())) { + return nullptr; + } + return app->tabs[app->activeTabIndex].get(); +} + +int findBookmarkIndex(const BrowserApp* app, const std::string& url) { + if (!app || url.empty()) return -1; + for (size_t i = 0; i < app->bookmarks.size(); ++i) { + if (app->bookmarks[i].url == url) return static_cast(i); + } + return -1; +} + +void evalJsOnTab(TabEntry* tab, const std::string& code) { + if (!tab || !tab->webView) return; + webkit_web_view_evaluate_javascript(tab->webView, code.c_str(), -1, + nullptr, nullptr, nullptr, nullptr, nullptr); +} + +void syncJsFlags(TabEntry* tab) { + if (!tab) return; + std::ostringstream oss; + oss << "if(window.__webarchy)window.__webarchy.setFlags(" + << (tab->darkMode ? "true" : "false") << "," + << (tab->mobileFit ? "true" : "false") << ");"; + evalJsOnTab(tab, oss.str()); +} + +void updateTabRowVisual(TabEntry* tab, int index, bool active) { + if (!tab || !tab->rowBox) return; + GtkStyleContext* ctx = gtk_widget_get_style_context(tab->rowBox); + if (active) gtk_style_context_add_class(ctx, "active"); + else gtk_style_context_remove_class(ctx, "active"); + + std::string badge; + if (tab->loading) badge = "◌"; + else if (tab->playingAudio) badge = "♪"; + else if (index < 9) badge = std::to_string(index + 1); + else badge = "•"; + gtk_label_set_text(GTK_LABEL(tab->idxLabel), badge.c_str()); + + std::string title = tab->title.empty() ? extractHostFromUrl(tab->url) : tab->title; + gtk_label_set_text(GTK_LABEL(tab->titleLabel), title.c_str()); + + std::string host = extractHostFromUrl(tab->url); + gtk_label_set_text(GTK_LABEL(tab->domainLabel), host.c_str()); +} + +void refreshBookmarksPopover(BrowserApp* app); + +void refreshChromeUi(BrowserApp* app) { + if (!app) return; + TabEntry* tab = currentTab(app); + + for (size_t i = 0; i < app->tabs.size(); ++i) { + updateTabRowVisual(app->tabs[i].get(), static_cast(i), + static_cast(i) == app->activeTabIndex); + } + std::string tabHdr = "TABS (" + std::to_string(app->tabs.size()) + ")"; + if (app->tabHeaderLabel) gtk_label_set_text(app->tabHeaderLabel, tabHdr.c_str()); + + if (!tab) return; + + if (!gtk_widget_has_focus(GTK_WIDGET(app->urlEntry))) { + gtk_entry_set_text(app->urlEntry, tab->url.c_str()); + } + + gtk_widget_set_sensitive(app->backBtn, webkit_web_view_can_go_back(tab->webView)); + gtk_widget_set_sensitive(app->fwdBtn, webkit_web_view_can_go_forward(tab->webView)); + gtk_button_set_label(GTK_BUTTON(app->reloadBtn), tab->loading ? "✕" : "↻"); + + bool bookmarked = findBookmarkIndex(app, tab->url) >= 0; + gtk_button_set_label(GTK_BUTTON(app->bookmarkBtn), bookmarked ? "★" : "☆"); + GtkStyleContext* bmCtx = gtk_widget_get_style_context(app->bookmarkBtn); + if (bookmarked) gtk_style_context_add_class(bmCtx, "active-accent"); + else gtk_style_context_remove_class(bmCtx, "active-accent"); + + if (tab->loading && tab->progress < 0.99) { + gtk_progress_bar_set_fraction(app->progressBar, std::clamp(tab->progress, 0.05, 0.98)); + gtk_widget_show(GTK_WIDGET(app->progressBar)); + } else { + gtk_widget_hide(GTK_WIDGET(app->progressBar)); + } + + std::string stLine = !app->hoveredUri.empty() + ? ("Link: " + app->hoveredUri) + : app->statusMsg; + gtk_label_set_text(app->statusLabel, stLine.c_str()); + + int zoomPct = static_cast(std::round(webkit_web_view_get_zoom_level(tab->webView) * 100.0)); + std::string badge = std::string(app->softwareRenderer ? "SW" : "GPU") + + (tab->darkMode ? " • DARK" : "") + + (tab->mobileFit ? " • FIT" : "") + + " • " + std::to_string(zoomPct) + "%"; + gtk_label_set_text(app->modeBadgeLabel, badge.c_str()); + + if (app->zoomLabel) { + std::string zTxt = std::to_string(zoomPct) + "%"; + gtk_label_set_text(app->zoomLabel, zTxt.c_str()); + } + + if (app->tabDarkBtn) { + GtkStyleContext* dc = gtk_widget_get_style_context(app->tabDarkBtn); + if (tab->darkMode) gtk_style_context_add_class(dc, "active-accent"); + else gtk_style_context_remove_class(dc, "active-accent"); + } + + app->syncingUiFlags = true; + if (app->darkCheckBtn) + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(app->darkCheckBtn), tab->darkMode); + if (app->fitCheckBtn) + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(app->fitCheckBtn), tab->mobileFit); + if (app->swCheckBtn) + gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(app->swCheckBtn), app->softwareRenderer); + app->syncingUiFlags = false; + + std::string winTitle = + (tab->title.empty() ? extractHostFromUrl(tab->url) : tab->title) + " — Webarchy"; + gtk_window_set_title(GTK_WINDOW(app->window), winTitle.c_str()); +} + +void selectTab(BrowserApp* app, int index) { + if (!app || app->tabs.empty()) return; + index = std::clamp(index, 0, static_cast(app->tabs.size()) - 1); + app->activeTabIndex = index; + TabEntry* tab = app->tabs[index].get(); + gtk_stack_set_visible_child_name(app->webStack, tab->stackName.c_str()); + app->hoveredUri.clear(); + app->statusMsg = tab->loading ? ("Loading " + extractHostFromUrl(tab->url) + "...") : tab->url; + refreshChromeUi(app); +} + +int indexOfTab(BrowserApp* app, TabEntry* target) { + if (!app || !target) return -1; + for (size_t i = 0; i < app->tabs.size(); ++i) { + if (app->tabs[i].get() == target) return static_cast(i); + } + return -1; +} + +void closeTabAt(BrowserApp* app, int index) { + if (!app || index < 0 || index >= static_cast(app->tabs.size())) return; + if (app->tabs.size() == 1) { + TabEntry* sole = app->tabs[0].get(); + if (!sole->url.empty() && sole->url != kDefaultHomepage) { + app->closedTabUrls.push_back(sole->url); + if (app->closedTabUrls.size() > 16) app->closedTabUrls.erase(app->closedTabUrls.begin()); + } + webkit_web_view_load_uri(sole->webView, kDefaultHomepage); + refreshChromeUi(app); + return; + } + + TabEntry* doomed = app->tabs[index].get(); + if (!doomed->url.empty()) { + app->closedTabUrls.push_back(doomed->url); + if (app->closedTabUrls.size() > 16) app->closedTabUrls.erase(app->closedTabUrls.begin()); + } + gtk_container_remove(GTK_CONTAINER(app->tabListBox), doomed->rowBox); + gtk_container_remove(GTK_CONTAINER(app->webStack), GTK_WIDGET(doomed->webView)); + app->tabs.erase(app->tabs.begin() + index); + + int nextIdx = app->activeTabIndex; + if (index < nextIdx) --nextIdx; + nextIdx = std::clamp(nextIdx, 0, static_cast(app->tabs.size()) - 1); + selectTab(app, nextIdx); +} + +TabEntry* createTab(BrowserApp* app, const std::string& initialUrl, bool switchTo, + WebKitWebView* relatedTo = nullptr); + +void onLoadChanged(WebKitWebView* webView, WebKitLoadEvent loadEvent, gpointer ud) { + auto* tab = static_cast(ud); + if (!tab || !tab->app) return; + const char* uri = webkit_web_view_get_uri(webView); + if (uri && uri[0]) tab->url = uri; + const char* title = webkit_web_view_get_title(webView); + if (title && title[0]) tab->title = title; + else tab->title = extractHostFromUrl(tab->url); + + if (loadEvent == WEBKIT_LOAD_STARTED || loadEvent == WEBKIT_LOAD_REDIRECTED) { + tab->loading = true; + tab->progress = 0.08; + if (tab == currentTab(tab->app)) { + tab->app->statusMsg = "Loading " + extractHostFromUrl(tab->url) + "..."; + } + } else if (loadEvent == WEBKIT_LOAD_COMMITTED) { + tab->loading = true; + syncJsFlags(tab); + } else if (loadEvent == WEBKIT_LOAD_FINISHED) { + tab->loading = false; + tab->progress = 1.0; + syncJsFlags(tab); + if (tab == currentTab(tab->app)) { + tab->app->statusMsg = tab->url; + } + } + refreshChromeUi(tab->app); +} + +void onNotifyWebViewProp(GObject* obj, GParamSpec*, gpointer ud) { + auto* tab = static_cast(ud); + auto* wv = WEBKIT_WEB_VIEW(obj); + if (!tab || !tab->app || !wv) return; + const char* uri = webkit_web_view_get_uri(wv); + if (uri && uri[0]) tab->url = uri; + const char* title = webkit_web_view_get_title(wv); + if (title && title[0]) tab->title = title; + else tab->title = extractHostFromUrl(tab->url); + tab->progress = webkit_web_view_get_estimated_load_progress(wv); + tab->playingAudio = webkit_web_view_is_playing_audio(wv); + refreshChromeUi(tab->app); +} + +void onMouseTargetChanged(WebKitWebView*, WebKitHitTestResult* hit, guint, gpointer ud) { + auto* tab = static_cast(ud); + if (!tab || !tab->app || tab != currentTab(tab->app)) return; + if (hit && webkit_hit_test_result_context_is_link(hit)) { + const char* link = webkit_hit_test_result_get_link_uri(hit); + tab->app->hoveredUri = (link && link[0]) ? link : ""; + } else { + tab->app->hoveredUri.clear(); + } + refreshChromeUi(tab->app); +} + +gboolean onDecidePolicy(WebKitWebView*, + WebKitPolicyDecision* decision, + WebKitPolicyDecisionType type, + gpointer ud) { + auto* tab = static_cast(ud); + if (!tab || !tab->app) return FALSE; + + if (type == WEBKIT_POLICY_DECISION_TYPE_NEW_WINDOW_ACTION) { + auto* navDec = WEBKIT_NAVIGATION_POLICY_DECISION(decision); + WebKitNavigationAction* action = + webkit_navigation_policy_decision_get_navigation_action(navDec); + WebKitURIRequest* req = webkit_navigation_action_get_request(action); + const char* uri = req ? webkit_uri_request_get_uri(req) : nullptr; + if (uri && uri[0]) { + createTab(tab->app, uri, true); + } + webkit_policy_decision_ignore(decision); + return TRUE; + } + + if (type == WEBKIT_POLICY_DECISION_TYPE_NAVIGATION_ACTION) { + auto* navDec = WEBKIT_NAVIGATION_POLICY_DECISION(decision); + WebKitNavigationAction* action = + webkit_navigation_policy_decision_get_navigation_action(navDec); + WebKitNavigationType navType = webkit_navigation_action_get_navigation_type(action); + guint btn = webkit_navigation_action_get_mouse_button(action); + guint mods = webkit_navigation_action_get_modifiers(action); + if (navType == WEBKIT_NAVIGATION_TYPE_LINK_CLICKED && + (btn == 2 || (mods & GDK_CONTROL_MASK) != 0)) { + WebKitURIRequest* req = webkit_navigation_action_get_request(action); + const char* uri = req ? webkit_uri_request_get_uri(req) : nullptr; + if (uri && uri[0]) { + createTab(tab->app, uri, (mods & GDK_SHIFT_MASK) == 0); + webkit_policy_decision_ignore(decision); + return TRUE; + } + } + } + return FALSE; +} + +GtkWidget* onCreatePopupWebView(WebKitWebView* parentWv, + WebKitNavigationAction* action, + gpointer ud) { + auto* tab = static_cast(ud); + if (!tab || !tab->app) return nullptr; + WebKitURIRequest* req = action ? webkit_navigation_action_get_request(action) : nullptr; + const char* uri = req ? webkit_uri_request_get_uri(req) : nullptr; + if (uri && uri[0] && std::strcmp(uri, "about:blank") != 0) { + createTab(tab->app, uri, true); + return nullptr; + } + TabEntry* child = createTab(tab->app, "", true, parentWv); + return child ? GTK_WIDGET(child->webView) : nullptr; +} + +gboolean onPermissionRequest(WebKitWebView*, WebKitPermissionRequest* req, gpointer) { + webkit_permission_request_allow(req); + return TRUE; +} + +gboolean onLoadFailed(WebKitWebView*, WebKitLoadEvent, gchar* failingUri, GError* error, gpointer ud) { + auto* tab = static_cast(ud); + if (!tab || !tab->app) return FALSE; + tab->loading = false; + tab->progress = 1.0; + if (error) { + std::ostringstream oss; + oss << "Load failed: " << (error->message ? error->message : "WebKit error"); + if (error->domain) + oss << " [" << g_quark_to_string(error->domain) << "/" << error->code << "]"; + if (tab->app->softwareRenderer) oss << " (SW)"; + tab->app->statusMsg = oss.str(); + } else if (failingUri) { + tab->app->statusMsg = std::string("Failed: ") + failingUri; + } + refreshChromeUi(tab->app); + return FALSE; +} + +gboolean onWebProcessTerminated(WebKitWebView*, + WebKitWebProcessTerminationReason reason, + gpointer ud) { + auto* tab = static_cast(ud); + if (!tab || !tab->app) return TRUE; + BrowserApp* app = tab->app; + tab->loading = false; + tab->progress = 1.0; + if (!app->softwareRenderer && app->wkSettings && + reason == WEBKIT_WEB_PROCESS_CRASHED) { + app->softwareRenderer = true; + configureWebkitRenderer(true); + webkit_settings_set_hardware_acceleration_policy( + app->wkSettings, WEBKIT_HARDWARE_ACCELERATION_POLICY_NEVER); + app->statusMsg = "GPU renderer crashed; switched to software rendering"; + if (!tab->url.empty()) { + webkit_web_view_load_uri(tab->webView, tab->url.c_str()); + } + } else { + app->statusMsg = "Web process restarted"; + } + refreshChromeUi(app); + return TRUE; +} + +gboolean onTabButtonPress(GtkWidget*, GdkEventButton* ev, gpointer ud) { + auto* tab = static_cast(ud); + if (!tab || !tab->app) return FALSE; + int idx = indexOfTab(tab->app, tab); + if (idx < 0) return FALSE; + if (ev->type == GDK_BUTTON_PRESS && ev->button == 2) { + closeTabAt(tab->app, idx); + return TRUE; + } + return FALSE; +} + +void onTabActivateClicked(GtkButton*, gpointer ud) { + auto* tab = static_cast(ud); + if (!tab || !tab->app) return; + int idx = indexOfTab(tab->app, tab); + if (idx >= 0) selectTab(tab->app, idx); +} + +void onTabCloseClicked(GtkButton*, gpointer ud) { + auto* tab = static_cast(ud); + if (!tab || !tab->app) return; + int idx = indexOfTab(tab->app, tab); + if (idx >= 0) closeTabAt(tab->app, idx); +} + +TabEntry* createTab(BrowserApp* app, const std::string& initialUrl, bool switchTo, + WebKitWebView* relatedTo) { + auto tab = std::make_unique(); + tab->id = app->nextTabId++; + tab->app = app; + tab->stackName = "tab-" + std::to_string(tab->id); + tab->url = initialUrl.empty() ? kDefaultHomepage : initialUrl; + + if (relatedTo) { + tab->webView = WEBKIT_WEB_VIEW(g_object_new( + WEBKIT_TYPE_WEB_VIEW, + "related-view", relatedTo, + nullptr)); + } else { + tab->webView = WEBKIT_WEB_VIEW(g_object_new( + WEBKIT_TYPE_WEB_VIEW, + "web-context", app->webCtx, + "user-content-manager", app->ucm, + "settings", app->wkSettings, + "website-policies", app->wkPolicies, + nullptr)); + } + + g_signal_connect(tab->webView, "load-changed", G_CALLBACK(onLoadChanged), tab.get()); + g_signal_connect(tab->webView, "load-failed", G_CALLBACK(onLoadFailed), tab.get()); + g_signal_connect(tab->webView, "notify::uri", G_CALLBACK(onNotifyWebViewProp), tab.get()); + g_signal_connect(tab->webView, "notify::title", G_CALLBACK(onNotifyWebViewProp), tab.get()); + g_signal_connect(tab->webView, "notify::estimated-load-progress", + G_CALLBACK(onNotifyWebViewProp), tab.get()); + g_signal_connect(tab->webView, "notify::is-playing-audio", + G_CALLBACK(onNotifyWebViewProp), tab.get()); + g_signal_connect(tab->webView, "mouse-target-changed", + G_CALLBACK(onMouseTargetChanged), tab.get()); + g_signal_connect(tab->webView, "decide-policy", G_CALLBACK(onDecidePolicy), tab.get()); + g_signal_connect(tab->webView, "create", G_CALLBACK(onCreatePopupWebView), tab.get()); + g_signal_connect(tab->webView, "permission-request", G_CALLBACK(onPermissionRequest), tab.get()); + g_signal_connect(tab->webView, "web-process-terminated", + G_CALLBACK(onWebProcessTerminated), tab.get()); + + // Build vertical tab row widget for the right sidebar + tab->rowBox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 2); + gtk_style_context_add_class(gtk_widget_get_style_context(tab->rowBox), "wa-tab-row"); + + tab->activateBtn = gtk_button_new(); + gtk_widget_set_can_focus(tab->activateBtn, FALSE); + gtk_style_context_add_class(gtk_widget_get_style_context(tab->activateBtn), "wa-tab-btn"); + + GtkWidget* btnInner = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 6); + tab->idxLabel = gtk_label_new("1"); + gtk_style_context_add_class(gtk_widget_get_style_context(tab->idxLabel), "wa-tab-idx"); + gtk_label_set_xalign(GTK_LABEL(tab->idxLabel), 0.5f); + + GtkWidget* textCol = gtk_box_new(GTK_ORIENTATION_VERTICAL, 1); + tab->titleLabel = gtk_label_new("New Tab"); + gtk_style_context_add_class(gtk_widget_get_style_context(tab->titleLabel), "wa-tab-title"); + gtk_label_set_xalign(GTK_LABEL(tab->titleLabel), 0.0f); + gtk_label_set_ellipsize(GTK_LABEL(tab->titleLabel), PANGO_ELLIPSIZE_END); + gtk_label_set_single_line_mode(GTK_LABEL(tab->titleLabel), TRUE); + + tab->domainLabel = gtk_label_new("Webarchy"); + gtk_style_context_add_class(gtk_widget_get_style_context(tab->domainLabel), "wa-tab-domain"); + gtk_label_set_xalign(GTK_LABEL(tab->domainLabel), 0.0f); + gtk_label_set_ellipsize(GTK_LABEL(tab->domainLabel), PANGO_ELLIPSIZE_END); + gtk_label_set_single_line_mode(GTK_LABEL(tab->domainLabel), TRUE); + + gtk_box_pack_start(GTK_BOX(textCol), tab->titleLabel, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(textCol), tab->domainLabel, FALSE, FALSE, 0); + + gtk_box_pack_start(GTK_BOX(btnInner), tab->idxLabel, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(btnInner), textCol, TRUE, TRUE, 0); + gtk_container_add(GTK_CONTAINER(tab->activateBtn), btnInner); + + tab->closeBtn = gtk_button_new_with_label("×"); + gtk_widget_set_can_focus(tab->closeBtn, FALSE); + gtk_style_context_add_class(gtk_widget_get_style_context(tab->closeBtn), "wa-tab-close"); + + gtk_box_pack_start(GTK_BOX(tab->rowBox), tab->activateBtn, TRUE, TRUE, 0); + gtk_box_pack_end(GTK_BOX(tab->rowBox), tab->closeBtn, FALSE, FALSE, 0); + + g_signal_connect(tab->activateBtn, "clicked", G_CALLBACK(onTabActivateClicked), tab.get()); + g_signal_connect(tab->activateBtn, "button-press-event", G_CALLBACK(onTabButtonPress), tab.get()); + g_signal_connect(tab->closeBtn, "clicked", G_CALLBACK(onTabCloseClicked), tab.get()); + + gtk_widget_show_all(tab->rowBox); + gtk_widget_show(GTK_WIDGET(tab->webView)); + gtk_stack_add_named(app->webStack, GTK_WIDGET(tab->webView), tab->stackName.c_str()); + gtk_box_pack_start(GTK_BOX(app->tabListBox), tab->rowBox, FALSE, FALSE, 0); + + TabEntry* raw = tab.get(); + app->tabs.push_back(std::move(tab)); + int newIdx = static_cast(app->tabs.size()) - 1; + + if (!initialUrl.empty()) { + webkit_web_view_load_uri(raw->webView, initialUrl.c_str()); + } + if (switchTo || app->tabs.size() == 1) { + selectTab(app, newIdx); + } else { + refreshChromeUi(app); + } + return raw; +} + +void navigateCurrentTab(BrowserApp* app, const std::string& rawInput) { + TabEntry* tab = currentTab(app); + if (!tab || !tab->webView) return; + std::string url = normalizeInputUrlOrSearch(rawInput); + tab->url = url; + app->statusMsg = "Loading " + extractHostFromUrl(url) + "..."; + webkit_web_view_load_uri(tab->webView, url.c_str()); + gtk_widget_grab_focus(GTK_WIDGET(tab->webView)); + refreshChromeUi(app); +} + +void toggleBookmarkCurrent(BrowserApp* app) { + TabEntry* tab = currentTab(app); + if (!tab || tab->url.empty()) return; + int idx = findBookmarkIndex(app, tab->url); + if (idx >= 0) { + app->bookmarks.erase(app->bookmarks.begin() + idx); + app->statusMsg = "Removed bookmark"; + } else { + std::string title = tab->title.empty() ? extractHostFromUrl(tab->url) : tab->title; + app->bookmarks.push_back({title, tab->url}); + app->statusMsg = "Saved bookmark: " + title; + } + saveBookmarks(app->bookmarks); + refreshBookmarksPopover(app); + refreshChromeUi(app); +} + +void adjustZoom(BrowserApp* app, double delta) { + TabEntry* tab = currentTab(app); + if (!tab || !tab->webView) return; + double cur = webkit_web_view_get_zoom_level(tab->webView); + double next = (delta == 0.0) ? 1.0 : std::clamp(cur + delta, 0.5, 2.5); + webkit_web_view_set_zoom_level(tab->webView, next); + app->statusMsg = "Zoom: " + std::to_string(static_cast(std::round(next * 100.0))) + "%"; + refreshChromeUi(app); +} + +void toggleDarkMode(BrowserApp* app) { + TabEntry* tab = currentTab(app); + if (!tab) return; + tab->darkMode = !tab->darkMode; + syncJsFlags(tab); + app->statusMsg = tab->darkMode ? "Dark mode enabled" : "Dark mode disabled"; + refreshChromeUi(app); +} + +void toggleMobileFit(BrowserApp* app) { + TabEntry* tab = currentTab(app); + if (!tab) return; + tab->mobileFit = !tab->mobileFit; + syncJsFlags(tab); + app->statusMsg = tab->mobileFit ? "Reader width fit enabled" : "Reader width fit disabled"; + refreshChromeUi(app); +} + +void toggleTabSidebar(BrowserApp* app) { + if (!app || !app->tabSidebar) return; + app->tabBarVisible = !app->tabBarVisible; + gtk_widget_set_visible(app->tabSidebar, app->tabBarVisible); + GtkStyleContext* ctx = gtk_widget_get_style_context(app->toggleTabsBtn); + if (app->tabBarVisible) gtk_style_context_add_class(ctx, "active-accent"); + else gtk_style_context_remove_class(ctx, "active-accent"); +} + +void openFindBar(BrowserApp* app) { + if (!app || !app->findRevealer) return; + gtk_revealer_set_reveal_child(app->findRevealer, TRUE); + gtk_widget_grab_focus(GTK_WIDGET(app->findEntry)); + gtk_editable_select_region(GTK_EDITABLE(app->findEntry), 0, -1); +} + +void closeFindBar(BrowserApp* app) { + if (!app || !app->findRevealer) return; + gtk_revealer_set_reveal_child(app->findRevealer, FALSE); + if (TabEntry* tab = currentTab(app)) { + WebKitFindController* fc = webkit_web_view_get_find_controller(tab->webView); + webkit_find_controller_search_finish(fc); + gtk_widget_grab_focus(GTK_WIDGET(tab->webView)); + } + gtk_label_set_text(app->findCountLabel, ""); +} + +void runFindSearch(BrowserApp* app, const char* text) { + TabEntry* tab = currentTab(app); + if (!tab) return; + WebKitFindController* fc = webkit_web_view_get_find_controller(tab->webView); + if (!text || !text[0]) { + webkit_find_controller_search_finish(fc); + gtk_label_set_text(app->findCountLabel, ""); + return; + } + webkit_find_controller_search(fc, text, WEBKIT_FIND_OPTIONS_CASE_INSENSITIVE | WEBKIT_FIND_OPTIONS_WRAP_AROUND, 256); +} + +struct BookmarkClickCtx { + BrowserApp* app; + size_t idx; + bool newTab; +}; + +void destroyCtx(gpointer data, GClosure*) { + delete static_cast(data); +} + +void onBookmarkOpenClicked(GtkButton*, gpointer ud) { + auto* ctx = static_cast(ud); + if (!ctx || !ctx->app || ctx->idx >= ctx->app->bookmarks.size()) return; + std::string url = ctx->app->bookmarks[ctx->idx].url; + gtk_popover_popdown(GTK_POPOVER(ctx->app->bookmarksPopover)); + if (ctx->newTab) { + createTab(ctx->app, url, true); + } else { + navigateCurrentTab(ctx->app, url); + } +} + +void onBookmarkDeleteClicked(GtkButton*, gpointer ud) { + auto* ctx = static_cast(ud); + if (!ctx || !ctx->app || ctx->idx >= ctx->app->bookmarks.size()) return; + BrowserApp* app = ctx->app; + app->bookmarks.erase(app->bookmarks.begin() + static_cast(ctx->idx)); + saveBookmarks(app->bookmarks); + refreshBookmarksPopover(app); + refreshChromeUi(app); +} + +void refreshBookmarksPopover(BrowserApp* app) { + if (!app || !app->bookmarksListBox) return; + GList* children = gtk_container_get_children(GTK_CONTAINER(app->bookmarksListBox)); + for (GList* l = children; l != nullptr; l = l->next) { + gtk_widget_destroy(GTK_WIDGET(l->data)); + } + g_list_free(children); + + if (app->bookmarks.empty()) { + GtkWidget* emptyLbl = gtk_label_new("No bookmarks saved yet. Press ☆ or Ctrl+D."); + gtk_box_pack_start(GTK_BOX(app->bookmarksListBox), emptyLbl, FALSE, FALSE, 4); + gtk_widget_show(emptyLbl); + return; + } + + for (size_t i = 0; i < app->bookmarks.size(); ++i) { + const auto& bm = app->bookmarks[i]; + GtkWidget* row = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 4); + std::string label = (bm.title.empty() ? extractHostFromUrl(bm.url) : bm.title) + + " [" + extractHostFromUrl(bm.url) + "]"; + GtkWidget* openBtn = gtk_button_new_with_label(label.c_str()); + if (GtkWidget* lbl = gtk_bin_get_child(GTK_BIN(openBtn))) { + gtk_label_set_xalign(GTK_LABEL(lbl), 0.0f); + gtk_label_set_ellipsize(GTK_LABEL(lbl), PANGO_ELLIPSIZE_END); + } + GtkWidget* tabBtn = gtk_button_new_with_label("+Tab"); + GtkWidget* delBtn = gtk_button_new_with_label("×"); + + g_signal_connect_data(openBtn, "clicked", G_CALLBACK(onBookmarkOpenClicked), + new BookmarkClickCtx{app, i, false}, destroyCtx, GConnectFlags(0)); + g_signal_connect_data(tabBtn, "clicked", G_CALLBACK(onBookmarkOpenClicked), + new BookmarkClickCtx{app, i, true}, destroyCtx, GConnectFlags(0)); + g_signal_connect_data(delBtn, "clicked", G_CALLBACK(onBookmarkDeleteClicked), + new BookmarkClickCtx{app, i, false}, destroyCtx, GConnectFlags(0)); + + gtk_box_pack_start(GTK_BOX(row), openBtn, TRUE, TRUE, 0); + gtk_box_pack_start(GTK_BOX(row), tabBtn, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(row), delBtn, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(app->bookmarksListBox), row, FALSE, FALSE, 0); + } + gtk_widget_show_all(app->bookmarksListBox); +} + +void promptCustomUserAgent(BrowserApp* app) { + GtkWidget* dlg = gtk_dialog_new_with_buttons( + "Custom User-Agent", + GTK_WINDOW(app->window), + static_cast(GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT), + "Cancel", GTK_RESPONSE_CANCEL, + "Apply", GTK_RESPONSE_ACCEPT, + nullptr); + GtkWidget* area = gtk_dialog_get_content_area(GTK_DIALOG(dlg)); + GtkWidget* entry = gtk_entry_new(); + gtk_entry_set_text(GTK_ENTRY(entry), app->userAgent.c_str()); + gtk_entry_set_width_chars(GTK_ENTRY(entry), 56); + gtk_box_pack_start(GTK_BOX(area), entry, TRUE, TRUE, 8); + gtk_widget_show_all(dlg); + if (gtk_dialog_run(GTK_DIALOG(dlg)) == GTK_RESPONSE_ACCEPT) { + std::string val = trimStr(gtk_entry_get_text(GTK_ENTRY(entry))); + if (!val.empty()) { + app->userAgent = val; + saveUserAgent(val); + webkit_settings_set_user_agent(app->wkSettings, val.c_str()); + if (TabEntry* tab = currentTab(app)) webkit_web_view_reload(tab->webView); + app->statusMsg = "Updated custom User-Agent"; + refreshChromeUi(app); + } + } + gtk_widget_destroy(dlg); +} + +void onUaComboChanged(GtkComboBox* combo, gpointer ud) { + auto* app = static_cast(ud); + if (!app || app->syncingUiFlags) return; + int active = gtk_combo_box_get_active(combo); + constexpr int numPresets = static_cast(sizeof(kUaPresets) / sizeof(kUaPresets[0])); + if (active >= 0 && active < numPresets) { + app->userAgent = kUaPresets[active].ua; + saveUserAgent(app->userAgent); + webkit_settings_set_user_agent(app->wkSettings, app->userAgent.c_str()); + if (TabEntry* tab = currentTab(app)) webkit_web_view_reload(tab->webView); + app->statusMsg = std::string("User-Agent: ") + kUaPresets[active].name; + refreshChromeUi(app); + } else if (active == numPresets) { + gtk_popover_popdown(GTK_POPOVER(app->toolsPopover)); + promptCustomUserAgent(app); + } +} + +void onSoftwareRendererToggled(GtkToggleButton* btn, gpointer ud) { + auto* app = static_cast(ud); + if (!app || app->syncingUiFlags) return; + bool sw = gtk_toggle_button_get_active(btn); + app->softwareRenderer = sw; + configureWebkitRenderer(sw); + webkit_settings_set_hardware_acceleration_policy( + app->wkSettings, + sw ? WEBKIT_HARDWARE_ACCELERATION_POLICY_NEVER + : WEBKIT_HARDWARE_ACCELERATION_POLICY_ALWAYS); + + std::string flagPath = getHomeDirPath() + kSoftwareRendererFlag; + if (sw) { + ensureParentDir(flagPath); + std::ofstream out(flagPath, std::ios::trunc); + if (out.is_open()) out << "1\n"; + } else { + ::unlink(flagPath.c_str()); + } + if (TabEntry* tab = currentTab(app)) webkit_web_view_reload(tab->webView); + app->statusMsg = sw ? "Switched to Software WebKit renderer" : "Switched to GPU WebKit renderer"; + refreshChromeUi(app); +} + +gboolean onWindowKeyPress(GtkWidget*, GdkEventKey* ev, gpointer ud) { + auto* app = static_cast(ud); + if (!app) return FALSE; + guint kv = ev->keyval; + guint mods = ev->state & (GDK_CONTROL_MASK | GDK_SHIFT_MASK | GDK_MOD1_MASK); + bool ctrl = (mods & GDK_CONTROL_MASK) != 0; + bool shift = (mods & GDK_SHIFT_MASK) != 0; + bool alt = (mods & GDK_MOD1_MASK) != 0; + + if (ctrl && !shift && !alt && (kv == GDK_KEY_t || kv == GDK_KEY_T)) { + createTab(app, kDefaultHomepage, true); + gtk_widget_grab_focus(GTK_WIDGET(app->urlEntry)); + gtk_editable_select_region(GTK_EDITABLE(app->urlEntry), 0, -1); + return TRUE; + } + if (ctrl && shift && !alt && (kv == GDK_KEY_T || kv == GDK_KEY_t)) { + if (!app->closedTabUrls.empty()) { + std::string url = app->closedTabUrls.back(); + app->closedTabUrls.pop_back(); + createTab(app, url, true); + } + return TRUE; + } + if (ctrl && !alt && (kv == GDK_KEY_w || kv == GDK_KEY_W)) { + closeTabAt(app, app->activeTabIndex); + return TRUE; + } + if (ctrl && !alt && (kv == GDK_KEY_q || kv == GDK_KEY_Q)) { + gtk_main_quit(); + return TRUE; + } + if ((ctrl && kv == GDK_KEY_Tab) || (alt && (kv == GDK_KEY_Down || kv == GDK_KEY_Page_Down))) { + if (!app->tabs.empty()) { + int next = (app->activeTabIndex + (shift ? -1 : 1) + static_cast(app->tabs.size())) % + static_cast(app->tabs.size()); + selectTab(app, next); + } + return TRUE; + } + if ((ctrl && (kv == GDK_KEY_ISO_Left_Tab || (shift && kv == GDK_KEY_Tab))) || + (alt && (kv == GDK_KEY_Up || kv == GDK_KEY_Page_Up))) { + if (!app->tabs.empty()) { + int prev = (app->activeTabIndex - 1 + static_cast(app->tabs.size())) % + static_cast(app->tabs.size()); + selectTab(app, prev); + } + return TRUE; + } + if (alt && !ctrl && kv >= GDK_KEY_1 && kv <= GDK_KEY_9) { + int slot = static_cast(kv - GDK_KEY_1); + if (kv == GDK_KEY_9) slot = static_cast(app->tabs.size()) - 1; + if (slot >= 0 && slot < static_cast(app->tabs.size())) { + selectTab(app, slot); + } + return TRUE; + } + if ((ctrl && !shift && !alt && (kv == GDK_KEY_b || kv == GDK_KEY_B)) || + (alt && !ctrl && (kv == GDK_KEY_t || kv == GDK_KEY_T))) { + toggleTabSidebar(app); + return TRUE; + } + if ((ctrl && !alt && (kv == GDK_KEY_l || kv == GDK_KEY_L)) || + (alt && !ctrl && (kv == GDK_KEY_d || kv == GDK_KEY_D)) || + kv == GDK_KEY_F6) { + gtk_widget_grab_focus(GTK_WIDGET(app->urlEntry)); + gtk_editable_select_region(GTK_EDITABLE(app->urlEntry), 0, -1); + return TRUE; + } + if ((ctrl && !alt && (kv == GDK_KEY_r || kv == GDK_KEY_R)) || kv == GDK_KEY_F5) { + if (TabEntry* tab = currentTab(app)) { + if (shift) webkit_web_view_reload_bypass_cache(tab->webView); + else webkit_web_view_reload(tab->webView); + } + return TRUE; + } + if (alt && !ctrl && kv == GDK_KEY_Left) { + if (TabEntry* tab = currentTab(app)) webkit_web_view_go_back(tab->webView); + return TRUE; + } + if (alt && !ctrl && kv == GDK_KEY_Right) { + if (TabEntry* tab = currentTab(app)) webkit_web_view_go_forward(tab->webView); + return TRUE; + } + if (ctrl && !shift && !alt && (kv == GDK_KEY_d || kv == GDK_KEY_D)) { + toggleBookmarkCurrent(app); + return TRUE; + } + if (ctrl && shift && !alt && (kv == GDK_KEY_D || kv == GDK_KEY_d)) { + toggleDarkMode(app); + return TRUE; + } + if (ctrl && !alt && (kv == GDK_KEY_f || kv == GDK_KEY_F)) { + openFindBar(app); + return TRUE; + } + if (ctrl && !alt && (kv == GDK_KEY_plus || kv == GDK_KEY_equal || kv == GDK_KEY_KP_Add)) { + adjustZoom(app, 0.1); + return TRUE; + } + if (ctrl && !alt && (kv == GDK_KEY_minus || kv == GDK_KEY_KP_Subtract)) { + adjustZoom(app, -0.1); + return TRUE; + } + if (ctrl && !alt && (kv == GDK_KEY_0 || kv == GDK_KEY_KP_0)) { + adjustZoom(app, 0.0); + return TRUE; + } + if (kv == GDK_KEY_F11) { + app->fullscreen = !app->fullscreen; + if (app->fullscreen) gtk_window_fullscreen(GTK_WINDOW(app->window)); + else gtk_window_unfullscreen(GTK_WINDOW(app->window)); + return TRUE; + } + if (kv == GDK_KEY_Escape) { + if (gtk_revealer_get_reveal_child(app->findRevealer)) { + closeFindBar(app); + return TRUE; + } + if (TabEntry* tab = currentTab(app); tab && tab->loading) { + webkit_web_view_stop_loading(tab->webView); + return TRUE; + } + } + return FALSE; +} + +gboolean onSigUsr1ThemeReload(gpointer ud) { + applyGtkThemeCss(static_cast(ud)); + return G_SOURCE_CONTINUE; +} + +gboolean onFifoReadable(gint fd, GIOCondition, gpointer ud) { + auto* app = static_cast(ud); + char buf[4096]; + ssize_t n = ::read(fd, buf, sizeof(buf) - 1); + if (n <= 0 || !app) return G_SOURCE_CONTINUE; + buf[n] = '\0'; + std::istringstream iss(buf); + std::string line; + while (std::getline(iss, line)) { + std::string cmd = trimStr(line); + if (cmd.rfind("NEW_TAB ", 0) == 0) { + std::string target = normalizeInputUrlOrSearch(cmd.substr(8)); + createTab(app, target, true); + } + gtk_window_present(GTK_WINDOW(app->window)); + } + return G_SOURCE_CONTINUE; +} + +bool tryForwardToExistingInstance(const std::string& initialUrl) { + std::ifstream pidIn(pidRuntimePath()); + pid_t pid = 0; + if (!(pidIn >> pid) || pid <= 0 || ::kill(pid, 0) != 0) { + return false; + } + int fd = ::open(fifoRuntimePath().c_str(), O_WRONLY | O_NONBLOCK); + if (fd < 0) return false; + std::string msg = initialUrl.empty() ? "FOCUS\n" : ("NEW_TAB " + initialUrl + "\n"); + ssize_t wrote = ::write(fd, msg.data(), msg.size()); + ::close(fd); + return wrote > 0; +} + +void buildUi(BrowserApp* app) { + app->cssProvider = gtk_css_provider_new(); + if (GdkScreen* scr = gdk_screen_get_default()) { + gtk_style_context_add_provider_for_screen( + scr, GTK_STYLE_PROVIDER(app->cssProvider), GTK_STYLE_PROVIDER_PRIORITY_USER); + } + applyGtkThemeCss(app); + + app->window = gtk_window_new(GTK_WINDOW_TOPLEVEL); +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" + gtk_window_set_wmclass(GTK_WINDOW(app->window), "webarchy", "Webarchy"); +#pragma GCC diagnostic pop + gtk_window_set_title(GTK_WINDOW(app->window), "Webarchy Browser"); + // Gemini PDA is 2160x1080 physical; with GDK_SCALE=2 and DWM 68px bar -> 1080x506 logical px. + gtk_window_set_default_size(GTK_WINDOW(app->window), 1080, 506); + + GtkWidget* root = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0); + gtk_widget_set_name(root, "wa-root"); + gtk_container_add(GTK_CONTAINER(app->window), root); + + // Left side: Main web viewport + top navbar + find bar + status bar + GtkWidget* mainPane = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); + gtk_widget_set_name(mainPane, "wa-main-pane"); + gtk_widget_set_hexpand(mainPane, TRUE); + gtk_widget_set_vexpand(mainPane, TRUE); + gtk_box_pack_start(GTK_BOX(root), mainPane, TRUE, TRUE, 0); + + // Top navigation bar + GtkWidget* navbar = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 4); + gtk_widget_set_name(navbar, "wa-navbar"); + gtk_box_pack_start(GTK_BOX(mainPane), navbar, FALSE, FALSE, 0); + + app->backBtn = gtk_button_new_with_label("←"); + app->fwdBtn = gtk_button_new_with_label("→"); + app->reloadBtn = gtk_button_new_with_label("↻"); + app->homeBtn = gtk_button_new_with_label("⌂"); + app->urlEntry = GTK_ENTRY(gtk_entry_new()); + gtk_widget_set_name(GTK_WIDGET(app->urlEntry), "wa-urlbar"); + gtk_entry_set_placeholder_text(app->urlEntry, "Enter URL or DuckDuckGo search..."); + gtk_widget_set_hexpand(GTK_WIDGET(app->urlEntry), TRUE); + + app->bookmarkBtn = gtk_button_new_with_label("☆"); + app->menuBtn = gtk_menu_button_new(); + gtk_button_set_label(GTK_BUTTON(app->menuBtn), "☰"); + app->toggleTabsBtn = gtk_button_new_with_label("Tabs ◫"); + gtk_style_context_add_class(gtk_widget_get_style_context(app->toggleTabsBtn), "active-accent"); + + for (GtkWidget* w : {app->backBtn, app->fwdBtn, app->reloadBtn, app->homeBtn, + app->bookmarkBtn, app->menuBtn, app->toggleTabsBtn}) { + gtk_widget_set_can_focus(w, FALSE); + } + + gtk_box_pack_start(GTK_BOX(navbar), app->backBtn, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(navbar), app->fwdBtn, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(navbar), app->reloadBtn, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(navbar), app->homeBtn, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(navbar), GTK_WIDGET(app->urlEntry), TRUE, TRUE, 2); + gtk_box_pack_start(GTK_BOX(navbar), app->bookmarkBtn, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(navbar), app->menuBtn, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(navbar), app->toggleTabsBtn, FALSE, FALSE, 0); + + // Slim load progress bar + app->progressBar = GTK_PROGRESS_BAR(gtk_progress_bar_new()); + gtk_widget_set_name(GTK_WIDGET(app->progressBar), "wa-progress"); + gtk_widget_set_no_show_all(GTK_WIDGET(app->progressBar), TRUE); + gtk_box_pack_start(GTK_BOX(mainPane), GTK_WIDGET(app->progressBar), FALSE, FALSE, 0); + + // Find-in-page revealer + app->findRevealer = GTK_REVEALER(gtk_revealer_new()); + gtk_revealer_set_transition_type(app->findRevealer, GTK_REVEALER_TRANSITION_TYPE_SLIDE_DOWN); + GtkWidget* findBox = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 4); + gtk_widget_set_name(findBox, "wa-findbar"); + app->findEntry = GTK_ENTRY(gtk_entry_new()); + gtk_entry_set_placeholder_text(app->findEntry, "Find in page..."); + gtk_widget_set_hexpand(GTK_WIDGET(app->findEntry), TRUE); + GtkWidget* findPrevBtn = gtk_button_new_with_label("↑ Prev"); + GtkWidget* findNextBtn = gtk_button_new_with_label("↓ Next"); + app->findCountLabel = GTK_LABEL(gtk_label_new("")); + GtkWidget* findCloseBtn = gtk_button_new_with_label("✕"); + gtk_box_pack_start(GTK_BOX(findBox), GTK_WIDGET(app->findEntry), TRUE, TRUE, 0); + gtk_box_pack_start(GTK_BOX(findBox), findPrevBtn, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(findBox), findNextBtn, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(findBox), GTK_WIDGET(app->findCountLabel), FALSE, FALSE, 4); + gtk_box_pack_start(GTK_BOX(findBox), findCloseBtn, FALSE, FALSE, 0); + gtk_container_add(GTK_CONTAINER(app->findRevealer), findBox); + gtk_box_pack_start(GTK_BOX(mainPane), GTK_WIDGET(app->findRevealer), FALSE, FALSE, 0); + + // WebView stack + app->webStack = GTK_STACK(gtk_stack_new()); + gtk_stack_set_transition_type(app->webStack, GTK_STACK_TRANSITION_TYPE_NONE); + gtk_widget_set_hexpand(GTK_WIDGET(app->webStack), TRUE); + gtk_widget_set_vexpand(GTK_WIDGET(app->webStack), TRUE); + gtk_box_pack_start(GTK_BOX(mainPane), GTK_WIDGET(app->webStack), TRUE, TRUE, 0); + + // Bottom status bar + GtkWidget* statusBar = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 8); + gtk_widget_set_name(statusBar, "wa-statusbar"); + app->statusLabel = GTK_LABEL(gtk_label_new("Ready")); + gtk_label_set_xalign(app->statusLabel, 0.0f); + gtk_label_set_ellipsize(app->statusLabel, PANGO_ELLIPSIZE_END); + gtk_widget_set_hexpand(GTK_WIDGET(app->statusLabel), TRUE); + app->modeBadgeLabel = GTK_LABEL(gtk_label_new("GPU • 100%")); + gtk_box_pack_start(GTK_BOX(statusBar), GTK_WIDGET(app->statusLabel), TRUE, TRUE, 0); + gtk_box_pack_end(GTK_BOX(statusBar), GTK_WIDGET(app->modeBadgeLabel), FALSE, FALSE, 0); + gtk_box_pack_end(GTK_BOX(mainPane), statusBar, FALSE, FALSE, 0); + + // Right-side vertical tab bar (236 logical px = 472 physical px snapped flush right on 2160x1080) + app->tabSidebar = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); + gtk_widget_set_name(app->tabSidebar, "wa-tabbar"); + gtk_widget_set_size_request(app->tabSidebar, 236, -1); + gtk_widget_set_hexpand(app->tabSidebar, FALSE); + gtk_widget_set_hexpand_set(app->tabSidebar, TRUE); + gtk_widget_set_halign(app->tabSidebar, GTK_ALIGN_END); + gtk_box_pack_end(GTK_BOX(root), app->tabSidebar, FALSE, TRUE, 0); + + GtkWidget* tabHeader = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 4); + gtk_widget_set_name(tabHeader, "wa-tabbar-header"); + app->tabHeaderLabel = GTK_LABEL(gtk_label_new("TABS (1)")); + gtk_label_set_xalign(app->tabHeaderLabel, 0.0f); + GtkWidget* newTabBtn = gtk_button_new_with_label("+ New Tab"); + gtk_widget_set_name(newTabBtn, "wa-newtab-btn"); + gtk_widget_set_can_focus(newTabBtn, FALSE); + gtk_box_pack_start(GTK_BOX(tabHeader), GTK_WIDGET(app->tabHeaderLabel), TRUE, TRUE, 0); + gtk_box_pack_end(GTK_BOX(tabHeader), newTabBtn, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(app->tabSidebar), tabHeader, FALSE, FALSE, 0); + + GtkWidget* tabScroll = gtk_scrolled_window_new(nullptr, nullptr); + gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(tabScroll), + GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC); + gtk_widget_set_vexpand(tabScroll, TRUE); + app->tabListBox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0); + gtk_widget_set_name(app->tabListBox, "wa-tablist"); + gtk_container_add(GTK_CONTAINER(tabScroll), app->tabListBox); + gtk_box_pack_start(GTK_BOX(app->tabSidebar), tabScroll, TRUE, TRUE, 0); + + // Thumb-reachable quick controls footer on right vertical tab bar + GtkWidget* tabFooter = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 4); + gtk_widget_set_name(tabFooter, "wa-tabbar-footer"); + GtkWidget* bmMenuBtn = gtk_menu_button_new(); + gtk_button_set_label(GTK_BUTTON(bmMenuBtn), "★"); + gtk_widget_set_tooltip_text(bmMenuBtn, "Bookmarks"); + app->tabDarkBtn = gtk_button_new_with_label("◐"); + gtk_widget_set_tooltip_text(app->tabDarkBtn, "Toggle Dark Mode"); + GtkWidget* zoomOutBtn = gtk_button_new_with_label("−"); + app->zoomLabel = GTK_LABEL(gtk_label_new("100%")); + GtkWidget* zoomInBtn = gtk_button_new_with_label("+"); + for (GtkWidget* w : {bmMenuBtn, app->tabDarkBtn, zoomOutBtn, zoomInBtn}) { + gtk_widget_set_can_focus(w, FALSE); + } + gtk_box_pack_start(GTK_BOX(tabFooter), bmMenuBtn, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(tabFooter), app->tabDarkBtn, FALSE, FALSE, 0); + gtk_box_pack_end(GTK_BOX(tabFooter), zoomInBtn, FALSE, FALSE, 0); + gtk_box_pack_end(GTK_BOX(tabFooter), GTK_WIDGET(app->zoomLabel), FALSE, FALSE, 2); + gtk_box_pack_end(GTK_BOX(tabFooter), zoomOutBtn, FALSE, FALSE, 0); + gtk_box_pack_end(GTK_BOX(app->tabSidebar), tabFooter, FALSE, FALSE, 0); + + // Bookmarks popover (attached to sidebar footer button) + app->bookmarksPopover = gtk_popover_new(bmMenuBtn); + GtkWidget* bmScroll = gtk_scrolled_window_new(nullptr, nullptr); + gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(bmScroll), + GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC); + gtk_widget_set_size_request(bmScroll, 320, 260); + app->bookmarksListBox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 4); + gtk_container_set_border_width(GTK_CONTAINER(app->bookmarksListBox), 8); + gtk_container_add(GTK_CONTAINER(bmScroll), app->bookmarksListBox); + gtk_widget_show_all(bmScroll); + gtk_container_add(GTK_CONTAINER(app->bookmarksPopover), bmScroll); + gtk_menu_button_set_popover(GTK_MENU_BUTTON(bmMenuBtn), app->bookmarksPopover); + refreshBookmarksPopover(app); + + // Tools menu popover (attached to top-bar ☰ button) + app->toolsPopover = gtk_popover_new(app->menuBtn); + GtkWidget* toolsBox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6); + gtk_container_set_border_width(GTK_CONTAINER(toolsBox), 10); + + GtkWidget* uaTitle = gtk_label_new("User-Agent Profile:"); + gtk_label_set_xalign(GTK_LABEL(uaTitle), 0.0f); + app->uaCombo = gtk_combo_box_text_new(); + int activeUa = -1; + constexpr int numPresets = static_cast(sizeof(kUaPresets) / sizeof(kUaPresets[0])); + for (int i = 0; i < numPresets; ++i) { + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(app->uaCombo), kUaPresets[i].name); + if (app->userAgent == kUaPresets[i].ua) activeUa = i; + } + gtk_combo_box_text_append_text(GTK_COMBO_BOX_TEXT(app->uaCombo), "Custom User-Agent..."); + gtk_combo_box_set_active(GTK_COMBO_BOX(app->uaCombo), activeUa >= 0 ? activeUa : numPresets); + + app->darkCheckBtn = gtk_check_button_new_with_label("Dark Page Inverter (Ctrl+Shift+D)"); + app->fitCheckBtn = gtk_check_button_new_with_label("Reader Width Fit"); + app->swCheckBtn = gtk_check_button_new_with_label("Software WebKit Renderer"); + + GtkWidget* findTriggerBtn = gtk_button_new_with_label("Find in Page (Ctrl+F)"); + GtkWidget* resetZoomBtn = gtk_button_new_with_label("Reset Zoom 100% (Ctrl+0)"); + GtkWidget* reopenTabBtn = gtk_button_new_with_label("Reopen Closed Tab (Ctrl+Shift+T)"); + GtkWidget* helpLbl = gtk_label_new( + "Shortcuts: Ctrl+T New Tab | Ctrl+W Close | Ctrl+Tab Next\n" + "Ctrl+L URL | Ctrl+B Tabs | Alt+1..9 Tab | F11 Fullscreen"); + gtk_label_set_xalign(GTK_LABEL(helpLbl), 0.0f); + + gtk_box_pack_start(GTK_BOX(toolsBox), uaTitle, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(toolsBox), app->uaCombo, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(toolsBox), gtk_separator_new(GTK_ORIENTATION_HORIZONTAL), FALSE, FALSE, 2); + gtk_box_pack_start(GTK_BOX(toolsBox), app->darkCheckBtn, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(toolsBox), app->fitCheckBtn, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(toolsBox), app->swCheckBtn, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(toolsBox), gtk_separator_new(GTK_ORIENTATION_HORIZONTAL), FALSE, FALSE, 2); + gtk_box_pack_start(GTK_BOX(toolsBox), findTriggerBtn, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(toolsBox), resetZoomBtn, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(toolsBox), reopenTabBtn, FALSE, FALSE, 0); + gtk_box_pack_start(GTK_BOX(toolsBox), gtk_separator_new(GTK_ORIENTATION_HORIZONTAL), FALSE, FALSE, 2); + gtk_box_pack_start(GTK_BOX(toolsBox), helpLbl, FALSE, FALSE, 0); + gtk_widget_show_all(toolsBox); + gtk_container_add(GTK_CONTAINER(app->toolsPopover), toolsBox); + gtk_menu_button_set_popover(GTK_MENU_BUTTON(app->menuBtn), app->toolsPopover); + + // Wire UI signals + g_signal_connect(app->window, "destroy", G_CALLBACK(gtk_main_quit), nullptr); + g_signal_connect(app->window, "key-press-event", G_CALLBACK(onWindowKeyPress), app); + + g_signal_connect(app->backBtn, "clicked", G_CALLBACK(+[](GtkButton*, gpointer ud) { + if (TabEntry* tab = currentTab(static_cast(ud))) { + webkit_web_view_go_back(tab->webView); + } + }), app); + g_signal_connect(app->fwdBtn, "clicked", G_CALLBACK(+[](GtkButton*, gpointer ud) { + if (TabEntry* tab = currentTab(static_cast(ud))) { + webkit_web_view_go_forward(tab->webView); + } + }), app); + g_signal_connect(app->reloadBtn, "clicked", G_CALLBACK(+[](GtkButton*, gpointer ud) { + if (TabEntry* tab = currentTab(static_cast(ud))) { + if (tab->loading) webkit_web_view_stop_loading(tab->webView); + else webkit_web_view_reload(tab->webView); + } + }), app); + g_signal_connect(app->homeBtn, "clicked", G_CALLBACK(+[](GtkButton*, gpointer ud) { + auto* a = static_cast(ud); + std::string homeUrl = a->bookmarks.empty() ? kDefaultHomepage : a->bookmarks[0].url; + navigateCurrentTab(a, homeUrl); + }), app); + g_signal_connect(app->urlEntry, "activate", G_CALLBACK(+[](GtkEntry* entry, gpointer ud) { + navigateCurrentTab(static_cast(ud), gtk_entry_get_text(entry)); + }), app); + g_signal_connect(app->bookmarkBtn, "clicked", G_CALLBACK(+[](GtkButton*, gpointer ud) { + toggleBookmarkCurrent(static_cast(ud)); + }), app); + g_signal_connect(app->toggleTabsBtn, "clicked", G_CALLBACK(+[](GtkButton*, gpointer ud) { + toggleTabSidebar(static_cast(ud)); + }), app); + g_signal_connect(newTabBtn, "clicked", G_CALLBACK(+[](GtkButton*, gpointer ud) { + auto* a = static_cast(ud); + createTab(a, kDefaultHomepage, true); + gtk_widget_grab_focus(GTK_WIDGET(a->urlEntry)); + gtk_editable_select_region(GTK_EDITABLE(a->urlEntry), 0, -1); + }), app); + g_signal_connect(app->tabDarkBtn, "clicked", G_CALLBACK(+[](GtkButton*, gpointer ud) { + toggleDarkMode(static_cast(ud)); + }), app); + g_signal_connect(zoomOutBtn, "clicked", G_CALLBACK(+[](GtkButton*, gpointer ud) { + adjustZoom(static_cast(ud), -0.1); + }), app); + g_signal_connect(zoomInBtn, "clicked", G_CALLBACK(+[](GtkButton*, gpointer ud) { + adjustZoom(static_cast(ud), 0.1); + }), app); + + g_signal_connect(app->findEntry, "changed", G_CALLBACK(+[](GtkEditable* ed, gpointer ud) { + runFindSearch(static_cast(ud), gtk_entry_get_text(GTK_ENTRY(ed))); + }), app); + g_signal_connect(app->findEntry, "activate", G_CALLBACK(+[](GtkEntry*, gpointer ud) { + if (TabEntry* tab = currentTab(static_cast(ud))) { + webkit_find_controller_search_next(webkit_web_view_get_find_controller(tab->webView)); + } + }), app); + g_signal_connect(findPrevBtn, "clicked", G_CALLBACK(+[](GtkButton*, gpointer ud) { + if (TabEntry* tab = currentTab(static_cast(ud))) { + webkit_find_controller_search_previous(webkit_web_view_get_find_controller(tab->webView)); + } + }), app); + g_signal_connect(findNextBtn, "clicked", G_CALLBACK(+[](GtkButton*, gpointer ud) { + if (TabEntry* tab = currentTab(static_cast(ud))) { + webkit_find_controller_search_next(webkit_web_view_get_find_controller(tab->webView)); + } + }), app); + g_signal_connect(findCloseBtn, "clicked", G_CALLBACK(+[](GtkButton*, gpointer ud) { + closeFindBar(static_cast(ud)); + }), app); + + g_signal_connect(app->uaCombo, "changed", G_CALLBACK(onUaComboChanged), app); + g_signal_connect(app->darkCheckBtn, "toggled", G_CALLBACK(+[](GtkToggleButton*, gpointer ud) { + auto* a = static_cast(ud); + if (!a->syncingUiFlags) toggleDarkMode(a); + }), app); + g_signal_connect(app->fitCheckBtn, "toggled", G_CALLBACK(+[](GtkToggleButton*, gpointer ud) { + auto* a = static_cast(ud); + if (!a->syncingUiFlags) toggleMobileFit(a); + }), app); + g_signal_connect(app->swCheckBtn, "toggled", G_CALLBACK(onSoftwareRendererToggled), app); + g_signal_connect(findTriggerBtn, "clicked", G_CALLBACK(+[](GtkButton*, gpointer ud) { + auto* a = static_cast(ud); + gtk_popover_popdown(GTK_POPOVER(a->toolsPopover)); + openFindBar(a); + }), app); + g_signal_connect(resetZoomBtn, "clicked", G_CALLBACK(+[](GtkButton*, gpointer ud) { + auto* a = static_cast(ud); + gtk_popover_popdown(GTK_POPOVER(a->toolsPopover)); + adjustZoom(a, 0.0); + }), app); + g_signal_connect(reopenTabBtn, "clicked", G_CALLBACK(+[](GtkButton*, gpointer ud) { + auto* a = static_cast(ud); + gtk_popover_popdown(GTK_POPOVER(a->toolsPopover)); + if (!a->closedTabUrls.empty()) { + std::string url = a->closedTabUrls.back(); + a->closedTabUrls.pop_back(); + createTab(a, url, true); + } + }), app); +} + +void initWebKitEngine(BrowserApp* app) { + // 1.2 GB limit suited for 4 GB Gemini PDA MT6797X with multi-tab browsing + WebKitMemoryPressureSettings* mp = webkit_memory_pressure_settings_new(); + webkit_memory_pressure_settings_set_memory_limit(mp, 1200); + webkit_memory_pressure_settings_set_kill_threshold(mp, 0.95); + webkit_memory_pressure_settings_set_strict_threshold(mp, 0.78); + webkit_memory_pressure_settings_set_conservative_threshold(mp, 0.55); + webkit_website_data_manager_set_memory_pressure_settings(mp); + webkit_memory_pressure_settings_free(mp); + + std::string dataDir = getHomeDirPath() + "/.local/share/geminux/webarchy/data"; + std::string cacheDir = getHomeDirPath() + "/.cache/geminux/webarchy"; + std::string cookieFile = getHomeDirPath() + "/.local/share/geminux/webarchy/cookies.sqlite"; + ensureParentDir(cookieFile); + + WebKitWebsiteDataManager* dataMgr = webkit_website_data_manager_new( + "base-data-directory", dataDir.c_str(), + "base-cache-directory", cacheDir.c_str(), + nullptr); + webkit_website_data_manager_set_tls_errors_policy( + dataMgr, WEBKIT_TLS_ERRORS_POLICY_IGNORE); + app->webCtx = webkit_web_context_new_with_website_data_manager(dataMgr); + g_object_unref(dataMgr); + + webkit_web_context_set_sandbox_enabled(app->webCtx, FALSE); + webkit_web_context_set_cache_model(app->webCtx, WEBKIT_CACHE_MODEL_WEB_BROWSER); + + WebKitCookieManager* cookieMgr = webkit_web_context_get_cookie_manager(app->webCtx); + webkit_cookie_manager_set_persistent_storage( + cookieMgr, cookieFile.c_str(), WEBKIT_COOKIE_PERSISTENT_STORAGE_SQLITE); + webkit_cookie_manager_set_accept_policy( + cookieMgr, WEBKIT_COOKIE_POLICY_ACCEPT_NO_THIRD_PARTY); + + app->ucm = webkit_user_content_manager_new(); + WebKitUserStyleSheet* cssSheet = webkit_user_style_sheet_new( + kWebarchyInjectedCss, + WEBKIT_USER_CONTENT_INJECT_ALL_FRAMES, + WEBKIT_USER_STYLE_LEVEL_USER, + nullptr, nullptr); + webkit_user_content_manager_add_style_sheet(app->ucm, cssSheet); + webkit_user_style_sheet_unref(cssSheet); + + WebKitUserScript* script = webkit_user_script_new( + kWebarchyInjectedJs, + WEBKIT_USER_CONTENT_INJECT_ALL_FRAMES, + WEBKIT_USER_SCRIPT_INJECT_AT_DOCUMENT_START, + nullptr, nullptr); + webkit_user_content_manager_add_script(app->ucm, script); + webkit_user_script_unref(script); + + WebKitSettings* s = webkit_settings_new(); + webkit_settings_set_user_agent(s, app->userAgent.c_str()); + webkit_settings_set_default_charset(s, "UTF-8"); + webkit_settings_set_default_font_family(s, "Noto Sans"); + webkit_settings_set_sans_serif_font_family(s, "Noto Sans"); + webkit_settings_set_serif_font_family(s, "Noto Serif"); + webkit_settings_set_cursive_font_family(s, "Noto Sans"); + webkit_settings_set_fantasy_font_family(s, "Noto Sans"); + webkit_settings_set_monospace_font_family(s, "Fira Code"); + webkit_settings_set_default_font_size(s, 15); + webkit_settings_set_default_monospace_font_size(s, 13); + webkit_settings_set_minimum_font_size(s, 10); + + webkit_settings_set_hardware_acceleration_policy( + s, app->softwareRenderer ? WEBKIT_HARDWARE_ACCELERATION_POLICY_NEVER + : WEBKIT_HARDWARE_ACCELERATION_POLICY_ALWAYS); + webkit_settings_set_enable_webgl(s, TRUE); + webkit_settings_set_enable_smooth_scrolling(s, TRUE); + webkit_settings_set_enable_page_cache(s, TRUE); + webkit_settings_set_enable_site_specific_quirks(s, TRUE); + webkit_settings_set_enable_javascript(s, TRUE); + webkit_settings_set_enable_media(s, TRUE); + webkit_settings_set_enable_mediasource(s, TRUE); + webkit_settings_set_enable_media_stream(s, TRUE); + webkit_settings_set_enable_media_capabilities(s, TRUE); + webkit_settings_set_enable_webaudio(s, TRUE); + webkit_settings_set_enable_encrypted_media(s, TRUE); + webkit_settings_set_media_playback_requires_user_gesture(s, FALSE); + webkit_settings_set_media_playback_allows_inline(s, TRUE); + webkit_settings_set_enable_fullscreen(s, TRUE); + app->wkSettings = s; + + app->wkPolicies = webkit_website_policies_new_with_policies( + "autoplay", WEBKIT_AUTOPLAY_ALLOW, nullptr); +} + +void setupSingleInstanceServer(BrowserApp* app) { + std::string pidPath = pidRuntimePath(); + std::ofstream pidOut(pidPath, std::ios::trunc); + if (pidOut.is_open()) pidOut << static_cast(::getpid()) << "\n"; + + std::string fifoPath = fifoRuntimePath(); + ::unlink(fifoPath.c_str()); + if (::mkfifo(fifoPath.c_str(), 0600) == 0) { + app->fifoFd = ::open(fifoPath.c_str(), O_RDWR | O_NONBLOCK); + if (app->fifoFd >= 0) { + app->fifoWatchId = g_unix_fd_add(app->fifoFd, G_IO_IN, onFifoReadable, app); + } + } +} + +void cleanupSingleInstanceServer(BrowserApp* app) { + if (app->fifoWatchId > 0) { + g_source_remove(app->fifoWatchId); + app->fifoWatchId = 0; + } + if (app->fifoFd >= 0) { + ::close(app->fifoFd); + app->fifoFd = -1; + } + ::unlink(fifoRuntimePath().c_str()); + ::unlink(pidRuntimePath().c_str()); +} + +} // namespace + +int main(int argc, char** argv) { + bool newWindow = false; + bool forceSoftware = false; + std::vector urls; + for (int i = 1; i < argc; ++i) { + if (!argv[i] || !argv[i][0]) continue; + if (std::strcmp(argv[i], "--new-window") == 0) newWindow = true; + else if (std::strcmp(argv[i], "--software") == 0) forceSoftware = true; + else urls.push_back(argv[i]); + } + + if (!newWindow) { + std::string first = urls.empty() ? "" : normalizeInputUrlOrSearch(urls[0]); + if (tryForwardToExistingInstance(first)) { + for (size_t i = 1; i < urls.size(); ++i) { + tryForwardToExistingInstance(normalizeInputUrlOrSearch(urls[i])); + } + return 0; + } + } + + BrowserApp app; + app.softwareRenderer = forceSoftware || webarchySoftwareRendererPreferred(); + configureWebkitRenderer(app.softwareRenderer); + + gtk_init(&argc, &argv); + + app.bookmarks = loadBookmarks(); + app.userAgent = loadUserAgent(); + + initWebKitEngine(&app); + buildUi(&app); + if (!newWindow) { + setupSingleInstanceServer(&app); + } + g_unix_signal_add(SIGUSR1, onSigUsr1ThemeReload, &app); + + if (urls.empty()) { + std::string homeUrl = app.bookmarks.empty() ? kDefaultHomepage : app.bookmarks[0].url; + createTab(&app, homeUrl, true); + } else { + for (size_t i = 0; i < urls.size(); ++i) { + createTab(&app, normalizeInputUrlOrSearch(urls[i]), i == 0); + } + } + + gtk_widget_show_all(app.window); + gtk_widget_hide(GTK_WIDGET(app.progressBar)); + refreshChromeUi(&app); + + gtk_main(); + + app.tabs.clear(); + if (!newWindow) cleanupSingleInstanceServer(&app); + if (app.wkPolicies) g_object_unref(app.wkPolicies); + if (app.wkSettings) g_object_unref(app.wkSettings); + if (app.ucm) g_object_unref(app.ucm); + if (app.webCtx) g_object_unref(app.webCtx); + if (app.cssProvider) g_object_unref(app.cssProvider); + return 0; +}