foreseen

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

render.cpp (16154B)


      1 #include "../include/render.hpp"
      2 
      3 #include <ncurses.h>
      4 #include <unctrl.h>
      5 
      6 #include <algorithm>
      7 #include <cassert>
      8 #include <chrono>
      9 #include <cstdint>
     10 #include <cstdlib>
     11 #include <string>
     12 #include <utility>
     13 #include <vector>
     14 
     15 #include "../include/browser.hpp"
     16 #include "../include/shared.hpp"
     17 #include "../include/utils.hpp"
     18 
     19 #ifndef CTRL
     20 #define CTRL(c) ((c) & 037)
     21 #endif
     22 
     23 #ifdef DEBUG_MODE
     24 const char* OUT_LOCATION = "/tmp/foreseen";
     25 #else
     26 const char* OUT_LOCATION = "";
     27 #endif
     28 
     29 int lowestPos(std::vector<std::pair<std::string, TextRender>>& strLs,
     30               DrawState& ds) {
     31     return (strLs.size() - (ds.lines - 2)) +
     32            1;  // this gives us two new lines at the end because the last line
     33                // should contain a \n.
     34 }
     35 
     36 bool isValidUserInput(int uinput) {
     37     if ((uinput >= 0x20 && uinput <= 0x7E)) {
     38         return true;
     39     }
     40     return false;
     41 }
     42 void drawInputBox(std::string text, std::string userInput, DrawState& ds) {
     43     move(ds.lines / 2 - 1, ds.columns / 4);
     44 
     45     attron(COLOR_PAIR(COLOR_CYAN + 1));
     46     for (int i = 0; i < ds.columns / 2; ++i) {
     47         addstr("-");
     48     }
     49 
     50     move(ds.lines / 2 + 1, ds.columns / 4);
     51     for (int i = 0; i < ds.columns / 2; ++i) {
     52         addstr("-");
     53     }
     54     attroff(COLOR_PAIR(COLOR_CYAN + 1));
     55 
     56     int userInputSize = userInput.size();
     57     int width = ds.columns / 2;
     58 
     59     if ((int)text.size() >= width) {
     60         text = text.substr(0, width - 6) + "...: ";
     61     }
     62 
     63     int textSize = text.size();
     64 
     65     assert(textSize < width);
     66 
     67     std::string userTextToRender = userInput;
     68 
     69     int delta = width - (textSize + userInputSize);
     70 
     71     if (delta < 0) {
     72         userTextToRender = userInput.substr(delta * -1, userInput.size());
     73     } else {
     74         while (delta != 0) {
     75             userTextToRender.append(
     76                 " ");  // this makes sure the background doesn't leak through.
     77             delta -= 1;
     78         }
     79     }
     80 
     81     move(ds.lines / 2, ds.columns / 4);
     82     attron(COLOR_PAIR(COLOR_WHITE + 1));
     83     addstr(text.c_str());
     84     addstr(userTextToRender.c_str());
     85     attroff(COLOR_PAIR(COLOR_WHITE + 1));
     86 }
     87 uint64_t getCurrentTime() {
     88     return std::chrono::duration_cast<std::chrono::milliseconds>(
     89                std::chrono::steady_clock::now().time_since_epoch())
     90         .count();
     91 }
     92 
     93 void draw(DrawState& ds) {
     94     if (ds.columns < 20) {
     95         erase();
     96         attron(COLOR_PAIR(COLOR_WHITE + 1));
     97         addstr("Screen width too small.");
     98         attroff(COLOR_PAIR(COLOR_WHITE + 1));
     99         refresh();
    100         return;
    101     }
    102     if (ds.lines < 5) {  //  This is the min size that still allows top and
    103                          //  bottom padding along with one line of text.
    104         erase();
    105         attron(COLOR_PAIR(COLOR_WHITE + 1));
    106         addstr("Screen height too small.");
    107         attroff(COLOR_PAIR(COLOR_WHITE + 1));
    108         refresh();
    109         return;
    110     }
    111 
    112     auto* cs = ds.bPtr->getCurrentSite();
    113 
    114     // CS is null or has status 2X
    115     if (!(cs != nullptr &&
    116           (cs->getStatusCode() < 20 || cs->getStatusCode() > 29))) {
    117         if (ds.mustReRender) {
    118             ds.prior = ds.bPtr->renderSite();
    119             sanitizeCharactersToDraw(ds.prior);
    120             ds.mustReRender = false;
    121             ds.reBreak = true;
    122         }
    123     }
    124 
    125     if (ds.reBreak) {
    126         ds.broken =
    127             breakLines(ds.prior, std::min(ds.columns, MAX_WIDTH), ds.columns);
    128         ds.reBreak = false;
    129     }
    130     if (ds.toLowest) {
    131         ds.y = lowestPos(ds.broken, ds);
    132         ds.toLowest = false;
    133     }
    134 
    135     ds.y = std::max(0, std::min(ds.y, lowestPos(ds.broken, ds)));
    136 
    137     erase();
    138     move(0, (ds.columns / 2) - ((int)ds.header.size() / 2));
    139 
    140     attron(A_BOLD);
    141     attron(COLOR_PAIR(COLOR_WHITE + 1));
    142 
    143     if ((int)ds.header.size() < ds.columns) {
    144         addstr(ds.header.c_str());
    145     } else {
    146         addstr((ds.header.substr(0, ds.columns - 3) + "...").c_str());
    147     }
    148 
    149     attroff(COLOR_PAIR(COLOR_WHITE + 1));
    150     attroff(A_BOLD);
    151 
    152     addstr(std::string(ds.columns, ' ').c_str());
    153 
    154     for (int i = ds.y; i - ds.y < ds.lines - 4 && i < (int)ds.broken.size();
    155          ++i) {
    156         move(i - ds.y + 2, 0);
    157 
    158         attron(COLOR_PAIR(ds.broken[i].second.color + 1));
    159         if (ds.broken[i].second.isBold) {
    160             attron(A_BOLD);
    161             addstr(ds.broken[i].first.c_str());
    162             attroff(A_BOLD);
    163         } else {
    164             addstr(ds.broken[i].first.c_str());
    165         }
    166         attroff(COLOR_PAIR(ds.broken[i].second.color + 1));
    167     }
    168 
    169     if (ds.handleRedirect) {
    170         std::string toShow = "Redirect to \"" + ds.metaLine + "\" (y/n): ";
    171         drawInputBox(toShow, ds.redirInput, ds);
    172     }
    173 
    174     if (ds.handleInput) {
    175         if (ds.metaLine != "") {
    176             drawInputBox(ds.metaLine + ": ", ds.userInput, ds);
    177         } else {
    178             drawInputBox("Input: ", ds.userInput, ds);
    179         }
    180     }
    181 
    182     if (ds.handleOpenOther) {
    183         drawInputBox("Destination / Link Number: ", ds.openOtherInput, ds);
    184     }
    185 
    186     if (ds.issueText != "") {
    187         uint64_t now = getCurrentTime();
    188         if (ds.timeToClearIssueText <= now) {
    189             ds.issueText = "";
    190         } else {
    191             move(0, 0);
    192             attron(A_BOLD);
    193             attron(COLOR_PAIR(COLOR_RED + 1));
    194 
    195             std::string tr = ds.issueText;
    196             std::string truncated;
    197 
    198             for (auto& ch : tr) {
    199                 truncated += (char)toascii(ch);
    200             }
    201 
    202             if ((int)ds.issueText.size() > ds.columns) {
    203                 truncated = truncated.substr(0, ds.columns - 3) + "...";
    204             }
    205 
    206             addstr(truncated.c_str());
    207             attroff(COLOR_PAIR(COLOR_RED + 1));
    208             attroff(A_BOLD);
    209         }
    210     }
    211 
    212     if (ds.bottomText != "") {
    213         uint64_t now = getCurrentTime();
    214         if (ds.timeToClearBottomText <= now) {
    215             ds.bottomText = "";
    216         } else {
    217             std::string tr = ds.bottomText;
    218             std::string truncated;
    219 
    220             for (auto& ch : tr) {
    221                 truncated += (char)toascii(ch);
    222             }
    223 
    224             if ((int)truncated.size() > ds.columns) {
    225                 truncated = truncated.substr(0, ds.columns - 3) + "...";
    226             }
    227 
    228             move(ds.lines - 1, (ds.columns / 2) - ((int)truncated.size() / 2));
    229             attron(A_BOLD);
    230             attron(COLOR_PAIR(COLOR_WHITE + 1));
    231             addstr(truncated.c_str());
    232             attroff(COLOR_PAIR(COLOR_WHITE + 1));
    233             attroff(A_BOLD);
    234         }
    235     }
    236 
    237     refresh();
    238 }
    239 
    240 void openPageHandler(DrawState& ds, int sel) {
    241     if (sel == KEY_BACKSPACE || sel == 127 || sel == 8) {
    242         if (ds.openOtherInput.size() > 0) {
    243             ds.openOtherInput =
    244                 ds.openOtherInput.substr(0, ds.openOtherInput.size() - 1);
    245         }
    246     }
    247 
    248     if (sel == 27) {
    249         ds.openOtherInput = "";
    250         ds.handleOpenOther = false;
    251         return;
    252     }
    253 
    254     if (sel == '\n' || sel == KEY_ENTER) {
    255         ds.handleOpenOther = false;
    256         return;
    257     }
    258 
    259     if (isValidUserInput(sel)) {
    260         ds.openOtherInput += std::string{(char)sel};
    261     }
    262 }
    263 
    264 void handleRedir(DrawState& ds, int input, Browser& b) {
    265     if (input == 'y') {
    266         ds.redirInput = "y";
    267         draw(ds);
    268         ds.handleRedirect = false;
    269         tryVisitSite(ds, b, b.getCurrentSite()->getMeta());
    270         ds.mustReRender = true;
    271     }
    272     if (input == 'n') {
    273         ds.redirInput = "n";
    274         draw(ds);
    275         ds.handleRedirect = false;
    276         b.goBack();
    277         ds.mustReRender = true;
    278     }
    279 }
    280 
    281 void handleUserInput(DrawState& ds, Browser& b, int sel) {
    282     if (sel == '\n' || sel == KEY_ENTER) {
    283         ds.handleInput = false;
    284 
    285         if (ds.userInput != "") {
    286             tryVisitSite(ds, b, "?" + ds.userInput);
    287         } else {
    288             b.goBack();
    289             ds.mustReRender = true;
    290         }
    291         return;
    292     }
    293     if (sel == 27) {
    294         ds.handleInput = false;
    295         draw(ds);  // this might not be totally necessary because back is
    296                    // generally fast, but it's not strictly guaranteed.
    297         b.goBack();
    298         ds.mustReRender = true;
    299         return;
    300     }
    301 
    302     if (sel == KEY_BACKSPACE || sel == 127 || sel == 8) {
    303         if (ds.userInput.size() > 0) {
    304             ds.userInput = ds.userInput.substr(0, ds.userInput.size() - 1);
    305         }
    306         return;
    307     }
    308 
    309     if (isValidUserInput(sel)) {
    310         ds.userInput += std::string{(char)sel};
    311     }
    312 }
    313 void handleResult(DrawState& ds, SiteLoadPair result) {
    314     switch (result.result) {
    315         case SITE_LOADED:
    316             if (result.metaLine != OPENED_EXT_TXT) {
    317                 ds.y = 0;
    318                 ds.mustReRender = true;
    319             }
    320             break;
    321         case SITE_TEMPORARY_FAILURE:
    322             if (result.metaLine != "") {
    323                 ds.issueText = "Temporary site failure: " + result.metaLine;
    324             } else {
    325                 ds.issueText = "Temporary site failure";
    326             }
    327             break;
    328         case SITE_PERMANENT_FAILURE:
    329             if (result.metaLine != "") {
    330                 ds.issueText = "Permanent site failure: " + result.metaLine;
    331             } else {
    332                 ds.issueText = "Permanent site failure";
    333             }
    334 
    335             break;
    336         case SITE_REQUIRES_CERTIFICATE:
    337             if (result.metaLine != "") {
    338                 ds.issueText =
    339                     "Site requires a certificate: " + result.metaLine;
    340             } else {
    341                 ds.issueText = "Site requires a certificate";
    342             }
    343 
    344             break;
    345         case SITE_REJECTED_CERTIFICATE:
    346             if (result.metaLine != "") {
    347                 ds.issueText =
    348                     "Your certificate is not authorized: " + result.metaLine;
    349             } else {
    350                 ds.issueText = "Your certificate is not authorized";
    351             }
    352 
    353             break;
    354         case SITE_INVALID_CERTIFICATE:
    355 
    356             if (result.metaLine != "") {
    357                 ds.issueText =
    358                     "Your certificate has been rejected as invalid: " +
    359                     result.metaLine;
    360             } else {
    361                 ds.issueText = "Your certificate has been rejected as invalid";
    362             }
    363 
    364             break;
    365         case SITE_UNEXPECTED_STATUS_CODE:
    366             ds.issueText = "The server replied with an invalid status code";
    367             break;
    368         case LINK_DOES_NOT_EXIST:
    369             ds.issueText = "Link not found";
    370             break;
    371     }
    372     ds.timeToClearIssueText = getCurrentTime() + 1000;
    373 }
    374 
    375 void tryVisitSite(DrawState& ds, Browser& b, std::string site) {
    376     // Should this be url encoded? Would that be better for users or like this?
    377     ds.bottomText = "Loading: " + site;
    378     ds.timeToClearBottomText = getCurrentTime() + 5000;
    379     draw(ds);
    380     SiteLoadPair result = b.goToSite(site);
    381     ds.bottomText = "";
    382     handleResult(ds, result);
    383 }
    384 
    385 bool mainLoop(DrawState& ds, Browser& b, int input, int cols, int lines) {
    386     if (lines != ds.lines || cols != ds.columns) {
    387         ds.reBreak = true;
    388     }
    389 
    390     ds.lines = lines;
    391     ds.columns = cols;
    392 
    393     if (ds.handleOpenOther) {
    394         openPageHandler(ds, input);
    395         if (!ds.handleOpenOther) {
    396             draw(ds);
    397             if (ds.openOtherInput != "") {
    398                 Destination destination =
    399                     handleDestinationResolution(ds.openOtherInput, false);
    400                 SiteLoadPair res;
    401                 switch (destination.t) {
    402                     case NUMBER_DESTINATION:
    403                         ds.bottomText = "Following link: " +
    404                                         std::to_string(destination.linkNumber);
    405                         ds.timeToClearBottomText = getCurrentTime() + 5000;
    406                         draw(ds);
    407                         res = b.followLinkNumber(destination.linkNumber);
    408                         handleResult(ds, res);
    409                         ds.bottomText = "";
    410                         break;
    411                     case STRING_DESTINATION:
    412                         tryVisitSite(ds, b, destination.destination);
    413                         break;
    414                     case NO_DESTINATION:
    415                         break;
    416                 }
    417                 ds.openOtherInput = "";
    418             }
    419             mainLoop(ds, b, KEY_RESIZE, ds.columns, ds.lines);
    420         } else {
    421             draw(ds);
    422         }
    423         return true;
    424     } else if (ds.handleRedirect) {
    425         handleRedir(ds, input, b);
    426 
    427         if (!ds.handleRedirect) {
    428             mainLoop(ds, b, KEY_RESIZE, ds.columns, ds.lines);
    429         } else {
    430             draw(ds);
    431         }
    432 
    433         return true;
    434     } else if (ds.handleInput) {
    435         handleUserInput(ds, b, input);
    436         if (!ds.handleInput) {
    437             mainLoop(ds, b, KEY_RESIZE, ds.columns, ds.lines);
    438         } else {
    439             draw(ds);
    440         }
    441         return true;
    442     }
    443 
    444     if (input == 'q') {
    445         return false;
    446     }
    447 
    448     if (input == KEY_DOWN) {
    449         ds.y += 1;
    450     } else if (input == KEY_UP) {
    451         ds.y -= 1;
    452     } else if (input == 'g') {
    453         ds.y = 0;
    454     } else if (input == 'G') {
    455         ds.toLowest = true;
    456     } else if (input == CTRL('d')) {
    457         ds.y += ds.lines / 2;
    458     } else if (input == CTRL('u')) {
    459         ds.y -= ds.lines / 2;
    460     } else if (input == 'r' || input == CTRL('r')) {
    461         ds.bottomText = "Refreshing " +
    462                         b.getCurrentLink()->getLinkDestination().to_string();
    463         ds.timeToClearBottomText = getCurrentTime() + 5000;
    464         draw(ds);
    465         b.refresh();
    466         ds.mustReRender = true;
    467         ds.bottomText = "";
    468     } else if (input == 'f') {
    469         b.goForward();  // TODO: it's possible this might not be in
    470                         // cache, but probably not worth bothering with
    471                         // rendering loading text.
    472         ds.mustReRender = true;
    473         ds.y = 0;
    474     } else if (input == 'd') {
    475         std::string outLocation = b.tryDownloadPage(OUT_LOCATION);
    476         if (outLocation == "") {
    477             ds.issueText = "Failed to download file";
    478             ds.timeToClearIssueText = getCurrentTime() + 1000;
    479         } else {
    480             ds.bottomText = "File downloaded to " + outLocation;
    481             ds.timeToClearBottomText = getCurrentTime() + 1000;
    482         }
    483     } else if (input == 'b') {
    484         b.goBack();
    485         ds.mustReRender = true;
    486         ds.y = 0;
    487     } else if (input == 'o') {
    488         ds.handleOpenOther = true;
    489     } else if (input == 'e') {
    490         std::string editor = getEditor();
    491         std::string dl = b.tryDownloadPage(OUT_LOCATION);
    492         if (dl != "") {
    493             def_prog_mode();
    494             endwin();
    495             std::string quoted = "'";
    496             for (char c : dl) {
    497                 if (c == '\'') {
    498                     quoted += std::string("'\\''");
    499                 } else {
    500                     quoted += std::string(1, c);
    501                 }
    502             }
    503             quoted += "'";
    504             system((editor + " " + quoted).c_str());
    505             refresh();
    506         } else {
    507             ds.issueText = "Failed to download file";
    508             ds.timeToClearIssueText = getCurrentTime() + 1000;
    509         }
    510     }
    511 
    512     if ((b.getCurrentSite()->getStatusCode() < 20 ||
    513          b.getCurrentSite()->getStatusCode() > 29) &&
    514         !ds.handleRedirect && !ds.handleInput) {
    515         if (b.getCurrentSite()->getStatusCode() >= 10 &&
    516             b.getCurrentSite()->getStatusCode() <= 19) {
    517             auto* st = b.getCurrentSite();
    518             assert(st != nullptr);
    519             ds.metaLine = st->getMeta();
    520 
    521             ds.handleInput = true;
    522             ds.userInput = "";
    523 
    524         } else if (b.getCurrentSite()->getStatusCode() >= 30 &&
    525                    b.getCurrentSite()->getStatusCode() <= 39 &&
    526                    !ds.handleRedirect) {
    527             auto* st = b.getCurrentSite();
    528             if (st != nullptr) {
    529                 ds.metaLine = st->getMeta();
    530             }
    531 
    532             ds.redirInput = "";
    533             ds.handleRedirect = true;
    534         }
    535     }
    536 
    537     auto* clk = b.getCurrentLink();
    538     assert(clk != nullptr);
    539     ds.header = clk->getLinkDestination().to_string();
    540 
    541     auto* st = b.getCurrentSite();
    542     assert(st != nullptr);
    543     ds.metaLine = st->getMeta();
    544 
    545     draw(ds);
    546     return true;
    547 }