Files
bananarchy/src/dwm-plugins/phone_data.h
T

1247 lines
36 KiB
C++
Raw Normal View History

#ifndef DWM_PLUGINS_PHONE_DATA_H
#define DWM_PLUGINS_PHONE_DATA_H
#include <X11/Xlib.h>
#include <X11/keysym.h>
#include <X11/XF86keysym.h>
#ifndef _EVDEVK
#define _EVDEVK(_v) (0x10081000 + (_v))
#endif
#include <algorithm>
#include <cctype>
#include <csignal>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <dirent.h>
#include <fcntl.h>
#include <fstream>
#include <sstream>
#include <string>
#include <sys/stat.h>
#include <unistd.h>
#include <unordered_map>
#include <unordered_set>
#include <vector>
namespace bananarchy {
constexpr int kScreenWidth = 240;
constexpr int kScreenHeight = 320;
constexpr int kTopBarHeight = 24;
constexpr int kWinX = 0;
constexpr int kWinY = kTopBarHeight;
constexpr int kWinWidth = kScreenWidth;
constexpr int kWinHeight = kScreenHeight - kTopBarHeight; // 296px flush below 24px dwm bar
// Nerd Font PUA icons matching sxmo_hook_icons.sh & dwm ("Fira Code, DejaVuSansM Nerd Font")
constexpr const char* kIconPhone = "\xef\x82\x95"; // U+F095 phone handset
constexpr const char* kIconPhoneLog = "\xef\x82\x98"; // U+F098 phone square
constexpr const char* kIconUser = "\xef\x80\x87"; // U+F007 user contact
constexpr const char* kIconBook = "\xef\x83\x80"; // U+F0C0 address book / users
constexpr const char* kIconClock = "\xef\x80\x97"; // U+F017 recent clock
constexpr const char* kIconOutCall = "\xef\x85\xb8"; // U+F178 outgoing arrow
constexpr const char* kIconInCall = "\xef\x85\xb5"; // U+F175 incoming arrow
constexpr const char* kIconMissedCall = "\xef\x81\xb1"; // U+F071 missed/alert
constexpr const char* kIconBackspace = "\xef\x86\x90"; // U+F190 left circle arrow
constexpr const char* kIconSearch = "\xef\x80\x82"; // U+F002 search
constexpr const char* kIconPlus = "\xef\x81\xa7"; // U+F067 plus/add
constexpr const char* kIconEdit = "\xef\x81\x84"; // U+F044 edit
constexpr const char* kIconTrash = "\xef\x87\xb8"; // U+F1F8 delete/trash
constexpr const char* kIconSms = "\xef\x83\xa0"; // U+F0E0 envelope/SMS
constexpr const char* kIconList = "\xef\x80\xba"; // U+F03A list
constexpr const char* kIconCheck = "\xef\x80\x8c"; // U+F00C check
constexpr const char* kIconFolder = "\xef\x81\xbb"; // U+F07B folder
constexpr const char* kIconFolderOpen = "\xef\x81\xbc"; // U+F07C folder-open
constexpr const char* kIconFile = "\xef\x80\x96"; // U+F016 file
constexpr const char* kIconFileText = "\xef\x85\x9c"; // U+F15C file-text
constexpr const char* kIconImage = "\xef\x80\xbe"; // U+F03E image
constexpr const char* kIconMusic = "\xef\x80\x81"; // U+F001 music/audio
constexpr const char* kIconTerm = "\xef\x84\xa0"; // U+F120 terminal
constexpr const char* kIconCamera = "\xef\x80\xb0"; // U+F030 camera
constexpr const char* kIconFlash = "\xef\x83\xa7"; // U+F0E7 bolt/flash
constexpr const char* kIconSend = "\xef\x87\x98"; // U+F1D8 paper-plane
constexpr const char* kIconCopy = "\xef\x83\x85"; // U+F0C5 copy
constexpr const char* kIconInfo = "\xef\x81\x9a"; // U+F05A info-circle
constexpr const char* kIconRefresh = "\xef\x80\xa1"; // U+F021 refresh
constexpr const char* kIconSort = "\xef\x83\x9c"; // U+F0DC sort
constexpr const char* kIconEye = "\xef\x81\xae"; // U+F06E eye/view
inline int64_t nowMs() {
struct timespec ts {};
clock_gettime(CLOCK_MONOTONIC, &ts);
return static_cast<int64_t>(ts.tv_sec) * 1000 + ts.tv_nsec / 1000000;
}
inline std::string getRuntimeFile(const char* name) {
const char* rdir = std::getenv("XDG_RUNTIME_DIR");
std::string base = (rdir && rdir[0]) ? rdir : "/run/user/10000";
if (::access(base.c_str(), W_OK) != 0) {
base = "/tmp";
}
return base + "/" + name;
}
inline int readIntFile(const std::string& path, int fallback = -1) {
int fd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC);
if (fd < 0) {
return fallback;
}
char buf[64];
ssize_t n = ::read(fd, buf, sizeof(buf) - 1);
::close(fd);
if (n <= 0) {
return fallback;
}
buf[n] = '\0';
return std::atoi(buf);
}
inline bool writeIntFile(const std::string& path, int value) {
int fd = ::open(path.c_str(), O_WRONLY | O_TRUNC | O_CREAT | O_CLOEXEC, 0644);
if (fd < 0) {
return false;
}
char buf[32];
int len = std::snprintf(buf, sizeof(buf), "%d\n", value);
ssize_t w = ::write(fd, buf, len);
::close(fd);
return w == len;
}
inline bool isPidFileAlive(const std::string& path) {
int pid = readIntFile(path, -1);
return (pid > 0 && ::kill(pid, 0) == 0);
}
inline std::string getPluginFifoPath(const char* name) {
return std::string("/tmp/dwm_plugin_") + name + ".fifo";
}
inline std::string getPluginDaemonPidPath(const char* name) {
return std::string("/tmp/dwm_plugin_") + name + ".pid";
}
inline bool isPluginDaemonAlive(const char* name) {
if (!name || !name[0]) {
return false;
}
int pid = readIntFile(getPluginDaemonPidPath(name), -1);
if (pid <= 0 || pid == static_cast<int>(::getpid()) || ::kill(pid, 0) != 0) {
return false;
}
char cmdPath[64];
std::snprintf(cmdPath, sizeof(cmdPath), "/proc/%d/cmdline", pid);
int fd = ::open(cmdPath, O_RDONLY | O_CLOEXEC);
if (fd < 0) {
return false;
}
char buf[256];
ssize_t n = ::read(fd, buf, sizeof(buf) - 1);
::close(fd);
if (n <= 0) {
return false;
}
for (ssize_t i = 0; i < n; ++i) {
if (buf[i] == '\0') {
buf[i] = ' ';
}
}
buf[n] = '\0';
return (std::strstr(buf, "dwm-plugin") != nullptr &&
std::strstr(buf, name) != nullptr);
}
inline bool sendPluginCommand(const char* name, const std::string& cmdLine) {
if (!isPluginDaemonAlive(name)) {
return false;
}
std::string fifoPath = getPluginFifoPath(name);
int fd = ::open(fifoPath.c_str(), O_WRONLY | O_NONBLOCK | O_CLOEXEC);
if (fd < 0) {
return false;
}
std::string msg = cmdLine + "\n";
ssize_t w = ::write(fd, msg.data(), msg.size());
::close(fd);
return w == static_cast<ssize_t>(msg.size());
}
inline int setupPluginDaemonFifo(const char* name) {
std::string fifoPath = getPluginFifoPath(name);
::mkfifo(fifoPath.c_str(), 0666);
::chmod(fifoPath.c_str(), 0666);
return ::open(fifoPath.c_str(), O_RDWR | O_NONBLOCK | O_CLOEXEC);
}
inline std::vector<std::string> readFifoLines(int fifoFd) {
std::vector<std::string> lines;
if (fifoFd < 0) {
return lines;
}
char buf[512];
ssize_t n = ::read(fifoFd, buf, sizeof(buf) - 1);
if (n <= 0) {
return lines;
}
buf[n] = '\0';
std::stringstream ss(buf);
std::string line;
while (std::getline(ss, line)) {
if (!line.empty() && line.back() == '\r') {
line.pop_back();
}
if (!line.empty()) {
lines.push_back(line);
}
}
return lines;
}
inline bool isCallRingingFast() {
std::string jobPath = getRuntimeFile("sxmo_jobs/ringing");
if (::access(jobPath.c_str(), F_OK) == 0) {
return true;
}
std::string ringPidFile = getRuntimeFile("sxmo.ring.pid");
int pid = readIntFile(ringPidFile, -1);
return (pid > 0 && ::kill(pid, 0) == 0);
}
struct FileStamp {
time_t sec = -1;
long nsec = -1;
off_t size = -1;
bool checkAndUpdate(const std::string& path) {
struct stat st {};
if (::stat(path.c_str(), &st) != 0) {
if (sec != 0 || size != 0) {
sec = 0;
nsec = 0;
size = 0;
return true;
}
return false;
}
if (st.st_mtim.tv_sec != sec || st.st_mtim.tv_nsec != nsec ||
st.st_size != size) {
sec = st.st_mtim.tv_sec;
nsec = st.st_mtim.tv_nsec;
size = st.st_size;
return true;
}
return false;
}
};
inline void writeSoftkeySuppress(int64_t untilMs) {
int fd = ::open("/tmp/sxmo_softkey_suppress",
O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
if (fd >= 0) {
char buf[32];
int len = std::snprintf(buf, sizeof(buf), "%lld\n",
static_cast<long long>(untilMs));
(void)::write(fd, buf, len);
::close(fd);
}
}
inline int querySoftkeysDown(Display* d) {
char km[32];
if (!XQueryKeymap(d, km)) {
return 0;
}
int mask = 0;
if (km[135 / 8] & (1 << (135 % 8))) {
mask |= 1;
}
if (km[166 / 8] & (1 << (166 % 8))) {
mask |= 2;
}
return mask;
}
inline bool isKeycodeDown(Display* d, int keycode) {
if (keycode <= 0 || keycode >= 256) {
return false;
}
char km[32];
if (!XQueryKeymap(d, km)) {
return false;
}
return (km[keycode / 8] & (1 << (keycode % 8))) != 0;
}
inline void runAsyncCmd(const std::string& cmd) {
pid_t pid = ::fork();
if (pid == 0) {
::setsid();
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);
}
}
execl("/bin/sh", "sh", "-c", cmd.c_str(), static_cast<char*>(nullptr));
_exit(0);
}
}
inline void runAsyncArgv(const char* prog,
const char* arg1 = nullptr,
const char* arg2 = nullptr) {
pid_t pid = ::fork();
if (pid == 0) {
::setsid();
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);
}
}
if (arg1 && arg2) {
execlp(prog, prog, arg1, arg2, static_cast<char*>(nullptr));
std::string localBin = std::string("/home/user/.local/bin/") + prog;
execl(localBin.c_str(), prog, arg1, arg2, static_cast<char*>(nullptr));
std::string usrBin = std::string("/usr/bin/") + prog;
execl(usrBin.c_str(), prog, arg1, arg2, static_cast<char*>(nullptr));
} else if (arg1) {
execlp(prog, prog, arg1, static_cast<char*>(nullptr));
std::string localBin = std::string("/home/user/.local/bin/") + prog;
execl(localBin.c_str(), prog, arg1, static_cast<char*>(nullptr));
std::string usrBin = std::string("/usr/bin/") + prog;
execl(usrBin.c_str(), prog, arg1, static_cast<char*>(nullptr));
} else {
execlp(prog, prog, static_cast<char*>(nullptr));
std::string localBin = std::string("/home/user/.local/bin/") + prog;
execl(localBin.c_str(), prog, static_cast<char*>(nullptr));
std::string usrBin = std::string("/usr/bin/") + prog;
execl(usrBin.c_str(), prog, static_cast<char*>(nullptr));
}
_exit(0);
}
}
inline char mapDialKey(KeySym sym, unsigned int keycode, unsigned int state) {
if (state & (ControlMask | Mod1Mask | Mod4Mask)) {
return '\0';
}
// Keypad star (*)
if (keycode == 63 || keycode == 530 || sym == XK_asterisk ||
sym == XK_KP_Multiply || static_cast<uint32_t>(sym) == 0x1008ffaa) {
return '*';
}
// Keypad pound (#)
if (keycode == 106 || keycode == 531 || sym == XK_numbersign ||
sym == XK_KP_Divide || static_cast<uint32_t>(sym) == 0x1008ffab) {
return '#';
}
if (sym == XK_plus || sym == XK_KP_Add) {
return '+';
}
if (sym >= XK_0 && sym <= XK_9) {
return static_cast<char>('0' + (sym - XK_0));
}
if (sym >= XK_KP_0 && sym <= XK_KP_9) {
return static_cast<char>('0' + (sym - XK_KP_0));
}
if (keycode >= 10 && keycode <= 18) {
return static_cast<char>('1' + (keycode - 10));
}
if (keycode == 19) {
return '0';
}
return '\0';
}
inline std::string trimStr(const std::string& s) {
size_t b = 0;
while (b < s.size() && std::isspace(static_cast<unsigned char>(s[b]))) {
++b;
}
size_t e = s.size();
while (e > b && std::isspace(static_cast<unsigned char>(s[e - 1]))) {
--e;
}
return s.substr(b, e - b);
}
inline std::string normalizePhone(const std::string& raw) {
std::string out;
out.reserve(raw.size());
for (char c : raw) {
if (std::isdigit(static_cast<unsigned char>(c)) || c == '+' || c == '*' ||
c == '#') {
out.push_back(c);
}
}
return out;
}
inline std::string phoneSuffixKey(const std::string& norm) {
std::string digits;
for (char c : norm) {
if (std::isdigit(static_cast<unsigned char>(c))) {
digits.push_back(c);
}
}
if (digits.size() >= 9) {
return digits.substr(digits.size() - 9);
}
return norm;
}
inline std::string toLowerStr(const std::string& s) {
std::string out = s;
for (char& c : out) {
c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
}
return out;
}
inline std::string toT9Digits(const std::string& name) {
std::string out;
out.reserve(name.size());
for (unsigned char uc : name) {
char c = static_cast<char>(std::tolower(uc));
if (c >= 'a' && c <= 'c') out.push_back('2');
else if (c >= 'd' && c <= 'f') out.push_back('3');
else if (c >= 'g' && c <= 'i') out.push_back('4');
else if (c >= 'j' && c <= 'l') out.push_back('5');
else if (c >= 'm' && c <= 'o') out.push_back('6');
else if (c >= 'p' && c <= 's') out.push_back('7');
else if (c >= 't' && c <= 'v') out.push_back('8');
else if (c >= 'w' && c <= 'z') out.push_back('9');
else if (c == ' ') out.push_back('0');
else if (std::isdigit(uc)) out.push_back(c);
}
return out;
}
inline std::string getContactsFilePath() {
const char* env = std::getenv("SXMO_CONTACTFILE");
if (env && env[0]) {
return env;
}
const char* xdg = std::getenv("XDG_CONFIG_HOME");
if (xdg && xdg[0]) {
return std::string(xdg) + "/sxmo/contacts.tsv";
}
const char* home = std::getenv("HOME");
return std::string(home && home[0] ? home : "/home/user") +
"/.config/sxmo/contacts.tsv";
}
inline std::string getModemLogFilePath() {
const char* env = std::getenv("SXMO_LOGDIR");
if (env && env[0]) {
return std::string(env) + "/modemlog.tsv";
}
const char* xdg = std::getenv("XDG_DATA_HOME");
if (xdg && xdg[0]) {
return std::string(xdg) + "/sxmo/modem/modemlog.tsv";
}
const char* home = std::getenv("HOME");
return std::string(home && home[0] ? home : "/home/user") +
"/.local/share/sxmo/modem/modemlog.tsv";
}
struct ContactEntry {
std::string name;
std::string number;
std::string normNumber;
std::string t9Name;
std::string lowerName;
bool isRecent = false;
};
class ContactBook {
public:
void load() {
saved_.clear();
exactMap_.clear();
suffixMap_.clear();
std::ifstream cf(getContactsFilePath());
std::string line;
while (std::getline(cf, line)) {
if (line.empty()) {
continue;
}
size_t tab = line.find('\t');
if (tab == std::string::npos) {
continue;
}
std::string num = trimStr(line.substr(0, tab));
std::string name = trimStr(line.substr(tab + 1));
std::string norm = normalizePhone(num);
if (norm.empty() || name.empty()) {
continue;
}
ContactEntry e;
e.name = name;
e.number = num;
e.normNumber = norm;
e.t9Name = toT9Digits(name);
e.lowerName = toLowerStr(name);
e.isRecent = false;
saved_.push_back(e);
exactMap_[norm] = name;
std::string sfx = phoneSuffixKey(norm);
if (!sfx.empty()) {
suffixMap_[sfx] = name;
}
}
std::sort(saved_.begin(), saved_.end(),
[](const ContactEntry& a, const ContactEntry& b) {
return a.lowerName < b.lowerName;
});
}
std::string resolveName(const std::string& rawNumber) const {
std::string norm = normalizePhone(rawNumber);
if (norm.empty()) {
return "";
}
auto it = exactMap_.find(norm);
if (it != exactMap_.end()) {
return it->second;
}
std::string sfx = phoneSuffixKey(norm);
if (!sfx.empty()) {
auto sit = suffixMap_.find(sfx);
if (sit != suffixMap_.end()) {
return sit->second;
}
}
return "";
}
std::vector<ContactEntry> buildDialerList() const {
std::vector<ContactEntry> out;
std::unordered_set<std::string> seenKey;
// 1. Recent unique numbers from modemlog.tsv in reverse chronological order
std::ifstream lf(getModemLogFilePath());
std::vector<std::string> logLines;
std::string line;
while (std::getline(lf, line)) {
if (!line.empty()) {
logLines.push_back(line);
}
}
for (auto it = logLines.rbegin(); it != logLines.rend(); ++it) {
size_t t1 = it->find('\t');
if (t1 == std::string::npos) continue;
size_t t2 = it->find('\t', t1 + 1);
if (t2 == std::string::npos) continue;
size_t t3 = it->find('\t', t2 + 1);
std::string num = trimStr(
t3 == std::string::npos ? it->substr(t2 + 1) : it->substr(t2 + 1, t3 - t2 - 1));
if (num.empty() || num == "NULL" || num.find('+', 1) != std::string::npos) {
continue;
}
std::string norm = normalizePhone(num);
if (norm.empty()) continue;
std::string key = phoneSuffixKey(norm);
if (seenKey.count(key) || seenKey.count(norm)) {
continue;
}
seenKey.insert(key);
seenKey.insert(norm);
ContactEntry e;
std::string cname = resolveName(num);
e.name = cname.empty() ? num : cname;
e.number = num;
e.normNumber = norm;
e.t9Name = toT9Digits(e.name);
e.lowerName = toLowerStr(e.name);
e.isRecent = true;
out.push_back(e);
}
// 2. All saved contacts (skipping duplicates already added from recents)
for (const auto& c : saved_) {
std::string key = phoneSuffixKey(c.normNumber);
if (seenKey.count(key) || seenKey.count(c.normNumber)) {
continue;
}
seenKey.insert(key);
seenKey.insert(c.normNumber);
out.push_back(c);
}
return out;
}
const std::vector<ContactEntry>& savedContacts() const { return saved_; }
std::vector<std::string> unknownRecentNumbers() const {
std::vector<std::string> out;
std::unordered_set<std::string> seen;
std::ifstream lf(getModemLogFilePath());
std::vector<std::string> logLines;
std::string line;
while (std::getline(lf, line)) {
if (!line.empty()) {
logLines.push_back(line);
}
}
for (auto it = logLines.rbegin(); it != logLines.rend(); ++it) {
size_t t1 = it->find('\t');
if (t1 == std::string::npos) continue;
size_t t2 = it->find('\t', t1 + 1);
if (t2 == std::string::npos) continue;
size_t t3 = it->find('\t', t2 + 1);
std::string num = trimStr(
t3 == std::string::npos ? it->substr(t2 + 1)
: it->substr(t2 + 1, t3 - t2 - 1));
if (num.empty() || num == "NULL" || num.find('+', 1) != std::string::npos) {
continue;
}
std::string norm = normalizePhone(num);
if (norm.empty() || !resolveName(num).empty()) {
continue;
}
std::string key = phoneSuffixKey(norm);
if (seen.count(key) || seen.count(norm)) {
continue;
}
seen.insert(key);
seen.insert(norm);
out.push_back(num);
}
return out;
}
static void ensureParentDir(const std::string& filePath) {
size_t slash = filePath.rfind('/');
if (slash == std::string::npos || slash == 0) {
return;
}
std::string dir = filePath.substr(0, slash);
std::string cur;
for (size_t i = 0; i < dir.size(); ++i) {
cur.push_back(dir[i]);
if (dir[i] == '/' && cur.size() > 1) {
::mkdir(cur.c_str(), 0755);
}
}
::mkdir(dir.c_str(), 0755);
}
bool addOrUpdateContact(const std::string& oldNumber,
const std::string& oldName,
const std::string& newNumberRaw,
const std::string& newNameRaw) {
std::string newNumber = trimStr(newNumberRaw);
std::string newName = trimStr(newNameRaw);
for (char& ch : newName) {
if (ch == '\t' || ch == '\r' || ch == '\n') {
ch = ' ';
}
}
if (newNumber.empty() || newName.empty()) {
return false;
}
std::string path = getContactsFilePath();
ensureParentDir(path);
std::vector<std::pair<std::string, std::string>> rows;
{
std::ifstream in(path);
std::string line;
while (std::getline(in, line)) {
if (line.empty()) continue;
size_t tab = line.find('\t');
if (tab == std::string::npos) continue;
std::string num = trimStr(line.substr(0, tab));
std::string name = trimStr(line.substr(tab + 1));
if (!num.empty() && !name.empty()) {
rows.push_back({num, name});
}
}
}
bool replaced = false;
std::string oldNorm = normalizePhone(oldNumber);
std::string newNorm = normalizePhone(newNumber);
for (auto& r : rows) {
if (!oldNumber.empty() &&
((r.first == oldNumber && r.second == oldName) ||
(!oldNorm.empty() && normalizePhone(r.first) == oldNorm &&
r.second == oldName))) {
r.first = newNumber;
r.second = newName;
replaced = true;
break;
}
}
if (!replaced && oldNumber.empty()) {
for (auto& r : rows) {
if (r.first == newNumber ||
(!newNorm.empty() && normalizePhone(r.first) == newNorm)) {
r.first = newNumber;
r.second = newName;
replaced = true;
break;
}
}
}
if (!replaced) {
rows.push_back({newNumber, newName});
}
std::ofstream out(path, std::ios::trunc);
if (!out.is_open()) {
return false;
}
for (const auto& r : rows) {
out << r.first << "\t" << r.second << "\n";
}
out.close();
load();
return true;
}
bool deleteContact(const std::string& number, const std::string& name) {
std::string path = getContactsFilePath();
std::vector<std::pair<std::string, std::string>> rows;
std::string targetNorm = normalizePhone(number);
bool removed = false;
{
std::ifstream in(path);
std::string line;
while (std::getline(in, line)) {
if (line.empty()) continue;
size_t tab = line.find('\t');
if (tab == std::string::npos) continue;
std::string num = trimStr(line.substr(0, tab));
std::string nm = trimStr(line.substr(tab + 1));
if (num.empty() || nm.empty()) continue;
if (!removed &&
((num == number && nm == name) ||
(!targetNorm.empty() && normalizePhone(num) == targetNorm &&
nm == name))) {
removed = true;
continue;
}
rows.push_back({num, nm});
}
}
if (!removed) {
return false;
}
std::ofstream out(path, std::ios::trunc);
if (!out.is_open()) {
return false;
}
for (const auto& r : rows) {
out << r.first << "\t" << r.second << "\n";
}
out.close();
load();
return true;
}
private:
std::vector<ContactEntry> saved_;
std::unordered_map<std::string, std::string> exactMap_;
std::unordered_map<std::string, std::string> suffixMap_;
};
enum class CallDirection {
Incoming = 0,
Outgoing = 1,
Missed = 2,
};
struct CallLogItem {
CallDirection direction;
std::string number;
std::string contactName;
std::string displayTime;
int durationSec = 0;
};
inline time_t parseIsoTime(const std::string& iso) {
if (iso.size() < 19) {
return 0;
}
struct tm tmVal {};
tmVal.tm_year = std::atoi(iso.substr(0, 4).c_str()) - 1900;
tmVal.tm_mon = std::atoi(iso.substr(5, 2).c_str()) - 1;
tmVal.tm_mday = std::atoi(iso.substr(8, 2).c_str());
tmVal.tm_hour = std::atoi(iso.substr(11, 2).c_str());
tmVal.tm_min = std::atoi(iso.substr(14, 2).c_str());
tmVal.tm_sec = std::atoi(iso.substr(17, 2).c_str());
tmVal.tm_isdst = -1;
return mktime(&tmVal);
}
inline std::string formatShortTime(const std::string& iso) {
if (iso.size() < 16) {
return iso;
}
// Convert "YYYY-MM-DDTHH:MM:SS+0300" -> "MM-DD HH:MM"
return iso.substr(5, 5) + " " + iso.substr(11, 5);
}
inline std::string formatDuration(int sec) {
if (sec <= 0) {
return "";
}
char buf[32];
if (sec >= 3600) {
std::snprintf(buf, sizeof(buf), "%dh%02dm", sec / 3600, (sec % 3600) / 60);
} else if (sec >= 60) {
std::snprintf(buf, sizeof(buf), "%dm%02ds", sec / 60, sec % 60);
} else {
std::snprintf(buf, sizeof(buf), "%ds", sec);
}
return buf;
}
inline std::vector<CallLogItem> loadCallLog(const ContactBook& book) {
std::ifstream lf(getModemLogFilePath());
std::string line;
struct ActiveSession {
bool active = false;
CallDirection dir = CallDirection::Incoming;
std::string number;
std::string startTimeStr;
time_t startEpoch = 0;
time_t answerEpoch = 0;
bool answered = false;
};
std::vector<CallLogItem> history;
ActiveSession cur;
auto flushSession = [&]() {
if (!cur.active || cur.number.empty()) {
cur = ActiveSession{};
return;
}
CallLogItem item;
item.direction = cur.dir;
item.number = cur.number;
item.contactName = book.resolveName(cur.number);
item.displayTime = formatShortTime(cur.startTimeStr);
item.durationSec = 0;
history.push_back(item);
cur = ActiveSession{};
};
while (std::getline(lf, line)) {
if (line.empty()) continue;
size_t t1 = line.find('\t');
if (t1 == std::string::npos) continue;
size_t t2 = line.find('\t', t1 + 1);
if (t2 == std::string::npos) continue;
size_t t3 = line.find('\t', t2 + 1);
std::string ts = trimStr(line.substr(0, t1));
std::string evt = trimStr(line.substr(t1 + 1, t2 - t1 - 1));
std::string num = trimStr(
t3 == std::string::npos ? line.substr(t2 + 1) : line.substr(t2 + 1, t3 - t2 - 1));
if (evt.rfind("call_", 0) != 0 && evt != "ring_muted") {
continue;
}
if (num.empty() || num == "NULL") {
continue;
}
time_t epoch = parseIsoTime(ts);
if (evt == "call_ring") {
flushSession();
cur.active = true;
cur.dir = CallDirection::Missed;
cur.number = num;
cur.startTimeStr = ts;
cur.startEpoch = epoch;
cur.answerEpoch = 0;
cur.answered = false;
} else if (evt == "call_start") {
flushSession();
cur.active = true;
cur.dir = CallDirection::Outgoing;
cur.number = num;
cur.startTimeStr = ts;
cur.startEpoch = epoch;
cur.answerEpoch = epoch;
cur.answered = true;
} else if (evt == "call_pickup") {
if (cur.active && normalizePhone(cur.number) == normalizePhone(num)) {
cur.dir = CallDirection::Incoming;
cur.answered = true;
cur.answerEpoch = epoch;
} else {
flushSession();
cur.active = true;
cur.dir = CallDirection::Incoming;
cur.number = num;
cur.startTimeStr = ts;
cur.startEpoch = epoch;
cur.answerEpoch = epoch;
cur.answered = true;
}
} else if (evt == "call_missed") {
if (cur.active && normalizePhone(cur.number) == normalizePhone(num)) {
cur.dir = CallDirection::Missed;
flushSession();
} else {
flushSession();
CallLogItem item;
item.direction = CallDirection::Missed;
item.number = num;
item.contactName = book.resolveName(num);
item.displayTime = formatShortTime(ts);
item.durationSec = 0;
history.push_back(item);
}
} else if (evt == "call_hangup" || evt == "call_finished" ||
evt == "call_discard") {
if (cur.active && normalizePhone(cur.number) == normalizePhone(num)) {
if (evt == "call_discard" && !cur.answered &&
cur.dir != CallDirection::Outgoing) {
cur.dir = CallDirection::Missed;
}
CallLogItem item;
item.direction = cur.dir;
item.number = cur.number;
item.contactName = book.resolveName(cur.number);
item.displayTime = formatShortTime(cur.startTimeStr);
if (cur.answered && cur.answerEpoch > 0 && epoch >= cur.answerEpoch) {
item.durationSec = static_cast<int>(epoch - cur.answerEpoch);
}
history.push_back(item);
cur = ActiveSession{};
}
}
}
flushSession();
std::reverse(history.begin(), history.end());
return history;
}
inline void placePhoneCall(const std::string& rawNumber) {
std::string num = normalizePhone(rawNumber);
if (num.empty()) {
return;
}
runAsyncArgv("sxmo_modemdial.sh", num.c_str());
}
inline void closeOtherPlugins(const char* selfPluginName) {
struct PluginRef {
const char* pidFile;
const char* name;
};
static const PluginRef kAllPlugins[] = {
{"xdrawer.pid", "xdrawer"},
{"xdialer.pid", "dialer"},
{"xcalllog.pid", "calllog"},
{"xcontacts.pid", "contacts"},
{"xsms.pid", "sms"},
{"xfiles.pid", "files"},
{"xcamera.pid", "camera"},
};
for (const auto& p : kAllPlugins) {
if (selfPluginName && std::strcmp(p.name, selfPluginName) == 0) {
continue;
}
if (isPidFileAlive(getRuntimeFile(p.pidFile))) {
sendPluginCommand(p.name, "CLOSE");
}
}
if (::access("/tmp/dwm_plugin_dmenu.active", F_OK) == 0) {
sendPluginCommand("dmenu", "CLOSE");
}
}
inline std::string getModemLogDirPath() {
const char* env = std::getenv("SXMO_LOGDIR");
if (env && env[0]) {
return env;
}
const char* xdg = std::getenv("XDG_DATA_HOME");
if (xdg && xdg[0]) {
return std::string(xdg) + "/sxmo/modem";
}
const char* home = std::getenv("HOME");
return std::string(home && home[0] ? home : "/home/user") +
"/.local/share/sxmo/modem";
}
struct SmsMessage {
bool incoming = true;
std::string sender;
std::string isoTime;
std::string displayTime;
time_t epoch = 0;
std::string text;
};
struct SmsThread {
std::string number;
std::string normNumber;
std::string contactName;
std::string t9Name;
std::string lowerName;
std::string lastPreview;
std::string lastDisplayTime;
time_t lastEpoch = 0;
bool lastIncoming = true;
bool hasDraft = false;
int messageCount = 0;
};
inline bool parseSmsHeaderLine(const std::string& line,
bool* outIncoming,
std::string* outSender,
std::string* outIsoTime) {
if (line.empty() || line.back() != ':') {
return false;
}
if (line.rfind("Received at ", 0) == 0 && line.size() > 13) {
*outIncoming = true;
outSender->clear();
*outIsoTime = line.substr(12, line.size() - 13);
return true;
}
if (line.rfind("Received from ", 0) == 0) {
size_t atPos = line.find(" at ");
if (atPos != std::string::npos && atPos + 4 < line.size() - 1) {
*outIncoming = true;
*outSender = line.substr(14, atPos - 14);
*outIsoTime = line.substr(atPos + 4, line.size() - (atPos + 4) - 1);
return true;
}
}
if (line.rfind("Sent at ", 0) == 0 && line.size() > 9) {
*outIncoming = false;
outSender->clear();
*outIsoTime = line.substr(8, line.size() - 9);
return true;
}
return false;
}
inline std::vector<SmsMessage> loadSmsThreadMessages(const std::string& number) {
std::vector<SmsMessage> msgs;
std::string path = getModemLogDirPath() + "/" + number + "/sms.txt";
std::ifstream in(path);
if (!in.is_open()) {
return msgs;
}
std::string line;
bool hasCur = false;
SmsMessage cur;
auto flushCur = [&]() {
if (!hasCur) {
return;
}
while (!cur.text.empty() &&
(cur.text.back() == '\n' || cur.text.back() == '\r')) {
cur.text.pop_back();
}
msgs.push_back(cur);
cur = SmsMessage{};
hasCur = false;
};
while (std::getline(in, line)) {
if (!line.empty() && line.back() == '\r') {
line.pop_back();
}
bool inc = true;
std::string sender;
std::string iso;
if (parseSmsHeaderLine(line, &inc, &sender, &iso)) {
flushCur();
hasCur = true;
cur.incoming = inc;
cur.sender = sender.empty() ? number : sender;
cur.isoTime = iso;
cur.displayTime = formatShortTime(iso);
cur.epoch = parseIsoTime(iso);
cur.text.clear();
} else if (hasCur) {
if (!cur.text.empty()) {
cur.text.push_back('\n');
}
cur.text += line;
} else if (!trimStr(line).empty()) {
hasCur = true;
cur.incoming = true;
cur.sender = number;
cur.text = line;
}
}
flushCur();
return msgs;
}
inline std::string loadSmsDraft(const std::string& number) {
if (number.empty()) {
return "";
}
std::string path = getModemLogDirPath() + "/" + number + "/draft.txt";
std::ifstream in(path);
if (!in.is_open()) {
return "";
}
std::ostringstream ss;
ss << in.rdbuf();
std::string s = ss.str();
while (!s.empty() && (s.back() == '\n' || s.back() == '\r')) {
s.pop_back();
}
if (s == "Enter message here") {
return "";
}
return s;
}
inline bool saveSmsDraft(const std::string& number, const std::string& text) {
if (number.empty()) {
return false;
}
std::string dir = getModemLogDirPath() + "/" + number;
std::string path = dir + "/draft.txt";
if (trimStr(text).empty()) {
::unlink(path.c_str());
return true;
}
ContactBook::ensureParentDir(path);
std::ofstream out(path, std::ios::trunc);
if (!out.is_open()) {
return false;
}
out << text << "\n";
return true;
}
inline void removeSmsDraft(const std::string& number) {
if (number.empty()) {
return;
}
std::string path = getModemLogDirPath() + "/" + number + "/draft.txt";
::unlink(path.c_str());
}
inline bool deleteSmsThread(const std::string& number) {
if (number.empty()) {
return false;
}
std::string dir = getModemLogDirPath() + "/" + number;
std::string smsPath = dir + "/sms.txt";
std::string draftPath = dir + "/draft.txt";
::unlink(smsPath.c_str());
::unlink(draftPath.c_str());
::rmdir(dir.c_str());
return true;
}
inline std::vector<SmsThread> loadSmsThreads(const ContactBook& book) {
std::vector<SmsThread> threads;
std::string baseDir = getModemLogDirPath();
DIR* d = ::opendir(baseDir.c_str());
if (!d) {
return threads;
}
struct dirent* ent;
while ((ent = ::readdir(d)) != nullptr) {
std::string name = ent->d_name;
if (name.empty() || name[0] == '.') {
continue;
}
std::string subDir = baseDir + "/" + name;
struct stat st {};
if (::stat(subDir.c_str(), &st) != 0 || !S_ISDIR(st.st_mode)) {
continue;
}
std::string smsPath = subDir + "/sms.txt";
std::string draftPath = subDir + "/draft.txt";
bool hasSms = (::access(smsPath.c_str(), R_OK) == 0);
std::string draft = loadSmsDraft(name);
bool hasDraft = !draft.empty();
if (!hasSms && !hasDraft) {
continue;
}
auto msgs = loadSmsThreadMessages(name);
if (msgs.empty() && !hasDraft) {
continue;
}
SmsThread th;
th.number = name;
th.normNumber = normalizePhone(name);
th.contactName = book.resolveName(name);
std::string label = th.contactName.empty() ? name : th.contactName;
th.t9Name = toT9Digits(label);
th.lowerName = toLowerStr(label);
th.hasDraft = hasDraft;
th.messageCount = static_cast<int>(msgs.size());
if (!msgs.empty()) {
const auto& last = msgs.back();
th.lastIncoming = last.incoming;
th.lastDisplayTime = last.displayTime;
th.lastEpoch = last.epoch;
std::string prev = last.text;
for (char& c : prev) {
if (c == '\n' || c == '\r' || c == '\t') {
c = ' ';
}
}
th.lastPreview = hasDraft ? ("[Draft] " + draft) : prev;
} else {
th.lastIncoming = false;
th.lastPreview = "[Draft] " + draft;
struct stat dst {};
if (::stat(draftPath.c_str(), &dst) == 0) {
th.lastEpoch = dst.st_mtim.tv_sec;
}
}
if (th.lastEpoch == 0 && ::stat(smsPath.c_str(), &st) == 0) {
th.lastEpoch = st.st_mtim.tv_sec;
}
threads.push_back(th);
}
::closedir(d);
std::sort(threads.begin(), threads.end(),
[](const SmsThread& a, const SmsThread& b) {
if (a.lastEpoch != b.lastEpoch) {
return a.lastEpoch > b.lastEpoch;
}
return a.number < b.number;
});
return threads;
}
} // namespace bananarchy
#endif // DWM_PLUGINS_PHONE_DATA_H