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

1086 lines
38 KiB
C++
Raw Normal View History

// SPDX-License-Identifier: GPL-2.0-only
// Email DWM Plugin (email.so / xemail / xmail) for Bananarchy (240x320)
// Supports IMAP4rev1, POP3, and SMTP with implicit TLS, STARTTLS, and SASL
// authentication (PLAIN / LOGIN), MIME RFC 2047 / Base64 / Quoted-Printable
// decoding, local offline inbox caching, message reader, and composer.
#include "../sxmo-dwm/dwm_plugin.h"
#include "net_tls.h"
#include <fstream>
namespace {
using namespace bananarchy;
volatile sig_atomic_t gRunning = 1;
void handleSignal(int) {
gRunning = 0;
}
struct EmailAccount {
std::string label = "Personal";
std::string address;
std::string username;
std::string password;
std::string inProtocol = "IMAP"; // IMAP or POP3
std::string inHost;
int inPort = 993;
std::string inSecurity = "TLS"; // TLS, STARTTLS, PLAIN
std::string smtpHost;
int smtpPort = 465;
std::string smtpSecurity = "TLS"; // TLS, STARTTLS, PLAIN
};
struct EmailMessage {
std::string id;
std::string from;
std::string to;
std::string subject;
std::string date;
std::string body;
bool unread = false;
};
std::string getEmailAccountsPath() {
return getHomeDirPath() + "/.config/sxmo/email_accounts.tsv";
}
std::string getEmailCacheDir() {
std::string dir = getHomeDirPath() + "/.local/share/sxmo/email";
ContactBook::ensureParentDir(dir + "/index.tsv");
return dir;
}
std::vector<EmailAccount> loadEmailAccounts() {
std::vector<EmailAccount> list;
std::ifstream in(getEmailAccountsPath());
std::string line;
while (std::getline(in, line)) {
line = trimStr(line);
if (line.empty() || line[0] == '#') continue;
std::vector<std::string> c;
std::stringstream ss(line);
std::string col;
while (std::getline(ss, col, '\t')) c.push_back(col);
if (c.size() >= 11) {
EmailAccount a;
a.label = c[0];
a.address = c[1];
a.username = c[2];
a.password = c[3];
a.inProtocol = c[4];
a.inHost = c[5];
a.inPort = std::max(1, std::atoi(c[6].c_str()));
a.inSecurity = c[7];
a.smtpHost = c[8];
a.smtpPort = std::max(1, std::atoi(c[9].c_str()));
a.smtpSecurity = c[10];
list.push_back(a);
}
}
return list;
}
void saveEmailAccounts(const std::vector<EmailAccount>& list) {
std::string path = getEmailAccountsPath();
ContactBook::ensureParentDir(path);
std::ofstream out(path, std::ios::trunc);
if (!out.is_open()) return;
for (const auto& a : list) {
out << a.label << "\t" << a.address << "\t" << a.username << "\t"
<< a.password << "\t" << a.inProtocol << "\t" << a.inHost << "\t"
<< a.inPort << "\t" << a.inSecurity << "\t" << a.smtpHost << "\t"
<< a.smtpPort << "\t" << a.smtpSecurity << "\n";
}
}
std::vector<EmailMessage> loadCachedMessages() {
std::vector<EmailMessage> list;
std::string dir = getEmailCacheDir();
std::ifstream in(dir + "/index.tsv");
std::string line;
while (std::getline(in, line)) {
line = trimStr(line);
if (line.empty()) continue;
std::vector<std::string> c;
std::stringstream ss(line);
std::string col;
while (std::getline(ss, col, '\t')) c.push_back(col);
if (c.size() >= 5) {
EmailMessage m;
m.id = c[0];
m.from = c[1];
m.subject = c[2];
m.date = c[3];
m.unread = (c[4] == "1");
std::ifstream bf(dir + "/msg_" + m.id + ".txt");
if (bf.is_open()) {
std::ostringstream oss;
oss << bf.rdbuf();
m.body = oss.str();
}
list.push_back(m);
}
}
return list;
}
void saveCachedMessages(const std::vector<EmailMessage>& list) {
std::string dir = getEmailCacheDir();
std::ofstream out(dir + "/index.tsv", std::ios::trunc);
if (!out.is_open()) return;
for (const auto& m : list) {
auto cleanField = [](std::string s) {
for (char& ch : s) {
if (ch == '\t' || ch == '\r' || ch == '\n') ch = ' ';
}
return s;
};
out << cleanField(m.id) << "\t" << cleanField(m.from) << "\t"
<< cleanField(m.subject) << "\t" << cleanField(m.date) << "\t"
<< (m.unread ? "1" : "0") << "\n";
std::ofstream bf(dir + "/msg_" + cleanField(m.id) + ".txt", std::ios::trunc);
if (bf.is_open()) {
bf << m.body;
}
}
}
EmailMessage parseRawRfc5322Message(const std::string& raw, const std::string& fallbackId) {
EmailMessage msg;
msg.id = fallbackId;
msg.subject = "(No Subject)";
msg.from = "(Unknown)";
msg.unread = true;
size_t split = raw.find("\r\n\r\n");
size_t sepLen = 4;
if (split == std::string::npos) {
split = raw.find("\n\n");
sepLen = 2;
}
std::string hdrBlock = (split == std::string::npos) ? raw : raw.substr(0, split);
std::string bodyBlock = (split == std::string::npos) ? "" : raw.substr(split + sepLen);
// Unfold multi-line RFC 5322 headers
std::vector<std::string> hdrLines;
std::istringstream hss(hdrBlock);
std::string line;
while (std::getline(hss, line)) {
if (!line.empty() && line.back() == '\r') line.pop_back();
if (!line.empty() && (line[0] == ' ' || line[0] == '\t') && !hdrLines.empty()) {
hdrLines.back() += " " + trimStr(line);
} else {
hdrLines.push_back(line);
}
}
std::string contentType;
std::string transferEnc;
for (const auto& h : hdrLines) {
size_t colon = h.find(':');
if (colon == std::string::npos) continue;
std::string k = toLowerStr(trimStr(h.substr(0, colon)));
std::string v = trimStr(h.substr(colon + 1));
if (k == "from") msg.from = decodeMimeHeader(v);
else if (k == "to") msg.to = decodeMimeHeader(v);
else if (k == "subject") msg.subject = decodeMimeHeader(v);
else if (k == "date") msg.date = v.substr(0, std::min<size_t>(22, v.size()));
else if (k == "content-type") contentType = v;
else if (k == "content-transfer-encoding") transferEnc = toLowerStr(v);
}
auto decodePartPayload = [](const std::string& payload,
const std::string& enc,
const std::string& ctype) -> std::string {
std::string decoded = payload;
std::string lowEnc = toLowerStr(enc);
if (lowEnc.find("base64") != std::string::npos) {
decoded = base64Decode(payload);
} else if (lowEnc.find("quoted-printable") != std::string::npos) {
decoded = decodeQuotedPrintable(payload, false);
}
if (toLowerStr(ctype).find("text/html") != std::string::npos) {
decoded = stripHtmlTags(decoded);
}
return trimStr(decoded);
};
// Handle multipart boundary if present
std::string lowCt = toLowerStr(contentType);
size_t bpos = lowCt.find("boundary=");
if (bpos != std::string::npos) {
std::string bval = contentType.substr(bpos + 9);
if (!bval.empty() && bval[0] == '"') {
size_t eq = bval.find('"', 1);
bval = (eq == std::string::npos) ? bval.substr(1) : bval.substr(1, eq - 1);
} else {
size_t sc = bval.find(';');
if (sc != std::string::npos) bval = trimStr(bval.substr(0, sc));
}
std::string marker = "--" + bval;
std::string htmlFallback;
size_t pos = bodyBlock.find(marker);
while (pos != std::string::npos) {
size_t partStart = bodyBlock.find('\n', pos);
if (partStart == std::string::npos) break;
++partStart;
size_t nextMarker = bodyBlock.find(marker, partStart);
std::string part = (nextMarker == std::string::npos)
? bodyBlock.substr(partStart)
: bodyBlock.substr(partStart, nextMarker - partStart);
size_t pSplit = part.find("\r\n\r\n");
size_t pSep = 4;
if (pSplit == std::string::npos) {
pSplit = part.find("\n\n");
pSep = 2;
}
if (pSplit != std::string::npos) {
std::string pHdr = part.substr(0, pSplit);
std::string pBody = part.substr(pSplit + pSep);
std::string pCt = "text/plain";
std::string pEnc;
std::istringstream pss(pHdr);
std::string pl;
while (std::getline(pss, pl)) {
if (!pl.empty() && pl.back() == '\r') pl.pop_back();
size_t c = pl.find(':');
if (c == std::string::npos) continue;
std::string pk = toLowerStr(trimStr(pl.substr(0, c)));
std::string pv = trimStr(pl.substr(c + 1));
if (pk == "content-type") pCt = pv;
else if (pk == "content-transfer-encoding") pEnc = pv;
}
if (toLowerStr(pCt).find("text/plain") != std::string::npos) {
msg.body = decodePartPayload(pBody, pEnc, pCt);
break;
} else if (toLowerStr(pCt).find("text/html") != std::string::npos &&
htmlFallback.empty()) {
htmlFallback = decodePartPayload(pBody, pEnc, pCt);
}
}
pos = nextMarker;
}
if (msg.body.empty()) {
msg.body = htmlFallback;
}
} else {
msg.body = decodePartPayload(bodyBlock, transferEnc, contentType);
}
return msg;
}
std::string imapQuote(const std::string& s) {
std::string out = "\"";
for (char c : s) {
if (c == '"' || c == '\\') out.push_back('\\');
out.push_back(c);
}
out.push_back('"');
return out;
}
bool fetchAccountEmails(const EmailAccount& acct,
std::vector<EmailMessage>& outMsgs,
std::string& outError) {
if (acct.inHost.empty() || acct.username.empty()) {
outError = "Account incomplete";
return false;
}
NetStream net;
if (!net.connectTcp(acct.inHost, acct.inPort, 6000)) {
outError = net.lastError();
return false;
}
if (acct.inSecurity == "TLS" && !net.startTls(acct.inHost, 6000)) {
outError = net.lastError();
return false;
}
std::string line;
if (!net.readLine(line, 6000)) {
outError = "No greeting from server";
return false;
}
if (toLowerStr(acct.inProtocol) == "pop3") {
if (acct.inSecurity == "STARTTLS") {
net.sendStr("STLS\r\n");
if (!net.readLine(line, 5000) || line.rfind("+OK", 0) != 0 ||
!net.startTls(acct.inHost, 6000)) {
outError = "POP3 STLS failed";
return false;
}
}
net.sendStr("USER " + acct.username + "\r\n");
if (!net.readLine(line, 5000) || line.rfind("+OK", 0) != 0) {
outError = "POP3 USER rejected";
return false;
}
net.sendStr("PASS " + acct.password + "\r\n");
if (!net.readLine(line, 5000) || line.rfind("+OK", 0) != 0) {
outError = "POP3 login failed";
return false;
}
net.sendStr("STAT\r\n");
if (!net.readLine(line, 5000) || line.rfind("+OK", 0) != 0) {
outError = "POP3 STAT failed";
return false;
}
int totalCount = 0;
{
std::istringstream iss(line.substr(3));
iss >> totalCount;
}
int startIdx = std::max(1, totalCount - 14);
for (int i = totalCount; i >= startIdx; --i) {
net.sendStr("RETR " + std::to_string(i) + "\r\n");
if (!net.readLine(line, 5000) || line.rfind("+OK", 0) != 0) continue;
std::string rawMsg;
while (net.readLine(line, 5000)) {
if (line == ".") break;
if (!line.empty() && line[0] == '.') line.erase(0, 1);
rawMsg += line + "\r\n";
}
outMsgs.push_back(parseRawRfc5322Message(rawMsg, "pop_" + std::to_string(i)));
}
net.sendStr("QUIT\r\n");
return true;
}
// IMAP4rev1 flow
auto runImapCmd = [&](const std::string& tag, const std::string& cmd,
std::string& outBlock) -> bool {
outBlock.clear();
if (!net.sendStr(tag + " " + cmd + "\r\n")) return false;
std::string l;
while (net.readLine(l, 6000)) {
if (l.rfind(tag + " ", 0) == 0) {
return l.find(tag + " OK") == 0;
}
outBlock += l + "\r\n";
}
return false;
};
std::string resp;
if (acct.inSecurity == "STARTTLS") {
if (!runImapCmd("A01", "STARTTLS", resp) || !net.startTls(acct.inHost, 6000)) {
outError = "IMAP STARTTLS failed";
return false;
}
}
if (!runImapCmd("A02",
"LOGIN " + imapQuote(acct.username) + " " + imapQuote(acct.password),
resp)) {
outError = "IMAP login failed";
return false;
}
if (!runImapCmd("A03", "SELECT INBOX", resp)) {
outError = "SELECT INBOX failed";
return false;
}
int existsCount = 0;
{
std::istringstream iss(resp);
std::string l;
while (std::getline(iss, l)) {
if (l.find(" EXISTS") != std::string::npos && l.rfind("* ", 0) == 0) {
existsCount = std::atoi(l.substr(2).c_str());
}
}
}
int startSeq = std::max(1, existsCount - 14);
for (int seq = existsCount; seq >= startSeq && seq >= 1; --seq) {
std::string tag = "F" + std::to_string(seq);
if (runImapCmd(tag,
"FETCH " + std::to_string(seq) + " (BODY.PEEK[])",
resp)) {
size_t firstNl = resp.find("\r\n");
std::string rawRfc = (firstNl == std::string::npos) ? resp : resp.substr(firstNl + 2);
if (rawRfc.size() > 3 && rawRfc.substr(rawRfc.size() - 3) == ")\r\n") {
rawRfc.erase(rawRfc.size() - 3);
}
outMsgs.push_back(parseRawRfc5322Message(rawRfc, "imap_" + std::to_string(seq)));
}
}
net.sendStr("A99 LOGOUT\r\n");
return true;
}
bool sendSmtpEmail(const EmailAccount& acct, const std::string& toAddr,
const std::string& subject, const std::string& body,
std::string& outError) {
if (acct.smtpHost.empty() || toAddr.empty()) {
outError = "Missing SMTP host or recipient";
return false;
}
NetStream net;
if (!net.connectTcp(acct.smtpHost, acct.smtpPort, 6000)) {
outError = net.lastError();
return false;
}
if (acct.smtpSecurity == "TLS" && !net.startTls(acct.smtpHost, 6000)) {
outError = net.lastError();
return false;
}
auto readSmtpCode = [&](int& codeOut) -> bool {
std::string l;
while (net.readLine(l, 6000)) {
if (l.size() >= 3 && std::isdigit(static_cast<unsigned char>(l[0]))) {
codeOut = std::atoi(l.substr(0, 3).c_str());
if (l.size() == 3 || l[3] == ' ') return true;
}
}
return false;
};
int code = 0;
if (!readSmtpCode(code) || code != 220) {
outError = "SMTP greeting failed";
return false;
}
net.sendStr("EHLO bananarchy.local\r\n");
if (!readSmtpCode(code) || code != 250) {
outError = "SMTP EHLO failed";
return false;
}
if (acct.smtpSecurity == "STARTTLS") {
net.sendStr("STARTTLS\r\n");
if (!readSmtpCode(code) || code != 220 || !net.startTls(acct.smtpHost, 6000)) {
outError = "SMTP STARTTLS failed";
return false;
}
net.sendStr("EHLO bananarchy.local\r\n");
if (!readSmtpCode(code) || code != 250) {
outError = "SMTP EHLO after TLS failed";
return false;
}
}
if (!acct.username.empty() && !acct.password.empty()) {
std::string authRaw;
authRaw.push_back('\0');
authRaw += acct.username;
authRaw.push_back('\0');
authRaw += acct.password;
net.sendStr("AUTH PLAIN " + base64EncodeStr(authRaw) + "\r\n");
if (!readSmtpCode(code) || code != 235) {
// Fallback to AUTH LOGIN
net.sendStr("AUTH LOGIN\r\n");
if (readSmtpCode(code) && code == 334) {
net.sendStr(base64EncodeStr(acct.username) + "\r\n");
if (readSmtpCode(code) && code == 334) {
net.sendStr(base64EncodeStr(acct.password) + "\r\n");
readSmtpCode(code);
}
}
if (code != 235) {
outError = "SMTP authentication failed";
return false;
}
}
}
std::string fromAddr = acct.address.empty() ? acct.username : acct.address;
net.sendStr("MAIL FROM:<" + fromAddr + ">\r\n");
if (!readSmtpCode(code) || (code != 250 && code != 251)) {
outError = "MAIL FROM rejected";
return false;
}
net.sendStr("RCPT TO:<" + trimStr(toAddr) + ">\r\n");
if (!readSmtpCode(code) || (code != 250 && code != 251)) {
outError = "RCPT TO rejected";
return false;
}
net.sendStr("DATA\r\n");
if (!readSmtpCode(code) || code != 354) {
outError = "SMTP DATA rejected";
return false;
}
time_t now = ::time(nullptr);
struct tm tmNow {};
localtime_r(&now, &tmNow);
char dateBuf[64];
std::strftime(dateBuf, sizeof(dateBuf), "%a, %d %b %Y %H:%M:%S %z", &tmNow);
std::ostringstream payload;
payload << "From: \"" << acct.label << "\" <" << fromAddr << ">\r\n"
<< "To: <" << trimStr(toAddr) << ">\r\n"
<< "Subject: " << subject << "\r\n"
<< "Date: " << dateBuf << "\r\n"
<< "Message-ID: <" << randomHexToken(8) << "@" << acct.smtpHost << ">\r\n"
<< "MIME-Version: 1.0\r\n"
<< "Content-Type: text/plain; charset=UTF-8\r\n"
<< "User-Agent: Bananarchy-XEmail/1.0\r\n\r\n"
<< body << "\r\n.\r\n";
net.sendStr(payload.str());
if (!readSmtpCode(code) || code != 250) {
outError = "SMTP message send failed";
return false;
}
net.sendStr("QUIT\r\n");
return true;
}
int email_run_main(int argc, char** argv) {
gRunning = 1;
bool isPreload = false;
std::string initCmd;
for (int i = 1; i < argc; ++i) {
if (!argv[i] || !argv[i][0]) continue;
if (std::strcmp(argv[i], "--preload") == 0) isPreload = true;
else {
if (!initCmd.empty()) initCmd.push_back(' ');
initCmd += argv[i];
}
}
std::string forwarded = isPreload ? "NOP" : (initCmd.empty() ? "OPEN" : ("OPEN " + initCmd));
if (sendPluginCommand("email", forwarded)) {
return 0;
}
std::string daemonPidPath = getPluginDaemonPidPath("email");
std::string activePidPath = getRuntimeFile("xemail.pid");
writeIntFile(daemonPidPath, static_cast<int>(::getpid()));
int fifoFd = setupPluginDaemonFifo("email");
struct sigaction sa {};
sa.sa_handler = handleSignal;
sigemptyset(&sa.sa_mask);
sigaction(SIGTERM, &sa, nullptr);
sigaction(SIGINT, &sa, nullptr);
NeoWindow neo;
if (!neo.create("xemail", "XEmail", "Email Client")) {
if (fifoFd >= 0) ::close(fifoFd);
::unlink(daemonPidPath.c_str());
return 1;
}
neo.bindAsActiveContext();
std::vector<EmailAccount> accounts = loadEmailAccounts();
std::vector<EmailMessage> messages = loadCachedMessages();
bool visible = false;
int activeTab = 0; // 0=Inbox, 1=Compose, 2=Accounts
int activeAcctIdx = 0;
int selectedRow = 0;
int scrollOffset = 0;
bool readingMsg = false;
int readScrollLine = 0;
bool menuOpen = false;
int menuSel = 0;
// Compose fields
int composeField = 0; // 0=To, 1=Subject, 2=Body
std::string composeTo;
std::string composeSubject;
std::string composeBody;
// Account editor modal
bool editModalOpen = false;
int editAcctIdx = -1;
int editFieldIdx = 0;
EmailAccount editDraft;
auto syncInputBuffer = [&]() {
if (editModalOpen) {
if (editFieldIdx == 0) neoui_input_reset(editDraft.label.c_str());
else if (editFieldIdx == 1) neoui_input_reset(editDraft.address.c_str());
else if (editFieldIdx == 2) neoui_input_reset(editDraft.username.c_str());
else if (editFieldIdx == 3) neoui_input_reset(editDraft.password.c_str());
else if (editFieldIdx == 5) neoui_input_reset(editDraft.inHost.c_str());
else if (editFieldIdx == 6) {
neoui_input_set_mode(NEO_INPUT_123);
neoui_input_reset(std::to_string(editDraft.inPort).c_str());
} else if (editFieldIdx == 8) neoui_input_reset(editDraft.smtpHost.c_str());
else if (editFieldIdx == 9) {
neoui_input_set_mode(NEO_INPUT_123);
neoui_input_reset(std::to_string(editDraft.smtpPort).c_str());
}
} else if (activeTab == 1) {
if (composeField == 0) neoui_input_reset(composeTo.c_str());
else if (composeField == 1) neoui_input_reset(composeSubject.c_str());
else neoui_input_reset(composeBody.c_str());
}
};
auto applyInputBuffer = [&]() {
std::string txt = neoui_input_get_text();
if (editModalOpen) {
if (editFieldIdx == 0) editDraft.label = txt;
else if (editFieldIdx == 1) {
editDraft.address = txt;
if (editDraft.username.empty()) editDraft.username = txt;
} else if (editFieldIdx == 2) editDraft.username = txt;
else if (editFieldIdx == 3) editDraft.password = txt;
else if (editFieldIdx == 5) editDraft.inHost = txt;
else if (editFieldIdx == 6) editDraft.inPort = std::max(1, std::atoi(txt.c_str()));
else if (editFieldIdx == 8) editDraft.smtpHost = txt;
else if (editFieldIdx == 9) editDraft.smtpPort = std::max(1, std::atoi(txt.c_str()));
} else if (activeTab == 1) {
if (composeField == 0) composeTo = txt;
else if (composeField == 1) composeSubject = txt;
else composeBody = txt;
}
};
auto render = [&]() {
if (!visible) return;
neo.bindAsActiveContext();
neoui_begin_frame();
std::string badge = accounts.empty()
? "NO ACCT"
: accounts[std::clamp(activeAcctIdx, 0,
static_cast<int>(accounts.size()) - 1)]
.label;
neoui_draw_header(kIconSms, NEO_TEXT_BLUE, "Email", badge.c_str());
if (readingMsg && selectedRow >= 0 &&
selectedRow < static_cast<int>(messages.size())) {
const auto& m = messages[selectedRow];
neoui_fill_rect(0, 34, 240, 44, neoui_color(NEO_COLOR_BG_ALT_EVEN));
neoui_draw_text(NEO_FONT_MAIN, NEO_TEXT_WHITE, 6, 35, 20, m.subject.c_str(), 228);
std::string meta = m.from + " | " + m.date;
neoui_draw_text(NEO_FONT_SMALL, NEO_TEXT_YELLOW, 6, 56, 18, meta.c_str(), 228);
neoui_draw_line(0, 78, 240, 78, neoui_color(NEO_COLOR_BORDER));
neoui_draw_text_wrapped(NEO_FONT_SMALL, NEO_TEXT_LIGHT, 6, 82, 228,
296 - 82 - NEO_SOFTBAR_H, m.body.c_str(),
readScrollLine);
neoui_draw_softkeys("Reply", "SCROLL", "Back");
neoui_end_frame();
return;
}
neoui_draw_tabs("Inbox|Compose|Accounts", activeTab, 34, 24);
constexpr int kBodyY = 58;
constexpr int kBodyH = 296 - kBodyY - NEO_SOFTBAR_H;
if (activeTab == 0) {
int rowH = 42;
int maxVis = kBodyH / rowH;
if (messages.empty()) {
neoui_draw_text_centered(NEO_FONT_MAIN, NEO_TEXT_MUTED, 0, kBodyY + 60,
240, 24, "Inbox Empty");
neoui_draw_text_centered(NEO_FONT_SMALL, NEO_TEXT_YELLOW, 0, kBodyY + 86,
240, 20, "Press Call or Menu -> Sync Inbox");
} else {
selectedRow = std::clamp(selectedRow, 0, static_cast<int>(messages.size()) - 1);
if (selectedRow < scrollOffset) scrollOffset = selectedRow;
if (selectedRow >= scrollOffset + maxVis) scrollOffset = selectedRow - maxVis + 1;
for (int i = 0; i < maxVis && (scrollOffset + i) < static_cast<int>(messages.size()); ++i) {
int idx = scrollOffset + i;
const auto& m = messages[idx];
neoui_draw_list_row(idx, kBodyY + i * rowH, rowH, idx == selectedRow ? 1 : 0,
kIconSms, m.unread ? NEO_TEXT_YELLOW : NEO_TEXT_MUTED,
m.subject.c_str(), m.from.c_str(), m.date.c_str());
}
neoui_draw_scrollbar(236, kBodyY, kBodyH, static_cast<int>(messages.size()),
maxVis, scrollOffset);
}
neoui_draw_softkeys("Menu", messages.empty() ? "SYNC" : "READ", "Close");
} else if (activeTab == 1) {
neoui_draw_input_box(6, kBodyY + 4, 228, 34, composeField == 0 ? 1 : 0,
"To:", composeField == 0 ? neoui_input_get_text() : composeTo.c_str(),
"recipient@example.com", 0);
neoui_draw_input_box(6, kBodyY + 42, 228, 34, composeField == 1 ? 1 : 0,
"Subject:", composeField == 1 ? neoui_input_get_text() : composeSubject.c_str(),
"Subject line", 0);
neoui_draw_input_box(6, kBodyY + 80, 228, 86, composeField == 2 ? 1 : 0,
"Message Body:", composeField == 2 ? neoui_input_get_text() : composeBody.c_str(),
"Write message...", 0);
neoui_draw_multitap_bar(0, 296 - NEO_SOFTBAR_H - 22, 240, 22,
"[Call/OK] Send [*] Input Mode");
neoui_draw_softkeys("Menu", "SEND", "Back");
} else {
int rowH = 42;
int maxVis = kBodyH / rowH;
if (accounts.empty()) {
neoui_draw_text_centered(NEO_FONT_MAIN, NEO_TEXT_MUTED, 0, kBodyY + 60,
240, 24, "No Email Accounts");
neoui_draw_text_centered(NEO_FONT_SMALL, NEO_TEXT_YELLOW, 0, kBodyY + 86,
240, 20, "Press OK to Add IMAP/POP3/SMTP");
} else {
selectedRow = std::clamp(selectedRow, 0, static_cast<int>(accounts.size()) - 1);
if (selectedRow < scrollOffset) scrollOffset = selectedRow;
if (selectedRow >= scrollOffset + maxVis) scrollOffset = selectedRow - maxVis + 1;
for (int i = 0; i < maxVis && (scrollOffset + i) < static_cast<int>(accounts.size()); ++i) {
int idx = scrollOffset + i;
const auto& a = accounts[idx];
std::string sub = a.inProtocol + ":" + a.inHost + " / SMTP:" + a.smtpHost;
neoui_draw_list_row(idx, kBodyY + i * rowH, rowH, idx == selectedRow ? 1 : 0,
kIconUser, idx == activeAcctIdx ? NEO_TEXT_GREEN : NEO_TEXT_LIGHT,
a.label.c_str(), sub.c_str(), a.inSecurity.c_str());
}
}
neoui_draw_softkeys("Menu", accounts.empty() ? "ADD" : "EDIT", "Back");
}
if (editModalOpen) {
neoui_draw_modal_box(4, 28, 232, 238, kIconEdit, NEO_TEXT_YELLOW,
editAcctIdx < 0 ? "Add Email Account" : "Edit Email Account");
const char* labels[11] = {
"Label", "Address", "Username", "Password", "Protocol",
"In Host", "In Port", "In TLS", "SMTP Host", "SMTP Port", "SMTP TLS"
};
std::string vals[11] = {
editDraft.label, editDraft.address, editDraft.username,
editDraft.password.empty() ? "" : "******",
editDraft.inProtocol, editDraft.inHost, std::to_string(editDraft.inPort),
editDraft.inSecurity, editDraft.smtpHost, std::to_string(editDraft.smtpPort),
editDraft.smtpSecurity
};
int startF = std::max(0, std::min(editFieldIdx - 2, 7));
for (int i = 0; i < 4 && (startF + i) < 11; ++i) {
int f = startF + i;
bool isText = (f != 4 && f != 7 && f != 10);
std::string v = (f == editFieldIdx && isText) ? neoui_input_get_text() : vals[f];
std::string rowStr = std::string(labels[f]) + ": " + v;
neoui_draw_list_row(f, 56 + i * 36, 36, f == editFieldIdx ? 1 : 0,
kIconKey, f == editFieldIdx ? NEO_TEXT_YELLOW : NEO_TEXT_MUTED,
rowStr.c_str(), "", "");
}
neoui_draw_multitap_bar(6, 204, 228, 22, "[*] Mode [OK] Cycle Option");
neoui_draw_softkeys("Save", "EDIT", "Cancel");
} else if (menuOpen) {
neoui_draw_menu_popup(
"Sync Inbox Now|Compose Email|Add Account|Switch Account|Delete Selected",
nullptr, menuSel, 5);
}
neoui_end_frame();
};
auto syncActiveInbox = [&]() {
if (accounts.empty()) {
neoui_show_toast("Configure an account first", 2000);
render();
return;
}
int idx = std::clamp(activeAcctIdx, 0, static_cast<int>(accounts.size()) - 1);
neoui_show_toast("Syncing inbox...", 1500);
render();
std::vector<EmailMessage> fetched;
std::string err;
if (fetchAccountEmails(accounts[idx], fetched, err)) {
messages = std::move(fetched);
saveCachedMessages(messages);
neoui_show_toast(
("Synced " + std::to_string(messages.size()) + " messages").c_str(),
2000);
} else {
neoui_show_toast(("Sync failed: " + err).c_str(), 2500);
}
render();
};
auto openWindow = [&]() {
if (isPhonePasscodeLocked()) return;
writeIntFile(activePidPath, static_cast<int>(::getpid()));
closeOtherPlugins("email");
visible = true;
neoui_show();
syncInputBuffer();
render();
};
auto closeWindow = [&]() {
if (!visible) return;
visible = false;
readingMsg = false;
editModalOpen = false;
menuOpen = false;
neoui_hide();
::unlink(activePidPath.c_str());
};
if (!isPreload) {
openWindow();
}
while (gRunning) {
for (const std::string& cmd : readFifoLines(fifoFd)) {
if (cmd == "NOP") continue;
if (cmd == "CLOSE") closeWindow();
else if (cmd == "RELOAD_THEME") {
neo.reloadTheme();
if (visible) render();
} else if (cmd == "OPEN" || cmd.rfind("OPEN ", 0) == 0) {
openWindow();
}
}
if (visible) {
neo.bindAsActiveContext();
int ev = neoui_poll_event(0);
while (ev != NEO_EV_NONE) {
if (ev == NEO_EV_EXPOSE || ev == NEO_EV_THEME_RELOAD) {
render();
} else if (ev == NEO_EV_CLOSE_REQ) {
closeWindow();
break;
} else if (ev == NEO_EV_SOFTKEY_LEFT) {
if (editModalOpen) {
applyInputBuffer();
if (editAcctIdx < 0) accounts.push_back(editDraft);
else if (editAcctIdx < static_cast<int>(accounts.size())) {
accounts[editAcctIdx] = editDraft;
}
saveEmailAccounts(accounts);
editModalOpen = false;
syncInputBuffer();
render();
} else if (readingMsg && selectedRow >= 0 &&
selectedRow < static_cast<int>(messages.size())) {
composeTo = messages[selectedRow].from;
size_t lt = composeTo.find('<');
size_t gt = composeTo.find('>');
if (lt != std::string::npos && gt != std::string::npos && gt > lt + 1) {
composeTo = composeTo.substr(lt + 1, gt - lt - 1);
}
composeSubject = "Re: " + messages[selectedRow].subject;
composeBody.clear();
readingMsg = false;
activeTab = 1;
composeField = 2;
syncInputBuffer();
render();
} else {
menuOpen = !menuOpen;
menuSel = 0;
render();
}
} else if (ev == NEO_EV_SOFTKEY_RIGHT) {
if (editModalOpen) {
editModalOpen = false;
syncInputBuffer();
render();
} else if (menuOpen) {
menuOpen = false;
render();
} else if (readingMsg) {
readingMsg = false;
render();
} else if (activeTab != 0) {
applyInputBuffer();
activeTab = 0;
render();
} else {
closeWindow();
break;
}
} else if (ev == NEO_EV_KEY_PRESS) {
int k = neoui_event_key();
if (menuOpen) {
if (k == NEO_KEY_UP) menuSel = (menuSel + 4) % 5;
else if (k == NEO_KEY_DOWN) menuSel = (menuSel + 1) % 5;
else if (k == NEO_KEY_OK) {
menuOpen = false;
if (menuSel == 0) syncActiveInbox();
else if (menuSel == 1) {
activeTab = 1;
composeField = 0;
syncInputBuffer();
} else if (menuSel == 2) {
editAcctIdx = -1;
editDraft = EmailAccount{};
editFieldIdx = 0;
editModalOpen = true;
syncInputBuffer();
} else if (menuSel == 3 && !accounts.empty()) {
activeAcctIdx = (activeAcctIdx + 1) % static_cast<int>(accounts.size());
} else if (menuSel == 4) {
if (activeTab == 2 && selectedRow >= 0 &&
selectedRow < static_cast<int>(accounts.size())) {
accounts.erase(accounts.begin() + selectedRow);
saveEmailAccounts(accounts);
} else if (activeTab == 0 && selectedRow >= 0 &&
selectedRow < static_cast<int>(messages.size())) {
messages.erase(messages.begin() + selectedRow);
saveCachedMessages(messages);
}
}
} else if (k == NEO_KEY_BACK || k == NEO_KEY_END) {
menuOpen = false;
}
render();
} else if (editModalOpen) {
if (k == NEO_KEY_UP) {
applyInputBuffer();
editFieldIdx = (editFieldIdx + 10) % 11;
syncInputBuffer();
} else if (k == NEO_KEY_DOWN) {
applyInputBuffer();
editFieldIdx = (editFieldIdx + 1) % 11;
syncInputBuffer();
} else if (k == NEO_KEY_OK) {
if (editFieldIdx == 4) {
editDraft.inProtocol = (editDraft.inProtocol == "IMAP") ? "POP3" : "IMAP";
editDraft.inPort = (editDraft.inProtocol == "IMAP") ? 993 : 995;
} else if (editFieldIdx == 7) {
if (editDraft.inSecurity == "TLS") editDraft.inSecurity = "STARTTLS";
else if (editDraft.inSecurity == "STARTTLS") editDraft.inSecurity = "PLAIN";
else editDraft.inSecurity = "TLS";
} else if (editFieldIdx == 10) {
if (editDraft.smtpSecurity == "TLS") editDraft.smtpSecurity = "STARTTLS";
else if (editDraft.smtpSecurity == "STARTTLS") editDraft.smtpSecurity = "PLAIN";
else editDraft.smtpSecurity = "TLS";
}
} else if (k == NEO_KEY_STAR) {
neoui_input_cycle_mode();
} else if (k == NEO_KEY_BACK) {
neoui_input_backspace();
applyInputBuffer();
} else if (k >= NEO_KEY_0 && k <= NEO_KEY_9) {
neoui_input_feed_key(k);
applyInputBuffer();
}
render();
} else if (readingMsg) {
if (k == NEO_KEY_UP) {
if (readScrollLine > 0) --readScrollLine;
} else if (k == NEO_KEY_DOWN || k == NEO_KEY_OK) {
++readScrollLine;
} else if (k == NEO_KEY_BACK || k == NEO_KEY_END) {
readingMsg = false;
}
render();
} else {
if (k == NEO_KEY_LEFT) {
applyInputBuffer();
activeTab = (activeTab + 2) % 3;
selectedRow = 0;
scrollOffset = 0;
syncInputBuffer();
} else if (k == NEO_KEY_RIGHT) {
applyInputBuffer();
activeTab = (activeTab + 1) % 3;
selectedRow = 0;
scrollOffset = 0;
syncInputBuffer();
} else if (activeTab == 0) {
if (k == NEO_KEY_UP && selectedRow > 0) --selectedRow;
else if (k == NEO_KEY_DOWN) ++selectedRow;
else if (k == NEO_KEY_CALL) syncActiveInbox();
else if (k == NEO_KEY_OK) {
if (messages.empty()) {
syncActiveInbox();
} else if (selectedRow >= 0 &&
selectedRow < static_cast<int>(messages.size())) {
messages[selectedRow].unread = false;
saveCachedMessages(messages);
readingMsg = true;
readScrollLine = 0;
}
} else if (k == NEO_KEY_BACK || k == NEO_KEY_END) {
closeWindow();
break;
}
} else if (activeTab == 1) {
if (k == NEO_KEY_UP) {
applyInputBuffer();
composeField = (composeField + 2) % 3;
syncInputBuffer();
} else if (k == NEO_KEY_DOWN) {
applyInputBuffer();
composeField = (composeField + 1) % 3;
syncInputBuffer();
} else if (k == NEO_KEY_CALL || k == NEO_KEY_OK) {
applyInputBuffer();
if (accounts.empty()) {
neoui_show_toast("Configure an account first", 2000);
} else {
neoui_show_toast("Sending email...", 1500);
render();
std::string err;
int idx = std::clamp(activeAcctIdx, 0,
static_cast<int>(accounts.size()) - 1);
if (sendSmtpEmail(accounts[idx], composeTo, composeSubject,
composeBody, err)) {
composeTo.clear();
composeSubject.clear();
composeBody.clear();
syncInputBuffer();
neoui_show_toast("Email sent!", 2000);
} else {
neoui_show_toast(("Send failed: " + err).c_str(), 2500);
}
}
} else if (k == NEO_KEY_STAR) {
neoui_input_cycle_mode();
} else if (k == NEO_KEY_BACK) {
neoui_input_backspace();
applyInputBuffer();
} else if (k >= NEO_KEY_0 && k <= NEO_KEY_9) {
neoui_input_feed_key(k);
applyInputBuffer();
}
} else if (activeTab == 2) {
if (k == NEO_KEY_UP && selectedRow > 0) --selectedRow;
else if (k == NEO_KEY_DOWN) ++selectedRow;
else if (k == NEO_KEY_OK) {
if (accounts.empty()) {
editAcctIdx = -1;
editDraft = EmailAccount{};
} else {
editAcctIdx = std::clamp(selectedRow, 0,
static_cast<int>(accounts.size()) - 1);
editDraft = accounts[editAcctIdx];
}
editFieldIdx = 0;
editModalOpen = true;
syncInputBuffer();
}
}
render();
}
}
ev = neoui_poll_event(0);
}
} else {
while (XPending(neo.dpy) > 0) {
XEvent xev;
XNextEvent(neo.dpy, &xev);
}
}
struct pollfd pfds[2] {};
pfds[0] = { ConnectionNumber(neo.dpy), POLLIN, 0 };
pfds[1] = { fifoFd, POLLIN, 0 };
int timeoutMs = visible ? (neoui_input_is_tap_active() ? 150 : 1000) : -1;
::poll(pfds, (fifoFd >= 0) ? 2 : 1, timeoutMs);
}
if (fifoFd >= 0) ::close(fifoFd);
::unlink(getPluginFifoPath("email").c_str());
::unlink(daemonPidPath.c_str());
return 0;
}
int email_plugin_init(const DwmHostApi* host) {
if (host && host->spawn_plugin) {
host->spawn_plugin("email", "--preload");
}
return 0;
}
} // namespace
extern "C" __attribute__((visibility("default"))) const DwmPlugin dwm_plugin_entry = {
DWM_PLUGIN_API_VERSION,
"email",
"IMAP4 / POP3 / SMTP Email client with TLS and STARTTLS support",
email_plugin_init,
nullptr,
nullptr,
nullptr,
nullptr,
email_run_main
};