Add ReMEdy native 240x320 J2ME (MIDP 2.0 / CLDC 1.1 / M3G 3D) emulator and file manager integration

This commit is contained in:
Luxferre committed 2026-10-28 12:41:00 +02:00
1 parent 3b9f2ee28d
commit 66769d7c2e
39 files changed
+15412 -15

No files matched your search

+2 -2
View File
@@ -17,7 +17,7 @@ It uses a pure **X11 (`Xlibre` + `sxmo-de-dwm`)** stack (no Wayland) with **Adre
- `src/xdrawer/`: global phone controls overlay (`xdrawer.so` / `xdrawer`), toggled by pressing both softkeys simultaneously.
- `src/sxmo-st/`: patched `st` terminal with HarfBuzz OpenType ligatures (`Fira Code`), `XIM` (`fcitx5-t9`), and live `SIGUSR1` `.Xresources` reload.
- `src/fcitx5-t9/`: 6-mode keypad input method (`abc`, `Abc`, `ABC`, `Sym`, `Ctl`, `123` + `*` long-press `Ctrl+` latch) with fixed bottom preedit bar (`Y=290, H=30`).
- `src/games/`: standalone keypad-driven `240x320` X11 games and emulators (`snake.cpp` -> `/usr/bin/snake`, `tetris.cpp` -> `/usr/bin/tetris`, `gambatte_phone.cpp` + `gambatte/` -> `/usr/bin/gambatte` / `/usr/bin/gbemu`) with built-in 5x7 bitmap fonts, `timerfd`-driven pacing, and offscreen `Pixmap` double buffering.
- `src/games/`: standalone keypad-driven `240x320` X11 games and emulators (`snake.cpp` -> `/usr/bin/snake`, `tetris.cpp` -> `/usr/bin/tetris`, `gambatte_phone.cpp` + `gambatte/` -> `/usr/bin/gambatte` / `/usr/bin/gbemu`, and `remedy/` -> `/usr/bin/remedy` / `/usr/bin/j2me` J2ME MIDP 2.0 / CLDC 1.1 + JSR-184 M3G 3D emulator) with built-in 5x7 bitmap fonts, NeoUI integration, `timerfd`-driven pacing, and offscreen `Pixmap` / EGL double buffering.
- `src/msm8905-cam/` & `src/leds-msm8905-torch/`: out-of-tree Linux `6.12.1-msm8916` kernel modules for the rear `GC2395` / `GC2385` / `GC2365` camera (`/dev/video0`) and `SY7807` torch LED (`white:torch`) / WCD codec init / PM8909 `PON` shutdown.
- `overlay/rootfs/`: system configuration overlay applied over the target rootfs (kept in sync with `prebuilt/`).
- `prebuilt/`: cross-compiled `armv7` binaries and kernel modules (`sxmo-x11`, `fcitx5-t9`, `xlibre`, `kernel-6.12.1-msm8916`, `bantam`, `games`).
@@ -27,7 +27,7 @@ It uses a pure **X11 (`Xlibre` + `sxmo-de-dwm`)** stack (no Wayland) with **Adre
All cross-compilation scripts run inside rootless Docker (`alpine:3.24` `armv7` sysroot) and automatically update both `prebuilt/` and `overlay/rootfs/`:
- `./scripts/build-sxmo-x11.sh` — builds `libneoui.so`, `st`, `dmenu.so`, `dwm`, `dwm-plugin`, `sxmo_vibrate`, and all C++ `.so` plugins (`xdrawer`, `dialer`, `calllog`, `callscreen`, `contacts`, `sms`, `files`, `camera`, `themes`, `modem`, `networks`, `ringtones`, `wallpapers`, `music`).
- `./scripts/build-dmenu.sh` — rebuilds only `dmenu.so`, `stest`, `dmenu_path`, and `dmenu_run`.
- `./scripts/build-games.sh` — builds standalone X11 games and emulators in `src/games/` (`snake`, `tetris`, `gambatte` / `gbemu`).
- `./scripts/build-games.sh` — builds standalone X11 games and emulators in `src/games/` (`snake`, `tetris`, `gambatte` / `gbemu`, `remedy` / `j2me`).
- `./scripts/build-fcitx5-t9.sh` — builds `src/fcitx5-t9` (`libt9.so` / `t9.so`).
- `./scripts/build-kernel-audio.sh` — builds `6.12.1-msm8916` Adreno 304 `drm/msm`, QDSP6 audio, torch LED, camera `.ko` modules, and device `.dtb` files.
- `./scripts/build-xlibre.sh` — builds Xlibre `Xorg`, `libglamoregl.so`, `libglx.so`, and `modesetting`/`libinput`/`fbdev` DDX drivers.
+5
View File
@@ -12,6 +12,11 @@ Release versions follow the `<year-letter><MM><DD>` format (where `2026` is `a`,
## Build `a1027` — codename `bonkers` (2026-10-27)
### New features and improvements
- **ReMEdy (`remedy` / `j2me`) native `240x320` J2ME (MIDP 2.0 / CLDC 1.1) emulator**:
- Built a standalone C++20 J2ME virtual machine and runtime (`/usr/bin/remedy`, symlinked as `/usr/bin/j2me`) running in full-screen `240x320` mode (`X=0, Y=0, W=240, H=320`) and declaring native `240x320` canvas dimensions to MIDlets, integrated into **System menu -> Applications**, **System menu -> Games**, and **file manager (`xfiles`)** for `.jar` and `.jad` files.
- Added a Gambatte-style NeoUI-themed frontend browser when launched without arguments (scanning `/usr/share/games/j2me`, `~/Games`, `~/J2ME`, and `~/Downloads` with `MANIFEST.MF` / `.jad` metadata preview, pause menu, keypad control remapping, scaling/3D/audio toggles, and RMS save manager).
- Implemented NeoUI-themed (`libneoui.so` / `PluginTheme`) high-level LCDUI components (`Form`, `List`, `TextBox`, `Alert`, `ChoiceGroup`, `Gauge`, `TextField`, `StringItem`, and `Command` bars/menus) alongside full-screen 2D `Canvas` / `GameCanvas` / `Sprite` / `TiledLayer` rendering, Nokia UI API (`com.nokia.mid.ui.*`), Adreno 304 (`FD304`) EGL + OpenGL ES 2.0 hardware-accelerated JSR-184 M3G 3D graphics (`javax.microedition.m3g.*`), HTTP/HTTPS and TCP/UDP socket networking (`javax.microedition.io.Connector`), `RecordStore` (RMS) persistence, and MMAPI (`javax.microedition.media.Manager`) ALSA audio.
- Preinstalled J2ME apps and functional test suites in `/usr/share/games/j2me/` and `~/Games/`: `g2048.jar` (240x320 2048), `ReMEdy3DArena.jar` (JSR-184 3D hardware-accelerated arena), `AstroBlaster240.jar` (`GameCanvas` space shooter with RMS high score and tone audio), and `NetToolJ2ME.jar` (NeoUI-themed LCDUI + HTTP/TCP socket test suite).
- **Adreno 304 (`FD304`) 3D GPU hardware acceleration and Xlibre Glamor offload**:
- Added full Qualcomm **Adreno 304 (`0x03000400`)** GPU and `qcom,msm8909-iommu` (`gfx3d_user` / `gfx3d_priv` context banks at `0x1f08000`) support to the `6.12.1-msm8916` kernel (`drm/msm` module and MSM8905/MSM8909 device trees across `nokia-argon`, `nokia-beatles`, `nokia-tough`, `nokia-sparkler`, and `nokia-leo`), configured for Adreno 304's `96 KB` (`SZ_64K + SZ_32K`) GMEM cache, `a300_pm4.fw` / `a300_pfp.fw` microcode, VBIF/ROQ/clock-gating registers, hard-reset recovery quirk, `OXILI_GDSC` power domain, and OPP frequency scaling up to `409.6 MHz`.
- Enabled headless render-only `drm/msm` initialization (`card1` / `renderD128`) alongside the SPI `panel-mipi-dbi` display (`card0`) and enabled `FD304` (`chip_id = 0x030004ff`) in Mesa Freedreno (`libgallium`) for hardware-accelerated **OpenGL 3.1** and **OpenGL ES 3.0**.
+9 -3
View File
@@ -34,7 +34,7 @@ This manual covers flashing, operating, and customizing **Bananarchy Linux** (`2
- **QDSP6 / Q6Voice audio and Dual-SIM modem**: loudspeaker, boosted (+6 dB) earpiece, internal MEMS and headset microphones, `ModemManager` + `q6voiced` call audio routing, and direct Qualcomm QMI UIM Dual-SIM Dual Standby (DSDS), instant default SIM switching, Primary/Secondary GW (`4G/Data`) slot swapping, PIN/PUK management, and SIM phonebook access.
- **Rear 2MP camera and torch LED**: `msm8905-cam` V4L2 driver (`/dev/video0` `800x600` `RGB3` for GalaxyCore `GC2395` / `GC2385` / `GC2365`) and `leds-msm8905-torch` (`white:torch` + PM8909 clean poweroff).
5. **Preinstalled developer and utility stack**:
- `gcc`/`g++`, `make`, `git`, GNU `coreutils`, GNU `bc`/`dc`, `nano`, `ed`, `less`, `rlwrap`, `lua` (`5.5` and `5.4`), `yabasic`, `janet` + `jpm`, `bantam` coding agent, `perl` (`IO::Socket::SSL`), `tcl` (`tcllib`, `tcl-tls`, `sqlite-tcl`), `sqlite3`, `frotz`, `ffmpeg`, `mpv`, `imv`, standalone `snake` and `tetris` X11 games, and the `gambatte` Game Boy / Game Boy Color emulator.
- `gcc`/`g++`, `make`, `git`, GNU `coreutils`, GNU `bc`/`dc`, `nano`, `ed`, `less`, `rlwrap`, `lua` (`5.5` and `5.4`), `yabasic`, `janet` + `jpm`, `bantam` coding agent, `perl` (`IO::Socket::SSL`), `tcl` (`tcllib`, `tcl-tls`, `sqlite-tcl`), `sqlite3`, `frotz`, `ffmpeg`, `mpv`, `imv`, standalone `snake` and `tetris` X11 games, the `gambatte` Game Boy / Game Boy Color emulator, and the **ReMEdy (`remedy` / `j2me`)** `240x320` J2ME (MIDP 2.0 / CLDC 1.1) emulator.
---
@@ -176,6 +176,7 @@ All fifteen phone applications are compiled as shared-object plugins (`/usr/lib/
- **Multi-tap keypad text entry**: type with `0`–`9` and `*` (with a live bottom candidate bar), press `#` to cycle input modes (`[abc]` -> `[Abc]` -> `[ABC]` -> `[123]` -> `[Sym]`), press **Center `OK` (`Return`)** to split the line / insert a newline, and press **Right softkey (`Del`)** or `BackSpace` to delete the character before the cursor (or join with the previous line at column `0`).
- **Editor menu (`Left softkey`)**: opens the editor menu with **Save File** (press **Left softkey** twice to save immediately), **Save & Close**, **Insert New Line**, **Insert Space**, **Duplicate Line**, **Delete Line**, and **Close Without Saving**.
- **Yabasic (`.yab`) script execution**: pressing `Return` on any `.yab` file (or selecting **Run in Yabasic (Terminal)** from the **Left softkey (`Actions`)** menu) launches `yabasic` inside `st` in the file's directory and waits for `Enter` after completion so output can be inspected.
- **J2ME (`.jar` / `.jad`) MIDlet launching**: pressing `Return` on any `.jar` or `.jad` file (or selecting **Run in ReMEdy (J2ME)** from the **Left softkey (`Actions`)** menu) opens it directly in the **ReMEdy (`remedy`)** full-screen `240x320` J2ME emulator; `.jad` files also include a **View JAD Descriptor** action in the **Actions** menu.
- **Game Boy / Game Boy Color ROM launching**: pressing `Return` on any `.gb` or `.gbc` file (or selecting **Play in Game Boy Emulator** from the **Left softkey (`Actions`)** menu) opens it directly in the **Gambatte (`gambatte`)** emulator.
- **Image preview and wallpaper installation**: pressing `Return` on any image file (`.jpg`, `.png`, `.bmp`, `.gif`, `.webp`, `.ppm`, `.tif`, `.ico`, `.svg`) opens the built-in image viewer (`*` toggles full-screen preview; **Left softkey (`Set Wall`)** installs the image into `~/Pictures/Wallpapers/`, applies it via `feh`, and refreshes Conky). You can also select **Preview Image** or **Set as Wallpaper** directly from the **Left softkey (`Actions`)** menu.
- **Audio playback and ringtone installation**: pressing `Return` on any audio or tracker module file opens it immediately in **Music (`xmusic`)**. From the **Left softkey (`Actions`)** menu on any audio/tracker file, select **Play in Music Player** to play it in `xmusic`, or **Set as Ringtone** to copy it to `~/Ringtones/` and set it as the active phone ringtone.
@@ -220,8 +221,8 @@ All fifteen phone applications are compiled as shared-object plugins (`/usr/lib/
- **`2:Queue`**: browse the active playlist queue, filter with `0`–`9`, press `Return` to jump to a track, `*` to remove a track, `#` to shuffle, or **Left softkey (`Actions`)** to set the selected track as ringtone or clear the queue.
- **`3:Files`**: browse the filesystem (`~/Music`, `/usr/share/sxmo/music`, `/usr/share/sxmo/ringtones`, or any folder), press `Return` to play a file and load its folder into the queue, `*` to append a file or folder to the queue, or `#` to play the entire current folder.
#### 3.1.3 Standalone keypad games (`Snake`, `Tetris`) and Game Boy / Game Boy Color emulator (`Gambatte`)
Two classic X11 games (`/usr/bin/snake` and `/usr/bin/tetris`) and the full-featured **Gambatte (`gambatte` / `gbemu`)** Game Boy / Game Boy Color emulator are accessible from **System menu -> Games** (or by opening any `.gb` / `.gbc` file directly in **Files (`xfiles`)**):
#### 3.1.3 Standalone keypad games (`Snake`, `Tetris`), Game Boy emulator (`Gambatte`), and J2ME emulator (`ReMEdy`)
Two classic X11 games (`/usr/bin/snake` and `/usr/bin/tetris`), the **Gambatte (`gambatte` / `gbemu`)** Game Boy / Game Boy Color emulator, and the **ReMEdy (`remedy` / `j2me`)** J2ME (MIDP 2.0 / CLDC 1.1) emulator are accessible from **System menu -> Games** (and **System menu -> Applications** for ReMEdy, or by opening `.gb`/`.gbc` and `.jar`/`.jad` files directly in **Files (`xfiles`)**):
- **Snake (`snake`)**: steer with `2`/`8`/`4`/`6` or D-Pad; pause or restart with `5`/`Return`/`#`/`*`; quit with `Right softkey`/`BackSpace`/`Escape`.
- **Tetris (`tetris`)**: move with `4`/`6` (`Left`/`Right`), rotate with `2` (`Up`), soft drop with `8` (`Down`), hard drop with `0`/`5`/`Return`, pause with `#`/`*`, and quit with `Right softkey`/`BackSpace`/`Escape`.
- **Game Boy / Game Boy Color emulator (`gambatte` / `gbemu`)**:
@@ -237,6 +238,11 @@ Two classic X11 games (`/usr/bin/snake` and `/usr/bin/tetris`) and the full-feat
- **Palette selection**: `*` (cycles through 10 built-in color palettes: `DMG Classic`, `Bananarchy Gold`, `GB Pocket Gray`, `GB Light Teal`, `GBC Blue/Red`, `Super Game Boy`, `Amber CRT`, `Mintberry`, `Virtual Boy`, `Inverted Dark`)
- **Fast forward (2x)**: `0` (while held)
- **Quick shortcuts (when unbound)**: `1` cycles screen scaling mode (`Fit 240x216` 1.5x area-interpolated, `1:1 160x144`, `Fill 240x246`, `Full 240x296`); `4` saves state to the active slot; `7` loads state from the active slot; `#`, `BackSpace`, `Escape`, or either softkey opens the **Gambatte Pause Menu** (Save/Load State across 10 slots `.st0`..`.st9`, Palette, Screen Scale, Audio toggle, Keypad Controls remapping, Load Another ROM, and Quit). Battery-backed SRAM (`.sav`) and RTC (`.rtc`) are saved automatically in `~/.local/share/sxmo/gambatte/saves/`.
- **ReMEdy J2ME (MIDP 2.0 / CLDC 1.1) emulator (`remedy` / `j2me`)**:
- **Launch**: open **ReMEdy (J2ME)** from **System menu -> Applications** or **System menu -> Games**, open any `.jar` or `.jad` file from **Files (`xfiles`)**, or run `remedy [app.jar|app.jad]`. When launched without a file argument, opens the NeoUI-themed **ReMEdy J2ME** browser scanning `/usr/share/games/j2me`, `~/Games`, `~/J2ME`, `~/Downloads`, and user directories, displaying the selected MIDlet's `MIDlet-Name`, `MIDlet-Vendor`, `MIDlet-Version`, main class, and RMS save status.
- **Full-screen `240x320` resolution and NeoUI-themed LCDUI**: runs in a full-screen `240x320` window (`X=0, Y=0, W=240, H=320`) and declares native `240x320` dimensions (`getWidth() == 240`, `getHeight() == 320`) to J2ME applications. Full-screen `Canvas` and `GameCanvas` games get the entire `240x320` display, while high-level LCDUI screens (`Form`, `List`, `TextBox`, `Alert`, `ChoiceGroup`, `Gauge`, `TextField`, `StringItem`, and `Command` bars/menus) render with `libneoui.so` (`PluginTheme`) and adapt automatically to the active `.Xresources` / `~/.xthemes/*.xth` system theme.
- **Hardware-accelerated 3D (JSR-184 M3G), networking, RMS, and audio**: accelerates JSR-184 (`javax.microedition.m3g.*`) 3D scenes on the Adreno 304 (`FD304`) GPU via EGL + OpenGL ES 2.0 (with depth-buffered software fallback), supports HTTP/HTTPS and raw TCP/UDP socket connections (`javax.microedition.io.Connector`, `HttpConnection`, `SocketConnection`, `FileConnection` JSR-75), Nokia UI API (`com.nokia.mid.ui.*`), persistent `RecordStore` (RMS) storage (`~/.local/share/sxmo/remedy/rms/`), and MMAPI (`javax.microedition.media.Manager`) tone and WAV/MIDI audio over ALSA (`hw:0,0`).
- **Keypad controls and pause menu**: maps D-Pad (`Up`/`Down`/`Left`/`Right`), `Center OK` (`FIRE`), `0`–`9`, `*`, `#`, **Left softkey** (`-6`), and **Right softkey** (`-7`) directly to MIDP 2.0 / Nokia key codes, with customizable D-Pad (`D-Pad + 2/4/6/8`, `D-Pad Only`, `2/4/6/8 Only`) and softkey modes persisted in `~/.config/sxmo/remedy.cfg`. Press **End / Power (red)** (`Escape`) during execution to open the **ReMEdy Pause Menu** (Resume, Send Left/Right Softkey Command, Screen Scaling, 3D Renderer toggle, Audio toggle, Keypad Controls remapping, Reset RMS Save Data, Load Another MIDlet, or Quit). Preinstalled MIDlets in `/usr/share/games/j2me/` and `~/Games/` include `g2048.jar`, `ReMEdy3DArena.jar` (JSR-184 3D benchmark), `AstroBlaster240.jar` (`GameCanvas` space shooter), and `NetToolJ2ME.jar` (LCDUI + HTTP/TCP socket test suite).
### 3.2 Multi-mode `fcitx5-t9` keypad reference
+4 -4
View File
@@ -28,13 +28,13 @@ Instead of spawning slow shell scripts for everyday phone tasks, Bananarchy runs
- **Contacts (`xcontacts`) and SMS manager (`xsms`)**: full phonebook editor with direct Qualcomm QMI SIM card contact import and export across SIM 1 and SIM 2, paired with a threaded SMS conversation view, multi-tap message composer with outgoing `SIM 1` / `SIM 2` selection when two SIMs are active, and built-in anti-spam blocklist / spam folder (`~/.local/share/sxmo/block`) with one-key thread blocking and restoration.
- **Modem and Dual-SIM manager (`xmodem`)**: 4-tab cellular control center (`SIMs`, `Radio`, `AT`, `Log`) supporting Dual-SIM Dual Standby (DSDS) with simultaneous network registration on both SIM slots, instant default SIM switching (`Set as Default SIM (Calls/SMS)`), full Primary/Secondary GW (`4G/Data`) slot swapping (`Make Primary GW (4G/Data Swap)`), SIM PIN unlock and PUK unblock wizards, 2G/3G/4G radio mode selection, interactive USSD sessions, and a live AT command console.
- **Networks and Bluetooth manager (`xnetworks`)**: 3-tab connectivity manager for Wi-Fi networks, WPA2 password entry, Wi-Fi hotspot, USB tethering, 4G/LTE mobile data (`wwan0`) and APN editing, and Bluetooth pairing.
- **File manager (`xfiles`), music and tracker player (`xmusic`), and camera (`xcamera`)**: keypad directory browser with built-in text viewer, integrated GUI multi-tap text editor (`Edit in Text Editor`, available as an action on any file), and image viewer (plus one-click actions to launch `.gb`/`.gbc` ROMs in the Game Boy emulator, run `.yab` scripts in Yabasic inside the terminal, play audio, preview images, set any image as wallpaper, or install any audio or tracker file as ringtone), a 3-tab music and chiptune tracker module player (`WAV`, `MP3`, `OGG`, `FLAC`, `Opus`, `MOD`, `XM`, `IT`, `S3M`, and more), and a live V4L2 camera viewfinder with digital zoom, flash/torch control, self-timer, and photo gallery.
- **File manager (`xfiles`), music and tracker player (`xmusic`), and camera (`xcamera`)**: keypad directory browser with built-in text viewer, integrated GUI multi-tap text editor (`Edit in Text Editor`, available as an action on any file), and image viewer (plus one-click actions to launch `.jar`/`.jad` MIDlets in the **ReMEdy (`remedy`)** J2ME emulator, launch `.gb`/`.gbc` ROMs in the Game Boy emulator, run `.yab` scripts in Yabasic inside the terminal, play audio, preview images, set any image as wallpaper, or install any audio or tracker file as ringtone), a 3-tab music and chiptune tracker module player (`WAV`, `MP3`, `OGG`, `FLAC`, `Opus`, `MOD`, `XM`, `IT`, `S3M`, and more), and a live V4L2 camera viewfinder with digital zoom, flash/torch control, self-timer, and photo gallery.
- **Themes (`xthemes`), wallpapers (`xwallpapers`), and ringtones (`xringtones`)**: installable `.Xresources` color and font themes (`~/.xthemes/*.xth`, 20 preinstalled schemes) with live zero-restart reload across the entire UI and terminal, alongside dedicated managers for desktop wallpapers and call ringtones (supporting both standard audio and tracker modules) with 3-level vibration control.
### Input, terminal, and developer tools
- **6-mode `fcitx5-t9` keypad input**: press `#` to cycle between `abc`, `Abc`, `ABC`, `Sym` (all 32 ASCII punctuation symbols), `Ctl` (`Ctrl` sequences, arrows, `PageUp`/`PageDown`, `F1`–`F12`), and `123` numeric modes with a fixed bottom candidate bar.
- **First-class Linux terminal (`st`)**: patched with HarfBuzz OpenType ligatures (`Fira Code` as the default system and terminal font), XIM T9 input, and live theme reloading.
- **On-device development, scripting, 3D demos, and gaming**: preinstalled `gcc`/`g++`, `make`, `git`, GNU `coreutils`, GNU `bc`/`dc`, `mandoc`, `nano`, `ed`, `sqlite3`, `lua` (`5.5` and `5.4`), `yabasic` (with full `yabasic-doc` manual and HTML documentation), `perl`, `tcl`, the [Janet](https://janet-lang.org/) language and `jpm`, the [Bantam](https://bantam.luxferre.top/) coding agent, `frotz` (interactive fiction), OpenGL / OpenGL ES hardware diagnostics and demos (`glxinfo`, `eglinfo`, `glxgears`, `glteapot`, `es2gears_x11`), standalone X11 keypad games (`Snake` and `Tetris`), and a full-featured Gambatte-based Game Boy / Game Boy Color emulator (`gambatte` / `gbemu`) with readjustable keypad controls (`B=8`, `Turbo B=5`, `A=9`, `Turbo A=6`, `D-pad`, `Start=2`, `Select=3`, `Palette=*`), 10 color palettes, save states, and file manager `.gb`/`.gbc` integration.
- **On-device development, scripting, 3D demos, and gaming**: preinstalled `gcc`/`g++`, `make`, `git`, GNU `coreutils`, GNU `bc`/`dc`, `mandoc`, `nano`, `ed`, `sqlite3`, `lua` (`5.5` and `5.4`), `yabasic` (with full `yabasic-doc` manual and HTML documentation), `perl`, `tcl`, the [Janet](https://janet-lang.org/) language and `jpm`, the [Bantam](https://bantam.luxferre.top/) coding agent, `frotz` (interactive fiction), OpenGL / OpenGL ES hardware diagnostics and demos (`glxinfo`, `eglinfo`, `glxgears`, `glteapot`, `es2gears_x11`), standalone X11 keypad games (`Snake` and `Tetris`), a full-featured Gambatte-based Game Boy / Game Boy Color emulator (`gambatte` / `gbemu`) with readjustable keypad controls (`B=8`, `Turbo B=5`, `A=9`, `Turbo A=6`, `D-pad`, `Start=2`, `Select=3`, `Palette=*`), 10 color palettes, save states, and file manager `.gb`/`.gbc` integration, and **ReMEdy (`remedy` / `j2me`)**, a native `240x320` J2ME (MIDP 2.0 / CLDC 1.1) emulator with Adreno 304 hardware-accelerated JSR-184 M3G 3D graphics, NeoUI-themed high-level LCDUI widgets, socket/HTTP networking (`Connector`), `RecordStore` (RMS) persistence, MMAPI audio, readjustable keypad controls, and `.jar`/`.jad` file manager integration.
- **NeoUI `240x320` UI SDK (`libneoui.so` + `/usr/include/neoui.h` + `neoui.yab`) and NeoNet (`neonet.yab`)**: unified C-compatible FFI and C++20 UI SDK wrapping Xlib, Xft, Pango, `libjpeg`/`libpng`, `.Xresources` / `~/.xthemes/*.xth` live theme resolution, offscreen `Pixmap` double buffering, standardized OS shell widgets (headers, tabs, softkey bars, list/toggle/slider rows, input boxes, progress bars, scrollbars, modals, popup menus, and toasts), keypad/softkey chord handling, and multi-tap text entry—usable from C, C++, or Yabasic (`~/Projects/neoui.yab` and `~/Projects/neoui_demo.yab`), paired with **NeoNet (`~/Projects/neonet.yab` and `~/Projects/neonet_demo.yab`)** for `libcurl`-based HTTP/HTTPS requests with custom headers and TCP/TLS/UDP socket exchange in Yabasic. See [SDK.md](./SDK.md) for full documentation.
---
@@ -79,7 +79,7 @@ bananarchy/
│ ├── xf86-input-libinput/ # Xlibre xf86-input-libinput DDX driver
│ ├── xf86-video-fbdev/ # Xlibre xf86-video-fbdev fallback DDX driver
│ ├── fcitx5-t9/ # 6-mode fcitx5-t9 keypad input method
│ ├── games/ # Standalone keypad X11 games and Gambatte GB/GBC emulator (snake, tetris, gambatte)
│ ├── games/ # Standalone keypad X11 games, Gambatte GB/GBC, and ReMEdy J2ME (snake, tetris, gambatte, remedy)
│ ├── leds-msm8905-torch/ # Kernel driver for SY7807 torch LED, WCD codec init, and PON shutdown
│ └── msm8905-cam/ # Kernel V4L2 driver for GC2395/GC2385/GC2365 2MP rear camera (/dev/video0)
├── overlay/rootfs/ # System configuration overlay applied over the target rootfs
@@ -106,7 +106,7 @@ All components are pre-compiled in `prebuilt/` and `overlay/rootfs/`, and can be
# Rebuild patched sxmo-st, sxmo-dmenu, sxmo-dwm, and all 14 C++ DWM plugins
./scripts/build-sxmo-x11.sh
# Rebuild standalone X11 games and emulators (snake, tetris, gambatte)
# Rebuild standalone X11 games and emulators (snake, tetris, gambatte, remedy)
./scripts/build-games.sh
# Rebuild multi-mode fcitx5-t9 input engine
@@ -0,0 +1,10 @@
MIDlet-Name: Astro Blaster 240
MIDlet-Version: 1.0.0
MIDlet-Vendor: Bananarchy
MIDlet-Description: 240x320 MIDP 2.0 GameCanvas vertical space shooter with RMS & MMAPI
MIDlet-Icon: /icon.png
MIDlet-1: Astro Blaster 240, /icon.png, AstroMIDlet
MIDlet-Jar-URL: AstroBlaster240.jar
MIDlet-Jar-Size: 3673
MicroEdition-Profile: MIDP-2.0
MicroEdition-Configuration: CLDC-1.1
Binary file not shown.
@@ -0,0 +1,10 @@
MIDlet-Name: J2ME Net & UI Tool
MIDlet-Version: 1.0.0
MIDlet-Vendor: Bananarchy
MIDlet-Description: NeoUI-themed LCDUI widget suite with GCF HTTP and TCP Socket tools
MIDlet-Icon: /icon.png
MIDlet-1: J2ME Net & UI Tool, /icon.png, NetToolMIDlet
MIDlet-Jar-URL: NetToolJ2ME.jar
MIDlet-Jar-Size: 3357
MicroEdition-Profile: MIDP-2.0
MicroEdition-Configuration: CLDC-1.1
Binary file not shown.
@@ -0,0 +1,10 @@
MIDlet-Name: ReMEdy 3D Arena
MIDlet-Version: 1.0.0
MIDlet-Vendor: Bananarchy
MIDlet-Description: 240x320 M3G (JSR-184) hardware-accelerated 3D cube/crystal arena
MIDlet-Icon: /icon.png
MIDlet-1: ReMEdy 3D Arena, /icon.png, Arena3DMIDlet
MIDlet-Jar-URL: ReMEdy3DArena.jar
MIDlet-Jar-Size: 4846
MicroEdition-Profile: MIDP-2.0
MicroEdition-Configuration: CLDC-1.1
Binary file not shown.
Binary file not shown.
+1
View File
@@ -0,0 +1 @@
remedy
BIN
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,10 @@
MIDlet-Name: Astro Blaster 240
MIDlet-Version: 1.0.0
MIDlet-Vendor: Bananarchy
MIDlet-Description: 240x320 MIDP 2.0 GameCanvas vertical space shooter with RMS & MMAPI
MIDlet-Icon: /icon.png
MIDlet-1: Astro Blaster 240, /icon.png, AstroMIDlet
MIDlet-Jar-URL: AstroBlaster240.jar
MIDlet-Jar-Size: 3673
MicroEdition-Profile: MIDP-2.0
MicroEdition-Configuration: CLDC-1.1
@@ -0,0 +1,10 @@
MIDlet-Name: J2ME Net & UI Tool
MIDlet-Version: 1.0.0
MIDlet-Vendor: Bananarchy
MIDlet-Description: NeoUI-themed LCDUI widget suite with GCF HTTP and TCP Socket tools
MIDlet-Icon: /icon.png
MIDlet-1: J2ME Net & UI Tool, /icon.png, NetToolMIDlet
MIDlet-Jar-URL: NetToolJ2ME.jar
MIDlet-Jar-Size: 3357
MicroEdition-Profile: MIDP-2.0
MicroEdition-Configuration: CLDC-1.1
Binary file not shown.
@@ -0,0 +1,10 @@
MIDlet-Name: ReMEdy 3D Arena
MIDlet-Version: 1.0.0
MIDlet-Vendor: Bananarchy
MIDlet-Description: 240x320 M3G (JSR-184) hardware-accelerated 3D cube/crystal arena
MIDlet-Icon: /icon.png
MIDlet-1: ReMEdy 3D Arena, /icon.png, Arena3DMIDlet
MIDlet-Jar-URL: ReMEdy3DArena.jar
MIDlet-Jar-Size: 4846
MicroEdition-Profile: MIDP-2.0
MicroEdition-Configuration: CLDC-1.1
Binary file not shown.
@@ -193,6 +193,7 @@ write_line_app qutebrowser "$icon_glb Qutebrowser" "qutebrowser"
write_line_app radio-cli "$icon_rad Radio Cli" "sxmo_terminal.sh radio-cli"
write_line_app railway "$icon_trn Railway" "railway"
write_line_app ranger "$icon_dir Ranger" "sxmo_terminal.sh ranger"
write_line_app remedy "$icon_gam ReMEdy (J2ME)" "remedy"
write_line_app resources "$icon_spd Resources" "resources"
write_line_app sacc "$icon_glb Sacc" "sxmo_terminal.sh sacc i-logout.cz/1/bongusta"
write_line_app secrets "$icon_lck Secrets" "secrets"
@@ -34,3 +34,4 @@ write_line_app() {
write_line_app snake "$icon_gam Snake" "snake"
write_line_app tetris "$icon_gam Tetris" "tetris"
write_line_app gambatte "$icon_gam Game Boy (Gambatte)" "gambatte"
write_line_app remedy "$icon_gam ReMEdy (J2ME)" "remedy"
+1
View File
@@ -0,0 +1 @@
remedy
BIN
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
+27 -5
View File
@@ -30,7 +30,7 @@ EOF
binutils-armv7 \
pkgconf >/dev/null
echo "[2/4] Preparing armv7 sysroot (X11 + ALSA)..."
echo "[2/4] Preparing armv7 sysroot (X11 + NeoUI + EGL/GLESv2 + ALSA + Media/Net)..."
SYSROOT="/tmp/armv7-sysroot"
mkdir -p "$SYSROOT/etc/apk/keys"
cp /etc/apk/repositories "$SYSROOT/etc/apk/repositories"
@@ -40,7 +40,18 @@ EOF
musl-dev \
linux-headers \
libx11-dev \
alsa-lib-dev >/dev/null
libxft-dev \
pango-dev \
glib-dev \
alsa-lib-dev \
zlib-dev \
libpng-dev \
libjpeg-turbo-dev \
curl-dev \
mesa-dev >/dev/null
cp /bananarchy/prebuilt/sxmo-x11/usr/lib/libneoui.so "$SYSROOT/usr/lib/libneoui.so"
cp /bananarchy/src/neoui/neoui.h "$SYSROOT/usr/include/neoui.h"
export PKG_CONFIG_SYSROOT_DIR="$SYSROOT"
export PKG_CONFIG_LIBDIR="$SYSROOT/usr/lib/pkgconfig:$SYSROOT/usr/share/pkgconfig"
@@ -51,7 +62,7 @@ EOF
mkdir -p /bananarchy/prebuilt/games/usr/bin
echo "[3/4] Compiling Snake, Tetris, and Gambatte (Game Boy / Game Boy Color)..."
echo "[3/4] Compiling Snake, Tetris, Gambatte (GB/GBC), and ReMEdy (J2ME MIDP 2.0 / M3G 3D)..."
$CXX $OPT_CFLAGS -std=c++17 -Wall -Wextra \
/bananarchy/src/games/snake.cpp $(pkgconf --libs x11) \
-o /bananarchy/prebuilt/games/usr/bin/snake
@@ -76,10 +87,21 @@ EOF
ln -sf gambatte /bananarchy/prebuilt/games/usr/bin/gbemu
$CXX $OPT_CFLAGS -std=c++20 -Wall -Wextra \
$(pkgconf --cflags x11 xft pangoxft pango glib-2.0 gobject-2.0 alsa zlib libpng libjpeg libcurl egl glesv2) \
/bananarchy/src/games/remedy/remedy_main.cpp \
-L"$SYSROOT/usr/lib" -lneoui \
$(pkgconf --libs x11 xft pangoxft pango glib-2.0 gobject-2.0 alsa zlib libpng libjpeg libcurl egl glesv2) \
-lpthread -lm \
-o /bananarchy/prebuilt/games/usr/bin/remedy
ln -sf remedy /bananarchy/prebuilt/games/usr/bin/j2me
$STRIP --strip-unneeded \
/bananarchy/prebuilt/games/usr/bin/snake \
/bananarchy/prebuilt/games/usr/bin/tetris \
/bananarchy/prebuilt/games/usr/bin/gambatte
/bananarchy/prebuilt/games/usr/bin/gambatte \
/bananarchy/prebuilt/games/usr/bin/remedy
echo "[4/4] Installing into overlay and (optional) target rootfs..."
mkdir -p /bananarchy/overlay/rootfs/usr/bin
@@ -92,5 +114,5 @@ EOF
/bananarchy/prebuilt/games \
/bananarchy/overlay/rootfs/usr/bin \
/bananarchy/src/games
ls -lh /bananarchy/prebuilt/games/usr/bin/snake /bananarchy/prebuilt/games/usr/bin/tetris /bananarchy/prebuilt/games/usr/bin/gambatte
ls -lh /bananarchy/prebuilt/games/usr/bin/snake /bananarchy/prebuilt/games/usr/bin/tetris /bananarchy/prebuilt/games/usr/bin/gambatte /bananarchy/prebuilt/games/usr/bin/remedy
'
+4188
View File
File diff suppressed because it is too large. Load diff
+14 -1
View File
@@ -194,6 +194,10 @@ bool isGameBoyExt(const std::string& ext) {
return ext == "gb" || ext == "gbc";
}
bool isJ2meExt(const std::string& ext) {
return ext == "jar" || ext == "jad";
}
bool isYabasicExt(const std::string& ext) {
return ext == "yab";
}
@@ -762,6 +766,11 @@ int runFilesApp(int argc, char** argv) {
actionsList.push_back({15, kIconBell, "Set as Ringtone"});
} else if (isGameBoyExt(ext)) {
actionsList.push_back({1, kIconGamepad, "Play in Game Boy Emulator"});
} else if (isJ2meExt(ext)) {
actionsList.push_back({1, kIconGamepad, "Run in ReMEdy (J2ME)"});
if (ext == "jad") {
actionsList.push_back({17, kIconEye, "View JAD Descriptor"});
}
} else if (isYabasicExt(ext)) {
actionsList.push_back({1, kIconTerm, "Run in Yabasic (Terminal)"});
actionsList.push_back({17, kIconEye, "View Text"});
@@ -855,6 +864,10 @@ int runFilesApp(int argc, char** argv) {
hideWindow();
runAsyncArgv("gambatte", item.fullPath.c_str());
return;
} else if (isJ2meExt(ext)) {
hideWindow();
runAsyncArgv("remedy", item.fullPath.c_str());
return;
} else if (isYabasicExt(ext)) {
runYabasicInTerminal(item.fullPath);
return;
@@ -967,7 +980,7 @@ int runFilesApp(int argc, char** argv) {
} else if (isMediaExt(ext)) {
ic = kIconMusic;
icCol = &colBlue;
} else if (isGameBoyExt(ext)) {
} else if (isGameBoyExt(ext) || isJ2meExt(ext)) {
ic = kIconGamepad;
icCol = &colYellow;
} else if (isYabasicExt(ext) || it.isExec || ext == "sh") {
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+565
View File
@@ -0,0 +1,565 @@
// SPDX-License-Identifier: GPL-2.0-only
// ReMEdy J2ME (MIDP 2.0 / CLDC 1.1) Emulator for Bananarchy Linux
// Part 4A: MIDP 2.0 LCDUI (240x320 Canvas, GameCanvas, Nokia UI, and NeoUI-Themed Forms/Lists)
#ifndef BANANARCHY_REMEDY_LCDUI_HPP
#define BANANARCHY_REMEDY_LCDUI_HPP
#include "remedy_cldc_net_media.hpp"
#include "../../neoui/neoui.h"
#include <jpeglib.h>
#include <png.h>
namespace remedy {
// ---------------------------------------------------------------------------
// Built-in 5x7 ASCII Bitmap Font for Fast Canvas / Offscreen Image Text
// ---------------------------------------------------------------------------
inline const uint8_t* glyph5x7(char c) {
static const uint8_t kFont[96][5] = {
{0x00,0x00,0x00,0x00,0x00}, {0x00,0x00,0x5F,0x00,0x00},
{0x00,0x07,0x00,0x07,0x00}, {0x14,0x7F,0x14,0x7F,0x14},
{0x24,0x2A,0x7F,0x2A,0x12}, {0x23,0x13,0x08,0x64,0x62},
{0x36,0x49,0x55,0x22,0x50}, {0x00,0x05,0x03,0x00,0x00},
{0x00,0x1C,0x22,0x41,0x00}, {0x00,0x41,0x22,0x1C,0x00},
{0x14,0x08,0x3E,0x08,0x14}, {0x08,0x08,0x3E,0x08,0x08},
{0x00,0x50,0x30,0x00,0x00}, {0x08,0x08,0x08,0x08,0x08},
{0x00,0x60,0x60,0x00,0x00}, {0x20,0x10,0x08,0x04,0x02},
{0x3E,0x51,0x49,0x45,0x3E}, {0x00,0x42,0x7F,0x40,0x00},
{0x42,0x61,0x51,0x49,0x46}, {0x21,0x41,0x45,0x4B,0x31},
{0x18,0x14,0x12,0x7F,0x10}, {0x27,0x45,0x45,0x45,0x39},
{0x3C,0x4A,0x49,0x49,0x30}, {0x01,0x71,0x09,0x05,0x03},
{0x36,0x49,0x49,0x49,0x36}, {0x06,0x49,0x49,0x29,0x1E},
{0x00,0x36,0x36,0x00,0x00}, {0x00,0x56,0x36,0x00,0x00},
{0x08,0x14,0x22,0x41,0x00}, {0x14,0x14,0x14,0x14,0x14},
{0x00,0x41,0x22,0x14,0x08}, {0x02,0x01,0x51,0x09,0x06},
{0x32,0x49,0x79,0x41,0x3E}, {0x7E,0x11,0x11,0x11,0x7E},
{0x7F,0x49,0x49,0x49,0x36}, {0x3E,0x41,0x41,0x41,0x22},
{0x7F,0x41,0x41,0x22,0x1C}, {0x7F,0x49,0x49,0x49,0x41},
{0x7F,0x09,0x09,0x09,0x01}, {0x3E,0x41,0x49,0x49,0x7A},
{0x7F,0x08,0x08,0x08,0x7F}, {0x00,0x41,0x7F,0x41,0x00},
{0x20,0x40,0x41,0x3F,0x01}, {0x7F,0x08,0x14,0x22,0x41},
{0x7F,0x40,0x40,0x40,0x40}, {0x7F,0x02,0x0C,0x02,0x7F},
{0x7F,0x04,0x08,0x10,0x7F}, {0x3E,0x41,0x41,0x41,0x3E},
{0x7F,0x09,0x09,0x09,0x06}, {0x3E,0x41,0x51,0x21,0x5E},
{0x7F,0x09,0x19,0x29,0x46}, {0x46,0x49,0x49,0x49,0x31},
{0x01,0x01,0x7F,0x01,0x01}, {0x3F,0x40,0x40,0x40,0x3F},
{0x1F,0x20,0x40,0x20,0x1F}, {0x3F,0x40,0x38,0x40,0x3F},
{0x63,0x14,0x08,0x14,0x63}, {0x07,0x08,0x70,0x08,0x07},
{0x61,0x51,0x49,0x45,0x43}, {0x00,0x7F,0x41,0x41,0x00},
{0x02,0x04,0x08,0x10,0x20}, {0x00,0x41,0x41,0x7F,0x00},
{0x04,0x02,0x01,0x02,0x04}, {0x40,0x40,0x40,0x40,0x40},
{0x00,0x01,0x02,0x04,0x00}, {0x20,0x54,0x54,0x54,0x78},
{0x7F,0x48,0x44,0x44,0x38}, {0x38,0x44,0x44,0x44,0x20},
{0x38,0x44,0x44,0x48,0x7F}, {0x38,0x54,0x54,0x54,0x18},
{0x08,0x7E,0x09,0x01,0x02}, {0x0C,0x52,0x52,0x52,0x3E},
{0x7F,0x08,0x04,0x04,0x78}, {0x00,0x44,0x7D,0x40,0x00},
{0x20,0x40,0x44,0x3D,0x00}, {0x7F,0x10,0x28,0x44,0x00},
{0x00,0x41,0x7F,0x40,0x00}, {0x7C,0x04,0x18,0x04,0x78},
{0x7C,0x08,0x04,0x04,0x78}, {0x38,0x44,0x44,0x44,0x38},
{0x7C,0x14,0x14,0x14,0x08}, {0x08,0x14,0x14,0x18,0x7C},
{0x7C,0x08,0x04,0x04,0x08}, {0x48,0x54,0x54,0x54,0x20},
{0x04,0x3F,0x44,0x40,0x20}, {0x3C,0x40,0x40,0x20,0x7C},
{0x1C,0x20,0x40,0x20,0x1C}, {0x3C,0x40,0x30,0x40,0x3C},
{0x44,0x28,0x10,0x28,0x44}, {0x0C,0x50,0x50,0x50,0x3C},
{0x44,0x64,0x54,0x4C,0x44}, {0x00,0x08,0x36,0x41,0x00},
{0x00,0x00,0x7F,0x00,0x00}, {0x00,0x41,0x36,0x08,0x00},
{0x10,0x08,0x08,0x10,0x08}, {0x7F,0x7F,0x7F,0x7F,0x7F}
};
unsigned char uc = static_cast<unsigned char>(c);
if (uc < 32 || uc > 127) uc = '?';
return kFont[uc - 32];
}
// ---------------------------------------------------------------------------
// 2D ARGB8888 Image & Graphics Surface
// ---------------------------------------------------------------------------
struct NativeImageSurface {
int width = 240;
int height = 320;
bool mutableImg = true;
bool isMutable = true;
std::vector<uint32_t> pixels; // 0xAARRGGBB
NativeImageSurface(int w = 240, int h = 320, uint32_t fill = 0xFFFFFFFFu)
: width(std::max(1, w)),
height(std::max(1, h)),
pixels(static_cast<size_t>(width) * height, fill) {}
NativeImageSurface(int w, int h, bool mut, uint32_t fill = 0xFFFFFFFFu)
: width(std::max(1, w)),
height(std::max(1, h)),
mutableImg(mut),
isMutable(mut),
pixels(static_cast<size_t>(width) * height, fill) {}
void clear(uint32_t fill = 0xFF000000u) {
std::fill(pixels.begin(), pixels.end(), fill);
}
void resize(int w, int h, uint32_t fill = 0xFF000000u) {
width = std::max(1, w);
height = std::max(1, h);
pixels.assign(static_cast<size_t>(width) * height, fill);
}
static bool DecodeFromMemory(const uint8_t* data, size_t len,
NativeImageSurface* out);
inline void blendPixel(int x, int y, uint32_t srcArgb) {
if (x < 0 || y < 0 || x >= width || y >= height) return;
uint32_t a = (srcArgb >> 24) & 0xFFu;
if (a == 0) return;
uint32_t& dst = pixels[static_cast<size_t>(y) * width + x];
if (a == 255) {
dst = srcArgb | 0xFF000000u;
return;
}
uint32_t invA = 255u - a;
uint32_t r = (((srcArgb >> 16) & 0xFFu) * a + ((dst >> 16) & 0xFFu) * invA) >> 8;
uint32_t g = (((srcArgb >> 8) & 0xFFu) * a + ((dst >> 8) & 0xFFu) * invA) >> 8;
uint32_t b = ((srcArgb & 0xFFu) * a + (dst & 0xFFu) * invA) >> 8;
dst = 0xFF000000u | (r << 16) | (g << 8) | b;
}
};
// PNG & JPEG decoding from memory
inline bool decodeImageBytes(const uint8_t* data, size_t len,
NativeImageSurface* out) {
if (!data || len < 8 || !out) return false;
// 1. Check PNG signature
if (png_sig_cmp(data, 0, 8) == 0) {
png_structp png = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr,
nullptr, nullptr);
if (!png) return false;
png_infop info = png_create_info_struct(png);
if (!info) {
png_destroy_read_struct(&png, nullptr, nullptr);
return false;
}
if (setjmp(png_jmpbuf(png))) {
png_destroy_read_struct(&png, &info, nullptr);
return false;
}
struct MemReader {
const uint8_t* ptr;
size_t size;
size_t pos;
} reader{data, len, 0};
png_set_read_fn(png, &reader,
[](png_structp p, png_bytep dst, png_size_t count) {
auto* r = static_cast<MemReader*>(png_get_io_ptr(p));
size_t avail = (r->size > r->pos) ? (r->size - r->pos) : 0;
size_t n = std::min<size_t>(count, avail);
if (n > 0) std::memcpy(dst, r->ptr + r->pos, n);
r->pos += n;
});
png_read_info(png, info);
png_uint_32 w = png_get_image_width(png, info);
png_uint_32 h = png_get_image_height(png, info);
png_byte colorType = png_get_color_type(png, info);
png_byte bitDepth = png_get_bit_depth(png, info);
if (bitDepth == 16) png_set_strip_16(png);
if (colorType == PNG_COLOR_TYPE_PALETTE) png_set_palette_to_rgb(png);
if (colorType == PNG_COLOR_TYPE_GRAY && bitDepth < 8) {
png_set_expand_gray_1_2_4_to_8(png);
}
if (png_get_valid(png, info, PNG_INFO_tRNS)) png_set_tRNS_to_alpha(png);
if (colorType == PNG_COLOR_TYPE_RGB || colorType == PNG_COLOR_TYPE_GRAY ||
colorType == PNG_COLOR_TYPE_PALETTE) {
png_set_filler(png, 0xFF, PNG_FILLER_AFTER);
}
if (colorType == PNG_COLOR_TYPE_GRAY ||
colorType == PNG_COLOR_TYPE_GRAY_ALPHA) {
png_set_gray_to_rgb(png);
}
png_read_update_info(png, info);
out->resize(static_cast<int>(w), static_cast<int>(h), 0);
out->mutableImg = false;
std::vector<uint8_t> row(w * 4);
for (png_uint_32 y = 0; y < h; ++y) {
png_read_row(png, row.data(), nullptr);
uint32_t* dst = out->pixels.data() + static_cast<size_t>(y) * w;
for (png_uint_32 x = 0; x < w; ++x) {
uint32_t r = row[x * 4 + 0];
uint32_t g = row[x * 4 + 1];
uint32_t b = row[x * 4 + 2];
uint32_t a = row[x * 4 + 3];
dst[x] = (a << 24) | (r << 16) | (g << 8) | b;
}
}
png_destroy_read_struct(&png, &info, nullptr);
return true;
}
// 2. Check JPEG signature (FF D8)
if (data[0] == 0xFF && data[1] == 0xD8) {
struct jpeg_decompress_struct cinfo {};
struct jpeg_error_mgr jerr {};
cinfo.err = jpeg_std_error(&jerr);
jpeg_create_decompress(&cinfo);
jpeg_mem_src(&cinfo, const_cast<unsigned char*>(data), len);
if (jpeg_read_header(&cinfo, TRUE) != JPEG_HEADER_OK) {
jpeg_destroy_decompress(&cinfo);
return false;
}
cinfo.out_color_space = JCS_RGB;
jpeg_start_decompress(&cinfo);
int w = static_cast<int>(cinfo.output_width);
int h = static_cast<int>(cinfo.output_height);
out->resize(w, h, 0xFF000000u);
out->mutableImg = false;
std::vector<uint8_t> row(static_cast<size_t>(w) * 3);
while (cinfo.output_scanline < cinfo.output_height) {
int y = static_cast<int>(cinfo.output_scanline);
JSAMPROW rowPtr = row.data();
jpeg_read_scanlines(&cinfo, &rowPtr, 1);
uint32_t* dst = out->pixels.data() + static_cast<size_t>(y) * w;
for (int x = 0; x < w; ++x) {
dst[x] = 0xFF000000u |
(static_cast<uint32_t>(row[x * 3 + 0]) << 16) |
(static_cast<uint32_t>(row[x * 3 + 1]) << 8) |
static_cast<uint32_t>(row[x * 3 + 2]);
}
}
jpeg_finish_decompress(&cinfo);
jpeg_destroy_decompress(&cinfo);
return true;
}
return false;
}
inline bool NativeImageSurface::DecodeFromMemory(const uint8_t* data,
size_t len,
NativeImageSurface* out) {
return decodeImageBytes(data, len, out);
}
struct NativeGraphicsState {
std::shared_ptr<NativeImageSurface> target;
int transX = 0;
int transY = 0;
int clipX = 0;
int clipY = 0;
int clipW = 240;
int clipH = 320;
uint32_t colorArgb = 0xFF000000u;
int strokeStyle = 0; // 0=SOLID, 1=DOTTED
int fontSize = 0; // 8=SMALL, 0=MEDIUM, 16=LARGE
int fontStyle = 0; // 0=PLAIN, 1=BOLD, 2=ITALIC, 4=UNDERLINED
uint32_t fontRef = 0;
void resetTarget(NativeImageSurface* surf) {
if (surf) {
target = std::shared_ptr<NativeImageSurface>(
surf, [](NativeImageSurface*) {});
clipX = 0;
clipY = 0;
clipW = surf->width;
clipH = surf->height;
} else {
target.reset();
}
transX = 0;
transY = 0;
colorArgb = 0xFF000000u;
strokeStyle = 0;
}
static int FontPixelHeight(int sz) {
if (sz == 8) return 9;
if (sz == 16) return 16;
return 12;
}
static int MeasureTextWidth(const std::string& s, int sz, int /*st*/) {
int adv = (sz == 8) ? 6 : (sz == 16 ? 12 : 7);
return static_cast<int>(s.size()) * adv;
}
int scaleForFont() const {
if (fontSize == 8) return 1; // SMALL: 6x9
if (fontSize == 16) return 2; // LARGE: 12x16
return 1; // MEDIUM: 7x11
}
int fontPixelHeight() const {
if (fontSize == 8) return 9;
if (fontSize == 16) return 16;
return 12;
}
int charAdvance() const {
if (fontSize == 8) return 6;
if (fontSize == 16) return 12;
return 7;
}
inline void putClipped(int x, int y, uint32_t argb) {
if (!target) return;
if (x < clipX || y < clipY || x >= clipX + clipW || y >= clipY + clipH) {
return;
}
target->blendPixel(x, y, argb);
}
void fillRect(int x, int y, int w, int h) {
if (!target || w <= 0 || h <= 0) return;
x += transX;
y += transY;
int x0 = std::max({0, clipX, x});
int y0 = std::max({0, clipY, y});
int x1 = std::min({target->width, clipX + clipW, x + w});
int y1 = std::min({target->height, clipY + clipH, y + h});
if (x0 >= x1 || y0 >= y1) return;
uint32_t a = (colorArgb >> 24) & 0xFFu;
for (int py = y0; py < y1; ++py) {
uint32_t* row = target->pixels.data() + static_cast<size_t>(py) * target->width;
if (a == 255) {
uint32_t c = colorArgb | 0xFF000000u;
for (int px = x0; px < x1; ++px) row[px] = c;
} else {
for (int px = x0; px < x1; ++px) target->blendPixel(px, py, colorArgb);
}
}
}
void drawLine(int x1, int y1, int x2, int y2) {
if (!target) return;
x1 += transX;
y1 += transY;
x2 += transX;
y2 += transY;
int dx = std::abs(x2 - x1), sx = x1 < x2 ? 1 : -1;
int dy = -std::abs(y2 - y1), sy = y1 < y2 ? 1 : -1;
int err = dx + dy;
int step = 0;
while (true) {
if (strokeStyle == 0 || ((step & 2) == 0)) {
putClipped(x1, y1, colorArgb);
}
if (x1 == x2 && y1 == y2) break;
int e2 = 2 * err;
if (e2 >= dy) {
err += dy;
x1 += sx;
}
if (e2 <= dx) {
err += dx;
y1 += sy;
}
++step;
}
}
void drawRect(int x, int y, int w, int h) {
if (w < 0 || h < 0) return;
drawLine(x, y, x + w, y);
drawLine(x + w, y, x + w, y + h);
drawLine(x + w, y + h, x, y + h);
drawLine(x, y + h, x, y);
}
void drawRoundRect(int x, int y, int w, int h, int /*arcW*/, int /*arcH*/) {
drawRect(x, y, w, h);
}
void fillRoundRect(int x, int y, int w, int h, int /*arcW*/, int /*arcH*/) {
fillRect(x, y, w, h);
}
void drawImage(const NativeImageSurface& src, int x, int y, int anchor) {
drawRegion(src, 0, 0, src.width, src.height, 0, x, y, anchor);
}
void fillTriangle(int x1, int y1, int x2, int y2, int x3, int y3) {
if (!target) return;
x1 += transX; y1 += transY;
x2 += transX; y2 += transY;
x3 += transX; y3 += transY;
int minX = std::max({0, clipX, std::min({x1, x2, x3})});
int maxX = std::min({target->width - 1, clipX + clipW - 1, std::max({x1, x2, x3})});
int minY = std::max({0, clipY, std::min({y1, y2, y3})});
int maxY = std::min({target->height - 1, clipY + clipH - 1, std::max({y1, y2, y3})});
auto edge = [](int ax, int ay, int bx, int by, int px, int py) {
return (px - ax) * (by - ay) - (py - ay) * (bx - ax);
};
int area = edge(x1, y1, x2, y2, x3, y3);
if (area == 0) {
drawLine(x1 - transX, y1 - transY, x2 - transX, y2 - transY);
return;
}
for (int py = minY; py <= maxY; ++py) {
for (int px = minX; px <= maxX; ++px) {
int w0 = edge(x2, y2, x3, y3, px, py);
int w1 = edge(x3, y3, x1, y1, px, py);
int w2 = edge(x1, y1, x2, y2, px, py);
if ((w0 >= 0 && w1 >= 0 && w2 >= 0) ||
(w0 <= 0 && w1 <= 0 && w2 <= 0)) {
target->blendPixel(px, py, colorArgb);
}
}
}
}
void fillArc(int x, int y, int w, int h, int /*startAngle*/, int /*arcAngle*/) {
if (!target || w <= 0 || h <= 0) return;
x += transX;
y += transY;
float rx = w * 0.5f;
float ry = h * 0.5f;
float cx = x + rx;
float cy = y + ry;
for (int py = y; py < y + h; ++py) {
for (int px = x; px < x + w; ++px) {
float dx = (px + 0.5f - cx) / rx;
float dy = (py + 0.5f - cy) / ry;
if (dx * dx + dy * dy <= 1.0f) {
putClipped(px, py, colorArgb);
}
}
}
}
void drawArc(int x, int y, int w, int h, int /*startAngle*/, int /*arcAngle*/) {
if (!target || w <= 0 || h <= 0) return;
x += transX;
y += transY;
float rx = w * 0.5f;
float ry = h * 0.5f;
float cx = x + rx;
float cy = y + ry;
for (int a = 0; a < 360; a += 2) {
float rad = a * 0.0174532925f;
int px = static_cast<int>(cx + rx * std::cos(rad));
int py = static_cast<int>(cy - ry * std::sin(rad));
putClipped(px, py, colorArgb);
}
}
void drawString(const std::string& text, int x, int y, int anchor) {
if (!target || text.empty()) return;
int sc = scaleForFont();
int adv = charAdvance();
int fh = fontPixelHeight();
int tw = static_cast<int>(text.size()) * adv;
int drawX = x + transX;
int drawY = y + transY;
// Horizontal anchor: HCENTER=1, LEFT=4, RIGHT=8
if (anchor & 1) drawX -= tw / 2;
else if (anchor & 8) drawX -= tw;
// Vertical anchor: VCENTER=2, TOP=16, BOTTOM=32, BASELINE=64
if (anchor & 2) drawY -= fh / 2;
else if (anchor & (32 | 64)) drawY -= fh;
int padY = (fh - 7 * sc) / 2;
bool bold = (fontStyle & 1) != 0;
for (size_t i = 0; i < text.size(); ++i) {
const uint8_t* g = glyph5x7(text[i]);
int cx = drawX + static_cast<int>(i) * adv;
for (int col = 0; col < 5; ++col) {
uint8_t bits = g[col];
for (int row = 0; row < 7; ++row) {
if (bits & (1u << row)) {
for (int sy = 0; sy < sc; ++sy) {
for (int sx = 0; sx < sc + (bold ? 1 : 0); ++sx) {
putClipped(cx + col * sc + sx, drawY + padY + row * sc + sy,
colorArgb);
}
}
}
}
}
}
if (fontStyle & 4) { // UNDERLINED
for (int ux = 0; ux < tw; ++ux) {
putClipped(drawX + ux, drawY + fh - 1, colorArgb);
}
}
}
// MIDP 2.0 drawRegion with all 8 Sprite transforms:
// 0=NONE, 1=MIRROR_ROT180, 2=MIRROR, 3=ROT180,
// 4=MIRROR_ROT270, 5=ROT90, 6=ROT270, 7=MIRROR_ROT90
void drawRegion(const NativeImageSurface& src, int xSrc, int ySrc,
int width, int height, int transform, int xDest, int yDest,
int anchor) {
if (!target || width <= 0 || height <= 0) return;
bool swapWH = (transform >= 4 && transform <= 7);
int dstW = swapWH ? height : width;
int dstH = swapWH ? width : height;
int dx = xDest + transX;
int dy = yDest + transY;
if (anchor & 1) dx -= dstW / 2;
else if (anchor & 8) dx -= dstW;
if (anchor & 2) dy -= dstH / 2;
else if (anchor & (32 | 64)) dy -= dstH;
for (int oy = 0; oy < dstH; ++oy) {
for (int ox = 0; ox < dstW; ++ox) {
int sx = ox, sy = oy;
switch (transform) {
case 0: sx = ox; sy = oy; break; // TRANS_NONE
case 1: sx = ox; sy = height - 1 - oy; break; // TRANS_MIRROR_ROT180
case 2: sx = width - 1 - ox; sy = oy; break; // TRANS_MIRROR
case 3: sx = width - 1 - ox; sy = height - 1 - oy; break; // TRANS_ROT180
case 4: sx = oy; sy = ox; break; // TRANS_MIRROR_ROT270
case 5: sx = oy; sy = height - 1 - ox; break; // TRANS_ROT90
case 6: sx = width - 1 - oy; sy = ox; break; // TRANS_ROT270
case 7: sx = width - 1 - oy; sy = height - 1 - ox; break; // TRANS_MIRROR_ROT90
}
int rx = xSrc + sx;
int ry = ySrc + sy;
if (rx >= 0 && ry >= 0 && rx < src.width && ry < src.height) {
putClipped(dx + ox, dy + oy,
src.pixels[static_cast<size_t>(ry) * src.width + rx]);
}
}
}
}
};
// ---------------------------------------------------------------------------
// High-Level LCDUI Command & Screen State (Rendered with NeoUI!)
// ---------------------------------------------------------------------------
struct LcduiCommandInfo {
uint32_t cmdRef = 0;
std::string label;
int type = 1; // 1=SCREEN, 2=BACK, 3=CANCEL, 4=OK, 5=HELP, 6=STOP, 7=EXIT, 8=ITEM
int priority = 1;
};
struct LcduiScreenState {
std::string title;
std::string tickerText;
uint32_t listenerRef = 0;
std::vector<LcduiCommandInfo> commands;
bool fullScreen = true;
int selectedIdx = 0;
int scrollOffset = 0;
// For List / ChoiceGroup:
int choiceType = 1; // 1=EXCLUSIVE, 2=MULTIPLE, 3=IMPLICIT
std::vector<std::string> listItems;
std::vector<uint32_t> listImages;
std::vector<bool> listSelected;
// For Form:
std::vector<uint32_t> formItemRefs;
// For TextBox / Alert:
std::string textContent;
int maxSize = 256;
int alertTimeoutMs = 3000;
uint32_t alertNextDisplayableRef = 0;
int64_t alertShownAtMs = 0;
};
} // namespace remedy
#endif // BANANARCHY_REMEDY_LCDUI_HPP
File diff suppressed because it is too large. Load diff
+542
View File
@@ -0,0 +1,542 @@
// SPDX-License-Identifier: GPL-2.0-only
// ReMEdy J2ME (MIDP 2.0 / CLDC 1.1) Emulator for Bananarchy Linux
// Part 4B: JSR-184 (M3G) 3D Hardware Acceleration via EGL + OpenGL ES 2.0 on Adreno 304 (FD304)
#ifndef BANANARCHY_REMEDY_M3G_GL_HPP
#define BANANARCHY_REMEDY_M3G_GL_HPP
#include "remedy_lcdui.hpp"
#include <EGL/egl.h>
#include <GLES2/gl2.h>
#include <array>
#include <cmath>
namespace remedy {
// ---------------------------------------------------------------------------
// 4x4 Column-Major Matrix Helper for M3G Transform & Camera
// ---------------------------------------------------------------------------
struct Mat4 {
std::array<float, 16> m = {
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
};
static Mat4 Identity() { return Mat4{}; }
static Mat4 Multiply(const Mat4& a, const Mat4& b) {
Mat4 r;
for (int col = 0; col < 4; ++col) {
for (int row = 0; row < 4; ++row) {
float sum = 0.0f;
for (int k = 0; k < 4; ++k) {
sum += a.m[k * 4 + row] * b.m[col * 4 + k];
}
r.m[col * 4 + row] = sum;
}
}
return r;
}
static Mat4 Perspective(float fovyDeg, float aspect, float zNear, float zFar) {
Mat4 r;
r.m.fill(0.0f);
float rad = fovyDeg * 0.0174532925f;
float f = 1.0f / std::tan(rad * 0.5f);
if (aspect <= 0.0001f) aspect = 240.0f / 320.0f;
float nf = 1.0f / (zNear - zFar);
r.m[0] = f / aspect;
r.m[5] = f;
r.m[10] = (zFar + zNear) * nf;
r.m[11] = -1.0f;
r.m[14] = (2.0f * zFar * zNear) * nf;
return r;
}
void postTranslate(float tx, float ty, float tz) {
Mat4 t = Identity();
t.m[12] = tx;
t.m[13] = ty;
t.m[14] = tz;
*this = Multiply(*this, t);
}
void postScale(float sx, float sy, float sz) {
Mat4 s = Identity();
s.m[0] = sx;
s.m[5] = sy;
s.m[10] = sz;
*this = Multiply(*this, s);
}
void postRotate(float angleDeg, float ax, float ay, float az) {
float len = std::sqrt(ax * ax + ay * ay + az * az);
if (len < 1e-6f) return;
ax /= len;
ay /= len;
az /= len;
float rad = angleDeg * 0.0174532925f;
float c = std::cos(rad);
float s = std::sin(rad);
float ic = 1.0f - c;
Mat4 r = Identity();
r.m[0] = ax * ax * ic + c;
r.m[1] = ay * ax * ic + az * s;
r.m[2] = az * ax * ic - ay * s;
r.m[4] = ax * ay * ic - az * s;
r.m[5] = ay * ay * ic + c;
r.m[6] = az * ay * ic + ax * s;
r.m[8] = ax * az * ic + ay * s;
r.m[9] = ay * az * ic - ax * s;
r.m[10] = az * az * ic + c;
*this = Multiply(*this, r);
}
void transformPoint(float x, float y, float z,
float* ox, float* oy, float* oz, float* ow) const {
*ox = m[0] * x + m[4] * y + m[8] * z + m[12];
*oy = m[1] * x + m[5] * y + m[9] * z + m[13];
*oz = m[2] * x + m[6] * y + m[10] * z + m[14];
*ow = m[3] * x + m[7] * y + m[11] * z + m[15];
}
};
// ---------------------------------------------------------------------------
// M3G Native Data Structures
// ---------------------------------------------------------------------------
struct M3gVertexArrayData {
int numVertices = 0;
int numComponents = 3;
int componentSize = 2; // 1=byte, 2=short
std::vector<float> values;
};
struct M3gVertexBufferData {
uint32_t positionsRef = 0;
float posScale = 1.0f;
float posBias[3] = {0.0f, 0.0f, 0.0f};
uint32_t normalsRef = 0;
uint32_t colorsRef = 0;
uint32_t texCoordsRef = 0;
float texScale = 1.0f;
float texBias[3] = {0.0f, 0.0f, 0.0f};
uint32_t defaultColor = 0xFFFFFFFFu;
};
struct M3gIndexBufferData {
std::vector<uint16_t> triangles; // Expanded triangle list (3 indices per tri)
};
struct M3gTransformData {
Mat4 mat = Mat4::Identity();
};
struct M3gCameraData {
Mat4 proj = Mat4::Perspective(50.0f, 240.0f / 320.0f, 0.1f, 100.0f);
};
struct M3gBackgroundData {
uint32_t color = 0xFF0A101Cu;
bool colorClearEnabled = true;
bool depthClearEnabled = true;
};
// ---------------------------------------------------------------------------
// Adreno 304 (FD304) EGL + GLES2 Offscreen 3D Renderer (with SW Fallback)
// ---------------------------------------------------------------------------
class M3gGlEngine {
public:
bool useHardwareGl = true;
bool hwInitialized = false;
std::string glRendererName = "FD304";
int vpX = 0;
int vpY = 0;
int vpW = 240;
int vpH = 320;
uint32_t boundGraphicsRef = 0;
uint32_t boundTargetRef = 0;
Mat4 projMat = Mat4::Perspective(50.0f, 240.0f / 320.0f, 0.1f, 100.0f);
Mat4 viewMat = Mat4::Identity();
uint32_t lightColor = 0xFFFFFFFFu;
float lightIntensity = 1.0f;
~M3gGlEngine() { shutdown(); }
bool init(Display* x11Dpy) {
if (hwInitialized) return true;
eglDpy_ = eglGetDisplay(reinterpret_cast<EGLNativeDisplayType>(x11Dpy));
if (eglDpy_ == EGL_NO_DISPLAY) {
eglDpy_ = eglGetDisplay(EGL_DEFAULT_DISPLAY);
}
if (eglDpy_ == EGL_NO_DISPLAY) return false;
EGLint maj = 0, min = 0;
if (!eglInitialize(eglDpy_, &maj, &min)) return false;
eglBindAPI(EGL_OPENGL_ES_API);
const EGLint cfgAttribs[] = {
EGL_SURFACE_TYPE, EGL_PBUFFER_BIT,
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL_RED_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_BLUE_SIZE, 8,
EGL_ALPHA_SIZE, 8,
EGL_DEPTH_SIZE, 16,
EGL_NONE
};
EGLConfig cfg = nullptr;
EGLint numCfg = 0;
if (!eglChooseConfig(eglDpy_, cfgAttribs, &cfg, 1, &numCfg) || numCfg < 1) {
// Fallback: config without pbuffer bit (we use an FBO anyway)
const EGLint cfgAttribs2[] = {
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL_RED_SIZE, 5,
EGL_GREEN_SIZE, 6,
EGL_BLUE_SIZE, 5,
EGL_DEPTH_SIZE, 16,
EGL_NONE
};
if (!eglChooseConfig(eglDpy_, cfgAttribs2, &cfg, 1, &numCfg) ||
numCfg < 1) {
return false;
}
}
const EGLint ctxAttribs[] = {EGL_CONTEXT_CLIENT_VERSION, 2, EGL_NONE};
eglCtx_ = eglCreateContext(eglDpy_, cfg, EGL_NO_CONTEXT, ctxAttribs);
if (eglCtx_ == EGL_NO_CONTEXT) return false;
const EGLint pbufAttribs[] = {EGL_WIDTH, 240, EGL_HEIGHT, 320, EGL_NONE};
eglSurf_ = eglCreatePbufferSurface(eglDpy_, cfg, pbufAttribs);
if (!eglMakeCurrent(eglDpy_, eglSurf_, eglSurf_, eglCtx_)) {
if (!eglMakeCurrent(eglDpy_, EGL_NO_SURFACE, EGL_NO_SURFACE, eglCtx_)) {
return false;
}
}
const char* rend = reinterpret_cast<const char*>(glGetString(GL_RENDERER));
if (rend && rend[0]) glRendererName = rend;
// Create 240x320 FBO + Depth Renderbuffer on FD304
glGenFramebuffers(1, &fbo_);
glBindFramebuffer(GL_FRAMEBUFFER, fbo_);
glGenTextures(1, &colorTex_);
glBindTexture(GL_TEXTURE_2D, colorTex_);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 240, 320, 0, GL_RGBA,
GL_UNSIGNED_BYTE, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D, colorTex_, 0);
glGenRenderbuffers(1, &depthRbo_);
glBindRenderbuffer(GL_RENDERBUFFER, depthRbo_);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, 240, 320);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
GL_RENDERBUFFER, depthRbo_);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
return false;
}
// Compile M3G GLSL ES 2.0 shader program
const char* vsSrc =
"attribute vec3 aPos;\n"
"attribute vec3 aNorm;\n"
"attribute vec4 aCol;\n"
"uniform mat4 uMVP;\n"
"varying vec4 vCol;\n"
"void main() {\n"
" gl_Position = uMVP * vec4(aPos, 1.0);\n"
" float lit = max(0.35, abs(aNorm.z) * 0.65 + 0.35);\n"
" vCol = vec4(aCol.rgb * lit, aCol.a);\n"
"}\n";
const char* fsSrc =
"precision mediump float;\n"
"varying vec4 vCol;\n"
"void main() {\n"
" gl_FragColor = vCol;\n"
"}\n";
auto compileShader = [](GLenum type, const char* src) -> GLuint {
GLuint s = glCreateShader(type);
glShaderSource(s, 1, &src, nullptr);
glCompileShader(s);
return s;
};
GLuint vs = compileShader(GL_VERTEX_SHADER, vsSrc);
GLuint fs = compileShader(GL_FRAGMENT_SHADER, fsSrc);
prog_ = glCreateProgram();
glAttachShader(prog_, vs);
glAttachShader(prog_, fs);
glBindAttribLocation(prog_, 0, "aPos");
glBindAttribLocation(prog_, 1, "aNorm");
glBindAttribLocation(prog_, 2, "aCol");
glLinkProgram(prog_);
uMvpLoc_ = glGetUniformLocation(prog_, "uMVP");
glDeleteShader(vs);
glDeleteShader(fs);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LEQUAL);
hwInitialized = true;
return true;
}
void shutdown() {
if (hwInitialized && eglDpy_ != EGL_NO_DISPLAY) {
if (prog_) glDeleteProgram(prog_);
if (depthRbo_) glDeleteRenderbuffers(1, &depthRbo_);
if (colorTex_) glDeleteTextures(1, &colorTex_);
if (fbo_) glDeleteFramebuffers(1, &fbo_);
eglMakeCurrent(eglDpy_, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
if (eglSurf_ != EGL_NO_SURFACE) eglDestroySurface(eglDpy_, eglSurf_);
if (eglCtx_ != EGL_NO_CONTEXT) eglDestroyContext(eglDpy_, eglCtx_);
eglTerminate(eglDpy_);
}
hwInitialized = false;
eglDpy_ = EGL_NO_DISPLAY;
eglCtx_ = EGL_NO_CONTEXT;
eglSurf_ = EGL_NO_SURFACE;
}
void clearTarget(NativeImageSurface* surf, uint32_t bgColorArgb,
bool clearColor, bool clearDepth) {
int w = surf ? surf->width : 240;
int h = surf ? surf->height : 320;
if (clearDepth) {
swZbuf_.assign(static_cast<size_t>(w) * h, 1.0e9f);
}
if (clearColor && surf) {
uint32_t c = bgColorArgb | 0xFF000000u;
for (int y = std::max(0, vpY); y < std::min(h, vpY + vpH); ++y) {
uint32_t* row = surf->pixels.data() + static_cast<size_t>(y) * w;
for (int x = std::max(0, vpX); x < std::min(w, vpX + vpW); ++x) {
row[x] = c;
}
}
}
if (useHardwareGl && hwInitialized) {
glBindFramebuffer(GL_FRAMEBUFFER, fbo_);
glViewport(vpX, 320 - (vpY + vpH), vpW, vpH);
GLbitfield mask = 0;
if (clearColor) {
float r = ((bgColorArgb >> 16) & 0xFFu) / 255.0f;
float g = ((bgColorArgb >> 8) & 0xFFu) / 255.0f;
float b = (bgColorArgb & 0xFFu) / 255.0f;
glClearColor(r, g, b, 1.0f);
mask |= GL_COLOR_BUFFER_BIT;
}
if (clearDepth) mask |= GL_DEPTH_BUFFER_BIT;
if (mask) glClear(mask);
}
}
void renderVertexBuffer(Jvm& vm, NativeImageSurface* surf,
uint32_t vbRef, uint32_t ibRef,
uint32_t /*appRef*/, const Mat4& modelMat) {
JObject* vbObj = vm.getObj(vbRef);
JObject* ibObj = vm.getObj(ibRef);
if (!vbObj || !vbObj->nativeData || !ibObj || !ibObj->nativeData) return;
auto* vb = static_cast<M3gVertexBufferData*>(vbObj->nativeData.get());
auto* ib = static_cast<M3gIndexBufferData*>(ibObj->nativeData.get());
JObject* posObj = vm.getObj(vb->positionsRef);
if (!posObj || !posObj->nativeData) return;
auto* posArr = static_cast<M3gVertexArrayData*>(posObj->nativeData.get());
if (posArr->numVertices <= 0 || ib->triangles.empty()) return;
M3gVertexArrayData* colArr = nullptr;
if (vb->colorsRef != 0) {
JObject* co = vm.getObj(vb->colorsRef);
if (co && co->nativeData) {
colArr = static_cast<M3gVertexArrayData*>(co->nativeData.get());
}
}
M3gVertexArrayData* normArr = nullptr;
if (vb->normalsRef != 0) {
JObject* no = vm.getObj(vb->normalsRef);
if (no && no->nativeData) {
normArr = static_cast<M3gVertexArrayData*>(no->nativeData.get());
}
}
int nVerts = posArr->numVertices;
std::vector<float> vPos(nVerts * 3);
std::vector<float> vNorm(nVerts * 3, 0.0f);
std::vector<float> vCol(nVerts * 4, 1.0f);
float defR = ((vb->defaultColor >> 16) & 0xFFu) / 255.0f;
float defG = ((vb->defaultColor >> 8) & 0xFFu) / 255.0f;
float defB = (vb->defaultColor & 0xFFu) / 255.0f;
float defA = ((vb->defaultColor >> 24) & 0xFFu) / 255.0f;
if (defA == 0.0f) defA = 1.0f;
for (int i = 0; i < nVerts; ++i) {
for (int c = 0; c < 3; ++c) {
float raw = (c < posArr->numComponents &&
static_cast<size_t>(i * posArr->numComponents + c) <
posArr->values.size())
? posArr->values[i * posArr->numComponents + c]
: 0.0f;
vPos[i * 3 + c] = raw * vb->posScale + vb->posBias[c];
}
if (normArr && static_cast<size_t>((i + 1) * normArr->numComponents) <=
normArr->values.size()) {
for (int c = 0; c < std::min(3, normArr->numComponents); ++c) {
vNorm[i * 3 + c] = normArr->values[i * normArr->numComponents + c] / 127.0f;
}
} else {
vNorm[i * 3 + 2] = 1.0f;
}
if (colArr && static_cast<size_t>((i + 1) * colArr->numComponents) <=
colArr->values.size()) {
int nc = colArr->numComponents;
auto toU8 = [](float v) -> float {
int iv = static_cast<int>(v);
if (iv < 0) iv += 256;
return std::clamp(iv, 0, 255) / 255.0f;
};
vCol[i * 4 + 0] = toU8(colArr->values[i * nc + 0]);
vCol[i * 4 + 1] = (nc >= 2) ? toU8(colArr->values[i * nc + 1]) : 1.0f;
vCol[i * 4 + 2] = (nc >= 3) ? toU8(colArr->values[i * nc + 2]) : 1.0f;
vCol[i * 4 + 3] = (nc >= 4) ? toU8(colArr->values[i * nc + 3]) : 1.0f;
} else {
vCol[i * 4 + 0] = defR;
vCol[i * 4 + 1] = defG;
vCol[i * 4 + 2] = defB;
vCol[i * 4 + 3] = defA;
}
}
Mat4 mv = Mat4::Multiply(viewMat, modelMat);
Mat4 mvp = Mat4::Multiply(projMat, mv);
if (useHardwareGl && hwInitialized) {
glBindFramebuffer(GL_FRAMEBUFFER, fbo_);
glViewport(vpX, 320 - (vpY + vpH), vpW, vpH);
glUseProgram(prog_);
glUniformMatrix4fv(uMvpLoc_, 1, GL_FALSE, mvp.m.data());
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, vPos.data());
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, vNorm.data());
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, 0, vCol.data());
glDrawElements(GL_TRIANGLES,
static_cast<GLsizei>(ib->triangles.size()),
GL_UNSIGNED_SHORT, ib->triangles.data());
return;
}
// Software depth-buffered 3D rasterizer fallback
if (!surf) return;
if (swZbuf_.size() != static_cast<size_t>(surf->width) * surf->height) {
swZbuf_.assign(static_cast<size_t>(surf->width) * surf->height, 1.0e9f);
}
struct ProjV {
float sx, sy, sz;
uint32_t col;
bool valid;
};
std::vector<ProjV> pv(nVerts);
for (int i = 0; i < nVerts; ++i) {
float cx, cy, cz, cw;
mvp.transformPoint(vPos[i * 3 + 0], vPos[i * 3 + 1], vPos[i * 3 + 2],
&cx, &cy, &cz, &cw);
if (cw <= 0.05f) {
pv[i].valid = false;
continue;
}
float invW = 1.0f / cw;
pv[i].sx = vpX + (cx * invW * 0.5f + 0.5f) * vpW;
pv[i].sy = vpY + (0.5f - cy * invW * 0.5f) * vpH;
pv[i].sz = cz * invW;
uint32_t r = static_cast<uint32_t>(std::clamp(vCol[i * 4 + 0], 0.0f, 1.0f) * 255.0f);
uint32_t g = static_cast<uint32_t>(std::clamp(vCol[i * 4 + 1], 0.0f, 1.0f) * 255.0f);
uint32_t b = static_cast<uint32_t>(std::clamp(vCol[i * 4 + 2], 0.0f, 1.0f) * 255.0f);
pv[i].col = 0xFF000000u | (r << 16) | (g << 8) | b;
pv[i].valid = true;
}
for (size_t t = 0; t + 2 < ib->triangles.size(); t += 3) {
uint16_t i0 = ib->triangles[t + 0];
uint16_t i1 = ib->triangles[t + 1];
uint16_t i2 = ib->triangles[t + 2];
if (i0 >= nVerts || i1 >= nVerts || i2 >= nVerts) continue;
const ProjV &v0 = pv[i0], &v1 = pv[i1], &v2 = pv[i2];
if (!v0.valid || !v1.valid || !v2.valid) continue;
int minX = std::max(0, static_cast<int>(std::min({v0.sx, v1.sx, v2.sx})));
int maxX = std::min(surf->width - 1,
static_cast<int>(std::max({v0.sx, v1.sx, v2.sx})));
int minY = std::max(0, static_cast<int>(std::min({v0.sy, v1.sy, v2.sy})));
int maxY = std::min(surf->height - 1,
static_cast<int>(std::max({v0.sy, v1.sy, v2.sy})));
auto edge = [](float ax, float ay, float bx, float by, float px, float py) {
return (px - ax) * (by - ay) - (py - ay) * (bx - ax);
};
float area = edge(v0.sx, v0.sy, v1.sx, v1.sy, v2.sx, v2.sy);
if (std::fabs(area) < 0.5f) continue;
float invArea = 1.0f / area;
for (int py = minY; py <= maxY; ++py) {
for (int px = minX; px <= maxX; ++px) {
float w0 = edge(v1.sx, v1.sy, v2.sx, v2.sy, px + 0.5f, py + 0.5f) * invArea;
float w1 = edge(v2.sx, v2.sy, v0.sx, v0.sy, px + 0.5f, py + 0.5f) * invArea;
float w2 = 1.0f - w0 - w1;
if (w0 >= 0.0f && w1 >= 0.0f && w2 >= 0.0f) {
float z = w0 * v0.sz + w1 * v1.sz + w2 * v2.sz;
size_t idx = static_cast<size_t>(py) * surf->width + px;
if (z < swZbuf_[idx]) {
swZbuf_[idx] = z;
surf->pixels[idx] = v0.col;
}
}
}
}
}
}
void finishTarget(NativeImageSurface* surf) {
if (!surf || !useHardwareGl || !hwInitialized) return;
glBindFramebuffer(GL_FRAMEBUFFER, fbo_);
glFinish();
std::vector<uint8_t> rgba(240 * 320 * 4);
glReadPixels(0, 0, 240, 320, GL_RGBA, GL_UNSIGNED_BYTE, rgba.data());
int copyW = std::min(240, surf->width);
int copyH = std::min(320, surf->height);
for (int y = std::max(0, vpY); y < std::min(copyH, vpY + vpH); ++y) {
int glY = 319 - y;
const uint8_t* srcRow = rgba.data() + static_cast<size_t>(glY) * 240 * 4;
uint32_t* dstRow = surf->pixels.data() + static_cast<size_t>(y) * surf->width;
for (int x = std::max(0, vpX); x < std::min(copyW, vpX + vpW); ++x) {
uint32_t r = srcRow[x * 4 + 0];
uint32_t g = srcRow[x * 4 + 1];
uint32_t b = srcRow[x * 4 + 2];
dstRow[x] = 0xFF000000u | (r << 16) | (g << 8) | b;
}
}
}
private:
EGLDisplay eglDpy_ = EGL_NO_DISPLAY;
EGLContext eglCtx_ = EGL_NO_CONTEXT;
EGLSurface eglSurf_ = EGL_NO_SURFACE;
GLuint fbo_ = 0;
GLuint colorTex_ = 0;
GLuint depthRbo_ = 0;
GLuint prog_ = 0;
GLint uMvpLoc_ = -1;
std::vector<float> swZbuf_;
};
} // namespace remedy
#endif // BANANARCHY_REMEDY_M3G_GL_HPP
File diff suppressed because it is too large. Load diff
+905
View File
@@ -0,0 +1,905 @@
// SPDX-License-Identifier: GPL-2.0-only
// ReMEdy J2ME (MIDP 2.0 / CLDC 1.1) Emulator for Bananarchy Linux
// Part 1: ZIP/JAR Reader, JAD/MANIFEST.MF Parser, and RMS (RecordStore) Engine
#ifndef BANANARCHY_REMEDY_ZIP_RMS_HPP
#define BANANARCHY_REMEDY_ZIP_RMS_HPP
#include <algorithm>
#include <cctype>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <curl/curl.h>
#include <dirent.h>
#include <fstream>
#include <map>
#include <sstream>
#include <string>
#include <sys/stat.h>
#include <unistd.h>
#include <unordered_map>
#include <vector>
#include <zlib.h>
namespace remedy {
inline int64_t nowMs() {
struct timespec ts {};
clock_gettime(CLOCK_MONOTONIC, &ts);
return static_cast<int64_t>(ts.tv_sec) * 1000LL + ts.tv_nsec / 1000000LL;
}
inline int64_t wallTimeMs() {
struct timespec ts {};
clock_gettime(CLOCK_REALTIME, &ts);
return static_cast<int64_t>(ts.tv_sec) * 1000LL + ts.tv_nsec / 1000000LL;
}
inline std::string trimStr(const std::string& s) {
size_t b = 0;
while (b < s.size() &&
(s[b] == ' ' || s[b] == '\t' || s[b] == '\r' || s[b] == '\n')) {
++b;
}
size_t e = s.size();
while (e > b &&
(s[e - 1] == ' ' || s[e - 1] == '\t' || s[e - 1] == '\r' ||
s[e - 1] == '\n')) {
--e;
}
return s.substr(b, e - b);
}
inline std::string toLowerStr(std::string s) {
for (char& c : s) {
c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
}
return s;
}
inline void ensureDir(const std::string& path) {
std::string cur;
for (size_t i = 0; i < path.size(); ++i) {
cur.push_back(path[i]);
if (path[i] == '/' && cur.size() > 1) {
::mkdir(cur.c_str(), 0755);
}
}
if (!cur.empty()) {
::mkdir(cur.c_str(), 0755);
}
}
inline std::string getHomeDir() {
const char* h = std::getenv("HOME");
return (h && h[0]) ? h : "/home/user";
}
inline std::string getDataRootDir() {
const char* xdg = std::getenv("XDG_DATA_HOME");
std::string base = (xdg && xdg[0]) ? xdg : (getHomeDir() + "/.local/share");
return base + "/sxmo/remedy";
}
inline std::string getConfigPath() {
const char* xdg = std::getenv("XDG_CONFIG_HOME");
std::string base = (xdg && xdg[0]) ? xdg : (getHomeDir() + "/.config");
return base + "/sxmo/remedy.cfg";
}
inline std::string sanitizePathToken(const std::string& s) {
std::string out;
out.reserve(s.size());
for (unsigned char c : s) {
if (std::isalnum(c) || c == '_' || c == '-' || c == '.') {
out.push_back(static_cast<char>(c));
} else {
out.push_back('_');
}
}
if (out.empty()) out = "default";
return out;
}
inline std::string dirnameOf(const std::string& p) {
size_t sl = p.rfind('/');
if (sl == std::string::npos) return ".";
if (sl == 0) return "/";
return p.substr(0, sl);
}
inline std::string basenameOf(const std::string& p) {
size_t sl = p.rfind('/');
return (sl == std::string::npos) ? p : p.substr(sl + 1);
}
inline std::string stripExtension(const std::string& p) {
std::string b = basenameOf(p);
size_t dot = b.rfind('.');
if (dot != std::string::npos && dot > 0) {
return b.substr(0, dot);
}
return b;
}
inline std::string getExtLower(const std::string& p) {
size_t dot = p.rfind('.');
if (dot == std::string::npos || dot + 1 >= p.size()) return "";
return toLowerStr(p.substr(dot + 1));
}
inline uint16_t readLe16(const uint8_t* p) {
return static_cast<uint16_t>(p[0]) | (static_cast<uint16_t>(p[1]) << 8);
}
inline uint32_t readLe32(const uint8_t* p) {
return static_cast<uint32_t>(p[0]) |
(static_cast<uint32_t>(p[1]) << 8) |
(static_cast<uint32_t>(p[2]) << 16) |
(static_cast<uint32_t>(p[3]) << 24);
}
// ---------------------------------------------------------------------------
// ZIP / JAR Archive Reader
// ---------------------------------------------------------------------------
struct ZipEntryMeta {
std::string name;
uint16_t method = 0;
uint32_t compSize = 0;
uint32_t uncompSize = 0;
uint32_t localHeaderOffset = 0;
};
class ZipArchive {
public:
bool openFile(const std::string& path) {
entries_.clear();
exactMap_.clear();
lowerMap_.clear();
std::ifstream in(path, std::ios::binary | std::ios::ate);
if (!in.is_open()) return false;
std::streamsize sz = in.tellg();
if (sz <= 0 || sz > 64 * 1024 * 1024) return false;
in.seekg(0, std::ios::beg);
raw_.resize(static_cast<size_t>(sz));
if (!in.read(reinterpret_cast<char*>(raw_.data()), sz)) return false;
return parseArchive();
}
bool isOpen() const { return !raw_.empty(); }
const std::vector<ZipEntryMeta>& entries() const { return entries_; }
static std::string normalizeEntryPath(const std::string& path) {
std::string clean;
clean.reserve(path.size());
for (char c : path) {
if (c == '\\') c = '/';
clean.push_back(c);
}
while (!clean.empty() && clean.front() == '/') {
clean.erase(clean.begin());
}
// Resolve "./" and "../" segments
std::vector<std::string> parts;
std::stringstream ss(clean);
std::string seg;
while (std::getline(ss, seg, '/')) {
if (seg.empty() || seg == ".") continue;
if (seg == "..") {
if (!parts.empty()) parts.pop_back();
} else {
parts.push_back(seg);
}
}
std::string out;
for (size_t i = 0; i < parts.size(); ++i) {
if (i > 0) out.push_back('/');
out += parts[i];
}
return out;
}
bool hasEntry(const std::string& name) const {
std::string norm = normalizeEntryPath(name);
if (exactMap_.find(norm) != exactMap_.end()) return true;
return lowerMap_.find(toLowerStr(norm)) != lowerMap_.end();
}
bool extractEntry(const std::string& name, std::vector<uint8_t>* out) const {
if (!out) return false;
out->clear();
std::string norm = normalizeEntryPath(name);
size_t idx = 0;
auto it = exactMap_.find(norm);
if (it != exactMap_.end()) {
idx = it->second;
} else {
auto lit = lowerMap_.find(toLowerStr(norm));
if (lit == lowerMap_.end()) return false;
idx = lit->second;
}
return extractByIndex(idx, out);
}
bool extractByIndex(size_t idx, std::vector<uint8_t>* out) const {
if (!out || idx >= entries_.size()) return false;
const ZipEntryMeta& e = entries_[idx];
if (e.localHeaderOffset + 30 > raw_.size()) return false;
const uint8_t* lh = raw_.data() + e.localHeaderOffset;
if (readLe32(lh) != 0x04034b50u) return false;
uint16_t fnLen = readLe16(lh + 26);
uint16_t extraLen = readLe16(lh + 28);
size_t dataOff = e.localHeaderOffset + 30u + fnLen + extraLen;
if (dataOff + e.compSize > raw_.size()) return false;
const uint8_t* compPtr = raw_.data() + dataOff;
if (e.method == 0) {
out->assign(compPtr, compPtr + e.compSize);
return true;
} else if (e.method == 8) {
out->resize(e.uncompSize > 0 ? e.uncompSize : (e.compSize * 4 + 256));
z_stream strm {};
strm.next_in = const_cast<Bytef*>(compPtr);
strm.avail_in = e.compSize;
if (inflateInit2(&strm, -MAX_WBITS) != Z_OK) return false;
size_t totalOut = 0;
int ret = Z_OK;
while (ret == Z_OK) {
if (totalOut >= out->size()) {
out->resize(out->size() * 2 + 4096);
}
strm.next_out = out->data() + totalOut;
strm.avail_out = static_cast<uInt>(out->size() - totalOut);
ret = inflate(&strm, Z_NO_FLUSH);
totalOut = strm.total_out;
if (ret == Z_STREAM_END) break;
if (ret != Z_OK && ret != Z_BUF_ERROR) {
inflateEnd(&strm);
return false;
}
if (strm.avail_in == 0 && ret == Z_BUF_ERROR) break;
}
inflateEnd(&strm);
out->resize(totalOut);
return true;
}
return false;
}
private:
std::vector<uint8_t> raw_;
std::vector<ZipEntryMeta> entries_;
std::unordered_map<std::string, size_t> exactMap_;
std::unordered_map<std::string, size_t> lowerMap_;
void registerEntry(const ZipEntryMeta& meta) {
size_t idx = entries_.size();
entries_.push_back(meta);
exactMap_[meta.name] = idx;
lowerMap_[toLowerStr(meta.name)] = idx;
}
bool parseArchive() {
if (raw_.size() < 22) return false;
// Search backwards for End of Central Directory (0x06054b50)
size_t minOff = (raw_.size() > 65557) ? (raw_.size() - 65557) : 0;
ssize_t eocdOff = -1;
for (ssize_t i = static_cast<ssize_t>(raw_.size()) - 22;
i >= static_cast<ssize_t>(minOff); --i) {
if (readLe32(raw_.data() + i) == 0x06054b50u) {
eocdOff = i;
break;
}
}
if (eocdOff >= 0) {
const uint8_t* eocd = raw_.data() + eocdOff;
uint16_t numEntries = readLe16(eocd + 10);
uint32_t cdSize = readLe32(eocd + 12);
uint32_t cdOff = readLe32(eocd + 16);
if (static_cast<size_t>(cdOff) + cdSize <= raw_.size()) {
size_t pos = cdOff;
for (uint16_t i = 0; i < numEntries && pos + 46 <= raw_.size(); ++i) {
const uint8_t* cfh = raw_.data() + pos;
if (readLe32(cfh) != 0x02014b50u) break;
uint16_t method = readLe16(cfh + 10);
uint32_t compSz = readLe32(cfh + 20);
uint32_t uncompSz = readLe32(cfh + 24);
uint16_t fnLen = readLe16(cfh + 28);
uint16_t extraLen = readLe16(cfh + 30);
uint16_t commentLen = readLe16(cfh + 32);
uint32_t lhOff = readLe32(cfh + 42);
if (pos + 46 + fnLen > raw_.size()) break;
std::string name(reinterpret_cast<const char*>(cfh + 46), fnLen);
name = normalizeEntryPath(name);
if (!name.empty()) {
ZipEntryMeta m;
m.name = name;
m.method = method;
m.compSize = compSz;
m.uncompSize = uncompSz;
m.localHeaderOffset = lhOff;
registerEntry(m);
}
pos += 46u + fnLen + extraLen + commentLen;
}
if (!entries_.empty()) return true;
}
}
// Fallback sequential scan of local file headers
size_t pos = 0;
while (pos + 30 <= raw_.size()) {
const uint8_t* lh = raw_.data() + pos;
if (readLe32(lh) != 0x04034b50u) break;
uint16_t method = readLe16(lh + 8);
uint32_t compSz = readLe32(lh + 18);
uint32_t uncompSz = readLe32(lh + 22);
uint16_t fnLen = readLe16(lh + 26);
uint16_t extraLen = readLe16(lh + 28);
if (pos + 30u + fnLen + extraLen + compSz > raw_.size()) break;
std::string name(reinterpret_cast<const char*>(lh + 30), fnLen);
name = normalizeEntryPath(name);
if (!name.empty()) {
ZipEntryMeta m;
m.name = name;
m.method = method;
m.compSize = compSz;
m.uncompSize = uncompSz;
m.localHeaderOffset = static_cast<uint32_t>(pos);
registerEntry(m);
}
pos += 30u + fnLen + extraLen + compSz;
}
return !entries_.empty();
}
};
// ---------------------------------------------------------------------------
// Manifest & JAD Parser + Suite Metadata
// ---------------------------------------------------------------------------
struct MidletEntry {
int index = 1;
std::string title;
std::string iconPath;
std::string mainClass;
};
struct MidletSuiteInfo {
std::string jarPath;
std::string jadPath;
std::string suiteName;
std::string vendor;
std::string version;
std::string description;
std::string jarUrl;
std::vector<MidletEntry> midlets;
std::unordered_map<std::string, std::string> properties;
std::string getProperty(const std::string& key) const {
auto it = properties.find(key);
if (it != properties.end()) return it->second;
return "";
}
std::string suiteStorageKey() const {
std::string base = suiteName.empty() ? stripExtension(jarPath) : suiteName;
if (!vendor.empty()) base += "_" + vendor;
return sanitizePathToken(base);
}
};
inline void parseManifestText(
const std::string& text,
std::unordered_map<std::string, std::string>* outProps) {
if (!outProps) return;
std::istringstream ss(text);
std::string rawLine;
std::string lastKey;
while (std::getline(ss, rawLine)) {
if (!rawLine.empty() && rawLine.back() == '\r') {
rawLine.pop_back();
}
// Strip UTF-8 BOM if present
if (rawLine.size() >= 3 &&
static_cast<unsigned char>(rawLine[0]) == 0xEF &&
static_cast<unsigned char>(rawLine[1]) == 0xBB &&
static_cast<unsigned char>(rawLine[2]) == 0xBF) {
rawLine.erase(0, 3);
}
if (rawLine.empty()) {
lastKey.clear();
continue;
}
if (rawLine[0] == ' ' && !lastKey.empty()) {
(*outProps)[lastKey] += rawLine.substr(1);
continue;
}
size_t colon = rawLine.find(':');
if (colon == std::string::npos) continue;
std::string k = trimStr(rawLine.substr(0, colon));
std::string v = trimStr(rawLine.substr(colon + 1));
if (!k.empty()) {
(*outProps)[k] = v;
lastKey = k;
}
}
}
inline size_t curlWriteVector(void* ptr, size_t size, size_t nmemb,
void* userdata) {
size_t total = size * nmemb;
auto* vec = static_cast<std::vector<uint8_t>*>(userdata);
const auto* bytes = static_cast<const uint8_t*>(ptr);
vec->insert(vec->end(), bytes, bytes + total);
return total;
}
inline bool downloadUrlToFile(const std::string& url,
const std::string& dstPath) {
CURL* curl = curl_easy_init();
if (!curl) return false;
std::vector<uint8_t> body;
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 20L);
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
curl_easy_setopt(curl, CURLOPT_USERAGENT,
"Nokia8110-4G/2.0 (Bananarchy; ReMEdy/1.0) Profile/MIDP-2.0 Configuration/CLDC-1.1");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curlWriteVector);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &body);
CURLcode res = curl_easy_perform(curl);
long code = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code);
curl_easy_cleanup(curl);
if (res != CURLE_OK || code < 200 || code >= 400 || body.size() < 22) {
return false;
}
ensureDir(dirnameOf(dstPath));
std::ofstream out(dstPath, std::ios::binary | std::ios::trunc);
if (!out.is_open()) return false;
out.write(reinterpret_cast<const char*>(body.data()),
static_cast<std::streamsize>(body.size()));
return out.good();
}
inline void extractMidletEntriesFromProps(MidletSuiteInfo* info) {
if (!info) return;
info->midlets.clear();
for (int i = 1; i <= 32; ++i) {
std::string key = "MIDlet-" + std::to_string(i);
auto it = info->properties.find(key);
if (it == info->properties.end()) continue;
const std::string& val = it->second;
std::vector<std::string> parts;
std::stringstream ss(val);
std::string seg;
while (std::getline(ss, seg, ',')) {
parts.push_back(trimStr(seg));
}
if (parts.size() >= 3 && !parts[2].empty()) {
MidletEntry me;
me.index = i;
me.title = parts[0].empty() ? parts[2] : parts[0];
me.iconPath = parts[1];
me.mainClass = parts[2];
for (char& c : me.mainClass) {
if (c == '.') c = '/';
}
info->midlets.push_back(me);
} else if (parts.size() == 1 && !parts[0].empty()) {
MidletEntry me;
me.index = i;
me.title = parts[0];
me.mainClass = parts[0];
for (char& c : me.mainClass) {
if (c == '.') c = '/';
}
info->midlets.push_back(me);
}
}
info->suiteName = info->getProperty("MIDlet-Name");
info->vendor = info->getProperty("MIDlet-Vendor");
info->version = info->getProperty("MIDlet-Version");
info->description = info->getProperty("MIDlet-Description");
info->jarUrl = info->getProperty("MIDlet-Jar-URL");
}
inline bool loadSuiteFromJarOrJad(const std::string& inputPath,
ZipArchive* outJar,
MidletSuiteInfo* outInfo,
std::string* outError = nullptr) {
if (!outJar || !outInfo) return false;
*outInfo = MidletSuiteInfo{};
std::string ext = getExtLower(inputPath);
std::unordered_map<std::string, std::string> jadProps;
std::string resolvedJarPath = inputPath;
if (ext == "jad") {
outInfo->jadPath = inputPath;
std::ifstream in(inputPath);
if (!in.is_open()) {
if (outError) *outError = "Cannot open JAD file";
return false;
}
std::ostringstream ss;
ss << in.rdbuf();
parseManifestText(ss.str(), &jadProps);
std::string dir = dirnameOf(inputPath);
std::string baseNoExt = stripExtension(inputPath);
std::string siblingJar = dir + "/" + baseNoExt + ".jar";
std::string siblingJarUpper = dir + "/" + baseNoExt + ".JAR";
std::string jarUrl = jadProps["MIDlet-Jar-URL"];
struct stat st {};
if (::stat(siblingJar.c_str(), &st) == 0 && S_ISREG(st.st_mode)) {
resolvedJarPath = siblingJar;
} else if (::stat(siblingJarUpper.c_str(), &st) == 0 &&
S_ISREG(st.st_mode)) {
resolvedJarPath = siblingJarUpper;
} else if (!jarUrl.empty()) {
if (jarUrl.rfind("http://", 0) == 0 || jarUrl.rfind("https://", 0) == 0) {
std::string cacheJar = getDataRootDir() + "/cache/" +
sanitizePathToken(baseNoExt) + ".jar";
if (::stat(cacheJar.c_str(), &st) != 0 || st.st_size < 22) {
if (!downloadUrlToFile(jarUrl, cacheJar)) {
if (outError) *outError = "Failed to download JAR from JAD URL";
return false;
}
}
resolvedJarPath = cacheJar;
} else {
std::string relJar = dir + "/" + basenameOf(jarUrl);
if (::stat(relJar.c_str(), &st) == 0 && S_ISREG(st.st_mode)) {
resolvedJarPath = relJar;
} else if (::stat(jarUrl.c_str(), &st) == 0 && S_ISREG(st.st_mode)) {
resolvedJarPath = jarUrl;
}
}
}
} else {
// Check if a sibling .jad exists alongside the .jar to merge properties
std::string dir = dirnameOf(inputPath);
std::string baseNoExt = stripExtension(inputPath);
std::string siblingJad = dir + "/" + baseNoExt + ".jad";
struct stat st {};
if (::stat(siblingJad.c_str(), &st) == 0 && S_ISREG(st.st_mode)) {
outInfo->jadPath = siblingJad;
std::ifstream in(siblingJad);
if (in.is_open()) {
std::ostringstream ss;
ss << in.rdbuf();
parseManifestText(ss.str(), &jadProps);
}
}
}
outInfo->jarPath = resolvedJarPath;
if (!outJar->openFile(resolvedJarPath)) {
if (outError) *outError = "Invalid or missing JAR archive";
return false;
}
std::vector<uint8_t> mfBytes;
if (outJar->extractEntry("META-INF/MANIFEST.MF", &mfBytes)) {
std::string mfText(reinterpret_cast<const char*>(mfBytes.data()),
mfBytes.size());
parseManifestText(mfText, &outInfo->properties);
}
// JAD properties override/supplement MANIFEST.MF properties
for (const auto& kv : jadProps) {
outInfo->properties[kv.first] = kv.second;
}
extractMidletEntriesFromProps(outInfo);
if (outInfo->suiteName.empty()) {
outInfo->suiteName = stripExtension(resolvedJarPath);
}
if (outInfo->vendor.empty()) {
outInfo->vendor = "J2ME MIDlet";
}
if (outInfo->version.empty()) {
outInfo->version = "1.0";
}
return true;
}
// Fast metadata peek for the ROM/JAR Browser
inline bool peekJarOrJadSummary(const std::string& path,
std::string* outTitle,
std::string* outSubtitle) {
std::string ext = getExtLower(path);
std::unordered_map<std::string, std::string> props;
if (ext == "jad") {
std::ifstream in(path);
if (!in.is_open()) return false;
std::ostringstream ss;
ss << in.rdbuf();
parseManifestText(ss.str(), &props);
} else if (ext == "jar") {
ZipArchive za;
if (!za.openFile(path)) return false;
std::vector<uint8_t> mf;
if (za.extractEntry("META-INF/MANIFEST.MF", &mf)) {
parseManifestText(
std::string(reinterpret_cast<const char*>(mf.data()), mf.size()),
&props);
}
} else {
return false;
}
std::string name = props["MIDlet-Name"];
std::string vendor = props["MIDlet-Vendor"];
std::string ver = props["MIDlet-Version"];
if (name.empty()) {
auto it = props.find("MIDlet-1");
if (it != props.end()) {
size_t comma = it->second.find(',');
name = trimStr(comma == std::string::npos ? it->second
: it->second.substr(0, comma));
}
}
if (outTitle) *outTitle = name.empty() ? stripExtension(path) : name;
if (outSubtitle) {
std::string sub;
if (!vendor.empty()) sub = vendor;
if (!ver.empty()) {
if (!sub.empty()) sub += " v";
else sub = "v";
sub += ver;
}
*outSubtitle = sub;
}
return true;
}
// ---------------------------------------------------------------------------
// RMS (javax.microedition.rms.RecordStore) Persistent Storage Engine
// ---------------------------------------------------------------------------
struct RmsStoreData {
std::string name;
int32_t version = 1;
int32_t nextRecordId = 1;
int64_t lastModified = 0;
int32_t openCount = 0;
std::map<int32_t, std::vector<uint8_t>> records;
};
class RmsManager {
public:
void setSuiteKey(const std::string& key) {
suiteKey_ = sanitizePathToken(key);
stores_.clear();
}
std::string suiteRmsDir() const {
return getDataRootDir() + "/rms/" +
(suiteKey_.empty() ? "default" : suiteKey_);
}
std::string storeFilePath(const std::string& storeName) const {
return suiteRmsDir() + "/" + sanitizePathToken(storeName) + ".rms";
}
RmsStoreData* openStore(const std::string& storeName, bool createIfNecessary) {
auto it = stores_.find(storeName);
if (it != stores_.end()) {
it->second.openCount++;
return &it->second;
}
std::string path = storeFilePath(storeName);
struct stat st {};
if (::stat(path.c_str(), &st) == 0 && S_ISREG(st.st_mode)) {
RmsStoreData data;
data.name = storeName;
if (loadStoreFromDisk(path, &data)) {
data.openCount = 1;
stores_[storeName] = std::move(data);
return &stores_[storeName];
}
}
if (!createIfNecessary) return nullptr;
RmsStoreData data;
data.name = storeName;
data.version = 1;
data.nextRecordId = 1;
data.lastModified = wallTimeMs();
data.openCount = 1;
saveStoreToDisk(path, data);
stores_[storeName] = std::move(data);
return &stores_[storeName];
}
bool closeStore(const std::string& storeName) {
auto it = stores_.find(storeName);
if (it == stores_.end()) return false;
saveStoreToDisk(storeFilePath(storeName), it->second);
if (it->second.openCount > 0) {
it->second.openCount--;
}
return true;
}
bool deleteStore(const std::string& storeName) {
stores_.erase(storeName);
std::string path = storeFilePath(storeName);
return ::unlink(path.c_str()) == 0;
}
std::vector<std::string> listStores() const {
std::vector<std::string> names;
std::string dir = suiteRmsDir();
DIR* d = ::opendir(dir.c_str());
if (!d) return names;
struct dirent* de = nullptr;
while ((de = ::readdir(d)) != nullptr) {
std::string fn = de->d_name;
if (fn.size() > 4 && fn.substr(fn.size() - 4) == ".rms") {
names.push_back(fn.substr(0, fn.size() - 4));
}
}
::closedir(d);
std::sort(names.begin(), names.end());
return names;
}
int32_t addRecord(RmsStoreData* s, const uint8_t* bytes, size_t len) {
if (!s) return -1;
int32_t id = s->nextRecordId++;
if (bytes && len > 0) {
s->records[id].assign(bytes, bytes + len);
} else {
s->records[id].clear();
}
s->version++;
s->lastModified = wallTimeMs();
saveStoreToDisk(storeFilePath(s->name), *s);
return id;
}
bool setRecord(RmsStoreData* s, int32_t id, const uint8_t* bytes, size_t len) {
if (!s || id <= 0) return false;
auto it = s->records.find(id);
if (it == s->records.end()) {
// Some MIDlets call setRecord(1, ...) directly after ensuring record 1
if (id >= s->nextRecordId) s->nextRecordId = id + 1;
}
if (bytes && len > 0) {
s->records[id].assign(bytes, bytes + len);
} else {
s->records[id].clear();
}
s->version++;
s->lastModified = wallTimeMs();
saveStoreToDisk(storeFilePath(s->name), *s);
return true;
}
bool getRecord(RmsStoreData* s, int32_t id, std::vector<uint8_t>* out) const {
if (!s) return false;
auto it = s->records.find(id);
if (it == s->records.end()) return false;
if (out) *out = it->second;
return true;
}
int32_t getRecordSize(RmsStoreData* s, int32_t id) const {
if (!s) return -1;
auto it = s->records.find(id);
if (it == s->records.end()) return -1;
return static_cast<int32_t>(it->second.size());
}
bool deleteRecord(RmsStoreData* s, int32_t id) {
if (!s) return false;
auto it = s->records.find(id);
if (it == s->records.end()) return false;
s->records.erase(it);
s->version++;
s->lastModified = wallTimeMs();
saveStoreToDisk(storeFilePath(s->name), *s);
return true;
}
int32_t getSize(const RmsStoreData* s) const {
if (!s) return 0;
int32_t total = 32;
for (const auto& kv : s->records) {
total += 8 + static_cast<int32_t>(kv.second.size());
}
return total;
}
void flushAll() {
for (const auto& kv : stores_) {
saveStoreToDisk(storeFilePath(kv.first), kv.second);
}
}
int clearAllSuiteStores() {
stores_.clear();
std::string dir = suiteRmsDir();
DIR* d = ::opendir(dir.c_str());
if (!d) return 0;
int removed = 0;
struct dirent* de = nullptr;
while ((de = ::readdir(d)) != nullptr) {
std::string fn = de->d_name;
if (fn == "." || fn == "..") continue;
std::string full = dir + "/" + fn;
if (::unlink(full.c_str()) == 0) ++removed;
}
::closedir(d);
return removed;
}
private:
std::string suiteKey_ = "default";
std::unordered_map<std::string, RmsStoreData> stores_;
static bool loadStoreFromDisk(const std::string& path, RmsStoreData* out) {
std::ifstream in(path, std::ios::binary);
if (!in.is_open() || !out) return false;
char magic[4] = {};
if (!in.read(magic, 4) || std::memcmp(magic, "RRMS", 4) != 0) return false;
uint32_t count = 0;
in.read(reinterpret_cast<char*>(&out->version), sizeof(int32_t));
in.read(reinterpret_cast<char*>(&out->nextRecordId), sizeof(int32_t));
in.read(reinterpret_cast<char*>(&out->lastModified), sizeof(int64_t));
in.read(reinterpret_cast<char*>(&count), sizeof(uint32_t));
if (!in.good() || count > 65536) return false;
out->records.clear();
for (uint32_t i = 0; i < count; ++i) {
int32_t recId = 0;
uint32_t recLen = 0;
if (!in.read(reinterpret_cast<char*>(&recId), sizeof(int32_t))) break;
if (!in.read(reinterpret_cast<char*>(&recLen), sizeof(uint32_t))) break;
if (recLen > 16 * 1024 * 1024) break;
std::vector<uint8_t> buf(recLen);
if (recLen > 0 &&
!in.read(reinterpret_cast<char*>(buf.data()), recLen)) {
break;
}
out->records[recId] = std::move(buf);
if (recId >= out->nextRecordId) {
out->nextRecordId = recId + 1;
}
}
return true;
}
static bool saveStoreToDisk(const std::string& path,
const RmsStoreData& data) {
ensureDir(dirnameOf(path));
std::ofstream out(path, std::ios::binary | std::ios::trunc);
if (!out.is_open()) return false;
out.write("RRMS", 4);
uint32_t count = static_cast<uint32_t>(data.records.size());
out.write(reinterpret_cast<const char*>(&data.version), sizeof(int32_t));
out.write(reinterpret_cast<const char*>(&data.nextRecordId),
sizeof(int32_t));
out.write(reinterpret_cast<const char*>(&data.lastModified),
sizeof(int64_t));
out.write(reinterpret_cast<const char*>(&count), sizeof(uint32_t));
for (const auto& kv : data.records) {
int32_t recId = kv.first;
uint32_t recLen = static_cast<uint32_t>(kv.second.size());
out.write(reinterpret_cast<const char*>(&recId), sizeof(int32_t));
out.write(reinterpret_cast<const char*>(&recLen), sizeof(uint32_t));
if (recLen > 0) {
out.write(reinterpret_cast<const char*>(kv.second.data()), recLen);
}
}
return out.good();
}
};
} // namespace remedy
#endif // BANANARCHY_REMEDY_ZIP_RMS_HPP
+10
View File
@@ -2091,6 +2091,8 @@ add_parsed_choice_line(const char *line)
return;
if (items[i].text && strstr(label, "Bantam") && strstr(items[i].text, "Bantam"))
return;
if (items[i].text && strstr(label, "ReMEdy") && strstr(items[i].text, "ReMEdy"))
return;
}
int loop = (strchr(loop_str, '1') != NULL) ? 1 : 0;
if (strncmp(cmd, "sxmo_appmenu.sh ", 16) == 0) {
@@ -2433,6 +2435,10 @@ open_builtin_menu(const char *menu_name, int keep_idx)
snprintf(label, sizeof(label), "%s Bantam", ICON_TRM);
add_menu_item(label, "cd \"$HOME\" && sxmo_terminal.sh bantam", 0);
}
if (access("/usr/bin/remedy", X_OK) == 0) {
snprintf(label, sizeof(label), "%s ReMEdy (J2ME)", ICON_GAM);
add_menu_item(label, "remedy", 0);
}
load_cache_or_hook("sxmo_apps.cache", "sxmo_hook_apps.sh");
snprintf(label, sizeof(label), "%s Themes", ICON_THM);
int has_themes = 0;
@@ -2469,6 +2475,10 @@ open_builtin_menu(const char *menu_name, int keep_idx)
snprintf(label, sizeof(label), "%s Game Boy (Gambatte)", ICON_GAM);
add_menu_item(label, "gambatte", 0);
}
if (access("/usr/bin/remedy", X_OK) == 0) {
snprintf(label, sizeof(label), "%s ReMEdy (J2ME)", ICON_GAM);
add_menu_item(label, "remedy", 0);
}
const char *rdir = getenv("XDG_RUNTIME_DIR");
char gcache[256];
snprintf(gcache, sizeof(gcache), "%s/sxmo_games.cache", (rdir && rdir[0]) ? rdir : "/run/user/10000");