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 CTRL(x) ((x)&0x1F)
73 #define MIN(a, b) ((a) < (b) ? (a) : (b))
74 #define MAX(a, b) ((a) > (b) ? (a) : (b))
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 struct line *nth_line(struct tab*, size_t);
90 static struct tab *current_tab(void);
91 static void dispatch_stdio(int, short, void*);
92 static void handle_clear_minibuf(int, short, void*);
93 static void handle_resize(int, short, void*);
94 static int word_bourdaries(const char*, const char*, const char**, const char**);
95 static void wrap_text(struct tab*, const char*, struct line*);
96 static int hardwrap_text(struct tab*, struct line*);
97 static int wrap_page(struct tab*);
98 static void print_line(struct line*);
99 static void redraw_tab(struct tab*);
100 static void message(const char*, ...) __attribute__((format(printf, 1, 2)));
102 typedef void (*interactivefn)(int);
104 static void cmd_unbound(int);
106 static WINDOW *tabline, *body, *modeline, *minibuf;
107 static int body_lines, body_cols;
109 static struct event clminibufev;
110 static int clminibufev_set;
111 static struct timeval clminibufev_timer = { 5, 0 };
113 struct ui_state {
114 int curs_x;
115 int curs_y;
116 size_t line_off;
117 size_t line_max;
119 TAILQ_HEAD(, line) head;
120 };
122 struct binding {
123 int key;
124 interactivefn fn;
125 } bindings[] = {
126 { CTRL('p'), cmd_previous_line, },
127 { CTRL('n'), cmd_next_line, },
128 { CTRL('f'), cmd_forward_char, },
129 { CTRL('b'), cmd_backward_char, },
131 { CTRL('L'), cmd_redraw, },
133 { 'J', cmd_scroll_down, },
134 { 'K', cmd_scroll_up, },
136 { 'q', cmd_kill_telescope, },
138 { 0, NULL, },
139 };
141 static int
142 push_line(struct tab *tab, const struct line *l, const char *buf, size_t len)
144 struct line *vl;
146 tab->s->line_max++;
148 if ((vl = calloc(1, sizeof(*vl))) == NULL)
149 return 0;
151 if (len != 0 && (vl->line = calloc(1, len+1)) == NULL) {
152 free(vl);
153 return 0;
156 vl->type = l->type;
157 if (len != 0)
158 memcpy(vl->line, buf, len);
159 vl->alt = l->alt;
161 if (TAILQ_EMPTY(&tab->s->head))
162 TAILQ_INSERT_HEAD(&tab->s->head, vl, lines);
163 else
164 TAILQ_INSERT_TAIL(&tab->s->head, vl, lines);
165 return 1;
168 static void
169 empty_vlist(struct tab *tab)
171 struct line *l, *t;
173 tab->s->line_max = 0;
175 TAILQ_FOREACH_SAFE(l, &tab->s->head, lines, t) {
176 TAILQ_REMOVE(&tab->s->head, l, lines);
177 free(l->line);
178 /* l->alt references the original line! */
179 free(l);
183 static void
184 restore_cursor(struct tab *tab)
186 wmove(body, tab->s->curs_y, tab->s->curs_x);
189 static void
190 cmd_previous_line(int k)
192 struct tab *tab;
194 tab = current_tab();
196 if (--tab->s->curs_y < 0) {
197 tab->s->curs_y = 0;
198 cmd_scroll_up(k);
201 restore_cursor(tab);
204 static void
205 cmd_next_line(int k)
207 struct tab *tab;
209 tab = current_tab();
211 if (++tab->s->curs_y > body_lines-1) {
212 tab->s->curs_y = body_lines-1;
213 cmd_scroll_down(k);
216 restore_cursor(tab);
219 static void
220 cmd_forward_char(int k)
222 struct tab *tab;
224 tab = current_tab();
225 tab->s->curs_x = MIN(body_cols-1, tab->s->curs_x+1);
226 restore_cursor(tab);
229 static void
230 cmd_backward_char(int k)
232 struct tab *tab;
234 tab = current_tab();
235 tab->s->curs_x = MAX(0, tab->s->curs_x-1);
236 restore_cursor(tab);
239 static void
240 cmd_redraw(int k)
242 handle_resize(0, 0, NULL);
245 static void
246 cmd_scroll_up(int k)
248 struct tab *tab;
249 struct line *l;
251 tab = current_tab();
252 if (tab->s->line_off == 0)
253 return;
255 l = nth_line(tab, --tab->s->line_off);
256 wscrl(body, -1);
257 wmove(body, 0, 0);
258 print_line(l);
261 static void
262 cmd_scroll_down(int k)
264 struct tab *tab;
265 struct line *l;
266 size_t n;
268 tab = current_tab();
270 if (tab->s->line_max == 0 || tab->s->line_off == tab->s->line_max-1)
271 return;
273 tab->s->line_off++;
274 wscrl(body, 1);
276 if (tab->s->line_max - tab->s->line_off < body_lines)
277 return;
279 l = nth_line(tab, tab->s->line_off + body_lines-1);
280 wmove(body, body_lines-1, 0);
281 print_line(l);
284 static void
285 cmd_kill_telescope(int k)
287 event_loopbreak();
290 static void
291 cmd_unbound(int k)
293 message("%c is undefined", k);
296 static struct line *
297 nth_line(struct tab *tab, size_t n)
299 struct line *l;
300 size_t i;
302 i = 0;
303 TAILQ_FOREACH(l, &tab->s->head, lines) {
304 if (i == n)
305 return l;
306 i++;
309 /* unreachable */
310 abort();
313 static struct tab *
314 current_tab(void)
316 struct tab *t;
318 TAILQ_FOREACH(t, &tabshead, tabs) {
319 if (t->flags & TAB_CURRENT)
320 return t;
323 /* unreachable */
324 abort();
327 static void
328 dispatch_stdio(int fd, short ev, void *d)
330 struct binding *b;
331 int k;
333 k = wgetch(body);
335 if (k == ERR)
336 return;
338 for (b = bindings; b->fn != NULL; ++b) {
339 if (k == b->key) {
340 b->fn(k);
341 goto done;
345 cmd_unbound(k);
347 done:
348 restore_cursor(current_tab());
349 wrefresh(tabline);
350 wrefresh(modeline);
351 wrefresh(minibuf);
353 wrefresh(body);
356 static void
357 handle_clear_minibuf(int fd, short ev, void *d)
359 clminibufev_set = 0;
360 werase(minibuf);
361 wrefresh(minibuf);
362 wrefresh(body);
365 static void
366 handle_resize(int sig, short ev, void *d)
368 struct tab *tab;
370 endwin();
371 refresh();
372 clear();
374 /* move and resize the windows, in reverse order! */
376 mvwin(minibuf, LINES-1, 0);
377 wresize(minibuf, 1, COLS);
379 mvwin(modeline, LINES-2, 0);
380 wresize(modeline, 1, COLS);
382 wresize(body, LINES-3, COLS);
383 body_lines = LINES-3;
384 body_cols = COLS;
386 wresize(tabline, 1, COLS);
388 tab = current_tab();
390 wrap_page(tab);
391 redraw_tab(tab);
394 /*
395 * Helper function for wrap_text. Find the end of the current word
396 * and the end of the separator after the word.
397 */
398 static int
399 word_boundaries(const char *s, const char *sep, const char **endword, const char **endspc)
401 *endword = s;
402 *endword = s;
404 if (*s == '\0')
405 return 0;
407 /* find the end of the current world */
408 for (; *s != '\0'; ++s) {
409 if (strchr(sep, *s) != NULL)
410 break;
413 *endword = s;
415 /* find the end of the separator */
416 for (; *s != '\0'; ++s) {
417 if (strchr(sep, *s) == NULL)
418 break;
421 *endspc = s;
423 return 1;
426 static inline int
427 emitline(struct tab *tab, size_t zero, size_t *off, const struct line *l,
428 const char **line)
430 if (!push_line(tab, l, *line, *off - zero))
431 return 0;
432 *line += *off - zero;
433 *off = zero;
434 return 1;
437 static inline void
438 emitstr(const char **s, size_t len, size_t *off)
440 size_t i;
442 /* printw("%*s", ...) doesn't seem to respect the precision, so... */
443 for (i = 0; i < len; ++i)
444 addch((*s)[i]);
445 *off += len;
446 *s += len;
449 /*
450 * Build a list of visual line by wrapping the given line, assuming
451 * that when printed will have a leading prefix prfx.
453 * TODO: it considers each byte one cell on the screen!
454 */
455 static void
456 wrap_text(struct tab *tab, const char *prfx, struct line *l)
458 size_t zero, off, len, split;
459 const char *endword, *endspc, *line, *linestart;
461 zero = strlen(prfx);
462 off = zero;
463 line = l->line;
464 linestart = l->line;
466 while (word_boundaries(line, " \t-", &endword, &endspc)) {
467 len = endword - line;
468 if (off + len >= body_cols) {
469 emitline(tab, zero, &off, l, &linestart);
470 while (len >= body_cols) {
471 /* hard wrap */
472 emitline(tab, zero, &off, l, &linestart);
473 len -= body_cols-1;
474 line += body_cols-1;
477 if (len != 0)
478 off += len;
479 } else
480 off += len;
482 /* print the spaces iff not at bol */
483 len = endspc - endword;
484 /* line = endspc; */
485 if (off != zero) {
486 if (off + len >= body_cols) {
487 emitline(tab, zero, &off, l, &linestart);
488 linestart = endspc;
489 } else
490 off += len;
493 line = endspc;
496 emitline(tab, zero, &off, l, &linestart);
499 static int
500 hardwrap_text(struct tab *tab, struct line *l)
502 size_t off, len;
503 const char *linestart;
505 len = strlen(l->line);
506 off = 0;
507 linestart = l->line;
509 while (len >= COLS) {
510 len -= COLS-1;
511 off = COLS-1;
512 if (!emitline(tab, 0, &off, l, &linestart))
513 return 0;
516 return 1;
519 static int
520 wrap_page(struct tab *tab)
522 struct line *l;
524 empty_vlist(tab);
526 TAILQ_FOREACH(l, &tab->page.head, lines) {
527 switch (l->type) {
528 case LINE_TEXT:
529 wrap_text(tab, "", l);
530 break;
531 case LINE_LINK:
532 wrap_text(tab, "=> ", l);
533 break;
534 case LINE_TITLE_1:
535 wrap_text(tab, "# ", l);
536 break;
537 case LINE_TITLE_2:
538 wrap_text(tab, "## ", l);
539 break;
540 case LINE_TITLE_3:
541 wrap_text(tab, "### ", l);
542 break;
543 case LINE_ITEM:
544 wrap_text(tab, "* ", l);
545 break;
546 case LINE_QUOTE:
547 wrap_text(tab, "> ", l);
548 break;
549 case LINE_PRE_START:
550 case LINE_PRE_END:
551 push_line(tab, l, NULL, 0);
552 break;
553 case LINE_PRE_CONTENT:
554 hardwrap_text(tab, l);
555 break;
558 return 1;
561 static inline void
562 print_line(struct line *l)
564 const char *text = l->line;
566 if (text == NULL)
567 text = "";
569 switch (l->type) {
570 case LINE_TEXT:
571 wprintw(body, "%s", text);
572 break;
573 case LINE_LINK:
574 wattron(body, A_UNDERLINE);
575 wprintw(body, "=> %s", text);
576 wattroff(body, A_UNDERLINE);
577 return;
578 case LINE_TITLE_1:
579 wattron(body, A_BOLD);
580 wprintw(body, "# %s", text);
581 wattroff(body, A_BOLD);
582 return;
583 case LINE_TITLE_2:
584 wattron(body, A_BOLD);
585 wprintw(body, "## %s", text);
586 wattroff(body, A_BOLD);
587 return;
588 case LINE_TITLE_3:
589 wattron(body, A_BOLD);
590 wprintw(body, "### %s", text);
591 wattroff(body, A_BOLD);
592 return;
593 case LINE_ITEM:
594 wprintw(body, "* %s", text);
595 return;
596 case LINE_QUOTE:
597 wattron(body, A_DIM);
598 wprintw(body, "> %s", text);
599 wattroff(body, A_DIM);
600 return;
601 case LINE_PRE_START:
602 case LINE_PRE_END:
603 wprintw(body, "```");
604 return;
605 case LINE_PRE_CONTENT:
606 wprintw(body, "%s", text);
607 return;
611 static void
612 redraw_modeline(struct tab *tab)
614 int x, y, max_x, max_y;
615 const char *url = "TODO:url";
616 const char *mode = "text/gemini-mode";
618 wclear(modeline);
619 wattron(modeline, A_REVERSE);
620 wmove(modeline, 0, 0);
622 wprintw(modeline, "-- %s %s ", mode, url);
623 getyx(modeline, y, x);
624 getmaxyx(modeline, max_y, max_x);
626 (void)y;
627 (void)max_y;
629 for (; x < max_x; ++x)
630 waddstr(modeline, "-");
633 static void
634 redraw_tab(struct tab *tab)
636 struct line *l;
637 int line;
639 werase(body);
641 tab->s->line_off = MIN(tab->s->line_max, tab->s->line_off);
642 if (TAILQ_EMPTY(&tab->s->head))
643 return;
645 line = 0;
646 l = nth_line(tab, tab->s->line_off);
647 for (; l != NULL; l = TAILQ_NEXT(l, lines)) {
648 wmove(body, line, 0);
649 print_line(l);
650 line++;
651 if (line == body_lines)
652 break;
655 redraw_modeline(tab);
657 restore_cursor(tab);
658 wrefresh(tabline);
659 wrefresh(modeline);
660 wrefresh(minibuf);
662 wrefresh(body);
665 static void
666 message(const char *fmt, ...)
668 va_list ap;
670 va_start(ap, fmt);
672 if (clminibufev_set)
673 evtimer_del(&clminibufev);
674 evtimer_set(&clminibufev, handle_clear_minibuf, NULL);
675 evtimer_add(&clminibufev, &clminibufev_timer);
676 clminibufev_set = 1;
678 werase(minibuf);
679 vw_printw(minibuf, fmt, ap);
681 wrefresh(minibuf);
682 wrefresh(body);
684 va_end(ap);
687 int
688 ui_init(void)
690 setlocale(LC_ALL, "");
692 initscr();
693 raw();
694 noecho();
696 nonl();
697 intrflush(stdscr, FALSE);
698 keypad(stdscr, TRUE);
700 if ((tabline = newwin(1, COLS, 0, 0)) == NULL)
701 return 0;
702 if ((body = newwin(LINES - 3, COLS, 1, 0)) == NULL)
703 return 0;
704 if ((modeline = newwin(1, COLS, LINES-2, 0)) == NULL)
705 return 0;
706 if ((minibuf = newwin(1, COLS, LINES-1, 0)) == NULL)
707 return 0;
709 body_lines = LINES-3;
710 body_cols = COLS;
712 scrollok(body, TRUE);
714 /* non-blocking input */
715 wtimeout(body, 0);
717 mvwprintw(body, 0, 0, "");
719 event_set(&stdioev, 0, EV_READ | EV_PERSIST, dispatch_stdio, NULL);
720 event_add(&stdioev, NULL);
722 signal_set(&winchev, SIGWINCH, handle_resize, NULL);
723 signal_add(&winchev, NULL);
725 return 1;
728 int
729 ui_on_new_tab(struct tab *tab)
731 struct tab *t;
733 if ((tab->s = calloc(1, sizeof(*t->s))) == NULL)
734 return 0;
736 TAILQ_INIT(&tab->s->head);
738 TAILQ_FOREACH(t, &tabshead, tabs) {
739 t->flags &= ~TAB_CURRENT;
741 tab->flags = TAB_CURRENT;
743 /* TODO: redraw the tab list */
744 /* TODO: switch to the new tab */
746 wmove(body, 0, 0);
748 return 1;
751 void
752 ui_on_tab_refresh(struct tab *tab)
754 if (!(tab->flags & TAB_CURRENT))
755 return;
757 wrap_page(tab);
758 redraw_tab(tab);
761 void
762 ui_end(void)
764 endwin();