// SPDX-License-Identifier: GPL-2.0-only // Tox / Trifa P2P Messenger & VoIP DWM Plugin (tox.so / xtox) for Bananarchy (240x320) // Built on c-toxcore (libtoxcore / tox.h + toxav.h) with: // - Persistent Tox profile (~/.local/share/sxmo/tox/profile.tox) // - DHT + TCP relay bootstrap with standby background mode // - Friend requests, P2P encrypted messaging, and per-friend chat logs // - ToxAV Opus audio calls integrated with CallScreen (callscreen.so) #include "../sxmo-dwm/dwm_plugin.h" #include "phone_data.h" #include #include #include #include namespace { using namespace bananarchy; volatile sig_atomic_t gRunning = 1; void handleSignal(int) { gRunning = 0; } std::string bytesToHexUpper(const uint8_t* data, size_t len) { std::string out; out.reserve(len * 2); char buf[4]; for (size_t i = 0; i < len; ++i) { std::snprintf(buf, sizeof(buf), "%02X", data[i]); out += buf; } return out; } bool hexToBytes(const std::string& hex, uint8_t* out, size_t expectedBytes) { std::string clean; for (char c : hex) { if (!std::isspace(static_cast(c))) { clean.push_back(c); } } if (clean.size() != expectedBytes * 2) return false; for (size_t i = 0; i < expectedBytes; ++i) { int hi = themeHexNibble(clean[i * 2]); int lo = themeHexNibble(clean[i * 2 + 1]); if (hi < 0 || lo < 0) return false; out[i] = static_cast((hi << 4) | lo); } return true; } std::string getToxDataDir() { std::string dir = getHomeDirPath() + "/.local/share/sxmo/tox"; ContactBook::ensureParentDir(dir + "/profile.tox"); return dir; } std::string getToxProfilePath() { return getToxDataDir() + "/profile.tox"; } struct ToxChatEntry { std::string timeStr; bool outgoing = false; std::string text; }; struct PendingFriendReq { uint8_t pubKey[TOX_PUBLIC_KEY_SIZE] {}; std::string pubKeyHex; std::string message; }; struct ToxRuntimeContext { Tox* tox = nullptr; ToxAV* toxav = nullptr; bool dhtConnected = false; std::string connBadge = "OFFLINE"; std::vector pendingReqs; // Active ToxAV call state bool inCall = false; bool callIncoming = false; bool callActive = false; uint32_t callFriendNum = UINT32_MAX; FILE* playPipe = nullptr; FILE* capPipe = nullptr; int capFd = -1; std::mutex audioMtx; bool uiDirty = false; }; std::string getFriendChatLogPath(const std::string& pubKeyHex) { return getToxDataDir() + "/chat_" + pubKeyHex.substr(0, 16) + ".tsv"; } std::vector loadFriendChat(const std::string& pubKeyHex) { std::vector list; std::ifstream in(getFriendChatLogPath(pubKeyHex)); std::string line; while (std::getline(in, line)) { if (!line.empty() && line.back() == '\r') line.pop_back(); if (line.empty()) continue; size_t t1 = line.find('\t'); size_t t2 = (t1 == std::string::npos) ? std::string::npos : line.find('\t', t1 + 1); if (t1 != std::string::npos && t2 != std::string::npos) { ToxChatEntry e; e.timeStr = line.substr(0, t1); e.outgoing = (line.substr(t1 + 1, t2 - t1 - 1) == "OUT"); e.text = line.substr(t2 + 1); list.push_back(std::move(e)); } } return list; } void appendFriendChat(const std::string& pubKeyHex, bool outgoing, const std::string& text) { time_t now = ::time(nullptr); struct tm tmNow {}; localtime_r(&now, &tmNow); char ts[16]; std::strftime(ts, sizeof(ts), "%H:%M", &tmNow); std::string clean = text; for (char& c : clean) { if (c == '\r' || c == '\n' || c == '\t') c = ' '; } std::ofstream out(getFriendChatLogPath(pubKeyHex), std::ios::app); if (out.is_open()) { out << ts << "\t" << (outgoing ? "OUT" : "IN") << "\t" << clean << "\n"; } } void saveToxProfile(Tox* tox) { if (!tox) return; size_t sz = tox_get_savedata_size(tox); if (sz == 0) return; std::vector buf(sz); tox_get_savedata(tox, buf.data()); std::string path = getToxProfilePath(); std::ofstream out(path, std::ios::binary | std::ios::trunc); if (out.is_open()) { out.write(reinterpret_cast(buf.data()), static_cast(buf.size())); } } std::string getFriendDisplayName(Tox* tox, uint32_t friendNum) { Tox_Err_Friend_Query err; size_t sz = tox_friend_get_name_size(tox, friendNum, &err); if (err == TOX_ERR_FRIEND_QUERY_OK && sz > 0 && sz < 256) { std::vector buf(sz); if (tox_friend_get_name(tox, friendNum, buf.data(), &err)) { std::string name(reinterpret_cast(buf.data()), sz); if (!trimStr(name).empty()) return trimStr(name); } } uint8_t pk[TOX_PUBLIC_KEY_SIZE] = {0}; if (tox_friend_get_public_key(tox, friendNum, pk, nullptr)) { return "Tox:" + bytesToHexUpper(pk, 4); } return "Friend #" + std::to_string(friendNum); } std::string getFriendPubKeyHex(Tox* tox, uint32_t friendNum) { uint8_t pk[TOX_PUBLIC_KEY_SIZE] = {0}; if (tox_friend_get_public_key(tox, friendNum, pk, nullptr)) { return bytesToHexUpper(pk, TOX_PUBLIC_KEY_SIZE); } return "0000000000000000"; } void startToxAvAudioPipes(ToxRuntimeContext* ctx) { std::lock_guard lk(ctx->audioMtx); ::system("amixer -c 0 cset \"name='PRI_MI2S_RX Audio Mixer MultiMedia1'\" 1 >/dev/null 2>&1; " "amixer -c 0 cset \"name='MultiMedia2 Mixer TERT_MI2S_TX'\" 1 >/dev/null 2>&1"); if (!ctx->playPipe) { ctx->playPipe = ::popen( "aplay -q --buffer-time=80000 --period-time=20000 -f S16_LE -r 48000 -c 1 -t raw 2>/dev/null", "w"); } if (!ctx->capPipe) { ctx->capPipe = ::popen( "arecord -q -D plughw:0,1 --buffer-time=80000 --period-time=20000 -f S16_LE -r 48000 -c 1 -t raw 2>/dev/null", "r"); if (ctx->capPipe) { ctx->capFd = ::fileno(ctx->capPipe); int fl = ::fcntl(ctx->capFd, F_GETFL, 0); ::fcntl(ctx->capFd, F_SETFL, fl | O_NONBLOCK); } } } void stopToxAvAudioPipes(ToxRuntimeContext* ctx) { std::lock_guard lk(ctx->audioMtx); if (ctx->capPipe) { ::pclose(ctx->capPipe); ctx->capPipe = nullptr; ctx->capFd = -1; } if (ctx->playPipe) { ::pclose(ctx->playPipe); ctx->playPipe = nullptr; } } // c-toxcore callbacks void onSelfConnectionStatus(Tox*, Tox_Connection status, void* userData) { auto* ctx = static_cast(userData); if (status == TOX_CONNECTION_UDP) { ctx->dhtConnected = true; ctx->connBadge = "DHT(UDP)"; } else if (status == TOX_CONNECTION_TCP) { ctx->dhtConnected = true; ctx->connBadge = "DHT(TCP)"; } else { ctx->dhtConnected = false; ctx->connBadge = "SEARCHING"; } ctx->uiDirty = true; } void onFriendRequest(Tox*, const Tox_Public_Key publicKey, const uint8_t message[], size_t length, void* userData) { auto* ctx = static_cast(userData); std::string hex = bytesToHexUpper(publicKey, TOX_PUBLIC_KEY_SIZE); for (const auto& r : ctx->pendingReqs) { if (r.pubKeyHex == hex) return; } PendingFriendReq req; std::memcpy(req.pubKey, publicKey, TOX_PUBLIC_KEY_SIZE); req.pubKeyHex = hex; req.message.assign(reinterpret_cast(message), length); ctx->pendingReqs.push_back(std::move(req)); bananarchy::runAsyncCmd("PATH=\"$HOME/.config/sxmo/hooks:/usr/share/sxmo/default_hooks:$PATH\" " "sxmo_hook_notification.sh >/dev/null 2>&1"); ctx->uiDirty = true; } void onFriendMessage(Tox* tox, Tox_Friend_Number friendNum, Tox_Message_Type, const uint8_t message[], size_t length, void* userData) { auto* ctx = static_cast(userData); std::string pkHex = getFriendPubKeyHex(tox, friendNum); std::string txt(reinterpret_cast(message), length); appendFriendChat(pkHex, false, txt); bananarchy::runAsyncCmd("PATH=\"$HOME/.config/sxmo/hooks:/usr/share/sxmo/default_hooks:$PATH\" " "sxmo_hook_notification.sh >/dev/null 2>&1"); ctx->uiDirty = true; } void onFriendName(Tox* tox, Tox_Friend_Number, const uint8_t[], size_t, void* userData) { auto* ctx = static_cast(userData); saveToxProfile(tox); ctx->uiDirty = true; } void onFriendConnectionStatus(Tox*, Tox_Friend_Number, Tox_Connection, void* userData) { auto* ctx = static_cast(userData); ctx->uiDirty = true; } void onToxAvCall(ToxAV*, Tox_Friend_Number friendNum, bool, bool, void* userData) { auto* ctx = static_cast(userData); if (ctx->inCall) { toxav_call_control(ctx->toxav, friendNum, TOXAV_CALL_CONTROL_CANCEL, nullptr); return; } ctx->inCall = true; ctx->callIncoming = true; ctx->callActive = false; ctx->callFriendNum = friendNum; std::string caller = getFriendDisplayName(ctx->tox, friendNum); for (char& c : caller) { if (c == ' ') c = '_'; } std::string cid = "tox:" + std::to_string(friendNum); writeIntFile("/tmp/sxmo_call_ringing", 1); runAsyncCmd("sxmo_jobs.sh start ringing sxmo_hook_ring.sh >/dev/null 2>&1"); if (!sendPluginCommand("callscreen", "INCOMING " + cid + " " + caller + " TOX")) { runAsyncArgv("xcallscreen", "incoming", cid.c_str(), caller.c_str()); } ctx->uiDirty = true; } void onToxAvCallState(ToxAV*, Tox_Friend_Number friendNum, uint32_t state, void* userData) { auto* ctx = static_cast(userData); if (friendNum != ctx->callFriendNum) return; if (state & (TOXAV_FRIEND_CALL_STATE_FINISHED | TOXAV_FRIEND_CALL_STATE_ERROR)) { stopToxAvAudioPipes(ctx); ctx->inCall = false; ctx->callIncoming = false; ctx->callActive = false; ctx->callFriendNum = UINT32_MAX; ::unlink("/tmp/sxmo_call_ringing"); runAsyncCmd("sxmo_jobs.sh stop ringing >/dev/null 2>&1; " "pkill -TERM -f sxmo_hook_ring.sh >/dev/null 2>&1"); sendPluginCommand("callscreen", "ENDED TOX CALL ENDED"); ctx->uiDirty = true; } else if (state & (TOXAV_FRIEND_CALL_STATE_SENDING_A | TOXAV_FRIEND_CALL_STATE_ACCEPTING_A)) { if (!ctx->callActive) { ctx->callActive = true; ctx->callIncoming = false; ::unlink("/tmp/sxmo_call_ringing"); runAsyncCmd("sxmo_jobs.sh stop ringing >/dev/null 2>&1; " "pkill -TERM -f sxmo_hook_ring.sh >/dev/null 2>&1"); startToxAvAudioPipes(ctx); std::string caller = getFriendDisplayName(ctx->tox, friendNum); for (char& c : caller) { if (c == ' ') c = '_'; } sendPluginCommand("callscreen", "ACTIVE tox:" + std::to_string(friendNum) + " " + caller + " TOX"); ctx->uiDirty = true; } } } void onToxAvAudioReceiveFrame(ToxAV*, Tox_Friend_Number, const int16_t pcm[], size_t sampleCount, uint8_t channels, uint32_t, void* userData) { auto* ctx = static_cast(userData); std::lock_guard lk(ctx->audioMtx); if (!ctx->playPipe || !pcm || sampleCount == 0) return; if (channels == 1) { std::fwrite(pcm, sizeof(int16_t), sampleCount, ctx->playPipe); } else { std::vector mono(sampleCount); for (size_t i = 0; i < sampleCount; ++i) { mono[i] = pcm[i * channels]; } std::fwrite(mono.data(), sizeof(int16_t), sampleCount, ctx->playPipe); } std::fflush(ctx->playPipe); } void bootstrapToxDht(Tox* tox) { struct BootstrapNode { const char* host; uint16_t port; const char* pubKeyHex; }; static const BootstrapNode kNodes[] = { {"114.35.245.150", 33445, "3F0A45A268367C1BEA652F258C85F4A66DA76BCAA667A49E770BCC4917AB6A25"}, {"24.87.200.32", 33445, "10C00EB250C3233E343E2AEBA07115A5C28920E9C8D29492F6D00B29049EDC7E"}, {"144.217.167.73", 33445, "7E5668E0EE09E19F320AD47902419331FFEE147BB3606769CFBE921A2A2FD34C"} }; for (const auto& n : kNodes) { uint8_t pk[TOX_PUBLIC_KEY_SIZE] = {0}; if (hexToBytes(n.pubKeyHex, pk, TOX_PUBLIC_KEY_SIZE)) { tox_bootstrap(tox, n.host, n.port, pk, nullptr); tox_add_tcp_relay(tox, n.host, n.port, pk, nullptr); } } } int tox_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("tox", forwarded)) { return 0; } std::string daemonPidPath = getPluginDaemonPidPath("tox"); std::string activePidPath = getRuntimeFile("xtox.pid"); writeIntFile(daemonPidPath, static_cast(::getpid())); int fifoFd = setupPluginDaemonFifo("tox"); struct sigaction sa {}; sa.sa_handler = handleSignal; sigemptyset(&sa.sa_mask); sigaction(SIGTERM, &sa, nullptr); sigaction(SIGINT, &sa, nullptr); NeoWindow neo; if (!neo.create("xtox", "XTox", "Tox Messenger")) { if (fifoFd >= 0) ::close(fifoFd); ::unlink(daemonPidPath.c_str()); return 1; } neo.bindAsActiveContext(); // Initialize c-toxcore instance from savedata or fresh profile Tox_Options* opts = tox_options_new(nullptr); tox_options_set_ipv6_enabled(opts, false); tox_options_set_udp_enabled(opts, true); tox_options_set_local_discovery_enabled(opts, true); std::vector savedData; { std::ifstream in(getToxProfilePath(), std::ios::binary); if (in.is_open()) { savedData.assign(std::istreambuf_iterator(in), std::istreambuf_iterator()); if (!savedData.empty()) { tox_options_set_savedata_type(opts, TOX_SAVEDATA_TYPE_TOX_SAVE); tox_options_set_savedata_data(opts, savedData.data(), savedData.size()); } } } Tox_Err_New newErr = TOX_ERR_NEW_OK; Tox* tox = tox_new(opts, &newErr); tox_options_free(opts); if (!tox) { tox = tox_new(nullptr, &newErr); } ToxRuntimeContext ctx; ctx.tox = tox; if (tox) { if (tox_self_get_name_size(tox) == 0) { const char* defName = "Bananarchy"; tox_self_set_name(tox, reinterpret_cast(defName), std::strlen(defName), nullptr); const char* defStatus = "On Bananarchy Linux"; tox_self_set_status_message(tox, reinterpret_cast(defStatus), std::strlen(defStatus), nullptr); } saveToxProfile(tox); tox_callback_self_connection_status(tox, onSelfConnectionStatus); tox_callback_friend_request(tox, onFriendRequest); tox_callback_friend_message(tox, onFriendMessage); tox_callback_friend_name(tox, onFriendName); tox_callback_friend_connection_status(tox, onFriendConnectionStatus); ctx.toxav = toxav_new(tox, nullptr); if (ctx.toxav) { toxav_callback_call(ctx.toxav, onToxAvCall, &ctx); toxav_callback_call_state(ctx.toxav, onToxAvCallState, &ctx); toxav_callback_audio_receive_frame(ctx.toxav, onToxAvAudioReceiveFrame, &ctx); } } // Export Tox ID to /tmp/tox_id.txt for easy sharing std::string selfToxIdHex; if (tox) { uint8_t addr[TOX_ADDRESS_SIZE] = {0}; tox_self_get_address(tox, addr); selfToxIdHex = bytesToHexUpper(addr, TOX_ADDRESS_SIZE); std::ofstream idOut("/tmp/tox_id.txt", std::ios::trunc); if (idOut.is_open()) { idOut << selfToxIdHex << "\n"; } } bool networkActive = false; int64_t lastBootstrapMs = 0; bool visible = false; int activeTab = 0; // 0=Friends, 1=Chat, 2=My Tox ID int selectedRow = 0; int scrollOffset = 0; uint32_t activeFriendNum = 0; bool hasActiveFriend = false; int chatScrollBack = 0; std::string chatInput; bool menuOpen = false; int menuSel = 0; // Add friend modal bool addModalOpen = false; std::string addToxIdStr; auto getFriendList = [&]() -> std::vector { std::vector list; if (!tox) return list; size_t cnt = tox_self_get_friend_list_size(tox); if (cnt > 0) { list.resize(cnt); tox_self_get_friend_list(tox, list.data()); } return list; }; auto ensureNetworkStarted = [&]() { if (!tox) return; if (!networkActive) { networkActive = true; ctx.connBadge = "CONNECTING"; bootstrapToxDht(tox); lastBootstrapMs = nowMs(); } }; auto render = [&]() { if (!visible) return; neo.bindAsActiveContext(); neoui_begin_frame(); neoui_draw_header(kIconShield, ctx.dhtConnected ? NEO_TEXT_GREEN : NEO_TEXT_YELLOW, "Tox / Trifa", ctx.connBadge.c_str()); neoui_draw_tabs("Friends|Chat|Tox ID", activeTab, 34, 24); constexpr int kBodyY = 58; constexpr int kBodyH = 296 - kBodyY - NEO_SOFTBAR_H; std::vector friends = getFriendList(); if (activeTab == 0) { int totalItems = static_cast(ctx.pendingReqs.size() + friends.size()); int rowH = 42; int maxVis = kBodyH / rowH; if (totalItems == 0) { neoui_draw_text_centered(NEO_FONT_MAIN, NEO_TEXT_MUTED, 0, kBodyY + 55, 240, 24, "No Tox Friends Yet"); neoui_draw_text_centered(NEO_FONT_SMALL, NEO_TEXT_YELLOW, 0, kBodyY + 82, 240, 20, "Press OK or Menu -> Add Friend"); } else { selectedRow = std::clamp(selectedRow, 0, totalItems - 1); if (selectedRow < scrollOffset) scrollOffset = selectedRow; if (selectedRow >= scrollOffset + maxVis) scrollOffset = selectedRow - maxVis + 1; for (int i = 0; i < maxVis && (scrollOffset + i) < totalItems; ++i) { int idx = scrollOffset + i; if (idx < static_cast(ctx.pendingReqs.size())) { const auto& r = ctx.pendingReqs[idx]; std::string title = "Req: " + r.pubKeyHex.substr(0, 12) + "..."; neoui_draw_list_row(idx, kBodyY + i * rowH, rowH, idx == selectedRow ? 1 : 0, kIconPlus, NEO_TEXT_YELLOW, title.c_str(), r.message.c_str(), "ACCEPT"); } else { uint32_t fnum = friends[idx - static_cast(ctx.pendingReqs.size())]; std::string name = getFriendDisplayName(tox, fnum); std::string pkHex = getFriendPubKeyHex(tox, fnum).substr(0, 16); Tox_Connection cstat = tox_friend_get_connection_status(tox, fnum, nullptr); const char* badge = (cstat == TOX_CONNECTION_UDP) ? "UDP" : ((cstat == TOX_CONNECTION_TCP) ? "TCP" : "OFF"); int col = (cstat != TOX_CONNECTION_NONE) ? NEO_TEXT_GREEN : NEO_TEXT_MUTED; neoui_draw_list_row(idx, kBodyY + i * rowH, rowH, idx == selectedRow ? 1 : 0, kIconUser, col, name.c_str(), pkHex.c_str(), badge); } } neoui_draw_scrollbar(236, kBodyY, kBodyH, totalItems, maxVis, scrollOffset); } neoui_draw_softkeys("Menu", totalItems == 0 ? "ADD" : "CHAT", "Close"); } else if (activeTab == 1) { if (!hasActiveFriend && !friends.empty()) { activeFriendNum = friends[0]; hasActiveFriend = true; } if (!hasActiveFriend) { neoui_draw_text_centered(NEO_FONT_MAIN, NEO_TEXT_MUTED, 0, kBodyY + 70, 240, 24, "Select a friend first"); neoui_draw_softkeys("Menu", "FRIENDS", "Back"); } else { std::string pkHex = getFriendPubKeyHex(tox, activeFriendNum); std::vector chat = loadFriendChat(pkHex); int msgAreaH = kBodyH - 48; int lineH = 18; int maxLines = msgAreaH / lineH; int total = static_cast(chat.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 = chat[startIdx + i]; std::string line = m.timeStr + (m.outgoing ? " Me: " : " Peer: ") + m.text; neoui_draw_text(NEO_FONT_SMALL, m.outgoing ? NEO_TEXT_GREEN : NEO_TEXT_WHITE, 6, kBodyY + 2 + i * lineH, lineH, line.c_str(), 228); } neoui_draw_input_box(4, kBodyY + msgAreaH, 232, 26, 1, "", neoui_input_get_text(), "Encrypted Tox message...", 0); neoui_draw_multitap_bar(0, 296 - NEO_SOFTBAR_H - 20, 240, 20, "[OK] Send [Call] Voice Call [*] Mode"); neoui_draw_softkeys("Menu", "SEND", "Back"); } } else { neoui_draw_text(NEO_FONT_SMALL, NEO_TEXT_YELLOW, 8, kBodyY + 4, 18, "Your 76-char Tox ID (saved in /tmp/tox_id.txt):", 224); // Display 76 hex chars across 4 clean lines of 19 chars for (int row = 0; row < 4; ++row) { size_t pos = static_cast(row * 19); if (pos < selfToxIdHex.size()) { std::string chunk = selfToxIdHex.substr(pos, 19); neoui_draw_text(NEO_FONT_MAIN, NEO_TEXT_WHITE, 12, kBodyY + 26 + row * 22, 20, chunk.c_str(), 216); } } neoui_draw_button(12, kBodyY + 124, 216, 32, 1, 0, kIconPlus, "Add Friend by Tox ID"); neoui_draw_softkeys("Menu", "ADD FRIEND", "Back"); } if (addModalOpen) { neoui_draw_modal_box(6, 48, 228, 170, kIconPlus, NEO_TEXT_YELLOW, "Add Friend (76-hex Tox ID)"); neoui_draw_input_box(12, 82, 216, 48, 1, "Tox ID:", neoui_input_get_text(), "76 hex chars...", 0); neoui_draw_multitap_bar(12, 140, 216, 22, "[*] Mode [Left Soft] Add"); neoui_draw_softkeys("Add", "PASTE /TMP", "Cancel"); } else if (menuOpen) { neoui_draw_menu_popup( "Add Friend by Tox ID|Start Voice Call|Bootstrap DHT Now|Rotate NoSpam|Delete Friend", nullptr, menuSel, 5); } neoui_end_frame(); }; auto startOutgoingToxCall = [&](uint32_t friendNum) { if (!ctx.toxav || ctx.inCall) return; Toxav_Err_Call err; if (toxav_call(ctx.toxav, friendNum, 32, 0, &err)) { ctx.inCall = true; ctx.callIncoming = false; ctx.callActive = false; ctx.callFriendNum = friendNum; std::string name = getFriendDisplayName(tox, friendNum); for (char& c : name) { if (c == ' ') c = '_'; } sendPluginCommand("callscreen", "OUTGOING tox:" + std::to_string(friendNum) + " " + name + " TOX"); } else { neoui_show_toast("Friend is offline or busy", 2000); } }; auto openWindow = [&]() { if (isDuressMode() || isPhonePasscodeLocked()) return; writeIntFile(activePidPath, static_cast(::getpid())); closeOtherPlugins("tox"); visible = true; neoui_show(); neoui_input_reset(chatInput.c_str()); render(); ensureNetworkStarted(); }; auto closeWindow = [&]() { if (!visible) return; visible = false; addModalOpen = 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") { if (isDuressMode()) { closeWindow(); networkActive = false; continue; } neo.reloadTheme(); if (visible) render(); } else if (cmd.rfind("CALL_ACCEPT", 0) == 0) { if (ctx.inCall && ctx.callIncoming && ctx.toxav) { if (toxav_answer(ctx.toxav, ctx.callFriendNum, 32, 0, nullptr)) { ctx.callActive = true; ctx.callIncoming = false; ::unlink("/tmp/sxmo_call_ringing"); runAsyncCmd("sxmo_jobs.sh stop ringing >/dev/null 2>&1; " "pkill -TERM -f sxmo_hook_ring.sh >/dev/null 2>&1"); startToxAvAudioPipes(&ctx); std::string caller = getFriendDisplayName(tox, ctx.callFriendNum); for (char& c : caller) { if (c == ' ') c = '_'; } sendPluginCommand("callscreen", "ACTIVE tox:" + std::to_string(ctx.callFriendNum) + " " + caller + " TOX"); } } } else if (cmd.rfind("CALL_HANGUP", 0) == 0) { if (ctx.inCall && ctx.toxav) { toxav_call_control(ctx.toxav, ctx.callFriendNum, TOXAV_CALL_CONTROL_CANCEL, nullptr); stopToxAvAudioPipes(&ctx); ctx.inCall = false; ctx.callIncoming = false; ctx.callActive = false; ctx.callFriendNum = UINT32_MAX; } } else if (cmd.rfind("CALL_MUTE_RING", 0) == 0) { ::unlink("/tmp/sxmo_call_ringing"); runAsyncCmd("sxmo_jobs.sh stop ringing >/dev/null 2>&1; " "pkill -TERM -f sxmo_hook_ring.sh >/dev/null 2>&1"); } else if (cmd == "OPEN" || cmd.rfind("OPEN ", 0) == 0) { openWindow(); } } // Iterate Tox and ToxAV when visible, in a call, or when friends are configured bool shouldIterateTox = !isDuressMode() && networkActive && tox && (visible || ctx.inCall || tox_self_get_friend_list_size(tox) > 0); if (shouldIterateTox) { tox_iterate(tox, &ctx); if (ctx.toxav) { toxav_iterate(ctx.toxav); } if (ctx.inCall && ctx.callActive && ctx.capFd >= 0 && ctx.toxav) { // Send 20ms (960 samples @ 48kHz) audio frames when available int16_t pcmFrame[960]; ssize_t r = ::read(ctx.capFd, pcmFrame, sizeof(pcmFrame)); if (r == sizeof(pcmFrame)) { toxav_audio_send_frame(ctx.toxav, ctx.callFriendNum, pcmFrame, 960, 1, 48000, nullptr); } } if (!ctx.dhtConnected && nowMs() - lastBootstrapMs >= 30000) { bootstrapToxDht(tox); lastBootstrapMs = nowMs(); } if (ctx.uiDirty && visible) { ctx.uiDirty = false; 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 (addModalOpen) { std::string rawId = trimStr(neoui_input_get_text()); uint8_t addrBytes[TOX_ADDRESS_SIZE] = {0}; if (hexToBytes(rawId, addrBytes, TOX_ADDRESS_SIZE)) { const char* msg = "Hello from Bananarchy Linux"; Tox_Err_Friend_Add addErr; tox_friend_add(tox, addrBytes, reinterpret_cast(msg), std::strlen(msg), &addErr); saveToxProfile(tox); addModalOpen = false; neoui_show_toast("Friend request sent", 2000); } else { neoui_show_toast("Invalid 76-hex Tox ID", 2000); } render(); } else { menuOpen = !menuOpen; menuSel = 0; render(); } } else if (ev == NEO_EV_SOFTKEY_RIGHT) { if (addModalOpen) { addModalOpen = false; render(); } else if (menuOpen) { menuOpen = false; render(); } else if (activeTab != 0) { activeTab = 0; render(); } else { closeWindow(); break; } } else if (ev == NEO_EV_KEY_PRESS) { int k = neoui_event_key(); std::vector friends = getFriendList(); 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) { addModalOpen = true; neoui_input_reset(""); } else if (menuSel == 1 && hasActiveFriend) { startOutgoingToxCall(activeFriendNum); } else if (menuSel == 2) { ensureNetworkStarted(); bootstrapToxDht(tox); neoui_show_toast("DHT bootstrap triggered", 1500); } else if (menuSel == 3 && tox) { tox_self_set_nospam(tox, static_cast(nowMs())); uint8_t addr[TOX_ADDRESS_SIZE] = {0}; tox_self_get_address(tox, addr); selfToxIdHex = bytesToHexUpper(addr, TOX_ADDRESS_SIZE); saveToxProfile(tox); } else if (menuSel == 4 && activeTab == 0 && !friends.empty()) { int fIdx = selectedRow - static_cast(ctx.pendingReqs.size()); if (fIdx >= 0 && fIdx < static_cast(friends.size())) { tox_friend_delete(tox, friends[fIdx], nullptr); saveToxProfile(tox); } } } else if (k == NEO_KEY_BACK || k == NEO_KEY_END) { menuOpen = false; } render(); } else if (addModalOpen) { if (k == NEO_KEY_OK) { // Paste from /tmp/tox_add.txt if present std::ifstream pf("/tmp/tox_add.txt"); if (pf.is_open()) { std::string line; std::getline(pf, line); neoui_input_set_text(trimStr(line).c_str()); } } else if (k == NEO_KEY_STAR) { neoui_input_cycle_mode(); } else if (k == NEO_KEY_BACK) { neoui_input_backspace(); } else if (k >= NEO_KEY_0 && k <= NEO_KEY_9) { neoui_input_feed_key(k); } render(); } else { if (k == NEO_KEY_LEFT) { activeTab = (activeTab + 2) % 3; selectedRow = 0; scrollOffset = 0; } else if (k == NEO_KEY_RIGHT) { activeTab = (activeTab + 1) % 3; selectedRow = 0; scrollOffset = 0; } 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) { int fIdx = selectedRow - static_cast(ctx.pendingReqs.size()); if (fIdx >= 0 && fIdx < static_cast(friends.size())) { startOutgoingToxCall(friends[fIdx]); } } else if (k == NEO_KEY_OK) { if (ctx.pendingReqs.empty() && friends.empty()) { addModalOpen = true; neoui_input_reset(""); } else if (selectedRow >= 0 && selectedRow < static_cast(ctx.pendingReqs.size())) { auto req = ctx.pendingReqs[selectedRow]; ctx.pendingReqs.erase(ctx.pendingReqs.begin() + selectedRow); tox_friend_add_norequest(tox, req.pubKey, nullptr); saveToxProfile(tox); neoui_show_toast("Friend request accepted", 1500); } else { int fIdx = selectedRow - static_cast(ctx.pendingReqs.size()); if (fIdx >= 0 && fIdx < static_cast(friends.size())) { activeFriendNum = friends[fIdx]; hasActiveFriend = true; activeTab = 1; chatScrollBack = 0; neoui_input_reset(""); } } } else if (k == NEO_KEY_BACK || k == NEO_KEY_END) { closeWindow(); break; } } else if (activeTab == 1) { if (k == NEO_KEY_UP) ++chatScrollBack; else if (k == NEO_KEY_DOWN && chatScrollBack > 0) --chatScrollBack; else if (k == NEO_KEY_CALL && hasActiveFriend) { startOutgoingToxCall(activeFriendNum); } else if (k == NEO_KEY_OK && hasActiveFriend) { std::string txt = trimStr(neoui_input_get_text()); if (!txt.empty()) { Tox_Err_Friend_Send_Message sendErr; tox_friend_send_message(tox, activeFriendNum, TOX_MESSAGE_TYPE_NORMAL, reinterpret_cast(txt.data()), txt.size(), &sendErr); if (sendErr == TOX_ERR_FRIEND_SEND_MESSAGE_OK) { appendFriendChat(getFriendPubKeyHex(tox, activeFriendNum), true, txt); neoui_input_reset(""); } else { neoui_show_toast("Friend is currently offline", 2000); } } } 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(); } else { activeTab = 0; } } else if (k >= NEO_KEY_0 && k <= NEO_KEY_9) { neoui_input_feed_key(k); } } else if (activeTab == 2) { if (k == NEO_KEY_OK) { addModalOpen = true; neoui_input_reset(""); } } 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 = -1; if (ctx.inCall && ctx.callActive) { timeoutMs = 20; } else if (visible) { int baseTimeout = shouldIterateTox ? static_cast(std::clamp( tox_iteration_interval(tox), 250, 1000)) : -1; timeoutMs = neoui_next_timeout_ms(baseTimeout); } else if (shouldIterateTox) { timeoutMs = static_cast( std::clamp(tox_iteration_interval(tox), 250, 1000)); } ::poll(pfds, (fifoFd >= 0) ? 2 : 1, timeoutMs); } stopToxAvAudioPipes(&ctx); if (ctx.toxav) toxav_kill(ctx.toxav); if (tox) { saveToxProfile(tox); tox_kill(tox); } if (fifoFd >= 0) ::close(fifoFd); ::unlink(getPluginFifoPath("tox").c_str()); ::unlink(daemonPidPath.c_str()); return 0; } int tox_plugin_init(const DwmHostApi* host) { if (host && host->spawn_plugin) { host->spawn_plugin("tox", "--preload"); } return 0; } } // namespace extern "C" __attribute__((visibility("default"))) const DwmPlugin dwm_plugin_entry = { DWM_PLUGIN_API_VERSION, "tox", "Tox / Trifa P2P messenger and audio call client (c-toxcore)", tox_plugin_init, nullptr, nullptr, nullptr, nullptr, tox_run_main };