1579 lines
50 KiB
C++
1579 lines
50 KiB
C++
#include "phone_data.h"
|
|
#include "monotone.h"
|
|
#include "../sxmo-dwm/dwm_plugin.h"
|
|
|
|
#include <X11/Xatom.h>
|
|
#include <X11/Xft/Xft.h>
|
|
#include <X11/Xlib.h>
|
|
#include <X11/Xutil.h>
|
|
#include <X11/keysym.h>
|
|
#include <X11/XF86keysym.h>
|
|
#ifndef _EVDEVK
|
|
#define _EVDEVK(_v) (0x10081000 + (_v))
|
|
#endif
|
|
#include <pango/pangoxft.h>
|
|
|
|
#include <dirent.h>
|
|
#include <fcntl.h>
|
|
#include <poll.h>
|
|
#include <signal.h>
|
|
#include <sys/socket.h>
|
|
#include <sys/stat.h>
|
|
#include <sys/un.h>
|
|
#include <sys/wait.h>
|
|
#include <unistd.h>
|
|
|
|
#include <algorithm>
|
|
#include <clocale>
|
|
#include <cmath>
|
|
#include <cstdio>
|
|
#include <cstdlib>
|
|
#include <cstring>
|
|
#include <fstream>
|
|
#include <random>
|
|
#include <string>
|
|
#include <vector>
|
|
|
|
namespace {
|
|
|
|
using namespace bananarchy;
|
|
|
|
volatile sig_atomic_t gRunning = 1;
|
|
|
|
void handleSignal(int) {
|
|
gRunning = 0;
|
|
}
|
|
|
|
enum class TabId {
|
|
Player = 0,
|
|
Queue = 1,
|
|
Browser = 2,
|
|
};
|
|
|
|
enum class RepeatMode {
|
|
All = 0,
|
|
One = 1,
|
|
Off = 2,
|
|
};
|
|
|
|
struct TrackEntry {
|
|
std::string path;
|
|
std::string displayName;
|
|
std::string folderName;
|
|
std::string formatTag;
|
|
bool isTracker = false;
|
|
off_t sizeBytes = 0;
|
|
};
|
|
|
|
struct BrowserItem {
|
|
std::string name;
|
|
std::string fullPath;
|
|
std::string lowerName;
|
|
std::string formatTag;
|
|
bool isParent = false;
|
|
bool isDir = false;
|
|
bool isTracker = false;
|
|
off_t sizeBytes = 0;
|
|
};
|
|
|
|
constexpr const char* kMpvSockPath = "/tmp/xmusic_mpv.sock";
|
|
|
|
std::string getExtLower(const std::string& name) {
|
|
size_t dot = name.rfind('.');
|
|
if (dot == std::string::npos || dot + 1 >= name.size()) {
|
|
return "";
|
|
}
|
|
return toLowerStr(name.substr(dot + 1));
|
|
}
|
|
|
|
bool isTrackerFormatExt(const std::string& ext) {
|
|
return ext == "mod" || ext == "xm" || ext == "it" || ext == "s3m" ||
|
|
ext == "mptm" || ext == "stm" || ext == "med" || ext == "okt" ||
|
|
ext == "669" || ext == "ult" || ext == "far" || ext == "mtm" ||
|
|
ext == "ptm" || ext == "amf" || ext == "dsm" || ext == "imf" ||
|
|
ext == "gdm" || ext == "stx" || ext == "umx" || ext == "mo3" ||
|
|
ext == "j2b" || ext == "psm" || ext == "dbm" || ext == "digi" ||
|
|
ext == "mdl" || ext == "mt2" || ext == "ams" || ext == "plm" ||
|
|
ext == "sfx";
|
|
}
|
|
|
|
bool isStandardAudioExt(const std::string& ext) {
|
|
return ext == "mp3" || ext == "wav" || ext == "ogg" || ext == "oga" ||
|
|
ext == "opus" || ext == "flac" || ext == "m4a" || ext == "aac" ||
|
|
ext == "wma" || ext == "aiff" || ext == "wv" || ext == "ape" ||
|
|
ext == "spx";
|
|
}
|
|
|
|
bool isSupportedAudioExt(const std::string& ext) {
|
|
return isStandardAudioExt(ext) || isTrackerFormatExt(ext) ||
|
|
isMonotoneExt(ext);
|
|
}
|
|
|
|
std::string toUpperTag(const std::string& ext) {
|
|
std::string out = ext;
|
|
for (char& c : out) {
|
|
c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
|
|
}
|
|
return out.empty() ? "AUD" : out;
|
|
}
|
|
|
|
std::string prettifyTrackName(const std::string& filename) {
|
|
std::string base = filename;
|
|
size_t dot = base.rfind('.');
|
|
if (dot != std::string::npos && dot > 0) {
|
|
base = base.substr(0, dot);
|
|
}
|
|
for (char& c : base) {
|
|
if (c == '_') c = ' ';
|
|
}
|
|
return base;
|
|
}
|
|
|
|
std::string extractParentName(const std::string& path) {
|
|
size_t sl = path.rfind('/');
|
|
if (sl == std::string::npos || sl == 0) return "/";
|
|
std::string dir = path.substr(0, sl);
|
|
size_t sl2 = dir.rfind('/');
|
|
if (sl2 == std::string::npos) return dir;
|
|
return dir.substr(sl2 + 1);
|
|
}
|
|
|
|
std::string formatFileSizeShort(off_t bytes) {
|
|
char buf[32];
|
|
if (bytes >= 1024LL * 1024LL) {
|
|
std::snprintf(buf, sizeof(buf), "%.1fM",
|
|
static_cast<double>(bytes) / (1024.0 * 1024.0));
|
|
} else if (bytes >= 1024LL) {
|
|
std::snprintf(buf, sizeof(buf), "%lldK",
|
|
static_cast<long long>((bytes + 512) / 1024));
|
|
} else {
|
|
std::snprintf(buf, sizeof(buf), "%lldB", static_cast<long long>(bytes));
|
|
}
|
|
return buf;
|
|
}
|
|
|
|
std::string formatTimeMmSs(double sec) {
|
|
if (sec < 0.0 || !std::isfinite(sec)) sec = 0.0;
|
|
int total = static_cast<int>(sec + 0.5);
|
|
int mins = total / 60;
|
|
int secs = total % 60;
|
|
char buf[32];
|
|
if (mins >= 60) {
|
|
int hrs = mins / 60;
|
|
mins %= 60;
|
|
std::snprintf(buf, sizeof(buf), "%d:%02d:%02d", hrs, mins, secs);
|
|
} else {
|
|
std::snprintf(buf, sizeof(buf), "%02d:%02d", mins, secs);
|
|
}
|
|
return buf;
|
|
}
|
|
|
|
std::string jsonEscape(const std::string& s) {
|
|
std::string out;
|
|
out.reserve(s.size() + 8);
|
|
for (char c : s) {
|
|
if (c == '\\') out += "\\\\";
|
|
else if (c == '"') out += "\\\"";
|
|
else if (c == '\n') out += "\\n";
|
|
else out.push_back(c);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
TrackEntry makeTrackEntry(const std::string& fullPath) {
|
|
TrackEntry t;
|
|
t.path = fullPath;
|
|
size_t sl = fullPath.rfind('/');
|
|
std::string fname =
|
|
(sl != std::string::npos) ? fullPath.substr(sl + 1) : fullPath;
|
|
std::string ext = getExtLower(fname);
|
|
t.displayName = prettifyTrackName(fname);
|
|
t.folderName = extractParentName(fullPath);
|
|
t.formatTag = toUpperTag(ext);
|
|
t.isTracker = isTrackerFormatExt(ext);
|
|
struct stat st {};
|
|
if (::stat(fullPath.c_str(), &st) == 0) {
|
|
t.sizeBytes = st.st_size;
|
|
}
|
|
return t;
|
|
}
|
|
|
|
void scanTracksInDir(const std::string& dirPath,
|
|
bool recursive,
|
|
std::vector<TrackEntry>& out,
|
|
int depth = 0) {
|
|
if (depth > 4) return;
|
|
DIR* d = ::opendir(dirPath.c_str());
|
|
if (!d) return;
|
|
|
|
std::vector<std::string> subdirs;
|
|
std::vector<std::string> files;
|
|
while (struct dirent* ent = ::readdir(d)) {
|
|
if (ent->d_name[0] == '.') continue;
|
|
std::string name = ent->d_name;
|
|
std::string full =
|
|
(dirPath == "/") ? ("/" + name) : (dirPath + "/" + name);
|
|
struct stat st {};
|
|
if (::stat(full.c_str(), &st) != 0) continue;
|
|
if (S_ISDIR(st.st_mode)) {
|
|
if (recursive) subdirs.push_back(full);
|
|
} else if (S_ISREG(st.st_mode)) {
|
|
std::string ext = getExtLower(name);
|
|
if (isSupportedAudioExt(ext)) {
|
|
files.push_back(full);
|
|
}
|
|
}
|
|
}
|
|
::closedir(d);
|
|
|
|
std::sort(files.begin(), files.end());
|
|
for (const auto& f : files) {
|
|
bool exists = false;
|
|
for (const auto& e : out) {
|
|
if (e.path == f) {
|
|
exists = true;
|
|
break;
|
|
}
|
|
}
|
|
if (!exists) {
|
|
out.push_back(makeTrackEntry(f));
|
|
}
|
|
}
|
|
|
|
std::sort(subdirs.begin(), subdirs.end());
|
|
for (const auto& sd : subdirs) {
|
|
scanTracksInDir(sd, recursive, out, depth + 1);
|
|
}
|
|
}
|
|
|
|
std::string getHomePath() {
|
|
return getHomeDirPath();
|
|
}
|
|
|
|
std::string getConfigDirPath() {
|
|
if (!isDuressMode()) {
|
|
const char* c = std::getenv("XDG_CONFIG_HOME");
|
|
if (c && *c) return std::string(c) + "/sxmo";
|
|
}
|
|
return getHomePath() + "/.config/sxmo";
|
|
}
|
|
|
|
int readSavedSpeakerVol() {
|
|
std::string outDev = "Speaker";
|
|
{
|
|
std::ifstream dfs("/tmp/sxmo_audio_out_device");
|
|
if (dfs) std::getline(dfs, outDev);
|
|
}
|
|
std::string vfile = "/speaker_vol";
|
|
int defv = 85;
|
|
if (outDev.find("Bluetooth") != std::string::npos ||
|
|
outDev.find("bluetooth") != std::string::npos) {
|
|
vfile = "/bluetooth_vol";
|
|
defv = 80;
|
|
} else if (outDev.find("Headphone") != std::string::npos ||
|
|
outDev.find("Headset") != std::string::npos) {
|
|
vfile = "/headphones_vol";
|
|
defv = 80;
|
|
} else if (outDev.find("Earpiece") != std::string::npos) {
|
|
vfile = "/earpiece_vol";
|
|
}
|
|
std::ifstream ifs(getConfigDirPath() + vfile);
|
|
int v = defv;
|
|
if (ifs && (ifs >> v)) {
|
|
return std::clamp((v / 5) * 5, 0, 100);
|
|
}
|
|
return defv;
|
|
}
|
|
|
|
void applySystemSpeakerVol(int pct) {
|
|
pct = std::clamp((pct / 5) * 5, 0, 100);
|
|
runAsyncCmd("sxmo_audio.sh vol set " + std::to_string(pct) + " >/dev/null 2>&1");
|
|
}
|
|
|
|
int runMusicApp(int argc, char** argv) {
|
|
gRunning = 1;
|
|
std::setlocale(LC_ALL, "");
|
|
XSetLocaleModifiers("");
|
|
|
|
bool isPreload = false;
|
|
std::string initTarget;
|
|
for (int i = 1; i < argc; ++i) {
|
|
if (!argv[i]) continue;
|
|
if (std::strcmp(argv[i], "--preload") == 0) {
|
|
isPreload = true;
|
|
} else if (argv[i][0] != '-' && initTarget.empty()) {
|
|
initTarget = argv[i];
|
|
}
|
|
}
|
|
|
|
std::string daemonPidPath = getPluginDaemonPidPath("music");
|
|
std::string activePidPath = getRuntimeFile("xmusic.pid");
|
|
|
|
if (isPluginDaemonAlive("music")) {
|
|
if (!isPreload) {
|
|
sendPluginCommand(
|
|
"music", initTarget.empty() ? "OPEN" : ("OPEN " + initTarget));
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
writeIntFile(daemonPidPath, static_cast<int>(::getpid()));
|
|
int fifoFd = setupPluginDaemonFifo("music");
|
|
|
|
struct sigaction sa {};
|
|
sa.sa_handler = handleSignal;
|
|
sigemptyset(&sa.sa_mask);
|
|
sigaction(SIGINT, &sa, nullptr);
|
|
sigaction(SIGTERM, &sa, nullptr);
|
|
|
|
NeoWindow neo;
|
|
if (!neo.create("xmusic", "XMusic", "Music",
|
|
kWinX, kWinY, kWinWidth, kWinHeight)) {
|
|
if (fifoFd >= 0) ::close(fifoFd);
|
|
::unlink(daemonPidPath.c_str());
|
|
return 1;
|
|
}
|
|
Display* dpy = neo.dpy;
|
|
Window win = neo.win;
|
|
Pixmap pix = neo.pix;
|
|
GC gc = neo.gc;
|
|
PluginTheme& pt = neo.theme;
|
|
auto& layoutMain = neo.layoutMain;
|
|
auto& layoutSmall = neo.layoutSmall;
|
|
auto& layoutIcon = neo.layoutIcon;
|
|
auto& colWhite = pt.colWhite;
|
|
auto& colLight = pt.colLight;
|
|
auto& colMuted = pt.colMuted;
|
|
auto& colYellow = pt.colYellow;
|
|
auto& colGreen = pt.colGreen;
|
|
auto& colBlue = pt.colBlue;
|
|
auto& colOrange = pt.colOrange;
|
|
|
|
std::string homeDir = getHomePath();
|
|
std::string musicRoot = homeDir + "/Music";
|
|
::mkdir(musicRoot.c_str(), 0755);
|
|
|
|
TabId activeTab = TabId::Player;
|
|
std::vector<TrackEntry> queue;
|
|
int currentTrackIdx = -1;
|
|
int queueSelIdx = 0;
|
|
|
|
std::string browserDir = musicRoot;
|
|
std::vector<BrowserItem> browserItems;
|
|
int browserSelIdx = 0;
|
|
|
|
RepeatMode repeatMode = RepeatMode::All;
|
|
bool shuffleOn = false;
|
|
int volumePct = readSavedSpeakerVol();
|
|
|
|
// Playback state from mpv IPC
|
|
pid_t mpvPid = -1;
|
|
int ipcFd = -1;
|
|
std::string ipcReadBuf;
|
|
std::string pendingLoadPath;
|
|
bool isPlaying = false;
|
|
bool isPaused = false;
|
|
double timePosSec = 0.0;
|
|
double durationSec = 0.0;
|
|
std::string mediaTitle;
|
|
int64_t ignoreEofUntilMs = 0;
|
|
|
|
std::string statusBanner;
|
|
int64_t statusBannerUntilMs = 0;
|
|
|
|
bool visible = false;
|
|
int64_t startupIgnoreUntilMs = 0;
|
|
bool initialSoftkeysReleased = true;
|
|
int softkeyPending = 0;
|
|
int64_t softkeyDeadlineMs = 0;
|
|
|
|
std::mt19937 rng(static_cast<uint32_t>(nowMs()));
|
|
|
|
auto setBanner = [&](const std::string& msg, int durationMs = 2000) {
|
|
statusBanner = msg;
|
|
statusBannerUntilMs = nowMs() + durationMs;
|
|
};
|
|
|
|
auto sendIpcRaw = [&](const std::string& jsonLine) -> bool {
|
|
if (ipcFd < 0) return false;
|
|
std::string msg = jsonLine + "\n";
|
|
ssize_t w = ::write(ipcFd, msg.data(), msg.size());
|
|
return w == static_cast<ssize_t>(msg.size());
|
|
};
|
|
|
|
auto stopMpvDaemon = [&]() {
|
|
if (ipcFd >= 0) {
|
|
::close(ipcFd);
|
|
ipcFd = -1;
|
|
}
|
|
ipcReadBuf.clear();
|
|
if (mpvPid > 0) {
|
|
::kill(mpvPid, SIGTERM);
|
|
for (int i = 0; i < 15; ++i) {
|
|
if (::waitpid(mpvPid, nullptr, WNOHANG) == mpvPid) {
|
|
break;
|
|
}
|
|
usleep(10000);
|
|
}
|
|
mpvPid = -1;
|
|
}
|
|
::unlink(kMpvSockPath);
|
|
};
|
|
|
|
auto ensureMpvRunning = [&]() {
|
|
if (mpvPid > 0) {
|
|
int st = 0;
|
|
pid_t r = ::waitpid(mpvPid, &st, WNOHANG);
|
|
if (r == mpvPid || (r < 0 && errno == ECHILD)) {
|
|
mpvPid = -1;
|
|
if (ipcFd >= 0) {
|
|
::close(ipcFd);
|
|
ipcFd = -1;
|
|
}
|
|
}
|
|
}
|
|
if (mpvPid <= 0) {
|
|
::unlink(kMpvSockPath);
|
|
pid_t pid = ::fork();
|
|
if (pid == 0) {
|
|
::setsid();
|
|
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);
|
|
}
|
|
std::string ipcArg =
|
|
std::string("--input-ipc-server=") + kMpvSockPath;
|
|
::execlp("mpv", "mpv", "--no-video", "--no-terminal", "--quiet",
|
|
"--ao=pipewire,pulse,alsa", "--audio-channels=stereo",
|
|
"--audio-samplerate=48000", "--idle=yes", "--keep-open=no",
|
|
"--volume-max=150", "--volume=100", ipcArg.c_str(),
|
|
static_cast<char*>(nullptr));
|
|
::_exit(127);
|
|
} else if (pid > 0) {
|
|
mpvPid = pid;
|
|
}
|
|
}
|
|
};
|
|
|
|
auto tryConnectIpc = [&]() -> bool {
|
|
if (ipcFd >= 0) return true;
|
|
int fd = ::socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0);
|
|
if (fd < 0) return false;
|
|
struct sockaddr_un addr {};
|
|
addr.sun_family = AF_UNIX;
|
|
std::snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", kMpvSockPath);
|
|
if (::connect(fd, reinterpret_cast<struct sockaddr*>(&addr),
|
|
sizeof(addr)) != 0) {
|
|
::close(fd);
|
|
return false;
|
|
}
|
|
ipcFd = fd;
|
|
ipcReadBuf.clear();
|
|
sendIpcRaw("{\"command\":[\"observe_property\",1,\"time-pos\"]}");
|
|
sendIpcRaw("{\"command\":[\"observe_property\",2,\"duration\"]}");
|
|
sendIpcRaw("{\"command\":[\"observe_property\",3,\"pause\"]}");
|
|
sendIpcRaw("{\"command\":[\"observe_property\",4,\"media-title\"]}");
|
|
if (!pendingLoadPath.empty()) {
|
|
std::string p = pendingLoadPath;
|
|
pendingLoadPath.clear();
|
|
ignoreEofUntilMs = nowMs() + 450;
|
|
sendIpcRaw("{\"command\":[\"loadfile\",\"" + jsonEscape(p) +
|
|
"\",\"replace\"]}");
|
|
sendIpcRaw("{\"command\":[\"set_property\",\"pause\",false]}");
|
|
}
|
|
return true;
|
|
};
|
|
|
|
auto playTrackAtIndex = [&](int idx) {
|
|
if (queue.empty() || idx < 0 || idx >= static_cast<int>(queue.size())) {
|
|
return;
|
|
}
|
|
currentTrackIdx = idx;
|
|
queueSelIdx = idx;
|
|
const auto& tr = queue[idx];
|
|
timePosSec = 0.0;
|
|
durationSec = 0.0;
|
|
mediaTitle = tr.displayName;
|
|
isPlaying = true;
|
|
isPaused = false;
|
|
ignoreEofUntilMs = nowMs() + 450;
|
|
|
|
runAsyncCmd("sxmo_audio.sh device apply >/dev/null 2>&1; "
|
|
"(sleep 0.25; "
|
|
"sink=$(pactl get-default-sink 2>/dev/null); "
|
|
"if [ -n \"$sink\" ]; then "
|
|
" for sid in $(pactl list short sink-inputs 2>/dev/null | awk '{print $1}'); do "
|
|
" pactl move-sink-input \"$sid\" \"$sink\" >/dev/null 2>&1 || true; "
|
|
" done; "
|
|
"fi) >/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(loadTarget) +
|
|
"\",\"replace\"]}");
|
|
sendIpcRaw("{\"command\":[\"set_property\",\"pause\",false]}");
|
|
} else {
|
|
pendingLoadPath = loadTarget;
|
|
}
|
|
};
|
|
|
|
auto stopPlayback = [&]() {
|
|
pendingLoadPath.clear();
|
|
isPlaying = false;
|
|
isPaused = false;
|
|
timePosSec = 0.0;
|
|
durationSec = 0.0;
|
|
ignoreEofUntilMs = nowMs() + 400;
|
|
if (ipcFd >= 0) {
|
|
sendIpcRaw("{\"command\":[\"stop\"]}");
|
|
}
|
|
};
|
|
|
|
auto togglePlayPause = [&]() {
|
|
if (queue.empty()) {
|
|
setBanner("Queue is empty");
|
|
return;
|
|
}
|
|
if (!isPlaying) {
|
|
int target = (currentTrackIdx >= 0 &&
|
|
currentTrackIdx < static_cast<int>(queue.size()))
|
|
? currentTrackIdx
|
|
: queueSelIdx;
|
|
playTrackAtIndex(std::clamp(target, 0,
|
|
static_cast<int>(queue.size()) - 1));
|
|
return;
|
|
}
|
|
isPaused = !isPaused;
|
|
if (tryConnectIpc()) {
|
|
sendIpcRaw(std::string("{\"command\":[\"set_property\",\"pause\",") +
|
|
(isPaused ? "true" : "false") + "]}");
|
|
}
|
|
};
|
|
|
|
auto pausePlayback = [&]() {
|
|
if (isPlaying && !isPaused) {
|
|
isPaused = true;
|
|
if (tryConnectIpc()) {
|
|
sendIpcRaw("{\"command\":[\"set_property\",\"pause\",true]}");
|
|
}
|
|
}
|
|
};
|
|
|
|
auto seekRelative = [&](int deltaSec) {
|
|
if (!isPlaying || ipcFd < 0) return;
|
|
sendIpcRaw("{\"command\":[\"seek\"," + std::to_string(deltaSec) +
|
|
",\"relative\"]}");
|
|
timePosSec = std::max(0.0, timePosSec + deltaSec);
|
|
if (durationSec > 0.0) {
|
|
timePosSec = std::min(durationSec, timePosSec);
|
|
}
|
|
};
|
|
|
|
auto stepTrack = [&](int delta, bool autoAdvance = false) {
|
|
if (queue.empty()) return;
|
|
int total = static_cast<int>(queue.size());
|
|
if (autoAdvance && repeatMode == RepeatMode::One && currentTrackIdx >= 0) {
|
|
playTrackAtIndex(currentTrackIdx);
|
|
return;
|
|
}
|
|
if (shuffleOn && total > 1) {
|
|
std::uniform_int_distribution<int> dist(0, total - 2);
|
|
int r = dist(rng);
|
|
if (r >= currentTrackIdx) ++r;
|
|
playTrackAtIndex(r);
|
|
return;
|
|
}
|
|
int base = (currentTrackIdx >= 0) ? currentTrackIdx : queueSelIdx;
|
|
int next = base + delta;
|
|
if (next >= total) {
|
|
if (autoAdvance && repeatMode == RepeatMode::Off) {
|
|
stopPlayback();
|
|
return;
|
|
}
|
|
next = 0;
|
|
} else if (next < 0) {
|
|
next = total - 1;
|
|
}
|
|
playTrackAtIndex(next);
|
|
};
|
|
|
|
auto loadBrowserDirectory = [&](const std::string& targetDir,
|
|
const std::string& selectName = "") {
|
|
char resolved[4096];
|
|
std::string dir = targetDir;
|
|
if (::realpath(targetDir.c_str(), resolved) != nullptr) {
|
|
dir = resolved;
|
|
}
|
|
if (isDuressMode()) {
|
|
std::string root = getHomeDirPath();
|
|
if (dir != root && dir.rfind(root + "/", 0) != 0) {
|
|
dir = root;
|
|
}
|
|
}
|
|
DIR* d = ::opendir(dir.c_str());
|
|
if (!d) {
|
|
setBanner("Cannot open folder");
|
|
return;
|
|
}
|
|
browserDir = dir;
|
|
browserItems.clear();
|
|
|
|
std::string topLimit = isDuressMode() ? getHomeDirPath() : "/";
|
|
if (browserDir != "/" && browserDir != topLimit) {
|
|
BrowserItem up;
|
|
up.name = ".. (Up)";
|
|
size_t sl = browserDir.rfind('/');
|
|
up.fullPath = (sl == 0 || sl == std::string::npos)
|
|
? "/"
|
|
: browserDir.substr(0, sl);
|
|
up.lowerName = "..";
|
|
up.isParent = true;
|
|
up.isDir = true;
|
|
browserItems.push_back(up);
|
|
}
|
|
|
|
std::vector<BrowserItem> dirs;
|
|
std::vector<BrowserItem> files;
|
|
while (struct dirent* ent = ::readdir(d)) {
|
|
if (ent->d_name[0] == '.') continue;
|
|
std::string name = ent->d_name;
|
|
std::string full =
|
|
(browserDir == "/") ? ("/" + name) : (browserDir + "/" + name);
|
|
struct stat st {};
|
|
if (::stat(full.c_str(), &st) != 0) continue;
|
|
|
|
BrowserItem item;
|
|
item.name = name;
|
|
item.fullPath = full;
|
|
item.lowerName = toLowerStr(name);
|
|
item.sizeBytes = st.st_size;
|
|
if (S_ISDIR(st.st_mode)) {
|
|
item.isDir = true;
|
|
item.formatTag = "DIR";
|
|
dirs.push_back(item);
|
|
} else if (S_ISREG(st.st_mode)) {
|
|
std::string ext = getExtLower(name);
|
|
if (isSupportedAudioExt(ext)) {
|
|
item.isTracker = isTrackerFormatExt(ext);
|
|
item.formatTag = toUpperTag(ext);
|
|
files.push_back(item);
|
|
}
|
|
}
|
|
}
|
|
::closedir(d);
|
|
|
|
auto cmp = [](const BrowserItem& a, const BrowserItem& b) {
|
|
return a.lowerName < b.lowerName;
|
|
};
|
|
std::sort(dirs.begin(), dirs.end(), cmp);
|
|
std::sort(files.begin(), files.end(), cmp);
|
|
|
|
browserItems.insert(browserItems.end(), dirs.begin(), dirs.end());
|
|
browserItems.insert(browserItems.end(), files.begin(), files.end());
|
|
|
|
browserSelIdx = 0;
|
|
if (!selectName.empty()) {
|
|
for (size_t i = 0; i < browserItems.size(); ++i) {
|
|
if (browserItems[i].name == selectName) {
|
|
browserSelIdx = static_cast<int>(i);
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
};
|
|
|
|
auto populateDefaultQueue = [&]() {
|
|
queue.clear();
|
|
scanTracksInDir(musicRoot, true, queue);
|
|
scanTracksInDir("/usr/share/sxmo/music", true, queue);
|
|
if (queue.empty()) {
|
|
scanTracksInDir("/usr/share/sxmo/ringtones", false, queue);
|
|
}
|
|
if (queueSelIdx >= static_cast<int>(queue.size())) {
|
|
queueSelIdx = std::max(0, static_cast<int>(queue.size()) - 1);
|
|
}
|
|
};
|
|
|
|
auto openTargetPath = [&](const std::string& rawTarget) {
|
|
if (rawTarget.empty()) return;
|
|
char resolved[4096];
|
|
std::string target = rawTarget;
|
|
if (::realpath(rawTarget.c_str(), resolved) != nullptr) {
|
|
target = resolved;
|
|
}
|
|
struct stat st {};
|
|
if (::stat(target.c_str(), &st) != 0) {
|
|
setBanner("File not found");
|
|
return;
|
|
}
|
|
if (S_ISDIR(st.st_mode)) {
|
|
std::vector<TrackEntry> dirTracks;
|
|
scanTracksInDir(target, true, dirTracks);
|
|
loadBrowserDirectory(target);
|
|
if (!dirTracks.empty()) {
|
|
queue = dirTracks;
|
|
activeTab = TabId::Player;
|
|
playTrackAtIndex(0);
|
|
} else {
|
|
activeTab = TabId::Browser;
|
|
setBanner("No audio files in folder");
|
|
}
|
|
return;
|
|
}
|
|
|
|
// Single audio/tracker file: load sibling audio files in the same folder
|
|
size_t sl = target.rfind('/');
|
|
std::string parentDir =
|
|
(sl == 0 || sl == std::string::npos) ? "/" : target.substr(0, sl);
|
|
std::string fname =
|
|
(sl != std::string::npos) ? target.substr(sl + 1) : target;
|
|
|
|
std::vector<TrackEntry> folderTracks;
|
|
scanTracksInDir(parentDir, false, folderTracks);
|
|
int foundIdx = -1;
|
|
for (size_t i = 0; i < folderTracks.size(); ++i) {
|
|
if (folderTracks[i].path == target) {
|
|
foundIdx = static_cast<int>(i);
|
|
break;
|
|
}
|
|
}
|
|
if (foundIdx < 0) {
|
|
folderTracks.insert(folderTracks.begin(), makeTrackEntry(target));
|
|
foundIdx = 0;
|
|
}
|
|
queue = folderTracks;
|
|
loadBrowserDirectory(parentDir, fname);
|
|
activeTab = TabId::Player;
|
|
playTrackAtIndex(foundIdx);
|
|
};
|
|
|
|
auto installTrackAsRingtone = [&](const TrackEntry& tr) {
|
|
std::string ringDir = homeDir + "/Ringtones";
|
|
::mkdir(ringDir.c_str(), 0755);
|
|
std::string targetPath = tr.path;
|
|
size_t sl = tr.path.rfind('/');
|
|
std::string fname =
|
|
(sl != std::string::npos) ? tr.path.substr(sl + 1) : tr.path;
|
|
if (tr.path.rfind("/usr/share/sxmo/", 0) != 0 &&
|
|
tr.path.rfind(ringDir + "/", 0) != 0 &&
|
|
tr.path.rfind(musicRoot + "/", 0) != 0) {
|
|
std::string dst = ringDir + "/" + fname;
|
|
pid_t pid = ::fork();
|
|
if (pid == 0) {
|
|
::execlp("cp", "cp", "-f", tr.path.c_str(), dst.c_str(),
|
|
static_cast<char*>(nullptr));
|
|
::_exit(127);
|
|
} else if (pid > 0) {
|
|
int st = 0;
|
|
::waitpid(pid, &st, 0);
|
|
if (WIFEXITED(st) && WEXITSTATUS(st) == 0) {
|
|
targetPath = dst;
|
|
}
|
|
}
|
|
}
|
|
std::string cfgDir = getConfigDirPath();
|
|
::mkdir(cfgDir.c_str(), 0755);
|
|
std::ofstream ofs(cfgDir + "/ringtone", std::ios::trunc);
|
|
if (ofs) ofs << targetPath << "\n";
|
|
setBanner("Ringtone set: " + tr.displayName);
|
|
};
|
|
|
|
auto parseIpcLine = [&](const std::string& line) {
|
|
if (line.find("\"event\":\"end-file\"") != std::string::npos) {
|
|
if (line.find("\"reason\":\"eof\"") != std::string::npos &&
|
|
nowMs() >= ignoreEofUntilMs && isPlaying) {
|
|
stepTrack(1, true);
|
|
}
|
|
return;
|
|
}
|
|
if (line.find("\"event\":\"property-change\"") == std::string::npos) {
|
|
return;
|
|
}
|
|
if (line.find("\"name\":\"time-pos\"") != std::string::npos) {
|
|
size_t dp = line.find("\"data\":");
|
|
if (dp != std::string::npos) {
|
|
const char* p = line.c_str() + dp + 7;
|
|
if (std::strncmp(p, "null", 4) != 0) {
|
|
timePosSec = std::strtod(p, nullptr);
|
|
}
|
|
}
|
|
} else if (line.find("\"name\":\"duration\"") != std::string::npos) {
|
|
size_t dp = line.find("\"data\":");
|
|
if (dp != std::string::npos) {
|
|
const char* p = line.c_str() + dp + 7;
|
|
if (std::strncmp(p, "null", 4) != 0) {
|
|
durationSec = std::strtod(p, nullptr);
|
|
}
|
|
}
|
|
} else if (line.find("\"name\":\"pause\"") != std::string::npos) {
|
|
if (line.find("\"data\":true") != std::string::npos) {
|
|
isPaused = true;
|
|
} else if (line.find("\"data\":false") != std::string::npos) {
|
|
isPaused = false;
|
|
}
|
|
} else if (line.find("\"name\":\"media-title\"") != std::string::npos) {
|
|
size_t dp = line.find("\"data\":\"");
|
|
if (dp != std::string::npos) {
|
|
size_t start = dp + 8;
|
|
size_t end = line.find('"', start);
|
|
if (end != std::string::npos && end > start) {
|
|
std::string t = line.substr(start, end - start);
|
|
if (!t.empty() && t.find("xmusic_monotone") == std::string::npos) {
|
|
mediaTitle = prettifyTrackName(t);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
};
|
|
|
|
auto drainIpcSocket = [&]() -> bool {
|
|
if (ipcFd < 0) return false;
|
|
bool changed = false;
|
|
char buf[1024];
|
|
while (true) {
|
|
ssize_t n = ::read(ipcFd, buf, sizeof(buf));
|
|
if (n > 0) {
|
|
ipcReadBuf.append(buf, static_cast<size_t>(n));
|
|
size_t nl = 0;
|
|
while ((nl = ipcReadBuf.find('\n')) != std::string::npos) {
|
|
std::string line = ipcReadBuf.substr(0, nl);
|
|
ipcReadBuf.erase(0, nl + 1);
|
|
parseIpcLine(line);
|
|
changed = true;
|
|
}
|
|
} else if (n == 0) {
|
|
::close(ipcFd);
|
|
ipcFd = -1;
|
|
ipcReadBuf.clear();
|
|
break;
|
|
} else {
|
|
if (errno == EAGAIN || errno == EWOULDBLOCK) break;
|
|
::close(ipcFd);
|
|
ipcFd = -1;
|
|
ipcReadBuf.clear();
|
|
break;
|
|
}
|
|
}
|
|
return changed;
|
|
};
|
|
|
|
auto drawPango = [&](PangoLayout* layout, XftColor* color, int x, int y,
|
|
int h, const std::string& text, int maxW = -1,
|
|
int align = 0) {
|
|
if (text.empty()) return;
|
|
neo.drawPango(layout, color, x, y, h, text, maxW, align);
|
|
};
|
|
|
|
auto drawSoftkeyBar = [&](const std::string& leftLabel,
|
|
const std::string& midLabel,
|
|
const std::string& rightLabel) {
|
|
neo.drawSoftbar(leftLabel, midLabel, rightLabel, &colYellow, 24);
|
|
};
|
|
|
|
auto render = [&]() {
|
|
if (!visible) return;
|
|
pt.checkAndReload();
|
|
|
|
XSetForeground(dpy, gc, pt.spec.bgMain);
|
|
XFillRectangle(dpy, pix, gc, 0, 0, kWinWidth, kWinHeight);
|
|
|
|
// Top 3-tab header (0..26)
|
|
XSetForeground(dpy, gc, pt.spec.bgHeader);
|
|
XFillRectangle(dpy, pix, gc, 0, 0, kWinWidth, 26);
|
|
|
|
const char* tabNames[3] = {"1:Player", "2:Queue", "3:Files"};
|
|
for (int i = 0; i < 3; ++i) {
|
|
int tx = i * 80;
|
|
bool isAct = (static_cast<int>(activeTab) == i);
|
|
if (isAct) {
|
|
XSetForeground(dpy, gc, pt.spec.selBg);
|
|
XFillRectangle(dpy, pix, gc, tx, 0, 80, 26);
|
|
XSetForeground(dpy, gc, pt.spec.accent);
|
|
XFillRectangle(dpy, pix, gc, tx, 24, 80, 2);
|
|
}
|
|
drawPango(layoutSmall, isAct ? &colWhite : &colMuted, tx + 2, 0, 24,
|
|
tabNames[i], 76, 1);
|
|
}
|
|
|
|
if (activeTab == TabId::Player) {
|
|
// Track info card (y=30..104)
|
|
XSetForeground(dpy, gc, pt.spec.bgAltEven);
|
|
XFillRectangle(dpy, pix, gc, 4, 30, kWinWidth - 8, 74);
|
|
XSetForeground(dpy, gc, pt.spec.border);
|
|
XDrawRectangle(dpy, pix, gc, 4, 30, kWinWidth - 9, 73);
|
|
|
|
bool hasTrack = (currentTrackIdx >= 0 &&
|
|
currentTrackIdx < static_cast<int>(queue.size()));
|
|
const TrackEntry* cur =
|
|
hasTrack ? &queue[currentTrackIdx]
|
|
: (!queue.empty() && queueSelIdx >= 0 &&
|
|
queueSelIdx < static_cast<int>(queue.size())
|
|
? &queue[queueSelIdx]
|
|
: nullptr);
|
|
|
|
if (cur) {
|
|
std::string badge =
|
|
std::string("[") + cur->formatTag +
|
|
(cur->isTracker ? " TRACKER]" : "]");
|
|
drawPango(layoutSmall, cur->isTracker ? &colOrange : &colBlue, 10, 33,
|
|
18, badge, 130, 0);
|
|
|
|
int dispIdx = hasTrack ? (currentTrackIdx + 1) : (queueSelIdx + 1);
|
|
std::string idxStr =
|
|
std::to_string(dispIdx) + " / " + std::to_string(queue.size());
|
|
drawPango(layoutSmall, &colMuted, 140, 33, 18, idxStr, 90, 2);
|
|
|
|
std::string titleStr =
|
|
(isPlaying && !mediaTitle.empty()) ? mediaTitle : cur->displayName;
|
|
drawPango(layoutMain, &colWhite, 10, 53, 24,
|
|
std::string(kIconMusic) + " " + titleStr, kWinWidth - 20, 0);
|
|
|
|
std::string subStr =
|
|
cur->folderName + " | " + formatFileSizeShort(cur->sizeBytes);
|
|
drawPango(layoutSmall, &colMuted, 10, 80, 18, subStr, kWinWidth - 20,
|
|
0);
|
|
} else {
|
|
drawPango(layoutMain, &colMuted, 10, 48, 24, "No tracks loaded",
|
|
kWinWidth - 20, 1);
|
|
drawPango(layoutSmall, &colMuted, 10, 72, 18,
|
|
"Press 3 to browse files", kWinWidth - 20, 1);
|
|
}
|
|
|
|
// Progress bar & time card (y=108..154)
|
|
XSetForeground(dpy, gc, pt.spec.bgAltOdd);
|
|
XFillRectangle(dpy, pix, gc, 4, 108, kWinWidth - 8, 46);
|
|
|
|
int barX = 12;
|
|
int barY = 116;
|
|
int barW = kWinWidth - 24;
|
|
int barH = 10;
|
|
XSetForeground(dpy, gc, pt.spec.bgHeader);
|
|
XFillRectangle(dpy, pix, gc, barX, barY, barW, barH);
|
|
XSetForeground(dpy, gc, pt.spec.border);
|
|
XDrawRectangle(dpy, pix, gc, barX, barY, barW - 1, barH - 1);
|
|
|
|
double frac = 0.0;
|
|
if (durationSec > 0.1 && timePosSec >= 0.0) {
|
|
frac = std::clamp(timePosSec / durationSec, 0.0, 1.0);
|
|
}
|
|
int fillW = static_cast<int>((barW - 2) * frac);
|
|
if (fillW > 0) {
|
|
XSetForeground(dpy, gc, pt.spec.accent);
|
|
XFillRectangle(dpy, pix, gc, barX + 1, barY + 1, fillW, barH - 2);
|
|
}
|
|
|
|
drawPango(layoutSmall, &colLight, 12, 130, 20,
|
|
formatTimeMmSs(timePosSec), 68, 0);
|
|
|
|
const char* stTxt = "STOPPED";
|
|
XftColor* stCol = &colMuted;
|
|
if (isPlaying) {
|
|
if (isPaused) {
|
|
stTxt = "PAUSED";
|
|
stCol = &colYellow;
|
|
} else {
|
|
stTxt = "PLAYING";
|
|
stCol = &colGreen;
|
|
}
|
|
}
|
|
drawPango(layoutSmall, stCol, 80, 130, 20, stTxt, 80, 1);
|
|
|
|
drawPango(layoutSmall, &colLight, 160, 130, 20,
|
|
durationSec > 0.1 ? formatTimeMmSs(durationSec) : "--:--", 68,
|
|
2);
|
|
|
|
// Mode pills row (y=158..180)
|
|
const char* repLbl =
|
|
(repeatMode == RepeatMode::All)
|
|
? "Rep:All"
|
|
: (repeatMode == RepeatMode::One ? "Rep:One" : "Rep:Off");
|
|
std::string volPill = "Vol:" + std::to_string(volumePct) + "%";
|
|
std::string shufPill = std::string("Shuf:") + (shuffleOn ? "On" : "Off");
|
|
|
|
XSetForeground(dpy, gc, pt.spec.bgAltEven);
|
|
XFillRectangle(dpy, pix, gc, 4, 158, 74, 22);
|
|
XFillRectangle(dpy, pix, gc, 83, 158, 74, 22);
|
|
XFillRectangle(dpy, pix, gc, 162, 158, 74, 22);
|
|
|
|
drawPango(layoutSmall, &colYellow, 6, 158, 22, volPill, 70, 1);
|
|
drawPango(layoutSmall,
|
|
repeatMode != RepeatMode::Off ? &colGreen : &colMuted, 85, 158,
|
|
22, repLbl, 70, 1);
|
|
drawPango(layoutSmall, shuffleOn ? &colBlue : &colMuted, 164, 158, 22,
|
|
shufPill, 70, 1);
|
|
|
|
// Keypad transport guide (y=184..268)
|
|
XSetForeground(dpy, gc, pt.spec.bgAltEven);
|
|
XFillRectangle(dpy, pix, gc, 4, 184, kWinWidth - 8, 84);
|
|
drawPango(layoutSmall, &colLight, 10, 186, 19, "[OK/5] Play/Pause", 112);
|
|
drawPango(layoutSmall, &colLight, 126, 186, 19, "[*] Stop", 104);
|
|
drawPango(layoutSmall, &colMuted, 10, 206, 19, "[L/R] Seek -/+5s", 112);
|
|
drawPango(layoutSmall, &colMuted, 126, 206, 19, "[4/6] Prev/Next", 104);
|
|
drawPango(layoutSmall, &colMuted, 10, 226, 19, "[U/D] Vol -/+5%", 112);
|
|
drawPango(layoutSmall, &colMuted, 126, 226, 19, "[7/9] Seek -/+30s", 104);
|
|
drawPango(layoutSmall, &colMuted, 10, 246, 19, "[0] Repeat Mode", 112);
|
|
drawPango(layoutSmall, &colMuted, 126, 246, 19, "[#] Shuffle", 104);
|
|
|
|
drawSoftkeyBar("Queue",
|
|
(isPlaying && !isPaused) ? "Pause" : "Play", "Hide");
|
|
|
|
} else if (activeTab == TabId::Queue) {
|
|
// Queue summary banner (y=28..50)
|
|
XSetForeground(dpy, gc, pt.spec.bgAltEven);
|
|
XFillRectangle(dpy, pix, gc, 4, 28, kWinWidth - 8, 22);
|
|
std::string qInfo = "Tracks: " + std::to_string(queue.size()) +
|
|
" ([*] Set Ring, [0] Rescan)";
|
|
drawPango(layoutSmall, &colBlue, 8, 28, 22, qInfo, kWinWidth - 16);
|
|
|
|
constexpr int kVisibleRows = 5;
|
|
int total = static_cast<int>(queue.size());
|
|
if (total == 0) {
|
|
drawPango(layoutMain, &colMuted, 12, 110, 24, "Queue is empty",
|
|
kWinWidth - 24, 1);
|
|
drawPango(layoutSmall, &colMuted, 12, 138, 20,
|
|
"Press 0 to scan ~/Music or 3 for Files", kWinWidth - 24, 1);
|
|
} else {
|
|
int startIdx = std::clamp(queueSelIdx - kVisibleRows / 2, 0,
|
|
std::max(0, total - kVisibleRows));
|
|
for (int i = 0; i < kVisibleRows; ++i) {
|
|
int idx = startIdx + i;
|
|
if (idx >= total) break;
|
|
const auto& tr = queue[idx];
|
|
int ry = 54 + i * 38;
|
|
bool isSel = (idx == queueSelIdx);
|
|
bool isCur = (idx == currentTrackIdx && isPlaying);
|
|
|
|
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 (isCur) {
|
|
XSetForeground(dpy, gc, pt.spec.accent);
|
|
XFillRectangle(dpy, pix, gc, 4, ry, 3, 36);
|
|
}
|
|
|
|
std::string line1 =
|
|
std::to_string(idx + 1) + ". " + tr.displayName;
|
|
drawPango(layoutMain, isSel ? &colWhite : &colLight, 10, ry + 1, 19,
|
|
line1, 152);
|
|
|
|
if (isCur) {
|
|
drawPango(layoutSmall, isPaused ? &colYellow : &colGreen, 162,
|
|
ry + 2, 18, isPaused ? "[PAUSED]" : "[PLAYING]", 70, 2);
|
|
}
|
|
|
|
std::string sub = tr.formatTag + " | " +
|
|
formatFileSizeShort(tr.sizeBytes) + " | " +
|
|
tr.folderName;
|
|
drawPango(layoutSmall, isSel ? &colLight : &colMuted, 10, ry + 19,
|
|
16, sub, kWinWidth - 20);
|
|
}
|
|
}
|
|
drawSoftkeyBar("Play", "Play", "Hide");
|
|
|
|
} else {
|
|
// Tab 3: Browser
|
|
XSetForeground(dpy, gc, pt.spec.bgAltEven);
|
|
XFillRectangle(dpy, pix, gc, 4, 28, kWinWidth - 8, 22);
|
|
std::string shortDir = browserDir;
|
|
if (shortDir == homeDir) shortDir = "~";
|
|
else if (shortDir.rfind(homeDir + "/", 0) == 0) {
|
|
shortDir = "~" + shortDir.substr(homeDir.size());
|
|
}
|
|
drawPango(layoutSmall, &colYellow, 8, 28, 22,
|
|
std::string(kIconFolderOpen) + " " + shortDir,
|
|
kWinWidth - 16);
|
|
|
|
constexpr int kVisibleRows = 5;
|
|
int total = static_cast<int>(browserItems.size());
|
|
if (total == 0) {
|
|
drawPango(layoutMain, &colMuted, 12, 120, 24, "No audio files here",
|
|
kWinWidth - 24, 1);
|
|
} else {
|
|
int startIdx = std::clamp(browserSelIdx - kVisibleRows / 2, 0,
|
|
std::max(0, total - kVisibleRows));
|
|
for (int i = 0; i < kVisibleRows; ++i) {
|
|
int idx = startIdx + i;
|
|
if (idx >= total) break;
|
|
const auto& it = browserItems[idx];
|
|
int ry = 54 + i * 38;
|
|
bool isSel = (idx == browserSelIdx);
|
|
|
|
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);
|
|
|
|
const char* ic = it.isParent
|
|
? kIconBackspace
|
|
: (it.isDir ? kIconFolder : kIconMusic);
|
|
XftColor* icCol =
|
|
it.isDir ? &colYellow : (it.isTracker ? &colOrange : &colBlue);
|
|
drawPango(layoutIcon, icCol, 8, ry + 2, 18, ic);
|
|
|
|
std::string disp =
|
|
it.isDir && !it.isParent ? (it.name + "/") : it.name;
|
|
drawPango(layoutMain, isSel ? &colWhite : &colLight, 26, ry + 1, 19,
|
|
disp, 198);
|
|
|
|
std::string sub =
|
|
it.isParent
|
|
? "Parent directory"
|
|
: (it.isDir ? "Folder (OK to open, LSK to play all)"
|
|
: (it.formatTag + " | " +
|
|
formatFileSizeShort(it.sizeBytes)));
|
|
drawPango(layoutSmall, isSel ? &colLight : &colMuted, 26, ry + 19,
|
|
16, sub, kWinWidth - 34);
|
|
}
|
|
}
|
|
drawSoftkeyBar("Play All", "Open", "Hide");
|
|
}
|
|
|
|
if (!statusBanner.empty() && nowMs() < statusBannerUntilMs) {
|
|
int by = kWinHeight - 46;
|
|
XSetForeground(dpy, gc, pt.spec.bgHeader);
|
|
XFillRectangle(dpy, pix, gc, 6, by, kWinWidth - 12, 20);
|
|
XSetForeground(dpy, gc, pt.spec.accent);
|
|
XDrawRectangle(dpy, pix, gc, 6, by, kWinWidth - 13, 19);
|
|
drawPango(layoutSmall, &colYellow, 10, by, 20, statusBanner,
|
|
kWinWidth - 20, 1);
|
|
}
|
|
|
|
XCopyArea(dpy, pix, win, gc, 0, 0, kWinWidth, kWinHeight, 0, 0);
|
|
XFlush(dpy);
|
|
};
|
|
|
|
auto showWindow = [&](const std::string& targetArg = "") {
|
|
writeIntFile(activePidPath, static_cast<int>(::getpid()));
|
|
closeOtherPlugins("music");
|
|
volumePct = readSavedSpeakerVol();
|
|
if (queue.empty()) {
|
|
populateDefaultQueue();
|
|
}
|
|
if (browserItems.empty()) {
|
|
loadBrowserDirectory(browserDir);
|
|
}
|
|
if (!targetArg.empty()) {
|
|
openTargetPath(targetArg);
|
|
}
|
|
if (!visible) {
|
|
visible = true;
|
|
XMapRaised(dpy, win);
|
|
XSync(dpy, False);
|
|
} else {
|
|
XRaiseWindow(dpy, win);
|
|
}
|
|
grabPluginKeyboard(dpy, win);
|
|
startupIgnoreUntilMs = nowMs() + 180;
|
|
initialSoftkeysReleased = (querySoftkeysDown(dpy) == 0);
|
|
softkeyPending = 0;
|
|
render();
|
|
};
|
|
|
|
auto hideWindow = [&]() {
|
|
if (!visible) return;
|
|
int xfdLocal = ConnectionNumber(dpy);
|
|
int64_t drainDeadline = nowMs() + 180;
|
|
while (nowMs() < drainDeadline && querySoftkeysDown(dpy) != 0) {
|
|
while (XPending(dpy) > 0) {
|
|
XEvent ev;
|
|
XNextEvent(dpy, &ev);
|
|
}
|
|
struct pollfd pfd {};
|
|
pfd.fd = xfdLocal;
|
|
pfd.events = POLLIN;
|
|
::poll(&pfd, 1, 10);
|
|
}
|
|
writeSoftkeySuppress(nowMs() + 450);
|
|
XUngrabKeyboard(dpy, CurrentTime);
|
|
visible = false;
|
|
softkeyPending = 0;
|
|
XUnmapWindow(dpy, win);
|
|
::unlink(activePidPath.c_str());
|
|
XFlush(dpy);
|
|
};
|
|
|
|
auto handleBrowserSelect = [&](bool playFolderAll) {
|
|
if (browserItems.empty()) return;
|
|
const BrowserItem item = browserItems[browserSelIdx];
|
|
if (playFolderAll) {
|
|
std::string dirToPlay =
|
|
(item.isDir && !item.isParent) ? item.fullPath : browserDir;
|
|
std::vector<TrackEntry> tracks;
|
|
scanTracksInDir(dirToPlay, true, tracks);
|
|
if (tracks.empty()) {
|
|
setBanner("No audio files found");
|
|
return;
|
|
}
|
|
queue = tracks;
|
|
activeTab = TabId::Player;
|
|
playTrackAtIndex(0);
|
|
setBanner("Playing " + std::to_string(queue.size()) + " tracks");
|
|
return;
|
|
}
|
|
if (item.isParent) {
|
|
std::string prevBase = browserDir;
|
|
size_t sl = prevBase.rfind('/');
|
|
std::string prevName =
|
|
(sl != std::string::npos) ? prevBase.substr(sl + 1) : "";
|
|
loadBrowserDirectory(item.fullPath, prevName);
|
|
return;
|
|
}
|
|
if (item.isDir) {
|
|
loadBrowserDirectory(item.fullPath);
|
|
return;
|
|
}
|
|
openTargetPath(item.fullPath);
|
|
};
|
|
|
|
if (!isPreload) {
|
|
showWindow(initTarget);
|
|
}
|
|
|
|
int xfd = ConnectionNumber(dpy);
|
|
while (gRunning) {
|
|
while (XPending(dpy) > 0) {
|
|
XEvent ev;
|
|
XNextEvent(dpy, &ev);
|
|
if (ev.type == Expose && ev.xexpose.count == 0) {
|
|
render();
|
|
} else if (ev.type == VisibilityNotify && visible &&
|
|
ev.xvisibility.state != VisibilityUnobscured) {
|
|
if (isAnotherPluginActive("music")) {
|
|
hideWindow();
|
|
} else {
|
|
XRaiseWindow(dpy, win);
|
|
grabPluginKeyboard(dpy, win);
|
|
render();
|
|
}
|
|
} else if (ev.type == KeyRelease) {
|
|
if (!initialSoftkeysReleased && querySoftkeysDown(dpy) == 0) {
|
|
initialSoftkeysReleased = true;
|
|
}
|
|
} else if (ev.type == KeyPress && visible) {
|
|
int64_t now = nowMs();
|
|
if (now < startupIgnoreUntilMs) continue;
|
|
|
|
KeySym sym = XLookupKeysym(&ev.xkey, 0);
|
|
unsigned int kc = ev.xkey.keycode;
|
|
|
|
bool isLSK = (kc == 135 || sym == XK_F1 || sym == XK_Menu ||
|
|
sym == XF86XK_TaskPane || sym == XF86XK_KbdLcdMenu1 ||
|
|
sym == _EVDEVK(0x246));
|
|
bool isRSK = (kc == 166 || sym == XK_F2 || sym == XF86XK_Back ||
|
|
sym == XK_Escape || sym == XF86XK_KbdLcdMenu2 ||
|
|
sym == _EVDEVK(0x247));
|
|
|
|
if (isLSK || isRSK) {
|
|
if (!initialSoftkeysReleased) continue;
|
|
int mask = querySoftkeysDown(dpy);
|
|
if (mask == 3 ||
|
|
(softkeyPending != 0 &&
|
|
((isLSK && softkeyPending == 2) ||
|
|
(isRSK && softkeyPending == 1)))) {
|
|
softkeyPending = 0;
|
|
writeSoftkeySuppress(now + 400);
|
|
hideWindow();
|
|
sendPluginCommand("xdrawer", "TOGGLE");
|
|
continue;
|
|
}
|
|
softkeyPending = isLSK ? 1 : 2;
|
|
softkeyDeadlineMs = now + 90;
|
|
continue;
|
|
}
|
|
|
|
if (isPowerKey(sym, kc)) {
|
|
hideWindow();
|
|
openPowerMenuFromPlugin(dpy);
|
|
continue;
|
|
}
|
|
|
|
if (sym == XF86XK_HangupPhone || sym == XK_Cancel) {
|
|
hideWindow();
|
|
continue;
|
|
}
|
|
|
|
char dch = mapDialKey(sym, kc, ev.xkey.state);
|
|
if (dch == '1') {
|
|
activeTab = TabId::Player;
|
|
render();
|
|
continue;
|
|
} else if (dch == '2') {
|
|
activeTab = TabId::Queue;
|
|
render();
|
|
continue;
|
|
} else if (dch == '3') {
|
|
activeTab = TabId::Browser;
|
|
if (browserItems.empty()) loadBrowserDirectory(browserDir);
|
|
render();
|
|
continue;
|
|
}
|
|
|
|
if (activeTab == TabId::Player) {
|
|
if (sym == XK_Return || sym == XK_KP_Enter || dch == '5') {
|
|
togglePlayPause();
|
|
} else if (sym == XK_Left || sym == XK_KP_Left) {
|
|
seekRelative(-5);
|
|
} else if (sym == XK_Right || sym == XK_KP_Right) {
|
|
seekRelative(5);
|
|
} else if (sym == XK_Up || sym == XK_KP_Up) {
|
|
volumePct = std::clamp(readSavedSpeakerVol() + 5, 0, 100);
|
|
applySystemSpeakerVol(volumePct);
|
|
setBanner("Volume: " + std::to_string(volumePct) + "%", 1200);
|
|
} else if (sym == XK_Down || sym == XK_KP_Down) {
|
|
volumePct = std::clamp(readSavedSpeakerVol() - 5, 0, 100);
|
|
applySystemSpeakerVol(volumePct);
|
|
setBanner("Volume: " + std::to_string(volumePct) + "%", 1200);
|
|
} else if (dch == '4') {
|
|
stepTrack(-1);
|
|
} else if (dch == '6') {
|
|
stepTrack(1);
|
|
} else if (dch == '7') {
|
|
seekRelative(-30);
|
|
} else if (dch == '9') {
|
|
seekRelative(30);
|
|
} else if (dch == '*') {
|
|
stopPlayback();
|
|
setBanner("Playback stopped");
|
|
} else if (dch == '0') {
|
|
repeatMode = static_cast<RepeatMode>(
|
|
(static_cast<int>(repeatMode) + 1) % 3);
|
|
const char* rl =
|
|
(repeatMode == RepeatMode::All)
|
|
? "Repeat: All"
|
|
: (repeatMode == RepeatMode::One ? "Repeat: One"
|
|
: "Repeat: Off");
|
|
setBanner(rl, 1400);
|
|
} else if (dch == '#') {
|
|
shuffleOn = !shuffleOn;
|
|
setBanner(std::string("Shuffle: ") + (shuffleOn ? "On" : "Off"),
|
|
1400);
|
|
}
|
|
render();
|
|
} else if (activeTab == TabId::Queue) {
|
|
if (sym == XK_Up || sym == XK_KP_Up) {
|
|
if (!queue.empty()) {
|
|
queueSelIdx = (queueSelIdx + static_cast<int>(queue.size()) - 1) %
|
|
static_cast<int>(queue.size());
|
|
}
|
|
} else if (sym == XK_Down || sym == XK_KP_Down) {
|
|
if (!queue.empty()) {
|
|
queueSelIdx = (queueSelIdx + 1) % static_cast<int>(queue.size());
|
|
}
|
|
} else if (sym == XK_Left || sym == XK_KP_Left) {
|
|
if (!queue.empty()) {
|
|
queueSelIdx = std::max(0, queueSelIdx - 5);
|
|
}
|
|
} else if (sym == XK_Right || sym == XK_KP_Right) {
|
|
if (!queue.empty()) {
|
|
queueSelIdx = std::min(static_cast<int>(queue.size()) - 1,
|
|
queueSelIdx + 5);
|
|
}
|
|
} else if (sym == XK_Return || sym == XK_KP_Enter) {
|
|
if (!queue.empty()) {
|
|
playTrackAtIndex(queueSelIdx);
|
|
activeTab = TabId::Player;
|
|
}
|
|
} else if (dch == '5') {
|
|
togglePlayPause();
|
|
} else if (dch == '*' && !queue.empty()) {
|
|
installTrackAsRingtone(queue[queueSelIdx]);
|
|
} else if (dch == '0') {
|
|
populateDefaultQueue();
|
|
setBanner("Rescanned Music (" + std::to_string(queue.size()) +
|
|
" tracks)");
|
|
}
|
|
render();
|
|
} else if (activeTab == TabId::Browser) {
|
|
if (sym == XK_Up || sym == XK_KP_Up) {
|
|
if (!browserItems.empty()) {
|
|
browserSelIdx =
|
|
(browserSelIdx + static_cast<int>(browserItems.size()) - 1) %
|
|
static_cast<int>(browserItems.size());
|
|
}
|
|
} else if (sym == XK_Down || sym == XK_KP_Down) {
|
|
if (!browserItems.empty()) {
|
|
browserSelIdx =
|
|
(browserSelIdx + 1) % static_cast<int>(browserItems.size());
|
|
}
|
|
} else if (sym == XK_Left || sym == XK_KP_Left ||
|
|
sym == XK_BackSpace || sym == XK_Delete) {
|
|
if (browserDir != "/") {
|
|
std::string prevBase = browserDir;
|
|
size_t sl = prevBase.rfind('/');
|
|
std::string prevName =
|
|
(sl != std::string::npos) ? prevBase.substr(sl + 1) : "";
|
|
std::string upDir = (sl == 0 || sl == std::string::npos)
|
|
? "/"
|
|
: prevBase.substr(0, sl);
|
|
loadBrowserDirectory(upDir, prevName);
|
|
}
|
|
} else if (sym == XK_Right || sym == XK_KP_Right ||
|
|
sym == XK_Return || sym == XK_KP_Enter) {
|
|
handleBrowserSelect(false);
|
|
} else if (dch == '5') {
|
|
togglePlayPause();
|
|
}
|
|
render();
|
|
}
|
|
}
|
|
}
|
|
|
|
if (mpvPid > 0 && ipcFd < 0) {
|
|
tryConnectIpc();
|
|
}
|
|
if (drainIpcSocket() && visible) {
|
|
render();
|
|
}
|
|
|
|
int timeoutMs = -1;
|
|
int64_t now = nowMs();
|
|
if (mpvPid > 0 && ipcFd < 0) {
|
|
timeoutMs = 35;
|
|
}
|
|
if (visible) {
|
|
if (softkeyPending != 0) {
|
|
int64_t rem = softkeyDeadlineMs - now;
|
|
if (rem <= 0) {
|
|
int pend = softkeyPending;
|
|
softkeyPending = 0;
|
|
if (querySoftkeysDown(dpy) == 3) {
|
|
writeSoftkeySuppress(now + 400);
|
|
hideWindow();
|
|
sendPluginCommand("xdrawer", "TOGGLE");
|
|
} else if (pend == 1) {
|
|
if (activeTab == TabId::Player) {
|
|
activeTab = TabId::Queue;
|
|
} else if (activeTab == TabId::Queue) {
|
|
if (!queue.empty()) {
|
|
playTrackAtIndex(queueSelIdx);
|
|
activeTab = TabId::Player;
|
|
}
|
|
} else if (activeTab == TabId::Browser) {
|
|
handleBrowserSelect(true);
|
|
}
|
|
render();
|
|
} else if (pend == 2) {
|
|
hideWindow();
|
|
}
|
|
} else {
|
|
timeoutMs = (timeoutMs < 0) ? static_cast<int>(rem)
|
|
: std::min(timeoutMs, static_cast<int>(rem));
|
|
}
|
|
}
|
|
if (!statusBanner.empty()) {
|
|
int64_t bRem = statusBannerUntilMs - now;
|
|
if (bRem <= 0) {
|
|
statusBanner.clear();
|
|
render();
|
|
} else if (timeoutMs < 0 || bRem < timeoutMs) {
|
|
timeoutMs = static_cast<int>(bRem);
|
|
}
|
|
}
|
|
if (isPlaying && !isPaused && (timeoutMs < 0 || timeoutMs > 250)) {
|
|
timeoutMs = 250;
|
|
}
|
|
}
|
|
|
|
struct pollfd pfds[3];
|
|
int nfds = 0;
|
|
pfds[nfds++] = {xfd, POLLIN, 0};
|
|
int fifoIdx = -1;
|
|
if (fifoFd >= 0) {
|
|
fifoIdx = nfds;
|
|
pfds[nfds++] = {fifoFd, POLLIN, 0};
|
|
}
|
|
int ipcIdx = -1;
|
|
if (ipcFd >= 0) {
|
|
ipcIdx = nfds;
|
|
pfds[nfds++] = {ipcFd, POLLIN, 0};
|
|
}
|
|
|
|
int pr = ::poll(pfds, nfds, timeoutMs);
|
|
if (pr > 0) {
|
|
if (ipcIdx >= 0 && (pfds[ipcIdx].revents & (POLLIN | POLLHUP | POLLERR))) {
|
|
if (drainIpcSocket() && visible) {
|
|
render();
|
|
}
|
|
}
|
|
if (fifoIdx >= 0 && (pfds[fifoIdx].revents & POLLIN)) {
|
|
for (const auto& cmd : readFifoLines(fifoFd)) {
|
|
if (cmd == "CLOSE") {
|
|
hideWindow();
|
|
} else if (cmd == "RELOAD_THEME") {
|
|
pt.reload();
|
|
if (visible) render();
|
|
} else if (cmd == "PAUSE") {
|
|
pausePlayback();
|
|
if (visible) render();
|
|
} else if (cmd == "STOP") {
|
|
stopPlayback();
|
|
if (visible) render();
|
|
} else if (cmd == "TOGGLE") {
|
|
if (visible) hideWindow();
|
|
else showWindow();
|
|
} else if (cmd == "OPEN") {
|
|
showWindow();
|
|
} else if (cmd.rfind("OPEN ", 0) == 0) {
|
|
showWindow(trimStr(cmd.substr(5)));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
hideWindow();
|
|
stopMpvDaemon();
|
|
if (fifoFd >= 0) ::close(fifoFd);
|
|
::unlink(daemonPidPath.c_str());
|
|
return 0;
|
|
}
|
|
|
|
int pluginInit(const DwmHostApi* host) {
|
|
if (host && host->spawn_plugin) {
|
|
host->spawn_plugin("music", "--preload");
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
void pluginCleanup(void) {}
|
|
|
|
} // namespace
|
|
|
|
extern "C" __attribute__((visibility("default"))) const DwmPlugin dwm_plugin_entry = {
|
|
DWM_PLUGIN_API_VERSION,
|
|
"music",
|
|
"Bananarchy Music & Tracker Player (240x320)",
|
|
pluginInit,
|
|
pluginCleanup,
|
|
nullptr,
|
|
nullptr,
|
|
nullptr,
|
|
runMusicApp
|
|
};
|