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(int);
82 static void cmd_next_line(int);
83 static void cmd_forward_char(int);
84 static void cmd_backward_char(int);
85 static void cmd_redraw(int);
86 static void cmd_scroll_down(int);
87 static void cmd_scroll_up(int);
88 static void cmd_kill_telescope(int);
89 static void cmd_push_button(int);
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_tab(struct tab*);
102 static void message(const char*, ...) __attribute__((format(printf, 1, 2)));
103 static void new_tab(void);
105 typedef void (*interactivefn)(int);
107 static WINDOW *tabline, *body, *modeline, *minibuf;
108 static int body_lines, body_cols;
110 static struct event clminibufev;
111 static int clminibufev_set;
112 static struct timeval clminibufev_timer = { 5, 0 };
114 static uint32_t tab_counter;
116 struct ui_state {
117 int curs_x;
118 int curs_y;
119 size_t line_off;
120 size_t line_max;
122 TAILQ_HEAD(, line) head;
123 };
125 struct key {
126 #define CTRLFLG 0x1
127 #define METAFLG 0x2
128 int flags;
129 int key;
130 };
132 #define KEY(n) ((struct key){0, n})
133 #define CKEY(n) ((struct key){0, (n) & 0x1F})
134 #define MKEY(n) ((struct key){METAFLG, n})
135 #define CMKEY(n) ((struct key){METAFLG, (n) & 0x1F})
137 struct binding {
138 struct key key;
139 interactivefn fn;
140 } bindings[] = {
141 { CKEY('p'), cmd_previous_line, },
142 { CKEY('n'), cmd_next_line, },
143 { CKEY('f'), cmd_forward_char, },
144 { CKEY('b'), cmd_backward_char, },
146 { CKEY('L'), cmd_redraw, },
148 { KEY('J'), cmd_scroll_down, },
149 { KEY('K'), cmd_scroll_up, },
151 { KEY('q'), cmd_kill_telescope, },
152 { CKEY('m'), cmd_push_button, },
154 { {0, 0}, NULL, },
155 };
157 static int
158 push_line(struct tab *tab, const struct line *l, const char *buf, size_t len)
160 struct line *vl;
162 tab->s->line_max++;
164 if ((vl = calloc(1, sizeof(*vl))) == NULL)
165 return 0;
167 if (len != 0 && (vl->line = calloc(1, len+1)) == NULL) {
168 free(vl);
169 return 0;
172 vl->type = l->type;
173 if (len != 0)
174 memcpy(vl->line, buf, len);
175 vl->alt = l->alt;
177 if (TAILQ_EMPTY(&tab->s->head))
178 TAILQ_INSERT_HEAD(&tab->s->head, vl, lines);
179 else
180 TAILQ_INSERT_TAIL(&tab->s->head, vl, lines);
181 return 1;
184 static void
185 empty_vlist(struct tab *tab)
187 struct line *l, *t;
189 tab->s->line_max = 0;
191 TAILQ_FOREACH_SAFE(l, &tab->s->head, lines, t) {
192 TAILQ_REMOVE(&tab->s->head, l, lines);
193 free(l->line);
194 /* l->alt references the original line! */
195 free(l);
199 static void
200 restore_cursor(struct tab *tab)
202 wmove(body, tab->s->curs_y, tab->s->curs_x);
205 static void
206 cmd_previous_line(int k)
208 struct tab *tab;
210 tab = current_tab();
212 if (--tab->s->curs_y < 0) {
213 tab->s->curs_y = 0;
214 cmd_scroll_up(k);
217 restore_cursor(tab);
220 static void
221 cmd_next_line(int k)
223 struct tab *tab;
225 tab = current_tab();
227 if (++tab->s->curs_y > body_lines-1) {
228 tab->s->curs_y = body_lines-1;
229 cmd_scroll_down(k);
232 restore_cursor(tab);
235 static void
236 cmd_forward_char(int k)
238 struct tab *tab;
240 tab = current_tab();
241 tab->s->curs_x = MIN(body_cols-1, tab->s->curs_x+1);
242 restore_cursor(tab);
245 static void
246 cmd_backward_char(int k)
248 struct tab *tab;
250 tab = current_tab();
251 tab->s->curs_x = MAX(0, tab->s->curs_x-1);
252 restore_cursor(tab);
255 static void
256 cmd_redraw(int k)
258 handle_resize(0, 0, NULL);
261 static void
262 cmd_scroll_up(int k)
264 struct tab *tab;
265 struct line *l;
267 tab = current_tab();
268 if (tab->s->line_off == 0)
269 return;
271 l = nth_line(tab, --tab->s->line_off);
272 wscrl(body, -1);
273 wmove(body, 0, 0);
274 print_line(l);
277 static void
278 cmd_scroll_down(int k)
280 struct tab *tab;
281 struct line *l;
282 size_t n;
284 tab = current_tab();
286 if (tab->s->line_max == 0 || tab->s->line_off == tab->s->line_max-1)
287 return;
289 tab->s->line_off++;
290 wscrl(body, 1);
292 if (tab->s->line_max - tab->s->line_off < body_lines)
293 return;
295 l = nth_line(tab, tab->s->line_off + body_lines-1);
296 wmove(body, body_lines-1, 0);
297 print_line(l);
300 static void
301 cmd_kill_telescope(int k)
303 event_loopbreak();
306 static void
307 cmd_push_button(int k)
309 struct tab *tab;
310 struct line *l;
311 size_t nth;
313 tab = current_tab();
315 nth = tab->s->line_off + tab->s->curs_y;
316 if (nth > tab->s->line_max)
317 return;
318 l = nth_line(tab, nth);
319 message("Enter on line: \"%s\"", l->line ? l->line : "");
322 static void
323 cmd_unbound(struct key k)
325 message("%s%c is undefined",
326 (k.flags & METAFLG) ? "M-" : "",
327 k.key);
330 static struct line *
331 nth_line(struct tab *tab, size_t n)
333 struct line *l;
334 size_t i;
336 i = 0;
337 TAILQ_FOREACH(l, &tab->s->head, lines) {
338 if (i == n)
339 return l;
340 i++;
343 /* unreachable */
344 abort();
347 static struct tab *
348 current_tab(void)
350 struct tab *t;
352 TAILQ_FOREACH(t, &tabshead, tabs) {
353 if (t->flags & TAB_CURRENT)
354 return t;
357 /* unreachable */
358 abort();
361 static void
362 dispatch_stdio(int fd, short ev, void *d)
364 struct binding *b;
365 struct key key;
366 int k, j;
368 key.flags = 0;
370 k = wgetch(body);
372 if (k == ERR)
373 return;
375 /* look for a M-key */
376 if (k == 27) {
377 wtimeout(body, 0); /* TODO: make escape-time customizable */
378 j = wgetch(body);
379 if (j != ERR) {
380 k = j;
381 key.flags = METAFLG;
385 key.key = k;
387 for (b = bindings; b->fn != NULL; ++b) {
388 if (key.flags == b->key.flags &&
389 key.key == b->key.key) {
390 b->fn(k);
391 goto done;
395 cmd_unbound(key);
397 done:
398 restore_cursor(current_tab());
399 wrefresh(tabline);
400 wrefresh(modeline);
401 wrefresh(minibuf);
403 wrefresh(body);
406 static void
407 handle_clear_minibuf(int fd, short ev, void *d)
409 clminibufev_set = 0;
410 werase(minibuf);
411 wrefresh(minibuf);
412 wrefresh(body);
415 static void
416 handle_resize(int sig, short ev, void *d)
418 struct tab *tab;
420 endwin();
421 refresh();
422 clear();
424 /* move and resize the windows, in reverse order! */
426 mvwin(minibuf, LINES-1, 0);
427 wresize(minibuf, 1, COLS);
429 mvwin(modeline, LINES-2, 0);
430 wresize(modeline, 1, COLS);
432 wresize(body, LINES-3, COLS);
433 body_lines = LINES-3;
434 body_cols = COLS;
436 wresize(tabline, 1, COLS);
438 tab = current_tab();
440 wrap_page(tab);
441 redraw_tab(tab);
444 /*
445 * Helper function for wrap_text. Find the end of the current word
446 * and the end of the separator after the word.
447 */
448 static int
449 word_boundaries(const char *s, const char *sep, const char **endword, const char **endspc)
451 *endword = s;
452 *endword = s;
454 if (*s == '\0')
455 return 0;
457 /* find the end of the current world */
458 for (; *s != '\0'; ++s) {
459 if (strchr(sep, *s) != NULL)
460 break;
463 *endword = s;
465 /* find the end of the separator */
466 for (; *s != '\0'; ++s) {
467 if (strchr(sep, *s) == NULL)
468 break;
471 *endspc = s;
473 return 1;
476 static inline int
477 emitline(struct tab *tab, size_t zero, size_t *off, const struct line *l,
478 const char **line)
480 if (!push_line(tab, l, *line, *off - zero))
481 return 0;
482 *line += *off - zero;
483 *off = zero;
484 return 1;
487 static inline void
488 emitstr(const char **s, size_t len, size_t *off)
490 size_t i;
492 /* printw("%*s", ...) doesn't seem to respect the precision, so... */
493 for (i = 0; i < len; ++i)
494 addch((*s)[i]);
495 *off += len;
496 *s += len;
499 /*
500 * Build a list of visual line by wrapping the given line, assuming
501 * that when printed will have a leading prefix prfx.
503 * TODO: it considers each byte one cell on the screen!
504 */
505 static void
506 wrap_text(struct tab *tab, const char *prfx, struct line *l)
508 size_t zero, off, len, split;
509 const char *endword, *endspc, *line, *linestart;
511 zero = strlen(prfx);
512 off = zero;
513 line = l->line;
514 linestart = l->line;
516 while (word_boundaries(line, " \t-", &endword, &endspc)) {
517 len = endword - line;
518 if (off + len >= body_cols) {
519 emitline(tab, zero, &off, l, &linestart);
520 while (len >= body_cols) {
521 /* hard wrap */
522 emitline(tab, zero, &off, l, &linestart);
523 len -= body_cols-1;
524 line += body_cols-1;
527 if (len != 0)
528 off += len;
529 } else
530 off += len;
532 /* print the spaces iff not at bol */
533 len = endspc - endword;
534 /* line = endspc; */
535 if (off != zero) {
536 if (off + len >= body_cols) {
537 emitline(tab, zero, &off, l, &linestart);
538 linestart = endspc;
539 } else
540 off += len;
543 line = endspc;
546 emitline(tab, zero, &off, l, &linestart);
549 static int
550 hardwrap_text(struct tab *tab, struct line *l)
552 size_t off, len;
553 const char *linestart;
555 len = strlen(l->line);
556 off = 0;
557 linestart = l->line;
559 while (len >= COLS) {
560 len -= COLS-1;
561 off = COLS-1;
562 if (!emitline(tab, 0, &off, l, &linestart))
563 return 0;
566 if (len != 0)
567 return emitline(tab, 0, &len, l, &linestart);
569 return 1;
572 static int
573 wrap_page(struct tab *tab)
575 struct line *l;
577 empty_vlist(tab);
579 TAILQ_FOREACH(l, &tab->page.head, lines) {
580 switch (l->type) {
581 case LINE_TEXT:
582 wrap_text(tab, "", l);
583 break;
584 case LINE_LINK:
585 wrap_text(tab, "=> ", l);
586 break;
587 case LINE_TITLE_1:
588 wrap_text(tab, "# ", l);
589 break;
590 case LINE_TITLE_2:
591 wrap_text(tab, "## ", l);
592 break;
593 case LINE_TITLE_3:
594 wrap_text(tab, "### ", l);
595 break;
596 case LINE_ITEM:
597 wrap_text(tab, "* ", l);
598 break;
599 case LINE_QUOTE:
600 wrap_text(tab, "> ", l);
601 break;
602 case LINE_PRE_START:
603 case LINE_PRE_END:
604 push_line(tab, l, NULL, 0);
605 break;
606 case LINE_PRE_CONTENT:
607 hardwrap_text(tab, l);
608 break;
611 return 1;
614 static inline void
615 print_line(struct line *l)
617 const char *text = l->line;
619 if (text == NULL)
620 text = "";
622 switch (l->type) {
623 case LINE_TEXT:
624 wprintw(body, "%s", text);
625 break;
626 case LINE_LINK:
627 wattron(body, A_UNDERLINE);
628 wprintw(body, "=> %s", text);
629 wattroff(body, A_UNDERLINE);
630 return;
631 case LINE_TITLE_1:
632 wattron(body, A_BOLD);
633 wprintw(body, "# %s", text);
634 wattroff(body, A_BOLD);
635 return;
636 case LINE_TITLE_2:
637 wattron(body, A_BOLD);
638 wprintw(body, "## %s", text);
639 wattroff(body, A_BOLD);
640 return;
641 case LINE_TITLE_3:
642 wattron(body, A_BOLD);
643 wprintw(body, "### %s", text);
644 wattroff(body, A_BOLD);
645 return;
646 case LINE_ITEM:
647 wprintw(body, "* %s", text);
648 return;
649 case LINE_QUOTE:
650 wattron(body, A_DIM);
651 wprintw(body, "> %s", text);
652 wattroff(body, A_DIM);
653 return;
654 case LINE_PRE_START:
655 case LINE_PRE_END:
656 wprintw(body, "```");
657 return;
658 case LINE_PRE_CONTENT:
659 wprintw(body, "%s", text);
660 return;
664 static void
665 redraw_modeline(struct tab *tab)
667 int x, y, max_x, max_y;
668 const char *url = "TODO:url";
669 const char *mode = "text/gemini-mode";
671 wclear(modeline);
672 wattron(modeline, A_REVERSE);
673 wmove(modeline, 0, 0);
675 wprintw(modeline, "-- %s %s ", mode, url);
676 getyx(modeline, y, x);
677 getmaxyx(modeline, max_y, max_x);
679 (void)y;
680 (void)max_y;
682 for (; x < max_x; ++x)
683 waddstr(modeline, "-");
686 static void
687 redraw_tab(struct tab *tab)
689 struct line *l;
690 int line;
692 werase(body);
694 tab->s->line_off = MIN(tab->s->line_max, tab->s->line_off);
695 if (TAILQ_EMPTY(&tab->s->head))
696 return;
698 line = 0;
699 l = nth_line(tab, tab->s->line_off);
700 for (; l != NULL; l = TAILQ_NEXT(l, lines)) {
701 wmove(body, line, 0);
702 print_line(l);
703 line++;
704 if (line == body_lines)
705 break;
708 redraw_modeline(tab);
710 restore_cursor(tab);
711 wrefresh(tabline);
712 wrefresh(modeline);
713 wrefresh(minibuf);
715 wrefresh(body);
718 static void
719 message(const char *fmt, ...)
721 va_list ap;
723 va_start(ap, fmt);
725 if (clminibufev_set)
726 evtimer_del(&clminibufev);
727 evtimer_set(&clminibufev, handle_clear_minibuf, NULL);
728 evtimer_add(&clminibufev, &clminibufev_timer);
729 clminibufev_set = 1;
731 werase(minibuf);
732 vw_printw(minibuf, fmt, ap);
734 wrefresh(minibuf);
735 wrefresh(body);
737 va_end(ap);
740 static void
741 new_tab(void)
743 struct tab *tab, *t;
744 const char *url = "about:new";
746 if ((tab = calloc(1, sizeof(*tab))) == NULL)
747 goto err;
749 if ((tab->s = calloc(1, sizeof(*t->s))) == NULL)
750 goto err;
752 TAILQ_INIT(&tab->s->head);
753 TAILQ_FOREACH(t, &tabshead, tabs) {
754 t->flags &= ~TAB_CURRENT;
757 tab->id = tab_counter++;
758 tab->flags = TAB_CURRENT;
760 if (TAILQ_EMPTY(&tabshead))
761 TAILQ_INSERT_HEAD(&tabshead, tab, tabs);
762 else
763 TAILQ_INSERT_TAIL(&tabshead, tab, tabs);
765 load_url(tab, url);
766 return;
768 err:
769 event_loopbreak();
772 int
773 ui_init(void)
775 setlocale(LC_ALL, "");
777 initscr();
778 raw();
779 noecho();
781 nonl();
782 intrflush(stdscr, FALSE);
783 keypad(stdscr, TRUE);
785 if ((tabline = newwin(1, COLS, 0, 0)) == NULL)
786 return 0;
787 if ((body = newwin(LINES - 3, COLS, 1, 0)) == NULL)
788 return 0;
789 if ((modeline = newwin(1, COLS, LINES-2, 0)) == NULL)
790 return 0;
791 if ((minibuf = newwin(1, COLS, LINES-1, 0)) == NULL)
792 return 0;
794 body_lines = LINES-3;
795 body_cols = COLS;
797 scrollok(body, TRUE);
799 /* non-blocking input */
800 wtimeout(body, 0);
802 mvwprintw(body, 0, 0, "");
804 event_set(&stdioev, 0, EV_READ | EV_PERSIST, dispatch_stdio, NULL);
805 event_add(&stdioev, NULL);
807 signal_set(&winchev, SIGWINCH, handle_resize, NULL);
808 signal_add(&winchev, NULL);
810 new_tab();
812 return 1;
815 void
816 ui_on_tab_refresh(struct tab *tab)
818 if (!(tab->flags & TAB_CURRENT))
819 return;
821 wrap_page(tab);
822 redraw_tab(tab);
825 void
826 ui_end(void)
828 endwin();