diff --git a/CHANGELOG.md b/CHANGELOG.md index 10f428c..631cd3a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,9 +34,11 @@ Release versions follow the `
` format (where `2026` is `a`, - Locks the UI theme and wallpaper exclusively to `NordFrost.xth` and `/usr/share/wallpapers/nordic-peaks.png` inside `xthemes` and `xwallpapers`. - Spoofs `*#06#` IMEI queries in `xdialer` (`dialer.so`) with session-persistent Luhn-valid random IMEIs (`/tmp/bananarchy_duress_imei`) generated from the device's real 8-digit TAC prefix (`/tmp/bananarchy_real_tac`) plus random 6-digit serial numbers and recomputed Luhn check digits. - Keeps subsequent lock/unlock cycles during the duress session in duress mode whether the user re-enters the duress passcode or the regular passcode, restoring the normal `/home/user` profile automatically on reboot or poweroff. -- **Bluetooth OBEX file transfer (`bananarchy-bt-obex`, `xnetworks`, and `xfiles`)**: - - Added `/usr/bin/bananarchy-bt-obex` (`daemon|stop|status|send|devices`) wrapping BlueZ `obexpushd` / `obexd` and `obexftp` / `bt-obex` so enabling Bluetooth (`sxmo_bluetoothtoggle.sh on` or `xnetworks`) automatically starts an OBEX Object Push receiver saving incoming files to `~/Downloads/` with toast and sound notifications. - - Added a live **OBEX File Receiver** status widget (and `#` shortcut to open `~/Downloads/` in `xfiles`) to the `3:Bluetooth` tab of `xnetworks`, and added **Send via Bluetooth** with an interactive device-picker modal to **file manager (`xfiles`)**. +- **Bluetooth audio (`A2DP`, `HSP/HFP`), HID peripherals (keyboards, mice, gamepads), discoverability & alias settings, active connection badges, and OBEX file transfer (`bananarchy-bt-obex`, `xnetworks`, `xdrawer`, `xfiles`)**: + - Configured BlueZ (`/etc/bluetooth/main.conf`, `/etc/bluetooth/input.conf`) and WirePlumber (`50-bluetooth.conf`) with full **A2DP** (`a2dp_sink`, `a2dp_source` with `sbc_xq`, `aac`, `ldac`, `aptx`, `aptx_hd`), **HSP/HFP** (`hsp_hs`, `hsp_ag`, `hfp_hf`, `hfp_ag` with `mSBC` wideband speech and hardware volume), and **HID / BLE HOGP** (`uhid`, `hidp`, `uinput`, `rfcomm`, `bnep`, `xpad`) profile support, and added `Bluetooth` as a selectable audio output/input route in `sxmo_audio.sh`, `xdrawer`, and `dmenu` Audio menu (plus automatic PipeWire `"default"` ALSA routing in `gambatte` and `remedy` when Bluetooth audio is active). + - Added **Discoverable** (`ON (Visible)` / `OFF (Hidden)`, persisted in `~/.config/sxmo/bt_discoverable`) and **Bluetooth Device Name** (`Name: [Edit]` with a multi-tap modal editor persisted in `~/.config/sxmo/bt_name` and applied via `bluetoothctl system-alias` independently of the system hostname) rows to the `3:Bluetooth` tab of `xnetworks`, alongside active connection count headers (`Bluetooth: ON (N Active)`), pinned active device cards with live profile and battery badges (`[ACTIVE: A2DP]`, `[ACTIVE: HSP/HFP]`, `[ACTIVE: HID Gamepad]`, `[ACTIVE: HID Keyboard]`, `[ACTIVE: HID Mouse]`), and a **Switch Audio (A2DP / HSP-HFP)** action. + - Added an automatic `/dev/uinput` gamepad-to-keypad bridge (`Bananarchy BT Gamepad Bridge`) inside `/usr/bin/bananarchy-bt-obex` so Bluetooth/USB gamepads (`D-Pad` / `Left Stick` -> `Up`/`Down`/`Left`/`Right`, `South/A` -> `Enter`, `East/B` -> `8`, `West/X` -> `5`, `North/Y` -> `6`, `Start` -> `2`, `Select` -> `3`, `L1`/`R1` -> `Left`/`Right softkey`, `L2`/`R2` -> `*`/`0`, `Mode` -> `Escape`) control all NeoUI apps and games (`snake`, `tetris`, `scoundrel`, `gambatte`, `remedy`) out of the box, and added dynamic `XFixes` cursor visibility in `dwm` (and `ButtonPress` handling in `dwm` and `libneoui.so`) so connecting a Bluetooth mouse shows the cursor on movement/click and hides it automatically on keypad use. + - Added `/usr/bin/bananarchy-bt-obex` (`daemon|stop|status|send|devices`) wrapping BlueZ `obexpushd` / `obexd` and `obexftp` / `bt-obex` so enabling Bluetooth (`sxmo_bluetoothtoggle.sh on` or `xnetworks`) automatically starts an OBEX Object Push receiver saving incoming files to `~/Downloads/` with toast and sound notifications, plus a live **OBEX File Receiver** status widget in `xnetworks` and **Send via Bluetooth** in `xfiles`. - **Native Scoundrel (`scoundrel`) roguelike solitaire card game**: - Built a native `240x320` C++20 X11/NeoUI implementation of the Zach Gage / Kurt Bieg roguelike solitaire dungeon crawler (`src/games/scoundrel.cpp` -> `/usr/bin/scoundrel`, based on Luxferre's C89/GB ports), featuring custom graphical playing cards, suit icons, health bar, equipped weapon and max-monster-level display, combat choice modal (`[1] Weapon` vs `[2] Barehanded`), rules/help and pause modals, direct `neoui_poll_event()` softkey and keypad controls (`1`–`4` or `D-Pad` + `5`/`OK` to play a room card, `Left softkey` or `*` to flee the room, `#` for rules, `Right softkey` or `0` for menu, and dual-softkey `xdrawer` handoff), and persistent stats in `~/.local/share/scoundrel_scores.txt`. - **Dynamic NeoUI theme synchronization for `dunst` notifications (`bananarchy-sync-dunst-theme`)**: @@ -58,12 +60,15 @@ Release versions follow the `
` format (where `2026` is `a`, - **Battery and idle power optimizations**: - Added `msm8905_cam_hw_deinit()` to the rear camera kernel driver (`src/msm8905-cam/msm8905-cam.c`) and wired it into `streamoff`, last-file-handle `release`, and module `exit` so closing `xcamera` (or stopping V4L2 streaming) immediately stops the CSI-2 stream, asserts sensor hardware standby (`GPIO_CAM_RESET=0`, `GPIO_CAM_STANDBY=0`, `GPIO_CAM_VDIG=0`, `GPIO_CAM_MCLK0=0x0001`), gates all 20 `CAMSS` `CBCR` branch clocks and 6 `RCG` roots (`200 MHz` `vfe0` / `csi0` / `camss_top_ahb` and `24 MHz` `mclk0`), releases `SMMU` vote clocks, and powers down the `VFE GDSC` domain. - Enabled `workqueue.power_efficient=Y` and `printk.console_suspend=Y` in `/etc/local.d/10-power-save.start`, lowered `78b9000.spi` runtime PM `autosuspend_delay_ms` from `1000 ms` to `50 ms`, enabled runtime PM (`power/control=auto`) across `1c00000.gpu`, `*.spi`, `*.sdhci`, and `*.serial`, and removed the legacy `ttyMSM0` serial `getty` rule from `scripts/configure-rootfs-from-scratch.sh`. - - Added VM writeback (`dirty_writeback_centisecs=6000`), `printk` throttling, `sched_autogroup_enabled=0`, `nmi_watchdog=0`, `schedutil` governor rate-limit tuning (`rate_limit_us=2000`, fixing the 6.44s default caused by `qcom-cpufreq` `UINT_MAX` transition latency so cores downclock to `200 MHz` within `2 ms`), Wi-Fi powersave (`iw dev wlan0 set power_save on`), USB/platform runtime PM (`power/control = auto`), and automatic unbinding of the `7864900.sdhci` microSD host controller when no card is inserted (along with `bias-pull-up` on `sdc2-cd-off-state` and unified Adreno 304 GPU / IOMMU device-tree nodes across all 5 device `.dts`/`.dtb` files). + - Added VM writeback (`dirty_writeback_centisecs=6000`), `printk` throttling, `sched_autogroup_enabled=0`, `nmi_watchdog=0`, `schedutil` governor rate-limit tuning (`rate_limit_us=2000`, fixing the 6.44s default caused by `qcom-cpufreq` `UINT_MAX` transition latency so cores downclock to `200 MHz` within `2 ms`), Wi-Fi powersave (`iw dev wlan0 set power_save on`), USB/platform runtime PM (`power/control = auto`), and `runtime_status = suspended` power management on the `7864900.sdhci` microSD host controller (with `bias-pull-up` on `sdc2-cd-off-state`, hardware GPIO 38 hotplug detection, and unified Adreno 304 GPU / IOMMU device-tree nodes across all 5 device `.dts`/`.dtb` files). - Replaced the 120ms busy-wait loop in `gps.so` (`OsmTileCache::workerLoop`) with `std::condition_variable`, cached Dual-SIM status in `/tmp/sxmo_dsds_active` to avoid repeated `qmicli` wakes on single-SIM setups, set the DSDS `msm-modem-uim-selection` `select()` timeout to infinite (`None`, pure `AF_QIPCRTR` event-driven wait) while the screen is locked and `600s` when unlocked, and set display framebuffer `bl_power = 4` (`FB_BLANK_POWERDOWN`) across `dwm`, `locker.so`, and `sxmo_wm.sh` whenever the screen is blanked. - Added `neoui_next_timeout_ms()` to `libneoui.so`, wired GLib `GMainContext` file descriptors and `"load-failed"` / `closeWindow()` load-stop handling into `webarchy.so` (along with `NO_AT_BRIDGE=1` and `GTK_A11Y=none`), added `inotify` directory watching to `sms.so`, and eliminated idle periodic `poll()` timers across `dialer.so`, `calllog.so`, `contacts.so`, `sms.so`, `xdrawer.so`, `locker.so`, `email.so`, `irc.so`, `smallweb.so`, `tox.so`, `sip.so`, and `webarchy.so` so visible and background plugins sleep at `0%` CPU unless a transient timer (`softkey` chord, multi-tap window, or toast expiry) is active. - Increased `conky` desktop clock refresh interval to `15.0s` and froze `conky` (`SIGSTOP`/`SIGCONT`) whenever the screen is off or locked (`sxmo_hook_screenoff.sh`, `sxmo_hook_lock.sh`, `dwm`, and `locker.so`), skipped `dwm` `drawbar()` Xorg/Glamor/SPI redraws and `sxmo_hook_statusbar.sh` process spawns whenever `bl_power != 0` or `/tmp/bananarchy_screen_locked` exists (with immediate bar refresh on wake/unlock), wrapped background spawns in double-fork subshells `( ... & )` across `bananarchy-x11-session.sh`, `sxmo_modemmonitor.sh`, `sxmo_hook_start.sh`, `sxmo_hook_postwake.sh`, and `msm-modem-uim-selection` to eliminate zombie child accumulation, and drained queued X11 `UnmapNotify` events in `neoui_hide()` so all resident DWM plugins sleep at `0%` CPU when hidden. -- **Universal Power button (`dmenu power`) access and ReMEdy `Call (green)` pause menu**: +- **Universal Power button (`dmenu power`) access, ReMEdy `Call (green)` pause menu, JSR expansion, and 64 MB mark-and-sweep GC**: - Updated `dwm`, `dmenu`, `xdrawer`, `libneoui.so`, `sxmo_multikey.sh`, all standalone Xlib DWM plugins, and standalone games (`scoundrel`, `gambatte`, `remedy`) so pressing **End / Power (red)** (`XF86PowerOff`, keycode `124`) from any active window or menu immediately opens (or toggles) the system **Power menu (`dmenu power`)** while mapped **Call (green)** (`XF86Phone` / `XF86PickupPhone`) and `500 ms` **Right softkey** hold in `remedy` open the **ReMEdy Pause Menu**. + - Upgraded **ReMEdy (`remedy` / `j2me`)** with a `64 MB` heap budget and mark-and-sweep garbage collector (`System.gc()` / `Runtime.gc()`, `freeSlots_` object reuse, and full heap/JAR release on MIDlet exit), synchronous `Canvas.serviceRepaints()`, `Thread.yield()` / `Thread.sleep()` background thread stepping, synthetic native static field storage (`System.out`, `System.err`, `List.SELECT_COMMAND`, `AlertType.*`, `Boolean.TRUE/FALSE`), exact `String` reference preservation in `List.getString()` and `ChoiceGroup.getString()` (for `MeBoy` / `GTA 2` GBC-to-J2ME cartridges), `java.io.InputStreamReader` / `OutputStreamWriter`, `java.lang.Float` / `Double` / `Character`, **JSR-75** (`FileSystemRegistry` / `FileConnection`), **JSR-82** (`javax.bluetooth.*`), **JSR-120** (`javax.wireless.messaging.*`), **JSR-135** (`MIDIControl`), full **Nokia `DirectGraphics`** (`drawPixels`, `getPixels`, `fillPolygon`, `drawPolygon`, `fillTriangle`, `drawTriangle`, `setARGBColor`), and automatic/configurable sub-QVGA (`128x128`, `128x160`, `176x208`, `176x220`) canvas scaling (`Asphalt 6: Adrenaline`). +- **Literal caller ID contact matching (`sxmo_contacts.sh`, `sxmo_common.sh`, `sxmo_modemsendsms.sh`)**: + - Replaced unescaped `grep -i "$NUMBER"` contact lookups with literal matching so carrier service numbers containing regex metacharacters (such as `*121#`) never match arbitrary contact entries. --- diff --git a/MANUAL.md b/MANUAL.md index b1a820a..d0ebbcb 100644 --- a/MANUAL.md +++ b/MANUAL.md @@ -180,7 +180,7 @@ All twenty-four phone applications are compiled as shared-object plugins (`/usr/ - **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. - **Monophonic ringtone viewer (`.nrt`, `.rtttl`, `.rtx`, `.emy`, `.imy`), audio playback, and ringtone/notification installation**: pressing `Return` on any Nokia RTTTL (`.nrt`, `.rtttl`, `.rtx`), Ericsson eMelody (`.emy`), or IrDA iMelody (`.imy`) file opens the built-in **Ringtone Viewer** (`RingtoneView`), displaying the melody title, format tag, BPM, note count, duration, graphical piano-roll pitch contour, and scrollable note sequence (`Up`/`Down`), with instant playback preview (`*` or `Center OK`), `Left`/`Right` to step through ringtones in the current folder, **Left softkey (`Set Ring`)** to set as the active call ringtone, **`#`** to set as the active notification/SMS sound, and `1` to edit the melody text. Pressing `Return` on standard audio or tracker module files opens **Music (`xmusic`)**. From the **Left softkey (`Actions`)** menu on any monophonic melody, audio, or tracker file, select **Preview Ringtone**, **Set as Ringtone**, **Set as Notif / SMS Sound**, **Open in Ringtones App**, or **Play in Music Player**. - - **MicroSD card (`/media/sdcard`) integration**: when a microSD card (`/dev/mmcblk1`) is inserted, `udev` and `/usr/bin/sxmo_sdcard.sh` automatically mount it at `/media/sdcard` (and unbind the `7864900.sdhci` controller when empty to save power). From the **Left softkey (`Actions`)** menu inside `xfiles` (or **System menu -> SD Card**), select **Open SD Card (/media/sdcard)** to jump straight to the card (mounting it on demand if needed) or **Mount / Unmount SD Card** to safely flush and unmount the card before removal. + - **MicroSD card (`/media/sdcard`) integration**: when a microSD card (`/dev/mmcblk1`) is inserted, `udev` and `/usr/bin/sxmo_sdcard.sh` automatically mount it at `/media/sdcard` (keeping `7864900.sdhci` in `runtime_status = suspended` when idle and unbinding only during `--force-unmount` duress mode). From the **Left softkey (`Actions`)** menu inside `xfiles` (or **System menu -> SD Card**), select **Open SD Card (/media/sdcard)** to jump straight to the card (mounting it on demand if needed) or **Mount / Unmount SD Card** to safely flush and unmount the card before removal. - **Bluetooth file transfer (`Send via Bluetooth`)**: select **Send via Bluetooth** from the **Left softkey (`Actions`)** menu on any file to choose a paired or nearby Bluetooth device (`*` rescans) and transmit the file over Bluetooth OBEX Object Push (`/usr/bin/bananarchy-bt-obex`). - **File management actions**: the **Left softkey (`Actions`)** menu also provides **Edit in Text Editor**, **View Text**, **Edit in nano**, **New Folder**, **New File**, **Rename**, **Copy**, **Cut / Move**, **Paste Here**, **Properties**, **Open Terminal Here**, and **Delete**. @@ -205,7 +205,7 @@ All twenty-four phone applications are compiled as shared-object plugins (`/usr/ - **Three connectivity tabs (`Left`/`Right` or `1`–`3`)**: - **`1:Wi-Fi`**: toggle Wi-Fi radio, rescan (`*`), toggle **Wi-Fi Hotspot**, and connect to WPA2/open networks with a multi-tap password dialog (`*` toggles password visibility). - **`2:Cell/APN`**: toggle **Mobile Data** (configuring the QMI `bam-dmux` `wwan0` static IPv4 bearer, default route, and DNS automatically), inspect `wwan0` IPv4 status, edit **APN Configuration**, and toggle **USB Tethering**. - - **`3:Bluetooth`**: toggle Bluetooth power (automatically starting the OBEX Object Push receiver daemon `/usr/bin/bananarchy-bt-obex`), monitor the live **OBEX File Receiver** widget (displaying incoming transfer status and the last received file in `~/Downloads/`), press `#` to jump straight to `~/Downloads/` in **Files (`xfiles`)**, scan nearby devices (`*`), and pair, connect, disconnect, or remove devices. + - **`3:Bluetooth`**: toggle **Bluetooth Power** (showing a live `ON (N Active)` badge and starting `/usr/bin/bananarchy-bt-obex`), toggle **Discoverable** (`ON (Visible)` vs `OFF (Hidden)`, persisted in `~/.config/sxmo/bt_discoverable`), edit the **Bluetooth Device Name** (`Name: [Edit]`, persisted in `~/.config/sxmo/bt_name` and applied via `bluetoothctl system-alias` independently of the system hostname), monitor the live **OBEX File Receiver** widget (`#` opens `~/Downloads/` in `xfiles`), scan nearby devices (`*`), and manage paired/discovered devices. Active connections are pinned to the top of the device list with a green border and live profile/battery badges (`[ACTIVE: A2DP]`, `[ACTIVE: HSP/HFP]`, `[ACTIVE: HID Gamepad]`, `[ACTIVE: HID Keyboard]`, `[ACTIVE: HID Mouse]`), and the device actions menu (`Center OK`) provides **Disconnect / Connect**, **Switch Audio (A2DP / HSP-HFP)**, **Trust**, and **Remove / Forget**. Supports Bluetooth **A2DP** (`sbc_xq`, `aac`, `ldac`, `aptx`, `aptx_hd`) and **HSP/HFP** (`mSBC` / `CVSD`) audio (routable via `xdrawer`, `dmenu Audio`, and `sxmo_audio.sh`), **HID keyboards**, **HID mice** (with automatic X11 cursor display on mouse movement/click and auto-hide on keypad input), and **HID gamepads** (automatically bridged to the phone's D-Pad, softkeys, and action keys via `/dev/uinput`). 13. **Ringtones, notification/SMS sounds, and ringer manager (`ringtones.so` / `xringtones`)**: - **Open**: select **Ringtones** from the System, Config, or Audio menu, select **Notification Sound** from the **Notifications (`Notifs`)** menu, or run `xringtones [--notif] [file]`. diff --git a/overlay/rootfs/etc/X11/xinit/xserverrc b/overlay/rootfs/etc/X11/xinit/xserverrc index e4bdcf7..b4de252 100755 --- a/overlay/rootfs/etc/X11/xinit/xserverrc +++ b/overlay/rootfs/etc/X11/xinit/xserverrc @@ -1,2 +1,2 @@ #!/bin/sh -exec /usr/bin/X -nocursor -nolisten tcp "$@" +exec /usr/bin/X -nolisten tcp "$@" diff --git a/overlay/rootfs/etc/bluetooth/input.conf b/overlay/rootfs/etc/bluetooth/input.conf new file mode 100644 index 0000000..0a28657 --- /dev/null +++ b/overlay/rootfs/etc/bluetooth/input.conf @@ -0,0 +1,5 @@ +[General] +IdleTimeout=0 +UserspaceHID=true +ClassicBondedOnly=false +LEAutoSecurity=true diff --git a/overlay/rootfs/etc/bluetooth/main.conf b/overlay/rootfs/etc/bluetooth/main.conf new file mode 100644 index 0000000..9f2e540 --- /dev/null +++ b/overlay/rootfs/etc/bluetooth/main.conf @@ -0,0 +1,17 @@ +[General] +DiscoverableTimeout = 0 +PairableTimeout = 0 +ControllerMode = dual +MultiProfile = multiple +JustWorksRepairing = always +Experimental = true + +[GATT] +Cache = always + +[Policy] +ReconnectUUIDs=00001112-0000-1000-8000-00805f9b34fb,0000111f-0000-1000-8000-00805f9b34fb,0000110a-0000-1000-8000-00805f9b34fb,0000110b-0000-1000-8000-00805f9b34fb,00001108-0000-1000-8000-00805f9b34fb,0000111e-0000-1000-8000-00805f9b34fb,00001124-0000-1000-8000-00805f9b34fb,00001812-0000-1000-8000-00805f9b34fb +ReconnectAttempts=7 +ReconnectIntervals=1,2,4,8,16,32,64 +AutoEnable=true +ResumeDelay = 2 diff --git a/overlay/rootfs/etc/doas.d/50-sxmo.conf b/overlay/rootfs/etc/doas.d/50-sxmo.conf index ea2cfb5..69f5525 100644 --- a/overlay/rootfs/etc/doas.d/50-sxmo.conf +++ b/overlay/rootfs/etc/doas.d/50-sxmo.conf @@ -7,7 +7,9 @@ permit nopass :wheel as root cmd poweroff permit nopass :wheel as root cmd reboot permit nopass :wheel as root cmd /sbin/poweroff permit nopass :wheel as root cmd /sbin/reboot +permit nopass :wheel as root cmd /usr/bin/sxmo_wifitoggle.sh permit nopass :wheel as root cmd sxmo_wifitoggle.sh +permit nopass setenv { SXMO_OS } :wheel as root cmd /usr/bin/sxmo_bluetoothtoggle.sh permit nopass setenv { SXMO_OS } :wheel as root cmd sxmo_bluetoothtoggle.sh permit nopass :wheel as root cmd rc-service args bluetooth restart permit nopass :wheel as root cmd systemctl args restart bluetooth diff --git a/overlay/rootfs/etc/skel/.config/wireplumber/wireplumber.conf.d/50-bluetooth.conf b/overlay/rootfs/etc/skel/.config/wireplumber/wireplumber.conf.d/50-bluetooth.conf new file mode 100644 index 0000000..0f40c24 --- /dev/null +++ b/overlay/rootfs/etc/skel/.config/wireplumber/wireplumber.conf.d/50-bluetooth.conf @@ -0,0 +1,9 @@ +monitor.bluez.properties = { + bluez5.roles = [ a2dp_sink a2dp_source bap_sink bap_source hsp_hs hsp_ag hfp_hf hfp_ag ] + bluez5.codecs = [ sbc sbc_xq aac ldac aptx aptx_hd aptx_ll aptx_ll_duplex faststream faststream_duplex opus_05 opus_05_51 opus_05_71 opus_05_dup opus_05_pro lc3 ] + bluez5.enable-sbc-xq = true + bluez5.enable-msbc = true + bluez5.enable-hw-volume = true + bluez5.hfphsp-backend = "native" + bluez5.hfphsp-backend-native-modem = "any" +} diff --git a/overlay/rootfs/etc/udev/rules.d/88-bananarchy-sdcard.rules b/overlay/rootfs/etc/udev/rules.d/88-bananarchy-sdcard.rules index 995b31f..f1a7f8e 100644 --- a/overlay/rootfs/etc/udev/rules.d/88-bananarchy-sdcard.rules +++ b/overlay/rootfs/etc/udev/rules.d/88-bananarchy-sdcard.rules @@ -1,4 +1,4 @@ -# Automatically mount and unmount removable microSD cards (mmcblk1) at /media/sdcard -SUBSYSTEM=="block", KERNEL=="mmcblk1p[1-9]*", ACTION=="add", RUN+="/usr/bin/sxmo_sdcard.sh automount add %k" -SUBSYSTEM=="block", KERNEL=="mmcblk1", ATTR{partition}!="1", ENV{ID_FS_USAGE}=="filesystem", ACTION=="add", RUN+="/usr/bin/sxmo_sdcard.sh automount add %k" -SUBSYSTEM=="block", KERNEL=="mmcblk1*", ACTION=="remove", RUN+="/usr/bin/sxmo_sdcard.sh automount remove %k" +# Bananarchy microSD card automount on insertion & cleanup on removal +ACTION=="add", SUBSYSTEM=="block", KERNEL=="mmcblk[1-9]p[1-9]", RUN+="/bin/sh -c '/usr/bin/sxmo_sdcard.sh automount add %k >/dev/null 2>&1 &'" +ACTION=="add", SUBSYSTEM=="block", KERNEL=="mmcblk[1-9]", ENV{DEVTYPE}=="disk", RUN+="/bin/sh -c 'sleep 1; /usr/bin/sxmo_sdcard.sh automount add %k >/dev/null 2>&1 &'" +ACTION=="remove", SUBSYSTEM=="block", KERNEL=="mmcblk[1-9]*", RUN+="/bin/sh -c '/usr/bin/sxmo_sdcard.sh automount remove %k >/dev/null 2>&1 &'" diff --git a/overlay/rootfs/etc/wireplumber/wireplumber.conf.d/50-bluetooth.conf b/overlay/rootfs/etc/wireplumber/wireplumber.conf.d/50-bluetooth.conf new file mode 100644 index 0000000..0f40c24 --- /dev/null +++ b/overlay/rootfs/etc/wireplumber/wireplumber.conf.d/50-bluetooth.conf @@ -0,0 +1,9 @@ +monitor.bluez.properties = { + bluez5.roles = [ a2dp_sink a2dp_source bap_sink bap_source hsp_hs hsp_ag hfp_hf hfp_ag ] + bluez5.codecs = [ sbc sbc_xq aac ldac aptx aptx_hd aptx_ll aptx_ll_duplex faststream faststream_duplex opus_05 opus_05_51 opus_05_71 opus_05_dup opus_05_pro lc3 ] + bluez5.enable-sbc-xq = true + bluez5.enable-msbc = true + bluez5.enable-hw-volume = true + bluez5.hfphsp-backend = "native" + bluez5.hfphsp-backend-native-modem = "any" +} diff --git a/overlay/rootfs/home/user/.config/wireplumber/wireplumber.conf.d/50-bluetooth.conf b/overlay/rootfs/home/user/.config/wireplumber/wireplumber.conf.d/50-bluetooth.conf new file mode 100644 index 0000000..0f40c24 --- /dev/null +++ b/overlay/rootfs/home/user/.config/wireplumber/wireplumber.conf.d/50-bluetooth.conf @@ -0,0 +1,9 @@ +monitor.bluez.properties = { + bluez5.roles = [ a2dp_sink a2dp_source bap_sink bap_source hsp_hs hsp_ag hfp_hf hfp_ag ] + bluez5.codecs = [ sbc sbc_xq aac ldac aptx aptx_hd aptx_ll aptx_ll_duplex faststream faststream_duplex opus_05 opus_05_51 opus_05_71 opus_05_dup opus_05_pro lc3 ] + bluez5.enable-sbc-xq = true + bluez5.enable-msbc = true + bluez5.enable-hw-volume = true + bluez5.hfphsp-backend = "native" + bluez5.hfphsp-backend-native-modem = "any" +} diff --git a/overlay/rootfs/usr/bin/bananarchy-bt-obex b/overlay/rootfs/usr/bin/bananarchy-bt-obex index 53f06de..cef1cd6 100755 --- a/overlay/rootfs/usr/bin/bananarchy-bt-obex +++ b/overlay/rootfs/usr/bin/bananarchy-bt-obex @@ -5,6 +5,8 @@ import os import sys import time +import fcntl +import select import struct import socket import signal @@ -60,15 +62,24 @@ def notify_networks_ui(): def notify_user(title, body): try: + bus_addr = "unix:path=/run/user/10000/bus" + if os.path.exists("/run/user/10000/dbus.bus"): + try: + with open("/run/user/10000/dbus.bus", "r", encoding="utf-8") as bf: + line = bf.readline().strip() + if line: + bus_addr = line + except OSError: + pass if os.geteuid() == 0: subprocess.Popen([ "su", "-", "user", "-c", - f"DISPLAY=:0 DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/10000/bus notify-send { subprocess.list2cmdline([title, body]) }" + f"DISPLAY=:0 DBUS_SESSION_BUS_ADDRESS={subprocess.list2cmdline([bus_addr])} notify-send {subprocess.list2cmdline([title, body])}" ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) else: env = os.environ.copy() env.setdefault("DISPLAY", ":0") - env.setdefault("DBUS_SESSION_BUS_ADDRESS", "unix:path=/run/user/10000/bus") + env.setdefault("DBUS_SESSION_BUS_ADDRESS", bus_addr) subprocess.Popen(["notify-send", title, body], env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) except Exception: @@ -278,6 +289,239 @@ def handle_obex_rx_session(sock): pass +def run_gamepad_uinput_bridge(is_running): + ev_fmt = "llHHi" + ev_size = struct.calcsize(ev_fmt) + ui_set_evbit = 0x40045564 + ui_set_keybit = 0x40045565 + ui_dev_create = 0x5501 + ui_dev_destroy = 0x5502 + eviocgbit_key = (2 << 30) | (96 << 16) | (0x45 << 8) | (0x20 + 0x01) + + # Map Linux gamepad button codes to Bananarchy keypad/navigation keys: + # South(A)=Enter(OK), East(B)=8(GB B), West(X)=5(Fire/Turbo B), North(Y)=6(Turbo A) + # Start=2(GB Start), Select=3(GB Select), L1=F1(LSK), R1=F2(RSK), L2=*, R2=0, Mode=Esc + btn_map = { + 0x130: 28, # BTN_SOUTH (A) -> KEY_ENTER + 0x131: 9, # BTN_EAST (B) -> KEY_8 + 0x132: 8, # BTN_C -> KEY_7 + 0x133: 6, # BTN_WEST (X) -> KEY_5 + 0x134: 7, # BTN_NORTH (Y) -> KEY_6 + 0x135: 10, # BTN_Z -> KEY_9 + 0x136: 59, # BTN_TL (L1) -> KEY_F1 (Left Softkey) + 0x137: 60, # BTN_TR (R1) -> KEY_F2 (Right Softkey) + 0x138: 55, # BTN_TL2 (L2) -> KEY_KPASTERISK (*) + 0x139: 11, # BTN_TR2 (R2) -> KEY_0 + 0x13a: 4, # BTN_SELECT -> KEY_3 + 0x13b: 3, # BTN_START -> KEY_2 + 0x13c: 1, # BTN_MODE -> KEY_ESC + 0x120: 28, # BTN_TRIGGER -> KEY_ENTER + 0x121: 9, # BTN_THUMB -> KEY_8 + 0x220: 103, # BTN_DPAD_UP -> KEY_UP + 0x221: 108, # BTN_DPAD_DOWN -> KEY_DOWN + 0x222: 105, # BTN_DPAD_LEFT -> KEY_LEFT + 0x223: 106, # BTN_DPAD_RIGHT -> KEY_RIGHT + } + all_keys = sorted(set(btn_map.values()) | {103, 108, 105, 106}) + + uinput_fd = None + gamepads = {} # path -> {"fd": int, "hat_x": 0, "hat_y": 0, "lx": 0, "ly": 0, "ax": {}} + last_scan = 0.0 + + def ensure_uinput(): + nonlocal uinput_fd + if uinput_fd is not None: + return True + try: + subprocess.run(["modprobe", "-q", "uinput"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + fd = os.open("/dev/uinput", os.O_WRONLY | os.O_NONBLOCK) + fcntl.ioctl(fd, ui_set_evbit, 0x00) # EV_SYN + fcntl.ioctl(fd, ui_set_evbit, 0x01) # EV_KEY + for k in all_keys: + fcntl.ioctl(fd, ui_set_keybit, k) + name = b"Bananarchy BT Gamepad Bridge" + udev = struct.pack("80sHHHHi", name, 0x06, 0x1209, 0x8110, 1, 0) + (b"\x00" * (64 * 4 * 4)) + os.write(fd, udev) + fcntl.ioctl(fd, ui_dev_create) + uinput_fd = fd + return True + except Exception: + return False + + def emit_key(code, val): + if uinput_fd is None and not ensure_uinput(): + return + try: + os.write(uinput_fd, struct.pack(ev_fmt, 0, 0, 0x01, code, val)) + os.write(uinput_fd, struct.pack(ev_fmt, 0, 0, 0x00, 0, 0)) + except OSError: + pass + + def get_axis_dir(fd, axis, val, cache): + if axis not in cache: + try: + ioc = (2 << 30) | (24 << 16) | (0x45 << 8) | (0x40 + axis) + buf = fcntl.ioctl(fd, ioc, b"\x00" * 24) + _v, min_v, max_v, _fz, _fl, _rs = struct.unpack("6i", buf) + if max_v > min_v: + cache[axis] = (min_v, max_v) + else: + cache[axis] = (-32768, 32767) + except Exception: + cache[axis] = (-32768, 32767) + min_v, max_v = cache[axis] + mid = (min_v + max_v) / 2.0 + span = (max_v - min_v) / 2.0 + if span <= 0: + return 0 + norm = (val - mid) / span + if norm < -0.40: + return -1 + if norm > 0.40: + return 1 + return 0 + + while is_running(): + now = time.monotonic() + if now - last_scan >= 2.0: + last_scan = now + try: + for entry in os.listdir("/dev/input"): + if not entry.startswith("event"): + continue + dev_path = f"/dev/input/{entry}" + if dev_path in gamepads: + continue + sys_name_path = f"/sys/class/input/{entry}/device/name" + try: + with open(sys_name_path, "r", encoding="utf-8") as nf: + dname = nf.read().strip() + if "Bananarchy BT Gamepad Bridge" in dname: + continue + except OSError: + pass + try: + fd = os.open(dev_path, os.O_RDONLY | os.O_NONBLOCK) + buf = bytearray(96) + fcntl.ioctl(fd, eviocgbit_key, buf, True) + has_gamepad = bool((buf[0x130 // 8] >> (0x130 % 8)) & 1) or bool((buf[0x120 // 8] >> (0x120 % 8)) & 1) + if has_gamepad: + ensure_uinput() + gamepads[dev_path] = { + "fd": fd, "hat_x": 0, "hat_y": 0, "lx": 0, "ly": 0, "ax": {} + } + else: + os.close(fd) + except Exception: + pass + except OSError: + pass + + if not gamepads: + time.sleep(1.5) + continue + + fd_map = {info["fd"]: (path, info) for path, info in list(gamepads.items())} + try: + rlist, _, _ = select.select(list(fd_map.keys()), [], [], 1.0) + except Exception: + time.sleep(0.5) + continue + + for rfd in rlist: + path, info = fd_map.get(rfd, (None, None)) + if not path: + continue + try: + data = os.read(rfd, ev_size * 16) + if not data: + raise OSError("EOF") + except OSError: + try: + os.close(rfd) + except OSError: + pass + gamepads.pop(path, None) + continue + + offset = 0 + while offset + ev_size <= len(data): + _sec, _usec, ev_type, ev_code, ev_val = struct.unpack_from(ev_fmt, data, offset) + offset += ev_size + if ev_type == 0x01 and ev_code in btn_map: + if ev_val in (0, 1, 2): + emit_key(btn_map[ev_code], ev_val) + elif ev_type == 0x03: + if ev_code == 0x10: # ABS_HAT0X + new_dir = -1 if ev_val < 0 else (1 if ev_val > 0 else 0) + old_dir = info["hat_x"] + if new_dir != old_dir: + if old_dir == -1: + emit_key(105, 0) + elif old_dir == 1: + emit_key(106, 0) + if new_dir == -1: + emit_key(105, 1) + elif new_dir == 1: + emit_key(106, 1) + info["hat_x"] = new_dir + elif ev_code == 0x11: # ABS_HAT0Y + new_dir = -1 if ev_val < 0 else (1 if ev_val > 0 else 0) + old_dir = info["hat_y"] + if new_dir != old_dir: + if old_dir == -1: + emit_key(103, 0) + elif old_dir == 1: + emit_key(108, 0) + if new_dir == -1: + emit_key(103, 1) + elif new_dir == 1: + emit_key(108, 1) + info["hat_y"] = new_dir + elif ev_code == 0x00: # ABS_X (Left Stick X) + new_dir = get_axis_dir(rfd, 0x00, ev_val, info["ax"]) + old_dir = info["lx"] + if new_dir != old_dir: + if old_dir == -1: + emit_key(105, 0) + elif old_dir == 1: + emit_key(106, 0) + if new_dir == -1: + emit_key(105, 1) + elif new_dir == 1: + emit_key(106, 1) + info["lx"] = new_dir + elif ev_code == 0x01: # ABS_Y (Left Stick Y) + new_dir = get_axis_dir(rfd, 0x01, ev_val, info["ax"]) + old_dir = info["ly"] + if new_dir != old_dir: + if old_dir == -1: + emit_key(103, 0) + elif old_dir == 1: + emit_key(108, 0) + if new_dir == -1: + emit_key(103, 1) + elif new_dir == 1: + emit_key(108, 1) + info["ly"] = new_dir + + for info in gamepads.values(): + try: + os.close(info["fd"]) + except OSError: + pass + if uinput_fd is not None: + try: + fcntl.ioctl(uinput_fd, ui_dev_destroy) + except Exception: + pass + try: + os.close(uinput_fd) + except OSError: + pass + + def run_daemon(): from jeepney import DBusAddress, new_method_call, new_method_return, MessageType from jeepney.io.blocking import open_dbus_connection @@ -297,14 +541,42 @@ def run_daemon(): signal.signal(signal.SIGTERM, stop_handler) signal.signal(signal.SIGINT, stop_handler) - # Make adapter discoverable and pairable when Bluetooth is ON so senders can see the phone - subprocess.run(["bluetoothctl", "discoverable-timeout", "0"], + bt_name = "" + try: + if os.path.exists("/home/user/.config/sxmo/bt_name"): + with open("/home/user/.config/sxmo/bt_name", "r", encoding="utf-8") as nf: + bt_name = nf.readline().strip() + except OSError: + pass + if not bt_name: + try: + bt_name = socket.gethostname().strip() + except Exception: + bt_name = "Bananarchy" + if bt_name: + subprocess.run(["timeout", "2", "bluetoothctl", "system-alias", bt_name], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + + bt_disc = "1" + try: + if os.path.exists("/home/user/.config/sxmo/bt_discoverable"): + with open("/home/user/.config/sxmo/bt_discoverable", "r", encoding="utf-8") as df: + bt_disc = df.readline().strip() or "1" + except OSError: + pass + disc_on = bt_disc.lower() not in ("0", "off", "no", "false") + + subprocess.run(["timeout", "2", "bluetoothctl", "discoverable-timeout", "0"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - subprocess.run(["bluetoothctl", "discoverable", "on"], + subprocess.run(["timeout", "2", "bluetoothctl", "discoverable", "on" if disc_on else "off"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) - subprocess.run(["bluetoothctl", "pairable", "on"], + subprocess.run(["timeout", "2", "bluetoothctl", "pairable", "on"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + gp_thread = threading.Thread(target=run_gamepad_uinput_bridge, + args=(lambda: running,), daemon=True) + gp_thread.start() + profile_path = "/org/bananarchy/obex_opp" conn = None try: diff --git a/overlay/rootfs/usr/bin/bananarchy-x11-session.sh b/overlay/rootfs/usr/bin/bananarchy-x11-session.sh index b74093e..ccdb699 100755 --- a/overlay/rootfs/usr/bin/bananarchy-x11-session.sh +++ b/overlay/rootfs/usr/bin/bananarchy-x11-session.sh @@ -89,7 +89,7 @@ if pidof -s plymouthd >/dev/null 2>&1; then fi if ! pidof -s Xorg >/dev/null 2>&1; then - "$XORG_BIN" :0 -s 0 -dpms -nocursor -nolisten tcp -config "$XORG_CONFIG" -modulepath "$XORG_MODPATH" -logfile /tmp/Xorg.0.log >/dev/null 2>&1 /dev/null 2>&1 /dev/null 2>&1; then diff --git a/overlay/rootfs/usr/bin/dwm b/overlay/rootfs/usr/bin/dwm index 2f7f6b8..1ba4a11 100755 Binary files a/overlay/rootfs/usr/bin/dwm and b/overlay/rootfs/usr/bin/dwm differ diff --git a/overlay/rootfs/usr/bin/gambatte b/overlay/rootfs/usr/bin/gambatte index 72478ae..1de0e68 100755 Binary files a/overlay/rootfs/usr/bin/gambatte and b/overlay/rootfs/usr/bin/gambatte differ diff --git a/overlay/rootfs/usr/bin/remedy b/overlay/rootfs/usr/bin/remedy index e1a9c96..6c536b2 100755 Binary files a/overlay/rootfs/usr/bin/remedy and b/overlay/rootfs/usr/bin/remedy differ diff --git a/overlay/rootfs/usr/bin/sxmo_audio.sh b/overlay/rootfs/usr/bin/sxmo_audio.sh index 39986dd..4d6219a 100755 --- a/overlay/rootfs/usr/bin/sxmo_audio.sh +++ b/overlay/rootfs/usr/bin/sxmo_audio.sh @@ -26,6 +26,7 @@ clamp_pct() { normalize_out_dev() { case "$1" in + *[Bb]luetooth*|*[Bb]luez*) printf "Bluetooth" ;; *[Ee]arpiece*) printf "Earpiece" ;; *[Hh]eadphone*|*[Hh]eadset*) printf "Headphones" ;; *) printf "Speaker" ;; @@ -34,14 +35,24 @@ normalize_out_dev() { normalize_in_dev() { case "$1" in + *[Bb]luetooth*|*[Bb]luez*) printf "Bluetooth" ;; *[Hh]eadset*) printf "Headset" ;; *) printf "Mic1" ;; esac } +find_bt_sink() { + pactl list short sinks 2>/dev/null | awk '$2 ~ /^bluez_output\./ { print $2; exit }' +} + +find_bt_source() { + pactl list short sources 2>/dev/null | awk '$2 ~ /^bluez_input\./ { print $2; exit }' +} + vol_file_for_dev() { dev="$(normalize_out_dev "$1")" case "$dev" in + Bluetooth) printf "%s/bluetooth_vol" "$CFG_DIR" ;; Earpiece) printf "%s/earpiece_vol" "$CFG_DIR" ;; Headphones) printf "%s/headphones_vol" "$CFG_DIR" ;; *) printf "%s/speaker_vol" "$CFG_DIR" ;; @@ -51,7 +62,7 @@ vol_file_for_dev() { default_vol_for_dev() { dev="$(normalize_out_dev "$1")" case "$dev" in - Headphones) printf "80" ;; + Bluetooth|Headphones) printf "80" ;; *) printf "85" ;; esac } @@ -104,11 +115,23 @@ pct_to_hw_adc() { } deviceget() { + sink="$(pactl get-default-sink 2>/dev/null || true)" + case "$sink" in + bluez_output.*) + printf "Bluetooth\n" > /tmp/sxmo_audio_out_device 2>/dev/null || true + printf "Bluetooth\n" + return 0 + ;; + esac if [ -r /tmp/sxmo_audio_out_device ]; then read -r dev < /tmp/sxmo_audio_out_device 2>/dev/null || dev="" if [ -n "$dev" ]; then - normalize_out_dev "$dev" - printf "\n" + dev="$(normalize_out_dev "$dev")" + if [ "$dev" = "Bluetooth" ] && [ -z "$(find_bt_sink)" ]; then + dev="Speaker" + printf "%s\n" "$dev" > /tmp/sxmo_audio_out_device 2>/dev/null || true + fi + printf "%s\n" "$dev" return 0 fi fi @@ -116,12 +139,14 @@ deviceget() { read -r dev < "$CFG_DIR/audio_out_device" 2>/dev/null || dev="" if [ -n "$dev" ]; then dev="$(normalize_out_dev "$dev")" + if [ "$dev" = "Bluetooth" ] && [ -z "$(find_bt_sink)" ]; then + dev="Speaker" + fi printf "%s\n" "$dev" > /tmp/sxmo_audio_out_device 2>/dev/null || true printf "%s\n" "$dev" return 0 fi fi - sink="$(pactl get-default-sink 2>/dev/null || true)" case "$sink" in *Earpiece*) dev="Earpiece" ;; *Headphones*) dev="Headphones" ;; @@ -132,11 +157,23 @@ deviceget() { } devicegetinput() { + src="$(pactl get-default-source 2>/dev/null || true)" + case "$src" in + bluez_input.*) + printf "Bluetooth\n" > /tmp/sxmo_audio_in_device 2>/dev/null || true + printf "Bluetooth\n" + return 0 + ;; + esac if [ -r /tmp/sxmo_audio_in_device ]; then read -r in_dev < /tmp/sxmo_audio_in_device 2>/dev/null || in_dev="" if [ -n "$in_dev" ]; then - normalize_in_dev "$in_dev" - printf "\n" + in_dev="$(normalize_in_dev "$in_dev")" + if [ "$in_dev" = "Bluetooth" ] && [ -z "$(find_bt_source)" ]; then + in_dev="Mic1" + printf "%s\n" "$in_dev" > /tmp/sxmo_audio_in_device 2>/dev/null || true + fi + printf "%s\n" "$in_dev" return 0 fi fi @@ -144,12 +181,14 @@ devicegetinput() { read -r in_dev < "$CFG_DIR/audio_in_device" 2>/dev/null || in_dev="" if [ -n "$in_dev" ]; then in_dev="$(normalize_in_dev "$in_dev")" + if [ "$in_dev" = "Bluetooth" ] && [ -z "$(find_bt_source)" ]; then + in_dev="Mic1" + fi printf "%s\n" "$in_dev" > /tmp/sxmo_audio_in_device 2>/dev/null || true printf "%s\n" "$in_dev" return 0 fi fi - src="$(pactl get-default-source 2>/dev/null || true)" case "$src" in *Headset*) in_dev="Headset" ;; *) in_dev="Mic1" ;; @@ -251,6 +290,18 @@ apply_alsa_out() { amixer -c 0 cset "name='RX2 Digital Volume'" 0 >/dev/null 2>&1 || true fi ;; + Bluetooth) + amixer -c 0 -q sset 'SPK DAC' off 2>/dev/null || amixer -c 0 cset "name='SPK DAC Switch'" 0 >/dev/null 2>&1 || true + amixer -c 0 cset "name='EAR_S'" 'ZERO' >/dev/null 2>&1 || true + amixer -c 0 cset "name='HPHL'" 'ZERO' >/dev/null 2>&1 || true + amixer -c 0 cset "name='HPHR'" 'ZERO' >/dev/null 2>&1 || true + amixer -c 0 cset "name='RX1 MIX1 INP1'" 'ZERO' >/dev/null 2>&1 || true + amixer -c 0 cset "name='RX2 MIX1 INP1'" 'ZERO' >/dev/null 2>&1 || true + amixer -c 0 cset "name='RX3 MIX1 INP1'" 'ZERO' >/dev/null 2>&1 || true + amixer -c 0 cset "name='RX1 Digital Volume'" 0 >/dev/null 2>&1 || true + amixer -c 0 cset "name='RX2 Digital Volume'" 0 >/dev/null 2>&1 || true + amixer -c 0 cset "name='RX3 Digital Volume'" 0 >/dev/null 2>&1 || true + ;; *) amixer -c 0 cset "name='EAR_S'" 'ZERO' >/dev/null 2>&1 || true amixer -c 0 cset "name='HPHL'" 'ZERO' >/dev/null 2>&1 || true @@ -274,7 +325,11 @@ apply_alsa_out() { if [ "$eff_pct" -gt 0 ]; then wpctl set-mute @DEFAULT_AUDIO_SINK@ 0 >/dev/null 2>&1 || true - wpctl set-volume @DEFAULT_AUDIO_SINK@ 100% >/dev/null 2>&1 || true + if [ "$dev" = "Bluetooth" ]; then + wpctl set-volume @DEFAULT_AUDIO_SINK@ "${eff_pct}%" >/dev/null 2>&1 || true + else + wpctl set-volume @DEFAULT_AUDIO_SINK@ 100% >/dev/null 2>&1 || true + fi else wpctl set-mute @DEFAULT_AUDIO_SINK@ 1 >/dev/null 2>&1 || true fi @@ -324,7 +379,11 @@ apply_alsa_in() { if [ "$eff_pct" -gt 0 ]; then wpctl set-mute @DEFAULT_AUDIO_SOURCE@ 0 >/dev/null 2>&1 || true - wpctl set-volume @DEFAULT_AUDIO_SOURCE@ 100% >/dev/null 2>&1 || true + if [ "$in_dev" = "Bluetooth" ]; then + wpctl set-volume @DEFAULT_AUDIO_SOURCE@ "${eff_pct}%" >/dev/null 2>&1 || true + else + wpctl set-volume @DEFAULT_AUDIO_SOURCE@ 100% >/dev/null 2>&1 || true + fi else wpctl set-mute @DEFAULT_AUDIO_SOURCE@ 1 >/dev/null 2>&1 || true fi @@ -333,6 +392,8 @@ apply_alsa_in() { profile_for_devices() { out_dev="$(normalize_out_dev "$1")" in_dev="$(normalize_in_dev "$2")" + [ "$out_dev" = "Bluetooth" ] && out_dev="Speaker" + [ "$in_dev" = "Bluetooth" ] && in_dev="Mic1" case "${out_dev}:${in_dev}" in Headphones:Headset) printf "HiFi (Headphones, Headset)" ;; Headphones:Mic1) printf "HiFi (Headphones, Mic1)" ;; @@ -349,10 +410,24 @@ sync_pipewire_profile() { prof="$(profile_for_devices "$out_dev" "$in_dev")" pactl set-card-profile alsa_card.comprC0 off >/dev/null 2>&1 || true pactl set-card-profile "$ALSA_CARD" "$prof" >/dev/null 2>&1 || true - sink_name="alsa_output.platform-7702000.sound.HiFi__${out_dev}__sink" - src_name="alsa_input.platform-7702000.sound.HiFi__${in_dev}__source" - pactl set-default-sink "$sink_name" >/dev/null 2>&1 || true - pactl set-default-source "$src_name" >/dev/null 2>&1 || true + if [ "$out_dev" = "Bluetooth" ]; then + bt_sink="$(find_bt_sink)" + if [ -n "$bt_sink" ]; then + pactl set-default-sink "$bt_sink" >/dev/null 2>&1 || true + fi + else + sink_name="alsa_output.platform-7702000.sound.HiFi__${out_dev}__sink" + pactl set-default-sink "$sink_name" >/dev/null 2>&1 || true + fi + if [ "$in_dev" = "Bluetooth" ]; then + bt_src="$(find_bt_source)" + if [ -n "$bt_src" ]; then + pactl set-default-source "$bt_src" >/dev/null 2>&1 || true + fi + else + src_name="alsa_input.platform-7702000.sound.HiFi__${in_dev}__source" + pactl set-default-source "$src_name" >/dev/null 2>&1 || true + fi } notifyvol() { @@ -523,28 +598,56 @@ devicesetinput() { } devicelist() { - printf "Speaker\nEarpiece\nHeadphones\n" + if [ -n "$(find_bt_sink)" ]; then + printf "Bluetooth\nSpeaker\nEarpiece\nHeadphones\n" + else + printf "Speaker\nEarpiece\nHeadphones\n" + fi } devicelistinput() { - printf "Mic1\nHeadset\n" + if [ -n "$(find_bt_source)" ]; then + printf "Bluetooth\nMic1\nHeadset\n" + else + printf "Mic1\nHeadset\n" + fi } devicecycle() { dir="${1:-next}" cur="$(deviceget)" + has_bt=0 + [ -n "$(find_bt_sink)" ] && has_bt=1 if [ "$dir" = "prev" ]; then - case "$cur" in - Speaker) next="Headphones" ;; - Earpiece) next="Speaker" ;; - *) next="Earpiece" ;; - esac + if [ "$has_bt" = "1" ]; then + case "$cur" in + Bluetooth) next="Headphones" ;; + Speaker) next="Bluetooth" ;; + Earpiece) next="Speaker" ;; + *) next="Earpiece" ;; + esac + else + case "$cur" in + Speaker) next="Headphones" ;; + Earpiece) next="Speaker" ;; + *) next="Earpiece" ;; + esac + fi else - case "$cur" in - Speaker) next="Earpiece" ;; - Earpiece) next="Headphones" ;; - *) next="Speaker" ;; - esac + if [ "$has_bt" = "1" ]; then + case "$cur" in + Bluetooth) next="Speaker" ;; + Speaker) next="Earpiece" ;; + Earpiece) next="Headphones" ;; + *) next="Bluetooth" ;; + esac + else + case "$cur" in + Speaker) next="Earpiece" ;; + Earpiece) next="Headphones" ;; + *) next="Speaker" ;; + esac + fi fi deviceset "$next" printf "%s\n" "$next" @@ -570,6 +673,7 @@ devicegetdefaultsource() { sourceset() { pactl set-default-source "$1" >/dev/null 2>&1 || true case "$1" in + bluez_input.*|*Bluetooth*) devicesetinput Bluetooth ;; *Headset*) devicesetinput Headset ;; *) devicesetinput Mic1 ;; esac @@ -578,6 +682,7 @@ sourceset() { sinkset() { pactl set-default-sink "$1" >/dev/null 2>&1 || true case "$1" in + bluez_output.*|*Bluetooth*) deviceset Bluetooth ;; *Earpiece*) deviceset Earpiece ;; *Headphones*) deviceset Headphones ;; *) deviceset Speaker ;; @@ -616,7 +721,7 @@ profileset() { _outportssubmenu() { active_out="$(deviceget)" - for dev in Speaker Earpiece Headphones; do + for dev in $(devicelist); do if [ "$active_out" = "$dev" ]; then icon="$icon_ton" else @@ -629,7 +734,7 @@ _outportssubmenu() { _inportssubmenu() { active_in="$(devicegetinput)" - for dev in Mic1 Headset; do + for dev in $(devicelistinput); do if [ "$active_in" = "$dev" ]; then icon="$icon_ton" else diff --git a/overlay/rootfs/usr/bin/sxmo_bluetoothtoggle.sh b/overlay/rootfs/usr/bin/sxmo_bluetoothtoggle.sh index f5f45e0..1893116 100755 --- a/overlay/rootfs/usr/bin/sxmo_bluetoothtoggle.sh +++ b/overlay/rootfs/usr/bin/sxmo_bluetoothtoggle.sh @@ -2,12 +2,15 @@ # SPDX-License-Identifier: AGPL-3.0-only # Copyright 2022 Sxmo Contributors -# Must be run as root +if [ "$(id -u)" != "0" ]; then + exec doas -n /usr/bin/sxmo_bluetoothtoggle.sh "$@" +fi . sxmo_common.sh on() { rfkill unblock bluetooth + modprobe -q uhid hidp uinput rfcomm bnep xpad 2>/dev/null || true if [ -d /run/systemd/system ]; then systemctl start bluetooth @@ -17,7 +20,34 @@ on() { rc-update add bluetooth fi sleep 0.4 - bluetoothctl power on >/dev/null 2>&1 || true + timeout 2 bluetoothctl power on >/dev/null 2>&1 || true + + bt_name="" + if [ -r /home/user/.config/sxmo/bt_name ]; then + IFS= read -r bt_name < /home/user/.config/sxmo/bt_name 2>/dev/null || true + fi + if [ -z "$bt_name" ]; then + bt_name="$(hostname 2>/dev/null || cat /etc/hostname 2>/dev/null || printf "Bananarchy")" + fi + if [ -n "$bt_name" ]; then + timeout 2 bluetoothctl system-alias "$bt_name" >/dev/null 2>&1 || true + fi + + bt_disc="1" + if [ -r /home/user/.config/sxmo/bt_discoverable ]; then + IFS= read -r bt_disc < /home/user/.config/sxmo/bt_discoverable 2>/dev/null || true + fi + timeout 2 bluetoothctl discoverable-timeout 0 >/dev/null 2>&1 || true + timeout 2 bluetoothctl pairable on >/dev/null 2>&1 || true + case "$bt_disc" in + 0|off|OFF|no|NO|false|FALSE) + timeout 2 bluetoothctl discoverable off >/dev/null 2>&1 || true + ;; + *) + timeout 2 bluetoothctl discoverable on >/dev/null 2>&1 || true + ;; + esac + /usr/bin/bananarchy-bt-obex start >/dev/null 2>&1 & } @@ -33,15 +63,22 @@ off() { rfkill block bluetooth } -case "$1" in +case "${1:-toggle}" in on) on ;; off) off ;; + status) + if rfkill list bluetooth -no ID,SOFT,HARD | grep -vq " blocked" && pidof -s bluetoothd >/dev/null 2>&1; then + echo "on" + else + echo "off" + fi + ;; *) # toggle - if rfkill list bluetooth -no ID,SOFT,HARD | grep -vq " blocked"; then + if rfkill list bluetooth -no ID,SOFT,HARD | grep -vq " blocked" && pidof -s bluetoothd >/dev/null 2>&1; then off else on diff --git a/overlay/rootfs/usr/bin/sxmo_common.sh b/overlay/rootfs/usr/bin/sxmo_common.sh index e70298e..7bf9bb2 100755 --- a/overlay/rootfs/usr/bin/sxmo_common.sh +++ b/overlay/rootfs/usr/bin/sxmo_common.sh @@ -28,6 +28,11 @@ export XDG_CONFIG_HOME="${XDG_CONFIG_HOME:-$HOME/.config}" export XDG_DATA_HOME="${XDG_DATA_HOME:-$HOME/.local/share}" export XDG_CACHE_HOME="${XDG_CACHE_HOME:-$HOME/.cache}" export XDG_STATE_HOME="${XDG_STATE_HOME:-$HOME/.local/state}" +export SXMO_CONTACTFILE="${SXMO_CONTACTFILE:-$XDG_CONFIG_HOME/sxmo/contacts.tsv}" +export SXMO_BLOCKFILE="${SXMO_BLOCKFILE:-$XDG_CONFIG_HOME/sxmo/block.tsv}" +export SXMO_BLOCKDIR="${SXMO_BLOCKDIR:-$XDG_DATA_HOME/sxmo/block}" +export SXMO_LOGDIR="${SXMO_LOGDIR:-$XDG_DATA_HOME/sxmo/modem}" +export SXMO_NOTIFDIR="${SXMO_NOTIFDIR:-$XDG_DATA_HOME/sxmo/notifications}" export LANG="${LANG:-C.UTF-8}" export LC_ALL="${LC_ALL:-C.UTF-8}" export XMODIFIERS="${XMODIFIERS:-@im=fcitx}" diff --git a/overlay/rootfs/usr/bin/sxmo_contacts.sh b/overlay/rootfs/usr/bin/sxmo_contacts.sh new file mode 100755 index 0000000..0c53e72 --- /dev/null +++ b/overlay/rootfs/usr/bin/sxmo_contacts.sh @@ -0,0 +1,143 @@ +#!/bin/sh +# SPDX-License-Identifier: AGPL-3.0-only +# Copyright 2022 Sxmo Contributors +# This script prints in reverse chronological order unique entries from the +# modem log merged with contact names defined in contacts file tsv. +# Wherein $SXMO_CONTACTFILE is tsv with two fields: number\tcontact name +# Wherein $LOGFILE is *sorted* tsv with three fields: date\tevt\tnumber +# +# Most normal numbers should be a full phone number starting with + and the country number +# Some special numbers (ie. 2222, "CR AGRICOLE") can ignore this pattern +# +# Prints in output format: "number: contact" + +# include common definitions +# shellcheck source=scripts/core/sxmo_common.sh +. sxmo_common.sh + +LOGFILE="$SXMO_LOGDIR"/modemlog.tsv + +prepare_contacts_list() { + cut -f3 | + tac | + awk '!($0 in a){a[$0]; print}' | + sed '/^[[:space:]]*$/d' | + awk -F '\t' -v SXMO_CONTACTFILE="$SXMO_CONTACTFILE" ' + function join(array, sep) { + result = "" + cs = "" + + for (i in array) { + if (length(result)) cs = sep; + result = result cs array[i] + } + + return result + } + + function name_for_num(num) { + if (!a[num]) a[num] = "???"; + return a[num] + } + + FILENAME == SXMO_CONTACTFILE { + if (!length()) next; + a[$1] = $2; + next + } + + # Multiple numbers, unknown group name + /(\+[^+]+){2,}/ && !a[$1] { + split("", names) # empty the names array + split($1, nums, "+") + + for (i in nums) { + num = nums[i] + if (length(num) == 0) continue; + + names[i] = name_for_num("+" num) + } + + print join(names, ", ") ": " $0 + next + } + + { + print name_for_num($1) ": " $0 + } + ' "$SXMO_CONTACTFILE" - +} + +contacts() { + prepare_contacts_list < "$LOGFILE" +} + +texted_contacts() { + grep "\(recv\|sent\)_\(txt\|mms\|vvm\)" "$LOGFILE" | prepare_contacts_list +} + +called_contacts() { + grep "call_\(pickup\|start\)" "$LOGFILE" | prepare_contacts_list +} + +all_contacts() { + awk -F'\t' '{ + print $2 ": " $1 + }' "$SXMO_CONTACTFILE" | sort -f -k 1 +} + +unknown_contacts() { + contacts \ + | grep "^???" \ + | cut -d: -f2 \ + | grep "^ +[0-9]\{9,14\}" \ + | sed 's/^ //' +} + +[ -f "$SXMO_CONTACTFILE" ] || touch "$SXMO_CONTACTFILE" + +if [ "$1" = "--all" ]; then + if [ "$2" = "--no-groups" ]; then + all_contacts | grep -v '+.*+' + else + all_contacts + fi +elif [ "$1" = "--no-groups" ]; then + contacts | grep -v '+.*+' +elif [ "$1" = "--unknown" ]; then + unknown_contacts +elif [ "$1" = "--texted" ]; then + texted_contacts +elif [ "$1" = "--called" ]; then + called_contacts +elif [ "$1" = "--me" ]; then + all_contacts \ + | grep "^Me: " \ + | sed 's|^Me: ||' +elif [ "$1" = "--name-or-number" ]; then + if [ -z "$2" ]; then + printf "???\n" + else + contact="$(sxmo_contacts.sh --name "$2")" + if [ "$contact" = "???" ] || [ -z "$contact" ]; then + contact="$2" + fi + printf %s "$contact" + fi +elif [ "$1" = "--name" ]; then + if [ -z "$2" ]; then + printf "???\n" + else + awk -F'\t' -v num="$2" ' + $1 == num { name = $2 } + END { + gsub(/^[ \t]+|[ \t]+$/, "", name) + print (length(name) ? name : "???") + } + ' "$SXMO_CONTACTFILE" + fi +elif [ -n "$*" ]; then + all_contacts | grep -i -F "$*" +else + contacts +fi diff --git a/overlay/rootfs/usr/bin/sxmo_modemsendsms.sh b/overlay/rootfs/usr/bin/sxmo_modemsendsms.sh index 114eeac..399701c 100755 --- a/overlay/rootfs/usr/bin/sxmo_modemsendsms.sh +++ b/overlay/rootfs/usr/bin/sxmo_modemsendsms.sh @@ -62,7 +62,7 @@ make_attachments_arg() { } if ! echo "$NUMBER" | grep -q '^+'; then - ACTUAL_NUMBER="$(sxmo_contacts.sh --all | grep "^$NUMBER:" | cut -d':' -f2 | sed 's/^ //')" + ACTUAL_NUMBER="$(sxmo_contacts.sh --all | awk -F': ' -v n="$NUMBER" '$1 == n {print $2; exit}')" if [ -z "$ACTUAL_NUMBER" ]; then info "WARNING: $NUMBER does not look like a phone number or a contact." else diff --git a/overlay/rootfs/usr/bin/sxmo_sdcard.sh b/overlay/rootfs/usr/bin/sxmo_sdcard.sh index d6d5ddb..17fd539 100755 --- a/overlay/rootfs/usr/bin/sxmo_sdcard.sh +++ b/overlay/rootfs/usr/bin/sxmo_sdcard.sh @@ -12,10 +12,15 @@ notify_user() { title="$1" body="$2" if command -v notify-send >/dev/null 2>&1; then + bus_addr="unix:path=/run/user/10000/bus" + if [ -r /run/user/10000/dbus.bus ]; then + IFS= read -r bus_line < /run/user/10000/dbus.bus 2>/dev/null || true + [ -n "$bus_line" ] && bus_addr="$bus_line" + fi if [ "$(id -u)" -eq 0 ]; then - su - user -c "DISPLAY=:0 DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/10000/bus notify-send '$title' '$body'" >/dev/null 2>&1 & + su - user -c "DISPLAY=:0 DBUS_SESSION_BUS_ADDRESS=\"$bus_addr\" notify-send \"$title\" \"$body\"" >/dev/null 2>&1 & else - DISPLAY="${DISPLAY:-:0}" notify-send "$title" "$body" >/dev/null 2>&1 & + DISPLAY="${DISPLAY:-:0}" DBUS_SESSION_BUS_ADDRESS="${DBUS_SESSION_BUS_ADDRESS:-$bus_addr}" notify-send "$title" "$body" >/dev/null 2>&1 & fi fi } @@ -79,26 +84,22 @@ probe_controller() { if [ -f /tmp/bananarchy_duress_mode ]; then return 1 fi - if [ -b /dev/mmcblk1 ]; then - return 0 - fi - if [ -w /sys/bus/platform/drivers/sdhci_msm/unbind ]; then - if [ -e /sys/bus/platform/drivers/sdhci_msm/7864900.sdhci ]; then + find_sd_disk >/dev/null 2>&1 && return 0 + if [ -w /sys/bus/platform/drivers/sdhci_msm/bind ]; then + if [ -e /sys/bus/platform/drivers/sdhci_msm/7864900.sdhci ] && [ -w /sys/bus/platform/drivers/sdhci_msm/unbind ]; then printf "7864900.sdhci" > /sys/bus/platform/drivers/sdhci_msm/unbind 2>/dev/null || true - sleep 0.2 + sleep 0.15 fi printf "7864900.sdhci" > /sys/bus/platform/drivers/sdhci_msm/bind 2>/dev/null || true + printf "auto" > /sys/devices/platform/soc@0/7864900.sdhci/power/control 2>/dev/null || true i=0 while [ "$i" -lt 12 ]; do - [ -b /dev/mmcblk1 ] && return 0 + find_sd_disk >/dev/null 2>&1 && return 0 sleep 0.1 i="$(( i + 1 ))" done - if [ ! -b /dev/mmcblk1 ]; then - printf "7864900.sdhci" > /sys/bus/platform/drivers/sdhci_msm/unbind 2>/dev/null || true - fi fi - [ -b /dev/mmcblk1 ] + find_sd_disk >/dev/null 2>&1 } do_mount() { @@ -107,7 +108,7 @@ do_mount() { return 1 fi if [ "$(id -u)" -ne 0 ]; then - exec doas /usr/bin/sxmo_sdcard.sh mount "$@" + exec doas -n /usr/bin/sxmo_sdcard.sh mount "$@" fi if is_mounted; then @@ -141,6 +142,7 @@ do_mount() { fi ;; exfat) + modprobe -q exfat 2>/dev/null || true if mount -t exfat -o "rw,nosuid,nodev,noatime,uid=${USER_UID},gid=${USER_GID},fmask=0022,dmask=0022" "$part" "$MOUNT_POINT" 2>/dev/null || \ mount -o "rw,nosuid,nodev,noatime,uid=${USER_UID},gid=${USER_GID}" "$part" "$MOUNT_POINT" 2>/dev/null; then mounted_ok=1 @@ -153,12 +155,15 @@ do_mount() { fi ;; ext4|ext3|ext2|f2fs|btrfs|xfs) + [ "$fstype" = "f2fs" ] && { modprobe -q f2fs 2>/dev/null || true; } + [ "$fstype" = "btrfs" ] && { modprobe -q btrfs 2>/dev/null || true; } if mount -o "rw,nosuid,nodev,noatime" "$part" "$MOUNT_POINT" 2>/dev/null; then mounted_ok=1 chown "${USER_UID}:${USER_GID}" "$MOUNT_POINT" 2>/dev/null || true fi ;; *) + modprobe -q exfat f2fs 2>/dev/null || true if mount -o "rw,nosuid,nodev,noatime,uid=${USER_UID},gid=${USER_GID}" "$part" "$MOUNT_POINT" 2>/dev/null || \ mount -o "rw,nosuid,nodev,noatime" "$part" "$MOUNT_POINT" 2>/dev/null; then mounted_ok=1 @@ -185,7 +190,7 @@ do_mount() { do_unmount() { if [ "$(id -u)" -ne 0 ]; then - exec doas /usr/bin/sxmo_sdcard.sh unmount "$@" + exec doas -n /usr/bin/sxmo_sdcard.sh unmount "$@" fi force_mode=0 @@ -226,7 +231,7 @@ do_rescan() { return 1 fi if [ "$(id -u)" -ne 0 ]; then - exec doas /usr/bin/sxmo_sdcard.sh rescan + exec doas -n /usr/bin/sxmo_sdcard.sh rescan fi probe_controller || true if find_sd_part >/dev/null 2>&1; then @@ -341,23 +346,21 @@ case "$cmd" in if [ -f /tmp/bananarchy_duress_mode ]; then exit 0 fi + if [ ! -e /sys/bus/platform/drivers/sdhci_msm/7864900.sdhci ] && [ -w /sys/bus/platform/drivers/sdhci_msm/bind ]; then + printf "7864900.sdhci" > /sys/bus/platform/drivers/sdhci_msm/bind 2>/dev/null || true + fi + printf "auto" > /sys/devices/platform/soc@0/7864900.sdhci/power/control 2>/dev/null || true if [ -n "$kname" ]; then do_mount "/dev/$kname" >/dev/null 2>&1 || true - else - if find_sd_part >/dev/null 2>&1; then - do_mount >/dev/null 2>&1 || true - elif [ -w /sys/bus/platform/drivers/sdhci_msm/unbind ]; then - printf "7864900.sdhci" > /sys/bus/platform/drivers/sdhci_msm/unbind 2>/dev/null || true - fi + elif find_sd_part >/dev/null 2>&1; then + do_mount >/dev/null 2>&1 || true fi ;; remove) if [ "$(id -u)" -eq 0 ]; then umount -l "$MOUNT_POINT" 2>/dev/null || true rm -f "$STATE_FILE" 2>/dev/null || true - if [ -w /sys/bus/platform/drivers/sdhci_msm/unbind ]; then - printf "7864900.sdhci" > /sys/bus/platform/drivers/sdhci_msm/unbind 2>/dev/null || true - fi + printf "auto" > /sys/devices/platform/soc@0/7864900.sdhci/power/control 2>/dev/null || true if [ ! -f /tmp/bananarchy_duress_mode ]; then notify_user "SD Card" "SD card removed" fi diff --git a/overlay/rootfs/usr/bin/tinydm-run-session b/overlay/rootfs/usr/bin/tinydm-run-session index 7ad6253..a1f4b59 100755 --- a/overlay/rootfs/usr/bin/tinydm-run-session +++ b/overlay/rootfs/usr/bin/tinydm-run-session @@ -75,7 +75,7 @@ run_session_x() { cmd_startx="$cmd_startx $arg" done - cmd_startx="$cmd_startx -- -nocursor -nolisten tcp vt1 -keeptty" + cmd_startx="$cmd_startx -- -nolisten tcp vt1 -keeptty" # shellcheck disable=SC2086 exec setpriv --ambient-caps '-all' $cmd_startx diff --git a/overlay/rootfs/usr/lib/dwm/plugins/dmenu.so b/overlay/rootfs/usr/lib/dwm/plugins/dmenu.so index fddf0ea..4718ea0 100755 Binary files a/overlay/rootfs/usr/lib/dwm/plugins/dmenu.so and b/overlay/rootfs/usr/lib/dwm/plugins/dmenu.so differ diff --git a/overlay/rootfs/usr/lib/dwm/plugins/files.so b/overlay/rootfs/usr/lib/dwm/plugins/files.so index ab64288..3d76e4f 100755 Binary files a/overlay/rootfs/usr/lib/dwm/plugins/files.so and b/overlay/rootfs/usr/lib/dwm/plugins/files.so differ diff --git a/overlay/rootfs/usr/lib/dwm/plugins/networks.so b/overlay/rootfs/usr/lib/dwm/plugins/networks.so index f0532f0..4241ae6 100755 Binary files a/overlay/rootfs/usr/lib/dwm/plugins/networks.so and b/overlay/rootfs/usr/lib/dwm/plugins/networks.so differ diff --git a/overlay/rootfs/usr/lib/dwm/plugins/xdrawer.so b/overlay/rootfs/usr/lib/dwm/plugins/xdrawer.so index ed85869..34824fe 100755 Binary files a/overlay/rootfs/usr/lib/dwm/plugins/xdrawer.so and b/overlay/rootfs/usr/lib/dwm/plugins/xdrawer.so differ diff --git a/overlay/rootfs/usr/lib/libneoui.so b/overlay/rootfs/usr/lib/libneoui.so index a2e1faa..874cc91 100755 Binary files a/overlay/rootfs/usr/lib/libneoui.so and b/overlay/rootfs/usr/lib/libneoui.so differ diff --git a/overlay/rootfs/usr/share/wireplumber/wireplumber.conf.d/50-bluetooth.conf b/overlay/rootfs/usr/share/wireplumber/wireplumber.conf.d/50-bluetooth.conf new file mode 100644 index 0000000..0f40c24 --- /dev/null +++ b/overlay/rootfs/usr/share/wireplumber/wireplumber.conf.d/50-bluetooth.conf @@ -0,0 +1,9 @@ +monitor.bluez.properties = { + bluez5.roles = [ a2dp_sink a2dp_source bap_sink bap_source hsp_hs hsp_ag hfp_hf hfp_ag ] + bluez5.codecs = [ sbc sbc_xq aac ldac aptx aptx_hd aptx_ll aptx_ll_duplex faststream faststream_duplex opus_05 opus_05_51 opus_05_71 opus_05_dup opus_05_pro lc3 ] + bluez5.enable-sbc-xq = true + bluez5.enable-msbc = true + bluez5.enable-hw-volume = true + bluez5.hfphsp-backend = "native" + bluez5.hfphsp-backend-native-modem = "any" +} diff --git a/prebuilt/games/usr/bin/gambatte b/prebuilt/games/usr/bin/gambatte index 72478ae..1de0e68 100755 Binary files a/prebuilt/games/usr/bin/gambatte and b/prebuilt/games/usr/bin/gambatte differ diff --git a/prebuilt/games/usr/bin/remedy b/prebuilt/games/usr/bin/remedy index e1a9c96..6c536b2 100755 Binary files a/prebuilt/games/usr/bin/remedy and b/prebuilt/games/usr/bin/remedy differ diff --git a/prebuilt/sxmo-x11/usr/bin/dwm b/prebuilt/sxmo-x11/usr/bin/dwm index 2f7f6b8..1ba4a11 100755 Binary files a/prebuilt/sxmo-x11/usr/bin/dwm and b/prebuilt/sxmo-x11/usr/bin/dwm differ diff --git a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/dmenu.so b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/dmenu.so index fddf0ea..4718ea0 100755 Binary files a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/dmenu.so and b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/dmenu.so differ diff --git a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/files.so b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/files.so index ab64288..3d76e4f 100755 Binary files a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/files.so and b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/files.so differ diff --git a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/networks.so b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/networks.so index f0532f0..4241ae6 100755 Binary files a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/networks.so and b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/networks.so differ diff --git a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/xdrawer.so b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/xdrawer.so index ed85869..34824fe 100755 Binary files a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/xdrawer.so and b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/xdrawer.so differ diff --git a/prebuilt/sxmo-x11/usr/lib/libneoui.so b/prebuilt/sxmo-x11/usr/lib/libneoui.so index a2e1faa..874cc91 100755 Binary files a/prebuilt/sxmo-x11/usr/lib/libneoui.so and b/prebuilt/sxmo-x11/usr/lib/libneoui.so differ diff --git a/scripts/build-dmenu.sh b/scripts/build-dmenu.sh index 6c76d63..8d570c8 100755 --- a/scripts/build-dmenu.sh +++ b/scripts/build-dmenu.sh @@ -16,7 +16,7 @@ exec docker run --rm --network=host \ -v "$ROOTFS_DIR:/target-rootfs" \ alpine:3.24 sh -eu -c ' cat > /etc/apk/repositories < /etc/apk/repositories < /etc/apk/repositories < queryBtSendTargets(bool scanFirst = false) { std::string rfk = runCaptureCmd("/usr/sbin/rfkill list bluetooth 2>/dev/null"); - if (rfk.find("Soft blocked: yes") != std::string::npos || + if (::access("/run/bluetoothd.pid", F_OK) != 0 || + rfk.find("Soft blocked: yes") != std::string::npos || rfk.find("Hard blocked: yes") != std::string::npos) { runCaptureCmd("SXMO_OS=alpine doas -n sxmo_bluetoothtoggle.sh on >/dev/null 2>&1"); } if (scanFirst) { - runCaptureCmd("bluetoothctl --timeout 4 scan on >/dev/null 2>&1"); + runCaptureCmd("timeout 5 bluetoothctl --timeout 4 scan on >/dev/null 2>&1"); } std::unordered_set pairedMacs; std::unordered_set connectedMacs; @@ -62,14 +63,14 @@ std::vector queryBtSendTargets(bool scanFirst = false) { } } }; - parseSet(runCaptureCmd("bluetoothctl devices Paired 2>/dev/null || " - "bluetoothctl paired-devices 2>/dev/null"), + parseSet(runCaptureCmd("timeout 2 bluetoothctl devices Paired 2>/dev/null || " + "timeout 2 bluetoothctl paired-devices 2>/dev/null"), pairedMacs); - parseSet(runCaptureCmd("bluetoothctl devices Connected 2>/dev/null"), + parseSet(runCaptureCmd("timeout 2 bluetoothctl devices Connected 2>/dev/null"), connectedMacs); std::vector out; - std::string allRaw = runCaptureCmd("bluetoothctl devices 2>/dev/null"); + std::string allRaw = runCaptureCmd("timeout 2 bluetoothctl devices 2>/dev/null"); std::istringstream ss(allRaw); std::string line; while (std::getline(ss, line)) { diff --git a/src/dwm-plugins/networks_plugin.cpp b/src/dwm-plugins/networks_plugin.cpp index eaa3c95..1f772b5 100644 --- a/src/dwm-plugins/networks_plugin.cpp +++ b/src/dwm-plugins/networks_plugin.cpp @@ -38,6 +38,20 @@ enum class NetModal { WifiPassword = 2, ApnEditor = 3, BtActions = 4, + BtNameEditor = 5, +}; + +constexpr const char* kIconHeadphones = "\xef\x80\xa5"; // U+F025 headphones +constexpr const char* kIconKeyboard = "\xef\x84\x9c"; // U+F11C keyboard +constexpr const char* kIconMouse = "\xef\x89\x85"; // U+F245 mouse pointer + +enum class BtDevKind { + Generic = 0, + Audio = 1, + Gamepad = 2, + Keyboard = 3, + Mouse = 4, + Phone = 5, }; enum class TextMode { @@ -109,8 +123,76 @@ struct BtDeviceEntry { std::string name; bool paired = false; bool connected = false; + BtDevKind kind = BtDevKind::Generic; + std::string profileLabel; + int batteryPct = -1; }; +struct BtControllerState { + std::string name = "Bananarchy"; + bool discoverable = true; + int activeCount = 0; + std::string activeSummary; +}; + +std::string getSystemHostname() { + char buf[128] = {}; + if (::gethostname(buf, sizeof(buf) - 1) == 0 && buf[0] != '\0') { + std::string h = trimStr(buf); + if (!h.empty()) return h; + } + std::ifstream in("/etc/hostname"); + std::string line; + if (in.is_open() && std::getline(in, line)) { + line = trimStr(line); + if (!line.empty()) return line; + } + return "Bananarchy"; +} + +std::string readSavedBtName() { + std::string path = getHomeDirPath() + "/.config/sxmo/bt_name"; + std::ifstream in(path); + std::string line; + if (in.is_open() && std::getline(in, line)) { + line = trimStr(line); + if (!line.empty()) return line; + } + return getSystemHostname(); +} + +void writeSavedBtName(const std::string& name) { + std::string dir = getHomeDirPath() + "/.config/sxmo"; + ::mkdir(dir.c_str(), 0755); + std::ofstream out(dir + "/bt_name", std::ios::trunc); + if (out.is_open()) { + out << name << "\n"; + } +} + +bool readSavedBtDiscoverable() { + std::string path = getHomeDirPath() + "/.config/sxmo/bt_discoverable"; + std::ifstream in(path); + std::string line; + if (in.is_open() && std::getline(in, line)) { + std::string v = toLowerStr(trimStr(line)); + if (v == "0" || v == "off" || v == "no" || v == "false") { + return false; + } + if (!v.empty()) return true; + } + return true; +} + +void writeSavedBtDiscoverable(bool disc) { + std::string dir = getHomeDirPath() + "/.config/sxmo"; + ::mkdir(dir.c_str(), 0755); + std::ofstream out(dir + "/bt_discoverable", std::ios::trunc); + if (out.is_open()) { + out << (disc ? "1\n" : "0\n"); + } +} + struct BtRxStatus { std::string state = "IDLE"; std::string fileName; @@ -162,6 +244,9 @@ bool isWifiEnabledFast() { } bool isBtEnabledFast() { + if (::access("/run/bluetoothd.pid", F_OK) != 0) { + return false; + } std::string out = runCaptureCmd("/usr/sbin/rfkill list bluetooth 2>/dev/null"); if (out.find("Soft blocked: yes") != std::string::npos || out.find("Hard blocked: yes") != std::string::npos) { @@ -324,6 +409,17 @@ CellularNetInfo queryCellularInfo() { return info; } +const char* iconForBtDevice(const BtDeviceEntry& d) { + switch (d.kind) { + case BtDevKind::Audio: return kIconHeadphones; + case BtDevKind::Gamepad: return kIconGamepad; + case BtDevKind::Keyboard: return kIconKeyboard; + case BtDevKind::Mouse: return kIconMouse; + case BtDevKind::Phone: return kIconPhone; + default: return kIconBluetooth; + } +} + std::vector queryBtDevices() { std::vector out; std::unordered_set pairedMacs; @@ -334,22 +430,27 @@ std::vector queryBtDevices() { std::istringstream ss(raw); std::string line; while (std::getline(ss, line)) { - // Format: "Device XX:XX:XX:XX:XX:XX Name..." if (line.rfind("Device ", 0) == 0 && line.size() >= 24) { dst.insert(line.substr(7, 17)); } } }; - parseMacSet(runCaptureCmd("bluetoothctl devices Paired 2>/dev/null || " - "bluetoothctl paired-devices 2>/dev/null"), + parseMacSet(runCaptureCmd("timeout 2 bluetoothctl devices Paired 2>/dev/null || " + "timeout 2 bluetoothctl paired-devices 2>/dev/null"), pairedMacs); - parseMacSet(runCaptureCmd("bluetoothctl devices Connected 2>/dev/null"), + parseMacSet(runCaptureCmd("timeout 2 bluetoothctl devices Connected 2>/dev/null"), connectedMacs); - std::string allRaw = runCaptureCmd("bluetoothctl devices 2>/dev/null"); + std::string paRaw = runCaptureCmd( + "pactl list sinks short 2>/dev/null; pactl list sources short 2>/dev/null"); + + std::string allRaw = runCaptureCmd("timeout 2 bluetoothctl devices 2>/dev/null"); std::istringstream ss(allRaw); std::string line; + std::string infoCmd; + int infoCount = 0; + while (std::getline(ss, line)) { if (line.rfind("Device ", 0) != 0 || line.size() < 24) continue; BtDeviceEntry d; @@ -358,6 +459,115 @@ std::vector queryBtDevices() { d.paired = (pairedMacs.count(d.mac) > 0); d.connected = (connectedMacs.count(d.mac) > 0); out.push_back(d); + if ((d.connected || d.paired) && infoCount < 12) { + infoCmd += "printf '===BTDEV %s===\\n' " + shellQuote(d.mac) + + "; timeout 1 bluetoothctl info " + shellQuote(d.mac) + + " 2>/dev/null; "; + ++infoCount; + } + } + + std::unordered_map infoByMac; + if (!infoCmd.empty()) { + std::string batchInfo = runCaptureCmd(infoCmd); + std::istringstream iss(batchInfo); + std::string iline; + std::string curMac; + while (std::getline(iss, iline)) { + if (iline.rfind("===BTDEV ", 0) == 0 && iline.size() >= 26) { + curMac = iline.substr(9, 17); + } else if (!curMac.empty()) { + infoByMac[curMac] += iline + "\n"; + } + } + } + + for (auto& d : out) { + std::string macU = d.mac; + for (char& c : macU) { + if (c == ':') c = '_'; + } + bool hasPaSink = (paRaw.find("bluez_output." + macU) != std::string::npos); + bool hasPaSrc = (paRaw.find("bluez_input." + macU) != std::string::npos); + + std::string info = infoByMac[d.mac]; + std::string infoLow = toLowerStr(info); + std::string nameLow = toLowerStr(d.name); + + bool hasA2dp = (infoLow.find("0000110b-") != std::string::npos || + infoLow.find("0000110a-") != std::string::npos || + infoLow.find("audio sink") != std::string::npos || + infoLow.find("audio source") != std::string::npos); + bool hasHfp = (infoLow.find("00001108-") != std::string::npos || + infoLow.find("00001112-") != std::string::npos || + infoLow.find("0000111e-") != std::string::npos || + infoLow.find("0000111f-") != std::string::npos || + infoLow.find("handsfree") != std::string::npos || + infoLow.find("headset") != std::string::npos); + bool hasHid = (infoLow.find("00001124-") != std::string::npos || + infoLow.find("00001812-") != std::string::npos || + infoLow.find("human interface device") != std::string::npos); + + if (infoLow.find("icon: input-gaming") != std::string::npos || + infoLow.find("icon: input-joystick") != std::string::npos || + nameLow.find("gamepad") != std::string::npos || + nameLow.find("controller") != std::string::npos || + nameLow.find("joy-con") != std::string::npos || + nameLow.find("dualshock") != std::string::npos || + nameLow.find("dualsense") != std::string::npos || + nameLow.find("8bitdo") != std::string::npos || + nameLow.find("xbox") != std::string::npos) { + d.kind = BtDevKind::Gamepad; + d.profileLabel = "HID Gamepad"; + } else if (infoLow.find("icon: input-keyboard") != std::string::npos || + nameLow.find("keyboard") != std::string::npos || + nameLow.find("keychron") != std::string::npos) { + d.kind = BtDevKind::Keyboard; + d.profileLabel = "HID Keyboard"; + } else if (infoLow.find("icon: input-mouse") != std::string::npos || + infoLow.find("icon: input-tablet") != std::string::npos || + nameLow.find("mouse") != std::string::npos || + nameLow.find("trackpad") != std::string::npos) { + d.kind = BtDevKind::Mouse; + d.profileLabel = "HID Mouse"; + } else if (hasPaSink || hasPaSrc || hasA2dp || hasHfp || + infoLow.find("icon: audio-") != std::string::npos) { + d.kind = BtDevKind::Audio; + if (d.connected) { + if (hasPaSrc) { + d.profileLabel = "HSP/HFP"; + } else if (hasPaSink) { + d.profileLabel = "A2DP"; + } else if (hasA2dp && hasHfp) { + d.profileLabel = "A2DP+HFP"; + } else if (hasHfp) { + d.profileLabel = "HSP/HFP"; + } else { + d.profileLabel = "A2DP"; + } + } else { + if (hasA2dp && hasHfp) d.profileLabel = "Audio A2DP/HFP"; + else if (hasHfp) d.profileLabel = "Audio HSP/HFP"; + else d.profileLabel = "Audio A2DP"; + } + } else if (hasHid) { + d.kind = BtDevKind::Keyboard; + d.profileLabel = "HID Input"; + } else if (infoLow.find("icon: phone") != std::string::npos || + infoLow.find("icon: computer") != std::string::npos) { + d.kind = BtDevKind::Phone; + d.profileLabel = "OBEX/PAN"; + } + + size_t batPos = info.find("Battery Percentage:"); + if (batPos != std::string::npos) { + size_t lp = info.find('(', batPos); + size_t rp = info.find(')', batPos); + if (lp != std::string::npos && rp != std::string::npos && rp > lp + 1) { + d.batteryPct = std::clamp( + std::atoi(info.substr(lp + 1, rp - lp - 1).c_str()), 0, 100); + } + } } std::sort(out.begin(), out.end(), @@ -369,6 +579,48 @@ std::vector queryBtDevices() { return out; } +BtControllerState queryBtController(bool btOn, + const std::vector& devs) { + BtControllerState st; + st.name = readSavedBtName(); + st.discoverable = readSavedBtDiscoverable(); + + if (btOn) { + std::string showOut = runCaptureCmd("timeout 2 bluetoothctl show 2>/dev/null"); + std::istringstream ss(showOut); + std::string line; + while (std::getline(ss, line)) { + std::string t = trimStr(line); + if (t.rfind("Discoverable:", 0) == 0) { + std::string v = toLowerStr(trimStr(t.substr(13))); + if (v == "yes") st.discoverable = true; + else if (v == "no") st.discoverable = false; + } else if (t.rfind("Alias:", 0) == 0) { + std::string al = trimStr(t.substr(6)); + if (!al.empty() && al.rfind("BlueZ", 0) != 0 && + ::access((getHomeDirPath() + "/.config/sxmo/bt_name").c_str(), F_OK) != 0) { + st.name = al; + } + } + } + } + + for (const auto& d : devs) { + if (!d.connected) continue; + ++st.activeCount; + std::string item = d.name; + if (!d.profileLabel.empty()) { + item += " (" + d.profileLabel + ")"; + } + if (st.activeSummary.empty()) { + st.activeSummary = item; + } else { + st.activeSummary += ", " + item; + } + } + return st; +} + int runNetworksApp(int argc, char** argv) { gRunning = 1; std::setlocale(LC_ALL, ""); @@ -448,8 +700,10 @@ int runNetworksApp(int argc, char** argv) { bool btOn = false; std::vector btList; + BtControllerState btCtrl; BtRxStatus btRx; - int btRowSel = 0; // 0 = BT Power Toggle, 1 = Scan Devices, 2 = File Reception Widget, 3..N = BT devices + std::string btNameEdit; + int btRowSel = 0; // 0=Power, 1=Discoverable, 2=Device Name, 3=Scan, 4=OBEX Rx, 5..N=Devices int actionSel = 0; @@ -503,16 +757,19 @@ int runNetworksApp(int argc, char** argv) { } else if (activeTab == NetTab::Bluetooth) { btOn = isBtEnabledFast(); if (btOn) { - runAsyncCmd("/usr/bin/bananarchy-bt-obex start >/dev/null 2>&1"); + if (::access("/tmp/bananarchy_bt_obex.pid", F_OK) != 0) { + runAsyncCmd("/usr/bin/bananarchy-bt-obex start >/dev/null 2>&1"); + } btRx = readBtRxStatus(); if (forceScan) { - runCaptureCmd("bluetoothctl --timeout 5 scan on >/dev/null 2>&1"); + runCaptureCmd("timeout 6 bluetoothctl --timeout 5 scan on >/dev/null 2>&1"); } btList = queryBtDevices(); } else { btList.clear(); } - int maxRow = btOn ? (2 + static_cast(btList.size())) : 1; + btCtrl = queryBtController(btOn, btList); + int maxRow = btOn ? (4 + static_cast(btList.size())) : 2; if (btRowSel > maxRow) btRowSel = maxRow; } }; @@ -729,96 +986,146 @@ int runNetworksApp(int argc, char** argv) { } drawSoftkeyBar("Refresh", "Select", "Close"); } else if (activeTab == NetTab::Bluetooth) { - // Row 0: BT Power Toggle (height 26) + // Row 0: BT Power Toggle + Active Connection Badge (height 22) bool sel0 = (btRowSel == 0); XSetForeground(dpy, gc, sel0 ? pt.spec.selBg : pt.spec.bgAltEven); - XFillRectangle(dpy, pix, gc, 4, contentY, kWinWidth - 8, 26); - drawPango(layoutIcon, btOn ? &colBlue : &colMuted, 10, contentY, 26, kIconBluetooth); - drawPango(layoutMain, sel0 ? &colWhite : &colLight, - 30, contentY, 26, std::string("Bluetooth: ") + (btOn ? "ON" : "OFF")); + XFillRectangle(dpy, pix, gc, 4, contentY, kWinWidth - 8, 22); + drawPango(layoutIcon, btOn ? &colBlue : &colMuted, 10, contentY, 22, kIconBluetooth); + std::string btPowerLbl = std::string("Bluetooth: ") + (btOn ? "ON" : "OFF"); + if (btOn) { + btPowerLbl += (btCtrl.activeCount > 0) + ? (" (" + std::to_string(btCtrl.activeCount) + " Active)") + : " (Idle)"; + } + drawPango(layoutSmall, sel0 ? &colWhite : (btCtrl.activeCount > 0 ? &colGreen : &colLight), + 28, contentY, 22, btPowerLbl, kWinWidth - 58); drawPango(layoutIcon, btOn ? &colGreen : &colMuted, - kWinWidth - 28, contentY, 26, btOn ? kIconToggleOn : kIconToggleOff); + kWinWidth - 26, contentY, 22, btOn ? kIconToggleOn : kIconToggleOff); - // Row 1: Scan for Devices (height 24) + // Row 1: Discoverability Toggle (height 22) bool sel1 = (btRowSel == 1); + int r1Y = contentY + 23; XSetForeground(dpy, gc, sel1 ? pt.spec.selBg : pt.spec.bgAltOdd); - XFillRectangle(dpy, pix, gc, 4, contentY + 28, kWinWidth - 8, 24); - drawPango(layoutIcon, &colYellow, 10, contentY + 28, 24, kIconSearch); + XFillRectangle(dpy, pix, gc, 4, r1Y, kWinWidth - 8, 22); + drawPango(layoutIcon, btCtrl.discoverable ? &colGreen : &colMuted, + 10, r1Y, 22, kIconEye); drawPango(layoutSmall, sel1 ? &colWhite : &colLight, - 30, contentY + 28, 24, "Scan for Bluetooth Devices"); + 28, r1Y, 22, + std::string("Discoverable: ") + + (btCtrl.discoverable ? "ON (Visible)" : "OFF (Hidden)"), + kWinWidth - 58); + drawPango(layoutIcon, btCtrl.discoverable ? &colGreen : &colMuted, + kWinWidth - 26, r1Y, 22, + btCtrl.discoverable ? kIconToggleOn : kIconToggleOff); + + // Row 2: Bluetooth Device Name (height 22) + bool sel2 = (btRowSel == 2); + int r2Y = contentY + 46; + XSetForeground(dpy, gc, sel2 ? pt.spec.selBg : pt.spec.bgAltEven); + XFillRectangle(dpy, pix, gc, 4, r2Y, kWinWidth - 8, 22); + drawPango(layoutIcon, &colYellow, 10, r2Y, 22, kIconEdit); + drawPango(layoutSmall, sel2 ? &colWhite : &colLight, + 28, r2Y, 22, "Name: " + btCtrl.name, kWinWidth - 66); + drawPango(layoutSmall, sel2 ? &colYellow : &colMuted, + kWinWidth - 38, r2Y, 22, "[Edit]"); if (!btOn) { - drawPango(layoutMain, &colMuted, 18, contentY + 96, 24, + drawPango(layoutMain, &colMuted, 18, contentY + 102, 24, "Bluetooth is turned off."); + drawPango(layoutSmall, &colMuted, 18, contentY + 128, 20, + "Visibility & Name apply on start."); } else { - // Row 2: Bluetooth File Reception Widget (height 36) - bool sel2 = (btRowSel == 2); - int rxY = contentY + 54; - XSetForeground(dpy, gc, sel2 ? pt.spec.selBg : pt.spec.bgHeader); - XFillRectangle(dpy, pix, gc, 4, rxY, kWinWidth - 8, 36); + // Row 3: Scan for Devices + Active Summary (height 22) + bool sel3 = (btRowSel == 3); + int r3Y = contentY + 69; + XSetForeground(dpy, gc, sel3 ? pt.spec.selBg : pt.spec.bgAltOdd); + XFillRectangle(dpy, pix, gc, 4, r3Y, kWinWidth - 8, 22); + drawPango(layoutIcon, &colYellow, 10, r3Y, 22, kIconSearch); + std::string scanLbl = (btCtrl.activeCount > 0) + ? ("Scan [Active: " + btCtrl.activeSummary + "]") + : "Scan for Bluetooth Devices"; + drawPango(layoutSmall, sel3 ? &colWhite : (btCtrl.activeCount > 0 ? &colGreen : &colLight), + 28, r3Y, 22, scanLbl, kWinWidth - 34); + + // Row 4: Compact OBEX File Reception Bar (height 22) + bool sel4 = (btRowSel == 4); + int rxY = contentY + 92; + XSetForeground(dpy, gc, sel4 ? pt.spec.selBg : pt.spec.bgHeader); + XFillRectangle(dpy, pix, gc, 4, rxY, kWinWidth - 8, 22); XSetForeground(dpy, gc, btRx.state == "RECEIVING" ? pt.spec.warning - : (btRx.state == "RECEIVED" ? pt.spec.success : pt.spec.accent)); - XDrawRectangle(dpy, pix, gc, 4, rxY, kWinWidth - 9, 35); + : (btRx.state == "RECEIVED" ? pt.spec.success : pt.spec.border)); + XDrawRectangle(dpy, pix, gc, 4, rxY, kWinWidth - 9, 21); drawPango(layoutIcon, btRx.state == "RECEIVED" ? &colGreen : (btRx.state == "RECEIVING" ? &colYellow : &colBlue), - 10, rxY + 1, 18, + 10, rxY, 22, btRx.state == "RECEIVED" ? kIconCheck : kIconFolderOpen); if (btRx.state == "RECEIVING") { - drawPango(layoutSmall, &colYellow, 30, rxY + 1, 18, - "Receiving: " + btRx.fileName + " (" + btRx.detail + ")", - kWinWidth - 38); - int barW = kWinWidth - 42; - XSetForeground(dpy, gc, pt.spec.bgInput); - XFillRectangle(dpy, pix, gc, 30, rxY + 22, barW, 8); - int fillW = (barW * std::clamp(btRx.pct, 0, 100)) / 100; - XSetForeground(dpy, gc, pt.spec.success); - XFillRectangle(dpy, pix, gc, 30, rxY + 22, fillW, 8); + drawPango(layoutSmall, &colYellow, 28, rxY, 22, + "Rx: " + btRx.fileName + " (" + btRx.detail + ")", + kWinWidth - 34); } else if (btRx.state == "RECEIVED") { - drawPango(layoutSmall, &colGreen, 30, rxY + 1, 18, - "Received: " + btRx.fileName, kWinWidth - 38); - drawPango(layoutSmall, sel2 ? &colWhite : &colLight, 30, rxY + 18, 16, - btRx.detail + " [OK: Open in Files]", kWinWidth - 38); + drawPango(layoutSmall, sel4 ? &colWhite : &colGreen, 28, rxY, 22, + "Received: " + btRx.fileName + " [Open]", + kWinWidth - 34); } else { - drawPango(layoutSmall, sel2 ? &colWhite : &colYellow, 30, rxY + 1, 18, - "File Receive: Ready (OBEX Push)", kWinWidth - 38); - drawPango(layoutSmall, sel2 ? &colLight : &colMuted, 30, rxY + 18, 16, - "Saves to ~/Downloads [OK: Open]", kWinWidth - 38); + drawPango(layoutSmall, sel4 ? &colWhite : &colMuted, 28, rxY, 22, + "OBEX Receive: ~/Downloads [Open]", + kWinWidth - 34); } - int listY = contentY + 92; - int listH = contentH - 92; + int listY = contentY + 116; + int listH = contentH - 116; if (btList.empty()) { - drawPango(layoutMain, &colMuted, 18, listY + 34, 24, - "No devices. Select Scan."); + drawPango(layoutSmall, &colMuted, 18, listY + 30, 22, + "No devices found. Press Scan."); } else { - const int rowH = 36; - const int maxVis = std::max(1, listH / rowH); - int devSel = std::max(0, btRowSel - 3); + const int rowH = 38; + const int maxVis = std::max(1, listH / rowH); // 3 rows + int devSel = std::max(0, btRowSel - 5); int startIdx = std::clamp(devSel - maxVis / 2, 0, std::max(0, static_cast(btList.size()) - maxVis)); for (int i = 0; i < maxVis && (startIdx + i) < static_cast(btList.size()); ++i) { int idx = startIdx + i; const auto& d = btList[idx]; int ry = listY + i * rowH; - bool isSel = (btRowSel == (idx + 3)); + bool isSel = (btRowSel == (idx + 5)); XSetForeground(dpy, gc, isSel ? pt.spec.selBg : ((i % 2 == 0) ? pt.spec.bgAltEven : pt.spec.bgAltOdd)); XFillRectangle(dpy, pix, gc, 4, ry, kWinWidth - 8, rowH - 2); + if (d.connected) { + XSetForeground(dpy, gc, pt.spec.success); + XDrawRectangle(dpy, pix, gc, 4, ry, kWinWidth - 9, rowH - 3); + } drawPango(layoutIcon, d.connected ? &colGreen : (d.paired ? &colBlue : &colMuted), - 10, ry + 1, 18, kIconBluetooth); + 10, ry + 1, 18, iconForBtDevice(d)); + int nameMaxW = (d.batteryPct >= 0) ? (kWinWidth - 76) : (kWinWidth - 38); drawPango(layoutMain, isSel ? &colWhite : &colLight, - 30, ry + 1, 18, d.name, kWinWidth - 42); + 28, ry + 1, 18, d.name, nameMaxW); + if (d.batteryPct >= 0) { + std::string batStr = std::to_string(d.batteryPct) + "%"; + drawPango(layoutSmall, &colGreen, kWinWidth - 40, ry + 2, 16, batStr); + } - std::string st = d.connected ? "[Connected] " - : (d.paired ? "[Paired] " : "[Available] "); + std::string st; + if (d.connected) { + st = "[ACTIVE: " + + (d.profileLabel.empty() ? std::string("Connected") : d.profileLabel) + + "] "; + } else if (d.paired) { + st = "[Paired" + + (d.profileLabel.empty() ? std::string("") : (": " + d.profileLabel)) + + "] "; + } else { + st = "[Available] "; + } st += d.mac; drawPango(layoutSmall, d.connected ? &colGreen : (isSel ? &colLight : &colMuted), - 30, ry + 18, 16, st, kWinWidth - 42); + 28, ry + 19, 16, st, kWinWidth - 36); } } } @@ -938,26 +1245,69 @@ int runNetworksApp(int argc, char** argv) { drawSoftkeyBar("Save", "Select", "Cancel"); } else if (modal == NetModal::BtActions) { XSetForeground(dpy, gc, pt.spec.bgOverlay); - XFillRectangle(dpy, pix, gc, 12, 48, kWinWidth - 24, 174); + XFillRectangle(dpy, pix, gc, 10, 40, kWinWidth - 20, 194); XSetForeground(dpy, gc, pt.spec.accent); - XDrawRectangle(dpy, pix, gc, 12, 48, kWinWidth - 25, 173); + XDrawRectangle(dpy, pix, gc, 10, 40, kWinWidth - 21, 193); - drawPango(layoutMain, &colYellow, 20, 52, 24, targetBt.name, kWinWidth - 40); - const char* acts[4] = { + drawPango(layoutMain, &colYellow, 18, 44, 22, targetBt.name, kWinWidth - 36); + const char* acts[5] = { "Connect Device", "Disconnect Device", "Pair & Trust Device", + "Switch Audio (A2DP / HSP-HFP)", "Forget / Remove Device", }; - for (int i = 0; i < 4; ++i) { - int ry = 82 + i * 32; + for (int i = 0; i < 5; ++i) { + int ry = 70 + i * 31; bool isSel = (actionSel == i); XSetForeground(dpy, gc, isSel ? pt.spec.selBg : pt.spec.bgButton); - XFillRectangle(dpy, pix, gc, 18, ry, kWinWidth - 36, 28); + XFillRectangle(dpy, pix, gc, 16, ry, kWinWidth - 32, 27); drawPango(layoutSmall, isSel ? &colWhite : &colLight, - 24, ry, 28, acts[i], kWinWidth - 48); + 22, ry, 27, acts[i], kWinWidth - 44); } drawSoftkeyBar("Select", "OK", "Back"); + } else if (modal == NetModal::BtNameEditor) { + XSetForeground(dpy, gc, pt.spec.bgOverlay); + XFillRectangle(dpy, pix, gc, 10, 42, kWinWidth - 20, 198); + XSetForeground(dpy, gc, pt.spec.accent); + XDrawRectangle(dpy, pix, gc, 10, 42, kWinWidth - 21, 197); + + drawPango(layoutMain, &colYellow, 18, 48, 22, + "Bluetooth Name", kWinWidth - 80); + drawPango(layoutSmall, &colBlue, kWinWidth - 58, 48, 22, + std::string("[") + textModeLabel() + "]"); + + drawPango(layoutSmall, &colLight, 18, 74, 20, + "Visible name on other devices:"); + + XSetForeground(dpy, gc, pt.spec.bgInputFocus); + XFillRectangle(dpy, pix, gc, 18, 98, kWinWidth - 36, 34); + XSetForeground(dpy, gc, pt.spec.accent); + XDrawRectangle(dpy, pix, gc, 18, 98, kWinWidth - 37, 33); + + std::string dispFit = + tailFitPangoText(layoutMain, btNameEdit + "_", kWinWidth - 48); + drawPango(layoutMain, &colWhite, 24, 98, 34, dispFit, kWinWidth - 48); + + if (lastTapDigit >= 0 && lastTapDigit <= 9 && + (nowMs() - lastTapMs) <= 850) { + const char* seq = (textMode == TextMode::Sym) + ? kSymTapMap[lastTapDigit] + : kMultiTapMap[lastTapDigit]; + std::string cand = formatMultiTapBar( + std::to_string(lastTapDigit) + ":", seq, lastTapCycle, + textMode == TextMode::Upper, 6, 19); + drawPango(layoutSmall, &colYellow, 18, 142, 18, cand, kWinWidth - 36); + } else { + drawPango(layoutSmall, &colMuted, 18, 142, 18, + "# Input mode", kWinWidth - 36); + } + drawPango(layoutSmall, &colMuted, 18, 162, 18, + "[BackSpace] Delete character"); + drawPango(layoutSmall, &colMuted, 18, 182, 18, + "Independent from system hostname"); + + drawSoftkeyBar("Save", "Save", "Cancel"); } if (!statusBanner.empty() && nowMs() < statusBannerUntilMs) { @@ -1113,35 +1463,96 @@ int runNetworksApp(int argc, char** argv) { } }; + auto saveBtDeviceName = [&]() { + std::string clean = trimStr(btNameEdit); + if (clean.empty()) { + clean = getSystemHostname(); + } + modal = NetModal::None; + writeSavedBtName(clean); + btCtrl.name = clean; + if (btOn) { + runCaptureCmd("timeout 2 bluetoothctl system-alias " + shellQuote(clean) + + " >/dev/null 2>&1"); + } + refreshCurrentTab(false); + setBanner("Bluetooth name: " + clean); + }; + + auto toggleBtDiscoverable = [&]() { + bool nextDisc = !btCtrl.discoverable; + writeSavedBtDiscoverable(nextDisc); + btCtrl.discoverable = nextDisc; + if (btOn) { + runCaptureCmd("timeout 2 bluetoothctl discoverable-timeout 0 >/dev/null 2>&1; " + "timeout 2 bluetoothctl discoverable " + + std::string(nextDisc ? "on" : "off") + " >/dev/null 2>&1"); + } + refreshCurrentTab(false); + setBanner(nextDisc ? "Bluetooth: Visible to nearby devices" + : "Bluetooth: Hidden from discovery"); + }; + auto executeBtAction = [&](int act) { modal = NetModal::None; int rc = 0; if (act == 0) { setBanner("Connecting " + targetBt.name + "..."); render(); - runCaptureCmd("bluetoothctl connect " + shellQuote(targetBt.mac) + + runCaptureCmd("timeout 8 bluetoothctl connect " + shellQuote(targetBt.mac) + " >/dev/null 2>&1", &rc); refreshCurrentTab(false); + if (rc == 0 && targetBt.kind == BtDevKind::Audio) { + runAsyncCmd("sxmo_audio.sh device set Bluetooth >/dev/null 2>&1"); + } setBanner(rc == 0 ? ("Connected: " + targetBt.name) : "Connect failed"); } else if (act == 1) { setBanner("Disconnecting " + targetBt.name + "..."); render(); - runCaptureCmd("bluetoothctl disconnect " + shellQuote(targetBt.mac) + + runCaptureCmd("timeout 4 bluetoothctl disconnect " + shellQuote(targetBt.mac) + " >/dev/null 2>&1", &rc); refreshCurrentTab(false); setBanner("Disconnected " + targetBt.name); } else if (act == 2) { setBanner("Pairing " + targetBt.name + "..."); render(); - runCaptureCmd("bluetoothctl --timeout 8 pair " + shellQuote(targetBt.mac) + - " >/dev/null 2>&1; bluetoothctl trust " + + runCaptureCmd("timeout 10 bluetoothctl --timeout 8 pair " + + shellQuote(targetBt.mac) + + " >/dev/null 2>&1; timeout 2 bluetoothctl trust " + shellQuote(targetBt.mac) + " >/dev/null 2>&1; " - "bluetoothctl connect " + shellQuote(targetBt.mac) + + "timeout 6 bluetoothctl connect " + shellQuote(targetBt.mac) + " >/dev/null 2>&1", &rc); refreshCurrentTab(false); setBanner("Paired & trusted " + targetBt.name); } else if (act == 3) { - runCaptureCmd("bluetoothctl remove " + shellQuote(targetBt.mac) + + std::string macU = targetBt.mac; + for (char& c : macU) { + if (c == ':') c = '_'; + } + std::string card = "bluez_card." + macU; + bool wantHfp = (targetBt.profileLabel.find("HSP") == std::string::npos && + targetBt.profileLabel.find("HFP") == std::string::npos); + setBanner(std::string("Switching to ") + (wantHfp ? "HSP/HFP..." : "A2DP...")); + render(); + if (wantHfp) { + runCaptureCmd("pactl set-card-profile " + shellQuote(card) + + " headset-head-unit >/dev/null 2>&1 || " + "pactl set-card-profile " + shellQuote(card) + + " headset-head-unit-msbc >/dev/null 2>&1 || " + "pactl set-card-profile " + shellQuote(card) + + " headset-head-unit-cvsd >/dev/null 2>&1", &rc); + runAsyncCmd("sxmo_audio.sh device set Bluetooth >/dev/null 2>&1; " + "sxmo_audio.sh device setinput Bluetooth >/dev/null 2>&1"); + } else { + runCaptureCmd("pactl set-card-profile " + shellQuote(card) + + " a2dp-sink >/dev/null 2>&1", &rc); + runAsyncCmd("sxmo_audio.sh device set Bluetooth >/dev/null 2>&1"); + } + refreshCurrentTab(false); + setBanner(rc == 0 ? (std::string("Audio profile: ") + (wantHfp ? "HSP/HFP" : "A2DP")) + : "Profile switch unsupported by device"); + } else if (act == 4) { + runCaptureCmd("timeout 3 bluetoothctl remove " + shellQuote(targetBt.mac) + " >/dev/null 2>&1", &rc); refreshCurrentTab(false); setBanner("Removed " + targetBt.name); @@ -1169,6 +1580,10 @@ int runNetworksApp(int argc, char** argv) { executeBtAction(actionSel); return; } + if (modal == NetModal::BtNameEditor) { + saveBtDeviceName(); + return; + } if (activeTab == NetTab::Wifi) { if (wifiRowSel == 0) { @@ -1255,12 +1670,19 @@ int runNetworksApp(int argc, char** argv) { runCaptureCmd("SXMO_OS=alpine doas -n sxmo_bluetoothtoggle.sh " + std::string(btOn ? "off" : "on") + " >/dev/null 2>&1"); refreshCurrentTab(false); + setBanner(btOn ? "Bluetooth enabled" : "Bluetooth disabled"); } else if (btRowSel == 1) { + toggleBtDiscoverable(); + } else if (btRowSel == 2) { + btNameEdit = btCtrl.name; + lastTapDigit = -1; + modal = NetModal::BtNameEditor; + } else if (btRowSel == 3 && btOn) { setBanner("Scanning Bluetooth devices (5s)..."); render(); refreshCurrentTab(true); setBanner("Found " + std::to_string(btList.size()) + " device(s)"); - } else if (btRowSel == 2 && btOn) { + } else if (btRowSel == 4 && btOn) { std::string target = (!btRx.savedPath.empty()) ? btRx.savedPath : (getHomeDirPath() + "/Downloads"); @@ -1269,9 +1691,9 @@ int runNetworksApp(int argc, char** argv) { if (!sendPluginCommand("files", "OPEN " + target)) { runAsyncArgv("xfiles", target.c_str()); } - } else if (btRowSel - 3 >= 0 && - btRowSel - 3 < static_cast(btList.size())) { - targetBt = btList[btRowSel - 3]; + } else if (btOn && btRowSel - 5 >= 0 && + btRowSel - 5 < static_cast(btList.size())) { + targetBt = btList[btRowSel - 5]; actionSel = 0; modal = NetModal::BtActions; } @@ -1283,6 +1705,10 @@ int runNetworksApp(int argc, char** argv) { saveAndConnectApn(); return; } + if (modal == NetModal::BtNameEditor) { + saveBtDeviceName(); + return; + } if (modal != NetModal::None) { handleEnterKey(); return; @@ -1296,10 +1722,17 @@ int runNetworksApp(int argc, char** argv) { refreshCurrentTab(false); setBanner("Refreshed cellular state"); } else if (activeTab == NetTab::Bluetooth) { - setBanner("Scanning Bluetooth (5s)..."); - render(); - refreshCurrentTab(true); - setBanner("Found " + std::to_string(btList.size()) + " device(s)"); + if (!btOn) { + setBanner("Turning Bluetooth ON..."); + render(); + runCaptureCmd("SXMO_OS=alpine doas -n sxmo_bluetoothtoggle.sh on >/dev/null 2>&1"); + refreshCurrentTab(false); + } else { + setBanner("Scanning Bluetooth (5s)..."); + render(); + refreshCurrentTab(true); + setBanner("Found " + std::to_string(btList.size()) + " device(s)"); + } } }; @@ -1422,12 +1855,25 @@ int runNetworksApp(int argc, char** argv) { continue; } + if (modal == NetModal::BtNameEditor) { + if (sym == XK_Return || sym == XK_KP_Enter) { + saveBtDeviceName(); + render(); + continue; + } + if (handleMultiTapKey(btNameEdit, sym, kc, ev.xkey.state)) { + render(); + } + continue; + } + if (modal == NetModal::WifiActions || modal == NetModal::BtActions) { + int actCount = (modal == NetModal::BtActions) ? 5 : 4; if (sym == XK_Up || sym == XK_KP_Up) { - actionSel = (actionSel + 3) % 4; + actionSel = (actionSel + actCount - 1) % actCount; render(); } else if (sym == XK_Down || sym == XK_KP_Down) { - actionSel = (actionSel + 1) % 4; + actionSel = (actionSel + 1) % actCount; render(); } else if (sym == XK_Return || sym == XK_KP_Enter) { handleEnterKey(); @@ -1470,7 +1916,7 @@ int runNetworksApp(int argc, char** argv) { } else if (activeTab == NetTab::Cellular) { cellRowSel = (cellRowSel + 3) % 4; } else if (activeTab == NetTab::Bluetooth) { - int total = btOn ? (3 + static_cast(btList.size())) : 2; + int total = btOn ? (5 + static_cast(btList.size())) : 3; btRowSel = (btRowSel + total - 1) % total; } render(); @@ -1481,7 +1927,7 @@ int runNetworksApp(int argc, char** argv) { } else if (activeTab == NetTab::Cellular) { cellRowSel = (cellRowSel + 1) % 4; } else if (activeTab == NetTab::Bluetooth) { - int total = btOn ? (3 + static_cast(btList.size())) : 2; + int total = btOn ? (5 + static_cast(btList.size())) : 3; btRowSel = (btRowSel + 1) % total; } render(); @@ -1525,7 +1971,8 @@ int runNetworksApp(int argc, char** argv) { } } if (lastTapDigit != -1 && - (modal == NetModal::WifiPassword || modal == NetModal::ApnEditor)) { + (modal == NetModal::WifiPassword || modal == NetModal::ApnEditor || + modal == NetModal::BtNameEditor)) { int64_t tRem = (lastTapMs + 851) - now; if (tRem <= 0) { lastTapDigit = -1; diff --git a/src/games/gambatte_phone.cpp b/src/games/gambatte_phone.cpp index b694c34..d52a91d 100644 --- a/src/games/gambatte_phone.cpp +++ b/src/games/gambatte_phone.cpp @@ -1007,8 +1007,24 @@ class PcmAudioOut { private: void audioThreadMain() { snd_pcm_t* h = nullptr; - const char* devs[] = {"hw:0,0", "default", "plughw:0,0"}; - for (const char* dev : devs) { + bool preferDefault = (::access("/run/bluetoothd.pid", F_OK) == 0); + if (!preferDefault) { + FILE* af = std::fopen("/tmp/sxmo_audio_out_device", "r"); + if (af) { + char abuf[64] = {}; + if (std::fgets(abuf, sizeof(abuf), af)) { + if (std::strstr(abuf, "Bluetooth") || std::strstr(abuf, "bluetooth")) { + preferDefault = true; + } + } + std::fclose(af); + } + } + const char* devsHwFirst[] = {"hw:0,0", "default", "plughw:0,0"}; + const char* devsDefFirst[] = {"default", "hw:0,0", "plughw:0,0"}; + const char** devs = preferDefault ? devsDefFirst : devsHwFirst; + for (int di = 0; di < 3; ++di) { + const char* dev = devs[di]; if (snd_pcm_open(&h, dev, SND_PCM_STREAM_PLAYBACK, 0) >= 0) { if (configureLowLatency(h)) { break; @@ -1018,7 +1034,8 @@ class PcmAudioOut { } } if (!h) { - for (const char* dev : devs) { + for (int di = 0; di < 3; ++di) { + const char* dev = devs[di]; if (snd_pcm_open(&h, dev, SND_PCM_STREAM_PLAYBACK, 0) >= 0) { if (snd_pcm_set_params(h, SND_PCM_FORMAT_S16_LE, SND_PCM_ACCESS_RW_INTERLEAVED, 2, 48000, 1, @@ -2253,6 +2270,10 @@ int main(int argc, char** argv) { usedByAction = true; } } + if (!usedByAction && tok == "OK") { + actionDown[ACT_A] = isPress; + usedByAction = true; + } if (isPress && !usedByAction) { if (tok == "1") { cfg.scaleMode = (cfg.scaleMode + 1) % 4; diff --git a/src/games/remedy/remedy_cldc_net_media.hpp b/src/games/remedy/remedy_cldc_net_media.hpp index 28b2785..2a93714 100644 --- a/src/games/remedy/remedy_cldc_net_media.hpp +++ b/src/games/remedy/remedy_cldc_net_media.hpp @@ -333,6 +333,7 @@ class AlsaSoundEngine { int playerId = -1; bool active = false; bool loop = false; + size_t rawSize = 0; float gain = 0.8f; std::vector events; size_t eventIdx = 0; @@ -777,10 +778,20 @@ class AlsaSoundEngine { auto it = playerGains_.find(playerId); if (it != playerGains_.end()) g = it->second; + if (midiSeq_.active && midiSeq_.playerId == playerId && + midiSeq_.rawSize == mid.size() && midiSeq_.currentFrame > 0 && + midiSeq_.currentFrame < midiSeq_.totalFrames) { + midiSeq_.loop = loop; + midiSeq_.gain = g; + lastActiveMs_ = nowMs(); + return; + } + midiSeq_ = MidiSequence{}; midiSeq_.playerId = playerId; midiSeq_.active = true; midiSeq_.loop = loop; + midiSeq_.rawSize = mid.size(); midiSeq_.gain = g; midiSeq_.events = std::move(frameEvents); midiSeq_.totalFrames = @@ -1132,12 +1143,32 @@ class AlsaSoundEngine { snd_pcm_close(pcm); pcm = nullptr; } + if (!enabled || sysMuted) { + std::lock_guard lk(mu_); + voices_.clear(); + for (auto it = pcmStreams_.begin(); it != pcmStreams_.end();) { + if (!it->loop) { + it = pcmStreams_.erase(it); + } else { + ++it; + } + } + if (midiSeq_.active && !midiSeq_.loop) { + midiSeq_.active = false; + midiVoices_.clear(); + } + } ::usleep(10000); continue; } if (!pcm) { - for (const char* dev : {"hw:0,0", "default", "plughw:0,0"}) { + bool preferDefault = (::access("/run/bluetoothd.pid", F_OK) == 0); + const char* devsHwFirst[] = {"hw:0,0", "default", "plughw:0,0"}; + const char* devsDefFirst[] = {"default", "hw:0,0", "plughw:0,0"}; + const char** devs = preferDefault ? devsDefFirst : devsHwFirst; + for (int di = 0; di < 3; ++di) { + const char* dev = devs[di]; if (snd_pcm_open(&pcm, dev, SND_PCM_STREAM_PLAYBACK, 0) == 0) { if (!configureLowLatency(pcm, kSampleRate, kPeriod, kBuffer)) { snd_pcm_set_params(pcm, SND_PCM_FORMAT_S16_LE, @@ -1577,13 +1608,29 @@ class CldcNetMediaRuntime { }); // java/lang/System & Runtime + uint32_t sysOutRef = vm.allocObject("java/io/PrintStream"); + uint32_t sysErrRef = vm.allocObject("java/io/PrintStream"); + vm.setStaticFieldVal("java/lang/System", "out", "Ljava/io/PrintStream;", + JVal::MakeRef(sysOutRef)); + vm.setStaticFieldVal("java/lang/System", "err", "Ljava/io/PrintStream;", + JVal::MakeRef(sysErrRef)); + uint32_t boolTrueRef = vm.allocObject("java/lang/Boolean"); + vm.getObj(boolTrueRef)->setField("value", JVal::MakeInt(1)); + uint32_t boolFalseRef = vm.allocObject("java/lang/Boolean"); + vm.getObj(boolFalseRef)->setField("value", JVal::MakeInt(0)); + vm.setStaticFieldVal("java/lang/Boolean", "TRUE", "Ljava/lang/Boolean;", + JVal::MakeRef(boolTrueRef)); + vm.setStaticFieldVal("java/lang/Boolean", "FALSE", "Ljava/lang/Boolean;", + JVal::MakeRef(boolFalseRef)); + vm.registerNative("java/lang/System", "currentTimeMillis", "()J", [](Jvm&, JThread&, const std::vector&, JVal* r) { *r = JVal::MakeLong(wallTimeMs()); return true; }); vm.registerNative("java/lang/System", "gc", "()V", - [](Jvm&, JThread&, const std::vector&, JVal*) { + [](Jvm& v, JThread&, const std::vector&, JVal*) { + v.collectGarbage(); return true; }); vm.registerNative("java/lang/System", "exit", "(I)V", @@ -1653,6 +1700,7 @@ class CldcNetMediaRuntime { else if (key == "microedition.locale") val = "en-US"; else if (key == "microedition.m3g.version") val = "1.1"; else if (key == "microedition.io.file.FileConnection.version") val = "1.0"; + else if (key == "bluetooth.api.version") val = "1.1"; else if (key == "file.separator") val = "/"; else if (key == "fileconn.dir.photos") val = "file:///home/user/Pictures/"; else if (key == "fileconn.dir.music") val = "file:///home/user/Music/"; @@ -1674,17 +1722,18 @@ class CldcNetMediaRuntime { return true; }); vm.registerNative("java/lang/Runtime", "freeMemory", "()J", - [](Jvm&, JThread&, const std::vector&, JVal* r) { - *r = JVal::MakeLong(16 * 1024 * 1024LL); + [](Jvm& v, JThread&, const std::vector&, JVal* r) { + *r = JVal::MakeLong(v.freeHeapBytes()); return true; }); vm.registerNative("java/lang/Runtime", "totalMemory", "()J", - [](Jvm&, JThread&, const std::vector&, JVal* r) { - *r = JVal::MakeLong(32 * 1024 * 1024LL); + [](Jvm& v, JThread&, const std::vector&, JVal* r) { + *r = JVal::MakeLong(v.totalHeapBytes()); return true; }); vm.registerNative("java/lang/Runtime", "gc", "()V", - [](Jvm&, JThread&, const std::vector&, JVal*) { + [](Jvm& v, JThread&, const std::vector&, JVal*) { + v.collectGarbage(); return true; }); @@ -2380,6 +2429,182 @@ class CldcNetMediaRuntime { *r = JVal::MakeRef(v.allocString(std::to_string(val))); return true; }); + vm.registerNative("java/lang/Integer", "toBinaryString", + "(I)Ljava/lang/String;", + [](Jvm& v, JThread&, const std::vector& a, JVal* r) { + uint32_t u = static_cast(a[0].i); + if (u == 0) { + *r = JVal::MakeRef(v.allocString("0")); + return true; + } + std::string s; + while (u > 0) { + s.insert(s.begin(), (u & 1) ? '1' : '0'); + u >>= 1; + } + *r = JVal::MakeRef(v.allocString(s)); + return true; + }); + vm.registerNative("java/lang/Integer", "toOctalString", + "(I)Ljava/lang/String;", + [](Jvm& v, JThread&, const std::vector& a, JVal* r) { + char buf[32]; + std::snprintf(buf, sizeof(buf), "%o", + static_cast(a[0].i)); + *r = JVal::MakeRef(v.allocString(buf)); + return true; + }); + vm.registerNative("java/lang/Character", "isDigit", "(C)Z", + [](Jvm&, JThread&, const std::vector& a, JVal* r) { + *r = JVal::MakeInt((a[0].i >= '0' && a[0].i <= '9') ? 1 : 0); + return true; + }); + vm.registerNative("java/lang/Character", "isLowerCase", "(C)Z", + [](Jvm&, JThread&, const std::vector& a, JVal* r) { + *r = JVal::MakeInt((a[0].i >= 'a' && a[0].i <= 'z') ? 1 : 0); + return true; + }); + vm.registerNative("java/lang/Character", "isUpperCase", "(C)Z", + [](Jvm&, JThread&, const std::vector& a, JVal* r) { + *r = JVal::MakeInt((a[0].i >= 'A' && a[0].i <= 'Z') ? 1 : 0); + return true; + }); + vm.registerNative("java/lang/Character", "toLowerCase", "(C)C", + [](Jvm&, JThread&, const std::vector& a, JVal* r) { + int c = a[0].i; + if (c >= 'A' && c <= 'Z') c += ('a' - 'A'); + *r = JVal::MakeInt(c); + return true; + }); + vm.registerNative("java/lang/Character", "toUpperCase", "(C)C", + [](Jvm&, JThread&, const std::vector& a, JVal* r) { + int c = a[0].i; + if (c >= 'a' && c <= 'z') c -= ('a' - 'A'); + *r = JVal::MakeInt(c); + return true; + }); + vm.registerNative("java/lang/Character", "digit", "(CI)I", + [](Jvm&, JThread&, const std::vector& a, JVal* r) { + int c = a[0].i; + int radix = a[1].i; + int d = -1; + if (c >= '0' && c <= '9') d = c - '0'; + else if (c >= 'a' && c <= 'z') d = 10 + (c - 'a'); + else if (c >= 'A' && c <= 'Z') d = 10 + (c - 'A'); + if (d >= radix) d = -1; + *r = JVal::MakeInt(d); + return true; + }); + vm.registerNative("java/lang/Float", "", "*", + [](Jvm& v, JThread&, const std::vector& a, JVal*) { + JObject* self = v.getObj(a[0].ref); + if (!self || a.size() < 2) return true; + float fv = (a[1].type == JType::Double) + ? static_cast(a[1].d) + : a[1].f; + self->setField("value", JVal::MakeFloat(fv)); + return true; + }); + vm.registerNative("java/lang/Float", "floatValue", "()F", + [](Jvm& v, JThread&, const std::vector& a, JVal* r) { + const JObject* self = v.getObj(a[0].ref); + *r = JVal::MakeFloat(self ? self->getField("value", 'F').f : 0.0f); + return true; + }); + vm.registerNative("java/lang/Float", "parseFloat", "(Ljava/lang/String;)F", + [](Jvm& v, JThread&, const std::vector& a, JVal* r) { + *r = JVal::MakeFloat( + std::strtof(v.getStringUtf8(a[0].ref).c_str(), nullptr)); + return true; + }); + vm.registerNative("java/lang/Float", "valueOf", "(Ljava/lang/String;)Ljava/lang/Float;", + [](Jvm& v, JThread&, const std::vector& a, JVal* r) { + float fv = std::strtof(v.getStringUtf8(a[0].ref).c_str(), nullptr); + uint32_t ref = v.allocObject("java/lang/Float"); + v.getObj(ref)->setField("value", JVal::MakeFloat(fv)); + *r = JVal::MakeRef(ref); + return true; + }); + vm.registerNative("java/lang/Float", "toString", "*", + [](Jvm& v, JThread&, const std::vector& a, JVal* r) { + float fv = (a[0].type == JType::Ref) + ? (v.getObj(a[0].ref) + ? v.getObj(a[0].ref)->getField("value", 'F').f + : 0.0f) + : a[0].f; + char buf[64]; + std::snprintf(buf, sizeof(buf), "%g", fv); + *r = JVal::MakeRef(v.allocString(buf)); + return true; + }); + vm.registerNative("java/lang/Float", "floatToIntBits", "(F)I", + [](Jvm&, JThread&, const std::vector& a, JVal* r) { + int32_t bits = 0; + std::memcpy(&bits, &a[0].f, sizeof(int32_t)); + *r = JVal::MakeInt(bits); + return true; + }); + vm.registerNative("java/lang/Float", "intBitsToFloat", "(I)F", + [](Jvm&, JThread&, const std::vector& a, JVal* r) { + float fv = 0.0f; + std::memcpy(&fv, &a[0].i, sizeof(float)); + *r = JVal::MakeFloat(fv); + return true; + }); + vm.registerNative("java/lang/Double", "", "(D)V", + [](Jvm& v, JThread&, const std::vector& a, JVal*) { + JObject* self = v.getObj(a[0].ref); + if (self && a.size() >= 2) { + self->setField("value", JVal::MakeDouble(a[1].d)); + } + return true; + }); + vm.registerNative("java/lang/Double", "doubleValue", "()D", + [](Jvm& v, JThread&, const std::vector& a, JVal* r) { + const JObject* self = v.getObj(a[0].ref); + *r = JVal::MakeDouble(self ? self->getField("value", 'D').d : 0.0); + return true; + }); + vm.registerNative("java/lang/Double", "parseDouble", "(Ljava/lang/String;)D", + [](Jvm& v, JThread&, const std::vector& a, JVal* r) { + *r = JVal::MakeDouble( + std::strtod(v.getStringUtf8(a[0].ref).c_str(), nullptr)); + return true; + }); + vm.registerNative("java/lang/Double", "valueOf", "(Ljava/lang/String;)Ljava/lang/Double;", + [](Jvm& v, JThread&, const std::vector& a, JVal* r) { + double dv = std::strtod(v.getStringUtf8(a[0].ref).c_str(), nullptr); + uint32_t ref = v.allocObject("java/lang/Double"); + v.getObj(ref)->setField("value", JVal::MakeDouble(dv)); + *r = JVal::MakeRef(ref); + return true; + }); + vm.registerNative("java/lang/Double", "toString", "*", + [](Jvm& v, JThread&, const std::vector& a, JVal* r) { + double dv = (a[0].type == JType::Ref) + ? (v.getObj(a[0].ref) + ? v.getObj(a[0].ref)->getField("value", 'D').d + : 0.0) + : a[0].d; + char buf[64]; + std::snprintf(buf, sizeof(buf), "%g", dv); + *r = JVal::MakeRef(v.allocString(buf)); + return true; + }); + vm.registerNative("java/lang/Double", "doubleToLongBits", "(D)J", + [](Jvm&, JThread&, const std::vector& a, JVal* r) { + int64_t bits = 0; + std::memcpy(&bits, &a[0].d, sizeof(int64_t)); + *r = JVal::MakeLong(bits); + return true; + }); + vm.registerNative("java/lang/Double", "longBitsToDouble", "(J)D", + [](Jvm&, JThread&, const std::vector& a, JVal* r) { + double dv = 0.0; + std::memcpy(&dv, &a[0].l, sizeof(double)); + *r = JVal::MakeDouble(dv); + return true; + }); // java/lang/Math vm.registerNative("java/lang/Math", "abs", "(I)I", @@ -2982,7 +3207,10 @@ class CldcNetMediaRuntime { vm.registerNative("java/util/Hashtable", "clear", "()V", [](Jvm& v, JThread&, const std::vector& a, JVal*) { JObject* self = v.getObj(a[0].ref); - if (self) self->fields.clear(); + if (self) { + self->fields.clear(); + self->refArr.clear(); + } return true; }); vm.registerNative("java/util/Hashtable", "size", "()I", @@ -2993,6 +3221,45 @@ class CldcNetMediaRuntime { : 0); return true; }); + vm.registerNative("java/util/Hashtable", "isEmpty", "()Z", + [](Jvm& v, JThread&, const std::vector& a, JVal* r) { + JObject* self = v.getObj(a[0].ref); + *r = JVal::MakeInt( + (!self || self->fields.empty()) ? 1 : 0); + return true; + }); + vm.registerNative("java/util/Hashtable", "keys", + "()Ljava/util/Enumeration;", + [](Jvm& v, JThread&, const std::vector& a, JVal* r) { + JObject* self = v.getObj(a[0].ref); + uint32_t en = v.allocObject("java/util/Enumeration"); + JObject* eo = v.getObj(en); + if (self && eo) { + eo->nativeTag = 0; + for (const auto& kv : self->fields) { + eo->refArr.push_back(v.allocString(kv.first)); + } + } + *r = JVal::MakeRef(en); + return true; + }); + vm.registerNative("java/util/Hashtable", "elements", + "()Ljava/util/Enumeration;", + [](Jvm& v, JThread&, const std::vector& a, JVal* r) { + JObject* self = v.getObj(a[0].ref); + uint32_t en = v.allocObject("java/util/Enumeration"); + JObject* eo = v.getObj(en); + if (self && eo) { + eo->nativeTag = 0; + for (const auto& kv : self->fields) { + if (kv.second.type == JType::Ref) { + eo->refArr.push_back(kv.second.ref); + } + } + } + *r = JVal::MakeRef(en); + return true; + }); // java/util/Timer & TimerTask vm.registerNative("java/util/Timer", "", "*", @@ -3436,6 +3703,199 @@ class CldcNetMediaRuntime { return true; }); } + + // Reader & InputStreamReader (UTF-8 / ISO-8859-1 character stream decoder) + auto readOneUtf8Char = [](NativeInputStream* nis) -> int { + if (!nis) return -1; + int b = nis->readByte(); + if (b < 0) return -1; + if ((b & 0x80) == 0) return b; + if ((b & 0xE0) == 0xC0) { + int b2 = nis->readByte(); + if (b2 < 0) return b; + return ((b & 0x1F) << 6) | (b2 & 0x3F); + } + if ((b & 0xF0) == 0xE0) { + int b2 = nis->readByte(); + int b3 = nis->readByte(); + if (b2 < 0 || b3 < 0) return b; + return ((b & 0x0F) << 12) | ((b2 & 0x3F) << 6) | (b3 & 0x3F); + } + return b; + }; + for (const char* rdrCls : {"java/io/Reader", "java/io/InputStreamReader"}) { + vm.registerNative( + rdrCls, "", "*", + [](Jvm& v, JThread&, const std::vector& a, JVal*) { + JObject* self = v.getObj(a[0].ref); + if (self && a.size() >= 2 && a[1].type == JType::Ref) { + JObject* src = v.getObj(a[1].ref); + if (src && src->nativeData) { + self->nativeData = src->nativeData; + } + self->setField("in", a[1]); + } + return true; + }); + vm.registerNative( + rdrCls, "read", "()I", + [readOneUtf8Char](Jvm& v, JThread&, const std::vector& a, + JVal* r) { + auto nis = getOrCreateInputStream(v, a[0].ref); + *r = JVal::MakeInt(readOneUtf8Char(nis.get())); + return true; + }); + vm.registerNative( + rdrCls, "read", "([C)I", + [readOneUtf8Char](Jvm& v, JThread&, const std::vector& a, + JVal* r) { + auto nis = getOrCreateInputStream(v, a[0].ref); + JObject* arr = v.getObj(a[1].ref); + if (!nis || !arr || arr->arrayKind != ArrayKind::Char) { + *r = JVal::MakeInt(-1); + return true; + } + int len = static_cast(arr->charArr.size()); + if (len == 0) { + *r = JVal::MakeInt(0); + return true; + } + int count = 0; + for (int i = 0; i < len; ++i) { + int c = readOneUtf8Char(nis.get()); + if (c < 0) break; + arr->charArr[i] = static_cast(c); + ++count; + } + *r = JVal::MakeInt(count == 0 ? -1 : count); + return true; + }); + vm.registerNative( + rdrCls, "read", "([CII)I", + [readOneUtf8Char](Jvm& v, JThread&, const std::vector& a, + JVal* r) { + auto nis = getOrCreateInputStream(v, a[0].ref); + JObject* arr = v.getObj(a[1].ref); + int off = a[2].i; + int len = a[3].i; + if (!nis || !arr || arr->arrayKind != ArrayKind::Char || off < 0 || + len < 0 || off + len > static_cast(arr->charArr.size())) { + *r = JVal::MakeInt(-1); + return true; + } + if (len == 0) { + *r = JVal::MakeInt(0); + return true; + } + int count = 0; + for (int i = 0; i < len; ++i) { + int c = readOneUtf8Char(nis.get()); + if (c < 0) break; + arr->charArr[off + i] = static_cast(c); + ++count; + } + *r = JVal::MakeInt(count == 0 ? -1 : count); + return true; + }); + vm.registerNative( + rdrCls, "skip", "(J)J", + [readOneUtf8Char](Jvm& v, JThread&, const std::vector& a, + JVal* r) { + auto nis = getOrCreateInputStream(v, a[0].ref); + int64_t want = std::max(0, a[1].l); + int64_t skipped = 0; + while (skipped < want && readOneUtf8Char(nis.get()) >= 0) { + ++skipped; + } + *r = JVal::MakeLong(skipped); + return true; + }); + vm.registerNative( + rdrCls, "ready", "()Z", + [](Jvm& v, JThread&, const std::vector& a, JVal* r) { + auto nis = getOrCreateInputStream(v, a[0].ref); + *r = JVal::MakeInt((nis && nis->available() > 0) ? 1 : 0); + return true; + }); + vm.registerNative( + rdrCls, "markSupported", "()Z", + [](Jvm&, JThread&, const std::vector&, JVal* r) { + *r = JVal::MakeInt(1); + return true; + }); + vm.registerNative( + rdrCls, "mark", "(I)V", + [](Jvm& v, JThread&, const std::vector& a, JVal*) { + auto nis = getOrCreateInputStream(v, a[0].ref); + if (nis) nis->markPos = nis->pos; + return true; + }); + vm.registerNative( + rdrCls, "reset", "()V", + [](Jvm& v, JThread&, const std::vector& a, JVal*) { + auto nis = getOrCreateInputStream(v, a[0].ref); + if (nis) nis->pos = nis->markPos; + return true; + }); + vm.registerNative( + rdrCls, "close", "()V", + [](Jvm&, JThread&, const std::vector&, JVal*) { return true; }); + } + + // Writer & OutputStreamWriter + for (const char* wrCls : {"java/io/Writer", "java/io/OutputStreamWriter"}) { + vm.registerNative( + wrCls, "", "*", + [](Jvm& v, JThread&, const std::vector& a, JVal*) { + JObject* self = v.getObj(a[0].ref); + if (self && a.size() >= 2 && a[1].type == JType::Ref) { + JObject* sub = v.getObj(a[1].ref); + if (sub && sub->nativeData) self->nativeData = sub->nativeData; + } + return true; + }); + vm.registerNative( + wrCls, "write", "(I)V", + [](Jvm& v, JThread&, const std::vector& a, JVal*) { + auto nos = getOrCreateOutputStream(v, a[0].ref); + if (nos) { + uint16_t ch = static_cast(a[1].i); + std::string s = Jvm::u16ToUtf8(&ch, 1); + nos->writeBytes(reinterpret_cast(s.data()), + static_cast(s.size())); + } + return true; + }); + vm.registerNative( + wrCls, "write", "*", + [](Jvm& v, JThread&, const std::vector& a, JVal*) { + auto nos = getOrCreateOutputStream(v, a[0].ref); + if (!nos || a.size() < 2 || a[1].type != JType::Ref) return true; + JObject* arg = v.getObj(a[1].ref); + if (!arg) return true; + std::string s; + if (arg->arrayKind == ArrayKind::Char) { + int off = (a.size() >= 4) ? a[2].i : 0; + int len = (a.size() >= 4) ? a[3].i + : static_cast(arg->charArr.size()); + off = std::clamp(off, 0, static_cast(arg->charArr.size())); + len = std::clamp(len, 0, + static_cast(arg->charArr.size()) - off); + s = Jvm::u16ToUtf8(arg->charArr.data() + off, len); + } else { + s = v.getStringUtf8(a[1].ref); + } + nos->writeBytes(reinterpret_cast(s.data()), + static_cast(s.size())); + return true; + }); + vm.registerNative( + wrCls, "flush", "()V", + [](Jvm&, JThread&, const std::vector&, JVal*) { return true; }); + vm.registerNative( + wrCls, "close", "()V", + [](Jvm&, JThread&, const std::vector&, JVal*) { return true; }); + } } void registerRms(Jvm& vm) { @@ -4161,6 +4621,7 @@ class CldcNetMediaRuntime { "javax/microedition/media/Control", "javax/microedition/media/control/VolumeControl", "javax/microedition/media/control/ToneControl", + "javax/microedition/media/control/MIDIControl", "com/nokia/mid/sound/Sound"}) { vm.registerNative( pCls, "", "*", @@ -4331,13 +4792,12 @@ class CldcNetMediaRuntime { return true; } if (np->state == 400 && !np->data.empty()) { - bool isMidi = (np->data.size() >= 4 && - std::memcmp(np->data.data(), "MThd", 4) == 0); bool isLooping = (np->loopCount < 0 || np->loopCount > 1); - if (!isMidi && !isLooping) { - // One-shot WAV SFX play asynchronously in the 6-channel mixer; - // report PREFETCHED (300) so games that check getState() == 400 - // before starting music or rapid SFX never drop sounds. + if (!isLooping) { + // One-shot WAV/MIDI SFX and jingles play asynchronously in the + // mixer; report PREFETCHED (300) so games that check + // getState() == 400 before loading a level or playing SFX + // never deadlock. np->state = 300; } else if (!sound.isPlayerActive(np->playerId)) { np->state = 300; // Transition back to PREFETCHED when finished @@ -4414,9 +4874,12 @@ class CldcNetMediaRuntime { ? v.getStringUtf8(a[1].ref) : "VolumeControl"; std::string clsName = - (ctrlType.find("ToneControl") != std::string::npos) - ? "javax/microedition/media/control/ToneControl" - : "javax/microedition/media/control/VolumeControl"; + "javax/microedition/media/control/VolumeControl"; + if (ctrlType.find("ToneControl") != std::string::npos) { + clsName = "javax/microedition/media/control/ToneControl"; + } else if (ctrlType.find("MIDIControl") != std::string::npos) { + clsName = "javax/microedition/media/control/MIDIControl"; + } uint32_t cref = v.allocObject(clsName); JObject* co = v.getObj(cref); if (co && self) { @@ -4519,7 +4982,296 @@ class CldcNetMediaRuntime { } return true; }); + vm.registerNative( + pCls, "shortMidiEvent", "(III)V", + [this, ensureNativePlayer](Jvm& v, JThread&, + const std::vector& a, JVal*) { + if (a.size() >= 4) { + int status = a[1].i & 0xF0; + int data1 = a[2].i & 0x7F; + int data2 = a[3].i & 0x7F; + if (status == 0x90 && data2 > 0) { + NativePlayer* np = ensureNativePlayer(v.getObj(a[0].ref)); + int vol = np ? (np->muted ? 0 : np->volumeLevel) : 80; + sound.playTone(data1, 90, + std::clamp((data2 * vol) / 127, 0, 100)); + } + } + return true; + }); + vm.registerNative( + pCls, "longMidiEvent", "([BII)I", + [](Jvm&, JThread&, const std::vector& a, JVal* r) { + *r = JVal::MakeInt(a.size() >= 4 ? a[3].i : 0); + return true; + }); + vm.registerNative( + pCls, "setChannelVolume", "(II)V", + [](Jvm&, JThread&, const std::vector&, JVal*) { return true; }); + vm.registerNative( + pCls, "setProgram", "(III)V", + [](Jvm&, JThread&, const std::vector&, JVal*) { return true; }); } + + // StreamConnectionNotifier & ServerSocketConnection + for (const char* scnCls : + {"javax/microedition/io/StreamConnectionNotifier", + "javax/microedition/io/ServerSocketConnection"}) { + vm.registerNative( + scnCls, "acceptAndOpen", + "()Ljavax/microedition/io/StreamConnection;", + [](Jvm& v, JThread& th, const std::vector&, JVal*) { + v.throwException(th, "java/io/IOException", + "Connection closed"); + return false; + }); + vm.registerNative( + scnCls, "close", "()V", + [](Jvm&, JThread&, const std::vector&, JVal*) { return true; }); + } + + // JSR-82 Bluetooth API (javax.bluetooth.*) + vm.registerNative( + "javax/bluetooth/LocalDevice", "getLocalDevice", + "()Ljavax/bluetooth/LocalDevice;", + [](Jvm& v, JThread&, const std::vector&, JVal* r) { + *r = JVal::MakeRef(v.allocObject("javax/bluetooth/LocalDevice")); + return true; + }); + vm.registerNative( + "javax/bluetooth/LocalDevice", "getProperty", + "(Ljava/lang/String;)Ljava/lang/String;", + [](Jvm& v, JThread&, const std::vector&, JVal* r) { + *r = JVal::MakeRef(v.allocString("1.1")); + return true; + }); + vm.registerNative( + "javax/bluetooth/LocalDevice", "getDiscoveryAgent", + "()Ljavax/bluetooth/DiscoveryAgent;", + [](Jvm& v, JThread&, const std::vector&, JVal* r) { + *r = JVal::MakeRef(v.allocObject("javax/bluetooth/DiscoveryAgent")); + return true; + }); + vm.registerNative( + "javax/bluetooth/LocalDevice", "getFriendlyName", + "()Ljava/lang/String;", + [](Jvm& v, JThread&, const std::vector&, JVal* r) { + *r = JVal::MakeRef(v.allocString("Nokia 8110 4G")); + return true; + }); + vm.registerNative( + "javax/bluetooth/LocalDevice", "getBluetoothAddress", + "()Ljava/lang/String;", + [](Jvm& v, JThread&, const std::vector&, JVal* r) { + *r = JVal::MakeRef(v.allocString("001122334455")); + return true; + }); + vm.registerNative( + "javax/bluetooth/LocalDevice", "setDiscoverable", "(I)Z", + [](Jvm&, JThread&, const std::vector&, JVal* r) { + *r = JVal::MakeInt(1); + return true; + }); + vm.registerNative( + "javax/bluetooth/LocalDevice", "getDiscoverable", "()I", + [](Jvm&, JThread&, const std::vector&, JVal* r) { + *r = JVal::MakeInt(0x9E8B33); + return true; + }); + vm.registerNative( + "javax/bluetooth/LocalDevice", "getRecord", + "(Ljavax/microedition/io/Connection;)Ljavax/bluetooth/ServiceRecord;", + [](Jvm& v, JThread&, const std::vector&, JVal* r) { + *r = JVal::MakeRef(v.allocObject("javax/bluetooth/ServiceRecord")); + return true; + }); + vm.registerNative( + "javax/bluetooth/LocalDevice", "updateRecord", + "(Ljavax/bluetooth/ServiceRecord;)V", + [](Jvm&, JThread&, const std::vector&, JVal*) { return true; }); + vm.registerNative( + "javax/bluetooth/DiscoveryAgent", "startInquiry", + "(ILjavax/bluetooth/DiscoveryListener;)Z", + [](Jvm& v, JThread&, const std::vector& a, JVal* r) { + if (a.size() >= 3 && a[2].ref != 0) { + v.invokeMethodSync(a[2].ref, "inquiryCompleted", "(I)V", + {JVal::MakeInt(0)}); + } + *r = JVal::MakeInt(1); + return true; + }); + vm.registerNative( + "javax/bluetooth/DiscoveryAgent", "cancelInquiry", + "(Ljavax/bluetooth/DiscoveryListener;)Z", + [](Jvm&, JThread&, const std::vector&, JVal* r) { + *r = JVal::MakeInt(1); + return true; + }); + vm.registerNative( + "javax/bluetooth/DiscoveryAgent", "searchServices", + "([I[Ljavax/bluetooth/UUID;Ljavax/bluetooth/RemoteDevice;Ljavax/bluetooth/DiscoveryListener;)I", + [](Jvm& v, JThread&, const std::vector& a, JVal* r) { + if (a.size() >= 5 && a[4].ref != 0) { + v.invokeMethodSync(a[4].ref, "serviceSearchCompleted", "(II)V", + {JVal::MakeInt(1), JVal::MakeInt(4)}); + } + *r = JVal::MakeInt(1); + return true; + }); + vm.registerNative( + "javax/bluetooth/DiscoveryAgent", "cancelServiceSearch", "(I)Z", + [](Jvm&, JThread&, const std::vector&, JVal* r) { + *r = JVal::MakeInt(1); + return true; + }); + vm.registerNative( + "javax/bluetooth/DiscoveryAgent", "retrieveDevices", + "(I)[Ljavax/bluetooth/RemoteDevice;", + [](Jvm&, JThread&, const std::vector&, JVal* r) { + *r = JVal::Null(); + return true; + }); + vm.registerNative( + "javax/bluetooth/RemoteDevice", "getFriendlyName", + "(Z)Ljava/lang/String;", + [](Jvm& v, JThread&, const std::vector&, JVal* r) { + *r = JVal::MakeRef(v.allocString("BT Device")); + return true; + }); + vm.registerNative( + "javax/bluetooth/RemoteDevice", "getBluetoothAddress", + "()Ljava/lang/String;", + [](Jvm& v, JThread&, const std::vector&, JVal* r) { + *r = JVal::MakeRef(v.allocString("001122334455")); + return true; + }); + vm.registerNative( + "javax/bluetooth/ServiceRecord", "getConnectionURL", + "(IZ)Ljava/lang/String;", + [](Jvm& v, JThread&, const std::vector&, JVal* r) { + *r = JVal::MakeRef(v.allocString("btspp://001122334455:1")); + return true; + }); + vm.registerNative( + "javax/bluetooth/ServiceRecord", "getHostDevice", + "()Ljavax/bluetooth/RemoteDevice;", + [](Jvm& v, JThread&, const std::vector&, JVal* r) { + *r = JVal::MakeRef(v.allocObject("javax/bluetooth/RemoteDevice")); + return true; + }); + vm.registerNative( + "javax/bluetooth/ServiceRecord", "getAttributeValue", + "(I)Ljavax/bluetooth/DataElement;", + [](Jvm&, JThread&, const std::vector&, JVal* r) { + *r = JVal::Null(); + return true; + }); + vm.registerNative( + "javax/bluetooth/ServiceRecord", "setAttributeValue", + "(ILjavax/bluetooth/DataElement;)Z", + [](Jvm&, JThread&, const std::vector&, JVal* r) { + *r = JVal::MakeInt(1); + return true; + }); + vm.registerNative( + "javax/bluetooth/ServiceRecord", "setDeviceServiceClasses", "(I)V", + [](Jvm&, JThread&, const std::vector&, JVal*) { return true; }); + vm.registerNative( + "javax/bluetooth/DataElement", "", "*", + [](Jvm& v, JThread&, const std::vector& a, JVal*) { + JObject* self = v.getObj(a[0].ref); + if (self && a.size() >= 3) self->setField("value", a[2]); + return true; + }); + vm.registerNative( + "javax/bluetooth/DataElement", "addElement", + "(Ljavax/bluetooth/DataElement;)V", + [](Jvm& v, JThread&, const std::vector& a, JVal*) { + JObject* self = v.getObj(a[0].ref); + if (self && a.size() >= 2) self->refArr.push_back(a[1].ref); + return true; + }); + vm.registerNative( + "javax/bluetooth/DataElement", "getValue", "()Ljava/lang/Object;", + [](Jvm& v, JThread&, const std::vector& a, JVal* r) { + JObject* self = v.getObj(a[0].ref); + if (self && !self->refArr.empty()) { + uint32_t en = v.allocObject("java/util/Enumeration"); + JObject* eo = v.getObj(en); + eo->refArr = self->refArr; + eo->nativeTag = 0; + *r = JVal::MakeRef(en); + } else { + *r = self ? self->getField("value", 'L') : JVal::Null(); + } + return true; + }); + vm.registerNative( + "javax/bluetooth/UUID", "", "*", + [](Jvm& v, JThread&, const std::vector& a, JVal*) { + JObject* self = v.getObj(a[0].ref); + if (self && a.size() >= 2 && a[1].type == JType::Ref) { + self->strUtf8 = v.getStringUtf8(a[1].ref); + } + return true; + }); + + // JSR-75 FileSystemRegistry & FileConnection extras + vm.registerNative( + "javax/microedition/io/file/FileSystemRegistry", "listRoots", + "()Ljava/util/Enumeration;", + [](Jvm& v, JThread&, const std::vector&, JVal* r) { + uint32_t en = v.allocObject("java/util/Enumeration"); + JObject* eo = v.getObj(en); + if (eo) { + eo->nativeTag = 0; + eo->refArr.push_back(v.allocString("root1/")); + } + *r = JVal::MakeRef(en); + return true; + }); + for (const char* fcMethod : {"exists", "isDirectory", "canRead", "canWrite"}) { + vm.registerNative( + "javax/microedition/io/file/FileConnection", fcMethod, "()Z", + [](Jvm&, JThread&, const std::vector&, JVal* r) { + *r = JVal::MakeInt(0); + return true; + }); + } + vm.registerNative( + "javax/microedition/io/file/FileConnection", "fileSize", "()J", + [](Jvm&, JThread&, const std::vector&, JVal* r) { + *r = JVal::MakeLong(0); + return true; + }); + vm.registerNative( + "javax/microedition/io/file/FileConnection", "list", "*", + [](Jvm& v, JThread&, const std::vector&, JVal* r) { + *r = JVal::MakeRef(v.allocObject("java/util/Enumeration")); + return true; + }); + for (const char* fcVoid : {"create", "mkdir", "delete", "truncate"}) { + vm.registerNative( + "javax/microedition/io/file/FileConnection", fcVoid, "*", + [](Jvm&, JThread&, const std::vector&, JVal*) { return true; }); + } + + // JSR-120 Wireless Messaging API (javax.wireless.messaging.*) + vm.registerNative( + "javax/wireless/messaging/MessageConnection", "newMessage", "*", + [](Jvm& v, JThread&, const std::vector&, JVal* r) { + *r = JVal::MakeRef( + v.allocObject("javax/wireless/messaging/TextMessage")); + return true; + }); + vm.registerNative( + "javax/wireless/messaging/MessageConnection", "send", + "(Ljavax/wireless/messaging/Message;)V", + [](Jvm&, JThread&, const std::vector&, JVal*) { return true; }); + vm.registerNative( + "javax/wireless/messaging/TextMessage", "setPayloadText", + "(Ljava/lang/String;)V", + [](Jvm&, JThread&, const std::vector&, JVal*) { return true; }); } }; diff --git a/src/games/remedy/remedy_jvm.hpp b/src/games/remedy/remedy_jvm.hpp index 3ce8fec..1ef4b87 100644 --- a/src/games/remedy/remedy_jvm.hpp +++ b/src/games/remedy/remedy_jvm.hpp @@ -442,6 +442,9 @@ class Jvm { MidletSuiteInfo* suiteInfo = nullptr; RmsManager* rms = nullptr; bool exitRequested = false; + std::function&)> + traceNativeRefs; + std::function&)> traceExtraRoots; Jvm() { heap_.emplace_back(); // id 0 == null @@ -454,21 +457,33 @@ class Jvm { // Heap allocation helpers JObject* getObj(uint32_t ref) { - if (ref == 0 || ref >= heap_.size()) return nullptr; + if (ref == 0 || ref >= heap_.size() || heap_[ref].id == 0) return nullptr; return &heap_[ref]; } const JObject* getObj(uint32_t ref) const { - if (ref == 0 || ref >= heap_.size()) return nullptr; + if (ref == 0 || ref >= heap_.size() || heap_[ref].id == 0) return nullptr; return &heap_[ref]; } - uint32_t allocObject(const std::string& className) { + uint32_t allocHeapSlot(JObject&& obj) { + if (!freeSlots_.empty()) { + uint32_t id = freeSlots_.back(); + freeSlots_.pop_back(); + obj.id = id; + heap_[id] = std::move(obj); + return id; + } uint32_t id = static_cast(heap_.size()); - JObject obj; obj.id = id; - obj.className = className; heap_.push_back(std::move(obj)); + return id; + } + + uint32_t allocObject(const std::string& className) { + JObject obj; + obj.className = className; + uint32_t id = allocHeapSlot(std::move(obj)); initInstanceDefaultFields(id, className); return id; } @@ -486,14 +501,11 @@ class Jvm { std::string readString(uint32_t ref) const { return getStringUtf8(ref); } uint32_t allocString(const std::string& utf8) { - uint32_t id = static_cast(heap_.size()); JObject obj; - obj.id = id; obj.className = "java/lang/String"; obj.isString = true; obj.strUtf8 = utf8; - heap_.push_back(std::move(obj)); - return id; + return allocHeapSlot(std::move(obj)); } uint32_t internString(const std::string& utf8) { @@ -579,9 +591,7 @@ class Jvm { uint32_t allocPrimitiveArray(uint8_t atype, int32_t count) { if (count < 0) count = 0; - uint32_t id = static_cast(heap_.size()); JObject obj; - obj.id = id; switch (atype) { case 4: // T_BOOLEAN obj.className = "[Z"; @@ -629,15 +639,12 @@ class Jvm { obj.intArr.assign(count, 0); break; } - heap_.push_back(std::move(obj)); - return id; + return allocHeapSlot(std::move(obj)); } uint32_t allocRefArray(const std::string& elemClass, int32_t count) { if (count < 0) count = 0; - uint32_t id = static_cast(heap_.size()); JObject obj; - obj.id = id; if (!elemClass.empty() && elemClass[0] == '[') { obj.className = "[" + elemClass; } else { @@ -645,8 +652,7 @@ class Jvm { } obj.arrayKind = ArrayKind::Ref; obj.refArr.assign(count, 0); - heap_.push_back(std::move(obj)); - return id; + return allocHeapSlot(std::move(obj)); } uint32_t allocMultiArray(const std::string& desc, const int32_t* dims, @@ -830,7 +836,7 @@ class Jvm { bool invokeManagedSync(JThread& th, JClass* cls, const JMethodInfo* m, const std::vector& args, - int maxSteps = 500000) { + int maxSteps = 50000000) { if (!cls || !m || !m->hasCode) return false; size_t depth = th.frames.size(); pushBytecodeFrame(th, cls, m, args); @@ -895,7 +901,7 @@ class Jvm { JThread tempThread; tempThread.id = 9999; pushBytecodeFrame(tempThread, cls, &m, {}); - runThreadUntilReturn(tempThread, 0, 2000000); + runThreadUntilReturn(tempThread, 0, 20000000); break; } } @@ -946,12 +952,12 @@ class Jvm { } // Synchronously invoke a method on an object (e.g. MIDlet.startApp, Canvas.paint, - //Canvas.keyPressed, CommandListener.commandAction, Runnable.run) + // Canvas.keyPressed, CommandListener.commandAction, Runnable.run) bool invokeMethodSync(uint32_t objRef, const std::string& methodName, const std::string& descriptor, const std::vector& extraArgs = {}, JVal* outRet = nullptr, - int maxSteps = 500000) { + int maxSteps = 50000000) { JObject* obj = getObj(objRef); if (!obj) return false; std::vector allArgs; @@ -993,15 +999,32 @@ class Jvm { // Execute up to `maxSteps` bytecode instructions on `th` until `th.frames.size() <= targetDepth` bool runThreadUntilReturn(JThread& th, size_t targetDepth, int maxSteps, JVal* outRet = nullptr) { + activeSyncThreads_.push_back(&th); int steps = 0; + bool ok = true; while (steps < maxSteps && th.frames.size() > targetDepth && !exitRequested) { if (!stepOneInstruction(th, outRet, targetDepth)) { - return false; + ok = false; + break; + } + if (th.yieldSlice || th.state != ThreadState::Runnable) { + th.yieldSlice = false; + th.state = ThreadState::Runnable; + th.wakeTimeMs = 0; + th.waitingOnRef = 0; + stepThreads(5000); } ++steps; } - return th.pendingExceptionRef == 0; + if (!activeSyncThreads_.empty() && activeSyncThreads_.back() == &th) { + activeSyncThreads_.pop_back(); + } else { + activeSyncThreads_.erase( + std::remove(activeSyncThreads_.begin(), activeSyncThreads_.end(), &th), + activeSyncThreads_.end()); + } + return ok && th.pendingExceptionRef == 0; } // Execute a quantum slice of instructions on a scheduled thread @@ -1059,8 +1082,171 @@ class Jvm { return ""; } + static constexpr int64_t kTotalHeapBudgetBytes = 64LL * 1024 * 1024; + + int64_t totalHeapBytes() const { return kTotalHeapBudgetBytes; } + + int64_t usedHeapBytes() const { + int64_t used = 0; + for (size_t i = 1; i < heap_.size(); ++i) { + const JObject& o = heap_[i]; + if (o.id == 0) continue; + used += 64; + used += static_cast(o.strUtf8.size()); + used += static_cast(o.byteArr.size()); + used += static_cast(o.charArr.size()) * 2; + used += static_cast(o.shortArr.size()) * 2; + used += static_cast(o.intArr.size()) * 4; + used += static_cast(o.longArr.size()) * 8; + used += static_cast(o.floatArr.size()) * 4; + used += static_cast(o.doubleArr.size()) * 8; + used += static_cast(o.refArr.size()) * 4; + used += static_cast(o.fields.size()) * 32; + } + return std::min(used, kTotalHeapBudgetBytes - 4 * 1024 * 1024); + } + + int64_t freeHeapBytes() const { + return std::max(4 * 1024 * 1024, + kTotalHeapBudgetBytes - usedHeapBytes()); + } + + // Mark-and-sweep garbage collector over Jvm::heap_ + size_t collectGarbage(const std::vector& extraRoots = {}) { + if (heap_.size() <= 1) return 0; + std::vector marked(heap_.size(), 0); + std::vector worklist; + worklist.reserve(1024); + + auto markRef = [&](uint32_t r) { + if (r > 0 && r < heap_.size() && !marked[r] && heap_[r].id != 0) { + marked[r] = 1; + worklist.push_back(r); + } + }; + + for (uint32_t r : extraRoots) markRef(r); + if (traceExtraRoots) traceExtraRoots(markRef); + for (const auto& kv : internPool_) markRef(kv.second); + + for (const auto& ckv : classes_) { + const JClass* cls = ckv.second.get(); + if (!cls) continue; + for (const auto& fkv : cls->staticFields) { + if (fkv.second.type == JType::Ref) markRef(fkv.second.ref); + } + for (const auto& ce : cls->cp) { + if (ce.cachedStringRef != 0) markRef(ce.cachedStringRef); + } + } + + auto markThread = [&](const JThread& th) { + markRef(th.threadObjRef); + markRef(th.pendingExceptionRef); + markRef(th.waitingOnRef); + for (const auto& f : th.frames) { + for (const auto& lv : f.locals) { + if (lv.type == JType::Ref) markRef(lv.ref); + } + for (const auto& sv : f.stack) { + if (sv.type == JType::Ref) markRef(sv.ref); + } + } + }; + + for (const auto& th : threads_) { + if (th) markThread(*th); + } + for (const JThread* sth : activeSyncThreads_) { + if (sth) markThread(*sth); + } + + while (!worklist.empty()) { + uint32_t cur = worklist.back(); + worklist.pop_back(); + const JObject& obj = heap_[cur]; + for (uint32_t r : obj.refArr) markRef(r); + for (const auto& fkv : obj.fields) { + if (fkv.second.type == JType::Ref) markRef(fkv.second.ref); + } + if (traceNativeRefs && obj.nativeData) { + traceNativeRefs(obj, markRef); + } + } + + freeSlots_.clear(); + size_t swept = 0; + for (uint32_t i = static_cast(heap_.size()) - 1; i >= 1; --i) { + if (!marked[i]) { + if (heap_[i].id != 0) { + heap_[i] = JObject{}; + ++swept; + } + freeSlots_.push_back(i); + } + } + + // Reap finished background threads that have no remaining frames + threads_.erase( + std::remove_if(threads_.begin(), threads_.end(), + [](const std::unique_ptr& t) { + return !t || + (t->state == ThreadState::Finished && + t->frames.empty()); + }), + threads_.end()); + + return swept; + } + + JVal* resolveStaticSlot(const std::string& className, + const std::string& fieldName, + const std::string& desc) { + std::string fkey = JObject::makeFieldKey(fieldName, desc); + JClass* cls = loadClass(className); + if (!cls) { + std::string name = className; + for (char& c : name) { + if (c == '.') c = '/'; + } + if (!name.empty() && name[0] == 'L' && name.back() == ';') { + name = name.substr(1, name.size() - 2); + } + auto synth = std::make_unique(); + synth->name = name; + synth->superName = getSuperClassName(name); + synth->clinitStarted = true; + synth->clinitDone = true; + cls = synth.get(); + classes_[name] = std::move(synth); + } + JVal* s = findStaticSlotIn(cls, fkey, fieldName, 0); + if (s) return s; + auto ins = cls->staticFields.emplace( + fkey, defaultValueForDesc(desc.empty() ? 'I' : desc[0])); + return &ins.first->second; + } + + JVal getStaticFieldVal(const std::string& className, + const std::string& fieldName, + const std::string& desc) { + JVal* s = resolveStaticSlot(className, fieldName, desc); + if (s) return *s; + return defaultValueForDesc(desc.empty() ? 'I' : desc[0]); + } + + void setStaticFieldVal(const std::string& className, + const std::string& fieldName, + const std::string& desc, + const JVal& val) { + JVal* s = resolveStaticSlot(className, fieldName, desc); + if (s) *s = val; + } + private: std::deque heap_; + std::vector freeSlots_; + std::vector activeSyncThreads_; std::unordered_map internPool_; std::unordered_map> classes_; std::unordered_map builtinSupers_; @@ -1179,8 +1365,28 @@ class Jvm { "java/lang/RuntimeException"; builtinSupers_["java/lang/ClassCastException"] = "java/lang/RuntimeException"; + builtinSupers_["java/lang/NumberFormatException"] = + "java/lang/IllegalArgumentException"; + builtinSupers_["java/lang/IndexOutOfBoundsException"] = + "java/lang/RuntimeException"; + builtinSupers_["java/lang/StringIndexOutOfBoundsException"] = + "java/lang/IndexOutOfBoundsException"; + builtinSupers_["java/lang/NegativeArraySizeException"] = + "java/lang/RuntimeException"; + builtinSupers_["java/lang/SecurityException"] = + "java/lang/RuntimeException"; + builtinSupers_["java/lang/OutOfMemoryError"] = "java/lang/Throwable"; + builtinSupers_["java/lang/Error"] = "java/lang/Throwable"; builtinSupers_["java/io/IOException"] = "java/lang/Exception"; builtinSupers_["java/io/EOFException"] = "java/io/IOException"; + builtinSupers_["java/io/UnsupportedEncodingException"] = + "java/io/IOException"; + builtinSupers_["javax/microedition/io/ConnectionNotFoundException"] = + "java/io/IOException"; + builtinSupers_["javax/bluetooth/BluetoothStateException"] = + "java/io/IOException"; + builtinSupers_["javax/microedition/media/MediaException"] = + "java/lang/Exception"; builtinSupers_["javax/microedition/rms/RecordStoreException"] = "java/lang/Exception"; builtinSupers_["javax/microedition/rms/RecordStoreNotFoundException"] = @@ -1277,35 +1483,6 @@ class Jvm { return nullptr; } - JVal* resolveStaticSlot(const std::string& className, - const std::string& fieldName, - const std::string& desc) { - std::string fkey = JObject::makeFieldKey(fieldName, desc); - JClass* cls = loadClass(className); - if (!cls) return nullptr; - JVal* s = findStaticSlotIn(cls, fkey, fieldName, 0); - if (s) return s; - auto ins = cls->staticFields.emplace( - fkey, defaultValueForDesc(desc.empty() ? 'I' : desc[0])); - return &ins.first->second; - } - - JVal getStaticFieldVal(const std::string& className, - const std::string& fieldName, - const std::string& desc) { - JVal* s = resolveStaticSlot(className, fieldName, desc); - if (s) return *s; - return defaultValueForDesc(desc.empty() ? 'I' : desc[0]); - } - - void setStaticFieldVal(const std::string& className, - const std::string& fieldName, - const std::string& desc, - const JVal& val) { - JVal* s = resolveStaticSlot(className, fieldName, desc); - if (s) *s = val; - } - // Big-endian readers for .class format static uint16_t be16(const uint8_t* p) { return (static_cast(p[0]) << 8) | p[1]; diff --git a/src/games/remedy/remedy_lcdui.hpp b/src/games/remedy/remedy_lcdui.hpp index e3e8a0a..98a6c5b 100644 --- a/src/games/remedy/remedy_lcdui.hpp +++ b/src/games/remedy/remedy_lcdui.hpp @@ -80,6 +80,8 @@ struct NativeImageSurface { int height = 320; bool mutableImg = true; bool isMutable = true; + int maxDrawnX = 0; + int maxDrawnY = 0; std::vector pixels; // 0xAARRGGBB NativeImageSurface(int w = 240, int h = 320, uint32_t fill = 0xFFFFFFFFu) @@ -96,21 +98,32 @@ struct NativeImageSurface { void clear(uint32_t fill = 0xFF000000u) { std::fill(pixels.begin(), pixels.end(), fill); + maxDrawnX = 0; + maxDrawnY = 0; } void resize(int w, int h, uint32_t fill = 0xFF000000u) { width = std::max(1, w); height = std::max(1, h); + maxDrawnX = 0; + maxDrawnY = 0; pixels.assign(static_cast(width) * height, fill); } static bool DecodeFromMemory(const uint8_t* data, size_t len, NativeImageSurface* out); + inline uint32_t getPixel(int x, int y) const { + if (x < 0 || y < 0 || x >= width || y >= height) return 0; + return pixels[static_cast(y) * width + x]; + } + 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; + if (x > maxDrawnX) maxDrawnX = x; + if (y > maxDrawnY) maxDrawnY = y; uint32_t& dst = pixels[static_cast(y) * width + x]; if (a == 255) { dst = srcArgb | 0xFF000000u; @@ -318,6 +331,8 @@ struct NativeGraphicsState { 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; + if (x1 - 1 > target->maxDrawnX) target->maxDrawnX = x1 - 1; + if (y1 - 1 > target->maxDrawnY) target->maxDrawnY = y1 - 1; uint32_t a = (colorArgb >> 24) & 0xFFu; for (int py = y0; py < y1; ++py) { uint32_t* row = target->pixels.data() + static_cast(py) * target->width; @@ -541,6 +556,7 @@ struct LcduiScreenState { std::string title; std::string tickerText; uint32_t listenerRef = 0; + uint32_t selectCommandRef = 0; std::vector commands; bool fullScreen = true; int selectedIdx = 0; @@ -548,6 +564,7 @@ struct LcduiScreenState { // For List / ChoiceGroup: int choiceType = 1; // 1=EXCLUSIVE, 2=MULTIPLE, 3=IMPLICIT std::vector listItems; + std::vector listItemRefs; std::vector listImages; std::vector listSelected; // For Form: diff --git a/src/games/remedy/remedy_lcdui_natives.hpp b/src/games/remedy/remedy_lcdui_natives.hpp index 1d4d258..13dffd2 100644 --- a/src/games/remedy/remedy_lcdui_natives.hpp +++ b/src/games/remedy/remedy_lcdui_natives.hpp @@ -28,10 +28,14 @@ struct RuntimeAppContext { uint32_t currentDisplayableRef = 0; uint32_t midletRef = 0; uint32_t sharedGraphicsRef = 0; + uint32_t graphics3dRef = 0; + uint32_t listSelectCommandRef = 0; bool midletDestroyed = false; bool midletPaused = false; bool repaintPending = true; + bool inPaint = false; + bool paintedInStep = false; bool commandMenuOpen = false; int commandMenuSel = 0; int latchedKeyStates = 0; @@ -58,6 +62,7 @@ struct LcduiItemState { int choiceType = 1; int selectedIdx = 0; std::vector choices; + std::vector choiceRefs; std::vector choiceSel; uint32_t imageRef = 0; }; @@ -144,6 +149,93 @@ inline uint32_t createGraphicsForSurface(Jvm& vm, NativeImageSurface* surf) { } inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) { + // Register GC root and nativeData reference tracers + vm.traceExtraRoots = [ctx](const std::function& mark) { + if (!ctx) return; + mark(ctx->displayRef); + mark(ctx->currentDisplayableRef); + mark(ctx->midletRef); + mark(ctx->sharedGraphicsRef); + mark(ctx->graphics3dRef); + mark(ctx->listSelectCommandRef); + for (uint32_t r : ctx->serialRunnables) mark(r); + if (ctx->m3g) { + mark(ctx->m3g->boundGraphicsRef); + mark(ctx->m3g->boundTargetRef); + } + }; + vm.traceNativeRefs = [&vm](const JObject& obj, + const std::function& mark) { + if (!obj.nativeData) return; + const std::string& cn = obj.className; + if (cn == "javax/microedition/lcdui/Form" || + cn == "javax/microedition/lcdui/List" || + cn == "javax/microedition/lcdui/TextBox" || + cn == "javax/microedition/lcdui/Alert" || + cn == "javax/microedition/lcdui/Canvas" || + cn == "javax/microedition/lcdui/game/GameCanvas" || + cn == "com/nokia/mid/ui/FullCanvas" || + vm.isSubclassOf(cn, "javax/microedition/lcdui/Displayable")) { + auto* st = static_cast(obj.nativeData.get()); + mark(st->listenerRef); + mark(st->selectCommandRef); + mark(st->alertNextDisplayableRef); + for (const auto& c : st->commands) mark(c.cmdRef); + for (uint32_t r : st->listItemRefs) mark(r); + for (uint32_t r : st->listImages) mark(r); + for (uint32_t r : st->formItemRefs) mark(r); + } else if (cn == "javax/microedition/lcdui/StringItem" || + cn == "javax/microedition/lcdui/ImageItem" || + cn == "javax/microedition/lcdui/TextField" || + cn == "javax/microedition/lcdui/ChoiceGroup" || + cn == "javax/microedition/lcdui/Gauge" || + vm.isSubclassOf(cn, "javax/microedition/lcdui/Item")) { + auto* is = static_cast(obj.nativeData.get()); + mark(is->imageRef); + for (uint32_t r : is->choiceRefs) mark(r); + } else if (cn == "javax/microedition/lcdui/game/Sprite" || + vm.isSubclassOf(cn, "javax/microedition/lcdui/game/Sprite")) { + auto* sp = static_cast(obj.nativeData.get()); + mark(sp->imageRef); + } else if (cn == "javax/microedition/lcdui/game/TiledLayer" || + vm.isSubclassOf(cn, "javax/microedition/lcdui/game/TiledLayer")) { + auto* tl = static_cast(obj.nativeData.get()); + mark(tl->imageRef); + } else if (cn == "javax/microedition/m3g/VertexBuffer") { + auto* vb = static_cast(obj.nativeData.get()); + mark(vb->positionsRef); + mark(vb->normalsRef); + mark(vb->colorsRef); + mark(vb->texCoordsRef); + } else if (cn == "javax/microedition/m3g/Mesh" || + cn == "javax/microedition/m3g/MorphingMesh" || + cn == "javax/microedition/m3g/SkinnedMesh") { + auto* md = static_cast(obj.nativeData.get()); + mark(md->vertexBufferRef); + for (uint32_t r : md->submeshRefs) mark(r); + for (uint32_t r : md->appearanceRefs) mark(r); + for (uint32_t r : md->childrenRefs) mark(r); + } + }; + + // Initialize List.SELECT_COMMAND and AlertType.* static constants + uint32_t selCmd = vm.allocObject("javax/microedition/lcdui/Command"); + if (JObject* co = vm.getObj(selCmd)) { + co->setField("label", JValue::FromRef(vm.internString(""))); + co->setField("type", JValue::FromInt(1)); // SCREEN + co->setField("priority", JValue::FromInt(0)); + } + ctx->listSelectCommandRef = selCmd; + vm.setStaticFieldVal("javax/microedition/lcdui/List", "SELECT_COMMAND", + "Ljavax/microedition/lcdui/Command;", + JValue::FromRef(selCmd)); + for (const char* atName : + {"INFO", "WARNING", "ERROR", "ALARM", "CONFIRMATION"}) { + uint32_t atRef = vm.allocObject("javax/microedition/lcdui/AlertType"); + vm.setStaticFieldVal("javax/microedition/lcdui/AlertType", atName, + "Ljavax/microedition/lcdui/AlertType;", + JValue::FromRef(atRef)); + } // ------------------------------------------------------------------------- // javax.microedition.midlet.MIDlet // ------------------------------------------------------------------------- @@ -363,11 +455,41 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) { ctx->repaintPending = true; return JValue::Null(); }); - v.registerWildcardNative(cls, "serviceRepaints", - [ctx](Jvm&, JThread&, JValue*) -> JValue { - ctx->repaintPending = true; - return JValue::Null(); - }); + v.registerWildcardNative( + cls, "serviceRepaints", + [ctx](Jvm& vmRef, JThread&, JValue*) -> JValue { + uint32_t dispRef = ctx->currentDisplayableRef; + if (!ctx->inPaint && dispRef != 0 && + isCanvasDisplayable(vmRef, dispRef)) { + JObject* dispObj = vmRef.getObj(dispRef); + if (dispObj) { + ctx->inPaint = true; + ctx->repaintPending = false; + JObject* gObj = vmRef.getObj(ctx->sharedGraphicsRef); + if (gObj && gObj->nativeData) { + auto* gs = + static_cast(gObj->nativeData.get()); + gs->resetTarget(&ctx->canvasFb); + } + auto [rc, rm] = vmRef.resolveMethod( + dispObj->className, "paint", + "(Ljavax/microedition/lcdui/Graphics;)V", false); + if (rm && !rm->code.empty()) { + JThread paintTh; + vmRef.invokeManagedSync( + paintTh, rc, rm, + {JValue::FromRef(dispRef), + JValue::FromRef(ctx->sharedGraphicsRef)}, + 25000000); + } + ctx->inPaint = false; + ctx->paintedInStep = true; + return JValue::Null(); + } + } + ctx->repaintPending = true; + return JValue::Null(); + }); v.registerWildcardNative(cls, "setTitle", [ctx](Jvm& vmRef, JThread&, JValue* a) -> JValue { LcduiScreenState* st = ensureScreenState(vmRef, a[0].ref); @@ -1129,6 +1251,11 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) { } return JValue::Null(); }); + vm.registerWildcardNative( + "javax/microedition/lcdui/Graphics", "getDisplayColor", + [](Jvm&, JThread&, JValue* a) -> JValue { + return JValue::FromInt(a[1].i & 0x00FFFFFF); + }); // com.nokia.mid.ui.DirectUtils / DirectGraphics vm.registerWildcardNative( @@ -1154,6 +1281,193 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) { auto surf = std::make_shared(w, h, true, col); return JValue::FromRef(createImageObjectFromSurface(v, surf)); }); + for (const char* dgCls : + {"com/nokia/mid/ui/DirectGraphics", + "javax/microedition/lcdui/Graphics"}) { + vm.registerWildcardNative( + dgCls, "setARGBColor", + [getGraphicsState](Jvm& v, JThread&, JValue* a) -> JValue { + if (auto* g = getGraphicsState(v, a[0].ref)) { + g->colorArgb = static_cast(a[1].i); + } + return JValue::Null(); + }); + vm.registerWildcardNative( + dgCls, "getAlphaComponent", + [getGraphicsState](Jvm& v, JThread&, JValue* a) -> JValue { + auto* g = getGraphicsState(v, a[0].ref); + return JValue::FromInt( + g ? static_cast((g->colorArgb >> 24) & 0xFFu) : 255); + }); + vm.registerWildcardNative( + dgCls, "getNativePixelFormat", + [](Jvm&, JThread&, JValue*) -> JValue { + return JValue::FromInt(8888); // TYPE_INT_8888_ARGB + }); + vm.registerWildcardNative( + dgCls, "drawTriangle", + [getGraphicsState](Jvm& v, JThread&, JValue* a) -> JValue { + if (auto* g = getGraphicsState(v, a[0].ref)) { + if (a[7].i != 0) g->colorArgb = static_cast(a[7].i); + g->drawLine(a[1].i, a[2].i, a[3].i, a[4].i); + g->drawLine(a[3].i, a[4].i, a[5].i, a[6].i); + g->drawLine(a[5].i, a[6].i, a[1].i, a[2].i); + } + return JValue::Null(); + }); + vm.registerWildcardNative( + dgCls, "fillTriangle", + [getGraphicsState, dgCls](Jvm& v, JThread&, JValue* a) -> JValue { + if (auto* g = getGraphicsState(v, a[0].ref)) { + if (a[7].i != 0 && dgCls[0] == 'c') { + g->colorArgb = static_cast(a[7].i); + } + g->fillTriangle(a[1].i, a[2].i, a[3].i, a[4].i, a[5].i, a[6].i); + } + return JValue::Null(); + }); + vm.registerWildcardNative( + dgCls, "drawPolygon", + [getGraphicsState](Jvm& v, JThread&, JValue* a) -> JValue { + auto* g = getGraphicsState(v, a[0].ref); + JObject* xArr = v.getObj(a[1].ref); + JObject* yArr = v.getObj(a[3].ref); + if (!g || !xArr || !yArr) return JValue::Null(); + int xOff = a[2].i, yOff = a[4].i, n = a[5].i; + g->colorArgb = static_cast(a[6].i); + for (int i = 0; i < n; ++i) { + int j = (i + 1) % n; + if (xOff + i >= 0 && yOff + i >= 0 && xOff + j >= 0 && + yOff + j >= 0 && + static_cast(xOff + i) < xArr->intArr.size() && + static_cast(yOff + i) < yArr->intArr.size() && + static_cast(xOff + j) < xArr->intArr.size() && + static_cast(yOff + j) < yArr->intArr.size()) { + g->drawLine(xArr->intArr[xOff + i], yArr->intArr[yOff + i], + xArr->intArr[xOff + j], yArr->intArr[yOff + j]); + } + } + return JValue::Null(); + }); + vm.registerWildcardNative( + dgCls, "fillPolygon", + [getGraphicsState](Jvm& v, JThread&, JValue* a) -> JValue { + auto* g = getGraphicsState(v, a[0].ref); + JObject* xArr = v.getObj(a[1].ref); + JObject* yArr = v.getObj(a[3].ref); + if (!g || !xArr || !yArr) return JValue::Null(); + int xOff = a[2].i, yOff = a[4].i, n = a[5].i; + g->colorArgb = static_cast(a[6].i); + for (int i = 1; i + 1 < n; ++i) { + if (xOff + i + 1 < static_cast(xArr->intArr.size()) && + yOff + i + 1 < static_cast(yArr->intArr.size())) { + g->fillTriangle(xArr->intArr[xOff], yArr->intArr[yOff], + xArr->intArr[xOff + i], yArr->intArr[yOff + i], + xArr->intArr[xOff + i + 1], + yArr->intArr[yOff + i + 1]); + } + } + return JValue::Null(); + }); + vm.registerWildcardNative( + dgCls, "drawPixels", + [getGraphicsState](Jvm& v, JThread&, JValue* a) -> JValue { + auto* g = getGraphicsState(v, a[0].ref); + JObject* arr = v.getObj(a[1].ref); + if (!g || !arr) return JValue::Null(); + bool trans = (a[2].i != 0); + int offset = a[3].i, scanlen = a[4].i, x = a[5].i, y = a[6].i; + int w = a[7].i, h = a[8].i, manip = a[9].i, fmt = a[10].i; + bool flipX = (manip & 8192) != 0; + bool flipY = (manip & 16384) != 0; + int rot = manip & 0x1FFF; + if (rot == 180) { + flipX = !flipX; + flipY = !flipY; + } + for (int row = 0; row < h; ++row) { + int sRow = flipY ? (h - 1 - row) : row; + for (int col = 0; col < w; ++col) { + int sCol = flipX ? (w - 1 - col) : col; + int idx = offset + sRow * scanlen + sCol; + if (idx < 0) continue; + uint32_t argb = 0; + if (arr->arrayKind == ArrayKind::Int && + static_cast(idx) < arr->intArr.size()) { + argb = static_cast(arr->intArr[idx]); + if (!trans || fmt == 888) argb |= 0xFF000000u; + } else if (arr->arrayKind == ArrayKind::Short && + static_cast(idx) < arr->shortArr.size()) { + uint16_t spx = static_cast(arr->shortArr[idx]); + if (fmt == 565) { + uint32_t r = ((spx >> 11) & 0x1Fu) * 255u / 31u; + uint32_t gr = ((spx >> 5) & 0x3Fu) * 255u / 63u; + uint32_t b = (spx & 0x1Fu) * 255u / 31u; + argb = 0xFF000000u | (r << 16) | (gr << 8) | b; + } else if (fmt == 1555) { + uint32_t al = (!trans || (spx & 0x8000u)) ? 255u : 0u; + uint32_t r = ((spx >> 10) & 0x1Fu) * 255u / 31u; + uint32_t gr = ((spx >> 5) & 0x1Fu) * 255u / 31u; + uint32_t b = (spx & 0x1Fu) * 255u / 31u; + argb = (al << 24) | (r << 16) | (gr << 8) | b; + } else { + // 4444 or 444 + uint32_t al = (!trans || fmt == 444) + ? 255u + : (((spx >> 12) & 0xFu) * 17u); + uint32_t r = ((spx >> 8) & 0xFu) * 17u; + uint32_t gr = ((spx >> 4) & 0xFu) * 17u; + uint32_t b = (spx & 0xFu) * 17u; + argb = (al << 24) | (r << 16) | (gr << 8) | b; + } + } else { + continue; + } + if ((argb >> 24) == 0) continue; + g->putClipped(x + g->transX + col, y + g->transY + row, argb); + } + } + return JValue::Null(); + }); + vm.registerWildcardNative( + dgCls, "getPixels", + [getGraphicsState](Jvm& v, JThread&, JValue* a) -> JValue { + auto* g = getGraphicsState(v, a[0].ref); + JObject* arr = v.getObj(a[1].ref); + if (!g || !g->target || !arr) return JValue::Null(); + int offset = a[3].i, scanlen = a[4].i, x = a[5].i, y = a[6].i; + int w = a[7].i, h = a[8].i, fmt = a[9].i; + for (int row = 0; row < h; ++row) { + for (int col = 0; col < w; ++col) { + int idx = offset + row * scanlen + col; + if (idx < 0) continue; + uint32_t argb = g->target->getPixel(x + g->transX + col, + y + g->transY + row); + if (arr->arrayKind == ArrayKind::Int && + static_cast(idx) < arr->intArr.size()) { + arr->intArr[idx] = static_cast(argb); + } else if (arr->arrayKind == ArrayKind::Short && + static_cast(idx) < arr->shortArr.size()) { + uint32_t al = (argb >> 24) & 0xFFu; + uint32_t r = (argb >> 16) & 0xFFu; + uint32_t gr = (argb >> 8) & 0xFFu; + uint32_t b = argb & 0xFFu; + uint16_t spx = 0; + if (fmt == 565) { + spx = static_cast(((r >> 3) << 11) | + ((gr >> 2) << 5) | (b >> 3)); + } else { + spx = static_cast(((al >> 4) << 12) | + ((r >> 4) << 8) | + ((gr >> 4) << 4) | (b >> 4)); + } + arr->shortArr[idx] = static_cast(spx); + } + } + } + return JValue::Null(); + }); + } vm.registerWildcardNative("com/nokia/mid/ui/DeviceControl", "setLights", [](Jvm&, JThread&, JValue*) -> JValue { return JValue::Null(); }); vm.registerWildcardNative("com/nokia/mid/ui/DeviceControl", "startVibra", @@ -1243,15 +1557,19 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) { // List vm.registerWildcardNative( "javax/microedition/lcdui/List", "", - [](Jvm& v, JThread&, JValue* a) -> JValue { + [ctx](Jvm& v, JThread&, JValue* a) -> JValue { LcduiScreenState* st = ensureScreenState(v, a[0].ref); if (st) { st->title = v.readString(a[1].ref); st->choiceType = a[2].i; + if (st->choiceType == 3) { + st->selectCommandRef = ctx->listSelectCommandRef; + } JObject* strArr = v.getObj(a[3].ref); if (strArr) { for (uint32_t sref : strArr->refArr) { st->listItems.push_back(v.readString(sref)); + st->listItemRefs.push_back(sref); st->listImages.push_back(0); st->listSelected.push_back(false); } @@ -1265,11 +1583,28 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) { LcduiScreenState* st = ensureScreenState(v, a[0].ref); if (!st) return JValue::FromInt(0); st->listItems.push_back(v.readString(a[1].ref)); + st->listItemRefs.push_back(a[1].ref); st->listImages.push_back(a[2].ref); st->listSelected.push_back(false); ctx->repaintPending = true; return JValue::FromInt(static_cast(st->listItems.size()) - 1); }); + vm.registerWildcardNative( + "javax/microedition/lcdui/List", "insert", + [ctx](Jvm& v, JThread&, JValue* a) -> JValue { + LcduiScreenState* st = ensureScreenState(v, a[0].ref); + if (st) { + int idx = std::clamp( + a[1].i, 0, static_cast(st->listItems.size())); + st->listItems.insert(st->listItems.begin() + idx, + v.readString(a[2].ref)); + st->listItemRefs.insert(st->listItemRefs.begin() + idx, a[2].ref); + st->listImages.insert(st->listImages.begin() + idx, a[3].ref); + st->listSelected.insert(st->listSelected.begin() + idx, false); + ctx->repaintPending = true; + } + return JValue::Null(); + }); vm.registerWildcardNative( "javax/microedition/lcdui/List", "set", [ctx](Jvm& v, JThread&, JValue* a) -> JValue { @@ -1277,6 +1612,7 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) { if (st && a[1].i >= 0 && static_cast(a[1].i) < st->listItems.size()) { st->listItems[a[1].i] = v.readString(a[2].ref); + st->listItemRefs[a[1].i] = a[2].ref; st->listImages[a[1].i] = a[3].ref; ctx->repaintPending = true; } @@ -1289,6 +1625,7 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) { if (st && a[1].i >= 0 && static_cast(a[1].i) < st->listItems.size()) { st->listItems.erase(st->listItems.begin() + a[1].i); + st->listItemRefs.erase(st->listItemRefs.begin() + a[1].i); st->listImages.erase(st->listImages.begin() + a[1].i); st->listSelected.erase(st->listSelected.begin() + a[1].i); ctx->repaintPending = true; @@ -1301,6 +1638,7 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) { LcduiScreenState* st = ensureScreenState(v, a[0].ref); if (st) { st->listItems.clear(); + st->listItemRefs.clear(); st->listImages.clear(); st->listSelected.clear(); st->selectedIdx = 0; @@ -1319,6 +1657,11 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) { LcduiScreenState* st = ensureScreenState(v, a[0].ref); if (st && a[1].i >= 0 && static_cast(a[1].i) < st->listItems.size()) { + if (static_cast(a[1].i) < + st->listItemRefs.size() && + st->listItemRefs[a[1].i] != 0) { + return JValue::FromRef(st->listItemRefs[a[1].i]); + } return JValue::FromRef( v.internString(st->listItems[a[1].i])); } @@ -1351,7 +1694,9 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) { return JValue::FromInt(st->selectedIdx == a[1].i ? 1 : 0); }); vm.registerWildcardNative("javax/microedition/lcdui/List", "setSelectCommand", - [](Jvm&, JThread&, JValue*) -> JValue { + [](Jvm& v, JThread&, JValue* a) -> JValue { + LcduiScreenState* st = ensureScreenState(v, a[0].ref); + if (st) st->selectCommandRef = a[1].ref; return JValue::Null(); }); @@ -1531,6 +1876,7 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) { if (arr) { for (uint32_t sref : arr->refArr) { is->choices.push_back(v.readString(sref)); + is->choiceRefs.push_back(sref); is->choiceSel.push_back(false); } } @@ -1543,6 +1889,7 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) { LcduiItemState* is = ensureItemState(v, a[0].ref); if (!is) return JValue::FromInt(0); is->choices.push_back(v.readString(a[1].ref)); + is->choiceRefs.push_back(a[1].ref); is->choiceSel.push_back(false); ctx->repaintPending = true; return JValue::FromInt(static_cast(is->choices.size()) - 1); @@ -1571,10 +1918,32 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) { LcduiItemState* is = ensureItemState(v, a[0].ref); if (is && a[1].i >= 0 && static_cast(a[1].i) < is->choices.size()) { + if (static_cast(a[1].i) < is->choiceRefs.size() && + is->choiceRefs[a[1].i] != 0) { + return JValue::FromRef(is->choiceRefs[a[1].i]); + } return JValue::FromRef(v.internString(is->choices[a[1].i])); } return JValue::FromRef(v.internString("")); }); + vm.registerWildcardNative( + "javax/microedition/lcdui/ChoiceGroup", "isSelected", + [](Jvm& v, JThread&, JValue* a) -> JValue { + LcduiItemState* is = ensureItemState(v, a[0].ref); + if (!is) return JValue::FromInt(0); + if (is->choiceType == 2 && a[1].i >= 0 && + static_cast(a[1].i) < is->choiceSel.size()) { + return JValue::FromInt(is->choiceSel[a[1].i] ? 1 : 0); + } + return JValue::FromInt(is->selectedIdx == a[1].i ? 1 : 0); + }); + vm.registerWildcardNative( + "javax/microedition/lcdui/ChoiceGroup", "size", + [](Jvm& v, JThread&, JValue* a) -> JValue { + LcduiItemState* is = ensureItemState(v, a[0].ref); + return JValue::FromInt( + is ? static_cast(is->choices.size()) : 0); + }); vm.registerWildcardNative( "javax/microedition/lcdui/Gauge", "", @@ -1610,6 +1979,17 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) { LcduiItemState* is = ensureItemState(v, a[0].ref); return JValue::FromInt(is ? is->maxValue : 100); }); + vm.registerWildcardNative( + "javax/microedition/lcdui/Gauge", "setMaxValue", + [ctx](Jvm& v, JThread&, JValue* a) -> JValue { + LcduiItemState* is = ensureItemState(v, a[0].ref); + if (is) { + is->maxValue = std::max(1, a[1].i); + is->value = std::clamp(is->value, 0, is->maxValue); + ctx->repaintPending = true; + } + return JValue::Null(); + }); // ------------------------------------------------------------------------- // javax.microedition.lcdui.game.Sprite / TiledLayer / LayerManager @@ -1781,12 +2161,11 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) { // ------------------------------------------------------------------------- vm.registerWildcardNative( "javax/microedition/m3g/Graphics3D", "getInstance", - [](Jvm& v, JThread&, JValue*) -> JValue { - static uint32_t g3dRef = 0; - if (g3dRef == 0) { - g3dRef = v.allocObject("javax/microedition/m3g/Graphics3D"); + [ctx](Jvm& v, JThread&, JValue*) -> JValue { + if (ctx->graphics3dRef == 0) { + ctx->graphics3dRef = v.allocObject("javax/microedition/m3g/Graphics3D"); } - return JValue::FromRef(g3dRef); + return JValue::FromRef(ctx->graphics3dRef); }); vm.registerWildcardNative( "javax/microedition/m3g/Graphics3D", "bindTarget", diff --git a/src/games/remedy/remedy_main.cpp b/src/games/remedy/remedy_main.cpp index a9d5a4e..5a86674 100644 --- a/src/games/remedy/remedy_main.cpp +++ b/src/games/remedy/remedy_main.cpp @@ -8,6 +8,7 @@ #include #include +#include #include #include #include @@ -65,6 +66,7 @@ static const char* const kActionNames[ACT_COUNT] = { struct RemedyConfig { bool hwAccel3D = true; + int scaleMode = 0; // 0=Auto, 1=Full Stretch, 2=1:1 (240x320) int softbarMode = 0; // 0=Auto (non-fullscreen Canvas), 1=Always Overlay, 2=Hidden int fpsLimit = 30; // 30 or 60 FPS bool audioEnabled = true; @@ -95,6 +97,7 @@ struct RemedyConfig { std::string v = line.substr(eq + 1); int iv = std::atoi(v.c_str()); if (k == "hwAccel3D") hwAccel3D = (iv != 0); + else if (k == "scaleMode") scaleMode = std::clamp(iv, 0, 2); else if (k == "softbarMode") softbarMode = std::clamp(iv, 0, 2); else if (k == "fpsLimit") fpsLimit = (iv == 60) ? 60 : 30; else if (k == "audioEnabled") audioEnabled = (iv != 0); @@ -115,6 +118,7 @@ struct RemedyConfig { std::ofstream f(p, std::ios::trunc); if (!f) return; f << "hwAccel3D=" << (hwAccel3D ? 1 : 0) << "\n"; + f << "scaleMode=" << scaleMode << "\n"; f << "softbarMode=" << softbarMode << "\n"; f << "fpsLimit=" << fpsLimit << "\n"; f << "audioEnabled=" << (audioEnabled ? 1 : 0) << "\n"; @@ -336,6 +340,7 @@ class RemedyEmulator { } void shutdown() { + unloadMidletSuite(); if (canvasXimg) { canvasXimg->data = nullptr; XDestroyImage(canvasXimg); @@ -347,6 +352,29 @@ class RemedyEmulator { neoWin.destroy(); } + void unloadMidletSuite() { + cldcRuntime.sound.stopAll(); + activeCanvasKeys.clear(); + if (vm && hasLoadedMidlet && appCtx.midletRef != 0) { + JObject* mo = vm->getObj(appCtx.midletRef); + if (mo) { + auto [dc, dm] = + vm->resolveMethod(mo->className, "destroyApp", "(Z)V", false); + if (dm && !dm->code.empty()) { + JThread dTh; + vm->invokeManagedSync( + dTh, dc, dm, + {JValue::FromRef(appCtx.midletRef), JValue::FromInt(1)}, + 1000000); + } + } + } + vm.reset(); + appCtx = RuntimeAppContext{}; + jar = ZipArchive{}; + hasLoadedMidlet = false; + } + void grabKeyboard() { if (!neoWin.dpy || neoWin.win == None) return; if (isExternalOverlayActive()) { @@ -490,8 +518,7 @@ class RemedyEmulator { } bool loadMidletSuite(const std::string& path) { - cldcRuntime.sound.stopAll(); - activeCanvasKeys.clear(); + unloadMidletSuite(); midletTickCount = 0; std::string errMsg; if (!loadSuiteFromJarOrJad(path, &jar, &suite, &errMsg)) { @@ -538,7 +565,7 @@ class RemedyEmulator { vm->resolveMethod(mainClass, "", "()V", false); if (initM && !initM->code.empty()) { vm->invokeManagedSync(mainTh, initCls, initM, - {JValue::FromRef(midletRef)}, 5000000); + {JValue::FromRef(midletRef)}, 20000000); } mainTh.pendingExceptionRef = 0; mainTh.frames.clear(); @@ -546,7 +573,7 @@ class RemedyEmulator { vm->resolveMethod(mainClass, "startApp", "()V", false); if (startM && !startM->code.empty()) { vm->invokeManagedSync(mainTh, startCls, startM, - {JValue::FromRef(midletRef)}, 25000000); + {JValue::FromRef(midletRef)}, 50000000); } currentJarOrJadPath = path; @@ -598,20 +625,27 @@ class RemedyEmulator { // Use a wall-clock budget (~60% of the frame interval) instead of a fixed // instruction count so CPU-heavy loaders (level/asset unpacking in games // like Castlevania) run at full interpreter speed, while idle games that - // sleep in Thread.sleep() / wait() still return to poll() immediately. + // sleep in Thread.sleep() / wait() or finish a serviceRepaints() frame + // return to poll() immediately. cldcRuntime.tickTimersAndSerialCallbacks(*vm); { int64_t frameMs = 1000 / std::max(1, cfg.fpsLimit); int64_t budgetMs = std::max(6, (frameMs * 6) / 10); int64_t deadline = Jvm::NowMs() + budgetMs; int slices = 0; + appCtx.paintedInStep = false; do { vm->stepThreads(20000); ++slices; } while (slices < 64 && !vm->exitRequested && !appCtx.midletDestroyed && - vm->anyThreadReady() && Jvm::NowMs() < deadline); + !appCtx.paintedInStep && vm->anyThreadReady() && + Jvm::NowMs() < deadline); } midletTickCount++; + if (midletTickCount % 120 == 0 || + vm->usedHeapBytes() > 24 * 1024 * 1024) { + vm->collectGarbage(); + } if (!activeCanvasKeys.empty()) { int64_t nowMs = Jvm::NowMs(); @@ -633,8 +667,7 @@ class RemedyEmulator { } if (appCtx.midletDestroyed || vm->exitRequested) { - cldcRuntime.sound.stopAll(); - hasLoadedMidlet = false; + unloadMidletSuite(); mode = EmuUiMode::BROWSER; renderBrowserMenu(); return; @@ -671,7 +704,9 @@ class RemedyEmulator { // Active Displayable is a full-screen 240x320 Canvas / GameCanvas JObject* dispObj = vm->getObj(dispRef); - if (dispObj && appCtx.repaintPending) { + if (dispObj && appCtx.repaintPending && !appCtx.inPaint) { + appCtx.inPaint = true; + appCtx.repaintPending = false; JObject* gObj = vm->getObj(appCtx.sharedGraphicsRef); if (gObj && gObj->nativeData) { auto* gs = static_cast(gObj->nativeData.get()); @@ -686,14 +721,54 @@ class RemedyEmulator { paintTh, rc, rm, {JValue::FromRef(dispRef), JValue::FromRef(appCtx.sharedGraphicsRef)}, - 250000); + 25000000); } - appCtx.repaintPending = false; + appCtx.inPaint = false; } - // Blit 240x320 ARGB8888 canvasFb to NeoWindow's offscreen Pixmap - std::memcpy(ximgPixels.data(), appCtx.canvasFb.pixels.data(), - 240 * 320 * sizeof(uint32_t)); + // Blit 240x320 ARGB8888 canvasFb to NeoWindow's offscreen Pixmap, + // automatically scaling sub-QVGA games (128x128, 128x160, 176x208, 176x220) + int maxX = appCtx.canvasFb.maxDrawnX; + int maxY = appCtx.canvasFb.maxDrawnY; + if (cfg.scaleMode != 2 && maxX > 0 && maxX < 192 && maxY > 0 && maxY < 236) { + int srcW = 240; + int srcH = 320; + if (maxX < 128 && maxY < 128) { + srcW = 128; + srcH = 128; + } else if (maxX < 128 && maxY < 160) { + srcW = 128; + srcH = 160; + } else if (maxX < 176 && maxY < 208) { + srcW = 176; + srcH = 208; + } else if (maxX < 176 && maxY < 220) { + srcW = 176; + srcH = 220; + } else { + srcW = maxX + 1; + srcH = maxY + 1; + } + int dstW = 240; + int dstH = (cfg.scaleMode == 1) + ? 320 + : std::min(320, (srcH * 240 + srcW / 2) / srcW); + int dstY0 = (320 - dstH) / 2; + std::fill(ximgPixels.begin(), ximgPixels.end(), 0xFF000000u); + const uint32_t* srcPx = appCtx.canvasFb.pixels.data(); + for (int dy = 0; dy < dstH; ++dy) { + int sy = (dy * srcH) / dstH; + const uint32_t* sRow = srcPx + sy * 240; + uint32_t* dRow = ximgPixels.data() + (dstY0 + dy) * 240; + for (int dx = 0; dx < dstW; ++dx) { + int sx = (dx * srcW) / dstW; + dRow[dx] = sRow[sx]; + } + } + } else { + std::memcpy(ximgPixels.data(), appCtx.canvasFb.pixels.data(), + 240 * 320 * sizeof(uint32_t)); + } XPutImage(neoWin.dpy, neoWin.pix, neoWin.gc, canvasXimg, 0, 0, 0, 0, 240, 320); // Optional softkey bar or command popup overlay via NeoUI @@ -813,6 +888,8 @@ class RemedyEmulator { items.push_back("Resume MIDlet"); items.push_back("MIDlet Commands..."); } + const char* scModes[] = {"< Auto >", "< Full Stretch >", "< 1:1 (240x320) >"}; + items.push_back(std::string("Canvas Scale: ") + scModes[cfg.scaleMode]); items.push_back(std::string("3D Engine: ") + (m3g.useHardwareGl ? "< Adreno FD304 GL >" : "< Software 3D >")); const char* sbModes[] = {"< Auto >", "< Overlay >", "< Full 240x320 >"}; @@ -1069,7 +1146,7 @@ class RemedyEmulator { vm->invokeManagedSync( keyTh, rc, rm, {JValue::FromRef(dispRef), JValue::FromInt(midpKeyCode)}, - 100000); + 5000000); } } @@ -1153,21 +1230,28 @@ class RemedyEmulator { static_cast(st->selectedIdx) < st->listSelected.size()) { st->listSelected[st->selectedIdx] = !st->listSelected[st->selectedIdx]; } - // Trigger IMPLICIT list command or first OK/SCREEN command + // Trigger IMPLICIT list selectCommand (List.SELECT_COMMAND by default) + // or first OK/SCREEN/ITEM command uint32_t cmdToFire = 0; - for (const auto& c : st->commands) { - if (c.type == 1 || c.type == 4 || c.type == 8) { - cmdToFire = c.cmdRef; - break; + if (st->choiceType == 3) { + cmdToFire = st->selectCommandRef != 0 + ? st->selectCommandRef + : appCtx.listSelectCommandRef; + } + if (cmdToFire == 0) { + for (const auto& c : st->commands) { + if (c.type == 1 || c.type == 4 || c.type == 8) { + cmdToFire = c.cmdRef; + break; + } } } + if (cmdToFire == 0) { + cmdToFire = appCtx.listSelectCommandRef; + } JThread cmdTh; if (cmdToFire != 0) { invokeCommandOnDisplayable(*vm, cmdTh, dispRef, cmdToFire); - } else if (st->listenerRef != 0) { - // List.SELECT_COMMAND (null or synthetic command) - uint32_t selCmd = vm->allocObject("javax/microedition/lcdui/Command"); - invokeCommandOnDisplayable(*vm, cmdTh, dispRef, selCmd); } appCtx.repaintPending = true; } @@ -1500,7 +1584,11 @@ class RemedyEmulator { appCtx.repaintPending = true; return true; } - if (choice.rfind("3D Engine:", 0) == 0) { + if (choice.rfind("Canvas Scale:", 0) == 0) { + int dir = (ks == XK_Left) ? 2 : 1; + cfg.scaleMode = (cfg.scaleMode + dir) % 3; + cfg.save(); + } else if (choice.rfind("3D Engine:", 0) == 0) { cfg.hwAccel3D = !cfg.hwAccel3D; m3g.useHardwareGl = cfg.hwAccel3D && m3g.hwInitialized; cfg.save(); diff --git a/src/neoui/neoui.cpp b/src/neoui/neoui.cpp index 9d870d5..3254a57 100644 --- a/src/neoui/neoui.cpp +++ b/src/neoui/neoui.cpp @@ -1459,7 +1459,7 @@ bool NeoWindow::create(const char* resName, const char* resClass, swa.override_redirect = overrideRedirect ? True : False; swa.background_pixel = 0x222222; swa.border_pixel = 0x005577; - swa.event_mask = eventMask | VisibilityChangeMask | FocusChangeMask; + swa.event_mask = eventMask | VisibilityChangeMask | FocusChangeMask | ButtonPressMask; win = XCreateWindow( dpy, root, x, y, width, height, 0, DefaultDepth(dpy, screen), @@ -2880,6 +2880,50 @@ int neoui_poll_event(int timeout_ms) { } continue; } + if (ev.type == ButtonPress && ctx->visible) { + if (ev.xbutton.button == Button4) { + ctx->lastEventKey = NEO_KEY_UP; + ctx->lastEventKeysym = XK_Up; + ctx->lastEventType = NEO_EV_KEY_PRESS; + return NEO_EV_KEY_PRESS; + } + if (ev.xbutton.button == Button5) { + ctx->lastEventKey = NEO_KEY_DOWN; + ctx->lastEventKeysym = XK_Down; + ctx->lastEventType = NEO_EV_KEY_PRESS; + return NEO_EV_KEY_PRESS; + } + if (ev.xbutton.button == Button3) { + ctx->lastEventKey = NEO_KEY_SOFT_RIGHT; + ctx->lastEventKeysym = XK_F2; + ctx->lastEventType = NEO_EV_SOFTKEY_RIGHT; + return NEO_EV_SOFTKEY_RIGHT; + } + if (ev.xbutton.button == Button1) { + int winW = ctx->w ? ctx->w->width : NEO_WIN_W; + int winH = ctx->w ? ctx->w->height : NEO_WIN_H; + int sbH = NEO_SOFTBAR_H; + if (ev.xbutton.y >= winH - sbH) { + if (ev.xbutton.x < winW / 3) { + ctx->lastEventKey = NEO_KEY_SOFT_LEFT; + ctx->lastEventKeysym = XK_F1; + ctx->lastEventType = NEO_EV_SOFTKEY_LEFT; + return NEO_EV_SOFTKEY_LEFT; + } + if (ev.xbutton.x > (winW * 2) / 3) { + ctx->lastEventKey = NEO_KEY_SOFT_RIGHT; + ctx->lastEventKeysym = XK_F2; + ctx->lastEventType = NEO_EV_SOFTKEY_RIGHT; + return NEO_EV_SOFTKEY_RIGHT; + } + } + ctx->lastEventKey = NEO_KEY_OK; + ctx->lastEventKeysym = XK_Return; + ctx->lastEventType = NEO_EV_KEY_PRESS; + return NEO_EV_KEY_PRESS; + } + continue; + } if (ev.type == KeyPress || ev.type == KeyRelease) { if (bananarchy::isExternalOverlayOrLockActive(ctx->appName) || bananarchy::monotonicMs() < ctx->overlayGraceUntilMs) { diff --git a/src/sxmo-dmenu/dmenu.c b/src/sxmo-dmenu/dmenu.c index 216711c..a93e582 100644 --- a/src/sxmo-dmenu/dmenu.c +++ b/src/sxmo-dmenu/dmenu.c @@ -2019,6 +2019,8 @@ readstdin(void) static int bt_is_unblocked_fast(void) { + if (access("/run/bluetoothd.pid", F_OK) != 0) + return 0; DIR *d = opendir("/sys/class/rfkill"); if (!d) return 0; @@ -2689,7 +2691,12 @@ open_builtin_menu(const char *menu_name, int keep_idx) int is_ear = (strstr(out_dev, "Earpiece") != NULL || strstr(out_dev, "earpiece") != NULL); int is_hp = (strstr(out_dev, "Headphone") != NULL || strstr(out_dev, "headphone") != NULL || strstr(out_dev, "Headset") != NULL || strstr(out_dev, "headset") != NULL); - int is_spk = (!is_ear && !is_hp); + int is_bt = (strstr(out_dev, "Bluetooth") != NULL || strstr(out_dev, "bluetooth") != NULL || + strstr(out_dev, "bluez") != NULL); + int is_spk = (!is_ear && !is_hp && !is_bt); + + snprintf(label, sizeof(label), "%s Route to Bluetooth %s", ICON_BTH, is_bt ? ICON_TON : ICON_TOF); + add_menu_item(label, "printf 'Bluetooth\\n' > /tmp/sxmo_audio_out_device; sxmo_audio.sh device set Bluetooth >/dev/null 2>&1", 1); snprintf(label, sizeof(label), "%s Route to Speaker %s", ICON_MUS, is_spk ? ICON_TON : ICON_TOF); add_menu_item(label, "printf 'Speaker\\n' > /tmp/sxmo_audio_out_device; sxmo_audio.sh device set Speaker >/dev/null 2>&1", 1); diff --git a/src/sxmo-dwm/dwm.c b/src/sxmo-dwm/dwm.c index b15617f..44d51b6 100644 --- a/src/sxmo-dwm/dwm.c +++ b/src/sxmo-dwm/dwm.c @@ -636,6 +636,9 @@ unswallow(Client *c) setclientstate(c, NormalState); } +static void dwm_cursor_set_visible(int show); +static void dwm_handle_softbar_click(int x); + void buttonpress(XEvent *e) { @@ -645,6 +648,11 @@ buttonpress(XEvent *e) Monitor *m; XButtonPressedEvent *ev = &e->xbutton; + dwm_cursor_set_visible(1); + if (selmon && ev->window == selmon->softwin && ev->button == Button1) { + dwm_handle_softbar_click(ev->x); + return; + } click = ClkRootWin; /* focus monitor if necessary */ if (!((c = wintoclient(ev->window)) && c->iskbd) @@ -2073,6 +2081,52 @@ flush_pending_softkey(void) } } +static long long last_mouse_ms = 0; +static int cursor_hidden = 0; + +static void +dwm_cursor_set_visible(int show) +{ + typedef void (*xfixes_cursor_fn)(Display *, Window); + static int xfixes_init = 0; + static xfixes_cursor_fn fn_hide = NULL; + static xfixes_cursor_fn fn_show = NULL; + + if (!dpy || !root) + return; + if (!xfixes_init) { + xfixes_init = 1; + void *h = dlopen("libXfixes.so.3", RTLD_LAZY | RTLD_LOCAL); + if (h) { + fn_hide = (xfixes_cursor_fn)dlsym(h, "XFixesHideCursor"); + fn_show = (xfixes_cursor_fn)dlsym(h, "XFixesShowCursor"); + } + } + if (show) { + last_mouse_ms = dwm_now_ms(); + if (cursor_hidden && fn_show) { + fn_show(dpy, root); + cursor_hidden = 0; + XFlush(dpy); + } + } else { + if (!cursor_hidden && fn_hide) { + fn_hide(dpy, root); + cursor_hidden = 1; + XFlush(dpy); + } + } +} + +static void +dwm_handle_softbar_click(int x) +{ + if (!selmon) + return; + softkey_pending = (x < selmon->ww / 2) ? SOFTKEY_LEFT : SOFTKEY_RIGHT; + flush_pending_softkey(); +} + static int is_star_key(KeySym ks, unsigned int keycode) { @@ -2181,6 +2235,8 @@ keypress(XEvent *e) ev = &e->xkey; keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0); + if (cursor_hidden == 0 && (dwm_now_ms() - last_mouse_ms) > 4000) + dwm_cursor_set_visible(0); if (is_screen_off()) { wake_phone(); @@ -2324,6 +2380,8 @@ keyrelease(XEvent *e) ev = &e->xkey; keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0); + if (cursor_hidden == 0 && (dwm_now_ms() - last_mouse_ms) > 4000) + dwm_cursor_set_visible(0); markreleased(keysym); @@ -2485,6 +2543,7 @@ motionnotify(XEvent *e) Monitor *m; XMotionEvent *ev = &e->xmotion; + dwm_cursor_set_visible(1); if (ev->window != root) return; if ((m = recttomon(ev->x_root, ev->y_root, 1, 1)) != mon && mon) { @@ -3108,6 +3167,7 @@ setup(void) load_plugins(); grabkeys(); focus(NULL); + dwm_cursor_set_visible(0); } @@ -3384,7 +3444,7 @@ updatebars(void) XSetWindowAttributes softwa = { .override_redirect = True, .background_pixmap = ParentRelative, - .event_mask = ExposureMask + .event_mask = ExposureMask|ButtonPressMask }; int sh_bar = 26; m->softwin = XCreateWindow(dpy, root, m->wx, m->my + m->mh - sh_bar, m->ww, sh_bar, 0, diff --git a/src/xdrawer/xdrawer.cpp b/src/xdrawer/xdrawer.cpp index c35a47c..3e89db3 100644 --- a/src/xdrawer/xdrawer.cpp +++ b/src/xdrawer/xdrawer.cpp @@ -296,8 +296,13 @@ class PhoneController { std::string outDev = readActiveOutputDevice(); bool outMuted = (readIntFile("/tmp/sxmo_out_muted", 0) == 1); - // 1. Primary output volume (Speaker or Headphones if Headphones are active, linear 0..100%) - if (outDev == "Headphones") { + // 1. Primary output volume (Speaker, Headphones, or Bluetooth, linear 0..100%) + if (outDev == "Bluetooth") { + int btPct = readIntFile(getSxmoCfgDir() + "/bluetooth_vol", 80); + btPct = std::clamp(((btPct + 2) / 5) * 5, 0, 100); + items_.push_back({ControlId::SpeakerVol, kIconHeadphones, kIconSoundOff, + "Bluetooth", true, 0, 100, 5, btPct}); + } else if (outDev == "Headphones") { int hpPct = readIntFile(getSxmoCfgDir() + "/headphones_vol", -1); if (hpPct < 0 || hpPct > 100) { long rx1 = alsa_.getInteger("RX1 Digital Volume", 78); @@ -365,10 +370,12 @@ class PhoneController { items_.push_back({ControlId::Flashlight, kIconFlashlight, kIconFlashlight, "Flashlight", false, 0, 1, 1, (torchCur > 0) ? 1 : 0}); - // 7. Audio Output Route / Mute (0=Muted, 1=Speaker, 2=Earpiece, 3=Headphones) + // 7. Audio Output Route / Mute (0=Muted, 1=Speaker, 2=Earpiece, 3=Headphones, 4=Bluetooth) int outMode = 1; if (outMuted) { outMode = 0; + } else if (outDev == "Bluetooth") { + outMode = 4; } else if (outDev == "Earpiece") { outMode = 2; } else if (outDev == "Headphones") { @@ -376,11 +383,11 @@ class PhoneController { } else { outMode = 1; } - const char* outIcon = (outMode == 3) ? kIconHeadphones + const char* outIcon = (outMode == 3 || outMode == 4) ? kIconHeadphones : (outMode == 2) ? kIconEarpiece : kIconSoundOn; items_.push_back({ControlId::SoundMute, outIcon, kIconSoundOff, - "Output", false, 0, 3, 1, outMode}); + "Output", false, 0, 4, 1, outMode}); // 8. Microphone on/off (toggle) unsigned int dec1 = alsa_.getEnum("DEC1 MUX", 1); @@ -435,8 +442,10 @@ class PhoneController { ControlItem& it = items_[idx]; if (it.isSlider) { it.value = std::clamp(it.value + dir * it.stepVal, it.minVal, it.maxVal); - } else if (it.id == ControlId::RingerMode || it.id == ControlId::SoundMute) { + } else if (it.id == ControlId::RingerMode) { it.value = (it.value + dir + 4) % 4; + } else if (it.id == ControlId::SoundMute) { + it.value = (it.value + dir + 5) % 5; } else if (it.id == ControlId::VibrateStrength) { it.value = ((it.value - 1 + dir + 3) % 3) + 1; } else { @@ -450,9 +459,12 @@ class PhoneController { return; } ControlItem& it = items_[idx]; - if (it.id == ControlId::RingerMode || it.id == ControlId::SoundMute) { + if (it.id == ControlId::RingerMode) { it.value = (it.value + 1) % 4; apply(it); + } else if (it.id == ControlId::SoundMute) { + it.value = (it.value + 1) % 5; + apply(it); } else if (it.id == ControlId::VibrateStrength) { it.value = (it.value % 3) + 1; apply(it); @@ -479,6 +491,10 @@ class PhoneController { if (dev.empty()) { dev = readLine(getSxmoCfgDir() + "/audio_out_device"); } + if (dev.find("Bluetooth") != std::string::npos || dev.find("bluetooth") != std::string::npos || + dev.find("bluez") != std::string::npos) { + return "Bluetooth"; + } if (dev.find("Earpiece") != std::string::npos || dev.find("earpiece") != std::string::npos) { return "Earpiece"; } @@ -589,7 +605,15 @@ class PhoneController { std::string cfg = getSxmoCfgDir(); ::mkdir(cfg.c_str(), 0755); std::string outDev = readActiveOutputDevice(); - if (outDev == "Headphones") { + if (outDev == "Bluetooth") { + writeIntFile(cfg + "/bluetooth_vol", it.value); + writeIntFile("/tmp/sxmo_out_muted", (it.value <= 0) ? 1 : 0); + char cmd[160]; + std::snprintf(cmd, sizeof(cmd), + "sxmo_audio.sh vol set %d Bluetooth >/dev/null 2>&1", + it.value); + runAsyncCmd(cmd); + } else if (outDev == "Headphones") { writeIntFile(cfg + "/headphones_vol", it.value); writeIntFile("/tmp/sxmo_out_muted", (it.value <= 0) ? 1 : 0); long hw = (it.value <= 0) ? 0 : (52 + std::lround((it.value * 32.0) / 100.0)); @@ -670,10 +694,11 @@ class PhoneController { runAsyncCmd("sxmo_audio.sh vol mute >/dev/null 2>&1"); } else { writeIntFile("/tmp/sxmo_out_muted", 0); - const char* targetDev = (it.value == 2) ? "Earpiece" + const char* targetDev = (it.value == 4) ? "Bluetooth" : (it.value == 3) ? "Headphones" + : (it.value == 2) ? "Earpiece" : "Speaker"; - it.iconOn = (it.value == 3) ? kIconHeadphones + it.iconOn = (it.value == 3 || it.value == 4) ? kIconHeadphones : (it.value == 2) ? kIconEarpiece : kIconSoundOn; { @@ -681,7 +706,12 @@ class PhoneController { if (ofs) ofs << targetDev << "\n"; } if (!items_.empty() && items_[0].id == ControlId::SpeakerVol) { - if (it.value == 3) { + if (it.value == 4) { + int btPct = readIntFile(getSxmoCfgDir() + "/bluetooth_vol", 80); + items_[0].label = "Bluetooth"; + items_[0].iconOn = kIconHeadphones; + items_[0].value = std::clamp(((btPct + 2) / 5) * 5, 0, 100); + } else if (it.value == 3) { int hpPct = readIntFile(getSxmoCfgDir() + "/headphones_vol", 80); items_[0].label = "Headphones"; items_[0].iconOn = kIconHeadphones; @@ -954,8 +984,8 @@ static int xdrawer_run_main(int argc, char** argv) { : ((it.value == 1) ? &colYellow : &colMuted); drawPango(layoutSmall, rCol, kWinWidth - stW - 6, ry, rowH, stStr); } else if (it.id == ControlId::SoundMute) { - const char* oModes[4] = {"Muted", "Speaker", "Earpiece", "Headset"}; - std::string stStr = std::string("< ") + oModes[std::clamp(it.value, 0, 3)] + " >"; + const char* oModes[5] = {"Muted", "Speaker", "Earpiece", "Headset", "Bluetooth"}; + std::string stStr = std::string("< ") + oModes[std::clamp(it.value, 0, 4)] + " >"; int stW = pangoWidth(layoutSmall, stStr); XftColor* oCol = (it.value > 0) ? (isSel ? &colYellow : &colGreen) : &colMuted; drawPango(layoutSmall, oCol, kWinWidth - stW - 6, ry, rowH, stStr);