Files
bananarchy/src/dwm-plugins/sms_plugin.cpp
T

2066 lines
74 KiB
C++
Raw Normal View History

#include "phone_data.h"
#include "../sxmo-dwm/dwm_plugin.h"
#include <X11/Xatom.h>
#include <X11/Xft/Xft.h>
#include <X11/Xutil.h>
#include <pango/pangoxft.h>
#include <poll.h>
#include <sys/inotify.h>
#include <sys/wait.h>
#include <clocale>
#include <cstdint>
#include <mutex>
#include <thread>
#include <unordered_set>
#include <vector>
namespace {
using namespace bananarchy;
volatile sig_atomic_t gRunning = 1;
// The PangoXft renderer on the target stack only paints the first line of a
// long multiline layout when the whole layout is handed to
// pango_xft_render_layout() in one call. Message bodies are therefore drawn
// line by line with pango_xft_render_layout_line().
constexpr int kMsgScrollStep = 16;
constexpr int kMsgBodyWidth = kWinWidth - 32; // cardW - 14
std::vector<uint32_t> decodeUtf8CodePoints(const std::string& s) {
std::vector<uint32_t> out;
size_t i = 0;
while (i < s.size()) {
unsigned char c = static_cast<unsigned char>(s[i]);
uint32_t cp = 0;
size_t n = 0;
if (c < 0x80) {
cp = c;
n = 1;
} else if ((c & 0xE0) == 0xC0) {
cp = c & 0x1F;
n = 2;
} else if ((c & 0xF0) == 0xE0) {
cp = c & 0x0F;
n = 3;
} else if ((c & 0xF8) == 0xF0) {
cp = c & 0x07;
n = 4;
} else {
++i;
continue;
}
if (i + n > s.size()) break;
bool ok = true;
for (size_t k = 1; k < n; ++k) {
unsigned char cc = static_cast<unsigned char>(s[i + k]);
if ((cc & 0xC0) != 0x80) {
ok = false;
break;
}
cp = (cp << 6) | (cc & 0x3F);
}
if (!ok) {
++i;
continue;
}
out.push_back(cp);
i += n;
}
return out;
}
struct SmsTextMetrics {
int units = 0; // GSM-7 septets or UTF-16 code units
int parts = 1; // concatenated SMS parts
int limit = 160; // capacity of the current number of parts
bool ucs2 = false;
};
// 3GPP TS 23.038 GSM 7-bit default alphabet and extension table. Any code
// point outside both forces UCS-2 (70 units per part, 67 when concatenated).
SmsTextMetrics smsTextMetrics(const std::string& text) {
static const std::unordered_set<uint32_t> kBasic = [] {
std::unordered_set<uint32_t> set;
for (uint32_t cp : decodeUtf8CodePoints(
"@\u00a3$\u00a5\u00e8\u00e9\u00f9\u00ec\u00f2\u00c7\n"
"\u00d8\u00f8\r\u00c5\u00e5"
"\u0394_\u03a6\u0393\u039b\u03a9\u03a0\u03a8\u03a3\u0398"
"\u039e\u00c6\u00e6\u00df\u00c9"
" !\"#\u00a4%&'()*+,-./0123456789:;<=>?"
"\u00a1ABCDEFGHIJKLMNOPQRSTUVWXYZ\u00c4\u00d6\u00d1\u00dc"
"\u00a7\u00bfabcdefghijklmnopqrstuvwxyz\u00e4\u00f6\u00f1"
"\u00fc\u00e0")) {
set.insert(cp);
}
return set;
}();
static const std::unordered_set<uint32_t> kExt = [] {
std::unordered_set<uint32_t> set;
for (uint32_t cp : decodeUtf8CodePoints("\f^{}\\[~]|\u20ac")) {
set.insert(cp);
}
return set;
}();
std::vector<uint32_t> cps = decodeUtf8CodePoints(text);
bool ucs2 = false;
int septets = 0;
for (uint32_t cp : cps) {
if (kBasic.count(cp)) {
++septets;
} else if (kExt.count(cp)) {
septets += 2;
} else {
ucs2 = true;
break;
}
}
SmsTextMetrics m;
m.ucs2 = ucs2;
if (ucs2) {
int units = 0;
for (uint32_t cp : cps) {
units += (cp > 0xFFFF) ? 2 : 1;
}
m.units = units;
m.parts = units <= 70 ? 1 : (units + 66) / 67;
m.limit = m.parts == 1 ? 70 : m.parts * 67;
} else {
m.units = septets;
m.parts = septets <= 160 ? 1 : (septets + 152) / 153;
m.limit = m.parts == 1 ? 160 : m.parts * 153;
}
return m;
}
void handleSignal(int) {
gRunning = 0;
}
enum class ViewMode {
Threads = 0,
ThreadView = 1,
Compose = 2,
PickContact = 3,
Options = 4,
ConfirmDelete = 5,
Blocklist = 6,
AddBlock = 7,
SelectSim = 8,
};
enum class TextCaseMode {
Title = 0, // Abc
Upper = 1, // ABC
Lower = 2, // abc
Num = 3, // 123
};
const char* kMultiTapSms[10] = {
" 0\n", // 0
kMultiTapPunct1, // 1
"abc2", // 2
"def3", // 3
"ghi4", // 4
"jkl5", // 5
"mno6", // 6
"pqrs7", // 7
"tuv8", // 8
"wxyz9" // 9
};
void popUtf8Char(std::string& s) {
if (s.empty()) {
return;
}
while (!s.empty() && (static_cast<unsigned char>(s.back()) & 0xC0) == 0x80) {
s.pop_back();
}
if (!s.empty()) {
s.pop_back();
}
}
int runSmsApp(int argc, char** argv) {
gRunning = 1;
std::setlocale(LC_ALL, "");
XSetLocaleModifiers("");
bool isPreload = false;
std::string initArg;
for (int i = 1; i < argc; ++i) {
if (!argv[i]) continue;
if (std::strcmp(argv[i], "--preload") == 0) {
isPreload = true;
} else if (std::strcmp(argv[i], "sendtextmenu") == 0 ||
std::strcmp(argv[i], "conversationloop") == 0) {
if (i + 1 < argc && argv[i + 1]) {
initArg = std::string("send:") + argv[++i];
} else {
initArg = "send:";
}
} else if (std::strcmp(argv[i], "tailtextlog") == 0) {
if (i + 1 < argc && argv[i + 1]) {
initArg = std::string("thread:") + argv[++i];
}
} else if ( std::strcmp(argv[i], "readtextmenu") == 0 ) {
initArg.clear();
} else if (initArg.empty()) {
initArg = argv[i];
}
}
std::string daemonPidPath = getPluginDaemonPidPath("sms");
std::string activePidPath = getRuntimeFile("xsms.pid");
if (isPluginDaemonAlive("sms")) {
if (!isPreload) {
sendPluginCommand("sms", initArg.empty() ? "OPEN" : ("OPEN " + initArg));
}
return 0;
}
writeIntFile(daemonPidPath, static_cast<int>(::getpid()));
int fifoFd = setupPluginDaemonFifo("sms");
int notifyPipe[2] = {-1, -1};
if (::pipe(notifyPipe) == 0) {
::fcntl(notifyPipe[0], F_SETFL, O_NONBLOCK | O_CLOEXEC);
::fcntl(notifyPipe[1], F_SETFL, O_NONBLOCK | O_CLOEXEC);
}
struct sigaction sa {};
sa.sa_handler = handleSignal;
sigemptyset(&sa.sa_mask);
sigaction(SIGINT, &sa, nullptr);
sigaction(SIGTERM, &sa, nullptr);
NeoWindow neo;
if (!neo.create("xsms", "XSms", "Messages")) {
if (fifoFd >= 0) ::close(fifoFd);
if (notifyPipe[0] >= 0) ::close(notifyPipe[0]);
if (notifyPipe[1] >= 0) ::close(notifyPipe[1]);
::unlink(daemonPidPath.c_str());
return 1;
}
Display* dpy = neo.dpy;
Window win = neo.win;
Pixmap pix = neo.pix;
GC gc = neo.gc;
XftDraw* xftDraw = neo.xftDraw;
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& colRed = pt.colRed;
ContactBook book;
BlockList blockList;
std::vector<SmsThread> inboxThreads;
std::vector<SmsThread> spamThreads;
std::vector<SmsThread> allThreads;
std::vector<SmsThread> filteredThreads;
std::vector<SmsMessage> threadMessages;
std::vector<ContactEntry> pickerContacts;
FileStamp contactsStamp;
FileStamp modemLogStamp;
FileStamp blockFileStamp;
FileStamp blockLogStamp;
bool loadedOnce = false;
bool viewingSpamFolder = false;
ViewMode mode = ViewMode::Threads;
ViewMode prevMode = ViewMode::Threads;
std::string searchQuery;
int selectedThread = 0;
int selectedMsg = 0;
int msgScrollPx = 0; // vertical scroll inside the selected message
int msgTextH = 0; // wrapped height of the selected message body
int msgViewH = 0; // visible body height inside its card
int selectedOption = 0;
int selectedPicker = 0;
int confirmSelected = 0;
int blockSelected = 0;
int simPickIdx = 0;
DualSimInfo simInfo;
std::string addBlockInput;
std::string activeNumber;
std::string composeRecipient;
std::string composeText;
int composeField = 1; // 0 = To, 1 = Message body, 2 = Send button, 3 = Save Draft
TextCaseMode caseMode = TextCaseMode::Title;
int lastTapDigit = -1;
int lastTapCycle = 0;
int64_t lastTapMs = 0;
bool zeroHeld = false;
int64_t zeroPressMs = 0;
std::mutex sendMutex;
bool sendingInProgress = false;
std::string statusBanner;
int64_t statusBannerUntilMs = 0;
bool visible = false;
int64_t openStartMs = 0;
int64_t startupIgnoreUntilMs = 0;
bool initialSoftkeysReleased = true;
int softkeyPending = 0;
int64_t softkeyDeadlineMs = 0;
struct OptionEntry {
int id;
std::string icon;
std::string label;
bool danger = false;
};
std::vector<OptionEntry> optionsList;
auto updateFilter = [&]() {
allThreads = viewingSpamFolder ? spamThreads : inboxThreads;
for (auto& t : allThreads) {
t.isBlocked = viewingSpamFolder || blockList.isBlocked(t.number);
}
filteredThreads.clear();
if (searchQuery.empty()) {
filteredThreads = allThreads;
} else {
std::string qNorm = normalizePhone(searchQuery);
std::string qLower = toLowerStr(searchQuery);
for (const auto& t : allThreads) {
bool match =
(!qLower.empty() && t.lowerName.find(qLower) != std::string::npos) ||
(!qNorm.empty() && t.t9Name.find(qNorm) != std::string::npos) ||
(!qNorm.empty() && t.normNumber.find(qNorm) != std::string::npos) ||
(!qLower.empty() &&
toLowerStr(t.lastPreview).find(qLower) != std::string::npos);
if (match) {
filteredThreads.push_back(t);
}
}
}
if (selectedThread >= static_cast<int>(filteredThreads.size())) {
selectedThread =
std::max(0, static_cast<int>(filteredThreads.size()) - 1);
}
};
auto reloadAllData = [&](bool force = false) -> bool {
bool cChanged = contactsStamp.checkAndUpdate(getContactsFilePath());
bool lChanged = modemLogStamp.checkAndUpdate(getModemLogFilePath());
bool bChanged = blockFileStamp.checkAndUpdate(getBlockFilePath());
bool blChanged = blockLogStamp.checkAndUpdate(getBlockedModemLogFilePath());
if (force || cChanged || lChanged || bChanged || blChanged || !loadedOnce) {
loadedOnce = true;
book.load();
blockList.load();
inboxThreads = loadSmsThreads(book, getModemLogDirPath());
spamThreads = loadSmsThreads(book, getBlockDirPath());
updateFilter();
if (blockSelected >= static_cast<int>(blockList.entries().size())) {
blockSelected = std::max(0, static_cast<int>(blockList.entries().size()) - 1);
}
if (!activeNumber.empty()) {
std::string curBase =
viewingSpamFolder ? getBlockDirPath() : getModemLogDirPath();
threadMessages = loadSmsThreadMessages(activeNumber, curBase);
if (selectedMsg >= static_cast<int>(threadMessages.size())) {
selectedMsg =
std::max(0, static_cast<int>(threadMessages.size()) - 1);
}
}
return true;
}
return false;
};
reloadAllData(true);
auto openThreadView = [&](const std::string& num) {
activeNumber = trimStr(num);
std::string curBase =
viewingSpamFolder ? getBlockDirPath() : getModemLogDirPath();
threadMessages = loadSmsThreadMessages(activeNumber, curBase);
selectedMsg = std::max(0, static_cast<int>(threadMessages.size()) - 1);
msgScrollPx = 0;
mode = ViewMode::ThreadView;
};
auto openComposeView = [&](const std::string& num, const std::string& prefill = "") {
prevMode = mode;
composeRecipient = trimStr(num);
if (!prefill.empty()) {
composeText = prefill;
} else if (!composeRecipient.empty()) {
composeText = loadSmsDraft(composeRecipient);
} else {
composeText.clear();
}
composeField = composeRecipient.empty() ? 0 : 1;
lastTapDigit = -1;
mode = ViewMode::Compose;
};
auto buildOptions = [&]() {
optionsList.clear();
if (mode == ViewMode::Threads) {
optionsList.push_back({1, kIconPlus, "New Message", false});
if (!filteredThreads.empty()) {
const auto& selTh = filteredThreads[selectedThread];
bool isBlk = blockList.isBlocked(selTh.number);
optionsList.push_back({2, kIconEye, "Open Conversation", false});
optionsList.push_back({3, kIconSend, "Reply to Selected", false});
optionsList.push_back({4, kIconPhone, "Call Contact", false});
if (isBlk || viewingSpamFolder) {
optionsList.push_back({8, kIconCheck, "Unblock & Restore", false});
} else {
optionsList.push_back({8, kIconBan, "Block Number (Spam)", true});
}
optionsList.push_back({5, kIconUser, "Open in Contacts", false});
optionsList.push_back({6, kIconTrash, "Delete Conversation", true});
}
if (viewingSpamFolder) {
optionsList.push_back(
{9, kIconSms,
"Switch to Inbox (" + std::to_string(inboxThreads.size()) + ")",
false});
} else {
optionsList.push_back(
{9, kIconShield,
"Spam Folder (" + std::to_string(spamThreads.size()) + ")",
false});
}
optionsList.push_back(
{10, kIconBan,
"Manage Blocklist (" + std::to_string(blockList.entries().size()) + ")",
false});
optionsList.push_back({11, kIconPlus, "Block a Number...", false});
} else if (mode == ViewMode::ThreadView) {
bool isBlk = blockList.isBlocked(activeNumber);
optionsList.push_back({3, kIconSend, "Reply / Compose", false});
optionsList.push_back({4, kIconPhone, "Call Contact", false});
if (!threadMessages.empty()) {
optionsList.push_back({7, kIconCopy, "Forward Selected Msg", false});
}
if (isBlk || viewingSpamFolder) {
optionsList.push_back({8, kIconCheck, "Unblock & Restore", false});
} else {
optionsList.push_back({8, kIconBan, "Block Number (Spam)", true});
}
optionsList.push_back({5, kIconUser, "Save / View Contact", false});
optionsList.push_back({6, kIconTrash, "Delete Conversation", true});
optionsList.push_back(
{10, kIconBan,
"Manage Blocklist (" + std::to_string(blockList.entries().size()) + ")",
false});
}
selectedOption = 0;
};
auto startAsyncSendSms = [&](const std::string& rawRecipient,
const std::string& body,
int chosenSim = 0) {
std::string recipient = normalizePhone(rawRecipient);
if (recipient.empty() || trimStr(body).empty()) {
statusBanner = "Set recipient and message";
statusBannerUntilMs = nowMs() + 2000;
return;
}
if (chosenSim == 0) {
simInfo = queryDualSimInfo(false);
if (simInfo.dualSimActive) {
simPickIdx = (simInfo.preferredSlot == 2) ? 1 : 0;
mode = ViewMode::SelectSim;
return;
}
chosenSim = simInfo.preferredSlot;
}
if (chosenSim != 1 && chosenSim != 2) {
chosenSim = 1;
}
{
std::lock_guard<std::mutex> lk(sendMutex);
if (sendingInProgress) {
return;
}
sendingInProgress = true;
}
saveSmsDraft(recipient, body);
statusBanner = "Sending SMS (SIM " + std::to_string(chosenSim) + ") to " +
recipient + "...";
statusBannerUntilMs = nowMs() + 15000;
int writePipe = notifyPipe[1];
std::thread([recipient, body, chosenSim, writePipe, &sendMutex,
&sendingInProgress, &statusBanner, &statusBannerUntilMs]() {
std::string draftPath =
getModemLogDirPath() + "/" + recipient + "/draft.txt";
ContactBook::ensureParentDir(draftPath);
{
std::ofstream out(draftPath, std::ios::trunc);
out << body << "\n";
}
std::string simStr = std::to_string(chosenSim);
int rc = -1;
pid_t pid = ::fork();
if (pid == 0) {
int nullfd = ::open("/dev/null", O_RDWR);
if (nullfd >= 0) {
::dup2(nullfd, STDIN_FILENO);
::dup2(nullfd, STDOUT_FILENO);
::dup2(nullfd, STDERR_FILENO);
if (nullfd > 2) ::close(nullfd);
}
execlp("sxmo_modemsendsms.sh", "sxmo_modemsendsms.sh",
"--sim", simStr.c_str(), recipient.c_str(), "-f",
draftPath.c_str(), static_cast<char*>(nullptr));
execl("/usr/bin/sxmo_modemsendsms.sh", "sxmo_modemsendsms.sh",
"--sim", simStr.c_str(), recipient.c_str(), "-f",
draftPath.c_str(), static_cast<char*>(nullptr));
_exit(127);
} else if (pid > 0) {
int status = 0;
::waitpid(pid, &status, 0);
if (WIFEXITED(status)) {
rc = WEXITSTATUS(status);
}
}
// If modem send failed (e.g. offline/no SIM), still log locally if user
// wants local record or keep draft so nothing is lost
if (rc == 0) {
removeSmsDraft(recipient);
} else {
// Record in local thread log as Sent (or Draft) so conversation is visible
time_t nowSec = std::time(nullptr);
struct tm tmNow {};
localtime_r(&nowSec, &tmNow);
char tbuf[32];
std::strftime(tbuf, sizeof(tbuf), "%Y-%m-%dT%H:%M:%S%z", &tmNow);
std::string smsPath =
getModemLogDirPath() + "/" + recipient + "/sms.txt";
ContactBook::ensureParentDir(smsPath);
std::ofstream smsOut(smsPath, std::ios::app);
if (smsOut.is_open()) {
smsOut << "Sent at " << tbuf << ":\n" << body << "\n\n";
}
std::ofstream logOut(getModemLogFilePath(), std::ios::app);
if (logOut.is_open()) {
logOut << tbuf << "\tsent_txt\t" << recipient << "\t[SIM "
<< chosenSim << "] " << smsTextMetrics(body).units
<< " units\n";
}
removeSmsDraft(recipient);
}
{
std::lock_guard<std::mutex> lk(sendMutex);
sendingInProgress = false;
statusBanner = (rc == 0)
? ("SMS Sent (SIM " + std::to_string(chosenSim) + ")!")
: "Saved to Sent (modem offline)";
statusBannerUntilMs = nowMs() + 2200;
}
if (writePipe >= 0) {
char c = 'S';
(void)::write(writePipe, &c, 1);
}
}).detach();
};
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);
};
// pango_xft_render_layout() only paints the first line of a long multiline
// UTF-8 layout on the target Pango/Xft stack, so every multiline body is
// drawn one line at a time, clipped to its visible rectangle. yPx is the
// layout origin and scrollPx is the number of layout pixels hidden above
// the clip (negative when the layout starts below the clip top).
auto renderLayoutLines = [&](PangoLayout* layout, XftColor* color, int xPx,
int yPx, int clipX, int clipY, int clipW,
int clipH, int scrollPx) {
if (clipW <= 0 || clipH <= 0) {
return;
}
XRectangle clip {
static_cast<short>(clipX), static_cast<short>(clipY),
static_cast<unsigned short>(clipW),
static_cast<unsigned short>(clipH)};
XftDrawSetClipRectangles(xftDraw, 0, 0, &clip, 1);
PangoLayoutIter* it = pango_layout_get_iter(layout);
if (it) {
do {
PangoRectangle logical{};
pango_layout_iter_get_line_extents(it, nullptr, &logical);
int lineTop = logical.y / PANGO_SCALE;
int lineBottom = (logical.y + logical.height) / PANGO_SCALE;
if (lineBottom <= scrollPx) continue;
if (lineTop >= scrollPx + clipH) break;
PangoLayoutLine* line = pango_layout_iter_get_line_readonly(it);
int baseline = pango_layout_iter_get_baseline(it) / PANGO_SCALE;
pango_xft_render_layout_line(
xftDraw, color, line, xPx * PANGO_SCALE,
(yPx + baseline - scrollPx) * PANGO_SCALE);
} while (pango_layout_iter_next_line(it));
pango_layout_iter_free(it);
}
XftDrawSetClip(xftDraw, nullptr);
};
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;
pt.checkAndReload();
XSetForeground(dpy, gc, pt.spec.bgMain);
XFillRectangle(dpy, pix, gc, 0, 0, kWinWidth, kWinHeight);
if (mode == ViewMode::Threads) {
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, viewingSpamFolder ? &colRed : &colYellow, 8, 2,
34, viewingSpamFolder ? kIconBan : kIconSms);
std::string hdrTitle =
viewingSpamFolder ? "Spam / Blocked" : "Messages";
drawPango(layoutMain, viewingSpamFolder ? &colRed : &colWhite, 30, 2,
34, hdrTitle, 145);
std::string cnt = "< [" + std::to_string(allThreads.size()) + "] >";
pango_layout_set_width(layoutSmall, -1);
pango_layout_set_text(layoutSmall, cnt.c_str(),
static_cast<int>(cnt.size()));
int cw = 0, chh = 0;
pango_layout_get_pixel_size(layoutSmall, &cw, &chh);
drawPango(layoutSmall, &colMuted, kWinWidth - cw - 8, 2, 34, cnt);
} else {
drawPango(layoutIcon, &colBlue, 8, 2, 34, kIconSearch);
drawPango(layoutMain, &colYellow, 30, 2, 34, searchQuery, 155);
std::string cnt = std::to_string(filteredThreads.size());
pango_layout_set_width(layoutSmall, -1);
pango_layout_set_text(layoutSmall, cnt.c_str(),
static_cast<int>(cnt.size()));
int cw = 0, chh = 0;
pango_layout_get_pixel_size(layoutSmall, &cw, &chh);
drawPango(layoutSmall, &colMuted, kWinWidth - cw - 8, 2, 34, cnt);
}
const int listY = 38;
const int rowH = 38;
const int visibleRows = 6;
if (filteredThreads.empty()) {
drawPango(layoutMain, &colMuted, 16, 110, 24,
searchQuery.empty()
? (viewingSpamFolder ? "No blocked messages"
: "No messages yet")
: "No matches",
208);
drawPango(layoutSmall, &colBlue, 16, 138, 20,
viewingSpamFolder ? "Left/Right: Switch to Inbox"
: "Left Softkey: Options / Blocklist",
208);
} else {
int scroll = 0;
if (selectedThread >= visibleRows) {
scroll = selectedThread - visibleRows + 1;
}
for (int i = 0; i < visibleRows; ++i) {
int idx = scroll + i;
if (idx >= static_cast<int>(filteredThreads.size())) break;
const auto& th = filteredThreads[idx];
int ry = listY + i * rowH;
bool isSel = (idx == selectedThread);
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 =
th.isBlocked
? kIconBan
: (th.hasDraft ? kIconEdit
: (th.lastIncoming ? kIconInCall : kIconOutCall));
XftColor* icCol =
th.isBlocked
? &colRed
: (th.hasDraft ? &colYellow
: (th.lastIncoming ? &colGreen : &colBlue));
drawPango(layoutIcon, icCol, 6, ry + 1, 20, ic);
std::string title =
th.contactName.empty() ? th.number : th.contactName;
drawPango(layoutMain, th.isBlocked ? &colRed : &colWhite, 26, ry + 1,
20, title, 128);
if (!th.lastDisplayTime.empty()) {
pango_layout_set_width(layoutSmall, -1);
pango_layout_set_text(layoutSmall, th.lastDisplayTime.c_str(),
static_cast<int>(th.lastDisplayTime.size()));
int tw = 0, thh = 0;
pango_layout_get_pixel_size(layoutSmall, &tw, &thh);
drawPango(layoutSmall, isSel ? &colLight : &colMuted,
kWinWidth - tw - 6, ry + 2, 18, th.lastDisplayTime);
}
drawPango(layoutSmall, isSel ? &colLight : &colMuted, 26, ry + 20, 16,
th.lastPreview, 206);
}
}
drawSoftkeyBar("Options",
filteredThreads.empty() ? "New SMS" : "Open",
searchQuery.empty() ? "Close" : "Clear");
} else if (mode == ViewMode::ThreadView) {
XSetForeground(dpy, gc, pt.spec.bgHeader);
XFillRectangle(dpy, pix, gc, 0, 0, kWinWidth, 36);
XSetForeground(dpy, gc, pt.spec.border);
XDrawLine(dpy, pix, gc, 0, 35, kWinWidth, 35);
std::string cname = book.resolveName(activeNumber);
std::string title = cname.empty() ? activeNumber : cname;
drawPango(layoutIcon, &colYellow, 6, 1, 18, kIconSms);
drawPango(layoutMain, &colWhite, 26, 0, 20, title, 160);
std::string sub = cname.empty()
? (std::to_string(threadMessages.size()) + " msgs")
: activeNumber;
drawPango(layoutSmall, &colMuted, 26, 19, 15, sub, 204);
if (threadMessages.empty()) {
drawPango(layoutMain, &colMuted, 16, 110, 24, "No messages in thread",
208);
drawPango(layoutSmall, &colBlue, 16, 138, 20,
"Press OK to write a message", 208);
} else {
// Measure and render message cards from bottom up or around selectedMsg
const int areaTop = 38;
const int areaBot = kWinHeight - 28;
const int areaH = areaBot - areaTop;
struct CardGeom {
int idx;
int h;
int bodyH;
std::string header;
std::string body;
bool incoming;
};
std::vector<CardGeom> cards;
cards.reserve(threadMessages.size());
for (size_t i = 0; i < threadMessages.size(); ++i) {
const auto& m = threadMessages[i];
CardGeom cg;
cg.idx = static_cast<int>(i);
cg.incoming = m.incoming;
cg.header = (m.incoming ? "Recv " : "Sent ") + m.displayTime;
cg.body = m.text;
pango_layout_set_width(layoutSmall, kMsgBodyWidth * PANGO_SCALE);
pango_layout_set_wrap(layoutSmall, PANGO_WRAP_WORD_CHAR);
pango_layout_set_ellipsize(layoutSmall, PANGO_ELLIPSIZE_NONE);
pango_layout_set_text(layoutSmall, cg.body.c_str(),
static_cast<int>(cg.body.size()));
int bw = 0, bh = 0;
pango_layout_get_pixel_size(layoutSmall, &bw, &bh);
cg.bodyH = bh;
cg.h = std::max(38, bh + 22);
cards.push_back(cg);
}
// Determine visible slice ending at selectedMsg (or covering selectedMsg)
int endIdx = std::clamp(selectedMsg, 0,
static_cast<int>(cards.size()) - 1);
int startIdx = endIdx;
int usedH = cards[endIdx].h;
while (startIdx > 0 && usedH + cards[startIdx - 1].h + 4 <= areaH) {
--startIdx;
usedH += cards[startIdx].h + 4;
}
while (endIdx + 1 < static_cast<int>(cards.size()) &&
usedH + cards[endIdx + 1].h + 4 <= areaH) {
++endIdx;
usedH += cards[endIdx].h + 4;
}
int curY = areaTop + 2;
for (int i = startIdx; i <= endIdx; ++i) {
const auto& cg = cards[i];
bool isSel = (cg.idx == selectedMsg);
int cardX = cg.incoming ? 4 : 14;
int cardW = kWinWidth - 18;
int cardH = std::min(cg.h, areaH - 4);
unsigned long bg = isSel
? pt.spec.bgInputFocus
: (cg.incoming ? pt.spec.bgBubbleIn
: pt.spec.bgBubbleOut);
XSetForeground(dpy, gc, bg);
XFillRectangle(dpy, pix, gc, cardX, curY, cardW, cardH);
unsigned long accent =
cg.incoming ? pt.spec.success : pt.spec.info;
XSetForeground(dpy, gc, isSel ? pt.spec.accent : accent);
if (cg.incoming) {
XFillRectangle(dpy, pix, gc, cardX, curY, 3, cardH);
} else {
XFillRectangle(dpy, pix, gc, cardX + cardW - 3, curY, 3, cardH);
}
drawPango(layoutSmall, cg.incoming ? &colGreen : &colBlue,
cardX + 8, curY + 2, 14, cg.header, cardW - 14);
pango_layout_set_width(layoutSmall, kMsgBodyWidth * PANGO_SCALE);
pango_layout_set_wrap(layoutSmall, PANGO_WRAP_WORD_CHAR);
pango_layout_set_ellipsize(layoutSmall, PANGO_ELLIPSIZE_NONE);
pango_layout_set_text(layoutSmall, cg.body.c_str(),
static_cast<int>(cg.body.size()));
const int bodyViewH = std::max(0, cardH - 20);
const int maxScroll = std::max(0, cg.bodyH - bodyViewH);
const int scrollPx =
isSel ? std::clamp(msgScrollPx, 0, maxScroll) : 0;
renderLayoutLines(layoutSmall, &colWhite, cardX + 8, curY + 18,
cardX + 8, curY + 18, cardW - 16, bodyViewH,
scrollPx);
if (isSel) {
msgTextH = cg.bodyH;
msgViewH = bodyViewH;
if (maxScroll > 0) {
int sbH = std::max(14, bodyViewH * bodyViewH / (cg.bodyH + 1));
int sbY = curY + 18 +
(bodyViewH - sbH) * scrollPx / maxScroll;
XSetForeground(dpy, gc, pt.spec.accent);
XFillRectangle(dpy, pix, gc, cardX + cardW - 5, sbY, 3, sbH);
}
}
curY += cardH + 4;
}
}
drawSoftkeyBar("Options", "Reply", "Back");
} else if (mode == ViewMode::Compose) {
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, &colBlue, 6, 0, 30, kIconSend);
drawPango(layoutMain, &colWhite, 26, 0, 30, "Compose", 100);
const char* modeBadge = "[Abc]";
if (composeField == 0) {
modeBadge = "[123]";
} else if (isExternalKeyboardActive()) {
modeBadge = "[KBD]";
} else if (caseMode == TextCaseMode::Upper) {
modeBadge = "[ABC]";
} else if (caseMode == TextCaseMode::Lower) {
modeBadge = "[abc]";
} else if (caseMode == TextCaseMode::Num) {
modeBadge = "[123]";
}
SmsTextMetrics sm = smsTextMetrics(composeText);
std::string rightHdr = std::string(modeBadge) + " " +
std::to_string(sm.units) + "/" +
std::to_string(sm.limit);
if (sm.parts > 1) {
rightHdr += "x" + std::to_string(sm.parts);
}
pango_layout_set_width(layoutSmall, -1);
pango_layout_set_text(layoutSmall, rightHdr.c_str(),
static_cast<int>(rightHdr.size()));
int rw = 0, rhh = 0;
pango_layout_get_pixel_size(layoutSmall, &rw, &rhh);
drawPango(layoutSmall, &colYellow, kWinWidth - rw - 6, 0, 30, rightHdr);
// Field 0: Recipient
bool toSel = (composeField == 0);
XSetForeground(dpy, gc,
toSel ? pt.spec.bgInputFocus : pt.spec.bgInput);
XFillRectangle(dpy, pix, gc, 6, 36, kWinWidth - 12, 32);
XSetForeground(dpy, gc, toSel ? pt.spec.accentAlt : pt.spec.border);
XDrawRectangle(dpy, pix, gc, 6, 36, kWinWidth - 13, 31);
std::string cname = book.resolveName(composeRecipient);
std::string toDisp = "To: " + composeRecipient;
if (toSel) toDisp += "|";
if (!cname.empty()) {
toDisp += " (" + cname + ")";
}
if (toSel && cname.empty()) {
toDisp = tailFitPangoText(layoutMain, toDisp, kWinWidth - 20);
}
drawPango(layoutMain, toSel ? &colWhite : &colLight, 10, 36, 32, toDisp,
kWinWidth - 20);
// Field 1: Message Body
bool msgSel = (composeField == 1);
bool smsTapActive =
(msgSel && lastTapDigit >= 0 && lastTapDigit <= 9 &&
(nowMs() - lastTapMs) <= 850);
XSetForeground(dpy, gc,
msgSel ? pt.spec.bgInputFocus : pt.spec.bgInput);
XFillRectangle(dpy, pix, gc, 6, 72, kWinWidth - 12, 156);
XSetForeground(dpy, gc, msgSel ? pt.spec.accentAlt : pt.spec.border);
XDrawRectangle(dpy, pix, gc, 6, 72, kWinWidth - 13, 155);
std::string bodyDisp = composeText;
if (msgSel) bodyDisp += "|";
int bodyMaxH = smsTapActive ? 126 : 146;
if (bodyDisp.empty()) {
drawPango(layoutSmall, &colMuted, 12, 78, 20,
"Type message (# Input mode)...", kWinWidth - 24);
} else {
pango_layout_set_width(layoutMain, (kWinWidth - 24) * PANGO_SCALE);
pango_layout_set_wrap(layoutMain, PANGO_WRAP_WORD_CHAR);
pango_layout_set_ellipsize(layoutMain, PANGO_ELLIPSIZE_NONE);
pango_layout_set_text(layoutMain, bodyDisp.c_str(),
static_cast<int>(bodyDisp.size()));
int tw = 0, th = 0;
pango_layout_get_pixel_size(layoutMain, &tw, &th);
int textY = 76;
if (th > bodyMaxH) {
textY = 76 - (th - bodyMaxH);
}
int clipY = 73;
int clipH = smsTapActive ? 134 : 154;
// Keep the layout origin at the clip top and express the upward
// scroll of a long draft as hidden layout pixels, so the tail of the
// text stays visible instead of being skipped by the line loop.
renderLayoutLines(layoutMain, &colWhite, 12, clipY, 6, clipY,
kWinWidth - 12, clipH, clipY - textY);
}
if (smsTapActive) {
XSetForeground(dpy, gc, pt.spec.bgAltOdd);
XFillRectangle(dpy, pix, gc, 7, 208, kWinWidth - 14, 19);
XSetForeground(dpy, gc, pt.spec.divider);
XDrawLine(dpy, pix, gc, 7, 208, kWinWidth - 8, 208);
std::string cand = formatMultiTapBar(
std::to_string(lastTapDigit) + ":", kMultiTapSms[lastTapDigit],
lastTapCycle, caseMode == TextCaseMode::Upper);
drawPango(layoutSmall, &colYellow, 10, 208, 19, cand, kWinWidth - 20);
}
// Field 2 & 3: Send & Save Draft buttons
bool sendSel = (composeField == 2);
bool draftSel = (composeField == 3);
XSetForeground(dpy, gc, sendSel ? pt.spec.selBg : pt.spec.bgButton);
XFillRectangle(dpy, pix, gc, 6, 234, 118, 30);
XSetForeground(dpy, gc, sendSel ? pt.spec.accentAlt : pt.spec.border);
XDrawRectangle(dpy, pix, gc, 6, 234, 117, 29);
drawPango(layoutMain, &colGreen, 18, 234, 30, "Send SMS", 100);
XSetForeground(dpy, gc, draftSel ? pt.spec.selBg : pt.spec.bgButton);
XFillRectangle(dpy, pix, gc, 130, 234, 104, 30);
XSetForeground(dpy, gc, draftSel ? pt.spec.accentAlt : pt.spec.border);
XDrawRectangle(dpy, pix, gc, 130, 234, 103, 29);
drawPango(layoutMain, &colYellow, 146, 234, 30, "Draft", 84);
if (composeField == 0) {
drawSoftkeyBar("Contacts",
composeRecipient.empty() ? "Contacts" : "Next",
composeRecipient.empty() ? "Cancel" : "Clear");
} else if (composeField == 1) {
drawSoftkeyBar("Send", "Send",
composeText.empty() ? "Cancel" : "Del");
} else if (composeField == 2) {
drawSoftkeyBar("Send", "Send", "Cancel");
} else {
drawSoftkeyBar("Send", "Draft", "Cancel");
}
} else if (mode == ViewMode::PickContact) {
XSetForeground(dpy, gc, pt.spec.bgHeader);
XFillRectangle(dpy, pix, gc, 0, 0, kWinWidth, 34);
drawPango(layoutIcon, &colBlue, 8, 0, 34, kIconBook);
drawPango(layoutMain, &colWhite, 30, 0, 34, "Select Recipient", 200);
const int listY = 36;
const int rowH = 38;
const int visibleRows = 6;
if (pickerContacts.empty()) {
drawPango(layoutMain, &colMuted, 16, 110, 24, "No saved contacts", 208);
} else {
int scroll = 0;
if (selectedPicker >= visibleRows) {
scroll = selectedPicker - visibleRows + 1;
}
for (int i = 0; i < visibleRows; ++i) {
int idx = scroll + i;
if (idx >= static_cast<int>(pickerContacts.size())) break;
const auto& c = pickerContacts[idx];
int ry = listY + i * rowH;
bool isSel = (idx == selectedPicker);
XSetForeground(dpy, gc, isSel ? pt.spec.selBg : pt.spec.bgMain);
XFillRectangle(dpy, pix, gc, 0, ry, kWinWidth, rowH - 1);
drawPango(layoutIcon, c.isRecent ? &colYellow : &colBlue, 6, ry + 1,
20, c.isRecent ? kIconClock : kIconUser);
drawPango(layoutMain, &colWhite, 28, ry + 1, 20, c.name, 204);
drawPango(layoutSmall, isSel ? &colLight : &colMuted, 28, ry + 20, 16,
c.number, 204);
}
}
drawSoftkeyBar("Select", "Select", "Back");
} else if (mode == ViewMode::Options) {
XSetForeground(dpy, gc, pt.spec.bgHeader);
XFillRectangle(dpy, pix, gc, 0, 0, kWinWidth, 34);
drawPango(layoutIcon, &colBlue, 8, 0, 34, kIconList);
drawPango(layoutMain, &colWhite, 30, 0, 34, "Message Options", 200);
const int listY = 38;
const int rowH = 36;
const int visRows = 6;
int scroll = 0;
if (selectedOption >= visRows) {
scroll = selectedOption - visRows + 1;
}
for (int i = 0; i < visRows; ++i) {
int idx = scroll + i;
if (idx >= static_cast<int>(optionsList.size())) break;
int ry = listY + i * rowH;
bool isSel = (idx == selectedOption);
XSetForeground(dpy, gc, isSel ? pt.spec.selBg : pt.spec.bgMain);
XFillRectangle(dpy, pix, gc, 0, ry, kWinWidth, rowH - 1);
XftColor* icCol =
optionsList[idx].danger ? &colRed : (isSel ? &colYellow : &colBlue);
XftColor* txCol = optionsList[idx].danger ? &colRed : &colWhite;
drawPango(layoutIcon, icCol, 10, ry, rowH, optionsList[idx].icon);
drawPango(layoutMain, txCol, 34, ry, rowH, optionsList[idx].label, 198);
}
drawSoftkeyBar("Select", "Select", "Back");
} else if (mode == ViewMode::Blocklist) {
XSetForeground(dpy, gc, pt.spec.bgHeader);
XFillRectangle(dpy, pix, gc, 0, 0, kWinWidth, 34);
drawPango(layoutIcon, &colRed, 8, 0, 34, kIconBan);
std::string hdr =
"Blocklist (" + std::to_string(blockList.entries().size()) + ")";
drawPango(layoutMain, &colWhite, 30, 0, 34, hdr, 200);
const auto& entries = blockList.entries();
if (entries.empty()) {
drawPango(layoutIcon, &colMuted, 112, 94, 24, kIconShield);
drawPango(layoutMain, &colMuted, 44, 124, 24, "Blocklist is empty",
180);
drawPango(layoutSmall, &colBlue, 22, 152, 20,
"Left Softkey: Block a Number", 204);
} else {
const int listY = 36;
const int rowH = 38;
const int visRows = 6;
int scroll = 0;
if (blockSelected >= visRows) {
scroll = blockSelected - visRows + 1;
}
for (int i = 0; i < visRows; ++i) {
int idx = scroll + i;
if (idx >= static_cast<int>(entries.size())) break;
const auto& e = entries[idx];
int ry = listY + i * rowH;
bool isSel = (idx == blockSelected);
XSetForeground(dpy, gc, isSel ? pt.spec.selBg : pt.spec.bgMain);
XFillRectangle(dpy, pix, gc, 0, ry, kWinWidth, rowH - 1);
std::string cname = book.resolveName(e.number);
std::string topLine = cname.empty() ? e.number : cname;
std::string subLine =
cname.empty() ? e.label : (e.number + " (" + e.label + ")");
drawPango(layoutIcon, &colRed, 8, ry + 1, 20, kIconBan);
drawPango(layoutMain, &colWhite, 28, ry + 1, 20, topLine, 204);
drawPango(layoutSmall, isSel ? &colLight : &colMuted, 28, ry + 20, 16,
subLine, 204);
}
}
drawSoftkeyBar("Add New", entries.empty() ? "" : "Unblock", "Back");
} else if (mode == ViewMode::AddBlock) {
XSetForeground(dpy, gc, pt.spec.bgHeader);
XFillRectangle(dpy, pix, gc, 0, 0, kWinWidth, 34);
drawPango(layoutIcon, &colRed, 8, 0, 34, kIconBan);
drawPango(layoutMain, &colWhite, 30, 0, 34, "Block Phone Number", 200);
drawPango(layoutSmall, &colMuted, 12, 54, 20,
"Enter number or prefix (e.g. +1800*):", 216);
XSetForeground(dpy, gc, pt.spec.bgInputFocus);
XFillRectangle(dpy, pix, gc, 12, 80, kWinWidth - 24, 34);
XSetForeground(dpy, gc, pt.spec.accentAlt);
XDrawRectangle(dpy, pix, gc, 12, 80, kWinWidth - 25, 33);
std::string disp =
tailFitPangoText(layoutMain, addBlockInput + "|", kWinWidth - 36);
drawPango(layoutMain, &colWhite, 18, 83, 28, disp, kWinWidth - 36);
drawPango(layoutSmall, &colMuted, 12, 124, 20,
"0-9 / * / #: Digits #: + prefix", 216);
drawPango(layoutSmall, &colMuted, 12, 146, 20,
"BackSpace/Left: Delete digit", 216);
drawSoftkeyBar("Block", "Save", "Cancel");
} else if (mode == ViewMode::ConfirmDelete) {
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 Thread?", 200);
drawPango(layoutMain, &colWhite, 14, 70, 26, activeNumber, 212);
drawPango(layoutSmall, &colMuted, 14, 98, 22,
"All SMS history for this number", 212);
drawPango(layoutSmall, &colMuted, 14, 118, 22, "will be removed.", 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 Thread" : "Yes, Delete Thread", 184);
}
drawSoftkeyBar("Select", "Confirm", "Cancel");
} else if (mode == ViewMode::SelectSim) {
XSetForeground(dpy, gc, pt.spec.bgHeader);
XFillRectangle(dpy, pix, gc, 0, 0, kWinWidth, 36);
drawPango(layoutIcon, &colYellow, 8, 0, 36, kIconSim);
drawPango(layoutMain, &colWhite, 30, 0, 36, "Select SIM for SMS", 200);
std::string cname = book.resolveName(composeRecipient);
std::string toLine =
"To: " + (cname.empty() ? composeRecipient : cname);
drawPango(layoutSmall, &colLight, 12, 44, 22, toLine, 216);
for (int i = 0; i < 2; ++i) {
int ry = 74 + i * 74;
bool isSel = (simPickIdx == i);
XSetForeground(dpy, gc, isSel ? pt.spec.selBg : pt.spec.bgAltEven);
XFillRectangle(dpy, pix, gc, 10, ry, kWinWidth - 20, 64);
XSetForeground(dpy, gc, isSel ? pt.spec.accent : pt.spec.border);
XDrawRectangle(dpy, pix, gc, 10, ry, kWinWidth - 21, 63);
std::string op = (i == 0) ? simInfo.slot1Operator : simInfo.slot2Operator;
std::string rat = (i == 0) ? simInfo.slot1Rat : simInfo.slot2Rat;
std::string num = (i == 0) ? simInfo.slot1Number : simInfo.slot2Number;
if (op.empty()) op = "SIM " + std::to_string(i + 1);
std::string title = "[" + std::to_string(i + 1) + "] SIM " +
std::to_string(i + 1) + " - " + op;
if (!rat.empty()) title += " [" + rat + "]";
std::string sub = num.empty() ? "Ready" : num;
if (simInfo.preferredSlot == (i + 1)) {
sub += " (Default)";
}
drawPango(layoutIcon, isSel ? &colYellow : &colGreen, 18, ry + 8, 22,
kIconSim);
drawPango(layoutMain, &colWhite, 40, ry + 8, 22, title, kWinWidth - 54);
drawPango(layoutSmall, isSel ? &colLight : &colMuted, 40, ry + 34, 18,
sub, kWinWidth - 54);
}
drawPango(layoutSmall, &colMuted, 12, 230, 20,
"Press 1 or 2, or Up/Down + Send", 216);
drawSoftkeyBar("Send", "Select", "Back");
}
int64_t tNow = nowMs();
{
std::lock_guard<std::mutex> lk(sendMutex);
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& argStr) {
writeIntFile(activePidPath, static_cast<int>(::getpid()));
closeOtherPlugins("sms");
reloadAllData(true);
lastTapDigit = -1;
zeroHeld = false;
softkeyPending = 0;
if (argStr.rfind("send:", 0) == 0) {
openComposeView(argStr.substr(5));
} else if (argStr.rfind("thread:", 0) == 0) {
openThreadView(argStr.substr(7));
} else if (!argStr.empty()) {
openThreadView(argStr);
} else {
mode = ViewMode::Threads;
searchQuery.clear();
updateFilter();
selectedThread = 0;
}
if (!visible) {
visible = true;
XMapRaised(dpy, win);
} else {
XRaiseWindow(dpy, win);
}
grabPluginKeyboard(dpy, win);
openStartMs = nowMs();
startupIgnoreUntilMs = openStartMs + 180;
initialSoftkeysReleased = (querySoftkeysDown(dpy) == 0);
drawUI();
};
auto hideWindow = [&]() {
if (!visible) return;
if (mode == ViewMode::Compose && !composeRecipient.empty()) {
saveSmsDraft(normalizePhone(composeRecipient), composeText);
}
writeSoftkeySuppress(nowMs() + 450);
XUngrabKeyboard(dpy, CurrentTime);
XUnmapWindow(dpy, win);
XFlush(dpy);
visible = false;
::unlink(activePidPath.c_str());
};
auto commitMultiTapChar = [&](int digit) {
const char* chars = kMultiTapSms[digit];
int len = static_cast<int>(std::strlen(chars));
if (len <= 0) return;
int64_t t = nowMs();
if (caseMode == TextCaseMode::Num) {
composeText.push_back(static_cast<char>('0' + digit));
lastTapDigit = -1;
return;
}
bool sameKey = (lastTapDigit == digit && (t - lastTapMs) <= 850 &&
!composeText.empty());
if (sameKey) {
lastTapCycle = (lastTapCycle + 1) % len;
popUtf8Char(composeText);
} else {
lastTapDigit = digit;
lastTapCycle = 0;
}
lastTapMs = t;
char ch = chars[lastTapCycle];
if (std::isalpha(static_cast<unsigned char>(ch))) {
if (caseMode == TextCaseMode::Upper) {
ch = static_cast<char>(std::toupper(static_cast<unsigned char>(ch)));
} else if (caseMode == TextCaseMode::Title) {
bool startOfWord = composeText.empty() ||
composeText.back() == ' ' ||
composeText.back() == '\n' ||
composeText.back() == '.';
if (startOfWord) {
ch = static_cast<char>(std::toupper(static_cast<unsigned char>(ch)));
}
}
}
composeText.push_back(ch);
};
auto executeOption = [&](int optId) {
if (optId == 1) {
openComposeView("");
} else if (optId == 2 && !filteredThreads.empty()) {
openThreadView(filteredThreads[selectedThread].number);
} else if (optId == 3) {
std::string target = (prevMode == ViewMode::ThreadView)
? activeNumber
: (!filteredThreads.empty()
? filteredThreads[selectedThread].number
: "");
openComposeView(target);
} else if (optId == 4) {
std::string target = (prevMode == ViewMode::ThreadView)
? activeNumber
: (!filteredThreads.empty()
? filteredThreads[selectedThread].number
: "");
if (!target.empty()) {
placePhoneCall(target);
hideWindow();
}
} else if (optId == 5) {
std::string target = (prevMode == ViewMode::ThreadView)
? activeNumber
: (!filteredThreads.empty()
? filteredThreads[selectedThread].number
: "");
hideWindow();
if (!target.empty() && book.resolveName(target).empty()) {
sendPluginCommand("contacts", "OPEN new:" + target);
} else {
sendPluginCommand("contacts", "OPEN " + target);
}
} else if (optId == 6) {
activeNumber = (prevMode == ViewMode::ThreadView)
? activeNumber
: (!filteredThreads.empty()
? filteredThreads[selectedThread].number
: "");
if (!activeNumber.empty()) {
confirmSelected = 0;
mode = ViewMode::ConfirmDelete;
} else {
mode = prevMode;
}
} else if (optId == 7 && !threadMessages.empty()) {
std::string body = threadMessages[selectedMsg].text;
openComposeView("", body);
} else if (optId == 8) {
std::string target = (prevMode == ViewMode::ThreadView)
? activeNumber
: (!filteredThreads.empty()
? filteredThreads[selectedThread].number
: "");
if (!target.empty()) {
if (blockList.isBlocked(target) || viewingSpamFolder) {
blockList.unblockNumber(target);
moveSmsThreadBetweenDirs(target, getBlockDirPath(),
getModemLogDirPath());
std::lock_guard<std::mutex> lk(sendMutex);
statusBanner = "Unblocked & restored " + target;
statusBannerUntilMs = nowMs() + 2000;
} else {
std::string cname = book.resolveName(target);
blockList.blockNumber(target, cname.empty() ? "SMS Spam" : cname);
moveSmsThreadBetweenDirs(target, getModemLogDirPath(),
getBlockDirPath());
std::lock_guard<std::mutex> lk(sendMutex);
statusBanner = "Blocked " + target;
statusBannerUntilMs = nowMs() + 2000;
}
reloadAllData(true);
}
mode = ViewMode::Threads;
} else if (optId == 9) {
viewingSpamFolder = !viewingSpamFolder;
selectedThread = 0;
reloadAllData(true);
mode = ViewMode::Threads;
} else if (optId == 10) {
blockList.load();
blockSelected = 0;
mode = ViewMode::Blocklist;
} else if (optId == 11) {
std::string target = (prevMode == ViewMode::ThreadView)
? activeNumber
: (!filteredThreads.empty()
? filteredThreads[selectedThread].number
: "");
addBlockInput = target;
mode = ViewMode::AddBlock;
}
};
auto handleSoftkeyAction = [&](bool isLeft) {
if (mode == ViewMode::Threads) {
if (isLeft) {
prevMode = ViewMode::Threads;
buildOptions();
mode = ViewMode::Options;
} else {
if (!searchQuery.empty()) {
popUtf8Char(searchQuery);
updateFilter();
} else if (viewingSpamFolder) {
viewingSpamFolder = false;
selectedThread = 0;
updateFilter();
} else {
hideWindow();
return;
}
}
} else if (mode == ViewMode::ThreadView) {
if (isLeft) {
prevMode = ViewMode::ThreadView;
buildOptions();
mode = ViewMode::Options;
} else {
reloadAllData(true);
mode = ViewMode::Threads;
}
} else if (mode == ViewMode::Compose) {
if (isLeft) {
if (composeField == 0) {
pickerContacts = book.buildDialerList();
selectedPicker = 0;
mode = ViewMode::PickContact;
} else {
startAsyncSendSms(composeRecipient, composeText);
}
} else {
if (composeField == 0 && !composeRecipient.empty()) {
popUtf8Char(composeRecipient);
} else if (composeField == 1 && !composeText.empty()) {
popUtf8Char(composeText);
lastTapDigit = -1;
} else {
if (!composeRecipient.empty()) {
saveSmsDraft(normalizePhone(composeRecipient), composeText);
}
reloadAllData(true);
mode = (prevMode == ViewMode::ThreadView) ? ViewMode::ThreadView
: ViewMode::Threads;
}
}
} else if (mode == ViewMode::PickContact) {
if (isLeft) {
if (!pickerContacts.empty()) {
composeRecipient = pickerContacts[selectedPicker].number;
composeField = 1;
}
mode = ViewMode::Compose;
} else {
mode = ViewMode::Compose;
}
} else if (mode == ViewMode::Options) {
if (isLeft) {
if (!optionsList.empty()) {
executeOption(optionsList[selectedOption].id);
}
} else {
mode = prevMode;
}
} else if (mode == ViewMode::Blocklist) {
if (isLeft) {
addBlockInput.clear();
mode = ViewMode::AddBlock;
} else {
reloadAllData(true);
mode = prevMode;
}
} else if (mode == ViewMode::AddBlock) {
if (isLeft) {
std::string num = trimStr(addBlockInput);
if (!normalizePhone(num).empty()) {
blockList.blockNumber(num, "SMS Blocklist");
moveSmsThreadBetweenDirs(num, getModemLogDirPath(),
getBlockDirPath());
reloadAllData(true);
std::lock_guard<std::mutex> lk(sendMutex);
statusBanner = "Blocked " + num;
statusBannerUntilMs = nowMs() + 2000;
}
mode = ViewMode::Blocklist;
} else {
if (!addBlockInput.empty()) {
popUtf8Char(addBlockInput);
} else {
mode = ViewMode::Blocklist;
}
}
} else if (mode == ViewMode::ConfirmDelete) {
if (isLeft) {
if (confirmSelected == 1) {
deleteSmsThread(activeNumber, viewingSpamFolder
? getBlockDirPath()
: getModemLogDirPath());
reloadAllData(true);
mode = ViewMode::Threads;
} else {
mode = prevMode;
}
} else {
mode = prevMode;
}
} else if (mode == ViewMode::SelectSim) {
if (isLeft) {
mode = ViewMode::Compose;
startAsyncSendSms(composeRecipient, composeText,
(simPickIdx == 1) ? 2 : 1);
} else {
mode = ViewMode::Compose;
}
}
drawUI();
};
if (!isPreload) {
showWindow(initArg);
}
int xfd = ConnectionNumber(dpy);
int inotifyFd = ::inotify_init1(IN_NONBLOCK | IN_CLOEXEC);
if (inotifyFd >= 0) {
ContactBook::ensureParentDir(getModemLogFilePath());
ContactBook::ensureParentDir(getBlockedModemLogFilePath());
::inotify_add_watch(inotifyFd, getModemLogDirPath().c_str(),
IN_MODIFY | IN_CLOSE_WRITE | IN_MOVED_TO | IN_CREATE | IN_DELETE);
::inotify_add_watch(inotifyFd, getBlockDirPath().c_str(),
IN_MODIFY | IN_CLOSE_WRITE | IN_MOVED_TO | IN_CREATE | IN_DELETE);
}
while (gRunning) {
for (const auto& cmd : readFifoLines(fifoFd)) {
if (cmd == "NOP") {
continue;
} else if (cmd == "REFRESH") {
if (reloadAllData(false) && visible) drawUI();
} else if (cmd == "RELOAD_THEME") {
pt.reload();
reloadAllData(true);
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("sms")) {
hideWindow();
} else {
XRaiseWindow(dpy, win);
grabPluginKeyboard(dpy, win);
drawUI();
}
} else if (ev.type == KeyRelease) {
unsigned int kc = ev.xkey.keycode;
KeySym sym = XLookupKeysym(&ev.xkey, 0);
if (kc == 19 || sym == XK_0 || sym == XK_KP_0) {
zeroHeld = false;
}
} 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;
}
bool isCallKey =
(kc == 177 || sym == XF86XK_PickupPhone || sym == XF86XK_Phone ||
sym == _EVDEVK(0x1bd) || sym == _EVDEVK(0x0a9));
if (isCallKey) {
if (mode == ViewMode::SelectSim) {
mode = ViewMode::Compose;
startAsyncSendSms(composeRecipient, composeText,
(simPickIdx == 1) ? 2 : 1);
drawUI();
} else if (mode == ViewMode::Compose) {
startAsyncSendSms(composeRecipient, composeText);
drawUI();
} else if (mode == ViewMode::ThreadView && !activeNumber.empty()) {
placePhoneCall(activeNumber);
hideWindow();
} else if (mode == ViewMode::Threads && !filteredThreads.empty()) {
std::string num = filteredThreads[selectedThread].number;
placePhoneCall(num);
hideWindow();
}
continue;
}
if (sym == XK_BackSpace || sym == XK_Delete) {
handleSoftkeyAction(false);
continue;
}
if (mode == ViewMode::Threads) {
if (sym == XK_Left || sym == XK_KP_Left || sym == XK_Right ||
sym == XK_KP_Right) {
viewingSpamFolder = !viewingSpamFolder;
selectedThread = 0;
updateFilter();
drawUI();
} else if (sym == XK_Up || sym == XK_KP_Up) {
if (!filteredThreads.empty()) {
selectedThread =
(selectedThread - 1 + static_cast<int>(filteredThreads.size())) %
static_cast<int>(filteredThreads.size());
drawUI();
}
} else if (sym == XK_Down || sym == XK_KP_Down) {
if (!filteredThreads.empty()) {
selectedThread =
(selectedThread + 1) % static_cast<int>(filteredThreads.size());
drawUI();
}
} else if (sym == XK_Return || sym == XK_KP_Enter) {
if (filteredThreads.empty()) {
openComposeView("");
} else {
openThreadView(filteredThreads[selectedThread].number);
}
drawUI();
} else {
char d = mapDialKey(sym, kc, ev.xkey.state);
if (d >= '0' && d <= '9') {
searchQuery.push_back(d);
updateFilter();
drawUI();
} else if (d == '*') {
openComposeView("");
drawUI();
}
}
} else if (mode == ViewMode::ThreadView) {
int maxScroll = std::max(0, msgTextH - msgViewH);
if (sym == XK_Up || sym == XK_KP_Up) {
if (msgScrollPx > 0) {
msgScrollPx = std::max(0, msgScrollPx - kMsgScrollStep);
drawUI();
} else if (selectedMsg > 0) {
--selectedMsg;
msgScrollPx = 0;
drawUI();
}
} else if (sym == XK_Down || sym == XK_KP_Down) {
if (msgScrollPx < maxScroll) {
msgScrollPx = std::min(maxScroll, msgScrollPx + kMsgScrollStep);
drawUI();
} else if (selectedMsg + 1 <
static_cast<int>(threadMessages.size())) {
++selectedMsg;
msgScrollPx = 0;
drawUI();
}
} else if (sym == XK_Return || sym == XK_KP_Enter) {
openComposeView(activeNumber);
drawUI();
}
} else if (mode == ViewMode::Compose) {
if (sym == XK_Up || sym == XK_KP_Up) {
lastTapDigit = -1;
composeField = std::max(0, composeField - 1);
drawUI();
} else if (sym == XK_Down || sym == XK_KP_Down) {
lastTapDigit = -1;
composeField = std::min(3, composeField + 1);
drawUI();
} else if (sym == XK_Left || sym == XK_KP_Left) {
if (composeField == 3) {
composeField = 2;
drawUI();
} else {
lastTapDigit = -1;
}
} else if (sym == XK_Right || sym == XK_KP_Right) {
if (composeField == 2) {
composeField = 3;
drawUI();
} else if (composeField == 0 && composeRecipient.empty()) {
composeRecipient = "+";
drawUI();
} else {
lastTapDigit = -1;
}
} else if (sym == XK_Return || sym == XK_KP_Enter) {
if (composeField == 0) {
if (composeRecipient.empty()) {
pickerContacts = book.buildDialerList();
selectedPicker = 0;
mode = ViewMode::PickContact;
} else {
composeField = 1;
}
} else if (composeField == 1 || composeField == 2) {
startAsyncSendSms(composeRecipient, composeText);
} else if (composeField == 3) {
saveSmsDraft(normalizePhone(composeRecipient), composeText);
statusBanner = "Draft saved";
statusBannerUntilMs = nowMs() + 1800;
reloadAllData(true);
mode = (prevMode == ViewMode::ThreadView) ? ViewMode::ThreadView
: ViewMode::Threads;
}
drawUI();
} else {
char d = mapDialKey(sym, kc, ev.xkey.state);
if (composeField == 0) {
if (d == '0') {
zeroHeld = true;
zeroPressMs = tNow;
composeRecipient.push_back('0');
drawUI();
} else if ((d >= '1' && d <= '9') || d == '+') {
composeRecipient.push_back(d);
drawUI();
}
} else if (composeField == 1) {
if (!isExternalKeyboardActive()) {
if (d == '#') {
lastTapDigit = -1;
caseMode = static_cast<TextCaseMode>(
(static_cast<int>(caseMode) + 1) % 4);
drawUI();
continue;
} else if (d == '*') {
commitMultiTapChar(1);
drawUI();
continue;
} else if (d >= '0' && d <= '9') {
commitMultiTapChar(d - '0');
drawUI();
continue;
}
}
if (sym >= 0x20 && sym <= 0x7e &&
!(ev.xkey.state & (ControlMask | Mod1Mask))) {
composeText.push_back(static_cast<char>(sym));
lastTapDigit = -1;
drawUI();
}
}
}
} else if (mode == ViewMode::PickContact) {
if (sym == XK_Up || sym == XK_KP_Up) {
if (!pickerContacts.empty()) {
selectedPicker =
(selectedPicker - 1 + static_cast<int>(pickerContacts.size())) %
static_cast<int>(pickerContacts.size());
drawUI();
}
} else if (sym == XK_Down || sym == XK_KP_Down) {
if (!pickerContacts.empty()) {
selectedPicker =
(selectedPicker + 1) % static_cast<int>(pickerContacts.size());
drawUI();
}
} else if (sym == XK_Return || sym == XK_KP_Enter) {
handleSoftkeyAction(true);
}
} else if (mode == ViewMode::Options) {
if (sym == XK_Up || sym == XK_KP_Up) {
if (!optionsList.empty()) {
selectedOption =
(selectedOption - 1 + static_cast<int>(optionsList.size())) %
static_cast<int>(optionsList.size());
drawUI();
}
} else if (sym == XK_Down || sym == XK_KP_Down) {
if (!optionsList.empty()) {
selectedOption =
(selectedOption + 1) % static_cast<int>(optionsList.size());
drawUI();
}
} else if (sym == XK_Return || sym == XK_KP_Enter) {
handleSoftkeyAction(true);
}
} else if (mode == ViewMode::Blocklist) {
if (sym == XK_Up || sym == XK_KP_Up) {
if (!blockList.entries().empty()) {
int n = static_cast<int>(blockList.entries().size());
blockSelected = (blockSelected + n - 1) % n;
drawUI();
}
} else if (sym == XK_Down || sym == XK_KP_Down) {
if (!blockList.entries().empty()) {
int n = static_cast<int>(blockList.entries().size());
blockSelected = (blockSelected + 1) % n;
drawUI();
}
} else if (sym == XK_Return || sym == XK_KP_Enter) {
if (!blockList.entries().empty() && blockSelected >= 0 &&
blockSelected < static_cast<int>(blockList.entries().size())) {
std::string num = blockList.entries()[blockSelected].number;
blockList.unblockNumber(num);
moveSmsThreadBetweenDirs(num, getBlockDirPath(),
getModemLogDirPath());
reloadAllData(true);
{
std::lock_guard<std::mutex> lk(sendMutex);
statusBanner = "Unblocked " + num;
statusBannerUntilMs = nowMs() + 1800;
}
drawUI();
}
}
} else if (mode == ViewMode::AddBlock) {
if (sym == XK_Left || sym == XK_KP_Left) {
if (!addBlockInput.empty()) {
popUtf8Char(addBlockInput);
drawUI();
}
} else if (sym == XK_Return || sym == XK_KP_Enter) {
handleSoftkeyAction(true);
} else {
char d = mapDialKey(sym, kc, ev.xkey.state);
if (d == '#') {
if (addBlockInput.empty()) {
addBlockInput.push_back('+');
} else {
addBlockInput.push_back('#');
}
drawUI();
} else if (d != '\0') {
addBlockInput.push_back(d);
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::SelectSim) {
char d = mapDialKey(sym, kc, ev.xkey.state);
if (d == '1') {
simPickIdx = 0;
handleSoftkeyAction(true);
} else if (d == '2') {
simPickIdx = 1;
handleSoftkeyAction(true);
} else if (sym == XK_Up || sym == XK_Down || sym == XK_KP_Up ||
sym == XK_KP_Down) {
simPickIdx = 1 - simPickIdx;
drawUI();
} else if (sym == XK_Return || sym == XK_KP_Enter) {
handleSoftkeyAction(true);
}
}
}
}
int64_t tNow = nowMs();
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 && zeroHeld && mode == ViewMode::Compose && composeField == 0 &&
(tNow - zeroPressMs) >= 420) {
if (isKeycodeDown(dpy, 19)) {
if (!composeRecipient.empty() && composeRecipient.back() == '0') {
composeRecipient.back() = '+';
drawUI();
}
}
zeroHeld = false;
}
if (visible && mode == ViewMode::Compose && lastTapDigit != -1 &&
(tNow - lastTapMs) > 850) {
lastTapDigit = -1;
drawUI();
}
int64_t bannerDeadline = 0;
bool bannerExpired = false;
{
std::lock_guard<std::mutex> lk(sendMutex);
if (!statusBanner.empty() && statusBannerUntilMs > 0) {
if (tNow >= statusBannerUntilMs) {
statusBanner.clear();
statusBannerUntilMs = 0;
bannerExpired = true;
} else {
bannerDeadline = statusBannerUntilMs;
}
}
}
if (visible && bannerExpired) {
drawUI();
}
int timeoutMs = -1;
if (visible) {
if (!initialSoftkeysReleased) {
timeoutMs = 40;
}
if (softkeyPending != 0) {
int rem = std::max(1, static_cast<int>(softkeyDeadlineMs - tNow));
timeoutMs = (timeoutMs < 0) ? rem : std::min(timeoutMs, rem);
}
if (zeroHeld) {
int rem = std::max(1, static_cast<int>((zeroPressMs + 420) - tNow));
timeoutMs = (timeoutMs < 0) ? rem : std::min(timeoutMs, rem);
}
if (mode == ViewMode::Compose && lastTapDigit != -1) {
int rem = std::max(1, static_cast<int>(851 - (tNow - lastTapMs)));
timeoutMs = (timeoutMs < 0) ? rem : std::min(timeoutMs, rem);
}
if (bannerDeadline > 0) {
int rem = std::max(1, static_cast<int>(bannerDeadline - tNow));
timeoutMs = (timeoutMs < 0) ? rem : std::min(timeoutMs, rem);
}
}
struct pollfd pfds[4];
int nfds = 0;
pfds[nfds++] = {xfd, POLLIN, 0};
int fifoIdx = -1;
if (fifoFd >= 0) {
fifoIdx = nfds;
pfds[nfds++] = {fifoFd, POLLIN, 0};
}
int pipeIdx = -1;
if (notifyPipe[0] >= 0) {
pipeIdx = nfds;
pfds[nfds++] = {notifyPipe[0], POLLIN, 0};
}
int inotifyIdx = -1;
if (inotifyFd >= 0 && visible) {
inotifyIdx = nfds;
pfds[nfds++] = {inotifyFd, POLLIN, 0};
}
int pr = ::poll(pfds, nfds, timeoutMs);
if (pr > 0) {
if (fifoIdx >= 0 && (pfds[fifoIdx].revents & POLLIN)) {
for (const auto& cmd : readFifoLines(fifoFd)) {
if (cmd == "REFRESH") {
if (reloadAllData(false) && visible) drawUI();
} else if (cmd == "RELOAD_THEME") {
pt.reload();
reloadAllData(true);
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)));
}
}
}
if (pipeIdx >= 0 && (pfds[pipeIdx].revents & POLLIN)) {
char drain[32];
while (::read(notifyPipe[0], drain, sizeof(drain)) > 0) {
}
std::string sentTo = normalizePhone(composeRecipient);
reloadAllData(true);
if (!sentTo.empty()) {
openThreadView(sentTo);
}
drawUI();
}
if (inotifyIdx >= 0 && (pfds[inotifyIdx].revents & POLLIN)) {
char ibuf[512];
while (::read(inotifyFd, ibuf, sizeof(ibuf)) > 0) {
}
if (reloadAllData(false) && visible) {
drawUI();
}
}
}
}
hideWindow();
if (inotifyFd >= 0) ::close(inotifyFd);
if (fifoFd >= 0) ::close(fifoFd);
if (notifyPipe[0] >= 0) ::close(notifyPipe[0]);
if (notifyPipe[1] >= 0) ::close(notifyPipe[1]);
::unlink(daemonPidPath.c_str());
return 0;
}
int sms_plugin_init(const DwmHostApi* host) {
if (host && host->spawn_plugin) {
host->spawn_plugin("sms", "--preload");
}
return 0;
}
} // namespace
extern "C" __attribute__((visibility("default"))) const DwmPlugin dwm_plugin_entry = {
DWM_PLUGIN_API_VERSION,
"sms",
"Keypad-driven SMS conversation manager and editor integrated with Sxmo",
sms_plugin_init,
nullptr,
nullptr,
nullptr,
nullptr,
runSmsApp
};