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 <stdlib.h>
66 #include <string.h>
68 #define TAB_CURRENT 0x1
70 #define CTRL(x) ((x)&0x1F)
72 #define MIN(a, b) ((a) < (b) ? (a) : (b))
73 #define MAX(a, b) ((a) > (b) ? (a) : (b))
75 static struct event stdioev, winchev;
77 static int push_line(struct tab*, const struct line*, const char*, size_t);
78 static void empty_vlist(struct tab*);
79 static void restore_cursor(struct tab *);
80 static void cmd_previous_line(int);
81 static void cmd_next_line(int);
82 static void cmd_forward_char(int);
83 static void cmd_backward_char(int);
84 static void cmd_redraw(int);
85 static void cmd_scroll_down(int);
86 static void cmd_scroll_up(int);
87 static void cmd_kill_telescope(int);
88 static struct line *nth_line(struct tab*, size_t);
89 static struct tab *current_tab(void);
90 static void dispatch_stdio(int, short, void*);
91 static void handle_clear_minibuf(int, short, void*);
92 static void handle_resize(int, short, void*);
93 static int word_bourdaries(const char*, const char*, const char**, const char**);
94 static void wrap_text(struct tab*, const char*, struct line*);
95 static int hardwrap_text(struct tab*, struct line*);
96 static int wrap_page(struct tab*);
97 static void print_line(struct line*);
98 static void redraw_tab(struct tab*);
100 typedef void (*interactivefn)(int);
102 static void cmd_unbound(int);
104 static WINDOW *tabline, *body, *modeline, *minibuf;
105 static int body_lines, body_cols;
107 static struct event clminibufev;
108 static int clminibufev_set;
109 static struct timeval clminibufev_timer = { 5, 0 };
111 struct ui_state {
112 int curs_x;
113 int curs_y;
114 size_t line_off;
115 size_t line_max;
117 TAILQ_HEAD(, line) head;
118 };
120 struct binding {
121 int key;
122 interactivefn fn;
123 } bindings[] = {
124 { CTRL('p'), cmd_previous_line, },
125 { CTRL('n'), cmd_next_line, },
126 { CTRL('f'), cmd_forward_char, },
127 { CTRL('b'), cmd_backward_char, },
129 { CTRL('L'), cmd_redraw, },
131 { 'J', cmd_scroll_down, },
132 { 'K', cmd_scroll_up, },
134 { 'q', cmd_kill_telescope, },
136 { 0, NULL, },
137 };
139 static int
140 push_line(struct tab *tab, const struct line *l, const char *buf, size_t len)
142 struct line *vl;
144 tab->s->line_max++;
146 if ((vl = calloc(1, sizeof(*vl))) == NULL)
147 return 0;
149 if (len != 0 && (vl->line = calloc(1, len+1)) == NULL) {
150 free(vl);
151 return 0;
154 vl->type = l->type;
155 if (len != 0)
156 memcpy(vl->line, buf, len);
157 vl->alt = l->alt;
159 if (TAILQ_EMPTY(&tab->s->head))
160 TAILQ_INSERT_HEAD(&tab->s->head, vl, lines);
161 else
162 TAILQ_INSERT_TAIL(&tab->s->head, vl, lines);
163 return 1;
166 static void
167 empty_vlist(struct tab *tab)
169 struct line *l, *t;
171 tab->s->line_max = 0;
173 TAILQ_FOREACH_SAFE(l, &tab->s->head, lines, t) {
174 TAILQ_REMOVE(&tab->s->head, l, lines);
175 free(l->line);
176 /* l->alt references the original line! */
177 free(l);
181 static void
182 restore_cursor(struct tab *tab)
184 wmove(body, tab->s->curs_y, tab->s->curs_x);
187 static void
188 cmd_previous_line(int k)
190 struct tab *tab;
192 tab = current_tab();
194 if (--tab->s->curs_y < 0) {
195 tab->s->curs_y = 0;
196 cmd_scroll_up(k);
199 restore_cursor(tab);
202 static void
203 cmd_next_line(int k)
205 struct tab *tab;
207 tab = current_tab();
209 if (++tab->s->curs_y > body_lines-1) {
210 tab->s->curs_y = body_lines-1;
211 cmd_scroll_down(k);
214 restore_cursor(tab);
217 static void
218 cmd_forward_char(int k)
220 struct tab *tab;
222 tab = current_tab();
223 tab->s->curs_x = MIN(body_cols-1, tab->s->curs_x+1);
224 restore_cursor(tab);
227 static void
228 cmd_backward_char(int k)
230 struct tab *tab;
232 tab = current_tab();
233 tab->s->curs_x = MAX(0, tab->s->curs_x-1);
234 restore_cursor(tab);
237 static void
238 cmd_redraw(int k)
240 handle_resize(0, 0, NULL);
243 static void
244 cmd_scroll_up(int k)
246 struct tab *tab;
247 struct line *l;
249 tab = current_tab();
250 if (tab->s->line_off == 0)
251 return;
253 l = nth_line(tab, --tab->s->line_off);
254 wscrl(body, -1);
255 wmove(body, 0, 0);
256 print_line(l);
259 static void
260 cmd_scroll_down(int k)
262 struct tab *tab;
263 struct line *l;
264 size_t n;
266 tab = current_tab();
268 if (tab->s->line_max == 0 || tab->s->line_off == tab->s->line_max-1)
269 return;
271 tab->s->line_off++;
272 wscrl(body, 1);
274 if (tab->s->line_max - tab->s->line_off < body_lines)
275 return;
277 l = nth_line(tab, tab->s->line_off + body_lines-1);
278 wmove(body, body_lines-1, 0);
279 print_line(l);
282 static void
283 cmd_kill_telescope(int k)
285 event_loopbreak();
288 static void
289 cmd_unbound(int k)
291 if (clminibufev_set)
292 evtimer_del(&clminibufev);
293 evtimer_set(&clminibufev, handle_clear_minibuf, NULL);
294 evtimer_add(&clminibufev, &clminibufev_timer);
295 clminibufev_set = 1;
297 werase(minibuf);
298 wprintw(minibuf, "%c is undefined", k);
299 restore_cursor(current_tab());
302 static struct line *
303 nth_line(struct tab *tab, size_t n)
305 struct line *l;
306 size_t i;
308 i = 0;
309 TAILQ_FOREACH(l, &tab->s->head, lines) {
310 if (i == n)
311 return l;
312 i++;
315 /* unreachable */
316 abort();
319 static struct tab *
320 current_tab(void)
322 struct tab *t;
324 TAILQ_FOREACH(t, &tabshead, tabs) {
325 if (t->flags & TAB_CURRENT)
326 return t;
329 /* unreachable */
330 abort();
333 static void
334 dispatch_stdio(int fd, short ev, void *d)
336 struct binding *b;
337 int k;
339 k = wgetch(body);
341 if (k == ERR)
342 return;
344 for (b = bindings; b->fn != NULL; ++b) {
345 if (k == b->key) {
346 b->fn(k);
347 goto done;
351 cmd_unbound(k);
353 done:
354 restore_cursor(current_tab());
355 wrefresh(tabline);
356 wrefresh(modeline);
357 wrefresh(minibuf);
359 wrefresh(body);
362 static void
363 handle_clear_minibuf(int fd, short ev, void *d)
365 clminibufev_set = 0;
366 werase(minibuf);
367 wrefresh(minibuf);
368 wrefresh(body);
371 static void
372 handle_resize(int sig, short ev, void *d)
374 struct tab *tab;
376 endwin();
377 refresh();
378 clear();
380 /* move and resize the windows, in reverse order! */
382 mvwin(minibuf, LINES-1, 0);
383 wresize(minibuf, 1, COLS);
385 mvwin(modeline, LINES-2, 0);
386 wresize(modeline, 1, COLS);
388 wresize(body, LINES-3, COLS);
389 body_lines = LINES-3;
390 body_cols = COLS;
392 wresize(tabline, 1, COLS);
394 tab = current_tab();
396 wrap_page(tab);
397 redraw_tab(tab);
400 /*
401 * Helper function for wrap_text. Find the end of the current word
402 * and the end of the separator after the word.
403 */
404 static int
405 word_boundaries(const char *s, const char *sep, const char **endword, const char **endspc)
407 *endword = s;
408 *endword = s;
410 if (*s == '\0')
411 return 0;
413 /* find the end of the current world */
414 for (; *s != '\0'; ++s) {
415 if (strchr(sep, *s) != NULL)
416 break;
419 *endword = s;
421 /* find the end of the separator */
422 for (; *s != '\0'; ++s) {
423 if (strchr(sep, *s) == NULL)
424 break;
427 *endspc = s;
429 return 1;
432 static inline int
433 emitline(struct tab *tab, size_t zero, size_t *off, const struct line *l,
434 const char **line)
436 if (!push_line(tab, l, *line, *off - zero))
437 return 0;
438 *line += *off - zero;
439 *off = zero;
440 return 1;
443 static inline void
444 emitstr(const char **s, size_t len, size_t *off)
446 size_t i;
448 /* printw("%*s", ...) doesn't seem to respect the precision, so... */
449 for (i = 0; i < len; ++i)
450 addch((*s)[i]);
451 *off += len;
452 *s += len;
455 /*
456 * Build a list of visual line by wrapping the given line, assuming
457 * that when printed will have a leading prefix prfx.
459 * TODO: it considers each byte one cell on the screen!
460 */
461 static void
462 wrap_text(struct tab *tab, const char *prfx, struct line *l)
464 size_t zero, off, len, split;
465 const char *endword, *endspc, *line, *linestart;
467 zero = strlen(prfx);
468 off = zero;
469 line = l->line;
470 linestart = l->line;
472 while (word_boundaries(line, " \t-", &endword, &endspc)) {
473 len = endword - line;
474 if (off + len >= body_cols) {
475 emitline(tab, zero, &off, l, &linestart);
476 while (len >= body_cols) {
477 /* hard wrap */
478 emitline(tab, zero, &off, l, &linestart);
479 len -= body_cols-1;
480 line += body_cols-1;
483 if (len != 0)
484 off += len;
485 } else
486 off += len;
488 /* print the spaces iff not at bol */
489 len = endspc - endword;
490 /* line = endspc; */
491 if (off != zero) {
492 if (off + len >= body_cols) {
493 emitline(tab, zero, &off, l, &linestart);
494 linestart = endspc;
495 } else
496 off += len;
499 line = endspc;
502 emitline(tab, zero, &off, l, &linestart);
505 static int
506 hardwrap_text(struct tab *tab, struct line *l)
508 size_t off, len;
509 const char *linestart;
511 len = strlen(l->line);
512 off = 0;
513 linestart = l->line;
515 while (len >= COLS) {
516 len -= COLS-1;
517 off = COLS-1;
518 if (!emitline(tab, 0, &off, l, &linestart))
519 return 0;
522 return 1;
525 static int
526 wrap_page(struct tab *tab)
528 struct line *l;
530 empty_vlist(tab);
532 TAILQ_FOREACH(l, &tab->page.head, lines) {
533 switch (l->type) {
534 case LINE_TEXT:
535 wrap_text(tab, "", l);
536 break;
537 case LINE_LINK:
538 wrap_text(tab, "=> ", l);
539 break;
540 case LINE_TITLE_1:
541 wrap_text(tab, "# ", l);
542 break;
543 case LINE_TITLE_2:
544 wrap_text(tab, "## ", l);
545 break;
546 case LINE_TITLE_3:
547 wrap_text(tab, "### ", l);
548 break;
549 case LINE_ITEM:
550 wrap_text(tab, "* ", l);
551 break;
552 case LINE_QUOTE:
553 wrap_text(tab, "> ", l);
554 break;
555 case LINE_PRE_START:
556 case LINE_PRE_END:
557 push_line(tab, l, NULL, 0);
558 break;
559 case LINE_PRE_CONTENT:
560 hardwrap_text(tab, l);
561 break;
564 return 1;
567 static inline void
568 print_line(struct line *l)
570 const char *text = l->line;
572 if (text == NULL)
573 text = "";
575 switch (l->type) {
576 case LINE_TEXT:
577 wprintw(body, "%s", text);
578 break;
579 case LINE_LINK:
580 wattron(body, A_UNDERLINE);
581 wprintw(body, "=> %s", text);
582 wattroff(body, A_UNDERLINE);
583 return;
584 case LINE_TITLE_1:
585 wattron(body, A_BOLD);
586 wprintw(body, "# %s", text);
587 wattroff(body, A_BOLD);
588 return;
589 case LINE_TITLE_2:
590 wattron(body, A_BOLD);
591 wprintw(body, "## %s", text);
592 wattroff(body, A_BOLD);
593 return;
594 case LINE_TITLE_3:
595 wattron(body, A_BOLD);
596 wprintw(body, "### %s", text);
597 wattroff(body, A_BOLD);
598 return;
599 case LINE_ITEM:
600 wprintw(body, "* %s", text);
601 return;
602 case LINE_QUOTE:
603 wattron(body, A_DIM);
604 wprintw(body, "> %s", text);
605 wattroff(body, A_DIM);
606 return;
607 case LINE_PRE_START:
608 case LINE_PRE_END:
609 wprintw(body, "```");
610 return;
611 case LINE_PRE_CONTENT:
612 wprintw(body, "%s", text);
613 return;
617 static void
618 redraw_modeline(struct tab *tab)
620 int x, y, max_x, max_y;
621 const char *url = "TODO:url";
622 const char *mode = "text/gemini-mode";
624 wclear(modeline);
625 wattron(modeline, A_REVERSE);
626 wmove(modeline, 0, 0);
628 wprintw(modeline, "-- %s %s ", mode, url);
629 getyx(modeline, y, x);
630 getmaxyx(modeline, max_y, max_x);
632 (void)y;
633 (void)max_y;
635 for (; x < max_x; ++x)
636 waddstr(modeline, "-");
639 static void
640 redraw_tab(struct tab *tab)
642 struct line *l;
643 int line;
645 werase(body);
647 tab->s->line_off = MIN(tab->s->line_max, tab->s->line_off);
648 if (TAILQ_EMPTY(&tab->s->head))
649 return;
651 line = 0;
652 l = nth_line(tab, tab->s->line_off);
653 for (; l != NULL; l = TAILQ_NEXT(l, lines)) {
654 wmove(body, line, 0);
655 print_line(l);
656 line++;
657 if (line == body_lines)
658 break;
661 redraw_modeline(tab);
663 restore_cursor(tab);
664 wrefresh(tabline);
665 wrefresh(modeline);
666 wrefresh(minibuf);
668 wrefresh(body);
671 int
672 ui_init(void)
674 setlocale(LC_ALL, "");
676 initscr();
677 raw();
678 noecho();
680 nonl();
681 intrflush(stdscr, FALSE);
682 keypad(stdscr, TRUE);
684 if ((tabline = newwin(1, COLS, 0, 0)) == NULL)
685 return 0;
686 if ((body = newwin(LINES - 3, COLS, 1, 0)) == NULL)
687 return 0;
688 if ((modeline = newwin(1, COLS, LINES-2, 0)) == NULL)
689 return 0;
690 if ((minibuf = newwin(1, COLS, LINES-1, 0)) == NULL)
691 return 0;
693 body_lines = LINES-3;
694 body_cols = COLS;
696 scrollok(body, TRUE);
698 /* non-blocking input */
699 wtimeout(body, 0);
701 mvwprintw(body, 0, 0, "");
703 event_set(&stdioev, 0, EV_READ | EV_PERSIST, dispatch_stdio, NULL);
704 event_add(&stdioev, NULL);
706 signal_set(&winchev, SIGWINCH, handle_resize, NULL);
707 signal_add(&winchev, NULL);
709 return 1;
712 int
713 ui_on_new_tab(struct tab *tab)
715 struct tab *t;
717 if ((tab->s = calloc(1, sizeof(*t->s))) == NULL)
718 return 0;
720 TAILQ_INIT(&tab->s->head);
722 TAILQ_FOREACH(t, &tabshead, tabs) {
723 t->flags &= ~TAB_CURRENT;
725 tab->flags = TAB_CURRENT;
727 /* TODO: redraw the tab list */
728 /* TODO: switch to the new tab */
730 wmove(body, 0, 0);
732 return 1;
735 void
736 ui_on_tab_refresh(struct tab *tab)
738 if (!(tab->flags & TAB_CURRENT))
739 return;
741 wrap_page(tab);
742 redraw_tab(tab);
745 void
746 ui_end(void)
748 endwin();