#include "phone_data.h" #include "media_utils.h" #include "monotone.h" #include "../sxmo-dwm/dwm_plugin.h" #include #include #include #include #include #include #include #include namespace { using namespace bananarchy; volatile sig_atomic_t gRunning = 1; void handleSignal(int) { gRunning = 0; } enum class ViewMode { Browser = 0, Actions = 1, TextView = 2, ImageView = 3, PropsView = 4, InputModal = 5, ConfirmDelete = 6, TextEdit = 7, RingtoneView = 8, BtSendModal = 9, }; struct BtSendTarget { std::string mac; std::string name; bool paired = false; bool connected = false; }; std::vector queryBtSendTargets(bool scanFirst = false) { std::string rfk = runCaptureCmd("/usr/sbin/rfkill list bluetooth 2>/dev/null"); if (::access("/run/bluetoothd.pid", F_OK) != 0 || rfk.find("Soft blocked: yes") != std::string::npos || rfk.find("Hard blocked: yes") != std::string::npos) { runCaptureCmd("SXMO_OS=alpine doas -n sxmo_bluetoothtoggle.sh on >/dev/null 2>&1"); } if (scanFirst) { runCaptureCmd("timeout 16 bluetoothctl --timeout 15 scan on >/dev/null 2>&1"); } std::unordered_set pairedMacs; std::unordered_set connectedMacs; auto parseSet = [](const std::string& raw, std::unordered_set& dst) { std::istringstream ss(raw); std::string line; while (std::getline(ss, line)) { if (line.rfind("Device ", 0) == 0 && line.size() >= 24) { dst.insert(line.substr(7, 17)); } } }; parseSet(runCaptureCmd("timeout 2 bluetoothctl devices Paired 2>/dev/null || " "timeout 2 bluetoothctl paired-devices 2>/dev/null"), pairedMacs); parseSet(runCaptureCmd("timeout 2 bluetoothctl devices Connected 2>/dev/null"), connectedMacs); std::vector out; std::string allRaw = runCaptureCmd("timeout 2 bluetoothctl devices 2>/dev/null"); std::istringstream ss(allRaw); std::string line; while (std::getline(ss, line)) { if (line.rfind("Device ", 0) != 0 || line.size() < 24) continue; BtSendTarget d; d.mac = line.substr(7, 17); d.name = (line.size() > 25) ? trimStr(line.substr(25)) : d.mac; d.paired = (pairedMacs.count(d.mac) > 0); d.connected = (connectedMacs.count(d.mac) > 0); out.push_back(d); } std::sort(out.begin(), out.end(), [](const BtSendTarget& a, const BtSendTarget& b) { if (a.connected != b.connected) return a.connected > b.connected; if (a.paired != b.paired) return a.paired > b.paired; return a.name < b.name; }); return out; } enum class SortMode { Name = 0, Date = 1, Size = 2, }; enum class InputAction { NewFolder = 0, NewFile = 1, Rename = 2, }; enum class TextCaseMode { Lower = 0, // abc Title = 1, // Abc Upper = 2, // ABC Num = 3, // 123 Sym = 4, // Sym }; const char* kMultiTapFile[10] = { " _-0", // 0 ".-_1,!?+@#$%~()[]{}", // 1 "abc2", // 2 "def3", // 3 "ghi4", // 4 "jkl5", // 5 "mno6", // 6 "pqrs7", // 7 "tuv8", // 8 "wxyz9" // 9 }; const char* kMultiTapEditorAlpha[11] = { " 0", // 0 kMultiTapPunct1, // 1 "abc2", // 2 "def3", // 3 "ghi4", // 4 "jkl5", // 5 "mno6", // 6 "pqrs7", // 7 "tuv8", // 8 "wxyz9", // 9 kMultiTapStar // 10 (*) }; const char* kMultiTapEditorSym[11] = { " _0", // 0 ".,:;!?-_1", // 1 "\"'`~@#2", // 2 "()[]{}<>3", // 3 "+-*/=%4", // 4 "|&^#$5", // 5 "_\\/$@6", // 6 "=<>!~7", // 7 "();,\"8", // 8 "{}[]#9", // 9 kMultiTapStar // 10 (*) }; struct FileItem { std::string name; std::string fullPath; std::string lowerName; std::string t9Name; bool isParent = false; bool isDir = false; bool isExec = false; off_t size = 0; time_t mtime = 0; mode_t mode = 0; }; void popUtf8(std::string& s) { if (s.empty()) return; while (!s.empty() && (static_cast(s.back()) & 0xC0) == 0x80) { s.pop_back(); } if (!s.empty()) s.pop_back(); } size_t prevUtf8Pos(const std::string& s, size_t pos) { if (pos == 0) return 0; if (pos > s.size()) pos = s.size(); --pos; while (pos > 0 && (static_cast(s[pos]) & 0xC0) == 0x80) { --pos; } return pos; } size_t nextUtf8Pos(const std::string& s, size_t pos) { if (pos >= s.size()) return s.size(); ++pos; while (pos < s.size() && (static_cast(s[pos]) & 0xC0) == 0x80) { ++pos; } return pos; } size_t clampUtf8Pos(const std::string& s, size_t pos) { if (pos >= s.size()) return s.size(); while (pos > 0 && (static_cast(s[pos]) & 0xC0) == 0x80) { --pos; } return pos; } std::string expandTabsForDisplay(const std::string& s) { std::string out; out.reserve(s.size()); for (char c : s) { if (c == '\t') { out += " "; } else if (static_cast(c) < 0x20) { out.push_back('?'); } else { out.push_back(c); } } return out; } 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 isImageExt(const std::string& ext) { return ext == "jpg" || ext == "jpeg" || ext == "png" || ext == "bmp" || ext == "gif" || ext == "webp" || ext == "ppm" || ext == "pgm" || ext == "pbm" || ext == "tif" || ext == "tiff" || ext == "ico" || 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" || ext == "wma" || ext == "aiff" || ext == "wv" || ext == "ape" || ext == "spx" || 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 isMediaExt(const std::string& ext) { return isAudioExt(ext) || ext == "mp4" || ext == "mkv" || ext == "webm" || ext == "avi"; } bool isGameBoyExt(const std::string& ext) { return ext == "gb" || ext == "gbc"; } bool isJ2meExt(const std::string& ext) { return ext == "jar" || ext == "jad"; } bool isYabasicExt(const std::string& ext) { return ext == "yab"; } bool isLikelyTextFile(const std::string& path, off_t size) { if (size == 0) return true; if (size > 256 * 1024) return false; std::ifstream in(path, std::ios::binary); if (!in.is_open()) return false; char buf[512]; in.read(buf, sizeof(buf)); std::streamsize n = in.gcount(); for (std::streamsize i = 0; i < n; ++i) { unsigned char c = static_cast(buf[i]); if (c == 0) { return false; } } return true; } std::string shortenPath(const std::string& path) { std::string h = getHomeDirPath(); std::string out = path; if (out == h) { out = "~"; } else if (out.rfind(h + "/", 0) == 0) { out = "~" + out.substr(h.size()); } if (out.size() > 18) { out = "..." + out.substr(out.size() - 15); } return out; } std::string formatPermissions(mode_t m) { std::string s(10, '-'); if (S_ISDIR(m)) s[0] = 'd'; else if (S_ISLNK(m)) s[0] = 'l'; if (m & S_IRUSR) s[1] = 'r'; if (m & S_IWUSR) s[2] = 'w'; if (m & S_IXUSR) s[3] = 'x'; if (m & S_IRGRP) s[4] = 'r'; if (m & S_IWGRP) s[5] = 'w'; if (m & S_IXGRP) s[6] = 'x'; if (m & S_IROTH) s[7] = 'r'; if (m & S_IWOTH) s[8] = 'w'; if (m & S_IXOTH) s[9] = 'x'; char oct[16]; std::snprintf(oct, sizeof(oct), " (%04o)", static_cast(m & 07777)); return s + oct; } bool removeRecursive(const std::string& path) { struct stat st {}; if (::lstat(path.c_str(), &st) != 0) { return false; } if (S_ISDIR(st.st_mode) && !S_ISLNK(st.st_mode)) { DIR* d = ::opendir(path.c_str()); if (d) { struct dirent* ent; while ((ent = ::readdir(d)) != nullptr) { if (std::strcmp(ent->d_name, ".") == 0 || std::strcmp(ent->d_name, "..") == 0) { continue; } removeRecursive(path + "/" + ent->d_name); } ::closedir(d); } return ::rmdir(path.c_str()) == 0; } return ::unlink(path.c_str()) == 0; } bool copyRecursive(const std::string& src, const std::string& dst) { pid_t pid = ::fork(); if (pid == 0) { execlp("cp", "cp", "-a", src.c_str(), dst.c_str(), static_cast(nullptr)); _exit(127); } else if (pid > 0) { int status = 0; ::waitpid(pid, &status, 0); return WIFEXITED(status) && WEXITSTATUS(status) == 0; } return false; } int runFilesApp(int argc, char** argv) { gRunning = 1; std::setlocale(LC_ALL, ""); XSetLocaleModifiers(""); bool isPreload = false; std::string initDir; 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] != '-' && initDir.empty()) { initDir = argv[i]; } } std::string daemonPidPath = getPluginDaemonPidPath("files"); std::string activePidPath = getRuntimeFile("xfiles.pid"); if (isPluginDaemonAlive("files")) { if (!isPreload) { sendPluginCommand("files", initDir.empty() ? "OPEN" : ("OPEN " + initDir)); } return 0; } writeIntFile(daemonPidPath, static_cast(::getpid())); int fifoFd = setupPluginDaemonFifo("files"); struct sigaction sa {}; sa.sa_handler = handleSignal; sigemptyset(&sa.sa_mask); sigaction(SIGINT, &sa, nullptr); sigaction(SIGTERM, &sa, nullptr); NeoWindow neo; if (!neo.create("xfiles", "XFiles", "Files")) { if (fifoFd >= 0) ::close(fifoFd); ::unlink(daemonPidPath.c_str()); return 1; } Display* dpy = neo.dpy; int screen = neo.screen; Visual* visual = neo.visual; Window win = neo.win; Pixmap pix = neo.pix; GC gc = neo.gc; PluginTheme& pt = neo.theme; auto& layoutMain = pt.layoutMain; auto& layoutSmall = pt.layoutSmall; auto& layoutIcon = pt.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; auto& colRed = pt.colRed; std::string homeDir = getHomeDirPath(); std::string currentDir = homeDir; // Bluetooth send modal state std::vector btTargets; int btTargetSel = 0; std::string btSendFilePath; std::string btSendFileName; ViewMode mode = ViewMode::Browser; SortMode sortMode = SortMode::Name; bool showHidden = false; std::string searchQuery; std::vector allItems; std::vector filteredItems; int selected = 0; int actionSelected = 0; int confirmSelected = 0; // Clipboard state std::string clipPath; std::string clipName; bool clipIsCut = false; // Text viewer state std::string viewingFilePath; std::string viewingFileName; std::vector textLines; int textScrollLine = 0; // Integrated GUI text editor state std::string editFilePath; std::string editFileName; std::vector editLines = {""}; int editCursorRow = 0; size_t editCursorCol = 0; int editScrollRow = 0; bool editModified = false; bool editMenuOpen = false; int editMenuSel = 0; TextCaseMode editCaseMode = TextCaseMode::Lower; int editLastTapDigit = -1; int editLastTapCycle = 0; int64_t editLastTapMs = 0; // Image viewer state constexpr int kImgCanvasW = 240; constexpr int kImgCanvasH = 232; std::vector imgCanvas(kImgCanvasW * kImgCanvasH, 0x111111); XImage* xImgPreview = XCreateImage( dpy, visual, DefaultDepth(dpy, screen), ZPixmap, 0, reinterpret_cast(imgCanvas.data()), kImgCanvasW, kImgCanvasH, 32, kImgCanvasW * 4); constexpr int kImgFullW = 240; constexpr int kImgFullH = 270; std::vector imgFullCanvas(kImgFullW * kImgFullH, 0x111111); XImage* xImgFullPreview = XCreateImage( dpy, visual, DefaultDepth(dpy, screen), ZPixmap, 0, reinterpret_cast(imgFullCanvas.data()), kImgFullW, kImgFullH, 32, kImgFullW * 4); int imgOrigW = 0; int imgOrigH = 0; 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; std::string inputValue; std::string inputTargetPath; TextCaseMode caseMode = TextCaseMode::Lower; int lastTapDigit = -1; int lastTapCycle = 0; int64_t lastTapMs = 0; std::string statusBanner; int64_t statusBannerUntilMs = 0; struct ActionEntry { int id; std::string icon; std::string label; }; std::vector actionsList; bool visible = false; int64_t openStartMs = 0; int64_t startupIgnoreUntilMs = 0; bool initialSoftkeysReleased = true; int softkeyPending = 0; int64_t softkeyDeadlineMs = 0; auto updateFilter = [&]() { filteredItems.clear(); if (searchQuery.empty()) { filteredItems = allItems; } else { std::string qLower = toLowerStr(searchQuery); for (const auto& it : allItems) { if (it.isParent) continue; if (it.lowerName.find(qLower) != std::string::npos || it.t9Name.find(searchQuery) != std::string::npos) { filteredItems.push_back(it); } } } if (selected >= static_cast(filteredItems.size())) { selected = std::max(0, static_cast(filteredItems.size()) - 1); } }; auto loadDirectory = [&](const std::string& targetDir, const std::string& selectName = "") { homeDir = getHomeDirPath(); char resolved[4096]; std::string dir = targetDir; if (::realpath(targetDir.c_str(), resolved) != nullptr) { dir = resolved; } if (isDuressMode()) { std::string root = kDuressHomeDirPath; ::mkdir(root.c_str(), 0700); if (dir != root && dir.rfind(root + "/", 0) != 0) { dir = root; } } DIR* d = ::opendir(dir.c_str()); if (!d) { statusBanner = "Cannot open directory"; statusBannerUntilMs = nowMs() + 1800; return; } currentDir = dir; allItems.clear(); std::string topLimit = isDuressMode() ? std::string(kDuressHomeDirPath) : "/"; if (currentDir != "/" && currentDir != topLimit) { FileItem parent; parent.name = ".."; size_t slash = currentDir.rfind('/'); parent.fullPath = (slash == 0 || slash == std::string::npos) ? "/" : currentDir.substr(0, slash); parent.lowerName = ".."; parent.isParent = true; parent.isDir = true; allItems.push_back(parent); } std::vector dirs; std::vector files; struct dirent* ent; while ((ent = ::readdir(d)) != nullptr) { std::string name = ent->d_name; if (name == "." || name == "..") continue; if (!showHidden && !name.empty() && name[0] == '.') continue; FileItem item; item.name = name; item.fullPath = (currentDir == "/") ? ("/" + name) : (currentDir + "/" + name); item.lowerName = toLowerStr(name); item.t9Name = toT9Digits(name); struct stat st {}; if (::stat(item.fullPath.c_str(), &st) == 0) { item.isDir = S_ISDIR(st.st_mode); item.isExec = !item.isDir && ((st.st_mode & S_IXUSR) != 0); item.size = st.st_size; item.mtime = st.st_mtim.tv_sec; item.mode = st.st_mode; } if (item.isDir) { dirs.push_back(item); } else { files.push_back(item); } } ::closedir(d); auto cmp = [&](const FileItem& a, const FileItem& b) { if (sortMode == SortMode::Date && a.mtime != b.mtime) { return a.mtime > b.mtime; } if (sortMode == SortMode::Size && a.size != b.size) { return a.size > b.size; } return a.lowerName < b.lowerName; }; std::sort(dirs.begin(), dirs.end(), cmp); std::sort(files.begin(), files.end(), cmp); allItems.insert(allItems.end(), dirs.begin(), dirs.end()); allItems.insert(allItems.end(), files.begin(), files.end()); searchQuery.clear(); updateFilter(); selected = 0; if (!selectName.empty()) { for (size_t i = 0; i < filteredItems.size(); ++i) { if (filteredItems[i].name == selectName) { selected = static_cast(i); break; } } } }; auto openTextViewer = [&](const FileItem& item) { viewingFilePath = item.fullPath; viewingFileName = item.name; textLines.clear(); textScrollLine = 0; std::ifstream in(item.fullPath); std::string line; int maxLines = 1500; while (maxLines-- > 0 && std::getline(in, line)) { if (!line.empty() && line.back() == '\r') { line.pop_back(); } // Wrap lines longer than 30 chars for clean 240px display if (line.empty()) { textLines.push_back(""); } else { for (size_t pos = 0; pos < line.size(); pos += 30) { textLines.push_back(line.substr(pos, 30)); } } } if (textLines.empty()) { textLines.push_back("(Empty file)"); } mode = ViewMode::TextView; }; constexpr int kEditVisibleRows = 10; auto syncEditorScroll = [&]() { if (editLines.empty()) { editLines.push_back(""); } editCursorRow = std::clamp(editCursorRow, 0, static_cast(editLines.size()) - 1); editCursorCol = clampUtf8Pos(editLines[editCursorRow], editCursorCol); if (editCursorRow < editScrollRow) { editScrollRow = editCursorRow; } else if (editCursorRow >= editScrollRow + kEditVisibleRows) { editScrollRow = editCursorRow - kEditVisibleRows + 1; } int maxScroll = std::max(0, static_cast(editLines.size()) - kEditVisibleRows); editScrollRow = std::clamp(editScrollRow, 0, maxScroll); }; auto openTextEditor = [&](const std::string& fullPath, const std::string& fileName) { editFilePath = fullPath; editFileName = fileName; editLines.clear(); editCursorRow = 0; editCursorCol = 0; editScrollRow = 0; editModified = false; editMenuOpen = false; editMenuSel = 0; editLastTapDigit = -1; std::ifstream in(fullPath, std::ios::binary); if (in.is_open()) { std::string line; int maxLines = 4000; while (maxLines-- > 0 && std::getline(in, line)) { if (!line.empty() && line.back() == '\r') { line.pop_back(); } for (char& c : line) { if (c == '\0') c = ' '; } editLines.push_back(line); } } if (editLines.empty()) { editLines.push_back(""); } syncEditorScroll(); mode = ViewMode::TextEdit; }; auto saveEditedFile = [&]() -> bool { std::ofstream out(editFilePath, std::ios::binary | std::ios::trunc); if (!out.is_open()) { statusBanner = "Save failed (read-only)"; statusBannerUntilMs = nowMs() + 2000; return false; } if (!(editLines.size() == 1 && editLines[0].empty())) { for (size_t i = 0; i < editLines.size(); ++i) { out.write(editLines[i].data(), static_cast(editLines[i].size())); out.put('\n'); } } out.flush(); if (!out.good()) { statusBanner = "Write error"; statusBannerUntilMs = nowMs() + 2000; return false; } editModified = false; statusBanner = "Saved: " + editFileName; statusBannerUntilMs = nowMs() + 1800; return true; }; auto openImageViewer = [&](const FileItem& item) { viewingFilePath = item.fullPath; viewingFileName = item.name; std::vector rgb; imgOrigW = 0; imgOrigH = 0; imgValid = loadImageRgb24(item.fullPath, &rgb, &imgOrigW, &imgOrigH); if (imgValid) { scaleRgb24ToBgrxCanvas(rgb.data(), imgOrigW, imgOrigH, imgCanvas.data(), kImgCanvasW, kImgCanvasH, 0x111111); scaleRgb24ToBgrxCanvas(rgb.data(), imgOrigW, imgOrigH, imgFullCanvas.data(), kImgFullW, kImgFullH, 0x111111); } else { std::fill(imgCanvas.begin(), imgCanvas.end(), 0x111111); std::fill(imgFullCanvas.begin(), imgFullCanvas.end(), 0x111111); } 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); int hp = (rvol <= 0) ? 0 : (52 + (rvol * 32 + 50) / 100); runAsyncCmd("outdev=$(cat /tmp/sxmo_audio_out_device 2>/dev/null); " "if [ \"$outdev\" = \"Bluetooth\" ]; then " " amixer -c 0 cset \"name='SPK DAC Switch'\" 0 >/dev/null 2>&1; " " wpctl set-mute @DEFAULT_AUDIO_SINK@ 0 >/dev/null 2>&1; " " wpctl set-volume @DEFAULT_AUDIO_SINK@ " + std::to_string(rvol) + "% >/dev/null 2>&1; " "elif [ \"$outdev\" = \"Headphones\" ]; then " " amixer -c 0 cset \"name='SPK DAC Switch'\" 0 >/dev/null 2>&1; " " amixer -c 0 cset \"name='EAR_S'\" 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='RX1 Digital Volume'\" " + std::to_string(hp) + " >/dev/null 2>&1; " " amixer -c 0 cset \"name='RX2 Digital Volume'\" " + std::to_string(hp) + " >/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; " "else " " 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; " "fi"); 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; std::string wallDir = homeDir + "/Pictures/Wallpapers"; std::string picDir = homeDir + "/Pictures"; if (srcPath.rfind("/usr/share/wallpapers/", 0) != 0 && srcPath.rfind(wallDir + "/", 0) != 0 && srcPath.rfind(picDir + "/", 0) != 0) { ::mkdir(picDir.c_str(), 0755); ::mkdir(wallDir.c_str(), 0755); std::string dst = wallDir + "/" + 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 + "/wallpaper", std::ios::trunc); if (ofs) ofs << targetPath << "\n"; } std::string fehFlag = "--bg-fill"; { std::ifstream ifs(cfgDir + "/wallpaper_mode"); std::string m; if (ifs && std::getline(ifs, m)) { m = toLowerStr(trimStr(m)); if (m == "max" || m == "--bg-max") fehFlag = "--bg-max"; else if (m == "scale" || m == "--bg-scale") fehFlag = "--bg-scale"; else if (m == "center" || m == "--bg-center") fehFlag = "--bg-center"; else if (m == "tile" || m == "--bg-tile") fehFlag = "--bg-tile"; } } runAsyncCmd("feh --no-fehbg " + fehFlag + " " + shellQuote(targetPath) + " >/dev/null 2>&1; " "PATH=\"$HOME/.config/sxmo/hooks:/usr/share/sxmo/default_hooks:$PATH\" " "sxmo_hook_statusbar.sh time >/dev/null 2>&1"); statusBanner = "Wallpaper set: " + fileName; statusBannerUntilMs = nowMs() + 2200; }; auto installAsRingtone = [&](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 + "/ringtone", std::ios::trunc); if (ofs) ofs << targetPath << "\n"; } statusBanner = "Ringtone set: " + fileName; 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; while (std::getline(f, line)) { if (line.find(" /media/sdcard ") != std::string::npos) { return true; } } return false; }; auto buildActionsList = [&]() { actionsList.clear(); bool hasSel = !filteredItems.empty(); bool isParent = hasSel && filteredItems[selected].isParent; bool duress = isDuressMode(); bool sdMounted = !duress && isSdCardMounted(); if (hasSel) { if (!filteredItems[selected].isDir) { std::string ext = getExtLower(filteredItems[selected].name); if (isImageExt(ext)) { actionsList.push_back({1, kIconEye, "Preview Image"}); if (!duress) { 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)) { actionsList.push_back({1, kIconGamepad, "Run in ReMEdy (J2ME)"}); if (ext == "jad") { actionsList.push_back({17, kIconEye, "View JAD Descriptor"}); } } else if (isYabasicExt(ext) && !duress) { actionsList.push_back({1, kIconTerm, "Run in Yabasic (Terminal)"}); actionsList.push_back({17, kIconEye, "View Text"}); } else { actionsList.push_back({1, kIconEye, "Open / View"}); } actionsList.push_back({25, kIconBluetooth, "Send via Bluetooth"}); actionsList.push_back({16, kIconEdit, "Edit in Text Editor"}); } else { actionsList.push_back({1, kIconFolderOpen, "Open Folder"}); } } if (!clipPath.empty()) { actionsList.push_back( {7, kIconCheck, std::string(clipIsCut ? "Move Here: " : "Paste Here: ") + clipName}); } actionsList.push_back({3, kIconPlus, "New Folder"}); actionsList.push_back({4, kIconFileText, "New Empty File"}); if (hasSel && !isParent) { if (!filteredItems[selected].isDir && !duress) { actionsList.push_back({2, kIconEdit, "Edit in nano"}); } actionsList.push_back({5, kIconEdit, "Rename"}); actionsList.push_back({6, kIconCopy, "Copy"}); actionsList.push_back({8, kIconOutCall, "Cut / Move"}); actionsList.push_back({9, kIconInfo, "Properties / Info"}); actionsList.push_back({13, kIconTrash, "Delete"}); } actionsList.push_back( {10, kIconEye, showHidden ? "Hide Dotfiles (.*)" : "Show Dotfiles (.*)"}); std::string sortLbl = "Sort: "; if (sortMode == SortMode::Name) sortLbl += "Date (#)"; else if (sortMode == SortMode::Date) sortLbl += "Size (#)"; else sortLbl += "Name (#)"; actionsList.push_back({11, kIconSort, sortLbl}); if (!duress) { if (sdMounted) { if (currentDir != "/media/sdcard") { actionsList.push_back({18, kIconFolderOpen, "Open SD Card (/media/sdcard)"}); } actionsList.push_back({19, kIconOutCall, "Unmount / Eject SD Card"}); } else { actionsList.push_back({20, kIconFolder, "Mount SD Card (/media/sdcard)"}); } actionsList.push_back({12, kIconTerm, "Open Terminal Here"}); } actionSelected = 0; }; auto hideWindow = [&]() { stopRingPreview(); if (!visible) return; writeSoftkeySuppress(nowMs() + 450); XUngrabKeyboard(dpy, CurrentTime); XUnmapWindow(dpy, win); XFlush(dpy); visible = false; ::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); } else { runAsyncArgv("xmusic", path.c_str()); } }; auto runYabasicInTerminal = [&](const std::string& path) { std::string d = currentDir; hideWindow(); runAsyncCmd("cd " + shellQuote(d) + " && exec st -e sh -c 'yabasic " + shellQuote(path) + "; rc=$?; printf \"\\n[Yabasic exited (%d) - press Enter]\" \"$rc\"; read -r _'"); }; auto openSelectedItem = [&]() { if (filteredItems.empty()) return; const FileItem item = filteredItems[selected]; if (item.isParent) { std::string prevBase = currentDir; size_t sl = prevBase.rfind('/'); std::string prevName = (sl != std::string::npos) ? prevBase.substr(sl + 1) : ""; loadDirectory(item.fullPath, prevName); return; } if (item.isDir) { loadDirectory(item.fullPath); return; } std::string ext = getExtLower(item.name); if (isImageExt(ext)) { imgFullscreen = false; openImageViewer(item); } else if (isRingtoneExt(ext)) { openRingtoneViewer(item, true); } else if (isAudioExt(ext)) { openInMusicPlayer(item.fullPath); return; } else if (isGameBoyExt(ext)) { hideWindow(); runAsyncArgv("gambatte", item.fullPath.c_str()); return; } else if (isJ2meExt(ext)) { hideWindow(); runAsyncArgv("remedy", item.fullPath.c_str()); return; } else if (isYabasicExt(ext)) { runYabasicInTerminal(item.fullPath); return; } else if (isMediaExt(ext)) { hideWindow(); runAsyncArgv("sxmo_open.sh", item.fullPath.c_str()); return; } else if (isLikelyTextFile(item.fullPath, item.size)) { openTextViewer(item); } else { buildActionsList(); mode = ViewMode::Actions; } }; auto drawPango = [&](PangoLayout* layout, XftColor* color, int x, int y, int h, const std::string& text, int maxW = -1) { return neo.drawPango(layout, color, x, y, h, text, maxW); }; auto drawSoftkeyBar = [&](const std::string& leftLabel, const std::string& centerLabel, const std::string& rightLabel) { neo.drawSoftbar(leftLabel, centerLabel, rightLabel, &colWhite); }; auto drawUI = [&]() { if (!visible) return; checkRingPreviewAlive(); pt.checkAndReload(); XSetForeground(dpy, gc, pt.spec.bgMain); XFillRectangle(dpy, pix, gc, 0, 0, kWinWidth, kWinHeight); if (mode == ViewMode::Browser) { XSetForeground(dpy, gc, pt.spec.bgHeader); XFillRectangle(dpy, pix, gc, 0, 0, kWinWidth, 38); XSetForeground(dpy, gc, pt.spec.border); XDrawLine(dpy, pix, gc, 0, 37, kWinWidth, 37); if (searchQuery.empty()) { drawPango(layoutIcon, &colYellow, 6, 2, 34, kIconFolderOpen); drawPango(layoutMain, &colWhite, 28, 2, 34, shortenPath(currentDir), 156); const char* sTag = (sortMode == SortMode::Name) ? "N" : (sortMode == SortMode::Date ? "T" : "S"); std::string badge = std::string("[") + sTag + ":" + std::to_string(filteredItems.size()) + "]"; pango_layout_set_width(layoutSmall, -1); pango_layout_set_text(layoutSmall, badge.c_str(), static_cast(badge.size())); int bw = 0, bhh = 0; pango_layout_get_pixel_size(layoutSmall, &bw, &bhh); drawPango(layoutSmall, &colMuted, kWinWidth - bw - 6, 2, 34, badge); } else { drawPango(layoutIcon, &colBlue, 6, 2, 34, kIconSearch); drawPango(layoutMain, &colYellow, 28, 2, 34, searchQuery, 160); std::string cnt = std::to_string(filteredItems.size()); pango_layout_set_width(layoutSmall, -1); pango_layout_set_text(layoutSmall, cnt.c_str(), static_cast(cnt.size())); int bw = 0, bhh = 0; pango_layout_get_pixel_size(layoutSmall, &bw, &bhh); drawPango(layoutSmall, &colMuted, kWinWidth - bw - 6, 2, 34, cnt); } const int listY = 38; const int rowH = 33; const int visibleRows = 7; if (filteredItems.empty()) { drawPango(layoutMain, &colMuted, 16, 120, 24, "Empty folder", 208); } else { int scroll = 0; if (selected >= visibleRows) { scroll = selected - visibleRows + 1; } for (int i = 0; i < visibleRows; ++i) { int idx = scroll + i; if (idx >= static_cast(filteredItems.size())) break; const auto& it = filteredItems[idx]; int ry = listY + i * rowH; bool isSel = (idx == selected); if (isSel) { XSetForeground(dpy, gc, pt.spec.selBg); XFillRectangle(dpy, pix, gc, 0, ry, kWinWidth, rowH - 1); XSetForeground(dpy, gc, pt.spec.accentAlt); XDrawLine(dpy, pix, gc, 0, ry, kWinWidth, ry); } else { XSetForeground(dpy, gc, (i % 2 == 0) ? pt.spec.bgAltEven : pt.spec.bgAltOdd); XFillRectangle(dpy, pix, gc, 0, ry, kWinWidth, rowH - 1); } const char* ic = kIconFile; XftColor* icCol = &colMuted; if (it.isParent) { ic = kIconBackspace; icCol = &colBlue; } else if (it.isDir) { ic = kIconFolder; icCol = &colYellow; } else { std::string ext = getExtLower(it.name); if (isImageExt(ext)) { ic = kIconImage; icCol = &colGreen; } else if (isRingtoneExt(ext)) { ic = kIconBell; icCol = &colYellow; } else if (isMediaExt(ext)) { ic = kIconMusic; icCol = &colBlue; } else if (isGameBoyExt(ext) || isJ2meExt(ext)) { ic = kIconGamepad; icCol = &colYellow; } else if (isYabasicExt(ext) || it.isExec || ext == "sh") { ic = kIconTerm; icCol = &colOrange; } else { ic = kIconFileText; icCol = &colLight; } } drawPango(layoutIcon, icCol, 6, ry, rowH, ic); std::string dispName = it.isParent ? ".. (Up)" : (it.isDir ? (it.name + "/") : it.name); drawPango(layoutMain, &colWhite, 28, ry, rowH, dispName, 154); std::string meta = it.isParent ? "" : (it.isDir ? "DIR" : formatFileSize(it.size)); if (!meta.empty()) { pango_layout_set_width(layoutSmall, -1); pango_layout_set_text(layoutSmall, meta.c_str(), static_cast(meta.size())); int mw = 0, mhh = 0; pango_layout_get_pixel_size(layoutSmall, &mw, &mhh); drawPango(layoutSmall, isSel ? &colLight : &colMuted, kWinWidth - mw - 6, ry, rowH, meta); } } } drawSoftkeyBar("Actions", "Open", searchQuery.empty() ? "Close" : "Clear"); } else if (mode == ViewMode::Actions) { XSetForeground(dpy, gc, pt.spec.bgHeader); XFillRectangle(dpy, pix, gc, 0, 0, kWinWidth, 34); drawPango(layoutIcon, &colBlue, 6, 0, 34, kIconList); drawPango(layoutMain, &colWhite, 28, 0, 34, "File Actions", 200); const int listY = 36; const int rowH = 33; const int visibleRows = 7; int scroll = 0; if (actionSelected >= visibleRows) { scroll = actionSelected - visibleRows + 1; } for (int i = 0; i < visibleRows; ++i) { int idx = scroll + i; if (idx >= static_cast(actionsList.size())) break; int ry = listY + i * rowH; bool isSel = (idx == actionSelected); XSetForeground(dpy, gc, isSel ? pt.spec.selBg : pt.spec.bgMain); XFillRectangle(dpy, pix, gc, 0, ry, kWinWidth, rowH - 1); drawPango(layoutIcon, isSel ? &colYellow : &colBlue, 8, ry, rowH, actionsList[idx].icon); drawPango(layoutMain, &colWhite, 32, ry, rowH, actionsList[idx].label, 202); } drawSoftkeyBar("Select", "Select", "Back"); } else if (mode == ViewMode::TextView) { XSetForeground(dpy, gc, pt.spec.bgHeader); XFillRectangle(dpy, pix, gc, 0, 0, kWinWidth, 32); drawPango(layoutIcon, &colBlue, 6, 0, 32, kIconFileText); drawPango(layoutMain, &colWhite, 28, 0, 32, viewingFileName, 150); std::string posStr = std::to_string(textScrollLine + 1) + "/" + std::to_string(textLines.size()); pango_layout_set_width(layoutSmall, -1); pango_layout_set_text(layoutSmall, posStr.c_str(), static_cast(posStr.size())); int pw = 0, phh = 0; pango_layout_get_pixel_size(layoutSmall, &pw, &phh); drawPango(layoutSmall, &colMuted, kWinWidth - pw - 6, 0, 32, posStr); const int startY = 36; const int lineH = 18; const int maxVis = 12; for (int i = 0; i < maxVis; ++i) { int idx = textScrollLine + i; if (idx >= static_cast(textLines.size())) break; drawPango(layoutSmall, &colLight, 6, startY + i * lineH, lineH, textLines[idx], kWinWidth - 12); } drawSoftkeyBar("Edit", "Down", "Back"); } else if (mode == ViewMode::ImageView) { if (imgFullscreen) { XPutImage(dpy, pix, gc, xImgFullPreview, 0, 0, 0, 0, kImgFullW, kImgFullH); } else { XSetForeground(dpy, gc, pt.spec.bgHeader); XFillRectangle(dpy, pix, gc, 0, 0, kWinWidth, 36); drawPango(layoutIcon, &colGreen, 6, 1, 18, kIconImage); drawPango(layoutMain, &colWhite, 28, 0, 20, viewingFileName, 145); std::string dim = imgValid ? (std::to_string(imgOrigW) + "x" + std::to_string(imgOrigH) + " ([*] Full)") : "Decode failed"; drawPango(layoutSmall, &colMuted, 28, 19, 15, dim, 200); XPutImage(dpy, pix, gc, xImgPreview, 0, 0, 0, 36, kImgCanvasW, kImgCanvasH); } drawSoftkeyBar("Set Wall", "Next", imgFullscreen ? "Header" : "Back"); } else if (mode == ViewMode::PropsView && !filteredItems.empty()) { const auto& it = filteredItems[selected]; XSetForeground(dpy, gc, pt.spec.bgHeader); XFillRectangle(dpy, pix, gc, 0, 0, kWinWidth, 34); drawPango(layoutIcon, &colBlue, 6, 0, 34, kIconInfo); drawPango(layoutMain, &colWhite, 28, 0, 34, "Properties", 200); drawPango(layoutSmall, &colMuted, 8, 42, 16, "Name:"); drawPango(layoutMain, &colWhite, 8, 58, 22, it.name, 224); drawPango(layoutSmall, &colMuted, 8, 86, 16, "Path:"); drawPango(layoutSmall, &colLight, 8, 102, 20, it.fullPath, 224); drawPango(layoutSmall, &colMuted, 8, 128, 16, "Size:"); drawPango(layoutMain, &colYellow, 8, 144, 22, formatFileSize(it.size) + " (" + std::to_string(it.size) + " B)", 224); drawPango(layoutSmall, &colMuted, 8, 172, 16, "Permissions:"); drawPango(layoutSmall, &colLight, 8, 188, 20, formatPermissions(it.mode), 224); struct tm tmM {}; localtime_r(&it.mtime, &tmM); char tbuf[32]; std::strftime(tbuf, sizeof(tbuf), "%Y-%m-%d %H:%M:%S", &tmM); drawPango(layoutSmall, &colMuted, 8, 214, 16, "Modified:"); drawPango(layoutSmall, &colLight, 8, 230, 20, tbuf, 224); drawSoftkeyBar("Back", "Back", "Back"); } else if (mode == ViewMode::InputModal) { XSetForeground(dpy, gc, pt.spec.bgHeader); XFillRectangle(dpy, pix, gc, 0, 0, kWinWidth, 36); drawPango(layoutIcon, &colBlue, 6, 0, 36, kIconEdit); drawPango(layoutMain, &colWhite, 28, 0, 36, inputTitle, 145); const char* mBadge = "[abc]"; if (isExternalKeyboardActive()) mBadge = "[KBD]"; else if (caseMode == TextCaseMode::Title) mBadge = "[Abc]"; else if (caseMode == TextCaseMode::Upper) mBadge = "[ABC]"; else if (caseMode == TextCaseMode::Num) mBadge = "[123]"; drawPango(layoutSmall, &colYellow, kWinWidth - 46, 0, 36, mBadge); XSetForeground(dpy, gc, pt.spec.bgInputFocus); XFillRectangle(dpy, pix, gc, 10, 74, kWinWidth - 20, 38); XSetForeground(dpy, gc, pt.spec.accentAlt); XDrawRectangle(dpy, pix, gc, 10, 74, kWinWidth - 21, 37); std::string modalDisp = tailFitPangoText(layoutMain, inputValue + "|", kWinWidth - 32); drawPango(layoutMain, &colWhite, 16, 74, 38, modalDisp, kWinWidth - 32); if (lastTapDigit >= 0 && lastTapDigit <= 9 && (nowMs() - lastTapMs) <= 850) { std::string cand = formatMultiTapBar( std::to_string(lastTapDigit) + ":", kMultiTapFile[lastTapDigit], lastTapCycle, caseMode == TextCaseMode::Upper); drawPango(layoutSmall, &colYellow, 10, 126, 20, cand, 220); } else { drawPango(layoutSmall, &colMuted, 10, 126, 20, "#:Mode *:Punct Right:Next", 220); } drawSoftkeyBar("Save", "Save", inputValue.empty() ? "Cancel" : "Del"); } else if (mode == ViewMode::ConfirmDelete && !filteredItems.empty()) { const auto& it = filteredItems[selected]; XSetForeground(dpy, gc, pt.spec.bgHeader); XFillRectangle(dpy, pix, gc, 0, 0, kWinWidth, 36); drawPango(layoutIcon, &colRed, 8, 0, 36, kIconTrash); drawPango(layoutMain, &colWhite, 30, 0, 36, "Delete Item?", 200); drawPango(layoutMain, &colWhite, 14, 68, 26, it.name, 212); drawPango(layoutSmall, &colMuted, 14, 98, 22, it.isDir ? "Directory and all contents" : "File will be permanently", 212); drawPango(layoutSmall, &colMuted, 14, 118, 22, it.isDir ? "will be deleted!" : "deleted.", 212); for (int i = 0; i < 2; ++i) { int ry = 164 + i * 40; bool isSel = (confirmSelected == i); XSetForeground( dpy, gc, isSel ? (i == 1 ? pt.spec.dangerBg : pt.spec.selBg) : pt.spec.bgButton); XFillRectangle(dpy, pix, gc, 16, ry, kWinWidth - 32, 34); drawPango(layoutMain, &colWhite, 28, ry, 34, i == 0 ? "No, Keep Item" : "Yes, Delete", 184); } drawSoftkeyBar("Select", "Confirm", "Cancel"); } else if (mode == ViewMode::TextEdit) { syncEditorScroll(); XSetForeground(dpy, gc, pt.spec.bgHeader); XFillRectangle(dpy, pix, gc, 0, 0, kWinWidth, 32); XSetForeground(dpy, gc, pt.spec.border); XDrawLine(dpy, pix, gc, 0, 31, kWinWidth, 31); drawPango(layoutIcon, editModified ? &colOrange : &colBlue, 5, 0, 32, kIconEdit); std::string titleDisp = (editModified ? "*" : "") + editFileName; drawPango(layoutMain, &colWhite, 25, 0, 32, titleDisp, 114); const char* mBadge = "[abc]"; if (isExternalKeyboardActive()) mBadge = "[KBD]"; else if (editCaseMode == TextCaseMode::Title) mBadge = "[Abc]"; else if (editCaseMode == TextCaseMode::Upper) mBadge = "[ABC]"; else if (editCaseMode == TextCaseMode::Num) mBadge = "[123]"; else if (editCaseMode == TextCaseMode::Sym) mBadge = "[Sym]"; std::string rightHdr = std::to_string(editCursorRow + 1) + ":" + std::to_string(editCursorCol + 1) + " " + mBadge; pango_layout_set_width(layoutSmall, -1); pango_layout_set_text(layoutSmall, rightHdr.c_str(), static_cast(rightHdr.size())); int rhw = 0, rhh = 0; pango_layout_get_pixel_size(layoutSmall, &rhw, &rhh); drawPango(layoutSmall, &colYellow, kWinWidth - rhw - 5, 0, 32, rightHdr); const int startY = 33; const int rowH = 21; const int gutterW = 28; XSetForeground(dpy, gc, pt.spec.bgAltOdd); XFillRectangle(dpy, pix, gc, 0, startY, gutterW, kEditVisibleRows * rowH); XSetForeground(dpy, gc, pt.spec.divider); XDrawLine(dpy, pix, gc, gutterW, startY, gutterW, startY + kEditVisibleRows * rowH); int64_t tCur = nowMs(); bool tapActive = (editLastTapDigit != -1 && (tCur - editLastTapMs) <= 850); for (int i = 0; i < kEditVisibleRows; ++i) { int idx = editScrollRow + i; if (idx >= static_cast(editLines.size())) break; int ry = startY + i * rowH; bool isCurRow = (idx == editCursorRow); if (isCurRow) { XSetForeground(dpy, gc, pt.spec.bgInputFocus); XFillRectangle(dpy, pix, gc, gutterW + 1, ry, kWinWidth - gutterW - 1, rowH); } std::string lnStr = std::to_string(idx + 1); drawPango(layoutSmall, isCurRow ? &colYellow : &colMuted, 3, ry, rowH, lnStr, gutterW - 4); const std::string& rawLine = editLines[idx]; size_t sliceStart = 0; int cx = 0; const int maxLineTextW = kWinWidth - gutterW - 10; if (isCurRow) { size_t curByte = static_cast(clampUtf8Pos(rawLine, editCursorCol)); if (curByte > 22) { sliceStart = static_cast(clampUtf8Pos(rawLine, editCursorCol - 22)); } while (sliceStart < curByte) { std::string beforeCur = expandTabsForDisplay( rawLine.substr(sliceStart, curByte - sliceStart)); pango_layout_set_width(layoutSmall, -1); pango_layout_set_ellipsize(layoutSmall, PANGO_ELLIPSIZE_NONE); pango_layout_set_text(layoutSmall, beforeCur.c_str(), static_cast(beforeCur.size())); int chh = 0; pango_layout_get_pixel_size(layoutSmall, &cx, &chh); if (cx <= maxLineTextW - 6) break; sliceStart = static_cast( nextUtf8Pos(rawLine, static_cast(sliceStart))); } } std::string rawSlice = rawLine.substr(sliceStart); std::string dispSlice = expandTabsForDisplay(rawSlice); drawPango(layoutSmall, isCurRow ? &colWhite : &colLight, gutterW + 4, ry, rowH, dispSlice, kWinWidth - gutterW - 8); if (isCurRow && !editMenuOpen) { int curX = std::min(kWinWidth - 4, gutterW + 4 + cx); XSetForeground(dpy, gc, tapActive ? pt.spec.success : pt.spec.accentAlt); XFillRectangle(dpy, pix, gc, curX, ry + 3, 2, rowH - 6); } } // Bottom candidate / hint bar const int hintY = kWinHeight - 46; XSetForeground(dpy, gc, pt.spec.bgAltOdd); XFillRectangle(dpy, pix, gc, 0, hintY, kWinWidth, 20); XSetForeground(dpy, gc, pt.spec.divider); XDrawLine(dpy, pix, gc, 0, hintY, kWinWidth, hintY); if (tapActive && editLastTapDigit >= 0 && editLastTapDigit <= 10) { const char* table = (editCaseMode == TextCaseMode::Sym) ? kMultiTapEditorSym[editLastTapDigit] : kMultiTapEditorAlpha[editLastTapDigit]; std::string pref = (editLastTapDigit == 10) ? "*:" : (std::to_string(editLastTapDigit) + ":"); std::string cand = formatMultiTapBar( pref, table, editLastTapCycle, editCaseMode == TextCaseMode::Upper); drawPango(layoutSmall, &colYellow, 6, hintY, 20, cand, kWinWidth - 12); } else { drawPango(layoutSmall, &colMuted, 6, hintY, 20, "#:Mode OK:Newline *:Sym Menu:Save", kWinWidth - 12); } if (editMenuOpen) { static const char* kEditMenuLabels[7] = { "Save File", "Save & Close", "Insert New Line", "Insert Space", "Duplicate Line", "Delete Line", "Close Without Saving" }; const int mW = 212; const int mRowH = 26; const int mH = 28 + 7 * mRowH + 6; const int mX = (kWinWidth - mW) / 2; const int mY = 26; XSetForeground(dpy, gc, pt.spec.bgHeader); XFillRectangle(dpy, pix, gc, mX, mY, mW, mH); XSetForeground(dpy, gc, pt.spec.accentAlt); XDrawRectangle(dpy, pix, gc, mX, mY, mW - 1, mH - 1); drawPango(layoutMain, &colYellow, mX + 10, mY + 2, 24, "Editor Menu", mW - 20); XSetForeground(dpy, gc, pt.spec.divider); XDrawLine(dpy, pix, gc, mX + 1, mY + 26, mX + mW - 2, mY + 26); for (int i = 0; i < 7; ++i) { int ry = mY + 28 + i * mRowH; bool isSel = (i == editMenuSel); if (isSel) { XSetForeground( dpy, gc, (i == 6 && editModified) ? pt.spec.dangerBg : pt.spec.selBg); XFillRectangle(dpy, pix, gc, mX + 2, ry, mW - 4, mRowH - 1); } drawPango(layoutSmall, &colWhite, mX + 12, ry, mRowH, kEditMenuLabels[i], mW - 24); } drawSoftkeyBar("Select", "Select", "Back"); } else { bool docEmpty = (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"); } else if (mode == ViewMode::BtSendModal) { XSetForeground(dpy, gc, pt.spec.bgHeader); XFillRectangle(dpy, pix, gc, 0, 0, kWinWidth, 28); drawPango(layoutMain, &colYellow, 6, 0, 28, std::string(kIconBluetooth) + " Send via Bluetooth", kWinWidth - 12); XSetForeground(dpy, gc, pt.spec.border); XDrawLine(dpy, pix, gc, 0, 27, kWinWidth, 27); XSetForeground(dpy, gc, pt.spec.bgAltOdd); XFillRectangle(dpy, pix, gc, 6, 32, kWinWidth - 12, 22); drawPango(layoutSmall, &colLight, 10, 32, 22, "File: " + btSendFileName, kWinWidth - 20); if (btTargets.empty()) { drawPango(layoutMain, &colMuted, 12, 110, 24, "No Bluetooth devices found", kWinWidth - 24); drawPango(layoutSmall, &colMuted, 12, 136, 20, "Press * to scan for nearby devices", kWinWidth - 24); } else { btTargetSel = std::clamp( btTargetSel, 0, static_cast(btTargets.size()) - 1); const int listY = 58; const int rowH = 30; const int maxVis = 6; int startIdx = std::max(0, btTargetSel - maxVis / 2); if (startIdx + maxVis > static_cast(btTargets.size())) { startIdx = std::max(0, static_cast(btTargets.size()) - maxVis); } for (int i = 0; i < maxVis; ++i) { int idx = startIdx + i; if (idx >= static_cast(btTargets.size())) break; int ry = listY + i * rowH; bool isSel = (idx == btTargetSel); XSetForeground(dpy, gc, isSel ? pt.spec.selBg : pt.spec.bgAltEven); XFillRectangle(dpy, pix, gc, 6, ry, kWinWidth - 12, rowH - 2); if (isSel) { XSetForeground(dpy, gc, pt.spec.accent); XFillRectangle(dpy, pix, gc, 6, ry, 3, rowH - 2); } std::string label = std::string(kIconBluetooth) + " " + btTargets[idx].name; drawPango(layoutMain, isSel ? &colWhite : &colLight, 12, ry, 18, label, kWinWidth - 74); std::string st = btTargets[idx].connected ? "Connected" : (btTargets[idx].paired ? "Paired" : "Nearby"); drawPango(layoutSmall, btTargets[idx].connected ? &colGreen : &colMuted, 12, ry + 14, 14, btTargets[idx].mac + " [" + st + "]", kWinWidth - 24); } } drawPango(layoutSmall, &colMuted, 8, 242, 18, "*:Scan Bluetooth OK:Send file", kWinWidth - 16); drawSoftkeyBar(btTargets.empty() ? "Scan [*]" : "Send", btTargets.empty() ? "Scan" : "Send", "Cancel"); } int64_t tNow = nowMs(); if (!statusBanner.empty() && tNow < statusBannerUntilMs) { XSetForeground(dpy, gc, pt.spec.bgToast); XFillRectangle(dpy, pix, gc, 8, kWinHeight - 58, kWinWidth - 16, 28); XSetForeground(dpy, gc, pt.spec.info); XDrawRectangle(dpy, pix, gc, 8, kWinHeight - 58, kWinWidth - 17, 27); drawPango(layoutSmall, &colWhite, 14, kWinHeight - 58, 28, statusBanner, kWinWidth - 28); } XCopyArea(dpy, pix, win, gc, 0, 0, kWinWidth, kWinHeight, 0, 0); XFlush(dpy); }; auto showWindow = [&](const std::string& dirArg) { writeIntFile(activePidPath, static_cast(::getpid())); closeOtherPlugins("files"); stopRingPreview(); mode = ViewMode::Browser; 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); } else { XRaiseWindow(dpy, win); } grabPluginKeyboard(dpy, win); openStartMs = nowMs(); startupIgnoreUntilMs = openStartMs + 180; initialSoftkeysReleased = (querySoftkeysDown(dpy) == 0); softkeyPending = 0; drawUI(); }; auto commitModalTap = [&](int digit) { const char* chars = kMultiTapFile[digit]; int len = static_cast(std::strlen(chars)); if (len <= 0) return; int64_t t = nowMs(); if (caseMode == TextCaseMode::Num) { inputValue.push_back(static_cast('0' + digit)); lastTapDigit = -1; return; } bool sameKey = (lastTapDigit == digit && (t - lastTapMs) <= 850 && !inputValue.empty()); if (sameKey) { lastTapCycle = (lastTapCycle + 1) % len; popUtf8(inputValue); } else { lastTapDigit = digit; lastTapCycle = 0; } lastTapMs = t; char ch = chars[lastTapCycle]; if (std::isalpha(static_cast(ch))) { if (caseMode == TextCaseMode::Upper) { ch = static_cast(std::toupper(static_cast(ch))); } else if (caseMode == TextCaseMode::Title && inputValue.empty()) { ch = static_cast(std::toupper(static_cast(ch))); } } inputValue.push_back(ch); }; auto insertEditorStr = [&](const std::string& s) { if (s.empty()) return; if (editLines.empty()) editLines.push_back(""); editCursorRow = std::clamp(editCursorRow, 0, static_cast(editLines.size()) - 1); std::string& line = editLines[editCursorRow]; editCursorCol = clampUtf8Pos(line, editCursorCol); line.insert(static_cast(editCursorCol), s); editCursorCol += static_cast(s.size()); editModified = true; syncEditorScroll(); }; auto deleteEditorCharBefore = [&]() { editLastTapDigit = -1; if (editLines.empty()) { editLines.push_back(""); editCursorRow = 0; editCursorCol = 0; return; } editCursorRow = std::clamp(editCursorRow, 0, static_cast(editLines.size()) - 1); std::string& line = editLines[editCursorRow]; editCursorCol = clampUtf8Pos(line, editCursorCol); if (editCursorCol > 0) { int prevPos = prevUtf8Pos(line, editCursorCol); line.erase(static_cast(prevPos), static_cast(editCursorCol - prevPos)); editCursorCol = prevPos; editModified = true; } else if (editCursorRow > 0) { int prevLen = static_cast(editLines[editCursorRow - 1].size()); editLines[editCursorRow - 1] += line; editLines.erase(editLines.begin() + editCursorRow); editCursorRow--; editCursorCol = prevLen; editModified = true; } syncEditorScroll(); }; auto insertEditorNewline = [&]() { editLastTapDigit = -1; if (editLines.empty()) editLines.push_back(""); editCursorRow = std::clamp(editCursorRow, 0, static_cast(editLines.size()) - 1); std::string& line = editLines[editCursorRow]; editCursorCol = clampUtf8Pos(line, editCursorCol); std::string tail = line.substr(static_cast(editCursorCol)); line.erase(static_cast(editCursorCol)); editLines.insert(editLines.begin() + editCursorRow + 1, tail); editCursorRow++; editCursorCol = 0; editModified = true; syncEditorScroll(); }; auto commitEditorTap = [&](int keyIdx) { if (keyIdx < 0 || keyIdx > 10) return; if (editLines.empty()) editLines.push_back(""); editCursorRow = std::clamp(editCursorRow, 0, static_cast(editLines.size()) - 1); std::string& line = editLines[editCursorRow]; editCursorCol = clampUtf8Pos(line, editCursorCol); if (editCaseMode == TextCaseMode::Num) { editLastTapDigit = -1; char c = (keyIdx == 10) ? '*' : static_cast('0' + keyIdx); insertEditorStr(std::string(1, c)); return; } int64_t t = nowMs(); const char* chars = (editCaseMode == TextCaseMode::Sym) ? kMultiTapEditorSym[keyIdx] : kMultiTapEditorAlpha[keyIdx]; int len = static_cast(std::strlen(chars)); if (len <= 0) return; bool replacePrev = (keyIdx == editLastTapDigit && (t - editLastTapMs) <= 850 && editCursorCol > 0); if (replacePrev) { int prevPos = prevUtf8Pos(line, editCursorCol); line.erase(static_cast(prevPos), static_cast(editCursorCol - prevPos)); editCursorCol = prevPos; editLastTapCycle = (editLastTapCycle + 1) % len; } else { editLastTapDigit = keyIdx; editLastTapCycle = 0; } editLastTapMs = t; char ch = chars[editLastTapCycle]; if (std::isalpha(static_cast(ch))) { if (editCaseMode == TextCaseMode::Upper) { ch = static_cast(std::toupper(static_cast(ch))); } else if (editCaseMode == TextCaseMode::Title) { bool atWordStart = (editCursorCol == 0); if (!atWordStart && editCursorCol > 0) { unsigned char prevCh = static_cast(line[editCursorCol - 1]); atWordStart = !std::isalnum(prevCh) && prevCh != '_'; } if (atWordStart) { ch = static_cast(std::toupper(static_cast(ch))); } } } line.insert(static_cast(editCursorCol), 1, ch); editCursorCol += 1; editModified = true; syncEditorScroll(); }; auto executeEditorMenuAction = [&](int menuIdx) { editMenuOpen = false; editLastTapDigit = -1; if (menuIdx == 0) { saveEditedFile(); } else if (menuIdx == 1) { if (saveEditedFile()) { loadDirectory(currentDir, editFileName); mode = ViewMode::Browser; } } else if (menuIdx == 2) { insertEditorNewline(); } else if (menuIdx == 3) { insertEditorStr(" "); } else if (menuIdx == 4) { if (editLines.empty()) editLines.push_back(""); editCursorRow = std::clamp(editCursorRow, 0, static_cast(editLines.size()) - 1); std::string copyLine = editLines[editCursorRow]; editLines.insert(editLines.begin() + editCursorRow + 1, copyLine); editCursorRow++; editCursorCol = clampUtf8Pos(editLines[editCursorRow], editCursorCol); editModified = true; syncEditorScroll(); } else if (menuIdx == 5) { if (editLines.size() <= 1) { editLines = {""}; editCursorRow = 0; editCursorCol = 0; } else { editCursorRow = std::clamp(editCursorRow, 0, static_cast(editLines.size()) - 1); editLines.erase(editLines.begin() + editCursorRow); if (editCursorRow >= static_cast(editLines.size())) { editCursorRow = static_cast(editLines.size()) - 1; } editCursorCol = clampUtf8Pos(editLines[editCursorRow], editCursorCol); } editModified = true; syncEditorScroll(); } else if (menuIdx == 6) { loadDirectory(currentDir, editFileName); mode = ViewMode::Browser; } }; auto executeAction = [&](int actId) { if (actId == 1) { mode = ViewMode::Browser; openSelectedItem(); } else if (actId == 2 && !filteredItems.empty()) { std::string p = filteredItems[selected].fullPath; hideWindow(); runAsyncCmd("st -e nano " + shellQuote(p)); } else if (actId == 3) { inputAction = InputAction::NewFolder; inputTitle = "New Folder"; inputValue.clear(); lastTapDigit = -1; mode = ViewMode::InputModal; } else if (actId == 4) { inputAction = InputAction::NewFile; inputTitle = "New File"; inputValue.clear(); lastTapDigit = -1; mode = ViewMode::InputModal; } else if (actId == 5 && !filteredItems.empty()) { inputAction = InputAction::Rename; inputTitle = "Rename"; inputValue = filteredItems[selected].name; inputTargetPath = filteredItems[selected].fullPath; lastTapDigit = -1; mode = ViewMode::InputModal; } else if (actId == 6 && !filteredItems.empty()) { clipPath = filteredItems[selected].fullPath; clipName = filteredItems[selected].name; clipIsCut = false; statusBanner = "Copied: " + clipName; statusBannerUntilMs = nowMs() + 1800; mode = ViewMode::Browser; } else if (actId == 8 && !filteredItems.empty()) { clipPath = filteredItems[selected].fullPath; clipName = filteredItems[selected].name; clipIsCut = true; statusBanner = "Cut: " + clipName; statusBannerUntilMs = nowMs() + 1800; mode = ViewMode::Browser; } else if (actId == 7 && !clipPath.empty()) { std::string dst = (currentDir == "/") ? ("/" + clipName) : (currentDir + "/" + clipName); bool ok = false; if (clipIsCut) { ok = (::rename(clipPath.c_str(), dst.c_str()) == 0); if (!ok && copyRecursive(clipPath, dst)) { removeRecursive(clipPath); ok = true; } if (ok) clipPath.clear(); } else { ok = copyRecursive(clipPath, dst); } statusBanner = ok ? "Paste complete" : "Paste failed"; statusBannerUntilMs = nowMs() + 1800; loadDirectory(currentDir, clipName); mode = ViewMode::Browser; } else if (actId == 9 && !filteredItems.empty()) { mode = ViewMode::PropsView; } else if (actId == 10) { showHidden = !showHidden; loadDirectory(currentDir); mode = ViewMode::Browser; } else if (actId == 11) { sortMode = static_cast((static_cast(sortMode) + 1) % 3); loadDirectory(currentDir); mode = ViewMode::Browser; } else if (actId == 12) { std::string d = currentDir; hideWindow(); runAsyncCmd("cd " + shellQuote(d) + " && exec st"); } else if (actId == 13 && !filteredItems.empty()) { confirmSelected = 0; mode = ViewMode::ConfirmDelete; } else if (actId == 14 && !filteredItems.empty()) { installAsWallpaper(filteredItems[selected].fullPath, filteredItems[selected].name); mode = ViewMode::Browser; } else if (actId == 15 && !filteredItems.empty()) { 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); } else if (actId == 17 && !filteredItems.empty()) { openTextViewer(filteredItems[selected]); } else if (actId == 18) { loadDirectory("/media/sdcard"); mode = ViewMode::Browser; } else if (actId == 19) { if (currentDir.rfind("/media/sdcard", 0) == 0) { loadDirectory(homeDir); } int rc = std::system("sxmo_sdcard.sh unmount >/dev/null 2>&1"); loadDirectory(currentDir); statusBanner = (rc == 0 && !isSdCardMounted()) ? "SD card unmounted" : "Unmount failed (busy)"; statusBannerUntilMs = nowMs() + 2200; mode = ViewMode::Browser; } else if (actId == 20) { mode = ViewMode::Browser; statusBanner = "Scanning SD card slot..."; statusBannerUntilMs = nowMs() + 2500; drawUI(); int rc = std::system("sxmo_sdcard.sh mount >/dev/null 2>&1"); if (rc == 0 && isSdCardMounted()) { loadDirectory("/media/sdcard"); statusBanner = "SD card mounted"; } else { loadDirectory(currentDir); statusBanner = "No SD card detected"; } statusBannerUntilMs = nowMs() + 2200; } else if (actId == 25 && !filteredItems.empty()) { btSendFilePath = filteredItems[selected].fullPath; btSendFileName = filteredItems[selected].name; btTargets = queryBtSendTargets(false); btTargetSel = 0; mode = ViewMode::BtSendModal; } }; auto stepImageInFolder = [&](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 && isImageExt(getExtLower(filteredItems[idx].name))) { selected = idx; openImageViewer(filteredItems[selected]); return; } } }; 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) { buildActionsList(); mode = ViewMode::Actions; } else { if (!searchQuery.empty()) { popUtf8(searchQuery); updateFilter(); } else { hideWindow(); return; } } } else if (mode == ViewMode::Actions) { if (isLeft) { if (!actionsList.empty()) { executeAction(actionsList[actionSelected].id); } } else { mode = ViewMode::Browser; } } else if (mode == ViewMode::TextView) { if (isLeft) { openTextEditor(viewingFilePath, viewingFileName); } else { mode = ViewMode::Browser; } } else if (mode == ViewMode::TextEdit) { if (editMenuOpen) { if (isLeft) { executeEditorMenuAction(editMenuSel); } else { editMenuOpen = false; } } else { if (isLeft) { editLastTapDigit = -1; editMenuOpen = true; editMenuSel = 0; } else { bool isEmptyDoc = (editLines.size() == 1 && editLines[0].empty()); if (isEmptyDoc && !editModified) { loadDirectory(currentDir, editFileName); mode = ViewMode::Browser; } else { deleteEditorCharBefore(); } } } } else if (mode == ViewMode::ImageView) { if (isLeft) { installAsWallpaper(viewingFilePath, viewingFileName); } else { if (imgFullscreen) { imgFullscreen = false; } else { 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) { if (isLeft) { std::string name = trimStr(inputValue); if (!name.empty() && name.find('/') == std::string::npos) { std::string target = (currentDir == "/") ? ("/" + name) : (currentDir + "/" + name); if (inputAction == InputAction::NewFolder) { ::mkdir(target.c_str(), 0755); loadDirectory(currentDir, name); mode = ViewMode::Browser; } else if (inputAction == InputAction::NewFile) { int fd = ::open(target.c_str(), O_WRONLY | O_CREAT, 0644); if (fd >= 0) ::close(fd); loadDirectory(currentDir, name); openTextEditor(target, name); } else if (inputAction == InputAction::Rename) { ::rename(inputTargetPath.c_str(), target.c_str()); loadDirectory(currentDir, name); mode = ViewMode::Browser; } } else { mode = ViewMode::Browser; } } else { if (!inputValue.empty()) { popUtf8(inputValue); lastTapDigit = -1; } else { mode = ViewMode::Browser; } } } else if (mode == ViewMode::ConfirmDelete) { if (isLeft) { if (confirmSelected == 1 && !filteredItems.empty()) { removeRecursive(filteredItems[selected].fullPath); loadDirectory(currentDir); } mode = ViewMode::Browser; } else { mode = ViewMode::Browser; } } else if (mode == ViewMode::BtSendModal) { if (isLeft) { if (btTargets.empty()) { statusBanner = "Scanning Bluetooth (15s)..."; statusBannerUntilMs = nowMs() + 16000; drawUI(); btTargets = queryBtSendTargets(true); btTargetSel = 0; statusBanner.clear(); statusBannerUntilMs = 0; } else { btTargetSel = std::clamp( btTargetSel, 0, static_cast(btTargets.size()) - 1); std::string mac = btTargets[btTargetSel].mac; std::string devName = btTargets[btTargetSel].name; std::string cmd = "/usr/bin/bananarchy-bt-obex send " + shellQuote(mac) + " " + shellQuote(btSendFilePath) + " >/dev/null 2>&1 &"; std::system(cmd.c_str()); statusBanner = "Sending to " + devName + "..."; statusBannerUntilMs = nowMs() + 2500; mode = ViewMode::Browser; } } else { mode = ViewMode::Browser; } } drawUI(); }; if (!isPreload) { showWindow(initDir); } int xfd = ConnectionNumber(dpy); while (gRunning) { for (const auto& cmd : readFifoLines(fifoFd)) { if (cmd == "NOP") { continue; } else if (cmd == "RELOAD_THEME") { pt.reload(); if (isDuressMode() && currentDir.rfind(kDuressHomeDirPath, 0) != 0) { loadDirectory(kDuressHomeDirPath); } if (visible) drawUI(); } else if (cmd == "CLOSE") { hideWindow(); } else if (cmd == "OPEN") { showWindow(""); } else if (cmd.rfind("OPEN ", 0) == 0) { showWindow(trimStr(cmd.substr(5))); } } while (XPending(dpy) > 0) { XEvent ev; XNextEvent(dpy, &ev); if (!visible) continue; if (ev.type == Expose && ev.xexpose.count == 0) { drawUI(); } else if (ev.type == VisibilityNotify && ev.xvisibility.state != VisibilityUnobscured) { if (isAnotherPluginActive("files")) { hideWindow(); } else { XRaiseWindow(dpy, win); grabPluginKeyboard(dpy, win); drawUI(); } } else if (ev.type == KeyPress) { int64_t tNow = nowMs(); unsigned int kc = ev.xkey.keycode; KeySym sym = XLookupKeysym(&ev.xkey, (ev.xkey.state & ShiftMask) ? 1 : 0); bool isLeftSk = (kc == 135 || sym == XK_Menu || sym == XF86XK_KbdLcdMenu1 || sym == _EVDEVK(0x246) || sym == XK_F1); bool isRightSk = (kc == 166 || sym == XF86XK_Back || sym == XF86XK_KbdLcdMenu2 || sym == _EVDEVK(0x247) || sym == XK_F2); if (!initialSoftkeysReleased) { if (querySoftkeysDown(dpy) == 0) { initialSoftkeysReleased = true; } else if (isLeftSk || isRightSk) { continue; } } if (tNow < startupIgnoreUntilMs && (isLeftSk || isRightSk)) { continue; } if (isLeftSk || isRightSk) { int bit = isLeftSk ? 1 : 2; softkeyPending |= bit; if (softkeyPending == 3 || querySoftkeysDown(dpy) == 3) { softkeyPending = 0; sendPluginCommand("xdrawer", "TOGGLE"); continue; } softkeyDeadlineMs = tNow + 35; continue; } if (isPowerKey(sym, kc)) { hideWindow(); openPowerMenuFromPlugin(dpy); continue; } if (sym == XK_Escape) { hideWindow(); continue; } if (sym == XK_BackSpace || sym == XK_Delete) { if (mode == ViewMode::Browser && searchQuery.empty() && currentDir != "/" && (!isDuressMode() || currentDir != kDuressHomeDirPath)) { std::string prevBase = currentDir; 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); loadDirectory(upDir, prevName); drawUI(); } else { handleSoftkeyAction(false); } continue; } if (mode == ViewMode::Browser) { if (sym == XK_Up || sym == XK_KP_Up) { if (!filteredItems.empty()) { selected = (selected - 1 + static_cast(filteredItems.size())) % static_cast(filteredItems.size()); drawUI(); } } else if (sym == XK_Down || sym == XK_KP_Down) { if (!filteredItems.empty()) { selected = (selected + 1) % static_cast(filteredItems.size()); drawUI(); } } else if (sym == XK_Left || sym == XK_KP_Left) { if (currentDir != "/" && (!isDuressMode() || currentDir != kDuressHomeDirPath)) { std::string prevBase = currentDir; 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); loadDirectory(upDir, prevName); drawUI(); } } else if (sym == XK_Right || sym == XK_KP_Right || sym == XK_Return || sym == XK_KP_Enter) { openSelectedItem(); drawUI(); } else { char d = mapDialKey(sym, kc, ev.xkey.state); if (d == '*') { showHidden = !showHidden; loadDirectory(currentDir); drawUI(); } else if (d == '#') { sortMode = static_cast((static_cast(sortMode) + 1) % 3); loadDirectory(currentDir); drawUI(); } else if (d >= '0' && d <= '9') { searchQuery.push_back(d); updateFilter(); drawUI(); } } } else if (mode == ViewMode::Actions) { if (sym == XK_Up || sym == XK_KP_Up) { if (!actionsList.empty()) { actionSelected = (actionSelected - 1 + static_cast(actionsList.size())) % static_cast(actionsList.size()); drawUI(); } } else if (sym == XK_Down || sym == XK_KP_Down) { if (!actionsList.empty()) { actionSelected = (actionSelected + 1) % static_cast(actionsList.size()); drawUI(); } } else if (sym == XK_Return || sym == XK_KP_Enter) { handleSoftkeyAction(true); } } else if (mode == ViewMode::TextView) { if (sym == XK_Up || sym == XK_KP_Up) { textScrollLine = std::max(0, textScrollLine - 1); drawUI(); } else if (sym == XK_Down || sym == XK_KP_Down || sym == XK_Return || sym == XK_KP_Enter) { textScrollLine = std::min( std::max(0, static_cast(textLines.size()) - 1), textScrollLine + 1); drawUI(); } else if (sym == XK_Left || sym == XK_KP_Left || sym == XK_Prior) { textScrollLine = std::max(0, textScrollLine - 10); drawUI(); } else if (sym == XK_Right || sym == XK_KP_Right || sym == XK_Next) { textScrollLine = std::min( std::max(0, static_cast(textLines.size()) - 1), textScrollLine + 10); drawUI(); } } else if (mode == ViewMode::TextEdit) { if (editMenuOpen) { if (sym == XK_Up || sym == XK_KP_Up) { editMenuSel = (editMenuSel - 1 + 7) % 7; drawUI(); } else if (sym == XK_Down || sym == XK_KP_Down) { editMenuSel = (editMenuSel + 1) % 7; drawUI(); } else if (sym == XK_Return || sym == XK_KP_Enter) { executeEditorMenuAction(editMenuSel); drawUI(); } } else { if (sym == XK_Up || sym == XK_KP_Up) { editLastTapDigit = -1; if (editCursorRow > 0) { editCursorRow--; editCursorCol = clampUtf8Pos(editLines[editCursorRow], editCursorCol); syncEditorScroll(); drawUI(); } } else if (sym == XK_Down || sym == XK_KP_Down) { editLastTapDigit = -1; if (editCursorRow + 1 < static_cast(editLines.size())) { editCursorRow++; editCursorCol = clampUtf8Pos(editLines[editCursorRow], editCursorCol); syncEditorScroll(); drawUI(); } } else if (sym == XK_Left || sym == XK_KP_Left) { editLastTapDigit = -1; if (editCursorCol > 0) { editCursorCol = prevUtf8Pos(editLines[editCursorRow], editCursorCol); } else if (editCursorRow > 0) { editCursorRow--; editCursorCol = static_cast(editLines[editCursorRow].size()); } syncEditorScroll(); drawUI(); } else if (sym == XK_Right || sym == XK_KP_Right) { if (editLastTapDigit != -1 && (nowMs() - editLastTapMs) <= 850) { editLastTapDigit = -1; drawUI(); } else { editLastTapDigit = -1; size_t lineLen = editLines[editCursorRow].size(); if (editCursorCol < lineLen) { editCursorCol = nextUtf8Pos(editLines[editCursorRow], editCursorCol); } else if (editCursorRow + 1 < static_cast(editLines.size())) { editCursorRow++; editCursorCol = 0; } syncEditorScroll(); drawUI(); } } else if (sym == XK_Return || sym == XK_KP_Enter) { insertEditorNewline(); drawUI(); } else { if (!isExternalKeyboardActive()) { char d = mapDialKey(sym, kc, ev.xkey.state); if (d == '#') { editLastTapDigit = -1; editCaseMode = static_cast( (static_cast(editCaseMode) + 1) % 5); drawUI(); continue; } else if (d == '*') { commitEditorTap(10); drawUI(); continue; } else if (d >= '0' && d <= '9') { commitEditorTap(d - '0'); drawUI(); continue; } } if (sym >= 0x20 && sym <= 0x7e && !(ev.xkey.state & (ControlMask | Mod1Mask))) { editLastTapDigit = -1; insertEditorStr(std::string(1, static_cast(sym))); drawUI(); } } } } else if (mode == ViewMode::ImageView) { char d = mapDialKey(sym, kc, ev.xkey.state); if (d == '*') { imgFullscreen = !imgFullscreen; drawUI(); } else if (sym == XK_Left || sym == XK_KP_Left || sym == XK_Up || sym == XK_KP_Up) { stepImageInFolder(-1); drawUI(); } else if (sym == XK_Right || sym == XK_KP_Right || sym == XK_Down || sym == XK_KP_Down || sym == XK_Return || sym == XK_KP_Enter) { 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; drawUI(); } } else if (mode == ViewMode::InputModal) { if (sym == XK_Return || sym == XK_KP_Enter) { handleSoftkeyAction(true); } else if (sym == XK_Right || sym == XK_KP_Right) { lastTapDigit = -1; drawUI(); } else { if (!isExternalKeyboardActive()) { char d = mapDialKey(sym, kc, ev.xkey.state); if (d == '#') { lastTapDigit = -1; caseMode = static_cast( (static_cast(caseMode) + 1) % 4); drawUI(); continue; } else if (d == '*') { commitModalTap(1); drawUI(); continue; } else if (d >= '0' && d <= '9') { commitModalTap(d - '0'); drawUI(); continue; } } if (sym >= 0x20 && sym <= 0x7e && !(ev.xkey.state & (ControlMask | Mod1Mask))) { lastTapDigit = -1; inputValue.push_back(static_cast(sym)); drawUI(); } } } else if (mode == ViewMode::ConfirmDelete) { if (sym == XK_Up || sym == XK_Down || sym == XK_KP_Up || sym == XK_KP_Down) { confirmSelected = 1 - confirmSelected; drawUI(); } else if (sym == XK_Return || sym == XK_KP_Enter) { handleSoftkeyAction(true); } } else if (mode == ViewMode::BtSendModal) { char d = mapDialKey(sym, kc, ev.xkey.state); if (sym == XK_Up || sym == XK_KP_Up) { if (!btTargets.empty()) { btTargetSel = (btTargetSel - 1 + static_cast(btTargets.size())) % static_cast(btTargets.size()); drawUI(); } } else if (sym == XK_Down || sym == XK_KP_Down) { if (!btTargets.empty()) { btTargetSel = (btTargetSel + 1) % static_cast(btTargets.size()); drawUI(); } } else if (d == '*') { statusBanner = "Scanning Bluetooth (15s)..."; statusBannerUntilMs = nowMs() + 16000; drawUI(); btTargets = queryBtSendTargets(true); btTargetSel = 0; statusBanner.clear(); statusBannerUntilMs = 0; drawUI(); } else if (sym == XK_Return || sym == XK_KP_Enter) { handleSoftkeyAction(true); } } } } int64_t tNow = nowMs(); if (visible && checkRingPreviewAlive()) { drawUI(); } if (visible && softkeyPending != 0 && tNow >= softkeyDeadlineMs) { if (querySoftkeysDown(dpy) == 3) { softkeyPending = 0; sendPluginCommand("xdrawer", "TOGGLE"); } else { bool isLeft = (softkeyPending == 1); softkeyPending = 0; handleSoftkeyAction(isLeft); } } if (visible && mode == ViewMode::TextEdit && editLastTapDigit != -1 && (tNow - editLastTapMs) > 850) { editLastTapDigit = -1; drawUI(); } if (visible && mode == ViewMode::InputModal && lastTapDigit != -1 && (tNow - lastTapMs) > 850) { lastTapDigit = -1; drawUI(); } int timeoutMs = -1; if (visible && softkeyPending != 0) { timeoutMs = std::max(1, static_cast(softkeyDeadlineMs - tNow)); } if (visible && mode == ViewMode::TextEdit && editLastTapDigit != -1) { int tapRem = std::max(1, static_cast(851 - (tNow - editLastTapMs))); timeoutMs = (timeoutMs < 0) ? tapRem : std::min(timeoutMs, tapRem); } if (visible && mode == ViewMode::InputModal && lastTapDigit != -1) { int tapRem = std::max(1, static_cast(851 - (tNow - lastTapMs))); timeoutMs = (timeoutMs < 0) ? tapRem : std::min(timeoutMs, tapRem); } if (visible && !statusBanner.empty() && statusBannerUntilMs > 0) { if (tNow >= statusBannerUntilMs) { statusBanner.clear(); statusBannerUntilMs = 0; drawUI(); } else { int banRem = std::max(1, static_cast(statusBannerUntilMs - tNow)); 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; pfds[nfds++] = {xfd, POLLIN, 0}; int fifoIdx = -1; if (fifoFd >= 0) { fifoIdx = nfds; pfds[nfds++] = {fifoFd, POLLIN, 0}; } int pr = ::poll(pfds, nfds, timeoutMs); if (pr > 0 && fifoIdx >= 0 && (pfds[fifoIdx].revents & POLLIN)) { for (const auto& cmd : readFifoLines(fifoFd)) { if (cmd == "RELOAD_THEME") { pt.reload(); if (isDuressMode() && currentDir.rfind(kDuressHomeDirPath, 0) != 0) { loadDirectory(kDuressHomeDirPath); } if (visible) drawUI(); } else if (cmd == "CLOSE") { hideWindow(); } else if (cmd == "OPEN") { showWindow(""); } else if (cmd.rfind("OPEN ", 0) == 0) { showWindow(trimStr(cmd.substr(5))); } } } } hideWindow(); if (xImgPreview) { xImgPreview->data = nullptr; XDestroyImage(xImgPreview); } if (xImgFullPreview) { xImgFullPreview->data = nullptr; XDestroyImage(xImgFullPreview); } if (fifoFd >= 0) ::close(fifoFd); ::unlink(daemonPidPath.c_str()); return 0; } int files_plugin_init(const DwmHostApi* host) { if (host && host->spawn_plugin) { host->spawn_plugin("files", "--preload"); } return 0; } } // namespace extern "C" __attribute__((visibility("default"))) const DwmPlugin dwm_plugin_entry = { DWM_PLUGIN_API_VERSION, "files", "Keypad-driven graphical file manager with text/image preview", files_plugin_init, nullptr, nullptr, nullptr, nullptr, runFilesApp };