diff --git a/AGENTS.md b/AGENTS.md index e56e2bf..70e6cf8 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -13,6 +13,7 @@ It uses a pure **X11 (`Xlibre` + `sxmo-de-dwm`)** stack (no Wayland) with **Adre - `theme.h`: header forwarding to `../neoui/neoui.h` for unified `.Xresources` / `~/.xthemes/*.xth` parsing, proportional font sizing (`theme.baseFontSize`), automatic shade derivation, and live Xft/Pango theme reloading (`PluginTheme`). - `phone_data.h`: shared X11 geometry (`240x296` below the 24px bar), FIFO IPC (`/tmp/dwm_plugin_.fifo`), softkey chord detection, Sxmo TSV contact/call/SMS parsers, and `libjpeg`/`libpng` helpers. - `net_tls.h`: shared C++20 TCP + OpenSSL TLS + STARTTLS socket class (`NetStream`), HTTP/HTTPS `GET` client (`httpGet`), MD5/CSPRNG helpers, and RFC 2047 / Base64 / Quoted-Printable MIME decoders. + - `monotone.h` + `bananarchy_melody.cpp` (`/usr/bin/bananarchy-melody`): Nokia RTTTL (`.nrt`, `.rtttl`, `.rtx`), Ericsson eMelody (`.emy`), and IrDA iMelody (`.imy`) monophonic ringtone parser and 48 kHz WAV synthesizer. - `locker_plugin.cpp` (`locker.so` / `xlocker`) + `verify_passcode.c` (`/usr/bin/bananarchy-verify-passcode`), `dialer_plugin.cpp` (`dialer.so` / `xdialer`), `calllog_plugin.cpp` (`calllog.so` / `xcalllog`), `callscreen_plugin.cpp` (`callscreen.so` / `xcallscreen`), `contacts_plugin.cpp` (`contacts.so` / `xcontacts`), `sms_plugin.cpp` (`sms.so` / `xsms`), `files_plugin.cpp` (`files.so` / `xfiles`), `camera_plugin.cpp` (`camera.so` / `xcamera`), `themes_plugin.cpp` (`themes.so` / `xthemes`), `modem_plugin.cpp` (`modem.so` / `xmodem`), `networks_plugin.cpp` (`networks.so` / `xnetworks` / `xbluetooth`), `ringtones_plugin.cpp` (`ringtones.so` / `xringtones`), `wallpapers_plugin.cpp` (`wallpapers.so` / `xwallpapers` / `xbackground`), `music_plugin.cpp` (`music.so` / `xmusic` / `xplayer`), `sip_plugin.cpp` (`sip.so` / `xsip`), `email_plugin.cpp` (`email.so` / `xemail` / `xmail`), `irc_plugin.cpp` (`irc.so` / `xirc`), `tox_plugin.cpp` (`tox.so` / `xtox`), `smallweb_plugin.cpp` (`smallweb.so` / `xkopher` / `kopher` / `xsmallweb`), `gps_plugin.cpp` (`gps.so` / `xgps` / `xmaps` / `xnav`). - `dwm_plugin_runner.c`: lightweight `/usr/bin/dwm-plugin` launcher symlinked by `xlocker`, `xdrawer`, `xdialer`, `xcalllog`, `xcallscreen`, `xcontacts`, `xsms`, `xfiles`, `xcamera`, `xthemes`, `xmodem`, `xnetworks`, `xbluetooth`, `xringtones`, `xwallpapers`, `xbackground`, `xmusic`, `xplayer`, `xsip`, `xemail`, `xmail`, `xirc`, `xtox`, `xkopher`, `kopher`, `xsmallweb`, `xgps`, `xmaps`, `xnav`, `dmenu`, and `xdmenu`. - `src/xdrawer/`: global phone controls overlay (`xdrawer.so` / `xdrawer`), toggled by pressing both softkeys simultaneously. @@ -26,7 +27,7 @@ It uses a pure **X11 (`Xlibre` + `sxmo-de-dwm`)** stack (no Wayland) with **Adre ## 3. Build and image generation commands All cross-compilation scripts run inside rootless Docker (`alpine:3.24` `armv7` sysroot) and automatically update both `prebuilt/` and `overlay/rootfs/`: -- `./scripts/build-sxmo-x11.sh` — builds `libneoui.so`, `st`, `dmenu.so`, `dwm`, `dwm-plugin`, `bananarchy-verify-passcode`, `sxmo_vibrate`, and all C++ `.so` plugins (`locker`, `xdrawer`, `dialer`, `calllog`, `callscreen`, `contacts`, `sms`, `files`, `camera`, `themes`, `modem`, `networks`, `ringtones`, `wallpapers`, `music`, `sip`, `email`, `irc`, `tox`, `smallweb`, `gps`). +- `./scripts/build-sxmo-x11.sh` — builds `libneoui.so`, `st`, `dmenu.so`, `dwm`, `dwm-plugin`, `bananarchy-verify-passcode`, `bananarchy-melody`, `sxmo_vibrate`, and all C++ `.so` plugins (`locker`, `xdrawer`, `dialer`, `calllog`, `callscreen`, `contacts`, `sms`, `files`, `camera`, `themes`, `modem`, `networks`, `ringtones`, `wallpapers`, `music`, `sip`, `email`, `irc`, `tox`, `smallweb`, `gps`). - `./scripts/build-dmenu.sh` — rebuilds only `dmenu.so`, `stest`, `dmenu_path`, and `dmenu_run`. - `./scripts/build-games.sh` — builds standalone X11 games and emulators in `src/games/` (`snake`, `tetris`, `gambatte` / `gbemu`, `remedy` / `j2me`). - `./scripts/build-fcitx5-t9.sh` — builds `src/fcitx5-t9` (`libt9.so` / `t9.so`). diff --git a/CHANGELOG.md b/CHANGELOG.md index ef50420..551f917 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -33,6 +33,10 @@ Release versions follow the `
` format (where `2026` is `a`, - Made volume controls strictly linear (`1%`–`100%` mapped directly without cubic `wpctl` distortion) across `sxmo_audio.sh`, `xdrawer`, and `dmenu`. - **Incoming and multipart SMS delivery and reassembly**: - Restored execute permissions (`0755`) on `/usr/share/sxmo/default_hooks/sxmo_hook_smslog.sh`, configured `QMI_WMS_SET_ROUTES` (`0x0032`) on Secondary GW (`SUB 1`) in `msm-modem-uim-selection dsds-daemon` to `STORE_AND_NOTIFY` / `TRANSFER_AND_ACK` so the Qualcomm baseband immediately acknowledges (`RP-ACK`) every incoming segment in hardware, added multi-pass SIM/NV message storage harvesting (`wms-list-messages`), and implemented full 8-bit (`IEI 0x00`) and 16-bit (`IEI 0x08`) concatenated SMS (CSMS) reassembly across both GSM-7 septet and UCS-2 UTF-16BE (including split surrogate pairs) with segment deduplication. +- **Monophonic mobile ringtones (`.nrt`, `.rtttl`, `.rtx`, `.emy`, `.imy`), File Manager (`xfiles`) `RingtoneView`, and distinct Notification / SMS sound configuration (`xringtones`, `sxmo_notifs.sh`, `sxmo_hook_notification.sh`)**: + - Added `src/dwm-plugins/monotone.h` and `/usr/bin/bananarchy-melody` (`--wav`, `--info`, `--play`) for parsing and synthesizing **Nokia RTTTL** (`.nrt`, `.rtttl`, `.rtx`), **Ericsson eMelody** (`.emy`), and **IrDA iMelody** (`.imy`) monophonic ringtones into 48 kHz 16-bit stereo PCM WAV audio, along with 10 preinstalled sample melodies in `/usr/share/sxmo/ringtones/` and `~/Ringtones/`. + - Added a dedicated **Ringtone Viewer (`RingtoneView`)** to **file manager (`xfiles`)** for `.nrt`, `.rtttl`, `.rtx`, `.emy`, and `.imy` files, displaying melody metadata, a graphical piano-roll pitch contour, a scrollable note sequence, live audio preview (`*` / `Center OK`), `Left`/`Right` folder stepping, **Left softkey (`Set Ring`)** to set as the call ringtone, **`#`** to set as the notification/SMS sound, and **Actions** menu items (`Preview Ringtone`, `Set as Ringtone`, `Set as Notif / SMS Sound`, `Open in Ringtones App`, `Play in Music Player`, `View Ringtone Text`, `Edit in Text Editor`), plus `.nrt`/`.rtttl`/`.rtx`/`.emy`/`.imy` playback in `xmusic`. + - Expanded **ringtones manager (`xringtones`)** to 3 tabs (`1:Ringtone`, `2:Notif/SMS`, `3:Settings`, plus `xringtones --notif` and **Notification Sound** in the `Notifs` menu) with a dedicated **Notification / SMS Sound** configuration (`~/.config/sxmo/notif_sound` and `SXMO_TEXTSOUND` in `~/.config/sxmo/ringsettings`, including `None (Mute Sound)`) wired directly into the system notification manager (`sxmo_notifs.sh`, `sxmo_hook_notification.sh`, `sxmo_hook_sms.sh`, `xirc`, and `xtox`) and incoming call ringer (`sxmo_hook_ring.sh`). - **Battery and idle power optimizations**: - Added VM writeback (`dirty_writeback_centisecs=6000`), `printk` throttling, `sched_autogroup_enabled=0`, Wi-Fi powersave (`iw dev wlan0 set power_save on`), and USB/platform runtime PM (`power/control = auto`) in `/etc/local.d/10-power-save.start` and `/etc/sysctl.d/10-power.conf`. - Increased `conky` desktop clock refresh interval to `15.0s` and froze `conky` (`SIGSTOP`/`SIGCONT`) whenever the screen is off or locked, replaced polling in `sxmo_modemmonitor.sh` with event-driven `dbus-monitor`, skipped redundant `sxmo_hook_statusbar.sh` updates while `screenoff`, and drained queued X11 `UnmapNotify` events in `neoui_hide()` so all 22 resident DWM plugins sleep at `0%` CPU when hidden. diff --git a/MANUAL.md b/MANUAL.md index c3bea0f..3fd2da5 100644 --- a/MANUAL.md +++ b/MANUAL.md @@ -179,7 +179,7 @@ All twenty-two phone applications are compiled as shared-object plugins (`/usr/l - **J2ME (`.jar` / `.jad`) MIDlet launching**: pressing `Return` on any `.jar` or `.jad` file (or selecting **Run in ReMEdy (J2ME)** from the **Left softkey (`Actions`)** menu) opens it directly in the **ReMEdy (`remedy`)** full-screen `240x320` J2ME emulator; `.jad` files also include a **View JAD Descriptor** action in the **Actions** menu. - **Game Boy / Game Boy Color ROM launching**: pressing `Return` on any `.gb` or `.gbc` file (or selecting **Play in Game Boy Emulator** from the **Left softkey (`Actions`)** menu) opens it directly in the **Gambatte (`gambatte`)** emulator. - **Image preview and wallpaper installation**: pressing `Return` on any image file (`.jpg`, `.png`, `.bmp`, `.gif`, `.webp`, `.ppm`, `.tif`, `.ico`, `.svg`) opens the built-in image viewer (`*` toggles full-screen preview; **Left softkey (`Set Wall`)** installs the image into `~/Pictures/Wallpapers/`, applies it via `feh`, and refreshes Conky). You can also select **Preview Image** or **Set as Wallpaper** directly from the **Left softkey (`Actions`)** menu. - - **Audio playback and ringtone installation**: pressing `Return` on any audio or tracker module file opens it immediately in **Music (`xmusic`)**. From the **Left softkey (`Actions`)** menu on any audio/tracker file, select **Play in Music Player** to play it in `xmusic`, or **Set as Ringtone** to copy it to `~/Ringtones/` and set it as the active phone ringtone. + - **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`. 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. - **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**. @@ -206,9 +206,13 @@ All twenty-two phone applications are compiled as shared-object plugins (`/usr/l - **`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, scan nearby devices (`*`), and pair, connect, disconnect, or remove devices. -13. **Ringtones and ringer manager (`ringtones.so` / `xringtones`)**: - - **Open**: select **Ringtones** from the System, Config, or Audio menu, or run `xringtones`. - - **Controls**: preview built-in, tracker module (`.mod`, `.xm`, `.it`, `.s3m`, etc.), and user ringtones (`~/Ringtones/`, `~/Music/`, `/usr/share/sxmo/ringtones/`, `/usr/share/sxmo/music/`) at the configured ringtone volume with `*` or **Left softkey (`Play` / `Stop`)**, press `Return` to set the active ringtone, and switch to **`2:Settings`** to configure **Ringer Mode**, **Ring Volume** (`0%`–`100%`, also adjustable in **XDrawer**), **Ring Duration**, **Ring Loop Count**, and 3-level hardware **Vibrate Strength** (`Level 1 (Light)` pulsed `1600 mV`, `Level 2 (Medium)` pulsed `2100 mV`, `Level 3 (Strong)` continuous `3100 mV`, also adjustable in **XDrawer**). +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]`. + - **Supported formats**: standard audio (`.wav`, `.ogg`, `.mp3`, `.flac`, `.opus`, `.m4a`, `.aac`), chiptune tracker modules (`.mod`, `.xm`, `.it`, `.s3m`, etc.), and classic monophonic mobile ringtones — **Nokia RTTTL** (`.nrt`, `.rtttl`, `.rtx`), **Ericsson eMelody** (`.emy`), and **IrDA iMelody** (`.imy`) — synthesized via `monotone.h` / `/usr/bin/bananarchy-melody` (`~/Ringtones/`, `~/Music/`, `/usr/share/sxmo/ringtones/`, `/usr/share/sxmo/music/`). + - **Three tabs (`1:Ringtone`, `2:Notif/SMS`, `3:Settings` — switch with `1`–`3` or `Left`/`Right` in Tabs 1 and 2)**: + - **`1:Ringtone`**: browse and preview call ringtones (`*` or **Left softkey (`Play [*]` / `Stop`)**), press `Return` to set the active **Call Ringtone** (`~/.config/sxmo/ringtone`), or press `#` to quick-assign the highlighted tone as the **Notification / SMS Sound**. + - **`2:Notif/SMS`**: browse and single-shot preview notification/SMS alert tones (including `None (Mute Sound)` for vibration-only notifications) and press `Return` to set the active **Notification / SMS Sound** (`~/.config/sxmo/notif_sound` and `SXMO_TEXTSOUND` in `~/.config/sxmo/ringsettings`), wired directly into the system notification manager (`sxmo_notifs.sh`, `sxmo_hook_notification.sh`, `sxmo_hook_sms.sh`, `xirc`, and `xtox`). + - **`3:Settings`**: configure **Ringer Mode** (`Ring + Vibrate`, `Ring Only`, `Vibrate Only`, `Silent`), **Notif / SMS Sound** (`Left`/`Right` cycles tones, `*` previews, `Return` opens Tab 2), **Call Ringtone** (`Left`/`Right` cycles tones, `*` previews, `Return` opens Tab 1), **Ring & Alert Volume** (`0%`–`100%`, also adjustable in **XDrawer**), **Call Ring Duration**, **Call Ring Loop Count**, and 3-level hardware **Vibrate Strength** (`Level 1 (Light)` pulsed `1600 mV`, `Level 2 (Medium)` pulsed `2100 mV`, `Level 3 (Strong)` continuous `3100 mV`, `Return` tests vibration). 14. **Desktop wallpaper manager (`wallpapers.so` / `xwallpapers` / `xbackground`)**: - **Open**: select **Wallpapers** from the System, Config, or Apps menu, or run `xwallpapers`. @@ -432,10 +436,16 @@ The `msm8905-cam` kernel module drives the rear 2MP GalaxyCore `GC2395` (TA-1048 Both the rear loudspeaker (`Speaker`, with boosted `RX3 Digital Volume` for loud, clear ringtones and media), the front earpiece speaker (`Earpiece`, boosted by +6 dB and selectable as a standard output device for any audio stream), and wired 3.5mm headphones (`Headphones`, automatically detected and routed on plug-in and restored to `Speaker` on unplug by `sxmo_soundmonitor.sh`), as well as the internal MEMS microphone (`Mic1`) and 3.5mm headset microphone (`Mic2`), are managed through PipeWire/WirePlumber and `sxmo_audio.sh` with linear `1%`–`100%` volume controls across all channels: -- **Open an audio file, tracker module (`.mod`, `.xm`, `.it`, `.s3m`), or folder in the native music player (`xmusic`)**: +- **Open an audio file, tracker module (`.mod`, `.xm`, `.it`, `.s3m`), monophonic ringtone (`.nrt`, `.rtttl`, `.rtx`, `.emy`, `.imy`), or folder in the native music player (`xmusic`)**: ```bash xmusic ~/Music/Bananarchy_Chip.mod ``` +- **Inspect, synthesize to WAV, or play a Nokia RTTTL (`.nrt`, `.rtttl`, `.rtx`), Ericsson eMelody (`.emy`), or IrDA iMelody (`.imy`) ringtone from the CLI (`bananarchy-melody`)**: + ```bash + bananarchy-melody --info /usr/share/sxmo/ringtones/Nokia_Gran_Vals.nrt + bananarchy-melody --wav /usr/share/sxmo/ringtones/Ericsson_Cascade.emy /tmp/out.wav + bananarchy-melody --play /usr/share/sxmo/ringtones/IrDA_Pager.imy + ``` - **List available audio outputs (`Speaker`, `Earpiece`, `Headphones`)**: ```bash sxmo_audio.sh out list diff --git a/README.md b/README.md index f9afb02..51345e7 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ Instead of spawning slow shell scripts for everyday phone tasks, Bananarchy runs - **Contacts (`xcontacts`) and SMS manager (`xsms`)**: full phonebook editor with direct Qualcomm QMI SIM card contact import and export across SIM 1 and SIM 2, paired with a threaded SMS conversation view, multi-tap message composer with outgoing `SIM 1` / `SIM 2` selection when two SIMs are active, and built-in anti-spam blocklist / spam folder (`~/.local/share/sxmo/block`) with one-key thread blocking and restoration. - **Modem and Dual-SIM manager (`xmodem`)**: 4-tab cellular control center (`SIMs`, `Radio`, `AT`, `Log`) supporting Dual-SIM Dual Standby (DSDS) with simultaneous network registration on both SIM slots, instant default SIM switching (`Set as Default SIM (Calls/SMS)`), full Primary/Secondary GW (`4G/Data`) slot swapping (`Make Primary GW (4G/Data Swap)`), SIM PIN unlock and PUK unblock wizards, 2G/3G/4G radio mode selection, interactive USSD sessions, and a live AT command console. - **Networks and Bluetooth manager (`xnetworks`)**: 3-tab connectivity manager for Wi-Fi networks, WPA2 password entry, Wi-Fi hotspot, USB tethering, 4G/LTE mobile data (`wwan0`) and APN editing, and Bluetooth pairing. -- **File manager (`xfiles`) with microSD automount (`sxmo_sdcard.sh`), music and tracker player (`xmusic`), and camera (`xcamera`)**: keypad directory browser with automatic microSD card (`/dev/mmcblk1`) detection and `/media/sdcard` mounting/unmounting, built-in text viewer, integrated GUI multi-tap text editor (`Edit in Text Editor`, available as an action on any file), and image viewer (plus one-click actions to launch `.jar`/`.jad` MIDlets in the **ReMEdy (`remedy`)** J2ME emulator, launch `.gb`/`.gbc` ROMs in the Game Boy emulator, run `.yab` scripts in Yabasic inside the terminal, play audio, preview images, set any image as wallpaper, or install any audio or tracker file as ringtone), a 3-tab music and chiptune tracker module player (`WAV`, `MP3`, `OGG`, `FLAC`, `Opus`, `MOD`, `XM`, `IT`, `S3M`, and more), and a live V4L2 camera viewfinder with digital zoom, flash/torch control, self-timer, and photo gallery. +- **File manager (`xfiles`) with microSD automount (`sxmo_sdcard.sh`), music and tracker player (`xmusic`), and camera (`xcamera`)**: keypad directory browser with automatic microSD card (`/dev/mmcblk1`) detection and `/media/sdcard` mounting/unmounting, built-in text viewer, integrated GUI multi-tap text editor (`Edit in Text Editor`, available as an action on any file), image viewer, and dedicated monophonic ringtone viewer (`RingtoneView` for Nokia RTTTL `.nrt`/`.rtttl`/`.rtx`, Ericsson eMelody `.emy`, and IrDA iMelody `.imy` with graphical piano-roll pitch contour, note sequence viewer, live audio preview, and one-key assignment as call ringtone or notification/SMS sound — plus one-click actions to launch `.jar`/`.jad` MIDlets in the **ReMEdy (`remedy`)** J2ME emulator, launch `.gb`/`.gbc` ROMs in the Game Boy emulator, run `.yab` scripts in Yabasic inside the terminal, play audio, preview images, set any image as wallpaper, or install any audio, tracker, or monophonic melody file as call ringtone or notification/SMS sound), a 3-tab music and chiptune tracker module player (`WAV`, `MP3`, `OGG`, `FLAC`, `Opus`, `MOD`, `XM`, `IT`, `S3M`, `NRT`, `RTTTL`, `RTX`, `EMY`, `IMY`, and more), and a live V4L2 camera viewfinder with digital zoom, flash/torch control, self-timer, and photo gallery. - **Native NeoUI communication and internet suite (`xsip`, `xemail`, `xirc`, `xtox`, `xkopher`)**: - **SIP VoIP client (`xsip` / `sip.so`)**: RFC 3261 SIP softphone (`Dialer`, `Accounts`, `History`) with Digest MD5 authentication, standby `REGISTER` keepalive, incoming `INVITE` ringing and call handling integrated with `xcallscreen`, bidirectional G.711 (`PCMU`/`PCMA` 8 kHz) RTP audio, and RFC 2833 DTMF. - **Email client (`xemail` / `xmail` / `email.so`)**: multi-account `IMAP4rev1`, `POP3`, and `SMTP` client (`Inbox`, `Compose`, `Accounts`) supporting implicit TLS, `STARTTLS`, and plain TCP, SASL `PLAIN`/`LOGIN`, MIME RFC 2047/Base64/Quoted-Printable decoding, offline inbox cache, full-screen message reader, and composer. @@ -37,7 +37,7 @@ Instead of spawning slow shell scripts for everyday phone tasks, Bananarchy runs - **Tox / Trifa P2P messenger and audio call client (`xtox` / `tox.so`)**: encrypted P2P messenger (`Friends`, `Chat`, `My Tox ID`) built on `c-toxcore` (`libtoxcore.so.2`) with DHT + TCP relay bootstrap, friend requests, persistent message history, and `ToxAV` 48 kHz Opus voice calls integrated with `xcallscreen`. - **Kopher SmallWeb browser (`xkopher` / `kopher` / `xsmallweb` / `smallweb.so`)**: multi-protocol SmallWeb client for **Gopher** (`gopher://`) with optional TLS (`gophers://`), **Gemini** (`gemini://`), **Spartan** (`spartan://`), and **Nex** (`nex://`), featuring WAP-style default keypad controls from [Kopher](https://code.luxferre.top/luxferre/kopher.git), user-adjustable keybindings (`~/.config/sxmo/smallweb_controls.tsv`), 10 bookmarks, and custom homepage support. - **GPS reception test utility (`bananarchy-gps`) and OpenStreetMap navigator (`xgps` / `xmaps` / `xnav` / `gps.so`)**: CLI GNSS/GPS diagnostic tool (`bananarchy-gps status|enable|disable|nmea|watch`) and 3-tab NeoUI GPS navigator (`1:GPS Status`, `2:OSM Map`, `3:Nav/Search`) with live NMEA/QMI PDS satellite and 3GPP cell telemetry, interactive `240x212` OpenStreetMap slippy-map tile viewer with offline PNG tile cache (`~/.cache/sxmo/osm_tiles/`), Nominatim place search, saved waypoints, and OSRM turn-by-turn route geometry and step navigation. -- **Themes (`xthemes`), wallpapers (`xwallpapers`), and ringtones (`xringtones`)**: installable `.Xresources` color and font themes (`~/.xthemes/*.xth`, 20 preinstalled schemes) with live zero-restart reload across the entire UI and terminal, alongside dedicated managers for desktop wallpapers and call ringtones (supporting both standard audio and tracker modules) with 3-level vibration control. +- **Themes (`xthemes`), wallpapers (`xwallpapers`), and ringtones (`xringtones`)**: installable `.Xresources` color and font themes (`~/.xthemes/*.xth`, 20 preinstalled schemes) with live zero-restart reload across the entire UI and terminal, alongside dedicated managers for desktop wallpapers and 3-tab call ringtones & notification/SMS alerts (`1:Ringtone`, `2:Notif/SMS`, `3:Settings`, supporting standard audio, tracker modules, and Nokia RTTTL `.nrt`/`.rtttl`/`.rtx`, Ericsson eMelody `.emy`, and IrDA iMelody `.imy` monophonic ringtones via `/usr/bin/bananarchy-melody`, wired into `sxmo_notifs.sh` and `sxmo_hook_notification.sh`) with 3-level vibration control. ### Input, terminal, and developer tools - **6-mode `fcitx5-t9` keypad input**: press `#` to cycle between `abc`, `Abc`, `ABC`, `Sym` (all 32 ASCII punctuation symbols), `Ctl` (`Ctrl` sequences, arrows, `PageUp`/`PageDown`, `F1`–`F12`), and `123` numeric modes with a fixed bottom candidate bar. diff --git a/overlay/rootfs/home/user/.config/sxmo/notif_sound b/overlay/rootfs/home/user/.config/sxmo/notif_sound new file mode 100644 index 0000000..4ba2ffc --- /dev/null +++ b/overlay/rootfs/home/user/.config/sxmo/notif_sound @@ -0,0 +1 @@ +/usr/share/sxmo/ringtones/Soft_Bell.wav diff --git a/overlay/rootfs/home/user/.config/sxmo/ringsettings b/overlay/rootfs/home/user/.config/sxmo/ringsettings index ce70c36..365e294 100644 --- a/overlay/rootfs/home/user/.config/sxmo/ringsettings +++ b/overlay/rootfs/home/user/.config/sxmo/ringsettings @@ -2,3 +2,4 @@ SXMO_RINGTIME=20 SXMO_RINGNUMBER=10 SXMO_VIBRATE_STRENGTH=2 SXMO_RINGVOL=100 +SXMO_TEXTSOUND="/usr/share/sxmo/ringtones/Soft_Bell.wav" diff --git a/overlay/rootfs/home/user/Ringtones/Banana_Bounce.rtttl b/overlay/rootfs/home/user/Ringtones/Banana_Bounce.rtttl new file mode 100644 index 0000000..4f14551 --- /dev/null +++ b/overlay/rootfs/home/user/Ringtones/Banana_Bounce.rtttl @@ -0,0 +1 @@ +BananaBounce:d=8,o=5,b=175:g,a,b,d6,16g6,16d6,b,4g,a,b,c6,e6,16a6,16e6,c6,4a,b,d6,g6,f#6,e6,d6,c6,b,a,d6,4f#6,4g6 diff --git a/overlay/rootfs/home/user/Ringtones/Neon_Arpeggio.rtx b/overlay/rootfs/home/user/Ringtones/Neon_Arpeggio.rtx new file mode 100644 index 0000000..cdfbc95 --- /dev/null +++ b/overlay/rootfs/home/user/Ringtones/Neon_Arpeggio.rtx @@ -0,0 +1 @@ +NeonArp:d=16,o=5,b=140,s=c,l=2:a,c6,e6,a6,e6,c6,a,e,g,b,d6,g6,d6,b,g,d,f,a,c6,f6,c6,a,f,c,e,g#,b,e6,4a6 diff --git a/overlay/rootfs/home/user/Ringtones/Nokia_Espionage.nrt b/overlay/rootfs/home/user/Ringtones/Nokia_Espionage.nrt new file mode 100644 index 0000000..cdd1c0e --- /dev/null +++ b/overlay/rootfs/home/user/Ringtones/Nokia_Espionage.nrt @@ -0,0 +1 @@ +Espionage:d=8,o=5,b=150:e,e,16p,e,16p,c,e,4g,4p,4g4,4p,c6,16p,g,16p,e,16p,a,b,16a#,a,g,e6,g6,4a6,f6,g6,16p,e6,c6,d6,4b diff --git a/overlay/rootfs/home/user/Ringtones/Nordic_Bells.emy b/overlay/rootfs/home/user/Ringtones/Nordic_Bells.emy new file mode 100644 index 0000000..4367cbf --- /dev/null +++ b/overlay/rootfs/home/user/Ringtones/Nordic_Bells.emy @@ -0,0 +1,7 @@ +BEGIN:EMELODY +VERSION:1.0 +NAME:Nordic Bells +COMPOSER:Bananarchy +BEAT:135 +MELODY:a+c+e+Ape+c+aEp(d+f+a+Dpc+e+g+Cp@2)a+e+A +END:EMELODY diff --git a/overlay/rootfs/home/user/Ringtones/Pocket_Chime.imy b/overlay/rootfs/home/user/Ringtones/Pocket_Chime.imy new file mode 100644 index 0000000..2c2a9a9 --- /dev/null +++ b/overlay/rootfs/home/user/Ringtones/Pocket_Chime.imy @@ -0,0 +1,10 @@ +BEGIN:IMELODY +VERSION:1.2 +FORMAT:CLASS1.0 +NAME:Pocket Chime +COMPOSER:Bananarchy +BEAT:150 +STYLE:S0 +VOLUME:V14 +MELODY:(*5c4*5e4*5g4*6c3r4*5b4*5g4*5d4*5g3r4@2)*5c4*5g4*6c4*6e4*6g2 +END:IMELODY diff --git a/overlay/rootfs/usr/bin/bananarchy-melody b/overlay/rootfs/usr/bin/bananarchy-melody new file mode 100755 index 0000000..1222f4b Binary files /dev/null and b/overlay/rootfs/usr/bin/bananarchy-melody differ diff --git a/overlay/rootfs/usr/bin/sxmo_notifs.sh b/overlay/rootfs/usr/bin/sxmo_notifs.sh index b9cc85b..52586e7 100755 --- a/overlay/rootfs/usr/bin/sxmo_notifs.sh +++ b/overlay/rootfs/usr/bin/sxmo_notifs.sh @@ -29,6 +29,7 @@ clear_all() { _handle_new_notif_file() { file="$1" + mode="$2" [ -f "$file" ] || return 0 if [ "$(wc -l < "$file" 2>/dev/null || echo 0)" -lt 3 ]; then @@ -37,7 +38,9 @@ _handle_new_notif_file() { return 0 fi - sxmo_hook_notification.sh "$file" & + if [ "$mode" != "boot" ]; then + sxmo_hook_notification.sh "$file" & + fi group="$(awk NR==1 "$file" 2>/dev/null)" action="$(awk NR==2 "$file" 2>/dev/null)" @@ -70,7 +73,7 @@ monitor() { mkdir -p "$SXMO_NOTIFDIR" find "$SXMO_NOTIFDIR" -type f 2>/dev/null | while read -r file; do - _handle_new_notif_file "$file" + _handle_new_notif_file "$file" "boot" done _notifications_hook @@ -112,6 +115,7 @@ menu() { choices="$(cat </dev/null 2>&1 + exit + ;; *) file="$( printf "%b" "$choices" | @@ -187,6 +195,10 @@ new() { mkdir -p "$SXMO_NOTIFDIR" printf "%s\n%s\n%b\n" "$group" "$action" "$msg" > "$SXMO_NOTIFDIR/$id" + if ! pgrep -f "sxmo_notifs.sh monitor" >/dev/null 2>&1; then + sxmo_hook_notification.sh "$SXMO_NOTIFDIR/$id" & + fi + sxmo_hook_statusbar.sh notifications } diff --git a/overlay/rootfs/usr/lib/dwm/plugins/dmenu.so b/overlay/rootfs/usr/lib/dwm/plugins/dmenu.so index cd53793..0c443b2 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 671171d..c7310f4 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/irc.so b/overlay/rootfs/usr/lib/dwm/plugins/irc.so index d1fa5cc..ac04941 100755 Binary files a/overlay/rootfs/usr/lib/dwm/plugins/irc.so and b/overlay/rootfs/usr/lib/dwm/plugins/irc.so differ diff --git a/overlay/rootfs/usr/lib/dwm/plugins/music.so b/overlay/rootfs/usr/lib/dwm/plugins/music.so index 4ac60b3..f93d444 100755 Binary files a/overlay/rootfs/usr/lib/dwm/plugins/music.so and b/overlay/rootfs/usr/lib/dwm/plugins/music.so differ diff --git a/overlay/rootfs/usr/lib/dwm/plugins/ringtones.so b/overlay/rootfs/usr/lib/dwm/plugins/ringtones.so index 23871bc..3d8c004 100755 Binary files a/overlay/rootfs/usr/lib/dwm/plugins/ringtones.so and b/overlay/rootfs/usr/lib/dwm/plugins/ringtones.so differ diff --git a/overlay/rootfs/usr/lib/dwm/plugins/tox.so b/overlay/rootfs/usr/lib/dwm/plugins/tox.so index 9078a4e..4b6b049 100755 Binary files a/overlay/rootfs/usr/lib/dwm/plugins/tox.so and b/overlay/rootfs/usr/lib/dwm/plugins/tox.so differ diff --git a/overlay/rootfs/usr/lib/dwm/plugins/xdrawer.so b/overlay/rootfs/usr/lib/dwm/plugins/xdrawer.so index bd9023b..63b835c 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/share/sxmo/default_hooks/sxmo_hook_notification.sh b/overlay/rootfs/usr/share/sxmo/default_hooks/sxmo_hook_notification.sh index cec3da3..d917b2c 100755 --- a/overlay/rootfs/usr/share/sxmo/default_hooks/sxmo_hook_notification.sh +++ b/overlay/rootfs/usr/share/sxmo/default_hooks/sxmo_hook_notification.sh @@ -3,19 +3,98 @@ # SPDX-License-Identifier: AGPL-3.0-only # Copyright 2022 Sxmo Contributors -# Runs when a notification arrives, +# Runs when a notification arrives in sxmo_notifs.sh (or via sxmo_hook_sms.sh). # Arguments: -# $1 - The notification file which contains the notification text. +# $1 - Optional notification file path or event context. # shellcheck source=scripts/core/sxmo_common.sh . sxmo_common.sh -#if [ ! -f "$XDG_CONFIG_HOME"/sxmo/.novibrate ]; then -# VIBS=5 -# VIBI=0 -# while [ "$VIBI" -lt "$VIBS" ]; do -# sxmo_vibrate 400 "${SXMO_VIBRATE_STRENGTH:-1}" & -# sleep 0.5 -# VIBI="$(echo "$VIBI+1" | bc)" -# done -#fi +XDG_CONFIG_HOME="${XDG_CONFIG_HOME:-$HOME/.config}" +RUNTIME_DIR="${XDG_RUNTIME_DIR:-/tmp}" + +# Do nothing during an active call or incoming call ring +if [ -f "$RUNTIME_DIR/sxmo_ringing.pid" ]; then + exit 0 +fi +if sxmo_modemcall.sh list_active_calls 2>/dev/null | grep -q active; then + exit 0 +fi + +# Do nothing in DND / busy mode +if [ -f "$RUNTIME_DIR/sxmo.busy" ]; then + exit 0 +fi +if [ -f "$XDG_CONFIG_HOME/sxmo/.busy" ]; then + end="$(cat "$XDG_CONFIG_HOME/sxmo/.busy" 2>/dev/null)" + if [ -z "$end" ] || [ "$(date +%s)" -lt "$end" ]; then + exit 0 + fi +fi + +# Deduplicate simultaneous notification + SMS hook invocations within 1 second +STAMP_FILE="$RUNTIME_DIR/sxmo_notif_alert.stamp" +LOCK_FILE="$RUNTIME_DIR/sxmo_notif_alert.lock" +exec 8>"$LOCK_FILE" +if command -v flock >/dev/null 2>&1; then + flock -n 8 || exit 0 +fi +now_ts="$(date +%s)" +if [ -f "$STAMP_FILE" ]; then + last_ts="$(cat "$STAMP_FILE" 2>/dev/null || echo 0)" + case "$last_ts" in + ''|*[!0-9]*) last_ts=0 ;; + esac + if [ $((now_ts - last_ts)) -lt 2 ]; then + exit 0 + fi +fi +printf '%s\n' "$now_ts" > "$STAMP_FILE" +exec 8>&- + +if [ -f "$XDG_CONFIG_HOME/sxmo/ringsettings" ]; then + # shellcheck disable=SC1091 + . "$XDG_CONFIG_HOME/sxmo/ringsettings" +fi + +NOTIF_SOUND="" +if [ -s "$XDG_CONFIG_HOME/sxmo/notif_sound" ]; then + IFS= read -r NOTIF_SOUND < "$XDG_CONFIG_HOME/sxmo/notif_sound" || true +fi +if [ -z "$NOTIF_SOUND" ]; then + NOTIF_SOUND="${SXMO_TEXTSOUND:-}" +fi +if [ -z "$NOTIF_SOUND" ]; then + if [ -f "/usr/share/sxmo/ringtones/Soft_Bell.wav" ]; then + NOTIF_SOUND="/usr/share/sxmo/ringtones/Soft_Bell.wav" + else + NOTIF_SOUND="/usr/share/sxmo/notify.ogg" + fi +fi + +if [ ! -f "$XDG_CONFIG_HOME/sxmo/.noring" ] && [ "$NOTIF_SOUND" != "NONE" ] && [ "$NOTIF_SOUND" != "none" ]; then + case "${SXMO_RINGVOL:-100}" in + ''|*[!0-9]*) SXMO_RINGVOL=100 ;; + esac + if [ "$SXMO_RINGVOL" -gt 0 ] && [ -n "$NOTIF_SOUND" ] && [ -f "$NOTIF_SOUND" ]; then + mpv_vol=$(( SXMO_RINGVOL * 130 / 100 )) + notif_ext="$(printf '%s' "${NOTIF_SOUND##*.}" | tr '[:upper:]' '[:lower:]')" + notif_play="$NOTIF_SOUND" + case "$notif_ext" in + nrt|rtttl|rtx|emy|imy) + notif_play="$RUNTIME_DIR/sxmo_monotone_notif.wav" + bananarchy-melody --wav "$NOTIF_SOUND" "$notif_play" >/dev/null 2>&1 || notif_play="" + ;; + esac + if [ -n "$notif_play" ] && [ -f "$notif_play" ]; then + mpv --no-config --no-terminal --no-resume-playback --quiet --no-video \ + --end=6 --volume-max=150 --volume="$mpv_vol" "$notif_play" >/dev/null 2>&1 & + fi + fi +fi + +if [ ! -f "$XDG_CONFIG_HOME/sxmo/.novibrate" ]; then + sxmo_vibrate 500 "${SXMO_VIBRATE_STRENGTH:-2}" & +fi + +wait diff --git a/overlay/rootfs/usr/share/sxmo/default_hooks/sxmo_hook_ring.sh b/overlay/rootfs/usr/share/sxmo/default_hooks/sxmo_hook_ring.sh index 9f5a799..a6259ca 100755 --- a/overlay/rootfs/usr/share/sxmo/default_hooks/sxmo_hook_ring.sh +++ b/overlay/rootfs/usr/share/sxmo/default_hooks/sxmo_hook_ring.sh @@ -150,6 +150,9 @@ finish() { pkill -TERM -f "pw-play.*$SXMO_RINGTONE" 2>/dev/null || true pkill -TERM -f "mpv.*$SXMO_RINGTONE" 2>/dev/null || true fi + pkill -TERM -f "pw-play.*sxmo_monotone_ring.wav" 2>/dev/null || true + pkill -TERM -f "mpv.*sxmo_monotone_ring.wav" 2>/dev/null || true + pkill -TERM -x bananarchy-melody 2>/dev/null || true pkill -TERM -x sxmo_vibrate 2>/dev/null || true if ! is_call_picked_up; then sxmo_audio.sh device apply >/dev/null 2>&1 || true @@ -202,8 +205,17 @@ EOF vhelper="$!" ext="$(printf '%s' "${SXMO_RINGTONE##*.}" | tr '[:upper:]' '[:lower:]')" + play_file="$SXMO_RINGTONE" use_pw=0 case "$ext" in + nrt|rtttl|rtx|emy|imy) + play_file="$XDG_RUNTIME_DIR/sxmo_monotone_ring.wav" + if bananarchy-melody --wav "$SXMO_RINGTONE" "$play_file" >/dev/null 2>&1; then + command -v pw-play >/dev/null 2>&1 && use_pw=1 + else + exit 0 + fi + ;; wav|ogg|oga|mp3|flac|aiff|aif) command -v pw-play >/dev/null 2>&1 && use_pw=1 ;; @@ -216,7 +228,7 @@ EOF should_stop_ringing && break amixer -c 0 cset "name='RX3 Digital Volume'" "$ring_rx3" >/dev/null 2>&1 || true wpctl set-volume @DEFAULT_AUDIO_SINK@ 100% >/dev/null 2>&1 || true - pw-play --volume=1.0 "$SXMO_RINGTONE" >/dev/null 2>&1 & + pw-play --volume=1.0 "$play_file" >/dev/null 2>&1 & rchild="$!" wait "$rchild" 2>/dev/null rc="$?" @@ -238,7 +250,7 @@ EOF mpv --no-config --no-terminal --no-resume-playback --quiet --vo=null --no-video \ --ao=pipewire,pulse,alsa --audio-channels=stereo --audio-samplerate=48000 \ --volume-max=100 --volume=100 \ - --loop="$loops" "$SXMO_RINGTONE" /dev/null 2>&1 & + --loop="$loops" "$play_file" /dev/null 2>&1 & rchild="$!" wait "$rchild" 2>/dev/null || true rchild="" diff --git a/overlay/rootfs/usr/share/sxmo/default_hooks/sxmo_hook_sms.sh b/overlay/rootfs/usr/share/sxmo/default_hooks/sxmo_hook_sms.sh index 99baa0d..633d129 100755 --- a/overlay/rootfs/usr/share/sxmo/default_hooks/sxmo_hook_sms.sh +++ b/overlay/rootfs/usr/share/sxmo/default_hooks/sxmo_hook_sms.sh @@ -3,50 +3,12 @@ # SPDX-License-Identifier: AGPL-3.0-only # Copyright 2022 Sxmo Contributors -# This script is executed after you received a text, mms, or vvm -# You can use it to play a notification sound or forward the sms elsewhere - -# The following parameters are provided: -# $1 = Contact Name or Number (if number not in contacts) -# $2 = Text (or 'VVM' if a vvm) -# mms and vvm will include these parameters: -# $3 = MMS or VVM payload ID -# Finally, mms may include this parameter: -# $4 = Group Contact Name or Number (if number not in contacts) +# This script is executed after receiving a text, mms, or vvm. +# It delegates to sxmo_hook_notification.sh so SMS and system notifications +# share the configured Notification / SMS sound (~/.config/sxmo/notif_sound) +# and vibration settings without playing duplicate alerts. # shellcheck source=scripts/core/sxmo_common.sh . sxmo_common.sh -# do nothing if active call -if sxmo_modemcall.sh list_active_calls | grep -q active; then - exit -fi - -# do nothing if silent mode -if [ -f "$XDG_CONFIG_HOME"/sxmo/.busy ]; then - end="$(cat "$XDG_CONFIG_HOME"/sxmo/.busy)" - if [ -z "$end" ] || [ "$(date +%s)" -lt "$end" ]; then - exit - fi -fi - -if [ -f "$XDG_CONFIG_HOME/sxmo/ringsettings" ]; then - # shellcheck disable=SC1091 - . "$XDG_CONFIG_HOME/sxmo/ringsettings" -fi - -if [ ! -f "$XDG_CONFIG_HOME"/sxmo/.noring ]; then - case "${SXMO_RINGVOL:-100}" in - ''|*[!0-9]*) SXMO_RINGVOL=100 ;; - esac - if [ "$SXMO_RINGVOL" -gt 0 ]; then - mpv_vol=$(( SXMO_RINGVOL * 130 / 100 )) - mpv --no-resume-playback --quiet --no-video --volume-max=150 --volume="$mpv_vol" "$SXMO_TEXTSOUND" >> /dev/null 2>&1 & - fi -fi - -if [ ! -f "$XDG_CONFIG_HOME"/sxmo/.novibrate ]; then - sxmo_vibrate 500 "${SXMO_VIBRATE_STRENGTH:-2}" & -fi - -wait +exec sxmo_hook_notification.sh --sms "$@" diff --git a/overlay/rootfs/usr/share/sxmo/ringtones/Bananarchy_Anthem.rtttl b/overlay/rootfs/usr/share/sxmo/ringtones/Bananarchy_Anthem.rtttl new file mode 100644 index 0000000..9b30914 --- /dev/null +++ b/overlay/rootfs/usr/share/sxmo/ringtones/Bananarchy_Anthem.rtttl @@ -0,0 +1 @@ +Bananarchy:d=8,o=5,b=160:c,e,g,c6,16e6,16c6,g,4e,d,f,a,d6,16f6,16d6,b,4g,c6,b,a,g,f,e,d,c,16e,16g,16c6,16e6,4g6,8p,4c6 diff --git a/overlay/rootfs/usr/share/sxmo/ringtones/Cyber_Matrix.rtx b/overlay/rootfs/usr/share/sxmo/ringtones/Cyber_Matrix.rtx new file mode 100644 index 0000000..f82ea2f --- /dev/null +++ b/overlay/rootfs/usr/share/sxmo/ringtones/Cyber_Matrix.rtx @@ -0,0 +1 @@ +CyberMatrix:d=16,o=5,b=150,s=n,l=2:e,g,b,e6,d6,b,g,e,c,e,g,c6,b,g,e,c,d,f#,a,d6,c6,a,f#,d,8e,8p,e,b,8e6,b=170,e6,g6,b6,4e7 diff --git a/overlay/rootfs/usr/share/sxmo/ringtones/Ericsson_Cascade.emy b/overlay/rootfs/usr/share/sxmo/ringtones/Ericsson_Cascade.emy new file mode 100644 index 0000000..e687e2b --- /dev/null +++ b/overlay/rootfs/usr/share/sxmo/ringtones/Ericsson_Cascade.emy @@ -0,0 +1,7 @@ +BEGIN:EMELODY +VERSION:1.0 +NAME:Ericsson Cascade +COMPOSER:Bananarchy +BEAT:140 +MELODY:e+c+bgEgp+d+bafDfp(+cbagfedc@2)+C +END:EMELODY diff --git a/overlay/rootfs/usr/share/sxmo/ringtones/IrDA_Pager.imy b/overlay/rootfs/usr/share/sxmo/ringtones/IrDA_Pager.imy new file mode 100644 index 0000000..11e8c70 --- /dev/null +++ b/overlay/rootfs/usr/share/sxmo/ringtones/IrDA_Pager.imy @@ -0,0 +1,10 @@ +BEGIN:IMELODY +VERSION:1.2 +FORMAT:CLASS1.0 +NAME:IrDA Pager +COMPOSER:Bananarchy +BEAT:160 +STYLE:S0 +VOLUME:V13 +MELODY:*5e4*5e4r4*5e4r4*5c4*5e3*5g2r2*4g2r2(*5c3r4*4g3r4*4e3*4a3*4b3&b4*4a3@2)*5c2 +END:IMELODY diff --git a/overlay/rootfs/usr/share/sxmo/ringtones/Nokia_Gran_Vals.nrt b/overlay/rootfs/usr/share/sxmo/ringtones/Nokia_Gran_Vals.nrt new file mode 100644 index 0000000..f228d38 --- /dev/null +++ b/overlay/rootfs/usr/share/sxmo/ringtones/Nokia_Gran_Vals.nrt @@ -0,0 +1 @@ +NokiaVals:d=4,o=5,b=225:8e6,8d6,f#,g#,8c#6,8b,d,e,8b,8a,c#,e,2a,8p,8e6,8d6,f#,g#,8c#6,8b,d,e,8b,8a,c#,e,2a diff --git a/prebuilt/sxmo-x11/usr/bin/bananarchy-melody b/prebuilt/sxmo-x11/usr/bin/bananarchy-melody new file mode 100755 index 0000000..1222f4b Binary files /dev/null and b/prebuilt/sxmo-x11/usr/bin/bananarchy-melody differ diff --git a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/dmenu.so b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/dmenu.so index cd53793..0c443b2 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 671171d..c7310f4 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/irc.so b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/irc.so index d1fa5cc..ac04941 100755 Binary files a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/irc.so and b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/irc.so differ diff --git a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/music.so b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/music.so index 4ac60b3..f93d444 100755 Binary files a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/music.so and b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/music.so differ diff --git a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/ringtones.so b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/ringtones.so index 23871bc..3d8c004 100755 Binary files a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/ringtones.so and b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/ringtones.so differ diff --git a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/tox.so b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/tox.so index 9078a4e..4b6b049 100755 Binary files a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/tox.so and b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/tox.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 bd9023b..63b835c 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/scripts/build-sxmo-x11.sh b/scripts/build-sxmo-x11.sh index 59a5d31..e82e79d 100755 --- a/scripts/build-sxmo-x11.sh +++ b/scripts/build-sxmo-x11.sh @@ -272,6 +272,11 @@ EOF -o /bananarchy/prebuilt/sxmo-x11/usr/bin/bananarchy-verify-passcode $STRIP --strip-unneeded /bananarchy/prebuilt/sxmo-x11/usr/bin/bananarchy-verify-passcode + $CXX $OPT_CFLAGS -std=c++20 -Wall -Wextra \ + /bananarchy/src/dwm-plugins/bananarchy_melody.cpp -lm \ + -o /bananarchy/prebuilt/sxmo-x11/usr/bin/bananarchy-melody + $STRIP --strip-unneeded /bananarchy/prebuilt/sxmo-x11/usr/bin/bananarchy-melody + ln -sf dwm-plugin /bananarchy/prebuilt/sxmo-x11/usr/bin/dmenu ln -sf dwm-plugin /bananarchy/prebuilt/sxmo-x11/usr/bin/xdmenu ln -sf dwm-plugin /bananarchy/prebuilt/sxmo-x11/usr/bin/xlocker diff --git a/src/dwm-plugins/bananarchy_melody.cpp b/src/dwm-plugins/bananarchy_melody.cpp new file mode 100644 index 0000000..f98c794 --- /dev/null +++ b/src/dwm-plugins/bananarchy_melody.cpp @@ -0,0 +1,213 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Bananarchy Monophonic Ringtone CLI Synthesizer & Player (bananarchy-melody) +// Supports Nokia RTTTL (.nrt, .rtttl, .rtx), Ericsson eMelody (.emy), and +// IrDA iMelody (.imy). + +#include "monotone.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +volatile sig_atomic_t gStopRequested = 0; +pid_t gChildPid = -1; + +void handleSignal(int) { + gStopRequested = 1; + if (gChildPid > 0) { + ::kill(gChildPid, SIGTERM); + } +} + +void printUsage(const char* prog) { + std::fprintf(stderr, + "Usage:\n" + " %s --wav [--loops N]\n" + " %s --info \n" + " %s [--play] [--loops N] [--volume PCT]\n", + prog, prog, prog); +} + +} // namespace + +int main(int argc, char** argv) { + using namespace bananarchy; + + if (argc < 2) { + printUsage(argv[0]); + return 1; + } + + enum class Mode { + Play = 0, + Wav = 1, + Info = 2, + }; + + Mode mode = Mode::Play; + std::string inputPath; + std::string outputWavPath; + int loops = 1; + int volumePct = 100; + + for (int i = 1; i < argc; ++i) { + const char* arg = argv[i]; + if (!arg) continue; + if (std::strcmp(arg, "-h") == 0 || std::strcmp(arg, "--help") == 0) { + printUsage(argv[0]); + return 0; + } else if (std::strcmp(arg, "--wav") == 0) { + mode = Mode::Wav; + } else if (std::strcmp(arg, "--info") == 0) { + mode = Mode::Info; + } else if (std::strcmp(arg, "--play") == 0) { + mode = Mode::Play; + } else if (std::strcmp(arg, "--loops") == 0 && i + 1 < argc) { + loops = std::clamp(std::atoi(argv[++i]), 1, 100); + } else if (std::strncmp(arg, "--loops=", 8) == 0) { + loops = std::clamp(std::atoi(arg + 8), 1, 100); + } else if (std::strcmp(arg, "--volume") == 0 && i + 1 < argc) { + volumePct = std::clamp(std::atoi(argv[++i]), 0, 150); + } else if (std::strncmp(arg, "--volume=", 9) == 0) { + volumePct = std::clamp(std::atoi(arg + 9), 0, 150); + } else if (arg[0] != '-') { + if (inputPath.empty()) { + inputPath = arg; + } else if (outputWavPath.empty()) { + outputWavPath = arg; + } + } + } + + if (inputPath.empty()) { + printUsage(argv[0]); + return 1; + } + + MonotoneSong song; + if (!parseMonotoneFile(inputPath, &song)) { + std::fprintf(stderr, "bananarchy-melody: failed to parse '%s'\n", + inputPath.c_str()); + return 2; + } + + if (mode == Mode::Info) { + std::printf("NAME=%s\n", song.name.c_str()); + std::printf("COMPOSER=%s\n", song.composer.c_str()); + std::printf("FORMAT=%s\n", song.formatTag.c_str()); + std::printf("FORMAT_LABEL=%s\n", monotoneFormatLabel(song.format)); + std::printf("STYLE=%s\n", monotoneStyleLabel(song.style)); + std::printf("BPM=%d\n", song.bpm); + std::printf("NOTES=%zu\n", song.notes.size()); + std::printf("PITCHED_NOTES=%d\n", song.pitchedNoteCount); + std::printf("DURATION_MS=%d\n", song.totalDurationMs); + return 0; + } + + if (mode == Mode::Wav) { + if (outputWavPath.empty()) { + std::fprintf(stderr, "bananarchy-melody: --wav requires output path\n"); + return 1; + } + if (!synthesizeMonotoneWav(song, outputWavPath, loops)) { + std::fprintf(stderr, "bananarchy-melody: failed to write WAV '%s'\n", + outputWavPath.c_str()); + return 3; + } + return 0; + } + + // Play mode: synthesize single cycle to temp WAV and play with pw-play or mpv + char tmpWav[128]; + std::snprintf(tmpWav, sizeof(tmpWav), "/tmp/bananarchy_melody_%d.wav", + static_cast(::getpid())); + if (!synthesizeMonotoneWav(song, tmpWav, 1)) { + std::fprintf(stderr, "bananarchy-melody: failed to synthesize '%s'\n", + inputPath.c_str()); + return 3; + } + + struct sigaction sa {}; + sa.sa_handler = handleSignal; + sigemptyset(&sa.sa_mask); + sigaction(SIGINT, &sa, nullptr); + sigaction(SIGTERM, &sa, nullptr); + + std::string runtimeDir = "/run/user/" + std::to_string(::getuid()); + const char* xdg = std::getenv("XDG_RUNTIME_DIR"); + struct stat stRuntime {}; + if (!xdg || !*xdg || ::stat(xdg, &stRuntime) != 0) { + ::setenv("XDG_RUNTIME_DIR", runtimeDir.c_str(), 1); + } + + bool playedWithPw = false; + if (::access("/usr/bin/pw-play", X_OK) == 0) { + char volBuf[32]; + std::snprintf(volBuf, sizeof(volBuf), "--volume=%.2f", + std::clamp(volumePct, 0, 150) / 100.0); + for (int i = 0; i < loops && !gStopRequested; ++i) { + pid_t pid = ::fork(); + if (pid == 0) { + int devNull = ::open("/dev/null", O_RDWR); + if (devNull >= 0) { + ::dup2(devNull, STDIN_FILENO); + ::dup2(devNull, STDOUT_FILENO); + ::dup2(devNull, STDERR_FILENO); + if (devNull > 2) ::close(devNull); + } + ::execl("/usr/bin/pw-play", "pw-play", volBuf, tmpWav, + static_cast(nullptr)); + ::_exit(127); + } else if (pid > 0) { + gChildPid = pid; + int st = 0; + ::waitpid(pid, &st, 0); + gChildPid = -1; + if (WIFEXITED(st) && WEXITSTATUS(st) == 0) { + playedWithPw = true; + } else { + break; + } + if (i + 1 < loops && !gStopRequested) { + ::usleep(180000); + } + } + } + } + + if (!playedWithPw && !gStopRequested) { + std::string volArg = "--volume=" + std::to_string(volumePct); + std::string loopArg = "--loop=" + std::to_string(loops); + pid_t pid = ::fork(); + if (pid == 0) { + int devNull = ::open("/dev/null", O_RDWR); + if (devNull >= 0) { + ::dup2(devNull, STDIN_FILENO); + ::dup2(devNull, STDOUT_FILENO); + ::dup2(devNull, STDERR_FILENO); + if (devNull > 2) ::close(devNull); + } + ::execlp("mpv", "mpv", "--no-config", "--no-terminal", + "--no-resume-playback", "--quiet", "--vo=null", "--no-video", + "--ao=pipewire,pulse,alsa", "--audio-channels=stereo", + "--audio-samplerate=48000", "--volume-max=150", volArg.c_str(), + loopArg.c_str(), tmpWav, static_cast(nullptr)); + ::_exit(127); + } else if (pid > 0) { + gChildPid = pid; + int st = 0; + ::waitpid(pid, &st, 0); + gChildPid = -1; + } + } + + ::unlink(tmpWav); + return 0; +} diff --git a/src/dwm-plugins/files_plugin.cpp b/src/dwm-plugins/files_plugin.cpp index 872ab1d..1cb4724 100644 --- a/src/dwm-plugins/files_plugin.cpp +++ b/src/dwm-plugins/files_plugin.cpp @@ -1,5 +1,6 @@ #include "phone_data.h" #include "media_utils.h" +#include "monotone.h" #include "../sxmo-dwm/dwm_plugin.h" #include @@ -30,6 +31,7 @@ enum class ViewMode { InputModal = 5, ConfirmDelete = 6, TextEdit = 7, + RingtoneView = 8, }; enum class SortMode { @@ -171,6 +173,10 @@ bool isImageExt(const std::string& ext) { ext == "svg" || ext == "avif" || ext == "heic"; } +bool isRingtoneExt(const std::string& ext) { + return isMonotoneExt(ext); +} + bool isAudioExt(const std::string& ext) { return ext == "mp3" || ext == "wav" || ext == "ogg" || ext == "oga" || ext == "opus" || ext == "flac" || ext == "m4a" || ext == "aac" || @@ -411,6 +417,17 @@ int runFilesApp(int argc, char** argv) { bool imgValid = false; bool imgFullscreen = false; + // Ringtone / audio preview viewer state + MonotoneSong ringPreviewSong; + bool ringPreviewValid = false; + bool ringPreviewIsMonotone = false; + std::string ringPreviewExtTag; + off_t ringPreviewSize = 0; + std::vector ringNoteLines; + int ringNoteScroll = 0; + pid_t ringPreviewPid = -1; + std::string ringPreviewActivePath; + // Modal input state (New Folder / New File / Rename) InputAction inputAction = InputAction::NewFolder; std::string inputTitle; @@ -673,6 +690,159 @@ int runFilesApp(int argc, char** argv) { mode = ViewMode::ImageView; }; + auto stopRingPreview = [&]() { + if (ringPreviewPid > 0) { + ::kill(ringPreviewPid, SIGTERM); + ::waitpid(ringPreviewPid, nullptr, WNOHANG); + ringPreviewPid = -1; + runAsyncCmd("sxmo_audio.sh device apply >/dev/null 2>&1"); + } + ringPreviewActivePath.clear(); + }; + + auto checkRingPreviewAlive = [&]() -> bool { + if (ringPreviewPid > 0) { + int st = 0; + pid_t r = ::waitpid(ringPreviewPid, &st, WNOHANG); + if (r == ringPreviewPid || (r < 0 && errno == ECHILD)) { + ringPreviewPid = -1; + ringPreviewActivePath.clear(); + return true; + } + } + return false; + }; + + auto readRingVolumePct = [&]() -> int { + std::string cfgDir = homeDir + "/.config/sxmo"; + const char* xdgCfg = std::getenv("XDG_CONFIG_HOME"); + if (xdgCfg && *xdgCfg) cfgDir = std::string(xdgCfg) + "/sxmo"; + std::ifstream ifs(cfgDir + "/ringsettings"); + std::string line; + int vol = 100; + while (std::getline(ifs, line)) { + line = trimStr(line); + auto eq = line.find('='); + if (eq == std::string::npos) continue; + if (trimStr(line.substr(0, eq)) == "SXMO_RINGVOL") { + int v = std::atoi(trimStr(line.substr(eq + 1)).c_str()); + if (v >= 0 && v <= 100) vol = v; + } + } + return vol; + }; + + auto toggleRingPreview = [&](const std::string& path) { + checkRingPreviewAlive(); + if (ringPreviewPid > 0 && ringPreviewActivePath == path) { + stopRingPreview(); + statusBanner = "Preview stopped"; + statusBannerUntilMs = nowMs() + 1800; + return; + } + stopRingPreview(); + + std::string playTarget = path; + if (isMonotoneFile(path)) { + playTarget = "/tmp/xfiles_ring_preview.wav"; + if (!synthesizeMonotoneFileToWav(path, playTarget, 1)) { + statusBanner = "Invalid ringtone file"; + statusBannerUntilMs = nowMs() + 2000; + return; + } + } + + int rvol = std::clamp(readRingVolumePct(), 0, 100); + int rx3 = (rvol <= 0) ? 0 : (56 + (rvol * 32 + 50) / 100); + runAsyncCmd("amixer -c 0 cset \"name='EAR_S'\" 0 >/dev/null 2>&1; " + "amixer -c 0 cset \"name='RX1 MIX1 INP1'\" 0 >/dev/null 2>&1; " + "amixer -c 0 cset \"name='PRI_MI2S_RX Audio Mixer MultiMedia1'\" 1 >/dev/null 2>&1; " + "amixer -c 0 cset \"name='SPK DAC Switch'\" 1 >/dev/null 2>&1; " + "amixer -c 0 cset \"name='RX3 MIX1 INP1'\" 3 >/dev/null 2>&1; " + "amixer -c 0 cset \"name='RX3 Digital Volume'\" " + + std::to_string(rx3) + " >/dev/null 2>&1; " + "wpctl set-mute @DEFAULT_AUDIO_SINK@ 0 >/dev/null 2>&1; " + "wpctl set-volume @DEFAULT_AUDIO_SINK@ 100% >/dev/null 2>&1"); + + pid_t pid = ::fork(); + if (pid == 0) { + std::string runtimeDir = "/run/user/" + std::to_string(::getuid()); + const char* xdg = std::getenv("XDG_RUNTIME_DIR"); + struct stat stRuntime {}; + if (!xdg || !*xdg || ::stat(xdg, &stRuntime) != 0) { + ::setenv("XDG_RUNTIME_DIR", runtimeDir.c_str(), 1); + } + int devNull = ::open("/dev/null", O_RDWR); + if (devNull >= 0) { + ::dup2(devNull, STDIN_FILENO); + ::dup2(devNull, STDOUT_FILENO); + ::dup2(devNull, STDERR_FILENO); + if (devNull > 2) ::close(devNull); + } + ::execlp("mpv", "mpv", "--no-config", "--no-terminal", + "--no-resume-playback", "--quiet", "--vo=null", + "--no-video", "--ao=pipewire,pulse,alsa", + "--audio-channels=stereo", "--audio-samplerate=48000", + "--volume-max=150", "--volume=100", + "--loop=2", playTarget.c_str(), + static_cast(nullptr)); + ::_exit(127); + } else if (pid > 0) { + ringPreviewPid = pid; + ringPreviewActivePath = path; + statusBanner = "Playing preview..."; + statusBannerUntilMs = nowMs() + 1800; + } + }; + + auto openRingtoneViewer = [&](const FileItem& item, bool autoPlay = true) { + viewingFilePath = item.fullPath; + viewingFileName = item.name; + ringPreviewSize = item.size; + ringPreviewExtTag = monoToUpper(getExtLower(item.name)); + ringPreviewIsMonotone = isMonotoneFile(item.name); + ringNoteLines.clear(); + ringNoteScroll = 0; + + if (ringPreviewIsMonotone) { + ringPreviewValid = parseMonotoneFile(item.fullPath, &ringPreviewSong); + if (ringPreviewValid) { + std::string curLine; + for (const auto& n : ringPreviewSong.notes) { + if (n.label.empty()) continue; + if (!curLine.empty() && + curLine.size() + 1 + n.label.size() > 28) { + ringNoteLines.push_back(curLine); + curLine = n.label; + } else { + if (!curLine.empty()) curLine.push_back(' '); + curLine += n.label; + } + } + if (!curLine.empty()) { + ringNoteLines.push_back(curLine); + } + } else { + ringPreviewSong = MonotoneSong{}; + ringPreviewSong.name = monoFilenameStem(item.name); + ringPreviewSong.formatTag = ringPreviewExtTag; + ringNoteLines.push_back("(Invalid or empty melody file)"); + } + } else { + ringPreviewValid = true; + ringPreviewSong = MonotoneSong{}; + ringPreviewSong.name = monoFilenameStem(item.name); + ringPreviewSong.formatTag = ringPreviewExtTag; + ringNoteLines.push_back("Format: " + ringPreviewExtTag + " Audio File"); + ringNoteLines.push_back("Size: " + formatFileSize(item.size)); + } + + mode = ViewMode::RingtoneView; + if (autoPlay && ringPreviewValid) { + toggleRingPreview(item.fullPath); + } + }; + auto installAsWallpaper = [&](const std::string& srcPath, const std::string& fileName) { std::string targetPath = srcPath; @@ -750,6 +920,35 @@ int runFilesApp(int argc, char** argv) { statusBannerUntilMs = nowMs() + 2200; }; + auto installAsNotifSound = [&](const std::string& srcPath, + const std::string& fileName) { + std::string targetPath = srcPath; + std::string ringDir = homeDir + "/Ringtones"; + std::string musDir = homeDir + "/Music"; + if (srcPath.rfind("/usr/share/sxmo/", 0) != 0 && + srcPath.rfind(ringDir + "/", 0) != 0 && + srcPath.rfind(musDir + "/", 0) != 0) { + ::mkdir(ringDir.c_str(), 0755); + std::string dst = ringDir + "/" + fileName; + if (copyRecursive(srcPath, dst)) { + targetPath = dst; + } + } + + std::string cfgDir = homeDir + "/.config/sxmo"; + const char* xdgCfg = std::getenv("XDG_CONFIG_HOME"); + if (xdgCfg && *xdgCfg) cfgDir = std::string(xdgCfg) + "/sxmo"; + ::mkdir((homeDir + "/.config").c_str(), 0755); + ::mkdir(cfgDir.c_str(), 0755); + + { + std::ofstream ofs(cfgDir + "/notif_sound", std::ios::trunc); + if (ofs) ofs << targetPath << "\n"; + } + statusBanner = "Notif/SMS sound set: " + fileName; + statusBannerUntilMs = nowMs() + 2200; + }; + auto isSdCardMounted = []() -> bool { std::ifstream f("/proc/mounts"); std::string line; @@ -773,9 +972,19 @@ int runFilesApp(int argc, char** argv) { if (isImageExt(ext)) { actionsList.push_back({1, kIconEye, "Preview Image"}); actionsList.push_back({14, kIconImage, "Set as Wallpaper"}); + } else if (isRingtoneExt(ext)) { + actionsList.push_back({1, kIconBell, "Preview Ringtone"}); + actionsList.push_back({15, kIconCheck, "Set as Ringtone"}); + actionsList.push_back({24, kIconSms, "Set as Notif / SMS Sound"}); + actionsList.push_back({21, kIconBell, "Open in Ringtones App"}); + actionsList.push_back({22, kIconMusic, "Play in Music Player"}); + actionsList.push_back({17, kIconEye, "View Ringtone Text"}); } else if (isAudioExt(ext)) { actionsList.push_back({1, kIconMusic, "Play in Music Player"}); + actionsList.push_back({23, kIconSpeaker, "Preview Audio / Ringtone"}); actionsList.push_back({15, kIconBell, "Set as Ringtone"}); + actionsList.push_back({24, kIconSms, "Set as Notif / SMS Sound"}); + actionsList.push_back({21, kIconBell, "Open in Ringtones App"}); } else if (isGameBoyExt(ext)) { actionsList.push_back({1, kIconGamepad, "Play in Game Boy Emulator"}); } else if (isJ2meExt(ext)) { @@ -832,6 +1041,7 @@ int runFilesApp(int argc, char** argv) { }; auto hideWindow = [&]() { + stopRingPreview(); if (!visible) return; writeSoftkeySuppress(nowMs() + 450); XUngrabKeyboard(dpy, CurrentTime); @@ -841,7 +1051,18 @@ int runFilesApp(int argc, char** argv) { ::unlink(activePidPath.c_str()); }; + auto openInRingtonesApp = [&](const std::string& path) { + stopRingPreview(); + hideWindow(); + if (isPluginDaemonAlive("ringtones")) { + sendPluginCommand("ringtones", "OPEN " + path); + } else { + runAsyncArgv("xringtones", path.c_str()); + } + }; + auto openInMusicPlayer = [&](const std::string& path) { + stopRingPreview(); hideWindow(); if (isPluginDaemonAlive("music")) { sendPluginCommand("music", "OPEN " + path); @@ -877,6 +1098,8 @@ int runFilesApp(int argc, char** argv) { if (isImageExt(ext)) { imgFullscreen = false; openImageViewer(item); + } else if (isRingtoneExt(ext)) { + openRingtoneViewer(item, true); } else if (isAudioExt(ext)) { openInMusicPlayer(item.fullPath); return; @@ -916,6 +1139,7 @@ int runFilesApp(int argc, char** argv) { auto drawUI = [&]() { if (!visible) return; + checkRingPreviewAlive(); pt.checkAndReload(); XSetForeground(dpy, gc, pt.spec.bgMain); @@ -997,6 +1221,9 @@ int runFilesApp(int argc, char** argv) { if (isImageExt(ext)) { ic = kIconImage; icCol = &colGreen; + } else if (isRingtoneExt(ext)) { + ic = kIconBell; + icCol = &colYellow; } else if (isMediaExt(ext)) { ic = kIconMusic; icCol = &colBlue; @@ -1366,6 +1593,147 @@ int runFilesApp(int argc, char** argv) { (editLines.size() == 1 && editLines[0].empty() && !editModified); drawSoftkeyBar("Menu/Save", "Enter", docEmpty ? "Close" : "Del"); } + + } else if (mode == ViewMode::RingtoneView) { + bool isPl = + (ringPreviewPid > 0 && ringPreviewActivePath == viewingFilePath); + + XSetForeground(dpy, gc, pt.spec.bgHeader); + XFillRectangle(dpy, pix, gc, 0, 0, kWinWidth, 34); + XSetForeground(dpy, gc, pt.spec.border); + XDrawLine(dpy, pix, gc, 0, 33, kWinWidth, 33); + + drawPango(layoutIcon, &colYellow, 6, 0, 34, kIconBell); + drawPango(layoutMain, &colWhite, 28, 0, 34, viewingFileName, 140); + + std::string stateBadge = isPl ? "[PLAYING]" : "[STOPPED]"; + pango_layout_set_width(layoutSmall, -1); + pango_layout_set_text(layoutSmall, stateBadge.c_str(), + static_cast(stateBadge.size())); + int sbw = 0, sbh = 0; + pango_layout_get_pixel_size(layoutSmall, &sbw, &sbh); + drawPango(layoutSmall, isPl ? &colGreen : &colMuted, + kWinWidth - sbw - 6, 0, 34, stateBadge); + + // Metadata card (y=38..104) + XSetForeground(dpy, gc, pt.spec.bgAltEven); + XFillRectangle(dpy, pix, gc, 4, 38, kWinWidth - 8, 66); + XSetForeground(dpy, gc, pt.spec.border); + XDrawRectangle(dpy, pix, gc, 4, 38, kWinWidth - 9, 65); + + std::string fmtTitle = + ringPreviewIsMonotone + ? std::string(monotoneFormatLabel(ringPreviewSong.format)) + : (ringPreviewExtTag + " Audio"); + drawPango(layoutSmall, &colBlue, 10, 40, 18, fmtTitle, 160); + + std::string szStr = formatFileSize(ringPreviewSize); + pango_layout_set_width(layoutSmall, -1); + pango_layout_set_text(layoutSmall, szStr.c_str(), + static_cast(szStr.size())); + int szw = 0, szh = 0; + pango_layout_get_pixel_size(layoutSmall, &szw, &szh); + drawPango(layoutSmall, &colMuted, kWinWidth - szw - 10, 40, 18, szStr); + + std::string nameLine = "Title: " + ringPreviewSong.name; + if (!ringPreviewSong.composer.empty()) { + nameLine += " (" + ringPreviewSong.composer + ")"; + } + drawPango(layoutMain, &colWhite, 10, 58, 22, nameLine, kWinWidth - 20); + + if (ringPreviewIsMonotone && ringPreviewValid) { + char statBuf[128]; + std::snprintf(statBuf, sizeof(statBuf), + "%s | %d BPM | %d notes | %.1fs", + monotoneStyleLabel(ringPreviewSong.style), + ringPreviewSong.bpm, ringPreviewSong.pitchedNoteCount, + ringPreviewSong.totalDurationMs / 1000.0); + drawPango(layoutSmall, &colYellow, 10, 81, 18, statBuf, kWinWidth - 20); + } else { + drawPango(layoutSmall, &colYellow, 10, 81, 18, + "Press OK or [*] to toggle preview", kWinWidth - 20); + } + + // Graphical Piano-Roll / Pitch Contour (y=108..164) + XSetForeground(dpy, gc, pt.spec.bgInput); + XFillRectangle(dpy, pix, gc, 4, 108, kWinWidth - 8, 56); + XSetForeground(dpy, gc, pt.spec.divider); + XDrawRectangle(dpy, pix, gc, 4, 108, kWinWidth - 9, 55); + + if (ringPreviewIsMonotone && ringPreviewValid && + !ringPreviewSong.notes.empty() && + ringPreviewSong.totalDurationMs > 0) { + int minMidi = 127; + int maxMidi = 0; + for (const auto& n : ringPreviewSong.notes) { + if (n.midiNote >= 0) { + minMidi = std::min(minMidi, n.midiNote); + maxMidi = std::max(maxMidi, n.midiNote); + } + } + if (minMidi > maxMidi) { + minMidi = 60; + maxMidi = 84; + } + if (maxMidi - minMidi < 12) { + int mid = (minMidi + maxMidi) / 2; + minMidi = mid - 6; + maxMidi = mid + 6; + } + + const int rollX = 8; + const int rollW = kWinWidth - 16; + const int rollY = 113; + const int rollH = 44; + int accumMs = 0; + int totalMs = std::max(1, ringPreviewSong.totalDurationMs); + + for (size_t ni = 0; ni < ringPreviewSong.notes.size(); ++ni) { + const auto& n = ringPreviewSong.notes[ni]; + int x0 = rollX + (accumMs * rollW) / totalMs; + int x1 = rollX + ((accumMs + n.durationMs) * rollW) / totalMs; + int bw = std::max(2, x1 - x0 - 1); + accumMs += n.durationMs; + + if (n.midiNote >= 0) { + int rel = n.midiNote - minMidi; + int span = std::max(1, maxMidi - minMidi); + int ny = rollY + rollH - 4 - (rel * (rollH - 4)) / span; + XSetForeground( + dpy, gc, + isPl ? ((ni % 2 == 0) ? pt.spec.accent : pt.spec.success) + : pt.spec.accentAlt); + XFillRectangle(dpy, pix, gc, x0, ny, bw, 4); + } else { + XSetForeground(dpy, gc, pt.spec.divider); + XFillRectangle(dpy, pix, gc, x0, rollY + rollH - 2, + std::max(1, bw), 1); + } + } + } else { + drawPango(layoutSmall, &colMuted, 12, 126, 20, + ringPreviewIsMonotone ? "No melody notes parsed" + : "Audio ringtone preview", + kWinWidth - 24); + } + + // Note sequence / details box (y=168..236) + XSetForeground(dpy, gc, pt.spec.bgAltOdd); + XFillRectangle(dpy, pix, gc, 4, 168, kWinWidth - 8, 68); + XSetForeground(dpy, gc, pt.spec.divider); + XDrawRectangle(dpy, pix, gc, 4, 168, kWinWidth - 9, 67); + + const int maxNoteVis = 3; + for (int i = 0; i < maxNoteVis; ++i) { + int idx = ringNoteScroll + i; + if (idx >= static_cast(ringNoteLines.size())) break; + drawPango(layoutSmall, &colLight, 8, 171 + i * 20, 20, + ringNoteLines[idx], kWinWidth - 16); + } + + drawPango(layoutSmall, &colMuted, 6, 240, 20, + "*:Play #:Set Notif L/R:Step 1:Edit", kWinWidth - 12); + drawSoftkeyBar("Set Ring", isPl ? "Stop" : "Play [*]", "Back"); } int64_t tNow = nowMs(); @@ -1385,8 +1753,33 @@ int runFilesApp(int argc, char** argv) { auto showWindow = [&](const std::string& dirArg) { writeIntFile(activePidPath, static_cast(::getpid())); closeOtherPlugins("files"); + stopRingPreview(); mode = ViewMode::Browser; - loadDirectory(dirArg.empty() ? currentDir : dirArg); + if (dirArg.empty()) { + loadDirectory(currentDir); + } else { + struct stat st {}; + if (::stat(dirArg.c_str(), &st) == 0 && S_ISREG(st.st_mode)) { + char resolved[4096]; + std::string full = dirArg; + if (::realpath(dirArg.c_str(), resolved) != nullptr) { + full = resolved; + } + size_t sl = full.rfind('/'); + std::string pDir = + (sl == 0 || sl == std::string::npos) ? "/" : full.substr(0, sl); + std::string fName = + (sl == std::string::npos) ? full : full.substr(sl + 1); + loadDirectory(pDir, fName); + if (!filteredItems.empty() && + filteredItems[selected].name == fName && + isRingtoneExt(getExtLower(fName))) { + openRingtoneViewer(filteredItems[selected], true); + } + } else { + loadDirectory(dirArg); + } + } if (!visible) { visible = true; XMapRaised(dpy, win); @@ -1682,6 +2075,16 @@ int runFilesApp(int argc, char** argv) { installAsRingtone(filteredItems[selected].fullPath, filteredItems[selected].name); mode = ViewMode::Browser; + } else if (actId == 24 && !filteredItems.empty()) { + installAsNotifSound(filteredItems[selected].fullPath, + filteredItems[selected].name); + mode = ViewMode::Browser; + } else if (actId == 21 && !filteredItems.empty()) { + openInRingtonesApp(filteredItems[selected].fullPath); + } else if (actId == 22 && !filteredItems.empty()) { + openInMusicPlayer(filteredItems[selected].fullPath); + } else if (actId == 23 && !filteredItems.empty()) { + openRingtoneViewer(filteredItems[selected], true); } else if (actId == 16 && !filteredItems.empty()) { openTextEditor(filteredItems[selected].fullPath, filteredItems[selected].name); @@ -1732,6 +2135,22 @@ int runFilesApp(int argc, char** argv) { } }; + auto stepRingtoneInFolder = [&](int delta) { + if (filteredItems.empty()) return; + int n = static_cast(filteredItems.size()); + for (int step = 1; step <= n; ++step) { + int idx = (selected + delta * step + n * 2) % n; + if (!filteredItems[idx].isDir) { + std::string ext = getExtLower(filteredItems[idx].name); + if (isRingtoneExt(ext) || isAudioExt(ext)) { + selected = idx; + openRingtoneViewer(filteredItems[selected], true); + return; + } + } + } + }; + auto handleSoftkeyAction = [&](bool isLeft) { if (mode == ViewMode::Browser) { if (isLeft) { @@ -1793,6 +2212,13 @@ int runFilesApp(int argc, char** argv) { mode = ViewMode::Browser; } } + } else if (mode == ViewMode::RingtoneView) { + if (isLeft) { + installAsRingtone(viewingFilePath, viewingFileName); + } else { + stopRingPreview(); + mode = ViewMode::Browser; + } } else if (mode == ViewMode::PropsView) { mode = ViewMode::Browser; } else if (mode == ViewMode::InputModal) { @@ -2113,6 +2539,35 @@ int runFilesApp(int argc, char** argv) { stepImageInFolder(1); drawUI(); } + } else if (mode == ViewMode::RingtoneView) { + char d = mapDialKey(sym, kc, ev.xkey.state); + if (d == '*' || sym == XK_Return || sym == XK_KP_Enter) { + toggleRingPreview(viewingFilePath); + drawUI(); + } else if (d == '#') { + installAsNotifSound(viewingFilePath, viewingFileName); + drawUI(); + } else if (d == '1') { + stopRingPreview(); + openTextEditor(viewingFilePath, viewingFileName); + drawUI(); + } else if (d == '2') { + openInRingtonesApp(viewingFilePath); + } else if (sym == XK_Left || sym == XK_KP_Left) { + stepRingtoneInFolder(-1); + drawUI(); + } else if (sym == XK_Right || sym == XK_KP_Right) { + stepRingtoneInFolder(1); + drawUI(); + } else if (sym == XK_Up || sym == XK_KP_Up) { + ringNoteScroll = std::max(0, ringNoteScroll - 1); + drawUI(); + } else if (sym == XK_Down || sym == XK_KP_Down) { + int maxSc = std::max( + 0, static_cast(ringNoteLines.size()) - 3); + ringNoteScroll = std::min(maxSc, ringNoteScroll + 1); + drawUI(); + } } else if (mode == ViewMode::PropsView) { if (sym == XK_Return || sym == XK_KP_Enter) { mode = ViewMode::Browser; @@ -2152,6 +2607,9 @@ int runFilesApp(int argc, char** argv) { } int64_t tNow = nowMs(); + if (visible && checkRingPreviewAlive()) { + drawUI(); + } if (visible && softkeyPending != 0 && tNow >= softkeyDeadlineMs) { if (querySoftkeysDown(dpy) == 3) { softkeyPending = 0; @@ -2195,6 +2653,9 @@ int runFilesApp(int argc, char** argv) { timeoutMs = (timeoutMs < 0) ? banRem : std::min(timeoutMs, banRem); } } + if (visible && ringPreviewPid > 0) { + timeoutMs = (timeoutMs < 0) ? 400 : std::min(timeoutMs, 400); + } struct pollfd pfds[2]; int nfds = 0; diff --git a/src/dwm-plugins/irc_plugin.cpp b/src/dwm-plugins/irc_plugin.cpp index 32b37ec..f3acd75 100644 --- a/src/dwm-plugins/irc_plugin.cpp +++ b/src/dwm-plugins/irc_plugin.cpp @@ -456,7 +456,8 @@ int irc_run_main(int argc, char** argv) { buffers[bIdx].unreadCount++; if (hl) { buffers[bIdx].hasHighlight = true; - neoui_vibrate(60); + runAsyncCmd("PATH=\"$HOME/.config/sxmo/hooks:/usr/share/sxmo/default_hooks:$PATH\" " + "sxmo_hook_notification.sh >/dev/null 2>&1"); } } return; diff --git a/src/dwm-plugins/monotone.h b/src/dwm-plugins/monotone.h new file mode 100644 index 0000000..2935614 --- /dev/null +++ b/src/dwm-plugins/monotone.h @@ -0,0 +1,1063 @@ +// SPDX-License-Identifier: GPL-2.0-only +// Bananarchy Monophonic Ringtone Parser & Synthesizer +// Supports Nokia RTTTL (.rtttl), Nokia Ringtone (.nrt), Extended RTTTL (.rtx), +// Ericsson eMelody (.emy), and IrDA iMelody (.imy). + +#ifndef DWM_PLUGINS_MONOTONE_H +#define DWM_PLUGINS_MONOTONE_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace bananarchy { + +enum class MonotoneFormat { + Unknown = 0, + Rtttl = 1, + Nrt = 2, + Rtx = 3, + EMelody = 4, + IMelody = 5, +}; + +enum class MonotoneStyle { + Normal = 0, // S0 / N: natural articulation gap at end of note + Continuous = 1, // S1 / C: legato (no gap between consecutive notes) + Staccato = 2, // S2 / S: staccato (short crisp notes) +}; + +struct MonotoneNote { + double freqHz = 0.0; // 0.0 = rest / pause + int durationMs = 0; // total note slot duration in ms + int toneMs = 0; // audible tone duration in ms + int midiNote = -1; // -1 for rest, else MIDI note number (69 = A4 = 440Hz) + int volume = 12; // 0..15 relative volume + std::string label; // compact note token, e.g. "8E6", "4F#5", "8P" + bool vibeOn = false; + bool ledOn = false; +}; + +struct MonotoneSong { + MonotoneFormat format = MonotoneFormat::Unknown; + std::string formatTag; // "NRT", "RTTTL", "RTX", "EMY", "IMY" + std::string name; // parsed melody name or filename stem + std::string composer; // optional COMPOSER header (.emy / .imy) + int bpm = 120; // tempo in beats per minute + int defaultOctave = 5; + int defaultDuration = 4; + int loopCount = 0; // RTX l= loop parameter + MonotoneStyle style = MonotoneStyle::Normal; + int totalDurationMs = 0; + int pitchedNoteCount = 0; + std::vector notes; + std::string rawMelody; +}; + +inline std::string monoToLower(const std::string& s) { + std::string out = s; + for (char& c : out) { + c = static_cast(std::tolower(static_cast(c))); + } + return out; +} + +inline std::string monoToUpper(const std::string& s) { + std::string out = s; + for (char& c : out) { + c = static_cast(std::toupper(static_cast(c))); + } + return out; +} + +inline std::string monoTrim(const std::string& s) { + size_t b = 0; + while (b < s.size() && + std::isspace(static_cast(s[b]))) { + ++b; + } + size_t e = s.size(); + while (e > b && + std::isspace(static_cast(s[e - 1]))) { + --e; + } + return s.substr(b, e - b); +} + +inline std::string monoGetExtLower(const std::string& pathOrName) { + size_t sl = pathOrName.rfind('/'); + size_t dot = pathOrName.rfind('.'); + if (dot == std::string::npos || (sl != std::string::npos && dot < sl) || + dot + 1 >= pathOrName.size()) { + return ""; + } + return monoToLower(pathOrName.substr(dot + 1)); +} + +inline std::string monoFilenameStem(const std::string& pathOrName) { + size_t sl = pathOrName.rfind('/'); + std::string base = + (sl == std::string::npos) ? pathOrName : pathOrName.substr(sl + 1); + size_t dot = base.rfind('.'); + if (dot != std::string::npos && dot > 0) { + base = base.substr(0, dot); + } + for (char& c : base) { + if (c == '_' || c == '-') c = ' '; + } + return monoTrim(base); +} + +inline bool isMonotoneExt(const std::string& extLower) { + std::string e = monoToLower(extLower); + return e == "nrt" || e == "rtttl" || e == "rtx" || + e == "emy" || e == "imy"; +} + +inline bool isMonotoneFile(const std::string& pathOrName, + std::string* extUpperOut = nullptr) { + std::string ext = monoGetExtLower(pathOrName); + if (!isMonotoneExt(ext)) return false; + if (extUpperOut) { + *extUpperOut = monoToUpper(ext); + } + return true; +} + +inline MonotoneFormat monotoneFormatFromExt(const std::string& extLower) { + std::string e = monoToLower(extLower); + if (e == "nrt") return MonotoneFormat::Nrt; + if (e == "rtttl") return MonotoneFormat::Rtttl; + if (e == "rtx") return MonotoneFormat::Rtx; + if (e == "emy") return MonotoneFormat::EMelody; + if (e == "imy") return MonotoneFormat::IMelody; + return MonotoneFormat::Unknown; +} + +inline const char* monotoneFormatTag(MonotoneFormat fmt) { + switch (fmt) { + case MonotoneFormat::Nrt: return "NRT"; + case MonotoneFormat::Rtttl: return "RTTTL"; + case MonotoneFormat::Rtx: return "RTX"; + case MonotoneFormat::EMelody: return "EMY"; + case MonotoneFormat::IMelody: return "IMY"; + default: return "TONE"; + } +} + +inline const char* monotoneFormatLabel(MonotoneFormat fmt) { + switch (fmt) { + case MonotoneFormat::Nrt: return "Nokia NRT (RTTTL)"; + case MonotoneFormat::Rtttl: return "Nokia RTTTL"; + case MonotoneFormat::Rtx: return "Nokia RTX"; + case MonotoneFormat::EMelody: return "Ericsson eMelody"; + case MonotoneFormat::IMelody: return "IrDA iMelody"; + default: return "Monophonic Ringtone"; + } +} + +inline const char* monotoneStyleLabel(MonotoneStyle st) { + switch (st) { + case MonotoneStyle::Continuous: return "Legato"; + case MonotoneStyle::Staccato: return "Staccato"; + default: return "Natural"; + } +} + +inline int noteCharToSemitone(char lowCh, bool* isRestOut = nullptr) { + if (isRestOut) *isRestOut = false; + switch (lowCh) { + case 'c': return 0; + case 'd': return 2; + case 'e': return 4; + case 'f': return 5; + case 'g': return 7; + case 'a': return 9; + case 'b': + case 'h': return 11; + case 'p': + case 'r': + if (isRestOut) *isRestOut = true; + return -1; + default: + return -2; + } +} + +inline const char* semitoneToNoteName(int semi) { + static const char* kNames[12] = { + "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" + }; + int idx = ((semi % 12) + 12) % 12; + return kNames[idx]; +} + +inline int computeToneDurationMs(int slotMs, MonotoneStyle style) { + if (slotMs <= 0) return 0; + if (style == MonotoneStyle::Continuous) { + return slotMs; + } + if (style == MonotoneStyle::Staccato) { + return std::max(12, (slotMs * 52) / 100); + } + int gap = std::clamp(slotMs / 10, 8, 32); + return std::max(12, slotMs - gap); +} + +inline MonotoneNote makeMonotoneNote(int midi, int durDivisor, int slotMs, + MonotoneStyle style, int volume = 12, + bool vibeOn = false, bool ledOn = false) { + MonotoneNote n; + n.durationMs = std::clamp(slotMs, 12, 12000); + n.volume = std::clamp(volume, 0, 15); + n.vibeOn = vibeOn; + n.ledOn = ledOn; + std::string dStr = (durDivisor > 0) ? std::to_string(durDivisor) : ""; + if (midi < 0 || n.volume == 0) { + n.freqHz = 0.0; + n.toneMs = 0; + n.midiNote = -1; + n.label = dStr + "P"; + return n; + } + midi = std::clamp(midi, 24, 119); + n.midiNote = midi; + n.freqHz = 440.0 * std::pow(2.0, static_cast(midi - 69) / 12.0); + n.toneMs = computeToneDurationMs(n.durationMs, style); + int oct = (midi / 12) - 1; + int semi = midi % 12; + n.label = dStr + semitoneToNoteName(semi) + std::to_string(oct); + return n; +} + +inline void applyRtttlControlPair(const std::string& rawPair, + int* curDur, int* curOct, int* curBpm, + MonotoneStyle* curStyle, int* loopCount) { + auto eq = rawPair.find('='); + if (eq == std::string::npos) return; + std::string k = monoToLower(monoTrim(rawPair.substr(0, eq))); + std::string v = monoToLower(monoTrim(rawPair.substr(eq + 1))); + if (k.empty() || v.empty()) return; + int val = std::atoi(v.c_str()); + if (k == "d" && val >= 1 && val <= 128) { + *curDur = val; + } else if (k == "o" && val >= 0 && val <= 8) { + *curOct = val; + } else if (k == "b" && val >= 10 && val <= 900) { + *curBpm = val; + } else if (k == "l" && val >= 0 && val <= 64) { + *loopCount = val; + } else if (k == "s") { + if (v[0] == 'c' || v[0] == '1') { + *curStyle = MonotoneStyle::Continuous; + } else if (v[0] == 's' || v[0] == '2') { + *curStyle = MonotoneStyle::Staccato; + } else { + *curStyle = MonotoneStyle::Normal; + } + } +} + +inline bool parseRtttlContent(const std::string& rawContent, + MonotoneFormat fmtHint, + const std::string& fallbackName, + MonotoneSong* outSong) { + if (!outSong) return false; + *outSong = MonotoneSong{}; + outSong->format = + (fmtHint == MonotoneFormat::Nrt || fmtHint == MonotoneFormat::Rtx) + ? fmtHint + : MonotoneFormat::Rtttl; + + std::string cleaned; + std::istringstream iss(rawContent); + std::string line; + int colonCount = 0; + while (std::getline(iss, line)) { + if (!line.empty() && line.back() == '\r') line.pop_back(); + if (cleaned.empty() && line.size() >= 3 && + static_cast(line[0]) == 0xEF && + static_cast(line[1]) == 0xBB && + static_cast(line[2]) == 0xBF) { + line.erase(0, 3); + } + std::string tr = monoTrim(line); + if (tr.empty()) continue; + if (cleaned.empty() && + (tr[0] == '#' || tr[0] == ';' || tr.rfind("//", 0) == 0)) { + continue; + } + int lineColons = 0; + for (char c : tr) { + if (c == ':') ++lineColons; + } + if (!cleaned.empty() && colonCount >= 2 && lineColons >= 1) { + // Stop at the start of a second RTTTL tune in a multi-tune file + break; + } + colonCount += lineColons; + if (!cleaned.empty() && cleaned.back() != ',' && cleaned.back() != ':' && + tr.front() != ',' && tr.front() != ':') { + cleaned.push_back(','); + } + cleaned += tr; + } + + if (cleaned.empty()) return false; + + std::string namePart; + std::string ctrlPart; + std::string notesPart; + + size_t c1 = cleaned.find(':'); + if (c1 == std::string::npos) { + notesPart = cleaned; + } else { + size_t c2 = cleaned.find(':', c1 + 1); + if (c2 == std::string::npos) { + std::string first = cleaned.substr(0, c1); + std::string second = cleaned.substr(c1 + 1); + if (first.find('=') != std::string::npos) { + ctrlPart = first; + } else { + namePart = first; + } + notesPart = second; + } else { + namePart = cleaned.substr(0, c1); + ctrlPart = cleaned.substr(c1 + 1, c2 - c1 - 1); + notesPart = cleaned.substr(c2 + 1); + } + } + + int curDur = 4; + int curOct = 6; + int curBpm = 63; + int loopCount = 0; + MonotoneStyle curStyle = MonotoneStyle::Normal; + + { + std::string tok; + for (size_t i = 0; i <= ctrlPart.size(); ++i) { + char c = (i < ctrlPart.size()) ? ctrlPart[i] : ','; + if (c == ',' || c == ';') { + if (!tok.empty()) { + applyRtttlControlPair(tok, &curDur, &curOct, &curBpm, &curStyle, + &loopCount); + tok.clear(); + } + } else { + tok.push_back(c); + } + } + } + + outSong->name = monoTrim(namePart); + if (outSong->name.empty()) { + outSong->name = fallbackName.empty() ? "Nokia Ringtone" : fallbackName; + } + outSong->bpm = curBpm; + outSong->defaultDuration = curDur; + outSong->defaultOctave = curOct; + outSong->style = curStyle; + outSong->loopCount = loopCount; + outSong->rawMelody = monoTrim(notesPart); + + int octOffset = (curOct <= 2) ? 3 : 0; + + std::string tok; + for (size_t i = 0; i <= notesPart.size(); ++i) { + char c = (i < notesPart.size()) ? notesPart[i] : ','; + if (c == ',' || c == ';') { + std::string t = monoTrim(tok); + tok.clear(); + if (t.empty()) continue; + + if (t.find('=') != std::string::npos) { + applyRtttlControlPair(t, &curDur, &curOct, &curBpm, &curStyle, + &loopCount); + if (outSong->format == MonotoneFormat::Rtttl) { + outSong->format = MonotoneFormat::Rtx; + } + continue; + } + + size_t pos = 0; + int parsedDur = 0; + while (pos < t.size() && + std::isdigit(static_cast(t[pos]))) { + parsedDur = parsedDur * 10 + (t[pos] - '0'); + ++pos; + } + int dur = (parsedDur > 0) ? parsedDur : curDur; + dur = std::clamp(dur, 1, 128); + + char noteCh = 0; + int accidental = 0; + int dots = 0; + int parsedOct = -1; + + while (pos < t.size()) { + char ch = static_cast( + std::tolower(static_cast(t[pos]))); + if (noteCh == 0 && + ((ch >= 'a' && ch <= 'h') || ch == 'p' || ch == 'r')) { + noteCh = ch; + } else if (ch == '#' || ch == '_') { + accidental = 1; + } else if (ch == '&') { + accidental = -1; + } else if (ch == 'b' && noteCh != 0 && noteCh != 'p' && + noteCh != 'r') { + accidental = -1; + } else if (ch == '.') { + ++dots; + } else if (std::isdigit(static_cast(ch)) && + parsedOct < 0) { + parsedOct = ch - '0'; + } + ++pos; + } + + if (noteCh == 0) continue; + bool isRest = false; + int semi = noteCharToSemitone(noteCh, &isRest); + if (semi == -2) continue; + + double wholeMs = 240000.0 / static_cast(std::max(10, curBpm)); + double slotMs = wholeMs / static_cast(dur); + if (dots == 1) slotMs *= 1.5; + else if (dots >= 2) slotMs *= 1.75; + + int midi = -1; + if (!isRest) { + int oct = ((parsedOct >= 0) ? parsedOct : curOct) + octOffset; + oct = std::clamp(oct, 2, 8); + midi = (oct + 1) * 12 + semi + accidental; + } + + MonotoneNote note = makeMonotoneNote( + midi, dur, static_cast(slotMs + 0.5), curStyle, 13); + outSong->totalDurationMs += note.durationMs; + if (note.midiNote >= 0) { + ++outSong->pitchedNoteCount; + } + outSong->notes.push_back(note); + if (outSong->notes.size() >= 2048) break; + } else { + tok.push_back(c); + } + } + + outSong->formatTag = monotoneFormatTag(outSong->format); + return !outSong->notes.empty(); +} + +inline std::string expandMelodyRepeats(const std::string& src, int depth = 0) { + if (depth > 4 || src.empty()) return src; + std::string out; + out.reserve(std::min(16384, src.size() * 2)); + + size_t i = 0; + while (i < src.size() && out.size() < 16384) { + if (src[i] == '(') { + int pDepth = 1; + size_t j = i + 1; + while (j < src.size() && pDepth > 0) { + if (src[j] == '(') ++pDepth; + else if (src[j] == ')') --pDepth; + ++j; + } + std::string inner = + (pDepth == 0) ? src.substr(i + 1, j - i - 2) : src.substr(i + 1); + int repeats = 2; + size_t atPos = inner.rfind('@'); + if (atPos != std::string::npos) { + std::string repStr = inner.substr(atPos + 1); + inner = inner.substr(0, atPos); + int parsedRep = std::atoi(repStr.c_str()); + if (parsedRep == 0) { + repeats = 2; // @0 is infinite repeat in iMelody; play twice for WAV + } else { + repeats = std::clamp(parsedRep, 1, 8); + } + } + std::string expandedInner = expandMelodyRepeats(inner, depth + 1); + for (int r = 0; r < repeats && out.size() < 16384; ++r) { + out += expandedInner; + } + i = j; + } else { + out.push_back(src[i]); + ++i; + } + } + return out; +} + +inline bool matchAsciiKeywordNoCase(const std::string& s, size_t pos, + const char* kw) { + size_t klen = std::strlen(kw); + if (pos + klen > s.size()) return false; + for (size_t i = 0; i < klen; ++i) { + if (std::tolower(static_cast(s[pos + i])) != + std::tolower(static_cast(kw[i]))) { + return false; + } + } + return true; +} + +inline bool parseMelodyHeaderAndBody(const std::string& rawContent, + MonotoneFormat fmtHint, + const std::string& fallbackName, + MonotoneSong* outSong) { + if (!outSong) return false; + *outSong = MonotoneSong{}; + outSong->format = + (fmtHint == MonotoneFormat::EMelody) ? MonotoneFormat::EMelody + : MonotoneFormat::IMelody; + outSong->bpm = 120; + outSong->defaultOctave = 5; + outSong->defaultDuration = (outSong->format == MonotoneFormat::EMelody) ? 8 : 4; + outSong->style = MonotoneStyle::Normal; + + int initVol = 12; + std::string melodyBuf; + std::string rawLinesFallback; + bool inMelody = false; + bool sawAnyHeader = false; + + std::istringstream iss(rawContent); + std::string line; + while (std::getline(iss, line)) { + if (!line.empty() && line.back() == '\r') line.pop_back(); + if (rawLinesFallback.empty() && line.size() >= 3 && + static_cast(line[0]) == 0xEF && + static_cast(line[1]) == 0xBB && + static_cast(line[2]) == 0xBF) { + line.erase(0, 3); + } + std::string tr = monoTrim(line); + if (tr.empty()) continue; + + std::string up = monoToUpper(tr); + if (up.rfind("BEGIN:IMELODY", 0) == 0) { + outSong->format = MonotoneFormat::IMelody; + sawAnyHeader = true; + inMelody = false; + } else if (up.rfind("BEGIN:EMELODY", 0) == 0) { + outSong->format = MonotoneFormat::EMelody; + sawAnyHeader = true; + inMelody = false; + } else if (up.rfind("END:IMELODY", 0) == 0 || + up.rfind("END:EMELODY", 0) == 0) { + inMelody = false; + break; + } else if (up.rfind("VERSION:", 0) == 0 || + up.rfind("FORMAT:", 0) == 0) { + sawAnyHeader = true; + inMelody = false; + } else if (up.rfind("NAME:", 0) == 0) { + outSong->name = monoTrim(tr.substr(5)); + sawAnyHeader = true; + inMelody = false; + } else if (up.rfind("COMPOSER:", 0) == 0) { + outSong->composer = monoTrim(tr.substr(9)); + sawAnyHeader = true; + inMelody = false; + } else if (up.rfind("BEAT:", 0) == 0) { + int b = std::atoi(monoTrim(tr.substr(5)).c_str()); + if (b >= 20 && b <= 900) outSong->bpm = b; + sawAnyHeader = true; + inMelody = false; + } else if (up.rfind("STYLE:", 0) == 0) { + std::string sv = monoToUpper(monoTrim(tr.substr(6))); + if (sv == "S1" || sv == "1") { + outSong->style = MonotoneStyle::Continuous; + } else if (sv == "S2" || sv == "2") { + outSong->style = MonotoneStyle::Staccato; + } else { + outSong->style = MonotoneStyle::Normal; + } + sawAnyHeader = true; + inMelody = false; + } else if (up.rfind("VOLUME:", 0) == 0) { + std::string vv = monoToUpper(monoTrim(tr.substr(7))); + if (!vv.empty() && vv[0] == 'V') vv.erase(0, 1); + if (!vv.empty() && std::isdigit(static_cast(vv[0]))) { + initVol = std::clamp(std::atoi(vv.c_str()), 1, 15); + } + sawAnyHeader = true; + inMelody = false; + } else if (up.rfind("MELODY:", 0) == 0) { + melodyBuf += monoTrim(tr.substr(7)); + sawAnyHeader = true; + inMelody = true; + } else { + if (inMelody) { + melodyBuf += tr; + } else if (!sawAnyHeader && tr[0] != ';') { + rawLinesFallback += tr; + } + } + } + + if (melodyBuf.empty()) { + melodyBuf = rawLinesFallback; + } + if (outSong->name.empty()) { + outSong->name = fallbackName.empty() ? "Melody Ringtone" : fallbackName; + } + outSong->rawMelody = melodyBuf; + outSong->formatTag = monotoneFormatTag(outSong->format); + + std::string s = expandMelodyRepeats(melodyBuf); + if (s.empty()) return false; + + int curVol = initVol; + MonotoneStyle curStyle = outSong->style; + bool curVibe = false; + bool curLed = false; + + size_t i = 0; + while (i < s.size() && outSong->notes.size() < 2048) { + unsigned char uc = static_cast(s[i]); + if (std::isspace(uc) || s[i] == ',' || s[i] == '(' || s[i] == ')') { + ++i; + continue; + } + + // Check special iMelody/eMelody device keywords first so their letters + // (b, a, c, e, d, f) are never misread as musical notes. + if (matchAsciiKeywordNoCase(s, i, "ledon")) { + curLed = true; + i += 5; + continue; + } + if (matchAsciiKeywordNoCase(s, i, "ledoff")) { + curLed = false; + i += 6; + continue; + } + if (matchAsciiKeywordNoCase(s, i, "vibeon")) { + curVibe = true; + i += 6; + continue; + } + if (matchAsciiKeywordNoCase(s, i, "vibeoff")) { + curVibe = false; + i += 7; + continue; + } + if (matchAsciiKeywordNoCase(s, i, "backon")) { + i += 6; + continue; + } + if (matchAsciiKeywordNoCase(s, i, "backoff")) { + i += 7; + continue; + } + + // Volume modifier: V+, V-, V0..V15 + if ((s[i] == 'v' || s[i] == 'V') && i + 1 < s.size()) { + char nx = s[i + 1]; + if (nx == '+') { + curVol = std::min(15, curVol + 1); + i += 2; + continue; + } else if (nx == '-') { + curVol = std::max(1, curVol - 1); + i += 2; + continue; + } else if (std::isdigit(static_cast(nx))) { + i += 1; + int v = 0; + while (i < s.size() && + std::isdigit(static_cast(s[i]))) { + v = v * 10 + (s[i] - '0'); + ++i; + } + curVol = std::clamp(v, 0, 15); + continue; + } + } + + // Inline style modifier: S0, S1, S2 + if ((s[i] == 's' || s[i] == 'S') && i + 1 < s.size() && + s[i + 1] >= '0' && s[i + 1] <= '2') { + char sc = s[i + 1]; + if (sc == '1') curStyle = MonotoneStyle::Continuous; + else if (sc == '2') curStyle = MonotoneStyle::Staccato; + else curStyle = MonotoneStyle::Normal; + i += 2; + continue; + } + + // Skip stray @repeat suffixes if any + if (s[i] == '@') { + ++i; + while (i < s.size() && + std::isdigit(static_cast(s[i]))) { + ++i; + } + continue; + } + + // Parse note prefix modifiers (+, -, *oct, #, &) + int octShift = 0; + int explicitOct = -1; + int accidental = 0; + while (i < s.size()) { + if (s[i] == '+') { + ++octShift; + ++i; + } else if (s[i] == '-') { + --octShift; + ++i; + } else if (s[i] == '*' && i + 1 < s.size() && + s[i + 1] >= '0' && s[i + 1] <= '8') { + explicitOct = s[i + 1] - '0'; + i += 2; + } else if (s[i] == '#') { + accidental = 1; + ++i; + } else if (s[i] == '&') { + accidental = -1; + ++i; + } else { + break; + } + } + + if (i >= s.size()) break; + + char rawNoteCh = s[i]; + char lowNoteCh = static_cast( + std::tolower(static_cast(rawNoteCh))); + bool isUpperNote = + std::isupper(static_cast(rawNoteCh)) != 0; + + bool isRest = false; + int semi = noteCharToSemitone(lowNoteCh, &isRest); + if (semi == -2) { + ++i; + continue; + } + ++i; + + // Optional postfix sharp if followed by duration digit, dot, or end + if (i < s.size() && s[i] == '#') { + if (i + 1 >= s.size() || + std::isdigit(static_cast(s[i + 1])) || + s[i + 1] == '.' || s[i + 1] == ':' || s[i + 1] == ';') { + accidental = 1; + ++i; + } + } + + // Duration digit: 0=whole, 1=half, 2=quarter, 3=eighth, 4=16th, 5=32nd + int durDivisor = 4; + if (i < s.size() && s[i] >= '0' && s[i] <= '5') { + int durCode = s[i] - '0'; + durDivisor = (1 << durCode); + ++i; + } else if (outSong->format == MonotoneFormat::EMelody) { + // Classic Ericsson eMelody: uppercase = 1/4 (long), lowercase = 1/8 (short) + durDivisor = isUpperNote ? 4 : 8; + } else { + durDivisor = 4; + } + + // Optional duration specifier (., :, ;) + double durMult = 1.0; + if (i < s.size()) { + if (s[i] == '.') { + durMult = 1.5; + ++i; + } else if (s[i] == ':') { + durMult = 1.75; + ++i; + } else if (s[i] == ';') { + durMult = 2.0 / 3.0; + ++i; + } + } + + double wholeMs = + 240000.0 / static_cast(std::max(20, outSong->bpm)); + double slotMs = + (wholeMs / static_cast(durDivisor)) * durMult; + + int midi = -1; + if (!isRest) { + int baseOct = (explicitOct >= 0) ? (explicitOct + 1) : 5; + int oct = std::clamp(baseOct + octShift, 2, 8); + midi = (oct + 1) * 12 + semi + accidental; + } + + MonotoneNote note = makeMonotoneNote( + midi, durDivisor, static_cast(slotMs + 0.5), curStyle, curVol, + curVibe, curLed); + outSong->totalDurationMs += note.durationMs; + if (note.midiNote >= 0) { + ++outSong->pitchedNoteCount; + } + outSong->notes.push_back(note); + } + + return !outSong->notes.empty(); +} + +inline bool parseMonotoneString(const std::string& content, + MonotoneFormat fmtHint, + const std::string& fallbackName, + MonotoneSong* outSong) { + if (!outSong) return false; + std::string up = monoToUpper(content); + MonotoneFormat fmt = fmtHint; + if (up.find("BEGIN:IMELODY") != std::string::npos) { + fmt = MonotoneFormat::IMelody; + } else if (up.find("BEGIN:EMELODY") != std::string::npos) { + fmt = MonotoneFormat::EMelody; + } else if (fmt == MonotoneFormat::Unknown) { + if (up.find("MELODY:") != std::string::npos) { + fmt = MonotoneFormat::IMelody; + } else { + fmt = MonotoneFormat::Rtttl; + } + } + + if (fmt == MonotoneFormat::IMelody || fmt == MonotoneFormat::EMelody) { + if (parseMelodyHeaderAndBody(content, fmt, fallbackName, outSong)) { + return true; + } + return parseRtttlContent(content, fmt, fallbackName, outSong); + } + if (parseRtttlContent(content, fmt, fallbackName, outSong)) { + return true; + } + return parseMelodyHeaderAndBody(content, fmt, fallbackName, outSong); +} + +inline bool parseMonotoneFile(const std::string& path, + MonotoneSong* outSong) { + std::ifstream ifs(path, std::ios::binary); + if (!ifs) return false; + std::ostringstream oss; + oss << ifs.rdbuf(); + std::string content = oss.str(); + if (content.empty()) return false; + + std::string ext = monoGetExtLower(path); + MonotoneFormat fmt = monotoneFormatFromExt(ext); + std::string fallbackName = monoFilenameStem(path); + return parseMonotoneString(content, fmt, fallbackName, outSong); +} + +inline bool synthesizeMonotoneWav(const MonotoneSong& song, + const std::string& wavOutPath, + int loops = 1) { + if (song.notes.empty()) return false; + loops = std::clamp(loops, 1, 20); + + constexpr int kSampleRate = 48000; + constexpr int kChannels = 2; + constexpr int kTableSize = 2048; + constexpr int kTableMask = kTableSize - 1; + + // Build base sine table once + static float sSinTable[kTableSize]; + static bool sSinInit = false; + if (!sSinInit) { + for (int i = 0; i < kTableSize; ++i) { + sSinTable[i] = static_cast( + std::sin((2.0 * 3.14159265358979323846 * i) / kTableSize)); + } + sSinInit = true; + } + + int singleLoopSamples = 0; + for (const auto& n : song.notes) { + singleLoopSamples += (n.durationMs * kSampleRate) / 1000; + } + int interLoopGapSamples = (loops > 1) ? (kSampleRate / 5) : 0; // 200ms gap + int tailSamples = (kSampleRate * 30) / 1000; // 30ms tail + int totalFrames = + singleLoopSamples * loops + interLoopGapSamples * (loops - 1) + tailSamples; + if (totalFrames <= 0 || totalFrames > kSampleRate * 180) { + totalFrames = std::clamp(totalFrames, kSampleRate / 10, kSampleRate * 180); + } + + std::vector pcm; + pcm.reserve(static_cast(totalFrames) * kChannels); + + float noteWave[kTableSize]; + int lastMidi = -999; + + for (int lp = 0; lp < loops; ++lp) { + for (const auto& n : song.notes) { + int slotFrames = (n.durationMs * kSampleRate) / 1000; + int toneFrames = std::min(slotFrames, (n.toneMs * kSampleRate) / 1000); + if (slotFrames <= 0) continue; + + if (n.freqHz <= 20.0 || n.midiNote < 0 || toneFrames <= 0 || + n.volume <= 0) { + pcm.insert(pcm.end(), static_cast(slotFrames) * kChannels, 0); + continue; + } + + // Rebuild band-limited mobile buzzer harmonic wavetable when pitch changes + if (n.midiNote != lastMidi) { + lastMidi = n.midiNote; + struct HarmSpec { + int mult; + float amp; + }; + static const HarmSpec kHarms[] = { + {1, 1.00f}, + {2, 0.32f}, + {3, 0.46f}, + {4, 0.12f}, + {5, 0.22f}, + {7, 0.10f}, + }; + std::fill(std::begin(noteWave), std::end(noteWave), 0.0f); + for (const auto& h : kHarms) { + if (n.freqHz * h.mult < 18000.0) { + for (int ti = 0; ti < kTableSize; ++ti) { + noteWave[ti] += + h.amp * sSinTable[(ti * h.mult) & kTableMask]; + } + } + } + float peak = 0.01f; + for (int ti = 0; ti < kTableSize; ++ti) { + peak = std::max(peak, std::fabs(noteWave[ti])); + } + float invPeak = 1.0f / peak; + for (int ti = 0; ti < kTableSize; ++ti) { + noteWave[ti] *= invPeak; + } + } + + uint32_t phase = 0; + uint32_t phaseStep = static_cast( + (n.freqHz * 4294967296.0) / static_cast(kSampleRate) + 0.5); + int attackFrames = std::min(toneFrames / 3, (kSampleRate * 2) / 1000); + int releaseFrames = std::min(toneFrames / 3, (kSampleRate * 3) / 1000); + float baseGain = + (static_cast(std::clamp(n.volume, 1, 15)) / 15.0f) * 24000.0f; + + for (int f = 0; f < toneFrames; ++f) { + float env = 1.0f; + if (attackFrames > 0 && f < attackFrames) { + env = static_cast(f) / static_cast(attackFrames); + } else if (releaseFrames > 0 && f >= toneFrames - releaseFrames) { + env = static_cast(toneFrames - 1 - f) / + static_cast(releaseFrames); + } else { + // Subtle natural piezo decay over long notes + float prog = static_cast(f) / static_cast(toneFrames); + env = 1.0f - 0.14f * prog; + } + float sampleF = + noteWave[(phase >> 21) & kTableMask] * baseGain * env; + int16_t s16 = static_cast( + std::clamp(sampleF, -32760.0f, 32760.0f)); + pcm.push_back(s16); + pcm.push_back(s16); + phase += phaseStep; + } + + int silenceFrames = slotFrames - toneFrames; + if (silenceFrames > 0) { + pcm.insert(pcm.end(), static_cast(silenceFrames) * kChannels, 0); + } + + if (pcm.size() >= static_cast(kSampleRate * 180 * kChannels)) { + break; + } + } + if (lp + 1 < loops && interLoopGapSamples > 0) { + pcm.insert(pcm.end(), + static_cast(interLoopGapSamples) * kChannels, 0); + } + } + + if (tailSamples > 0) { + pcm.insert(pcm.end(), static_cast(tailSamples) * kChannels, 0); + } + + std::ofstream ofs(wavOutPath, std::ios::binary | std::ios::trunc); + if (!ofs) return false; + + uint32_t dataBytes = static_cast(pcm.size() * sizeof(int16_t)); + uint32_t riffSize = 36 + dataBytes; + uint32_t fmtChunkSize = 16; + uint16_t audioFormat = 1; // PCM + uint16_t numChannels = kChannels; + uint32_t sampleRate = kSampleRate; + uint32_t byteRate = kSampleRate * kChannels * sizeof(int16_t); + uint16_t blockAlign = kChannels * sizeof(int16_t); + uint16_t bitsPerSample = 16; + + auto writeLe16 = [&](uint16_t v) { + char b[2] = { + static_cast(v & 0xFF), + static_cast((v >> 8) & 0xFF), + }; + ofs.write(b, 2); + }; + auto writeLe32 = [&](uint32_t v) { + char b[4] = { + static_cast(v & 0xFF), + static_cast((v >> 8) & 0xFF), + static_cast((v >> 16) & 0xFF), + static_cast((v >> 24) & 0xFF), + }; + ofs.write(b, 4); + }; + + ofs.write("RIFF", 4); + writeLe32(riffSize); + ofs.write("WAVE", 4); + ofs.write("fmt ", 4); + writeLe32(fmtChunkSize); + writeLe16(audioFormat); + writeLe16(numChannels); + writeLe32(sampleRate); + writeLe32(byteRate); + writeLe16(blockAlign); + writeLe16(bitsPerSample); + ofs.write("data", 4); + writeLe32(dataBytes); + ofs.write(reinterpret_cast(pcm.data()), + static_cast(dataBytes)); + ofs.flush(); + return ofs.good(); +} + +inline bool synthesizeMonotoneFileToWav(const std::string& inputPath, + const std::string& wavOutPath, + int loops = 1, + MonotoneSong* outSong = nullptr) { + MonotoneSong localSong; + MonotoneSong* target = outSong ? outSong : &localSong; + if (!parseMonotoneFile(inputPath, target)) { + return false; + } + return synthesizeMonotoneWav(*target, wavOutPath, loops); +} + +} // namespace bananarchy + +#endif // DWM_PLUGINS_MONOTONE_H diff --git a/src/dwm-plugins/music_plugin.cpp b/src/dwm-plugins/music_plugin.cpp index cc757ea..299cf32 100644 --- a/src/dwm-plugins/music_plugin.cpp +++ b/src/dwm-plugins/music_plugin.cpp @@ -1,4 +1,5 @@ #include "phone_data.h" +#include "monotone.h" #include "../sxmo-dwm/dwm_plugin.h" #include @@ -104,7 +105,8 @@ bool isStandardAudioExt(const std::string& ext) { } bool isSupportedAudioExt(const std::string& ext) { - return isStandardAudioExt(ext) || isTrackerFormatExt(ext); + return isStandardAudioExt(ext) || isTrackerFormatExt(ext) || + isMonotoneExt(ext); } std::string toUpperTag(const std::string& ext) { @@ -504,13 +506,27 @@ int runMusicApp(int argc, char** argv) { "amixer -c 0 cset \"name='RX3 MIX1 INP1'\" 3 >/dev/null 2>&1; " "wpctl set-mute @DEFAULT_AUDIO_SINK@ 0 >/dev/null 2>&1"); + std::string loadTarget = tr.path; + if (isMonotoneFile(tr.path)) { + loadTarget = "/tmp/xmusic_monotone.wav"; + MonotoneSong song; + if (!synthesizeMonotoneFileToWav(tr.path, loadTarget, 1, &song)) { + setBanner("Invalid melody file"); + isPlaying = false; + return; + } + if (!song.name.empty()) { + mediaTitle = song.name; + } + } + ensureMpvRunning(); if (tryConnectIpc()) { - sendIpcRaw("{\"command\":[\"loadfile\",\"" + jsonEscape(tr.path) + + sendIpcRaw("{\"command\":[\"loadfile\",\"" + jsonEscape(loadTarget) + "\",\"replace\"]}"); sendIpcRaw("{\"command\":[\"set_property\",\"pause\",false]}"); } else { - pendingLoadPath = tr.path; + pendingLoadPath = loadTarget; } }; @@ -808,7 +824,7 @@ int runMusicApp(int argc, char** argv) { size_t end = line.find('"', start); if (end != std::string::npos && end > start) { std::string t = line.substr(start, end - start); - if (!t.empty()) { + if (!t.empty() && t.find("xmusic_monotone") == std::string::npos) { mediaTitle = prettifyTrackName(t); } } diff --git a/src/dwm-plugins/ringtones_plugin.cpp b/src/dwm-plugins/ringtones_plugin.cpp index 1b2cde4..1fcbeb8 100644 --- a/src/dwm-plugins/ringtones_plugin.cpp +++ b/src/dwm-plugins/ringtones_plugin.cpp @@ -2,6 +2,7 @@ // Bananarchy Ringtone & Ringer Manager Plugin (ringtones.so / xringtones) #include "phone_data.h" +#include "monotone.h" #include "../sxmo-dwm/dwm_plugin.h" #include @@ -30,7 +31,8 @@ void handleSignal(int) { enum class TabId { Ringtones = 0, - Settings = 1, + NotifSound = 1, + Settings = 2, }; struct RingtoneEntry { @@ -39,6 +41,10 @@ struct RingtoneEntry { std::string formatTag; std::string sourceTag; off_t sizeBytes = 0; + bool isMonotone = false; + int bpm = 0; + int noteCount = 0; + int durationMs = 0; }; struct RingSettings { @@ -66,6 +72,9 @@ std::string getConfigDir() { } bool isAudioExtension(const std::string& name, std::string* extUpperOut = nullptr) { + if (isMonotoneFile(name, extUpperOut)) { + return true; + } size_t dot = name.rfind('.'); if (dot == std::string::npos || dot + 1 >= name.size()) return false; std::string ext = toLowerStr(name.substr(dot + 1)); @@ -97,6 +106,32 @@ std::string prettifyFilename(const std::string& filename) { return trimStr(stem); } +RingtoneEntry makeRingtoneEntry(const std::string& fullPath, + const std::string& name, + const std::string& extTag, + const std::string& sourceTag, + off_t sizeBytes) { + RingtoneEntry e; + e.path = fullPath; + e.displayName = prettifyFilename(name); + e.formatTag = extTag; + e.sourceTag = sourceTag; + e.sizeBytes = sizeBytes; + if (isMonotoneFile(name)) { + e.isMonotone = true; + MonotoneSong song; + if (parseMonotoneFile(fullPath, &song)) { + e.bpm = song.bpm; + e.noteCount = song.pitchedNoteCount; + e.durationMs = song.totalDurationMs; + if (!song.formatTag.empty()) { + e.formatTag = song.formatTag; + } + } + } + return e; +} + void scanDirectoryForRingtones(const std::string& dirPath, const std::string& sourceTag, std::vector& out) { @@ -116,13 +151,8 @@ void scanDirectoryForRingtones(const std::string& dirPath, std::string fullPath = dirPath + "/" + name; struct stat st {}; if (::stat(fullPath.c_str(), &st) != 0 || !S_ISREG(st.st_mode)) continue; - RingtoneEntry e; - e.path = fullPath; - e.displayName = prettifyFilename(name); - e.formatTag = extTag; - e.sourceTag = sourceTag; - e.sizeBytes = st.st_size; - out.push_back(e); + out.push_back(makeRingtoneEntry(fullPath, name, extTag, sourceTag, + st.st_size)); } } @@ -140,6 +170,15 @@ std::vector discoverRingtones() { defEntry.sizeBytes = st.st_size; list.push_back(defEntry); } + if (::stat("/usr/share/sxmo/notify.ogg", &st) == 0 && S_ISREG(st.st_mode)) { + RingtoneEntry notifEntry; + notifEntry.path = "/usr/share/sxmo/notify.ogg"; + notifEntry.displayName = "Sxmo Default Notify"; + notifEntry.formatTag = "OGG"; + notifEntry.sourceTag = "System"; + notifEntry.sizeBytes = st.st_size; + list.push_back(notifEntry); + } std::string home = getHomeDirPath(); scanDirectoryForRingtones(home + "/Ringtones", "User", list); @@ -180,6 +219,75 @@ bool saveActiveRingtonePath(const std::string& path) { return true; } +std::string loadActiveNotifSoundPath() { + std::string cfgDir = getConfigDir(); + { + std::ifstream ifs(cfgDir + "/notif_sound"); + if (ifs) { + std::string line; + if (std::getline(ifs, line)) { + line = trimStr(line); + if (line == "NONE" || line == "none") { + return "NONE"; + } + struct stat st {}; + if (!line.empty() && ::stat(line.c_str(), &st) == 0) { + return line; + } + } + } + } + { + std::ifstream ifs(cfgDir + "/ringsettings"); + std::string line; + while (std::getline(ifs, line)) { + line = trimStr(line); + if (line.empty() || line[0] == '#') continue; + auto eq = line.find('='); + if (eq == std::string::npos) continue; + std::string k = trimStr(line.substr(0, eq)); + std::string v = trimStr(line.substr(eq + 1)); + if (v.size() >= 2 && ((v.front() == '"' && v.back() == '"') || + (v.front() == '\'' && v.back() == '\''))) { + v = v.substr(1, v.size() - 2); + } + if (k == "SXMO_TEXTSOUND") { + if (v == "NONE" || v == "none") return "NONE"; + struct stat st {}; + if (!v.empty() && ::stat(v.c_str(), &st) == 0) { + return v; + } + } + } + } + struct stat stDef {}; + if (::stat("/usr/share/sxmo/ringtones/Soft_Bell.wav", &stDef) == 0) { + return "/usr/share/sxmo/ringtones/Soft_Bell.wav"; + } + const char* envTxt = std::getenv("SXMO_TEXTSOUND"); + if (envTxt && *envTxt && ::stat(envTxt, &stDef) == 0) { + return envTxt; + } + if (::stat("/usr/share/sxmo/notify.ogg", &stDef) == 0) { + return "/usr/share/sxmo/notify.ogg"; + } + return "/usr/share/sxmo/ringtones/Banana_Chime.wav"; +} + +void saveRingSettings(const RingSettings& s); + +bool saveActiveNotifSoundPath(const std::string& path, + const RingSettings& curSettings) { + std::string cfgDir = getConfigDir(); + ::mkdir(cfgDir.c_str(), 0755); + std::ofstream ofs(cfgDir + "/notif_sound", std::ios::trunc); + if (!ofs) return false; + ofs << path << "\n"; + ofs.close(); + saveRingSettings(curSettings); + return true; +} + RingSettings loadRingSettings() { RingSettings s; std::string cfgDir = getConfigDir(); @@ -237,12 +345,14 @@ void saveRingSettings(const RingSettings& s) { writeIntFile(noVibPath, 1); } + std::string notifPath = loadActiveNotifSoundPath(); std::ofstream ofs(cfgDir + "/ringsettings", std::ios::trunc); if (ofs) { ofs << "SXMO_RINGTIME=" << s.ringTimeSec << "\n"; ofs << "SXMO_RINGNUMBER=" << s.ringLoops << "\n"; ofs << "SXMO_VIBRATE_STRENGTH=" << s.vibrateStrength << "\n"; ofs << "SXMO_RINGVOL=" << std::clamp(s.ringVol, 0, 100) << "\n"; + ofs << "SXMO_TEXTSOUND=\"" << notifPath << "\"\n"; } runAsyncCmd("sxmo_hook_statusbar.sh audio >/dev/null 2>&1"); } @@ -253,9 +363,17 @@ int runRingtonesApp(int argc, char** argv) { XSetLocaleModifiers(""); bool isPreload = false; + bool initNotifTab = false; + std::string initTarget; for (int i = 1; i < argc; ++i) { - if (argv[i] && std::strcmp(argv[i], "--preload") == 0) { + if (!argv[i]) continue; + if (std::strcmp(argv[i], "--preload") == 0) { isPreload = true; + } else if (std::strcmp(argv[i], "--notif") == 0 || + std::strcmp(argv[i], "notif") == 0) { + initNotifTab = true; + } else if (argv[i][0] != '-' && initTarget.empty()) { + initTarget = argv[i]; } } @@ -264,7 +382,14 @@ int runRingtonesApp(int argc, char** argv) { if (isPluginDaemonAlive("ringtones")) { if (!isPreload) { - sendPluginCommand("ringtones", "OPEN"); + if (initNotifTab && !initTarget.empty()) { + sendPluginCommand("ringtones", "OPEN --notif " + initTarget); + } else if (initNotifTab) { + sendPluginCommand("ringtones", "OPEN --notif"); + } else { + sendPluginCommand( + "ringtones", initTarget.empty() ? "OPEN" : ("OPEN " + initTarget)); + } } return 0; } @@ -301,10 +426,14 @@ int runRingtonesApp(int argc, char** argv) { TabId activeTab = TabId::Ringtones; std::vector tones; + std::vector notifTones; std::string activePath; + std::string activeNotifPath; RingSettings settings; int selIdx = 0; + int notifSelIdx = 0; int settingsRow = 0; + constexpr int kTotalSettingsRows = 7; pid_t previewPid = -1; std::string previewPath; @@ -345,18 +474,34 @@ int runRingtonesApp(int argc, char** argv) { return false; }; - auto togglePreview = [&](const std::string& path) { + auto togglePreview = [&](const std::string& path, bool singleShot = false) { checkPreviewAlive(); + if (path.empty() || path == "NONE") { + stopPreview(); + setBanner("Notification sound is muted (None)"); + return; + } if (previewPid > 0 && previewPath == path) { stopPreview(); setBanner("Preview stopped"); return; } stopPreview(); + + std::string playTarget = path; + if (isMonotoneFile(path)) { + playTarget = "/tmp/xringtones_preview.wav"; + if (!synthesizeMonotoneFileToWav(path, playTarget, 1)) { + setBanner("Invalid melody ringtone"); + return; + } + } + settings = loadRingSettings(); int rvol = std::clamp(settings.ringVol, 0, 100); int rx3 = (rvol <= 0) ? 0 : (56 + (rvol * 32 + 50) / 100); std::string volArg = "--volume=100"; + std::string loopArg = singleShot ? "--loop=no" : "--loop=2"; runAsyncCmd("amixer -c 0 cset \"name='EAR_S'\" 0 >/dev/null 2>&1; " "amixer -c 0 cset \"name='RX1 MIX1 INP1'\" 0 >/dev/null 2>&1; " "amixer -c 0 cset \"name='PRI_MI2S_RX Audio Mixer MultiMedia1'\" 1 >/dev/null 2>&1; " @@ -384,12 +529,21 @@ int runRingtonesApp(int argc, char** argv) { ::dup2(devNull, STDERR_FILENO); if (devNull > 2) ::close(devNull); } - ::execlp("mpv", "mpv", "--no-config", "--no-terminal", - "--no-resume-playback", "--quiet", "--vo=null", - "--no-video", "--ao=pipewire,pulse,alsa", - "--audio-channels=stereo", "--audio-samplerate=48000", - "--volume-max=150", volArg.c_str(), - "--loop=2", path.c_str(), nullptr); + if (singleShot) { + ::execlp("mpv", "mpv", "--no-config", "--no-terminal", + "--no-resume-playback", "--quiet", "--vo=null", + "--no-video", "--ao=pipewire,pulse,alsa", + "--audio-channels=stereo", "--audio-samplerate=48000", + "--volume-max=150", volArg.c_str(), + "--end=6", loopArg.c_str(), playTarget.c_str(), nullptr); + } else { + ::execlp("mpv", "mpv", "--no-config", "--no-terminal", + "--no-resume-playback", "--quiet", "--vo=null", + "--no-video", "--ao=pipewire,pulse,alsa", + "--audio-channels=stereo", "--audio-samplerate=48000", + "--volume-max=150", volArg.c_str(), + loopArg.c_str(), playTarget.c_str(), nullptr); + } ::_exit(127); } else if (pid > 0) { previewPid = pid; @@ -398,13 +552,40 @@ int runRingtonesApp(int argc, char** argv) { } }; + auto rebuildNotifTones = [&]() { + notifTones.clear(); + RingtoneEntry noneEntry; + noneEntry.path = "NONE"; + noneEntry.displayName = "None (Mute Sound)"; + noneEntry.formatTag = "OFF"; + noneEntry.sourceTag = "Silent"; + notifTones.push_back(noneEntry); + for (const auto& t : tones) { + notifTones.push_back(t); + } + }; + auto refreshData = [&]() { tones = discoverRingtones(); + rebuildNotifTones(); activePath = loadActiveRingtonePath(); + activeNotifPath = loadActiveNotifSoundPath(); settings = loadRingSettings(); if (selIdx >= static_cast(tones.size())) { selIdx = std::max(0, static_cast(tones.size()) - 1); } + if (notifSelIdx >= static_cast(notifTones.size())) { + notifSelIdx = std::max(0, static_cast(notifTones.size()) - 1); + } + }; + + auto formatToneShortName = [&](const std::string& path) -> std::string { + if (path.empty() || path == "NONE") return "None (Silent)"; + for (const auto& t : tones) { + if (t.path == path) return t.displayName; + } + size_t sl = path.rfind('/'); + return prettifyFilename(sl == std::string::npos ? path : path.substr(sl + 1)); }; auto drawPango = [&](PangoLayout* layout, XftColor* color, int x, int y, @@ -427,32 +608,31 @@ int runRingtonesApp(int argc, char** argv) { XSetForeground(dpy, gc, pt.spec.bgMain); XFillRectangle(dpy, pix, gc, 0, 0, kWinWidth, kWinHeight); - // Top tab header (0..26) + // Top 3-tab header (0..26) XSetForeground(dpy, gc, pt.spec.bgHeader); XFillRectangle(dpy, pix, gc, 0, 0, kWinWidth, 26); - const char* tabNames[2] = {"1:Ringtones", "2:Settings"}; - for (int i = 0; i < 2; ++i) { - int tx = i * 120; + const char* tabNames[3] = {"1:Ringtone", "2:Notif/SMS", "3:Settings"}; + for (int i = 0; i < 3; ++i) { + int tx = i * 80; bool isAct = (static_cast(activeTab) == i); if (isAct) { XSetForeground(dpy, gc, pt.spec.selBg); - XFillRectangle(dpy, pix, gc, tx, 0, 120, 26); + XFillRectangle(dpy, pix, gc, tx, 0, 80, 26); XSetForeground(dpy, gc, pt.spec.accent); - XFillRectangle(dpy, pix, gc, tx, 24, 120, 2); + XFillRectangle(dpy, pix, gc, tx, 24, 80, 2); } - drawPango(layoutSmall, isAct ? &colWhite : &colMuted, tx + 4, 0, 24, - tabNames[i], 112, 1); + drawPango(layoutSmall, isAct ? &colWhite : &colMuted, tx + 2, 0, 24, + tabNames[i], 76, 1); } if (activeTab == TabId::Ringtones) { - // Active ringtone summary banner (y=28..50) + // Active call ringtone summary banner (y=28..50) XSetForeground(dpy, gc, pt.spec.bgAltEven); XFillRectangle(dpy, pix, gc, 4, 28, kWinWidth - 8, 22); - std::string actName = prettifyFilename( - activePath.substr(activePath.rfind('/') + 1)); + std::string actName = formatToneShortName(activePath); drawPango(layoutSmall, &colGreen, 8, 28, 22, - std::string(kIconBell) + " Active: " + actName, + std::string(kIconBell) + " Ring: " + actName, kWinWidth - 16); // List area (y=52..246, 5 rows of 38px) @@ -470,36 +650,52 @@ int runRingtonesApp(int argc, char** argv) { const auto& e = tones[idx]; int ry = 54 + i * 38; bool isSel = (idx == selIdx); - bool isActive = (e.path == activePath); + bool isActiveRing = (e.path == activePath); + bool isActiveNotif = (e.path == activeNotifPath); bool isPlaying = (previewPid > 0 && previewPath == e.path); XSetForeground(dpy, gc, isSel ? pt.spec.selBg : (i % 2 == 0 ? pt.spec.bgAltEven : pt.spec.bgAltOdd)); XFillRectangle(dpy, pix, gc, 4, ry, kWinWidth - 8, 36); - if (isActive) { + if (isActiveRing) { XSetForeground(dpy, gc, pt.spec.accent); XFillRectangle(dpy, pix, gc, 4, ry, 3, 36); + } else if (isActiveNotif) { + XSetForeground(dpy, gc, pt.spec.info); + XFillRectangle(dpy, pix, gc, 4, ry, 3, 36); } drawPango(layoutMain, isSel ? &colWhite : &colLight, 10, ry + 1, 19, - e.displayName, 152); + e.displayName, 148); std::string badge; XftColor* badgeCol = &colMuted; if (isPlaying) { badge = "[PLAYING]"; badgeCol = &colYellow; - } else if (isActive) { - badge = "[ACTIVE]"; + } else if (isActiveRing && isActiveNotif) { + badge = "[RING+SMS]"; badgeCol = &colGreen; + } else if (isActiveRing) { + badge = "[RING]"; + badgeCol = &colGreen; + } else if (isActiveNotif) { + badge = "[NOTIF]"; + badgeCol = &colBlue; } if (!badge.empty()) { - drawPango(layoutSmall, badgeCol, 162, ry + 2, 18, badge, 70, 2); + drawPango(layoutSmall, badgeCol, 158, ry + 2, 18, badge, 74, 2); } - std::string sub = e.formatTag + " | " + formatFileSize(e.sizeBytes) + - " | " + e.sourceTag + " ([*] Preview)"; + std::string sub; + if (e.isMonotone && e.bpm > 0) { + sub = e.formatTag + " " + std::to_string(e.bpm) + "bpm | " + + std::to_string(e.noteCount) + "n | [*]Play [#]SMS"; + } else { + sub = e.formatTag + " | " + formatFileSize(e.sizeBytes) + + " | " + e.sourceTag + " ([*]Play [#]SMS)"; + } drawPango(layoutSmall, isSel ? &colLight : &colMuted, 10, ry + 19, 16, sub, kWinWidth - 20); } @@ -509,8 +705,84 @@ int runRingtonesApp(int argc, char** argv) { previewPid > 0 && previewPath == tones[selIdx].path); drawSoftkeyBar(curPlaying ? "Stop" : "Play [*]", "Set Ring", "Close"); + } else if (activeTab == TabId::NotifSound) { + // Active notification/SMS sound summary banner (y=28..50) + XSetForeground(dpy, gc, pt.spec.bgAltEven); + XFillRectangle(dpy, pix, gc, 4, 28, kWinWidth - 8, 22); + std::string actNotifName = formatToneShortName(activeNotifPath); + drawPango(layoutSmall, &colBlue, 8, 28, 22, + std::string(kIconSms) + " Notif/SMS: " + actNotifName, + kWinWidth - 16); + + // List area (y=52..246, 5 rows of 38px) + constexpr int kVisibleRows = 5; + int total = static_cast(notifTones.size()); + int startIdx = 0; + if (total > kVisibleRows) { + startIdx = std::clamp(notifSelIdx - kVisibleRows / 2, 0, + total - kVisibleRows); + } + + for (int i = 0; i < kVisibleRows; ++i) { + int idx = startIdx + i; + if (idx >= total) break; + const auto& e = notifTones[idx]; + int ry = 54 + i * 38; + bool isSel = (idx == notifSelIdx); + bool isActiveNotif = (e.path == activeNotifPath); + bool isActiveRing = (e.path != "NONE" && e.path == activePath); + bool isPlaying = (previewPid > 0 && previewPath == e.path); + + XSetForeground(dpy, gc, isSel ? pt.spec.selBg + : (i % 2 == 0 ? pt.spec.bgAltEven + : pt.spec.bgAltOdd)); + XFillRectangle(dpy, pix, gc, 4, ry, kWinWidth - 8, 36); + if (isActiveNotif) { + XSetForeground(dpy, gc, pt.spec.accent); + XFillRectangle(dpy, pix, gc, 4, ry, 3, 36); + } + + drawPango(layoutMain, isSel ? &colWhite : &colLight, 10, ry + 1, 19, + e.displayName, 148); + + std::string badge; + XftColor* badgeCol = &colMuted; + if (isPlaying) { + badge = "[PLAYING]"; + badgeCol = &colYellow; + } else if (isActiveNotif) { + badge = "[ACTIVE]"; + badgeCol = &colGreen; + } else if (isActiveRing) { + badge = "[RING]"; + badgeCol = &colBlue; + } + if (!badge.empty()) { + drawPango(layoutSmall, badgeCol, 158, ry + 2, 18, badge, 74, 2); + } + + std::string sub; + if (e.path == "NONE") { + sub = "Silent notifications & SMS (vibration only)"; + } else if (e.isMonotone && e.bpm > 0) { + sub = e.formatTag + " " + std::to_string(e.bpm) + "bpm | " + + std::to_string(e.noteCount) + "n | " + e.sourceTag + + " ([*] Play)"; + } else { + sub = e.formatTag + " | " + formatFileSize(e.sizeBytes) + + " | " + e.sourceTag + " ([*] Preview)"; + } + drawPango(layoutSmall, isSel ? &colLight : &colMuted, 10, ry + 19, 16, + sub, kWinWidth - 20); + } + + bool curPlaying = (!notifTones.empty() && notifSelIdx >= 0 && + notifSelIdx < static_cast(notifTones.size()) && + previewPid > 0 && + previewPath == notifTones[notifSelIdx].path); + drawSoftkeyBar(curPlaying ? "Stop" : "Play [*]", "Set Notif", "Close"); } else { - // Tab 2: Settings + // Tab 3: Settings (scrollable 6 visible rows of 35px out of 7) const char* modeLabels[4] = { "Ring + Vibrate", "Ring Only", @@ -519,23 +791,31 @@ int runRingtonesApp(int argc, char** argv) { }; const char* vibLabels[3] = {"1 (Light)", "2 (Medium)", "3 (Strong)"}; int vIdx = std::clamp(settings.vibrateStrength, 1, 3) - 1; - std::string rows[6][2] = { + std::string rows[kTotalSettingsRows][2] = { {"Ringer Mode", "< " + std::string(modeLabels[settings.ringerMode % 4]) + " >"}, - {"Ring Volume", + {"Notif / SMS Sound", + "< " + formatToneShortName(activeNotifPath) + " >"}, + {"Call Ringtone", + "< " + formatToneShortName(activePath) + " >"}, + {"Ring & Alert Volume", "< " + std::to_string(settings.ringVol) + "% >"}, - {"Ring Duration", + {"Call Ring Duration", "< " + std::to_string(settings.ringTimeSec) + " sec >"}, - {"Ring Loop Count", + {"Call Ring Loop Count", "< " + std::to_string(settings.ringLoops) + " loops >"}, - {"Vibrate Strength", + {"Vibrate Strength (OK: Test)", "< Level " + std::string(vibLabels[vIdx]) + " >"}, - {"Test Vibration", "Press OK to vibrate"}, }; - for (int i = 0; i < 6; ++i) { + constexpr int kVisibleSettings = 6; + int startRow = std::clamp(settingsRow - kVisibleSettings / 2, 0, + kTotalSettingsRows - kVisibleSettings); + for (int i = 0; i < kVisibleSettings; ++i) { + int rIdx = startRow + i; + if (rIdx >= kTotalSettingsRows) break; int ry = 30 + i * 35; - bool isSel = (settingsRow == i); + bool isSel = (settingsRow == rIdx); XSetForeground(dpy, gc, isSel ? pt.spec.selBg : pt.spec.bgAltEven); XFillRectangle(dpy, pix, gc, 4, ry, kWinWidth - 8, 33); if (isSel) { @@ -543,11 +823,14 @@ int runRingtonesApp(int argc, char** argv) { XDrawRectangle(dpy, pix, gc, 4, ry, kWinWidth - 9, 32); } drawPango(layoutSmall, isSel ? &colWhite : &colMuted, 10, ry + 1, 15, - rows[i][0], kWinWidth - 20); + rows[rIdx][0], kWinWidth - 20); drawPango(layoutMain, isSel ? &colYellow : &colBlue, 10, ry + 15, 17, - rows[i][1], kWinWidth - 20); + rows[rIdx][1], kWinWidth - 20); } - drawSoftkeyBar("Change", "Select", "Close"); + std::string midLbl = "Select"; + if (settingsRow == 1 || settingsRow == 2) midLbl = "Browse"; + else if (settingsRow == 6) midLbl = "Test Vib"; + drawSoftkeyBar("Change", midLbl, "Close"); } if (!statusBanner.empty()) { @@ -564,16 +847,63 @@ int runRingtonesApp(int argc, char** argv) { XFlush(dpy); }; - auto showWindow = [&]() { + auto showWindow = [&](const std::string& openTarget = "", + bool openNotif = false) { writeIntFile(activePidPath, static_cast(::getpid())); closeOtherPlugins("ringtones"); refreshData(); + if (openNotif) { + activeTab = TabId::NotifSound; + } + std::string selectPath = activePath; + std::string selectNotifPath = activeNotifPath; + if (!openTarget.empty()) { + char resolved[4096]; + std::string target = openTarget; + if (::realpath(openTarget.c_str(), resolved) != nullptr) { + target = resolved; + } + struct stat st {}; + std::string extTag; + if (::stat(target.c_str(), &st) == 0 && S_ISREG(st.st_mode) && + isAudioExtension(target, &extTag)) { + bool found = false; + for (const auto& t : tones) { + if (t.path == target) { + found = true; + break; + } + } + if (!found) { + size_t sl = target.rfind('/'); + std::string fname = + (sl == std::string::npos) ? target : target.substr(sl + 1); + tones.insert(tones.begin(), + makeRingtoneEntry(target, fname, extTag, "File", + st.st_size)); + rebuildNotifTones(); + } + if (openNotif) { + selectNotifPath = target; + activeTab = TabId::NotifSound; + } else { + selectPath = target; + activeTab = TabId::Ringtones; + } + } + } for (size_t i = 0; i < tones.size(); ++i) { - if (tones[i].path == activePath) { + if (tones[i].path == selectPath) { selIdx = static_cast(i); break; } } + for (size_t i = 0; i < notifTones.size(); ++i) { + if (notifTones[i].path == selectNotifPath) { + notifSelIdx = static_cast(i); + break; + } + } if (!visible) { visible = true; XMapRaised(dpy, win); @@ -618,6 +948,36 @@ int runRingtonesApp(int argc, char** argv) { saveRingSettings(settings); setBanner("Ringer mode updated"); } else if (settingsRow == 1) { + if (notifTones.empty()) return; + int curIdx = 0; + for (size_t i = 0; i < notifTones.size(); ++i) { + if (notifTones[i].path == activeNotifPath) { + curIdx = static_cast(i); + break; + } + } + curIdx = (curIdx + static_cast(notifTones.size()) + delta) % + static_cast(notifTones.size()); + notifSelIdx = curIdx; + activeNotifPath = notifTones[curIdx].path; + saveActiveNotifSoundPath(activeNotifPath, settings); + setBanner("Notif/SMS: " + notifTones[curIdx].displayName); + } else if (settingsRow == 2) { + if (tones.empty()) return; + int curIdx = 0; + for (size_t i = 0; i < tones.size(); ++i) { + if (tones[i].path == activePath) { + curIdx = static_cast(i); + break; + } + } + curIdx = (curIdx + static_cast(tones.size()) + delta) % + static_cast(tones.size()); + selIdx = curIdx; + activePath = tones[curIdx].path; + saveActiveRingtonePath(activePath); + setBanner("Ringtone: " + tones[curIdx].displayName); + } else if (settingsRow == 3) { settings.ringVol = std::clamp(settings.ringVol + delta * 5, 0, 100); saveRingSettings(settings); if (previewPid > 0) { @@ -627,7 +987,7 @@ int runRingtonesApp(int argc, char** argv) { "wpctl set-volume @DEFAULT_AUDIO_SINK@ 100% >/dev/null 2>&1"); } setBanner("Ring volume: " + std::to_string(settings.ringVol) + "%"); - } else if (settingsRow == 2) { + } else if (settingsRow == 4) { int curIdx = 2; for (int i = 0; i < kNumRingTimeSteps; ++i) { if (kRingTimeSteps[i] == settings.ringTimeSec) { @@ -638,7 +998,7 @@ int runRingtonesApp(int argc, char** argv) { curIdx = (curIdx + kNumRingTimeSteps + delta) % kNumRingTimeSteps; settings.ringTimeSec = kRingTimeSteps[curIdx]; saveRingSettings(settings); - } else if (settingsRow == 3) { + } else if (settingsRow == 5) { int curIdx = 2; for (int i = 0; i < kNumRingLoopSteps; ++i) { if (kRingLoopSteps[i] == settings.ringLoops) { @@ -649,23 +1009,18 @@ int runRingtonesApp(int argc, char** argv) { curIdx = (curIdx + kNumRingLoopSteps + delta) % kNumRingLoopSteps; settings.ringLoops = kRingLoopSteps[curIdx]; saveRingSettings(settings); - } else if (settingsRow == 4) { + } else if (settingsRow == 6) { settings.vibrateStrength = ((settings.vibrateStrength - 1 + 3 + delta) % 3) + 1; saveRingSettings(settings); runAsyncCmd("SXMO_VIBRATE_FORCE=1 sxmo_vibrate 450 " + std::to_string(settings.vibrateStrength) + " >/dev/null 2>&1"); setBanner("Vibration level: " + std::to_string(settings.vibrateStrength)); - } else if (settingsRow == 5) { - runAsyncCmd("SXMO_VIBRATE_FORCE=1 sxmo_vibrate 800 " + - std::to_string(settings.vibrateStrength) + " >/dev/null 2>&1"); - setBanner("Testing vibration (Level " + - std::to_string(settings.vibrateStrength) + ")..."); } }; if (!isPreload) { - showWindow(); + showWindow(initTarget, initNotifTab); } int xfd = ConnectionNumber(dpy); @@ -729,45 +1084,77 @@ int runRingtonesApp(int argc, char** argv) { render(); continue; } else if (dch == '2') { + activeTab = TabId::NotifSound; + render(); + continue; + } else if (dch == '3') { activeTab = TabId::Settings; render(); continue; - } else if (dch == '*' && activeTab == TabId::Ringtones && + } else if (dch == '*') { + if (activeTab == TabId::Ringtones && !tones.empty()) { + togglePreview(tones[selIdx].path, false); + } else if (activeTab == TabId::NotifSound && !notifTones.empty()) { + togglePreview(notifTones[notifSelIdx].path, true); + } else if (activeTab == TabId::Settings && settingsRow == 1) { + togglePreview(activeNotifPath, true); + } else if (activeTab == TabId::Settings && settingsRow == 2) { + togglePreview(activePath, false); + } + render(); + continue; + } else if (dch == '#' && activeTab == TabId::Ringtones && !tones.empty()) { - togglePreview(tones[selIdx].path); + activeNotifPath = tones[selIdx].path; + saveActiveNotifSoundPath(activeNotifPath, settings); + for (size_t i = 0; i < notifTones.size(); ++i) { + if (notifTones[i].path == activeNotifPath) { + notifSelIdx = static_cast(i); + break; + } + } + setBanner("Notif/SMS set: " + tones[selIdx].displayName); render(); continue; } if (sym == XK_Left || sym == XK_KP_Left) { - if (activeTab == TabId::Settings && settingsRow < 5) { + if (activeTab == TabId::Settings) { adjustSettingRow(-1); } else { - activeTab = (activeTab == TabId::Ringtones) ? TabId::Settings - : TabId::Ringtones; + int nextTab = (static_cast(activeTab) + 2) % 3; + activeTab = static_cast(nextTab); } render(); } else if (sym == XK_Right || sym == XK_KP_Right) { - if (activeTab == TabId::Settings && settingsRow < 5) { + if (activeTab == TabId::Settings) { adjustSettingRow(1); } else { - activeTab = (activeTab == TabId::Ringtones) ? TabId::Settings - : TabId::Ringtones; + int nextTab = (static_cast(activeTab) + 1) % 3; + activeTab = static_cast(nextTab); } render(); } else if (sym == XK_Up || sym == XK_KP_Up) { if (activeTab == TabId::Ringtones && !tones.empty()) { selIdx = (selIdx + static_cast(tones.size()) - 1) % static_cast(tones.size()); + } else if (activeTab == TabId::NotifSound && !notifTones.empty()) { + notifSelIdx = + (notifSelIdx + static_cast(notifTones.size()) - 1) % + static_cast(notifTones.size()); } else if (activeTab == TabId::Settings) { - settingsRow = (settingsRow + 5) % 6; + settingsRow = + (settingsRow + kTotalSettingsRows - 1) % kTotalSettingsRows; } render(); } else if (sym == XK_Down || sym == XK_KP_Down) { if (activeTab == TabId::Ringtones && !tones.empty()) { selIdx = (selIdx + 1) % static_cast(tones.size()); + } else if (activeTab == TabId::NotifSound && !notifTones.empty()) { + notifSelIdx = + (notifSelIdx + 1) % static_cast(notifTones.size()); } else if (activeTab == TabId::Settings) { - settingsRow = (settingsRow + 1) % 6; + settingsRow = (settingsRow + 1) % kTotalSettingsRows; } render(); } else if (sym == XK_Return || sym == XK_KP_Enter) { @@ -775,8 +1162,24 @@ int runRingtonesApp(int argc, char** argv) { activePath = tones[selIdx].path; saveActiveRingtonePath(activePath); setBanner("Ringtone set: " + tones[selIdx].displayName); + } else if (activeTab == TabId::NotifSound && !notifTones.empty()) { + activeNotifPath = notifTones[notifSelIdx].path; + saveActiveNotifSoundPath(activeNotifPath, settings); + setBanner("Notif/SMS set: " + notifTones[notifSelIdx].displayName); } else if (activeTab == TabId::Settings) { - adjustSettingRow(1); + if (settingsRow == 1) { + activeTab = TabId::NotifSound; + } else if (settingsRow == 2) { + activeTab = TabId::Ringtones; + } else if (settingsRow == 6) { + runAsyncCmd("SXMO_VIBRATE_FORCE=1 sxmo_vibrate 800 " + + std::to_string(settings.vibrateStrength) + + " >/dev/null 2>&1"); + setBanner("Testing vibration (Level " + + std::to_string(settings.vibrateStrength) + ")..."); + } else { + adjustSettingRow(1); + } } render(); } @@ -800,7 +1203,9 @@ int runRingtonesApp(int argc, char** argv) { sendPluginCommand("xdrawer", "TOGGLE"); } else if (pend == 1) { if (activeTab == TabId::Ringtones && !tones.empty()) { - togglePreview(tones[selIdx].path); + togglePreview(tones[selIdx].path, false); + } else if (activeTab == TabId::NotifSound && !notifTones.empty()) { + togglePreview(notifTones[notifSelIdx].path, true); } else if (activeTab == TabId::Settings) { adjustSettingRow(1); } @@ -843,8 +1248,16 @@ int runRingtonesApp(int argc, char** argv) { } else if (cmd == "TOGGLE") { if (visible) hideWindow(); else showWindow(); - } else if (cmd.rfind("OPEN", 0) == 0) { + } else if (cmd == "OPEN") { showWindow(); + } else if (cmd == "OPEN --notif" || cmd == "OPEN notif") { + showWindow("", true); + } else if (cmd.rfind("OPEN --notif ", 0) == 0) { + showWindow(trimStr(cmd.substr(13)), true); + } else if (cmd.rfind("OPEN notif ", 0) == 0) { + showWindow(trimStr(cmd.substr(11)), true); + } else if (cmd.rfind("OPEN ", 0) == 0) { + showWindow(trimStr(cmd.substr(5)), false); } } } diff --git a/src/dwm-plugins/tox_plugin.cpp b/src/dwm-plugins/tox_plugin.cpp index e1f00cc..7360d21 100644 --- a/src/dwm-plugins/tox_plugin.cpp +++ b/src/dwm-plugins/tox_plugin.cpp @@ -230,7 +230,8 @@ void onFriendRequest(Tox*, const Tox_Public_Key publicKey, req.pubKeyHex = hex; req.message.assign(reinterpret_cast(message), length); ctx->pendingReqs.push_back(std::move(req)); - neoui_vibrate(70); + bananarchy::runAsyncCmd("PATH=\"$HOME/.config/sxmo/hooks:/usr/share/sxmo/default_hooks:$PATH\" " + "sxmo_hook_notification.sh >/dev/null 2>&1"); ctx->uiDirty = true; } @@ -241,7 +242,8 @@ void onFriendMessage(Tox* tox, Tox_Friend_Number friendNum, std::string pkHex = getFriendPubKeyHex(tox, friendNum); std::string txt(reinterpret_cast(message), length); appendFriendChat(pkHex, false, txt); - neoui_vibrate(60); + bananarchy::runAsyncCmd("PATH=\"$HOME/.config/sxmo/hooks:/usr/share/sxmo/default_hooks:$PATH\" " + "sxmo_hook_notification.sh >/dev/null 2>&1"); ctx->uiDirty = true; } diff --git a/src/sxmo-dmenu/dmenu.c b/src/sxmo-dmenu/dmenu.c index c71141b..b71379f 100644 --- a/src/sxmo-dmenu/dmenu.c +++ b/src/sxmo-dmenu/dmenu.c @@ -2643,6 +2643,8 @@ open_builtin_menu(const char *menu_name, int keep_idx) snprintf(label, sizeof(label), "%s Clear All Notifications", ICON_CLS); add_menu_item(label, "@toggle:notif_clear_all", 0); populate_notifications_menu(); + snprintf(label, sizeof(label), "%s Notification Sound", ICON_BEL); + add_menu_item(label, "@plugin:ringtones:notif", 0); snprintf(label, sizeof(label), "%s System Menu", ICON_MNU); add_menu_item(label, "@menu:sys", 1); snprintf(label, sizeof(label), "%s Close Menu", ICON_CLS); diff --git a/src/xdrawer/xdrawer.cpp b/src/xdrawer/xdrawer.cpp index e3bdce0..d2e11d6 100644 --- a/src/xdrawer/xdrawer.cpp +++ b/src/xdrawer/xdrawer.cpp @@ -551,6 +551,7 @@ class PhoneController { int ringLoops = 10; int vibStrength = 2; int ringVol = 100; + std::string textSound; { std::ifstream ifs(path); std::string line; @@ -558,11 +559,13 @@ class PhoneController { auto eq = line.find('='); if (eq == std::string::npos) continue; std::string k = line.substr(0, eq); - int val = std::atoi(line.substr(eq + 1).c_str()); + std::string rawVal = line.substr(eq + 1); + int val = std::atoi(rawVal.c_str()); if (k == "SXMO_RINGTIME" && val >= 5 && val <= 120) ringTime = val; else if (k == "SXMO_RINGNUMBER" && val >= 1 && val <= 100) ringLoops = val; else if (k == "SXMO_VIBRATE_STRENGTH" && val >= 1 && val <= 3) vibStrength = val; else if (k == "SXMO_RINGVOL" && val >= 0 && val <= 100) ringVol = val; + else if (k == "SXMO_TEXTSOUND") textSound = rawVal; } } if (newRingVol >= 0) ringVol = std::clamp(newRingVol, 0, 100); @@ -573,6 +576,9 @@ class PhoneController { ofs << "SXMO_RINGNUMBER=" << ringLoops << "\n"; ofs << "SXMO_VIBRATE_STRENGTH=" << vibStrength << "\n"; ofs << "SXMO_RINGVOL=" << ringVol << "\n"; + if (!textSound.empty()) { + ofs << "SXMO_TEXTSOUND=" << textSound << "\n"; + } } }