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

1014 lines
35 KiB
C++

// SPDX-License-Identifier: GPL-2.0-only
// IRC Client DWM Plugin (irc.so / xirc) for Bananarchy (240x320)
// Features:
// - Multi-server simultaneous connections over OpenSSL TLS or plain TCP
// - IRCv3 capability negotiation (CAP LS 302: sasl, server-time, message-tags,
// multi-prefix, away-notify, account-notify, chghost, cap-notify)
// - SASL PLAIN authentication + automatic PING/PONG background keepalive
// - Resident background mode with highlight/DM vibration alerts
// - NeoUI 3-tab interface: Chat View, Buffers List, and Server Manager
#include "../sxmo-dwm/dwm_plugin.h"
#include "net_tls.h"
#include <fstream>
#include <memory>
namespace {
using namespace bananarchy;
volatile sig_atomic_t gRunning = 1;
void handleSignal(int) {
gRunning = 0;
}
struct IrcMessageLine {
std::string timeStr;
std::string sender;
std::string text;
bool isHighlight = false;
bool isSystem = false;
};
struct IrcBuffer {
int serverIdx = 0;
std::string name; // e.g. "*status*", "#bananarchy", or "nick"
std::string topic;
std::vector<IrcMessageLine> lines;
int unreadCount = 0;
bool hasHighlight = false;
void append(const std::string& sender, const std::string& txt,
bool highlight = false, bool sys = false,
const std::string& customTime = "") {
IrcMessageLine m;
if (!customTime.empty()) {
m.timeStr = customTime;
} else {
time_t now = ::time(nullptr);
struct tm tmNow {};
localtime_r(&now, &tmNow);
char buf[16];
std::strftime(buf, sizeof(buf), "%H:%M", &tmNow);
m.timeStr = buf;
}
m.sender = sender;
m.text = txt;
m.isHighlight = highlight;
m.isSystem = sys;
lines.push_back(std::move(m));
if (lines.size() > 250) {
lines.erase(lines.begin(), lines.begin() + (lines.size() - 250));
}
}
};
struct IrcServerConfig {
std::string label = "Libera.Chat";
std::string host = "irc.libera.chat";
int port = 6697;
bool useTls = true;
std::string nick = "bananarchy";
std::string username = "bananarchy";
std::string realname = "Bananarchy Linux User";
std::string saslUser;
std::string saslPass;
std::string autoJoin = "#bananarchy";
bool keepInBackground = true;
// Runtime state
std::unique_ptr<NetStream> net;
std::string state = "DISC";
bool capNegotiating = false;
bool saslPending = false;
bool registered = false;
};
std::string getIrcServersPath() {
return getHomeDirPath() + "/.config/sxmo/irc_servers.tsv";
}
std::vector<IrcServerConfig> loadIrcServers() {
std::vector<IrcServerConfig> list;
std::ifstream in(getIrcServersPath());
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() >= 10) {
IrcServerConfig s;
s.label = c[0];
s.host = c[1];
s.port = std::max(1, std::atoi(c[2].c_str()));
s.useTls = (c[3] == "1" || toLowerStr(c[3]) == "true");
s.nick = c[4];
s.username = c[5];
s.realname = c[6];
s.saslUser = c[7];
s.saslPass = c[8];
s.autoJoin = c[9];
if (c.size() >= 11) {
s.keepInBackground = (c[10] == "1" || toLowerStr(c[10]) == "true");
}
list.push_back(std::move(s));
}
}
if (list.empty()) {
IrcServerConfig def;
def.label = "Libera.Chat";
def.host = "irc.libera.chat";
def.port = 6697;
def.useTls = true;
def.nick = "banana" + std::to_string(::getpid() % 900 + 100);
def.username = "bananarchy";
def.realname = "Bananarchy Linux";
def.autoJoin = "#bananarchy";
list.push_back(std::move(def));
}
return list;
}
void saveIrcServers(const std::vector<IrcServerConfig>& list) {
std::string path = getIrcServersPath();
ContactBook::ensureParentDir(path);
std::ofstream out(path, std::ios::trunc);
if (!out.is_open()) return;
for (const auto& s : list) {
out << s.label << "\t" << s.host << "\t" << s.port << "\t"
<< (s.useTls ? "1" : "0") << "\t" << s.nick << "\t" << s.username
<< "\t" << s.realname << "\t" << s.saslUser << "\t" << s.saslPass
<< "\t" << s.autoJoin << "\t" << (s.keepInBackground ? "1" : "0")
<< "\n";
}
}
int irc_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("irc", forwarded)) {
return 0;
}
std::string daemonPidPath = getPluginDaemonPidPath("irc");
std::string activePidPath = getRuntimeFile("xirc.pid");
writeIntFile(daemonPidPath, static_cast<int>(::getpid()));
int fifoFd = setupPluginDaemonFifo("irc");
struct sigaction sa {};
sa.sa_handler = handleSignal;
sigemptyset(&sa.sa_mask);
sigaction(SIGTERM, &sa, nullptr);
sigaction(SIGINT, &sa, nullptr);
NeoWindow neo;
if (!neo.create("xirc", "XIrc", "IRC Client")) {
if (fifoFd >= 0) ::close(fifoFd);
::unlink(daemonPidPath.c_str());
return 1;
}
neo.bindAsActiveContext();
std::vector<IrcServerConfig> servers = loadIrcServers();
std::vector<IrcBuffer> buffers;
int activeBufIdx = 0;
auto findOrCreateBuffer = [&](int srvIdx, const std::string& name) -> int {
std::string lowName = toLowerStr(name);
for (size_t i = 0; i < buffers.size(); ++i) {
if (buffers[i].serverIdx == srvIdx &&
toLowerStr(buffers[i].name) == lowName) {
return static_cast<int>(i);
}
}
IrcBuffer b;
b.serverIdx = srvIdx;
b.name = name;
buffers.push_back(std::move(b));
return static_cast<int>(buffers.size()) - 1;
};
for (size_t i = 0; i < servers.size(); ++i) {
findOrCreateBuffer(static_cast<int>(i), "*status*");
}
auto sendIrcRaw = [&](int srvIdx, const std::string& rawLine) -> bool {
if (srvIdx < 0 || srvIdx >= static_cast<int>(servers.size())) return false;
auto& s = servers[srvIdx];
if (!s.net || !s.net->isConnected()) return false;
return s.net->sendStr(rawLine + "\r\n");
};
auto connectServer = [&](int srvIdx) -> bool {
if (srvIdx < 0 || srvIdx >= static_cast<int>(servers.size())) return false;
auto& s = servers[srvIdx];
s.net = std::make_unique<NetStream>();
int stBuf = findOrCreateBuffer(srvIdx, "*status*");
buffers[stBuf].append("*", "Connecting to " + s.host + ":" +
std::to_string(s.port) +
(s.useTls ? " (TLS)..." : "..."),
false, true);
if (!s.net->connectTcp(s.host, s.port, 6000)) {
buffers[stBuf].append("!", "Connect failed: " + s.net->lastError(), false, true);
s.net->close();
s.state = "ERR";
return false;
}
if (s.useTls && !s.net->startTls(s.host, 6000)) {
buffers[stBuf].append("!", "TLS failed: " + s.net->lastError(), false, true);
s.net->close();
s.state = "TLS ERR";
return false;
}
s.state = s.useTls ? "TLS..." : "CONN...";
s.capNegotiating = true;
s.saslPending = false;
s.registered = false;
sendIrcRaw(srvIdx, "CAP LS 302");
if (s.nick.empty()) s.nick = "banana";
if (s.username.empty()) s.username = s.nick;
if (s.realname.empty()) s.realname = s.nick;
sendIrcRaw(srvIdx, "NICK " + s.nick);
sendIrcRaw(srvIdx, "USER " + s.username + " 0 * :" + s.realname);
return true;
};
auto disconnectServer = [&](int srvIdx, const std::string& reason = "Bananarchy IRC") {
if (srvIdx < 0 || srvIdx >= static_cast<int>(servers.size())) return;
auto& s = servers[srvIdx];
if (s.net && s.net->isConnected()) {
sendIrcRaw(srvIdx, "QUIT :" + reason);
s.net->close();
}
s.state = "DISC";
s.registered = false;
int stBuf = findOrCreateBuffer(srvIdx, "*status*");
buffers[stBuf].append("*", "Disconnected from " + s.label, false, true);
};
bool visible = false;
int activeTab = 0; // 0=Chat, 1=Buffers, 2=Servers
int chatScrollBack = 0;
std::string chatInput;
int selectedRow = 0;
int scrollOffset = 0;
bool menuOpen = false;
int menuSel = 0;
// Server editor modal
bool editModalOpen = false;
int editSrvIdx = -1;
int editFieldIdx = 0;
IrcServerConfig editDraft;
auto handleIncomingIrcLine = [&](int srvIdx, std::string line) {
if (line.empty()) return;
auto& srv = servers[srvIdx];
int stBuf = findOrCreateBuffer(srvIdx, "*status*");
// 1. Parse optional IRCv3 @tags prefix
std::string serverTimeHHMM;
if (line[0] == '@') {
size_t sp = line.find(' ');
if (sp != std::string::npos) {
std::string tags = line.substr(1, sp - 1);
line = trimStr(line.substr(sp + 1));
size_t tpos = tags.find("time=");
if (tpos != std::string::npos) {
size_t tend = tags.find(';', tpos);
std::string iso = tags.substr(
tpos + 5, (tend == std::string::npos) ? std::string::npos : (tend - tpos - 5));
size_t tchar = iso.find('T');
if (tchar != std::string::npos && tchar + 6 <= iso.size()) {
serverTimeHHMM = iso.substr(tchar + 1, 5);
}
}
}
}
// 2. Parse prefix (:nick!user@host)
std::string prefix;
std::string senderNick = "*";
if (!line.empty() && line[0] == ':') {
size_t sp = line.find(' ');
if (sp != std::string::npos) {
prefix = line.substr(1, sp - 1);
line = trimStr(line.substr(sp + 1));
size_t bang = prefix.find('!');
senderNick = (bang == std::string::npos) ? prefix : prefix.substr(0, bang);
}
}
// 3. Split command and args / trailing (:...)
std::string trailing;
size_t trailPos = line.find(" :");
std::string head = (trailPos == std::string::npos) ? line : line.substr(0, trailPos);
if (trailPos != std::string::npos) {
trailing = line.substr(trailPos + 2);
}
std::istringstream hss(head);
std::string cmd;
hss >> cmd;
std::vector<std::string> params;
std::string p;
while (hss >> p) params.push_back(p);
cmd = toLowerStr(cmd);
if (cmd == "ping") {
sendIrcRaw(srvIdx, "PONG :" + (trailing.empty() ? (params.empty() ? "server" : params[0]) : trailing));
return;
}
if (cmd == "cap") {
std::string sub = (params.size() >= 2) ? toLowerStr(params[1]) : "";
if (sub == "ls") {
std::string reqCaps;
std::string avail = toLowerStr(trailing);
const char* want[] = {
"sasl", "server-time", "message-tags", "multi-prefix",
"away-notify", "account-notify", "chghost", "cap-notify"
};
for (const char* w : want) {
if (avail.find(w) != std::string::npos) {
if (std::strcmp(w, "sasl") == 0 && srv.saslUser.empty()) continue;
if (!reqCaps.empty()) reqCaps.push_back(' ');
reqCaps += w;
}
}
if (!reqCaps.empty()) {
sendIrcRaw(srvIdx, "CAP REQ :" + reqCaps);
} else {
srv.capNegotiating = false;
sendIrcRaw(srvIdx, "CAP END");
}
} else if (sub == "ack") {
if (toLowerStr(trailing).find("sasl") != std::string::npos &&
!srv.saslUser.empty()) {
srv.saslPending = true;
sendIrcRaw(srvIdx, "AUTHENTICATE PLAIN");
} else {
srv.capNegotiating = false;
sendIrcRaw(srvIdx, "CAP END");
}
} else if (sub == "nak") {
srv.capNegotiating = false;
sendIrcRaw(srvIdx, "CAP END");
}
return;
}
if (cmd == "authenticate") {
if ((trailing == "+" || (!params.empty() && params[0] == "+")) &&
srv.saslPending) {
std::string rawAuth;
rawAuth.push_back('\0');
rawAuth += srv.saslUser;
rawAuth.push_back('\0');
rawAuth += srv.saslPass;
sendIrcRaw(srvIdx, "AUTHENTICATE " + base64EncodeStr(rawAuth));
}
return;
}
if (cmd == "903" || cmd == "904" || cmd == "905") {
srv.saslPending = false;
srv.capNegotiating = false;
sendIrcRaw(srvIdx, "CAP END");
buffers[stBuf].append("*", (cmd == "903") ? "SASL auth succeeded" : "SASL auth failed",
false, true, serverTimeHHMM);
return;
}
if (cmd == "001") {
srv.registered = true;
srv.state = srv.useTls ? "ONLINE(TLS)" : "ONLINE";
buffers[stBuf].append("*", trailing, false, true, serverTimeHHMM);
if (!srv.autoJoin.empty()) {
std::stringstream ss(srv.autoJoin);
std::string ch;
while (std::getline(ss, ch, ',')) {
ch = trimStr(ch);
if (!ch.empty()) {
sendIrcRaw(srvIdx, "JOIN " + ch);
}
}
}
return;
}
if (cmd == "join") {
std::string chan = !trailing.empty() ? trailing : (params.empty() ? "" : params[0]);
if (!chan.empty()) {
int bIdx = findOrCreateBuffer(srvIdx, chan);
buffers[bIdx].append("*", senderNick + " joined " + chan, false, true, serverTimeHHMM);
if (toLowerStr(senderNick) == toLowerStr(srv.nick)) {
activeBufIdx = bIdx;
}
}
return;
}
if (cmd == "part") {
std::string chan = params.empty() ? "" : params[0];
if (!chan.empty()) {
int bIdx = findOrCreateBuffer(srvIdx, chan);
buffers[bIdx].append("*", senderNick + " left " + chan, false, true, serverTimeHHMM);
}
return;
}
if (cmd == "privmsg" || cmd == "notice") {
std::string target = params.empty() ? "*status*" : params[0];
bool isChan = (!target.empty() && (target[0] == '#' || target[0] == '&'));
std::string bufName = isChan ? target : (cmd == "notice" ? "*status*" : senderNick);
int bIdx = findOrCreateBuffer(srvIdx, bufName);
bool hl = (!isChan && cmd == "privmsg") ||
(toLowerStr(trailing).find(toLowerStr(srv.nick)) != std::string::npos);
std::string displayTxt = trailing;
if (displayTxt.size() >= 7 && displayTxt[0] == '\x01' &&
displayTxt.rfind("\x01" "ACTION ", 0) == 0) {
displayTxt = "* " + senderNick + " " +
displayTxt.substr(8, displayTxt.size() - 9);
buffers[bIdx].append("*", displayTxt, hl, false, serverTimeHHMM);
} else {
buffers[bIdx].append(senderNick, displayTxt, hl, cmd == "notice",
serverTimeHHMM);
}
if (bIdx != activeBufIdx || !visible) {
buffers[bIdx].unreadCount++;
if (hl) {
buffers[bIdx].hasHighlight = true;
runAsyncCmd("PATH=\"$HOME/.config/sxmo/hooks:/usr/share/sxmo/default_hooks:$PATH\" "
"sxmo_hook_notification.sh >/dev/null 2>&1");
}
}
return;
}
if (cmd == "332" && params.size() >= 2) {
int bIdx = findOrCreateBuffer(srvIdx, params[1]);
buffers[bIdx].topic = trailing;
buffers[bIdx].append("*", "Topic: " + trailing, false, true, serverTimeHHMM);
return;
}
if (!trailing.empty()) {
buffers[stBuf].append(senderNick, trailing, false, true, serverTimeHHMM);
}
};
auto submitChatLine = [&]() {
chatInput = neoui_input_get_text();
std::string line = trimStr(chatInput);
if (line.empty()) return;
chatInput.clear();
neoui_input_reset("");
activeBufIdx = std::clamp(activeBufIdx, 0, static_cast<int>(buffers.size()) - 1);
int srvIdx = buffers[activeBufIdx].serverIdx;
auto& srv = servers[srvIdx];
if (line[0] == '/') {
std::istringstream iss(line.substr(1));
std::string cmd;
iss >> cmd;
std::string rest;
std::getline(iss, rest);
rest = trimStr(rest);
std::string low = toLowerStr(cmd);
if (low == "join" || low == "j") {
if (!rest.empty()) {
if (rest[0] != '#' && rest[0] != '&') rest = "#" + rest;
sendIrcRaw(srvIdx, "JOIN " + rest);
activeBufIdx = findOrCreateBuffer(srvIdx, rest);
}
} else if (low == "part" || low == "leave") {
std::string ch = buffers[activeBufIdx].name;
if (!ch.empty() && ch[0] == '#') {
sendIrcRaw(srvIdx, "PART " + ch + (rest.empty() ? "" : (" :" + rest)));
}
} else if (low == "msg" || low == "query") {
std::istringstream mss(rest);
std::string target, text;
mss >> target;
std::getline(mss, text);
text = trimStr(text);
if (!target.empty()) {
int bIdx = findOrCreateBuffer(srvIdx, target);
activeBufIdx = bIdx;
if (!text.empty()) {
sendIrcRaw(srvIdx, "PRIVMSG " + target + " :" + text);
buffers[bIdx].append(srv.nick, text);
}
}
} else if (low == "me") {
std::string target = buffers[activeBufIdx].name;
if (target != "*status*") {
sendIrcRaw(srvIdx, "PRIVMSG " + target + " :\x01" "ACTION " + rest + "\x01");
buffers[activeBufIdx].append("*", "* " + srv.nick + " " + rest);
}
} else if (low == "nick") {
if (!rest.empty()) {
srv.nick = rest;
sendIrcRaw(srvIdx, "NICK " + rest);
}
} else if (low == "clear") {
buffers[activeBufIdx].lines.clear();
} else if (low == "connect") {
connectServer(srvIdx);
} else if (low == "disconnect" || low == "quit") {
disconnectServer(srvIdx, rest.empty() ? "Bye" : rest);
} else if (low == "raw" || low == "quote") {
sendIrcRaw(srvIdx, rest);
} else {
sendIrcRaw(srvIdx, cmd + (rest.empty() ? "" : (" " + rest)));
}
return;
}
std::string target = buffers[activeBufIdx].name;
if (target == "*status*") {
sendIrcRaw(srvIdx, line);
buffers[activeBufIdx].append(srv.nick, line, false, true);
} else {
if (!sendIrcRaw(srvIdx, "PRIVMSG " + target + " :" + line)) {
buffers[activeBufIdx].append("!", "Not connected (Server -> Connect)", false, true);
} else {
buffers[activeBufIdx].append(srv.nick, line);
}
}
};
auto syncEditInput = [&]() {
if (!editModalOpen) {
neoui_input_reset(chatInput.c_str());
return;
}
if (editFieldIdx == 0) neoui_input_reset(editDraft.label.c_str());
else if (editFieldIdx == 1) neoui_input_reset(editDraft.host.c_str());
else if (editFieldIdx == 2) {
neoui_input_set_mode(NEO_INPUT_123);
neoui_input_reset(std::to_string(editDraft.port).c_str());
} else if (editFieldIdx == 4) neoui_input_reset(editDraft.nick.c_str());
else if (editFieldIdx == 5) neoui_input_reset(editDraft.saslUser.c_str());
else if (editFieldIdx == 6) neoui_input_reset(editDraft.saslPass.c_str());
else if (editFieldIdx == 7) neoui_input_reset(editDraft.autoJoin.c_str());
};
auto applyEditInput = [&]() {
std::string txt = neoui_input_get_text();
if (!editModalOpen) {
chatInput = txt;
return;
}
if (editFieldIdx == 0) editDraft.label = txt;
else if (editFieldIdx == 1) editDraft.host = txt;
else if (editFieldIdx == 2) editDraft.port = std::max(1, std::atoi(txt.c_str()));
else if (editFieldIdx == 4) {
editDraft.nick = txt;
editDraft.username = txt;
} else if (editFieldIdx == 5) editDraft.saslUser = txt;
else if (editFieldIdx == 6) editDraft.saslPass = txt;
else if (editFieldIdx == 7) editDraft.autoJoin = txt;
};
auto render = [&]() {
if (!visible) return;
neo.bindAsActiveContext();
neoui_begin_frame();
activeBufIdx = std::clamp(activeBufIdx, 0, static_cast<int>(buffers.size()) - 1);
auto& curBuf = buffers[activeBufIdx];
curBuf.unreadCount = 0;
curBuf.hasHighlight = false;
int srvIdx = std::clamp(curBuf.serverIdx, 0, static_cast<int>(servers.size()) - 1);
neoui_draw_header(kIconGlobe, NEO_TEXT_GREEN, curBuf.name.c_str(),
servers[srvIdx].state.c_str());
neoui_draw_tabs("Chat|Buffers|Servers", activeTab, 34, 24);
constexpr int kBodyY = 58;
constexpr int kBodyH = 296 - kBodyY - NEO_SOFTBAR_H;
if (activeTab == 0) {
int msgAreaH = kBodyH - 48;
int lineH = 16;
int maxLines = msgAreaH / lineH;
int total = static_cast<int>(curBuf.lines.size());
chatScrollBack = std::clamp(chatScrollBack, 0, std::max(0, total - maxLines));
int startIdx = std::max(0, total - maxLines - chatScrollBack);
for (int i = 0; i < maxLines && (startIdx + i) < total; ++i) {
const auto& m = curBuf.lines[startIdx + i];
int y = kBodyY + 2 + i * lineH;
std::string row = m.timeStr + " ";
int col = NEO_TEXT_LIGHT;
if (m.isHighlight) col = NEO_TEXT_YELLOW;
else if (m.isSystem) col = NEO_TEXT_MUTED;
if (m.sender == "*") {
row += "* " + m.text;
} else {
row += "<" + m.sender + "> " + m.text;
}
neoui_draw_text(NEO_FONT_SMALL, col, 4, y, lineH, row.c_str(), 232);
}
neoui_draw_input_box(4, kBodyY + msgAreaH, 232, 26, 1, "",
neoui_input_get_text(), "Message or /join #chan", 0);
neoui_draw_multitap_bar(0, 296 - NEO_SOFTBAR_H - 20, 240, 20,
"[OK/Call] Send [*] Mode");
neoui_draw_softkeys("Menu", "SEND", "BG/Close");
} else if (activeTab == 1) {
int rowH = 38;
int maxVis = kBodyH / rowH;
selectedRow = std::clamp(selectedRow, 0, static_cast<int>(buffers.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>(buffers.size()); ++i) {
int idx = scrollOffset + i;
const auto& b = buffers[idx];
std::string srvLbl = servers[b.serverIdx].label;
std::string badge = b.unreadCount > 0 ? ("+" + std::to_string(b.unreadCount)) : "";
int col = b.hasHighlight ? NEO_TEXT_YELLOW
: (idx == activeBufIdx ? NEO_TEXT_GREEN : NEO_TEXT_LIGHT);
neoui_draw_list_row(idx, kBodyY + i * rowH, rowH, idx == selectedRow ? 1 : 0,
kIconList, col, b.name.c_str(), srvLbl.c_str(),
badge.c_str());
}
neoui_draw_softkeys("Menu", "OPEN", "Back");
} else {
int rowH = 42;
int maxVis = kBodyH / rowH;
selectedRow = std::clamp(selectedRow, 0, static_cast<int>(servers.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>(servers.size()); ++i) {
int idx = scrollOffset + i;
const auto& s = servers[idx];
std::string sub = s.nick + "@" + s.host + ":" + std::to_string(s.port);
int col = (s.state.rfind("ONLINE", 0) == 0) ? NEO_TEXT_GREEN : NEO_TEXT_MUTED;
neoui_draw_list_row(idx, kBodyY + i * rowH, rowH, idx == selectedRow ? 1 : 0,
kIconGlobe, col, s.label.c_str(), sub.c_str(),
s.state.c_str());
}
neoui_draw_softkeys("Menu", "CONN/DISC", "Back");
}
if (editModalOpen) {
neoui_draw_modal_box(4, 28, 232, 238, kIconEdit, NEO_TEXT_YELLOW,
editSrvIdx < 0 ? "Add IRC Server" : "Edit IRC Server");
const char* labels[9] = {
"Label", "Host", "Port", "TLS", "Nick", "SASL User",
"SASL Pass", "AutoJoin", "BG Mode"
};
std::string vals[9] = {
editDraft.label, editDraft.host, std::to_string(editDraft.port),
editDraft.useTls ? "ON" : "OFF", editDraft.nick, editDraft.saslUser,
editDraft.saslPass.empty() ? "" : "******", editDraft.autoJoin,
editDraft.keepInBackground ? "ON" : "OFF"
};
int startF = std::max(0, std::min(editFieldIdx - 2, 5));
for (int i = 0; i < 4 && (startF + i) < 9; ++i) {
int f = startF + i;
bool isText = (f != 3 && f != 8);
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] Toggle");
neoui_draw_softkeys("Save", "EDIT", "Cancel");
} else if (menuOpen) {
neoui_draw_menu_popup(
"Connect / Disconnect|Add Server|Edit Selected Server|Join #bananarchy|Close Buffer",
nullptr, menuSel, 5);
}
neoui_end_frame();
};
auto openWindow = [&]() {
if (isPhonePasscodeLocked()) return;
writeIntFile(activePidPath, static_cast<int>(::getpid()));
closeOtherPlugins("irc");
visible = true;
neoui_show();
syncEditInput();
render();
};
auto closeWindow = [&]() {
if (!visible) return;
visible = false;
editModalOpen = false;
menuOpen = false;
for (size_t i = 0; i < servers.size(); ++i) {
if (!servers[i].keepInBackground) {
disconnectServer(static_cast<int>(i));
}
}
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();
}
}
// Pump all active IRC server sockets (even while UI window is hidden in background mode!)
for (size_t i = 0; i < servers.size(); ++i) {
if (!servers[i].net || !servers[i].net->isConnected()) continue;
int r = servers[i].net->pumpRx(0);
std::string line;
bool anyLine = false;
while (servers[i].net->popLine(line)) {
handleIncomingIrcLine(static_cast<int>(i), line);
anyLine = true;
}
if (r < 0) {
servers[i].net->close();
servers[i].state = "DISC";
servers[i].registered = false;
int stBuf = findOrCreateBuffer(static_cast<int>(i), "*status*");
buffers[stBuf].append("!", "Connection closed by server", false, true);
anyLine = true;
}
if (anyLine && visible) {
render();
}
}
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) {
applyEditInput();
if (editSrvIdx < 0) {
servers.push_back(std::move(editDraft));
findOrCreateBuffer(static_cast<int>(servers.size()) - 1, "*status*");
} else if (editSrvIdx < static_cast<int>(servers.size())) {
servers[editSrvIdx].label = editDraft.label;
servers[editSrvIdx].host = editDraft.host;
servers[editSrvIdx].port = editDraft.port;
servers[editSrvIdx].useTls = editDraft.useTls;
servers[editSrvIdx].nick = editDraft.nick;
servers[editSrvIdx].username = editDraft.username;
servers[editSrvIdx].saslUser = editDraft.saslUser;
servers[editSrvIdx].saslPass = editDraft.saslPass;
servers[editSrvIdx].autoJoin = editDraft.autoJoin;
servers[editSrvIdx].keepInBackground = editDraft.keepInBackground;
}
saveIrcServers(servers);
editModalOpen = false;
syncEditInput();
render();
} else {
menuOpen = !menuOpen;
menuSel = 0;
render();
}
} else if (ev == NEO_EV_SOFTKEY_RIGHT) {
if (editModalOpen) {
editModalOpen = false;
syncEditInput();
render();
} else if (menuOpen) {
menuOpen = false;
render();
} else if (activeTab != 0) {
activeTab = 0;
syncEditInput();
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;
int srvIdx = buffers[activeBufIdx].serverIdx;
if (menuSel == 0) {
if (servers[srvIdx].net && servers[srvIdx].net->isConnected()) {
disconnectServer(srvIdx);
} else {
connectServer(srvIdx);
}
} else if (menuSel == 1) {
editSrvIdx = -1;
editDraft = IrcServerConfig{};
editFieldIdx = 0;
editModalOpen = true;
syncEditInput();
} else if (menuSel == 2) {
int idx = (activeTab == 2) ? selectedRow : srvIdx;
idx = std::clamp(idx, 0, static_cast<int>(servers.size()) - 1);
editSrvIdx = idx;
editDraft.label = servers[idx].label;
editDraft.host = servers[idx].host;
editDraft.port = servers[idx].port;
editDraft.useTls = servers[idx].useTls;
editDraft.nick = servers[idx].nick;
editDraft.username = servers[idx].username;
editDraft.saslUser = servers[idx].saslUser;
editDraft.saslPass = servers[idx].saslPass;
editDraft.autoJoin = servers[idx].autoJoin;
editDraft.keepInBackground = servers[idx].keepInBackground;
editFieldIdx = 0;
editModalOpen = true;
syncEditInput();
} else if (menuSel == 3) {
sendIrcRaw(srvIdx, "JOIN #bananarchy");
activeBufIdx = findOrCreateBuffer(srvIdx, "#bananarchy");
activeTab = 0;
} else if (menuSel == 4 && buffers[activeBufIdx].name != "*status*" &&
buffers.size() > 1) {
buffers.erase(buffers.begin() + activeBufIdx);
activeBufIdx = 0;
}
} else if (k == NEO_KEY_BACK || k == NEO_KEY_END) {
menuOpen = false;
}
render();
} else if (editModalOpen) {
if (k == NEO_KEY_UP) {
applyEditInput();
editFieldIdx = (editFieldIdx + 8) % 9;
syncEditInput();
} else if (k == NEO_KEY_DOWN) {
applyEditInput();
editFieldIdx = (editFieldIdx + 1) % 9;
syncEditInput();
} else if (k == NEO_KEY_OK) {
if (editFieldIdx == 3) {
editDraft.useTls = !editDraft.useTls;
editDraft.port = editDraft.useTls ? 6697 : 6667;
} else if (editFieldIdx == 8) {
editDraft.keepInBackground = !editDraft.keepInBackground;
}
} else if (k == NEO_KEY_STAR) {
neoui_input_cycle_mode();
} else if (k == NEO_KEY_BACK) {
neoui_input_backspace();
applyEditInput();
} else if (k >= NEO_KEY_0 && k <= NEO_KEY_9) {
neoui_input_feed_key(k);
applyEditInput();
}
render();
} else {
if (k == NEO_KEY_LEFT) {
applyEditInput();
activeTab = (activeTab + 2) % 3;
selectedRow = 0;
scrollOffset = 0;
syncEditInput();
} else if (k == NEO_KEY_RIGHT) {
applyEditInput();
activeTab = (activeTab + 1) % 3;
selectedRow = 0;
scrollOffset = 0;
syncEditInput();
} else if (activeTab == 0) {
if (k == NEO_KEY_UP) ++chatScrollBack;
else if (k == NEO_KEY_DOWN && chatScrollBack > 0) --chatScrollBack;
else if (k == NEO_KEY_OK || k == NEO_KEY_CALL) {
submitChatLine();
chatScrollBack = 0;
} else if (k == NEO_KEY_STAR) {
neoui_input_cycle_mode();
} else if (k == NEO_KEY_BACK) {
if (!std::string(neoui_input_get_text()).empty()) {
neoui_input_backspace();
applyEditInput();
} else {
closeWindow();
break;
}
} else if (k >= NEO_KEY_0 && k <= NEO_KEY_9) {
neoui_input_feed_key(k);
applyEditInput();
} else if (k == NEO_KEY_END) {
closeWindow();
break;
}
} else if (activeTab == 1) {
if (k == NEO_KEY_UP && selectedRow > 0) --selectedRow;
else if (k == NEO_KEY_DOWN) ++selectedRow;
else if (k == NEO_KEY_OK) {
activeBufIdx = std::clamp(selectedRow, 0,
static_cast<int>(buffers.size()) - 1);
activeTab = 0;
chatScrollBack = 0;
syncEditInput();
}
} 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) {
int idx = std::clamp(selectedRow, 0,
static_cast<int>(servers.size()) - 1);
if (servers[idx].net && servers[idx].net->isConnected()) {
disconnectServer(idx);
} else {
connectServer(idx);
}
}
}
render();
}
}
ev = neoui_poll_event(0);
}
} else {
while (XPending(neo.dpy) > 0) {
XEvent xev;
XNextEvent(neo.dpy, &xev);
}
}
// Build pollfd array across X11, FIFO, and all active IRC server sockets
std::vector<struct pollfd> pfds;
pfds.push_back({ ConnectionNumber(neo.dpy), POLLIN, 0 });
if (fifoFd >= 0) pfds.push_back({ fifoFd, POLLIN, 0 });
for (const auto& s : servers) {
if (s.net && s.net->isConnected() && s.net->fd() >= 0) {
pfds.push_back({ s.net->fd(), POLLIN, 0 });
}
}
int timeoutMs = visible ? (neoui_input_is_tap_active() ? 150 : 1000) : -1;
::poll(pfds.data(), static_cast<nfds_t>(pfds.size()), timeoutMs);
}
for (size_t i = 0; i < servers.size(); ++i) {
disconnectServer(static_cast<int>(i));
}
if (fifoFd >= 0) ::close(fifoFd);
::unlink(getPluginFifoPath("irc").c_str());
::unlink(daemonPidPath.c_str());
return 0;
}
int irc_plugin_init(const DwmHostApi* host) {
if (host && host->spawn_plugin) {
host->spawn_plugin("irc", "--preload");
}
return 0;
}
} // namespace
extern "C" __attribute__((visibility("default"))) const DwmPlugin dwm_plugin_entry = {
DWM_PLUGIN_API_VERSION,
"irc",
"Multi-server IRCv3 + TLS client with background mode",
irc_plugin_init,
nullptr,
nullptr,
nullptr,
nullptr,
irc_run_main
};