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

1080 lines
38 KiB
C++

// SPDX-License-Identifier: GPL-2.0-only
// Small Web Protocol Client DWM Plugin (smallweb.so / xkopher / xsmallweb)
// Supports:
// - Gopher (gopher://) with optional TLS (gophers://)
// - Gemini (gemini://) with gemtext rendering, redirects, and input prompts
// - Spartan (spartan://) with gemtext and Spartan (=:) input links
// - Nex (nex://) plain-text & directory navigation
// - Kopher (https://code.luxferre.top/luxferre/kopher.git) default WAP-style
// controls + user-adjustable keybindings stored in ~/.config/sxmo/
#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 SmallWebControls {
char keyBack = '1';
char keyPrevLink = '2';
char keyForward = '3';
char keyToggleTheme = '4';
char keyNextLink = '5';
char keyToggleWrap = '6';
char keyLineStart = '7';
char keyPageTop = '8';
char keyLineEnd = '9';
char keyPageEnd = '0';
void resetKopherDefaults() {
keyBack = '1';
keyPrevLink = '2';
keyForward = '3';
keyToggleTheme = '4';
keyNextLink = '5';
keyToggleWrap = '6';
keyLineStart = '7';
keyPageTop = '8';
keyLineEnd = '9';
keyPageEnd = '0';
}
};
std::string getControlsPath() {
return getHomeDirPath() + "/.config/sxmo/smallweb_controls.tsv";
}
std::string getBookmarksPath() {
return getHomeDirPath() + "/.config/sxmo/smallweb_bookmarks.tsv";
}
SmallWebControls loadControls() {
SmallWebControls c;
std::ifstream in(getControlsPath());
std::string k, v;
while (in >> k >> v) {
if (v.empty()) continue;
char ch = v[0];
if (k == "back") c.keyBack = ch;
else if (k == "prev_link") c.keyPrevLink = ch;
else if (k == "forward") c.keyForward = ch;
else if (k == "toggle_theme") c.keyToggleTheme = ch;
else if (k == "next_link") c.keyNextLink = ch;
else if (k == "toggle_wrap") c.keyToggleWrap = ch;
else if (k == "line_start") c.keyLineStart = ch;
else if (k == "page_top") c.keyPageTop = ch;
else if (k == "line_end") c.keyLineEnd = ch;
else if (k == "page_end") c.keyPageEnd = ch;
}
return c;
}
void saveControls(const SmallWebControls& c) {
std::string path = getControlsPath();
ContactBook::ensureParentDir(path);
std::ofstream out(path, std::ios::trunc);
if (!out.is_open()) return;
out << "back\t" << c.keyBack << "\n"
<< "prev_link\t" << c.keyPrevLink << "\n"
<< "forward\t" << c.keyForward << "\n"
<< "toggle_theme\t" << c.keyToggleTheme << "\n"
<< "next_link\t" << c.keyNextLink << "\n"
<< "toggle_wrap\t" << c.keyToggleWrap << "\n"
<< "line_start\t" << c.keyLineStart << "\n"
<< "page_top\t" << c.keyPageTop << "\n"
<< "line_end\t" << c.keyLineEnd << "\n"
<< "page_end\t" << c.keyPageEnd << "\n";
}
std::vector<std::string> loadBookmarks() {
std::vector<std::string> bm(11, "");
std::ifstream in(getBookmarksPath());
std::string line;
int idx = 0;
while (std::getline(in, line) && idx < 11) {
bm[idx++] = trimStr(line);
}
return bm;
}
void saveBookmarks(const std::vector<std::string>& bm) {
std::string path = getBookmarksPath();
ContactBook::ensureParentDir(path);
std::ofstream out(path, std::ios::trunc);
if (!out.is_open()) return;
for (size_t i = 0; i < 11; ++i) {
out << (i < bm.size() ? bm[i] : "") << "\n";
}
}
std::string stripAnsiCodes(const std::string& s) {
std::string out;
out.reserve(s.size());
for (size_t i = 0; i < s.size(); ++i) {
if (s[i] == '\x1b' && i + 1 < s.size() && s[i + 1] == '[') {
i += 2;
while (i < s.size() &&
!(static_cast<unsigned char>(s[i]) >= 0x40 &&
static_cast<unsigned char>(s[i]) <= 0x7e)) {
++i;
}
continue;
}
if (s[i] != '\r') {
out.push_back(s[i]);
}
}
return out;
}
std::string urlEncode(const std::string& s) {
std::string out;
char hex[4];
for (unsigned char c : s) {
if (std::isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
out.push_back(static_cast<char>(c));
} else {
std::snprintf(hex, sizeof(hex), "%%%02X", c);
out += hex;
}
}
return out;
}
std::string resolveRelativeUrl(const std::string& baseUrl,
const std::string& target) {
std::string t = trimStr(target);
if (t.empty()) return baseUrl;
if (t.find("://") != std::string::npos || t.rfind("about:", 0) == 0) {
return t;
}
ParsedUrl b = parseUrl(baseUrl, "gemini");
std::string portPart;
if ((b.scheme == "gopher" && b.port != 70) ||
(b.scheme == "gemini" && b.port != 1965) ||
(b.scheme == "spartan" && b.port != 300) ||
(b.scheme == "nex" && b.port != 1900)) {
portPart = ":" + std::to_string(b.port);
}
if (t[0] == '/') {
return b.scheme + "://" + b.host + portPart + t;
}
std::string baseDir = b.path;
size_t lastSlash = baseDir.rfind('/');
if (lastSlash == std::string::npos) {
baseDir = "/";
} else {
baseDir = baseDir.substr(0, lastSlash + 1);
}
return b.scheme + "://" + b.host + portPart + baseDir + t;
}
struct DocLine {
std::string text;
int linkIndex = -1;
bool isHeading = false;
bool isQuote = false;
bool isError = false;
};
struct LinkItem {
std::string label;
std::string url;
bool requiresInput = false;
};
struct PageDocument {
std::string url;
std::string hostTitle;
std::string statusMsg;
std::vector<DocLine> lines;
std::vector<LinkItem> links;
};
void parseGophermap(const std::string& raw, const std::string& scheme,
PageDocument& doc) {
std::istringstream iss(raw);
std::string line;
while (std::getline(iss, line)) {
if (!line.empty() && line.back() == '\r') line.pop_back();
if (line == ".") break;
if (line.empty()) {
doc.lines.push_back({"", -1, false, false, false});
continue;
}
if (line.find('\t') == std::string::npos) {
doc.lines.push_back({stripAnsiCodes(line), -1, false, false, false});
continue;
}
char type = line[0];
std::string rest = line.substr(1);
std::vector<std::string> parts;
std::stringstream ss(rest);
std::string col;
while (std::getline(ss, col, '\t')) parts.push_back(col);
std::string display = parts.empty() ? "" : stripAnsiCodes(parts[0]);
std::string sel = (parts.size() >= 2) ? parts[1] : "";
std::string host = (parts.size() >= 3) ? trimStr(parts[2]) : "";
int port = (parts.size() >= 4) ? std::atoi(parts[3].c_str()) : 70;
if (port <= 0) port = 70;
if (type == 'i') {
doc.lines.push_back({display, -1, false, false, false});
} else if (type == '3') {
doc.lines.push_back({"[ERR] " + display, -1, false, false, true});
} else {
LinkItem lnk;
lnk.label = display;
if (type == 'h' && sel.rfind("URL:", 0) == 0) {
lnk.url = sel.substr(4);
} else if (type == '8') {
lnk.url = "telnet://" + host + ":" + std::to_string(port);
} else {
std::string portPart = (port == 70) ? "" : (":" + std::to_string(port));
if (!sel.empty() && sel[0] == '/') {
lnk.url = scheme + "://" + host + portPart + "/" + type + sel.substr(1);
} else {
lnk.url = scheme + "://" + host + portPart + "/" + type + sel;
}
}
lnk.requiresInput = (type == '7');
int lIdx = static_cast<int>(doc.links.size());
doc.links.push_back(lnk);
std::string prefix = "[LINK] ";
if (type == '1') prefix = "[DIR] ";
else if (type == '0') prefix = "[TXT] ";
else if (type == '7') prefix = "[?] ";
else if (type == 'I' || type == 'g') prefix = "[IMG] ";
else if (type == '9' || type == '5' || type == 's') prefix = "[BIN] ";
else if (type == 'h') prefix = "[URL] ";
doc.lines.push_back({prefix + display, lIdx, false, false, false});
}
}
}
void parseGemtext(const std::string& raw, const std::string& baseUrl,
PageDocument& doc, bool allowSpartanPrompt) {
std::istringstream iss(raw);
std::string line;
bool preformatted = false;
while (std::getline(iss, line)) {
if (!line.empty() && line.back() == '\r') line.pop_back();
if (line.rfind("```", 0) == 0) {
preformatted = !preformatted;
continue;
}
if (preformatted) {
doc.lines.push_back({line, -1, false, false, false});
continue;
}
bool isLink = (line.rfind("=>", 0) == 0);
bool isPromptLink = (allowSpartanPrompt && line.rfind("=:", 0) == 0);
if (isLink || isPromptLink) {
std::string rest = trimStr(line.substr(2));
if (!rest.empty()) {
size_t sp = 0;
while (sp < rest.size() && !std::isspace(static_cast<unsigned char>(rest[sp]))) {
++sp;
}
std::string rawTarget = rest.substr(0, sp);
std::string label = (sp < rest.size()) ? trimStr(rest.substr(sp)) : rawTarget;
LinkItem lnk;
lnk.url = resolveRelativeUrl(baseUrl, rawTarget);
lnk.label = label;
lnk.requiresInput = isPromptLink;
int lIdx = static_cast<int>(doc.links.size());
doc.links.push_back(lnk);
doc.lines.push_back({(isPromptLink ? "[?] " : "-> ") + label,
lIdx, false, false, false});
continue;
}
}
if (!line.empty() && line[0] == '#') {
doc.lines.push_back({line, -1, true, false, false});
} else if (!line.empty() && line[0] == '>') {
doc.lines.push_back({line, -1, false, true, false});
} else {
doc.lines.push_back({line, -1, false, false, false});
}
}
}
void parsePlainText(const std::string& raw, PageDocument& doc) {
std::istringstream iss(raw);
std::string line;
while (std::getline(iss, line)) {
if (!line.empty() && line.back() == '\r') line.pop_back();
doc.lines.push_back({stripAnsiCodes(line), -1, false, false, false});
}
}
bool loadSmallWebUrl(const std::string& rawUrl, const std::string& queryInput,
bool gopherUseTlsByDefault, const SmallWebControls& ctrls,
PageDocument& outDoc, bool& outNeedsPrompt,
std::string& outPromptLabel) {
outDoc = PageDocument{};
outNeedsPrompt = false;
outPromptLabel.clear();
std::string url = trimStr(rawUrl);
if (url.empty()) url = "about:kopher";
if (url.rfind("about:", 0) == 0) {
outDoc.url = url;
outDoc.hostTitle = url;
outDoc.statusMsg = url;
if (url == "about:help") {
std::ostringstream h;
h << "iKopher / SmallWeb Controls\t\tlocalhost\t70\r\n"
<< "i* Scroll: Up/Down/Left/Right\t\tlocalhost\t70\r\n"
<< "i* Prev/Next link: " << ctrls.keyPrevLink << "/" << ctrls.keyNextLink << "\t\tlocalhost\t70\r\n"
<< "i* Open link: Center / OK\t\tlocalhost\t70\r\n"
<< "i* Enter address / Menu: LSK\t\tlocalhost\t70\r\n"
<< "i* Go back: " << ctrls.keyBack << " or RSK\t\tlocalhost\t70\r\n"
<< "i* Go forward: " << ctrls.keyForward << "\t\tlocalhost\t70\r\n"
<< "i* Refresh: Call\t\tlocalhost\t70\r\n"
<< "i* Page start/end: " << ctrls.keyPageTop << "/" << ctrls.keyPageEnd << "\t\tlocalhost\t70\r\n"
<< "i* Line start/end: " << ctrls.keyLineStart << "/" << ctrls.keyLineEnd << "\t\tlocalhost\t70\r\n"
<< "i* Open homepage: # *\t\tlocalhost\t70\r\n"
<< "i* Open bookmark: # [1-0]\t\tlocalhost\t70\r\n"
<< "i* Save homepage: * *\t\tlocalhost\t70\r\n"
<< "i* Save bookmark: * [1-0]\t\tlocalhost\t70\r\n"
<< "i* Share URL: * Call\t\tlocalhost\t70\r\n"
<< "i* Toggle light/dark: " << ctrls.keyToggleTheme << "\t\tlocalhost\t70\r\n"
<< "i* Toggle line wrap: " << ctrls.keyToggleWrap << "\t\tlocalhost\t70\r\n"
<< "i* Page info: # #\t\tlocalhost\t70\r\n"
<< "i* Customize keys: # 6\t\tlocalhost\t70\r\n"
<< "1Back to about:kopher\t\tabout:kopher\t70\r\n";
parseGophermap(h.str(), "gopher", outDoc);
if (!outDoc.links.empty()) {
outDoc.links.back().url = "about:kopher";
}
return true;
}
std::string kopherPage =
"Welcome to Kopher / SmallWeb\r\n"
"hControls help\tURL:about:help\tlocalhost\t70\r\n"
"Useful Gopher links:\r\n"
"1Quarry\t/quarry\tgopher.icu\t70\r\n"
"1Magical Fish\t/\tmagical.fish\t70\r\n"
"1Floodgap portal\t/\tgopher.floodgap.com\t70\r\n"
"Gemini, Spartan & Nex portals:\r\n"
"hProject Gemini\tURL:gemini://geminiprotocol.net/\tlocalhost\t70\r\n"
"hSpartan Portal\tURL:spartan://spartan.mozz.us/\tlocalhost\t70\r\n"
"hNex Nightfall City\tURL:nex://nightfall.city/\tlocalhost\t70\r\n"
"\r\n"
"Created by Luxferre, public domain\r\n";
parseGophermap(kopherPage, "gopher", outDoc);
return true;
}
for (int redirects = 0; redirects < 5; ++redirects) {
ParsedUrl u = parseUrl(url, gopherUseTlsByDefault ? "gophers" : "gopher");
outDoc.url = u.scheme + "://" + u.host +
((u.port == 70 || u.port == 1965 || u.port == 300 || u.port == 1900)
? ""
: (":" + std::to_string(u.port))) +
u.path;
outDoc.hostTitle = u.host;
outDoc.statusMsg = u.path;
if (u.scheme == "gopher" || u.scheme == "gophers") {
if (u.gopherType == '7' && queryInput.empty()) {
outNeedsPrompt = true;
outPromptLabel = "Search query:";
return false;
}
NetStream net;
if (!net.connectTcp(u.host, u.port, 6000)) {
outDoc.lines.push_back({"[ERR] " + net.lastError(), -1, false, false, true});
return true;
}
bool useTls = (u.scheme == "gophers" || gopherUseTlsByDefault);
if (useTls && !net.startTls(u.host, 4000)) {
// Fallback to plain Gopher if opportunistic TLS fails on gopher://
if (u.scheme == "gopher") {
net.connectTcp(u.host, u.port, 6000);
} else {
outDoc.lines.push_back({"[ERR] Gopher TLS handshake failed", -1, false, false, true});
return true;
}
}
std::string req = u.gopherSelector;
if (!queryInput.empty()) {
req += "\t" + queryInput;
}
req += "\r\n";
net.sendStr(req);
std::string raw;
net.readUntilClose(raw, 2 * 1024 * 1024, 8000);
if (u.gopherType == '1' || u.gopherType == '7') {
parseGophermap(raw, u.scheme, outDoc);
} else if (u.gopherType == '9' || u.gopherType == 'I' || u.gopherType == 'g' ||
u.gopherType == '5' || u.gopherType == 's') {
size_t sl = u.gopherSelector.rfind('/');
std::string fn = (sl == std::string::npos) ? u.gopherSelector
: u.gopherSelector.substr(sl + 1);
if (fn.empty()) fn = "download.bin";
std::string savePath = getHomeDirPath() + "/" + fn;
std::ofstream out(savePath, std::ios::binary | std::ios::trunc);
if (out.is_open()) {
out.write(raw.data(), static_cast<std::streamsize>(raw.size()));
outDoc.statusMsg = "Saved " + savePath;
outDoc.lines.push_back({"Saved binary file to: " + savePath, -1, false, false, false});
}
} else {
parsePlainText(raw, outDoc);
}
return true;
}
if (u.scheme == "gemini") {
std::string fullUrl = url;
if (!queryInput.empty()) {
size_t q = fullUrl.find('?');
if (q != std::string::npos) fullUrl = fullUrl.substr(0, q);
fullUrl += "?" + urlEncode(queryInput);
outDoc.url = fullUrl;
}
NetStream net;
if (!net.connectTcp(u.host, u.port, 6000) ||
!net.startTls(u.host, 6000)) {
outDoc.lines.push_back({"[ERR] " + net.lastError(), -1, false, false, true});
return true;
}
net.sendStr(fullUrl + "\r\n");
std::string hdrLine;
if (!net.readLine(hdrLine, 6000) || hdrLine.size() < 2) {
outDoc.lines.push_back({"[ERR] Empty Gemini header", -1, false, false, true});
return true;
}
int status = std::atoi(hdrLine.substr(0, 2).c_str());
std::string meta = (hdrLine.size() > 3) ? trimStr(hdrLine.substr(3)) : "";
if (status >= 10 && status < 20) {
outNeedsPrompt = true;
outPromptLabel = meta.empty() ? "Gemini Input:" : meta;
return false;
}
if (status >= 30 && status < 40 && !meta.empty()) {
url = resolveRelativeUrl(fullUrl, meta);
continue;
}
if (status < 20 || status >= 30) {
outDoc.lines.push_back(
{"[Gemini " + std::to_string(status) + "] " + meta, -1, false, false, true});
return true;
}
std::string body;
net.readUntilClose(body, 2 * 1024 * 1024, 8000);
if (meta.empty() || toLowerStr(meta).find("text/gemini") != std::string::npos) {
parseGemtext(body, fullUrl, outDoc, false);
} else {
parsePlainText(body, outDoc);
}
return true;
}
if (u.scheme == "spartan") {
NetStream net;
if (!net.connectTcp(u.host, u.port, 6000)) {
outDoc.lines.push_back({"[ERR] " + net.lastError(), -1, false, false, true});
return true;
}
std::ostringstream req;
req << u.host << " " << (u.path.empty() ? "/" : u.path) << " "
<< queryInput.size() << "\r\n" << queryInput;
net.sendStr(req.str());
std::string hdrLine;
if (!net.readLine(hdrLine, 6000) || hdrLine.empty()) {
outDoc.lines.push_back({"[ERR] Empty Spartan response", -1, false, false, true});
return true;
}
int status = hdrLine[0] - '0';
std::string meta = (hdrLine.size() > 2) ? trimStr(hdrLine.substr(2)) : "";
if (status == 3 && !meta.empty()) {
url = resolveRelativeUrl(url, meta);
continue;
}
if (status != 2) {
outDoc.lines.push_back({"[Spartan " + std::to_string(status) + "] " + meta,
-1, false, false, true});
return true;
}
std::string body;
net.readUntilClose(body, 2 * 1024 * 1024, 8000);
if (toLowerStr(meta).find("text/gemini") != std::string::npos) {
parseGemtext(body, url, outDoc, true);
} else {
parsePlainText(body, outDoc);
}
return true;
}
if (u.scheme == "nex") {
NetStream net;
if (!net.connectTcp(u.host, u.port, 6000)) {
outDoc.lines.push_back({"[ERR] " + net.lastError(), -1, false, false, true});
return true;
}
net.sendStr((u.path.empty() ? "/" : u.path) + "\r\n");
std::string body;
net.readUntilClose(body, 2 * 1024 * 1024, 8000);
parseGemtext(body, url, outDoc, false);
return true;
}
outDoc.lines.push_back({"[ERR] Unsupported scheme: " + u.scheme, -1, false, false, true});
return true;
}
return true;
}
int smallweb_run_main(int argc, char** argv) {
gRunning = 1;
bool isPreload = false;
std::string initUrl;
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 (initUrl.empty()) initUrl = argv[i];
}
std::string forwarded = isPreload ? "NOP" : (initUrl.empty() ? "OPEN" : ("OPEN " + initUrl));
if (sendPluginCommand("smallweb", forwarded)) {
return 0;
}
std::string daemonPidPath = getPluginDaemonPidPath("smallweb");
std::string activePidPath = getRuntimeFile("xsmallweb.pid");
writeIntFile(daemonPidPath, static_cast<int>(::getpid()));
int fifoFd = setupPluginDaemonFifo("smallweb");
struct sigaction sa {};
sa.sa_handler = handleSignal;
sigemptyset(&sa.sa_mask);
sigaction(SIGTERM, &sa, nullptr);
sigaction(SIGINT, &sa, nullptr);
NeoWindow neo;
if (!neo.create("xkopher", "XKopher", "Kopher / SmallWeb")) {
if (fifoFd >= 0) ::close(fifoFd);
::unlink(daemonPidPath.c_str());
return 1;
}
neo.bindAsActiveContext();
SmallWebControls ctrls = loadControls();
std::vector<std::string> bookmarks = loadBookmarks();
std::vector<std::string> history;
int historyIdx = -1;
PageDocument currentDoc;
int scrollTopLine = 0;
int scrollLeftCol = 0;
int focusedLinkIdx = 0;
bool wrapLines = false;
bool lightThemeOverride = false;
bool gopherTlsDefault = false;
std::string chordPrefix;
bool visible = false;
bool promptModalOpen = false;
std::string promptTitle = "Enter address:";
std::string pendingPromptUrl;
bool promptIsAddressBar = true;
bool infoModalOpen = false;
std::string infoModalLine1;
std::string infoModalLine2;
bool controlsModalOpen = false;
int controlsSelRow = 0;
auto navigateTo = [&](const std::string& targetUrl,
const std::string& query = "",
bool pushHistory = true) {
std::string normUrl = trimStr(targetUrl);
if (normUrl.empty()) return;
if (normUrl.find("://") == std::string::npos &&
normUrl.rfind("about:", 0) != 0) {
normUrl = (gopherTlsDefault ? "gophers://" : "gopher://") + normUrl;
}
bool needsPrompt = false;
std::string promptLbl;
PageDocument doc;
if (!loadSmallWebUrl(normUrl, query, gopherTlsDefault, ctrls, doc,
needsPrompt, promptLbl)) {
if (needsPrompt) {
promptModalOpen = true;
promptIsAddressBar = false;
promptTitle = promptLbl;
pendingPromptUrl = normUrl;
neoui_input_reset("");
return;
}
}
currentDoc = std::move(doc);
scrollTopLine = 0;
scrollLeftCol = 0;
focusedLinkIdx = 0;
if (pushHistory) {
if (historyIdx + 1 < static_cast<int>(history.size())) {
history.erase(history.begin() + historyIdx + 1, history.end());
}
history.push_back(currentDoc.url);
historyIdx = static_cast<int>(history.size()) - 1;
}
};
// Load initial homepage (bookmark #0 or about:kopher)
navigateTo(!bookmarks[0].empty() ? bookmarks[0] : "about:kopher");
auto focusLinkRelative = [&](int delta) {
if (currentDoc.links.empty()) return;
int cnt = static_cast<int>(currentDoc.links.size());
focusedLinkIdx = (focusedLinkIdx + delta + cnt) % cnt;
for (size_t i = 0; i < currentDoc.lines.size(); ++i) {
if (currentDoc.lines[i].linkIndex == focusedLinkIdx) {
scrollTopLine = std::max(0, static_cast<int>(i) - 4);
break;
}
}
};
auto render = [&]() {
if (!visible) return;
neo.bindAsActiveContext();
neoui_begin_frame();
if (lightThemeOverride) {
neoui_clear(0xF5F5F0);
}
std::string protoBadge = "GOPHER";
if (currentDoc.url.rfind("gophers:", 0) == 0) protoBadge = "GOPHERS";
else if (currentDoc.url.rfind("gemini:", 0) == 0) protoBadge = "GEMINI";
else if (currentDoc.url.rfind("spartan:", 0) == 0) protoBadge = "SPARTAN";
else if (currentDoc.url.rfind("nex:", 0) == 0) protoBadge = "NEX";
else if (currentDoc.url.rfind("about:", 0) == 0) protoBadge = "KOPHER";
neoui_draw_header(kIconGlobe, NEO_TEXT_GREEN,
currentDoc.hostTitle.c_str(), protoBadge.c_str());
constexpr int kContentY = 36;
constexpr int kStatusY = 296 - NEO_SOFTBAR_H - 18;
constexpr int kContentH = kStatusY - kContentY;
constexpr int kLineH = 16;
int maxVisLines = kContentH / kLineH;
// Expand wrapped lines if wrapLines is enabled
struct RenderRow {
std::string text;
int linkIndex;
bool isHeading;
bool isQuote;
bool isError;
};
std::vector<RenderRow> rows;
for (const auto& dl : currentDoc.lines) {
if (!wrapLines || dl.text.size() <= 30) {
std::string sliced = dl.text;
if (!wrapLines && scrollLeftCol > 0) {
if (static_cast<size_t>(scrollLeftCol) < sliced.size()) {
sliced = sliced.substr(scrollLeftCol);
} else {
sliced.clear();
}
}
rows.push_back({sliced, dl.linkIndex, dl.isHeading, dl.isQuote, dl.isError});
} else {
size_t pos = 0;
while (pos < dl.text.size()) {
size_t take = std::min<size_t>(30, dl.text.size() - pos);
rows.push_back({dl.text.substr(pos, take), dl.linkIndex,
dl.isHeading, dl.isQuote, dl.isError});
pos += take;
}
}
}
int totalRows = static_cast<int>(rows.size());
scrollTopLine = std::clamp(scrollTopLine, 0, std::max(0, totalRows - maxVisLines));
for (int i = 0; i < maxVisLines && (scrollTopLine + i) < totalRows; ++i) {
const auto& r = rows[scrollTopLine + i];
int y = kContentY + i * kLineH;
bool isSelLink = (r.linkIndex >= 0 && r.linkIndex == focusedLinkIdx);
if (isSelLink) {
neoui_fill_rect(2, y, 234, kLineH, neoui_color(NEO_COLOR_SEL_BG));
}
int col = lightThemeOverride ? NEO_TEXT_MUTED : NEO_TEXT_LIGHT;
if (isSelLink) col = NEO_TEXT_WHITE;
else if (r.linkIndex >= 0) col = NEO_TEXT_BLUE;
else if (r.isHeading) col = NEO_TEXT_YELLOW;
else if (r.isQuote) col = NEO_TEXT_GREEN;
else if (r.isError) col = NEO_TEXT_RED;
neoui_draw_text(NEO_FONT_SMALL, col, 4, y, kLineH, r.text.c_str(), 230);
}
neoui_draw_scrollbar(236, kContentY, kContentH, totalRows, maxVisLines,
scrollTopLine);
// Kopher bottom status bar (above softkeys)
neoui_fill_rect(0, kStatusY, 240, 18, neoui_color(NEO_COLOR_BG_ALT_EVEN));
std::string stText = !chordPrefix.empty()
? ("Key chord: " + chordPrefix + "_")
: currentDoc.statusMsg;
neoui_draw_text(NEO_FONT_SMALL, NEO_TEXT_YELLOW, 6, kStatusY, 18,
stText.c_str(), 228);
neoui_draw_softkeys("Address", "OPEN", "Back");
if (promptModalOpen) {
neoui_draw_modal_box(6, 46, 228, 174, kIconGlobe, NEO_TEXT_YELLOW,
promptTitle.c_str());
neoui_draw_input_box(12, 80, 216, 42, 1,
"gopher://, gemini://, spartan://, nex://",
neoui_input_get_text(), "gopher.floodgap.com", 0);
neoui_draw_multitap_bar(12, 130, 216, 22, "[*] Mode [Call] Gopher-TLS");
neoui_draw_softkeys("Go", "OPEN", "Cancel");
} else if (infoModalOpen) {
neoui_draw_confirm_dialog("Kopher / SmallWeb", infoModalLine1.c_str(),
infoModalLine2.c_str(), "Close", "Keys", 0);
} else if (controlsModalOpen) {
neoui_draw_modal_box(6, 30, 228, 232, kIconSliders, NEO_TEXT_YELLOW,
"Adjustable Controls (Press 0-9)");
const char* names[10] = {
"Go Back", "Prev Link", "Go Forward", "Light/Dark", "Next Link",
"Line Wrap", "Line Start", "Page Start", "Line End", "Page End"
};
char curKeys[10] = {
ctrls.keyBack, ctrls.keyPrevLink, ctrls.keyForward, ctrls.keyToggleTheme,
ctrls.keyNextLink, ctrls.keyToggleWrap, ctrls.keyLineStart,
ctrls.keyPageTop, ctrls.keyLineEnd, ctrls.keyPageEnd
};
int startIdx = std::max(0, std::min(controlsSelRow - 2, 5));
for (int i = 0; i < 5 && (startIdx + i) < 10; ++i) {
int r = startIdx + i;
std::string kstr(1, curKeys[r]);
neoui_draw_list_row(r, 60 + i * 32, 32, r == controlsSelRow ? 1 : 0,
kIconKey, r == controlsSelRow ? NEO_TEXT_YELLOW : NEO_TEXT_LIGHT,
names[r], "", kstr.c_str());
}
neoui_draw_softkeys("Save", "RESET DEF", "Cancel");
}
neoui_end_frame();
};
auto openWindow = [&]() {
if (isPhonePasscodeLocked()) return;
writeIntFile(activePidPath, static_cast<int>(::getpid()));
closeOtherPlugins("smallweb");
visible = true;
neoui_show();
render();
};
auto closeWindow = [&]() {
if (!visible) return;
visible = false;
promptModalOpen = false;
infoModalOpen = false;
controlsModalOpen = false;
chordPrefix.clear();
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) {
if (cmd.size() > 5) {
navigateTo(trimStr(cmd.substr(5)));
}
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 (promptModalOpen) {
std::string val = trimStr(neoui_input_get_text());
promptModalOpen = false;
if (!val.empty()) {
if (promptIsAddressBar) navigateTo(val);
else navigateTo(pendingPromptUrl, val);
}
render();
} else if (controlsModalOpen) {
saveControls(ctrls);
controlsModalOpen = false;
neoui_show_toast("Controls saved", 1500);
render();
} else if (infoModalOpen) {
infoModalOpen = false;
render();
} else {
promptModalOpen = true;
promptIsAddressBar = true;
promptTitle = "Enter Address:";
neoui_input_reset(currentDoc.url.c_str());
render();
}
} else if (ev == NEO_EV_SOFTKEY_RIGHT) {
if (promptModalOpen) {
promptModalOpen = false;
render();
} else if (controlsModalOpen) {
controlsModalOpen = false;
render();
} else if (infoModalOpen) {
infoModalOpen = false;
controlsModalOpen = true;
render();
} else {
if (historyIdx > 0) {
--historyIdx;
navigateTo(history[historyIdx], "", false);
render();
} else {
closeWindow();
break;
}
}
} else if (ev == NEO_EV_KEY_PRESS) {
int k = neoui_event_key();
if (promptModalOpen) {
if (k == NEO_KEY_OK) {
std::string val = trimStr(neoui_input_get_text());
promptModalOpen = false;
if (!val.empty()) {
if (promptIsAddressBar) navigateTo(val);
else navigateTo(pendingPromptUrl, val);
}
} else if (k == NEO_KEY_CALL) {
gopherTlsDefault = !gopherTlsDefault;
neoui_show_toast(
gopherTlsDefault ? "Gopher TLS: ON" : "Gopher TLS: OFF", 1500);
} 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 (controlsModalOpen) {
if (k == NEO_KEY_UP) controlsSelRow = (controlsSelRow + 9) % 10;
else if (k == NEO_KEY_DOWN) controlsSelRow = (controlsSelRow + 1) % 10;
else if (k == NEO_KEY_OK) {
ctrls.resetKopherDefaults();
saveControls(ctrls);
neoui_show_toast("Reset to Kopher defaults", 1500);
} else if (k >= NEO_KEY_0 && k <= NEO_KEY_9) {
char ch = static_cast<char>(k);
if (controlsSelRow == 0) ctrls.keyBack = ch;
else if (controlsSelRow == 1) ctrls.keyPrevLink = ch;
else if (controlsSelRow == 2) ctrls.keyForward = ch;
else if (controlsSelRow == 3) ctrls.keyToggleTheme = ch;
else if (controlsSelRow == 4) ctrls.keyNextLink = ch;
else if (controlsSelRow == 5) ctrls.keyToggleWrap = ch;
else if (controlsSelRow == 6) ctrls.keyLineStart = ch;
else if (controlsSelRow == 7) ctrls.keyPageTop = ch;
else if (controlsSelRow == 8) ctrls.keyLineEnd = ch;
else if (controlsSelRow == 9) ctrls.keyPageEnd = ch;
} else if (k == NEO_KEY_BACK || k == NEO_KEY_END) {
controlsModalOpen = false;
}
render();
} else if (infoModalOpen) {
infoModalOpen = false;
render();
} else {
// Handle Kopher 2-key chords starting with * or #
if (!chordPrefix.empty()) {
std::string prefix = chordPrefix;
chordPrefix.clear();
if (prefix == "*") {
if (k == NEO_KEY_STAR) {
bookmarks[0] = currentDoc.url;
saveBookmarks(bookmarks);
neoui_show_toast("Saved as Homepage", 1800);
} else if (k >= NEO_KEY_0 && k <= NEO_KEY_9) {
int bIdx = (k == NEO_KEY_0) ? 10 : (k - NEO_KEY_0);
bookmarks[bIdx] = currentDoc.url;
saveBookmarks(bookmarks);
neoui_show_toast(
("Saved Bookmark #" + std::to_string(bIdx)).c_str(), 1800);
} else if (k == NEO_KEY_CALL) {
std::ofstream sf("/tmp/shared_url.txt", std::ios::trunc);
if (sf.is_open()) sf << currentDoc.url << "\n";
neoui_show_toast("Shared URL -> /tmp/shared_url.txt", 2000);
}
} else if (prefix == "#") {
if (k == NEO_KEY_STAR) {
navigateTo(!bookmarks[0].empty() ? bookmarks[0] : "about:kopher");
} else if (k == NEO_KEY_HASH) {
infoModalLine1 = "Kopher SmallWeb v1.0";
infoModalLine2 = currentDoc.url;
infoModalOpen = true;
} else if (k >= NEO_KEY_0 && k <= NEO_KEY_9) {
int bIdx = (k == NEO_KEY_0) ? 10 : (k - NEO_KEY_0);
if (!bookmarks[bIdx].empty()) {
navigateTo(bookmarks[bIdx]);
} else if (bIdx == 6) {
controlsModalOpen = true;
} else {
neoui_show_toast(
("No bookmark at #" + std::to_string(bIdx)).c_str(), 1500);
}
}
}
render();
} else if (k == NEO_KEY_STAR) {
chordPrefix = "*";
render();
} else if (k == NEO_KEY_HASH) {
chordPrefix = "#";
render();
} else if (k == NEO_KEY_UP) {
if (scrollTopLine > 0) --scrollTopLine;
render();
} else if (k == NEO_KEY_DOWN) {
++scrollTopLine;
render();
} else if (k == NEO_KEY_LEFT) {
scrollLeftCol = std::max(0, scrollLeftCol - 6);
render();
} else if (k == NEO_KEY_RIGHT) {
scrollLeftCol += 6;
render();
} else if (k == NEO_KEY_OK) {
if (focusedLinkIdx >= 0 &&
focusedLinkIdx < static_cast<int>(currentDoc.links.size())) {
const auto& lnk = currentDoc.links[focusedLinkIdx];
if (lnk.requiresInput) {
promptModalOpen = true;
promptIsAddressBar = false;
promptTitle = lnk.label;
pendingPromptUrl = lnk.url;
neoui_input_reset("");
} else {
navigateTo(lnk.url);
}
}
render();
} else if (k == NEO_KEY_CALL) {
navigateTo(currentDoc.url, "", false);
render();
} else if (k == NEO_KEY_END || k == NEO_KEY_BACK) {
closeWindow();
break;
} else if (k >= NEO_KEY_0 && k <= NEO_KEY_9) {
char ch = static_cast<char>(k);
if (ch == ctrls.keyBack) {
if (historyIdx > 0) {
--historyIdx;
navigateTo(history[historyIdx], "", false);
}
} else if (ch == ctrls.keyForward) {
if (historyIdx + 1 < static_cast<int>(history.size())) {
++historyIdx;
navigateTo(history[historyIdx], "", false);
}
} else if (ch == ctrls.keyPrevLink) {
focusLinkRelative(-1);
} else if (ch == ctrls.keyNextLink) {
focusLinkRelative(1);
} else if (ch == ctrls.keyToggleTheme) {
lightThemeOverride = !lightThemeOverride;
} else if (ch == ctrls.keyToggleWrap) {
wrapLines = !wrapLines;
scrollLeftCol = 0;
} else if (ch == ctrls.keyLineStart) {
scrollLeftCol = 0;
} else if (ch == ctrls.keyLineEnd) {
scrollLeftCol = 40;
} else if (ch == ctrls.keyPageTop) {
scrollTopLine = 0;
} else if (ch == ctrls.keyPageEnd) {
scrollTopLine = static_cast<int>(currentDoc.lines.size());
}
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("smallweb").c_str());
::unlink(daemonPidPath.c_str());
return 0;
}
int smallweb_plugin_init(const DwmHostApi* host) {
if (host && host->spawn_plugin) {
host->spawn_plugin("smallweb", "--preload");
}
return 0;
}
} // namespace
extern "C" __attribute__((visibility("default"))) const DwmPlugin dwm_plugin_entry = {
DWM_PLUGIN_API_VERSION,
"smallweb",
"Kopher SmallWeb browser for Gopher(s), Gemini, Spartan, and Nex",
smallweb_plugin_init,
nullptr,
nullptr,
nullptr,
nullptr,
smallweb_run_main
};