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 new_tab(void);
110 typedef void (*interactivefn)(struct tab*);
112 static WINDOW *tabline, *body, *modeline, *minibuf;
113 static int body_lines, body_cols;
115 static struct event clminibufev;
116 static int clminibufev_set;
117 static struct timeval clminibufev_timer = { 5, 0 };
118 static struct timeval loadingev_timer = { 0, 250000 };
120 static uint32_t tab_counter;
122 struct ui_state {
123 int curs_x;
124 int curs_y;
125 size_t line_off;
126 size_t line_max;
128 short loading_anim;
129 short loading_anim_step;
130 struct event loadingev;
132 TAILQ_HEAD(, line) head;
133 };
135 struct key {
136 int meta;
137 int key;
138 };
140 #define KEY(n) ((struct key){0, n})
141 #define CKEY(n) ((struct key){0, (n) & 0x1F})
142 #define MKEY(n) ((struct key){1, n})
143 #define CMKEY(n) ((struct key){1, (n) & 0x1F})
145 struct binding {
146 struct key key;
147 interactivefn fn;
148 } bindings[] = {
149 { CKEY('p'), cmd_previous_line, },
150 { CKEY('n'), cmd_next_line, },
151 { CKEY('f'), cmd_forward_char, },
152 { CKEY('b'), cmd_backward_char, },
154 { CKEY('L'), cmd_redraw, },
156 { KEY('J'), cmd_scroll_down, },
157 { KEY('K'), cmd_scroll_up, },
159 { KEY('q'), cmd_kill_telescope, },
160 { CKEY('m'), cmd_push_button, },
162 { {0, 0}, NULL, },
163 };
165 static int
166 push_line(struct tab *tab, const struct line *l, const char *buf, size_t len)
168 struct line *vl;
170 tab->s->line_max++;
172 if ((vl = calloc(1, sizeof(*vl))) == NULL)
173 return 0;
175 if (len != 0 && (vl->line = calloc(1, len+1)) == NULL) {
176 free(vl);
177 return 0;
180 vl->type = l->type;
181 if (len != 0)
182 memcpy(vl->line, buf, len);
183 vl->alt = l->alt;
185 if (TAILQ_EMPTY(&tab->s->head))
186 TAILQ_INSERT_HEAD(&tab->s->head, vl, lines);
187 else
188 TAILQ_INSERT_TAIL(&tab->s->head, vl, lines);
189 return 1;
192 static void
193 empty_vlist(struct tab *tab)
195 struct line *l, *t;
197 tab->s->line_max = 0;
199 TAILQ_FOREACH_SAFE(l, &tab->s->head, lines, t) {
200 TAILQ_REMOVE(&tab->s->head, l, lines);
201 free(l->line);
202 /* l->alt references the original line! */
203 free(l);
207 static void
208 restore_cursor(struct tab *tab)
210 wmove(body, tab->s->curs_y, tab->s->curs_x);
213 static void
214 cmd_previous_line(struct tab *tab)
216 if (--tab->s->curs_y < 0) {
217 tab->s->curs_y = 0;
218 cmd_scroll_up(tab);
221 restore_cursor(tab);
224 static void
225 cmd_next_line(struct tab *tab)
227 if (++tab->s->curs_y > body_lines-1) {
228 tab->s->curs_y = body_lines-1;
229 cmd_scroll_down(tab);
232 restore_cursor(tab);
235 static void
236 cmd_forward_char(struct tab *tab)
238 tab->s->curs_x = MIN(body_cols-1, tab->s->curs_x+1);
239 restore_cursor(tab);
242 static void
243 cmd_backward_char(struct tab *tab)
245 tab->s->curs_x = MAX(0, tab->s->curs_x-1);
246 restore_cursor(tab);
249 static void
250 cmd_redraw(struct tab *tab)
252 handle_resize(0, 0, NULL);
255 static void
256 cmd_scroll_up(struct tab *tab)
258 struct line *l;
260 if (tab->s->line_off == 0)
261 return;
263 l = nth_line(tab, --tab->s->line_off);
264 wscrl(body, -1);
265 wmove(body, 0, 0);
266 print_line(l);
269 static void
270 cmd_scroll_down(struct tab *tab)
272 struct line *l;
273 size_t n;
275 if (tab->s->line_max == 0 || tab->s->line_off == tab->s->line_max-1)
276 return;
278 tab->s->line_off++;
279 wscrl(body, 1);
281 if (tab->s->line_max - tab->s->line_off < body_lines)
282 return;
284 l = nth_line(tab, tab->s->line_off + body_lines-1);
285 wmove(body, body_lines-1, 0);
286 print_line(l);
289 static void
290 cmd_kill_telescope(struct tab *tab)
292 event_loopbreak();
295 static void
296 cmd_push_button(struct tab *tab)
298 struct line *l;
299 size_t nth;
301 nth = tab->s->line_off + tab->s->curs_y;
302 if (nth > tab->s->line_max)
303 return;
304 l = nth_line(tab, nth);
305 message("Enter on line: \"%s\"", l->line ? l->line : "");
308 static void
309 cmd_unbound(struct key k)
311 message("%s%c is undefined",
312 k.meta ? "M-" : "",
313 k.key);
316 static struct line *
317 nth_line(struct tab *tab, size_t n)
319 struct line *l;
320 size_t i;
322 i = 0;
323 TAILQ_FOREACH(l, &tab->s->head, lines) {
324 if (i == n)
325 return l;
326 i++;
329 /* unreachable */
330 abort();
333 static struct tab *
334 current_tab(void)
336 struct tab *t;
338 TAILQ_FOREACH(t, &tabshead, tabs) {
339 if (t->flags & TAB_CURRENT)
340 return t;
343 /* unreachable */
344 abort();
347 static void
348 dispatch_stdio(int fd, short ev, void *d)
350 struct binding *b;
351 struct key key;
352 int k, j;
354 k = wgetch(body);
356 if (k == ERR)
357 return;
359 /* look for a M-key */
360 if (k == 27) {
361 wtimeout(body, 0); /* TODO: make escape-time customizable */
362 j = wgetch(body);
363 if (j != ERR) {
364 k = j;
365 key.meta = 1;
366 } else {
367 key.meta = 0;
369 } else
370 key.meta = 0;
372 key.key = k;
374 for (b = bindings; b->fn != NULL; ++b) {
375 if (key.meta == b->key.meta &&
376 key.key == b->key.key) {
377 b->fn(current_tab());
378 goto done;
382 cmd_unbound(key);
384 done:
385 restore_cursor(current_tab());
386 wrefresh(tabline);
387 wrefresh(modeline);
388 wrefresh(minibuf);
390 wrefresh(body);
393 static void
394 handle_clear_minibuf(int fd, short ev, void *d)
396 clminibufev_set = 0;
397 werase(minibuf);
398 wrefresh(minibuf);
399 wrefresh(body);
402 static void
403 handle_resize(int sig, short ev, void *d)
405 struct tab *tab;
407 endwin();
408 refresh();
409 clear();
411 /* move and resize the windows, in reverse order! */
413 mvwin(minibuf, LINES-1, 0);
414 wresize(minibuf, 1, COLS);
416 mvwin(modeline, LINES-2, 0);
417 wresize(modeline, 1, COLS);
419 wresize(body, LINES-3, COLS);
420 body_lines = LINES-3;
421 body_cols = COLS;
423 wresize(tabline, 1, COLS);
425 tab = current_tab();
427 wrap_page(tab);
428 redraw_tab(tab);
431 /*
432 * Helper function for wrap_text. Find the end of the current word
433 * and the end of the separator after the word.
434 */
435 static int
436 word_boundaries(const char *s, const char *sep, const char **endword, const char **endspc)
438 *endword = s;
439 *endword = s;
441 if (*s == '\0')
442 return 0;
444 /* find the end of the current world */
445 for (; *s != '\0'; ++s) {
446 if (strchr(sep, *s) != NULL)
447 break;
450 *endword = s;
452 /* find the end of the separator */
453 for (; *s != '\0'; ++s) {
454 if (strchr(sep, *s) == NULL)
455 break;
458 *endspc = s;
460 return 1;
463 static inline int
464 emitline(struct tab *tab, size_t zero, size_t *off, const struct line *l,
465 const char **line)
467 if (!push_line(tab, l, *line, *off - zero))
468 return 0;
469 *line += *off - zero;
470 *off = zero;
471 return 1;
474 static inline void
475 emitstr(const char **s, size_t len, size_t *off)
477 size_t i;
479 /* printw("%*s", ...) doesn't seem to respect the precision, so... */
480 for (i = 0; i < len; ++i)
481 addch((*s)[i]);
482 *off += len;
483 *s += len;
486 /*
487 * Build a list of visual line by wrapping the given line, assuming
488 * that when printed will have a leading prefix prfx.
490 * TODO: it considers each byte one cell on the screen!
491 */
492 static void
493 wrap_text(struct tab *tab, const char *prfx, struct line *l)
495 size_t zero, off, len, split;
496 const char *endword, *endspc, *line, *linestart;
498 zero = strlen(prfx);
499 off = zero;
500 line = l->line;
501 linestart = l->line;
503 while (word_boundaries(line, " \t-", &endword, &endspc)) {
504 len = endword - line;
505 if (off + len >= body_cols) {
506 emitline(tab, zero, &off, l, &linestart);
507 while (len >= body_cols) {
508 /* hard wrap */
509 emitline(tab, zero, &off, l, &linestart);
510 len -= body_cols-1;
511 line += body_cols-1;
514 if (len != 0)
515 off += len;
516 } else
517 off += len;
519 /* print the spaces iff not at bol */
520 len = endspc - endword;
521 /* line = endspc; */
522 if (off != zero) {
523 if (off + len >= body_cols) {
524 emitline(tab, zero, &off, l, &linestart);
525 linestart = endspc;
526 } else
527 off += len;
530 line = endspc;
533 emitline(tab, zero, &off, l, &linestart);
536 static int
537 hardwrap_text(struct tab *tab, struct line *l)
539 size_t off, len;
540 const char *linestart;
542 len = strlen(l->line);
543 off = 0;
544 linestart = l->line;
546 while (len >= COLS) {
547 len -= COLS-1;
548 off = COLS-1;
549 if (!emitline(tab, 0, &off, l, &linestart))
550 return 0;
553 if (len != 0)
554 return emitline(tab, 0, &len, l, &linestart);
556 return 1;
559 static int
560 wrap_page(struct tab *tab)
562 struct line *l;
564 empty_vlist(tab);
566 TAILQ_FOREACH(l, &tab->page.head, lines) {
567 switch (l->type) {
568 case LINE_TEXT:
569 wrap_text(tab, "", l);
570 break;
571 case LINE_LINK:
572 wrap_text(tab, "=> ", l);
573 break;
574 case LINE_TITLE_1:
575 wrap_text(tab, "# ", l);
576 break;
577 case LINE_TITLE_2:
578 wrap_text(tab, "## ", l);
579 break;
580 case LINE_TITLE_3:
581 wrap_text(tab, "### ", l);
582 break;
583 case LINE_ITEM:
584 wrap_text(tab, "* ", l);
585 break;
586 case LINE_QUOTE:
587 wrap_text(tab, "> ", l);
588 break;
589 case LINE_PRE_START:
590 case LINE_PRE_END:
591 push_line(tab, l, NULL, 0);
592 break;
593 case LINE_PRE_CONTENT:
594 hardwrap_text(tab, l);
595 break;
598 return 1;
601 static inline void
602 print_line(struct line *l)
604 const char *text = l->line;
606 if (text == NULL)
607 text = "";
609 switch (l->type) {
610 case LINE_TEXT:
611 wprintw(body, "%s", text);
612 break;
613 case LINE_LINK:
614 wattron(body, A_UNDERLINE);
615 wprintw(body, "=> %s", text);
616 wattroff(body, A_UNDERLINE);
617 return;
618 case LINE_TITLE_1:
619 wattron(body, A_BOLD);
620 wprintw(body, "# %s", text);
621 wattroff(body, A_BOLD);
622 return;
623 case LINE_TITLE_2:
624 wattron(body, A_BOLD);
625 wprintw(body, "## %s", text);
626 wattroff(body, A_BOLD);
627 return;
628 case LINE_TITLE_3:
629 wattron(body, A_BOLD);
630 wprintw(body, "### %s", text);
631 wattroff(body, A_BOLD);
632 return;
633 case LINE_ITEM:
634 wprintw(body, "* %s", text);
635 return;
636 case LINE_QUOTE:
637 wattron(body, A_DIM);
638 wprintw(body, "> %s", text);
639 wattroff(body, A_DIM);
640 return;
641 case LINE_PRE_START:
642 case LINE_PRE_END:
643 wprintw(body, "```");
644 return;
645 case LINE_PRE_CONTENT:
646 wprintw(body, "%s", text);
647 return;
651 static void
652 redraw_tabline(void)
654 wclear(tabline);
655 wbkgd(tabline, A_REVERSE);
656 mvwprintw(tabline, 0, 0, "TODO: tabs here");
659 static void
660 redraw_modeline(struct tab *tab)
662 int x, y, max_x, max_y;
663 const char *mode = "text/gemini-mode";
664 const char *spin = "-\\|/";
666 wclear(modeline);
667 wattron(modeline, A_REVERSE);
668 wmove(modeline, 0, 0);
670 wprintw(modeline, "-%c %s %s ",
671 spin[tab->s->loading_anim_step], mode, tab->url);
672 getyx(modeline, y, x);
673 getmaxyx(modeline, max_y, max_x);
675 (void)y;
676 (void)max_y;
678 for (; x < max_x; ++x)
679 waddstr(modeline, "-");
682 static void
683 redraw_tab(struct tab *tab)
685 struct line *l;
686 int line;
688 werase(body);
690 tab->s->line_off = MIN(tab->s->line_max, tab->s->line_off);
691 if (TAILQ_EMPTY(&tab->s->head))
692 return;
694 line = 0;
695 l = nth_line(tab, tab->s->line_off);
696 for (; l != NULL; l = TAILQ_NEXT(l, lines)) {
697 wmove(body, line, 0);
698 print_line(l);
699 line++;
700 if (line == body_lines)
701 break;
704 redraw_tabline();
705 redraw_modeline(tab);
707 restore_cursor(tab);
708 wrefresh(tabline);
709 wrefresh(modeline);
710 wrefresh(minibuf);
712 wrefresh(body);
715 static void
716 message(const char *fmt, ...)
718 va_list ap;
720 va_start(ap, fmt);
722 if (clminibufev_set)
723 evtimer_del(&clminibufev);
724 evtimer_set(&clminibufev, handle_clear_minibuf, NULL);
725 evtimer_add(&clminibufev, &clminibufev_timer);
726 clminibufev_set = 1;
728 werase(minibuf);
729 vw_printw(minibuf, fmt, ap);
731 wrefresh(minibuf);
732 wrefresh(body);
734 va_end(ap);
737 static void
738 start_loading_anim(struct tab *tab)
740 if (tab->s->loading_anim)
741 return;
742 tab->s->loading_anim = 1;
743 evtimer_set(&tab->s->loadingev, update_loading_anim, tab);
744 evtimer_add(&tab->s->loadingev, &loadingev_timer);
747 static void
748 update_loading_anim(int fd, short ev, void *d)
750 struct tab *tab = d;
752 tab->s->loading_anim_step = (tab->s->loading_anim_step+1)%4;
754 redraw_modeline(tab);
755 wrefresh(modeline);
756 wrefresh(body);
758 evtimer_add(&tab->s->loadingev, &loadingev_timer);
761 static void
762 stop_loading_anim(struct tab *tab)
764 if (!tab->s->loading_anim)
765 return;
766 evtimer_del(&tab->s->loadingev);
767 tab->s->loading_anim = 0;
768 tab->s->loading_anim_step = 0;
771 static void
772 ui_load_url_in_tab(struct tab *tab, const char *url)
774 message("Loading %s...", url);
775 start_loading_anim(tab);
776 load_url(tab, url);
779 static void
780 new_tab(void)
782 struct tab *tab, *t;
783 const char *url = "about:new";
785 if ((tab = calloc(1, sizeof(*tab))) == NULL)
786 goto err;
788 if ((tab->s = calloc(1, sizeof(*t->s))) == NULL)
789 goto err;
791 TAILQ_INIT(&tab->s->head);
792 TAILQ_FOREACH(t, &tabshead, tabs) {
793 t->flags &= ~TAB_CURRENT;
796 tab->id = tab_counter++;
797 tab->flags = TAB_CURRENT;
799 if (TAILQ_EMPTY(&tabshead))
800 TAILQ_INSERT_HEAD(&tabshead, tab, tabs);
801 else
802 TAILQ_INSERT_TAIL(&tabshead, tab, tabs);
804 ui_load_url_in_tab(tab, url);
805 return;
807 err:
808 event_loopbreak();
811 int
812 ui_init(void)
814 setlocale(LC_ALL, "");
816 initscr();
817 raw();
818 noecho();
820 nonl();
821 intrflush(stdscr, FALSE);
822 keypad(stdscr, TRUE);
824 if ((tabline = newwin(1, COLS, 0, 0)) == NULL)
825 return 0;
826 if ((body = newwin(LINES - 3, COLS, 1, 0)) == NULL)
827 return 0;
828 if ((modeline = newwin(1, COLS, LINES-2, 0)) == NULL)
829 return 0;
830 if ((minibuf = newwin(1, COLS, LINES-1, 0)) == NULL)
831 return 0;
833 body_lines = LINES-3;
834 body_cols = COLS;
836 scrollok(body, TRUE);
838 /* non-blocking input */
839 wtimeout(body, 0);
841 mvwprintw(body, 0, 0, "");
843 event_set(&stdioev, 0, EV_READ | EV_PERSIST, dispatch_stdio, NULL);
844 event_add(&stdioev, NULL);
846 signal_set(&winchev, SIGWINCH, handle_resize, NULL);
847 signal_add(&winchev, NULL);
849 new_tab();
851 return 1;
854 void
855 ui_on_tab_loaded(struct tab *tab)
857 stop_loading_anim(tab);
858 message("Loaded %s", tab->url);
861 void
862 ui_on_tab_refresh(struct tab *tab)
864 if (!(tab->flags & TAB_CURRENT))
865 return;
867 wrap_page(tab);
868 redraw_tab(tab);
871 void
872 ui_end(void)
874 endwin();