Blob


1 /*
2 * Copyright (c) 2021 Omar Polo <op@omarpolo.com>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 /*
18 * Ncurses UI for telescope.
19 *
20 *
21 * Text wrapping
22 * =============
23 *
24 * There's a simple text wrapping algorithm.
25 *
26 * 1. if it's a line in a pre-formatted block:
27 * a. hard wrap.
28 * b. repeat
29 * 2. there is enough room for the next word?
30 * a. yes: render it
31 * b. no: break the current line.
32 * i. while there isn't enough space to draw the current
33 * word, hard-wrap it
34 * ii. draw the remainder of the current word (can be the
35 * the entirely)
36 * 3. render the spaces after the word
37 * a. but if there is not enough room break the line and
38 * forget them
39 * 4. repeat
40 *
41 *
42 * Text scrolling
43 * ==============
44 *
45 * ncurses allows you to scroll a window, but when a line goes out of
46 * the visible area it's forgotten. We keep a list of formatted lines
47 * (``visual lines'') that we know fits in the window, and draw them.
48 * This way is easy to scroll: just call wscrl and then render the
49 * first/last line!
50 *
51 * This means that on every resize we have to clear our list of lines
52 * and re-render everything. A clever approach would be to do this
53 * ``on-demand''.
54 *
55 * TODO: make the text formatting on-demand.
56 *
57 */
59 #include <telescope.h>
61 #include <curses.h>
62 #include <event.h>
63 #include <locale.h>
64 #include <signal.h>
65 #include <stdarg.h>
66 #include <stdlib.h>
67 #include <string.h>
69 #define TAB_CURRENT 0x1
71 #define MIN(a, b) ((a) < (b) ? (a) : (b))
72 #define MAX(a, b) ((a) > (b) ? (a) : (b))
74 struct key;
76 static struct event stdioev, winchev;
78 static int push_line(struct tab*, const struct line*, const char*, size_t);
79 static void empty_vlist(struct tab*);
80 static void restore_cursor(struct tab *);
81 static void cmd_previous_line(struct tab*);
82 static void cmd_next_line(struct tab*);
83 static void cmd_forward_char(struct tab*);
84 static void cmd_backward_char(struct tab*);
85 static void cmd_redraw(struct tab*);
86 static void cmd_scroll_down(struct tab*);
87 static void cmd_scroll_up(struct tab*);
88 static void cmd_kill_telescope(struct tab*);
89 static void cmd_push_button(struct tab*);
90 static void cmd_unbound(struct key);
91 static struct line *nth_line(struct tab*, size_t);
92 static struct tab *current_tab(void);
93 static void dispatch_stdio(int, short, void*);
94 static void handle_clear_minibuf(int, short, void*);
95 static void handle_resize(int, short, void*);
96 static int word_bourdaries(const char*, const char*, const char**, const char**);
97 static void wrap_text(struct tab*, const char*, struct line*);
98 static int hardwrap_text(struct tab*, struct line*);
99 static int wrap_page(struct tab*);
100 static void print_line(struct line*);
101 static void redraw_tabline(void);
102 static void redraw_modeline(struct tab*);
103 static void redraw_tab(struct tab*);
104 static void message(const char*, ...) __attribute__((format(printf, 1, 2)));
105 static void start_loading_anim(struct tab*);
106 static void update_loading_anim(int, short, void*);
107 static void stop_loading_anim(struct tab*);
108 static void load_url_in_tab(struct tab*, const char*);
109 static void new_tab(void);
111 typedef void (*interactivefn)(struct tab*);
113 static WINDOW *tabline, *body, *modeline, *minibuf;
114 static int body_lines, body_cols;
116 static struct event clminibufev;
117 static int clminibufev_set;
118 static struct timeval clminibufev_timer = { 5, 0 };
119 static struct timeval loadingev_timer = { 0, 250000 };
121 static uint32_t tab_counter;
123 struct ui_state {
124 int curs_x;
125 int curs_y;
126 size_t line_off;
127 size_t line_max;
129 short loading_anim;
130 short loading_anim_step;
131 struct event loadingev;
133 TAILQ_HEAD(, line) head;
134 };
136 struct key {
137 int meta;
138 int key;
139 };
141 #define KEY(n) ((struct key){0, n})
142 #define CKEY(n) ((struct key){0, (n) & 0x1F})
143 #define MKEY(n) ((struct key){1, n})
144 #define CMKEY(n) ((struct key){1, (n) & 0x1F})
146 struct binding {
147 struct key key;
148 interactivefn fn;
149 } bindings[] = {
150 { CKEY('p'), cmd_previous_line, },
151 { CKEY('n'), cmd_next_line, },
152 { CKEY('f'), cmd_forward_char, },
153 { CKEY('b'), cmd_backward_char, },
155 { {0,KEY_UP}, cmd_previous_line, },
156 { {0,KEY_DOWN}, cmd_next_line, },
158 { CKEY('L'), cmd_redraw, },
160 { KEY('J'), cmd_scroll_down, },
161 { KEY('K'), cmd_scroll_up, },
163 { KEY('q'), cmd_kill_telescope, },
164 { CKEY('m'), cmd_push_button, },
166 { {0, 0}, NULL, },
167 };
169 static int
170 push_line(struct tab *tab, const struct line *l, const char *buf, size_t len)
172 struct line *vl;
174 tab->s->line_max++;
176 if ((vl = calloc(1, sizeof(*vl))) == NULL)
177 return 0;
179 if (len != 0 && (vl->line = calloc(1, len+1)) == NULL) {
180 free(vl);
181 return 0;
184 vl->type = l->type;
185 if (len != 0)
186 memcpy(vl->line, buf, len);
187 vl->alt = l->alt;
189 if (TAILQ_EMPTY(&tab->s->head))
190 TAILQ_INSERT_HEAD(&tab->s->head, vl, lines);
191 else
192 TAILQ_INSERT_TAIL(&tab->s->head, vl, lines);
193 return 1;
196 static void
197 empty_vlist(struct tab *tab)
199 struct line *l, *t;
201 tab->s->line_max = 0;
203 TAILQ_FOREACH_SAFE(l, &tab->s->head, lines, t) {
204 TAILQ_REMOVE(&tab->s->head, l, lines);
205 free(l->line);
206 /* l->alt references the original line! */
207 free(l);
211 static void
212 restore_cursor(struct tab *tab)
214 wmove(body, tab->s->curs_y, tab->s->curs_x);
217 static void
218 cmd_previous_line(struct tab *tab)
220 if (--tab->s->curs_y < 0) {
221 tab->s->curs_y = 0;
222 cmd_scroll_up(tab);
225 restore_cursor(tab);
228 static void
229 cmd_next_line(struct tab *tab)
231 if (++tab->s->curs_y > body_lines-1) {
232 tab->s->curs_y = body_lines-1;
233 cmd_scroll_down(tab);
236 restore_cursor(tab);
239 static void
240 cmd_forward_char(struct tab *tab)
242 tab->s->curs_x = MIN(body_cols-1, tab->s->curs_x+1);
243 restore_cursor(tab);
246 static void
247 cmd_backward_char(struct tab *tab)
249 tab->s->curs_x = MAX(0, tab->s->curs_x-1);
250 restore_cursor(tab);
253 static void
254 cmd_redraw(struct tab *tab)
256 handle_resize(0, 0, NULL);
259 static void
260 cmd_scroll_up(struct tab *tab)
262 struct line *l;
264 if (tab->s->line_off == 0)
265 return;
267 l = nth_line(tab, --tab->s->line_off);
268 wscrl(body, -1);
269 wmove(body, 0, 0);
270 print_line(l);
273 static void
274 cmd_scroll_down(struct tab *tab)
276 struct line *l;
277 size_t n;
279 if (tab->s->line_max == 0 || tab->s->line_off == tab->s->line_max-1)
280 return;
282 tab->s->line_off++;
283 wscrl(body, 1);
285 if (tab->s->line_max - tab->s->line_off < body_lines)
286 return;
288 l = nth_line(tab, tab->s->line_off + body_lines-1);
289 wmove(body, body_lines-1, 0);
290 print_line(l);
293 static void
294 cmd_kill_telescope(struct tab *tab)
296 event_loopbreak();
299 static void
300 cmd_push_button(struct tab *tab)
302 struct line *l;
303 size_t nth;
305 nth = tab->s->line_off + tab->s->curs_y;
306 if (nth > tab->s->line_max)
307 return;
308 l = nth_line(tab, nth);
309 if (l->type != LINE_LINK)
310 return;
312 load_url_in_tab(tab, l->alt);
315 static void
316 cmd_unbound(struct key k)
318 message("%s%c is undefined",
319 k.meta ? "M-" : "",
320 k.key);
323 static struct line *
324 nth_line(struct tab *tab, size_t n)
326 struct line *l;
327 size_t i;
329 i = 0;
330 TAILQ_FOREACH(l, &tab->s->head, lines) {
331 if (i == n)
332 return l;
333 i++;
336 /* unreachable */
337 abort();
340 static struct tab *
341 current_tab(void)
343 struct tab *t;
345 TAILQ_FOREACH(t, &tabshead, tabs) {
346 if (t->flags & TAB_CURRENT)
347 return t;
350 /* unreachable */
351 abort();
354 static void
355 dispatch_stdio(int fd, short ev, void *d)
357 struct binding *b;
358 struct key key;
359 int k, j;
361 k = wgetch(body);
363 if (k == ERR)
364 return;
366 /* look for a M-key */
367 if (k == 27) {
368 wtimeout(body, 0); /* TODO: make escape-time customizable */
369 j = wgetch(body);
370 if (j != ERR) {
371 k = j;
372 key.meta = 1;
373 } else {
374 key.meta = 0;
376 } else
377 key.meta = 0;
379 key.key = k;
381 for (b = bindings; b->fn != NULL; ++b) {
382 if (key.meta == b->key.meta &&
383 key.key == b->key.key) {
384 b->fn(current_tab());
385 goto done;
389 cmd_unbound(key);
391 done:
392 restore_cursor(current_tab());
393 wrefresh(tabline);
394 wrefresh(modeline);
395 wrefresh(minibuf);
397 wrefresh(body);
400 static void
401 handle_clear_minibuf(int fd, short ev, void *d)
403 clminibufev_set = 0;
404 werase(minibuf);
405 wrefresh(minibuf);
406 wrefresh(body);
409 static void
410 handle_resize(int sig, short ev, void *d)
412 struct tab *tab;
414 endwin();
415 refresh();
416 clear();
418 /* move and resize the windows, in reverse order! */
420 mvwin(minibuf, LINES-1, 0);
421 wresize(minibuf, 1, COLS);
423 mvwin(modeline, LINES-2, 0);
424 wresize(modeline, 1, COLS);
426 wresize(body, LINES-3, COLS);
427 body_lines = LINES-3;
428 body_cols = COLS;
430 wresize(tabline, 1, COLS);
432 tab = current_tab();
434 wrap_page(tab);
435 redraw_tab(tab);
438 /*
439 * Helper function for wrap_text. Find the end of the current word
440 * and the end of the separator after the word.
441 */
442 static int
443 word_boundaries(const char *s, const char *sep, const char **endword, const char **endspc)
445 *endword = s;
446 *endword = s;
448 if (*s == '\0')
449 return 0;
451 /* find the end of the current world */
452 for (; *s != '\0'; ++s) {
453 if (strchr(sep, *s) != NULL)
454 break;
457 *endword = s;
459 /* find the end of the separator */
460 for (; *s != '\0'; ++s) {
461 if (strchr(sep, *s) == NULL)
462 break;
465 *endspc = s;
467 return 1;
470 static inline int
471 emitline(struct tab *tab, size_t zero, size_t *off, const struct line *l,
472 const char **line)
474 if (!push_line(tab, l, *line, *off - zero))
475 return 0;
476 *line += *off - zero;
477 *off = zero;
478 return 1;
481 static inline void
482 emitstr(const char **s, size_t len, size_t *off)
484 size_t i;
486 /* printw("%*s", ...) doesn't seem to respect the precision, so... */
487 for (i = 0; i < len; ++i)
488 addch((*s)[i]);
489 *off += len;
490 *s += len;
493 /*
494 * Build a list of visual line by wrapping the given line, assuming
495 * that when printed will have a leading prefix prfx.
497 * TODO: it considers each byte one cell on the screen!
498 */
499 static void
500 wrap_text(struct tab *tab, const char *prfx, struct line *l)
502 size_t zero, off, len, split;
503 const char *endword, *endspc, *line, *linestart;
505 zero = strlen(prfx);
506 off = zero;
507 line = l->line;
508 linestart = l->line;
510 while (word_boundaries(line, " \t-", &endword, &endspc)) {
511 len = endword - line;
512 if (off + len >= body_cols) {
513 emitline(tab, zero, &off, l, &linestart);
514 while (len >= body_cols) {
515 /* hard wrap */
516 emitline(tab, zero, &off, l, &linestart);
517 len -= body_cols-1;
518 line += body_cols-1;
521 if (len != 0)
522 off += len;
523 } else
524 off += len;
526 /* print the spaces iff not at bol */
527 len = endspc - endword;
528 /* line = endspc; */
529 if (off != zero) {
530 if (off + len >= body_cols) {
531 emitline(tab, zero, &off, l, &linestart);
532 linestart = endspc;
533 } else
534 off += len;
537 line = endspc;
540 emitline(tab, zero, &off, l, &linestart);
543 static int
544 hardwrap_text(struct tab *tab, struct line *l)
546 size_t off, len;
547 const char *linestart;
549 len = strlen(l->line);
550 off = 0;
551 linestart = l->line;
553 while (len >= COLS) {
554 len -= COLS-1;
555 off = COLS-1;
556 if (!emitline(tab, 0, &off, l, &linestart))
557 return 0;
560 if (len != 0)
561 return emitline(tab, 0, &len, l, &linestart);
563 return 1;
566 static int
567 wrap_page(struct tab *tab)
569 struct line *l;
571 empty_vlist(tab);
573 TAILQ_FOREACH(l, &tab->page.head, lines) {
574 switch (l->type) {
575 case LINE_TEXT:
576 wrap_text(tab, "", l);
577 break;
578 case LINE_LINK:
579 wrap_text(tab, "=> ", l);
580 break;
581 case LINE_TITLE_1:
582 wrap_text(tab, "# ", l);
583 break;
584 case LINE_TITLE_2:
585 wrap_text(tab, "## ", l);
586 break;
587 case LINE_TITLE_3:
588 wrap_text(tab, "### ", l);
589 break;
590 case LINE_ITEM:
591 wrap_text(tab, "* ", l);
592 break;
593 case LINE_QUOTE:
594 wrap_text(tab, "> ", l);
595 break;
596 case LINE_PRE_START:
597 case LINE_PRE_END:
598 push_line(tab, l, NULL, 0);
599 break;
600 case LINE_PRE_CONTENT:
601 hardwrap_text(tab, l);
602 break;
605 return 1;
608 static inline void
609 print_line(struct line *l)
611 const char *text = l->line;
613 if (text == NULL)
614 text = "";
616 switch (l->type) {
617 case LINE_TEXT:
618 wprintw(body, "%s", text);
619 break;
620 case LINE_LINK:
621 wattron(body, A_UNDERLINE);
622 wprintw(body, "=> %s", text);
623 wattroff(body, A_UNDERLINE);
624 return;
625 case LINE_TITLE_1:
626 wattron(body, A_BOLD);
627 wprintw(body, "# %s", text);
628 wattroff(body, A_BOLD);
629 return;
630 case LINE_TITLE_2:
631 wattron(body, A_BOLD);
632 wprintw(body, "## %s", text);
633 wattroff(body, A_BOLD);
634 return;
635 case LINE_TITLE_3:
636 wattron(body, A_BOLD);
637 wprintw(body, "### %s", text);
638 wattroff(body, A_BOLD);
639 return;
640 case LINE_ITEM:
641 wprintw(body, "* %s", text);
642 return;
643 case LINE_QUOTE:
644 wattron(body, A_DIM);
645 wprintw(body, "> %s", text);
646 wattroff(body, A_DIM);
647 return;
648 case LINE_PRE_START:
649 case LINE_PRE_END:
650 wprintw(body, "```");
651 return;
652 case LINE_PRE_CONTENT:
653 wprintw(body, "%s", text);
654 return;
658 static void
659 redraw_tabline(void)
661 wclear(tabline);
662 wbkgd(tabline, A_REVERSE);
663 mvwprintw(tabline, 0, 0, "TODO: tabs here");
666 static void
667 redraw_modeline(struct tab *tab)
669 int x, y, max_x, max_y;
670 const char *mode = "text/gemini-mode";
671 const char *spin = "-\\|/";
673 wclear(modeline);
674 wattron(modeline, A_REVERSE);
675 wmove(modeline, 0, 0);
677 wprintw(modeline, "-%c %s %s ",
678 spin[tab->s->loading_anim_step], mode, tab->urlstr);
679 getyx(modeline, y, x);
680 getmaxyx(modeline, max_y, max_x);
682 (void)y;
683 (void)max_y;
685 for (; x < max_x; ++x)
686 waddstr(modeline, "-");
689 static void
690 redraw_tab(struct tab *tab)
692 struct line *l;
693 int line;
695 werase(body);
697 tab->s->line_off = MIN(tab->s->line_max, tab->s->line_off);
698 if (TAILQ_EMPTY(&tab->s->head))
699 return;
701 line = 0;
702 l = nth_line(tab, tab->s->line_off);
703 for (; l != NULL; l = TAILQ_NEXT(l, lines)) {
704 wmove(body, line, 0);
705 print_line(l);
706 line++;
707 if (line == body_lines)
708 break;
711 redraw_tabline();
712 redraw_modeline(tab);
714 restore_cursor(tab);
715 wrefresh(tabline);
716 wrefresh(modeline);
717 wrefresh(minibuf);
719 wrefresh(body);
722 static void
723 message(const char *fmt, ...)
725 va_list ap;
727 va_start(ap, fmt);
729 if (clminibufev_set)
730 evtimer_del(&clminibufev);
731 evtimer_set(&clminibufev, handle_clear_minibuf, NULL);
732 evtimer_add(&clminibufev, &clminibufev_timer);
733 clminibufev_set = 1;
735 werase(minibuf);
736 vw_printw(minibuf, fmt, ap);
738 wrefresh(minibuf);
739 wrefresh(body);
741 va_end(ap);
744 static void
745 start_loading_anim(struct tab *tab)
747 if (tab->s->loading_anim)
748 return;
749 tab->s->loading_anim = 1;
750 evtimer_set(&tab->s->loadingev, update_loading_anim, tab);
751 evtimer_add(&tab->s->loadingev, &loadingev_timer);
754 static void
755 update_loading_anim(int fd, short ev, void *d)
757 struct tab *tab = d;
759 tab->s->loading_anim_step = (tab->s->loading_anim_step+1)%4;
761 redraw_modeline(tab);
762 wrefresh(modeline);
763 wrefresh(body);
765 evtimer_add(&tab->s->loadingev, &loadingev_timer);
768 static void
769 stop_loading_anim(struct tab *tab)
771 if (!tab->s->loading_anim)
772 return;
773 evtimer_del(&tab->s->loadingev);
774 tab->s->loading_anim = 0;
775 tab->s->loading_anim_step = 0;
777 redraw_modeline(tab);
778 wrefresh(modeline);
779 wrefresh(body);
782 static void
783 load_url_in_tab(struct tab *tab, const char *url)
785 empty_vlist(tab);
786 message("Loading %s...", url);
787 start_loading_anim(tab);
788 load_url(tab, url);
790 tab->s->curs_x = 0;
791 tab->s->curs_y = 0;
792 redraw_tab(tab);
795 static void
796 new_tab(void)
798 struct tab *tab, *t;
799 const char *url = "about:new";
801 if ((tab = calloc(1, sizeof(*tab))) == NULL)
802 goto err;
804 if ((tab->s = calloc(1, sizeof(*t->s))) == NULL)
805 goto err;
807 TAILQ_INIT(&tab->s->head);
808 TAILQ_FOREACH(t, &tabshead, tabs) {
809 t->flags &= ~TAB_CURRENT;
812 tab->id = tab_counter++;
813 tab->flags = TAB_CURRENT;
815 if (TAILQ_EMPTY(&tabshead))
816 TAILQ_INSERT_HEAD(&tabshead, tab, tabs);
817 else
818 TAILQ_INSERT_TAIL(&tabshead, tab, tabs);
820 load_url_in_tab(tab, url);
821 return;
823 err:
824 event_loopbreak();
827 int
828 ui_init(void)
830 setlocale(LC_ALL, "");
832 initscr();
833 raw();
834 noecho();
836 nonl();
837 intrflush(stdscr, FALSE);
839 if ((tabline = newwin(1, COLS, 0, 0)) == NULL)
840 return 0;
841 if ((body = newwin(LINES - 3, COLS, 1, 0)) == NULL)
842 return 0;
843 if ((modeline = newwin(1, COLS, LINES-2, 0)) == NULL)
844 return 0;
845 if ((minibuf = newwin(1, COLS, LINES-1, 0)) == NULL)
846 return 0;
848 body_lines = LINES-3;
849 body_cols = COLS;
851 keypad(body, TRUE);
852 scrollok(body, TRUE);
854 /* non-blocking input */
855 wtimeout(body, 0);
857 mvwprintw(body, 0, 0, "");
859 event_set(&stdioev, 0, EV_READ | EV_PERSIST, dispatch_stdio, NULL);
860 event_add(&stdioev, NULL);
862 signal_set(&winchev, SIGWINCH, handle_resize, NULL);
863 signal_add(&winchev, NULL);
865 new_tab();
867 return 1;
870 void
871 ui_on_tab_loaded(struct tab *tab)
873 stop_loading_anim(tab);
874 message("Loaded %s", tab->urlstr);
877 void
878 ui_on_tab_refresh(struct tab *tab)
880 if (!(tab->flags & TAB_CURRENT))
881 return;
883 wrap_page(tab);
884 redraw_tab(tab);
887 void
888 ui_end(void)
890 endwin();