foreseen

A text-based gemini browser with prefetching
git clone git://git.laack.co/foreseen.git
Log | Files | Refs | README | LICENSE

utils.cpp (13105B)


      1 #include "../include/utils.hpp"
      2 
      3 #include <fcntl.h>
      4 #include <spawn.h>
      5 #include <sys/wait.h>
      6 
      7 #include <algorithm>
      8 #include <cassert>
      9 #include <cstddef>
     10 #include <cstdlib>
     11 #include <filesystem>
     12 #include <fstream>
     13 #include <iomanip>
     14 #include <ios>
     15 #include <regex>
     16 #include <sstream>
     17 #include <stdexcept>
     18 #include <string>
     19 #include <utility>
     20 #include <vector>
     21 
     22 #include "../include/errors.hpp"
     23 #include "../include/format-switch.hpp"
     24 #include "../include/heading.hpp"
     25 #include "../include/link.hpp"
     26 #include "../include/list-item.hpp"
     27 #include "../include/plaintext.hpp"
     28 #include "../include/preformatted.hpp"
     29 #include "../include/quote.hpp"
     30 #include "../include/shared.hpp"
     31 
     32 extern char** environ;
     33 
     34 void openUrl(const std::string& url) {
     35     posix_spawn_file_actions_t fa;
     36     posix_spawn_file_actions_init(&fa);
     37     // we don't want the stdout mucking up our terminal.
     38     posix_spawn_file_actions_addopen(&fa, 1, "/dev/null", O_WRONLY, 0);
     39     posix_spawn_file_actions_adddup2(&fa, 1, 2);
     40 
     41     pid_t pid;
     42     char* argv[] = {(char*)openUnknownScheme, (char*)url.c_str(), nullptr};
     43     if (posix_spawnp(&pid, openUnknownScheme, &fa, nullptr, argv, environ) ==
     44         0) {
     45         waitpid(pid, nullptr, 0);
     46     }
     47     posix_spawn_file_actions_destroy(&fa);
     48 }
     49 
     50 bool isPrefixed(std::string input, std::string prefix) {
     51     return std::string(input).find(prefix) == 0;
     52 }
     53 
     54 std::string readFileToString(std::string filePath) {
     55     auto in = std::ifstream(filePath);
     56     if (in.fail()) {
     57         throw FileReadError{};
     58     }
     59     std::ostringstream sstr;
     60     sstr << in.rdbuf();
     61     return sstr.str();
     62 }
     63 
     64 std::string stripLeadingWhiteSpace(std::string& input) {
     65     std::size_t x = 0;
     66 
     67     while (x < input.size() && isWhiteSpace(input, x)) {
     68         x += 1;
     69     }
     70     return input.substr(x);
     71 }
     72 
     73 bool isWhiteSpace(std::string& line, int idx) {
     74     if (idx < (int)line.size() && idx >= 0) {
     75         return line[idx] == ' ' || line[idx] == '\t';
     76     }
     77     return false;
     78 }
     79 
     80 std::vector<std::string> stringToList(std::string input) {
     81     std::vector<std::string> res;
     82     if (!input.empty()) {
     83         int start = 0;
     84         do {
     85             std::size_t idx = input.find('\n', start);
     86             if (idx == std::string::npos) {
     87                 break;
     88             }
     89             int length = idx - start;
     90             res.push_back(input.substr(start, length));
     91             start += (length + 1);
     92 
     93         } while (true);
     94         res.push_back(input.substr(start));
     95     }
     96 
     97     return res;
     98 }
     99 
    100 Line* lineToLine(std::string input, std::optional<uri> prior, int linkCount,
    101                  bool isPreformatted) {
    102     if (input.substr(0, 3) == "```") {
    103         FormatSwitch* fs = new FormatSwitch{input};
    104         return fs;
    105     }
    106 
    107     if (!isPreformatted) {
    108         if (input.substr(0, 2) == "=>") {
    109             Link* ln = new Link{input, prior, linkCount};
    110             return ln;
    111         }
    112         if ((input.substr(0, 1) == "#") || (input.substr(0, 2) == "##") ||
    113             (input.substr(0, 3) == "###")) {
    114             Heading* hd = new Heading{input};
    115             return hd;
    116         }
    117 
    118         if (input.substr(0, 1) == ">") {
    119             Quote* qt = new Quote{input};
    120             return qt;
    121         }
    122         if (input.substr(0, 2) == "* ") {
    123             ListItem* li = new ListItem{input};
    124             return li;
    125         }
    126 
    127         return new Plaintext{input};
    128     } else {
    129         return new Preformatted{input};
    130     }
    131     return new Plaintext{input};
    132 }
    133 
    134 std::string urlEncode(const std::string& value) {
    135     std::ostringstream escaped;
    136     escaped.fill('0');
    137     escaped << std::hex;
    138 
    139     for (std::string::const_iterator i = value.begin(), n = value.end(); i != n;
    140          ++i) {
    141         std::string::value_type c = (*i);
    142 
    143         // Keep alphanumeric and other accepted characters intact
    144         if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
    145             escaped << c;
    146             continue;
    147         }
    148 
    149         // Any other characters are percent-encoded
    150         escaped << std::uppercase;
    151         escaped << '%' << std::setw(2) << int((unsigned char)c);
    152         escaped << std::nouppercase;
    153     }
    154 
    155     return escaped.str();
    156 }
    157 
    158 std::string getNewTab() {
    159     std::string st =
    160         "# New Tab\n"
    161         "\n"
    162         "This is a new tab. We have a few keybindings around here:\n"
    163         "\n"
    164         "* (q|C-c) -> quit\n"
    165         "* b -> back a page\n"
    166         "* f -> forward a page\n"
    167         "* o -> show url entry / link selection\n"
    168         "* C-d -> move half a page down\n"
    169         "* C-u -> move half a page up\n"
    170         "* g -> go to the top of the page\n"
    171         "* G -> go to the bottom of the page\n"
    172         "* d -> download current page\n"
    173         "* e -> open current page in your preferred text editor\n"
    174         "* (r | C-r) -> refresh page\n";
    175     return st;
    176 }
    177 
    178 int u8len(unsigned char c) {
    179     if (c < 0x80) {
    180         return 1;
    181     }
    182     if ((c >> 5) == 0x6) {
    183         return 2;
    184     }
    185     if ((c >> 4) == 0xE) {
    186         return 3;
    187     }
    188     if ((c >> 3) == 0x1E) {
    189         return 4;
    190     }
    191     return 1;
    192 }
    193 
    194 int u8width(const std::string& s, std::size_t i, int len) {
    195     unsigned char c = static_cast<unsigned char>(s[i]);
    196     if (len == 1 && c < 0x80) {
    197         return (c >= 0x20 && c != 0x7F) ? 1 : 0;
    198     }
    199 
    200     std::mbstate_t st{};
    201     wchar_t wc;
    202     if (std::mbrtowc(&wc, s.data() + i, len, &st) != (std::size_t)len) {
    203         return 1;
    204     }
    205     int w = wcwidth(wc);
    206     if (w < 0) {
    207         return 0;
    208     }
    209     return w;
    210 }
    211 
    212 // WIDTH IS INCLUSIVE
    213 // WE ASSUME NO WIDER CHARS (E.G. replace tabs with spaces.)
    214 
    215 std::vector<std::pair<std::string, TextRender>> breakLines(
    216     std::vector<std::pair<std::string, TextRender>>& strLs, int width,
    217     int cols) {
    218     std::vector<std::pair<std::string, TextRender>> res{};
    219 
    220     int leftPadAmount = std::max(0, (cols - width) / 2);
    221     std::string leftPadStr(leftPadAmount, ' ');
    222 
    223     if (width <= 0) {
    224         return res;
    225     }
    226 
    227     res.reserve(strLs.size());
    228 
    229     for (std::size_t i = 0; i < strLs.size(); ++i) {
    230         const std::string& cstr = strLs[i].first;
    231 
    232         if (!strLs[i].second.shouldFold) {
    233             int limit = cols - leftPadAmount;
    234             int w = 0;
    235             std::size_t end = 0;
    236             while (end < cstr.size()) {
    237                 int len = std::min(u8len(cstr[end]), (int)(cstr.size() - end));
    238                 int cw = u8width(cstr, end, len);
    239                 if (w + cw > limit) {
    240                     break;
    241                 }
    242                 w += cw;
    243                 end += len;
    244             }
    245             std::string rs =
    246                 cstr.substr(0, end);  // otherwise there's some funkiness at the
    247                                       // end due to how ncurses renders stuff.
    248             res.push_back(std::pair<std::string, TextRender>{leftPadStr + rs,
    249                                                              strLs[i].second});
    250             continue;
    251         }
    252 
    253         std::string current = "";
    254         int curWidth = 0;
    255         int lastSpace = -1;
    256         int lastSpaceWidth = 0;
    257 
    258         for (int x = 0; x < (int)cstr.size();) {
    259             if (cstr[x] == '\n') {
    260                 res.push_back(std::pair<std::string, TextRender>{
    261                     leftPadStr + current, strLs[i].second});
    262                 current = "";
    263                 curWidth = 0;
    264                 lastSpace = -1;
    265                 ++x;
    266                 continue;
    267             }
    268 
    269             int len = std::min(u8len(cstr[x]), (int)cstr.size() - x);
    270             int w = u8width(cstr, x, len);
    271 
    272             if (w > 0 && curWidth > 0 && curWidth + w > width) {
    273                 std::string toPush = current;
    274 
    275                 if (lastSpace != -1) {
    276                     toPush = current.substr(0, lastSpace + 1);
    277                     current = current.substr(lastSpace + 1);
    278                     curWidth = curWidth - lastSpaceWidth;
    279                 } else {
    280                     current = "";
    281                     curWidth = 0;
    282                 }
    283 
    284                 res.push_back(std::pair<std::string, TextRender>{
    285                     leftPadStr + toPush, strLs[i].second});
    286                 lastSpace = -1;
    287             }
    288 
    289             current.append(cstr, x, len);
    290             curWidth += w;
    291             if (cstr[x] == ' ') {
    292                 lastSpace = current.size() - 1;
    293                 lastSpaceWidth = curWidth;
    294             }
    295             x += len;
    296         }
    297         if (current.size() > 0) {
    298             res.push_back(std::pair<std::string, TextRender>{
    299                 leftPadStr + current, strLs[i].second});
    300             current = "";
    301         }
    302     }
    303 
    304     return res;
    305 }
    306 
    307 void writeStringToFile(std::string toWrite, std::string filePath) {
    308     std::filesystem::path path{filePath};
    309     std::ofstream ofs(path);
    310     ofs << toWrite;
    311 }
    312 std::string encodeAsFilename(uri link) {
    313     std::string base = link.to_string();
    314     assert(base.find(':') != std::string::npos);
    315     base =
    316         base.substr(base.find(':') + 1);  // works for file:/// and gemini:///
    317 
    318     while (base.size() > 0 && base[0] == '/') {
    319         base = base.substr(1);
    320     }
    321 
    322     std::string cleaned =
    323         std::regex_replace(base, std::regex("[^[:alnum:]._-]"), "_");
    324     return cleaned;
    325 }
    326 
    327 std::filesystem::path getHome() {
    328     std::string home = std::getenv("HOME");
    329     if (home == "") {
    330         throw std::runtime_error{"$HOME not set."};
    331     }
    332     if (!std::filesystem::exists(home)) {
    333         throw std::runtime_error{"$HOME directory doesn't exist..."};
    334     }
    335 
    336     return home;
    337 }
    338 
    339 Destination handleDestinationResolution(std::string destination, bool isCli) {
    340     Destination ret{};
    341 
    342     if (destination == "") {
    343         ret.t = NO_DESTINATION;
    344         return ret;
    345     }
    346 
    347     if (isCli) {
    348         if (std::filesystem::exists(destination)) {
    349             std::string path = "file://" +
    350                                std::filesystem::current_path().string() + "/" +
    351                                destination;
    352 
    353             if (destination.find('/') == std::size_t(0)) {
    354                 path = "file://" + destination;
    355             }
    356 
    357             ret.destination = path;
    358             ret.t = STRING_DESTINATION;
    359             return ret;
    360 
    361         } else {
    362             std::string inputString = destination;
    363             if (inputString.find("gemini://") == 0) {
    364                 ret.destination = destination;
    365                 ret.t = STRING_DESTINATION;
    366                 return ret;
    367             } else if (inputString.find(':') == std::string::npos) {
    368                 ret.destination = std::string{"gemini://"} + destination;
    369                 ret.t = STRING_DESTINATION;
    370                 return ret;
    371 
    372             } else {
    373                 ret.destination = destination;
    374                 ret.t = STRING_DESTINATION;
    375                 return ret;
    376             }
    377         }
    378     } else {
    379         try {
    380             std::size_t pos = 0;
    381             int dest = std::stoi(destination, &pos);
    382             if (pos == destination.size() && dest >= 0) {
    383                 ret.linkNumber = dest;
    384                 ret.t = NUMBER_DESTINATION;
    385                 return ret;
    386             } else {
    387                 throw std::invalid_argument("Unable to convert fully");
    388             }
    389         } catch (...) {
    390             if (destination.find(' ') == std::string::npos &&
    391                 (destination.rfind("localhost:", 0) == 0 ||
    392                  destination.rfind("localhost/", 0) == 0 ||
    393                  destination == "localhost")) {
    394                 destination = "gemini://" + destination;
    395             } else if (destination.find("://") == std::string::npos ||
    396                        destination.find(' ') != std::string::npos) {
    397                 if (destination.find('.') != std::string::npos &&
    398                     destination.find(' ') == std::string::npos) {
    399                     destination = "gemini://" + destination;
    400                 } else {
    401                     destination =
    402                         DEFAULT_SEARCH_ENGINE + urlEncode(destination);
    403                 }
    404             }
    405 
    406             ret.destination = destination;
    407             ret.t = STRING_DESTINATION;
    408             return ret;
    409         }
    410     }
    411     throw std::logic_error("Unexpected input.");
    412 }
    413 
    414 void sanitizeCharactersToDraw(
    415     std::vector<std::pair<std::string, TextRender>>& strLs) {
    416     for (std::size_t i = 0; i < strLs.size(); ++i) {
    417         std::string& s = strLs[i].first;
    418         std::string out;
    419         out.reserve(s.size());
    420 
    421         for (int c : s)
    422             if (c == '\r' || c == '\v' || c == '\b' || c == '\f' || c == '\a' ||
    423                 c == '\0') {
    424                 continue;
    425             } else if (c == '\t') {
    426                 out += "    ";  // \t is a larger character and fucks with
    427                                 // breaklines.
    428             } else {
    429                 out += c;
    430             }
    431 
    432         strLs[i].first = out;
    433     }
    434     return;
    435 }
    436 
    437 bool isSendableIfGeminiUrl(const uri& u) {
    438     return u.get_scheme() != "gemini" || u.to_string().size() <= 1024;
    439 }
    440 
    441 std::string getEditor() {
    442     const char* editor = std::getenv("EDITOR");
    443     if (editor) {
    444         return std::string{editor};
    445     } else {
    446         // if editor isn't set, default to nano
    447         return "nano";
    448     }
    449 }