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_resize(int, short, void*);
92 static int word_bourdaries(const char*, const char*, const char**, const char**);
93 static void wrap_text(struct tab*, const char*, struct line*);
94 static int hardwrap_text(struct tab*, struct line*);
95 static int wrap_page(struct tab*);
96 static void print_line(struct line*);
97 static void redraw_tab(struct tab*);
99 typedef void (*interactivefn)(int);
101 static void cmd_unbound(int);
103 static WINDOW *tabline, *body, *modeline, *minibuf;
104 static int body_lines, body_cols;
106 static struct event clminibufev;
107 static int clminibufev_set;
109 struct ui_state {
110 int curs_x;
111 int curs_y;
112 size_t line_off;
113 size_t line_max;
115 TAILQ_HEAD(, line) head;
116 };
118 struct binding {
119 int key;
120 interactivefn fn;
121 } bindings[] = {
122 { CTRL('p'), cmd_previous_line, },
123 { CTRL('n'), cmd_next_line, },
124 { CTRL('f'), cmd_forward_char, },
125 { CTRL('b'), cmd_backward_char, },
127 { CTRL('L'), cmd_redraw, },
129 { 'J', cmd_scroll_down, },
130 { 'K', cmd_scroll_up, },
132 { 'q', cmd_kill_telescope, },
134 { 0, NULL, },
135 };
137 static int
138 push_line(struct tab *tab, const struct line *l, const char *buf, size_t len)
140 struct line *vl;
142 tab->s->line_max++;
144 if ((vl = calloc(1, sizeof(*vl))) == NULL)
145 return 0;
147 if (len != 0 && (vl->line = calloc(1, len+1)) == NULL) {
148 free(vl);
149 return 0;
152 vl->type = l->type;
153 if (len != 0)
154 memcpy(vl->line, buf, len);
155 vl->alt = l->alt;
157 if (TAILQ_EMPTY(&tab->s->head))
158 TAILQ_INSERT_HEAD(&tab->s->head, vl, lines);
159 else
160 TAILQ_INSERT_TAIL(&tab->s->head, vl, lines);
161 return 1;
164 static void
165 empty_vlist(struct tab *tab)
167 struct line *l, *t;
169 tab->s->line_max = 0;
171 TAILQ_FOREACH_SAFE(l, &tab->s->head, lines, t) {
172 TAILQ_REMOVE(&tab->s->head, l, lines);
173 free(l->line);
174 /* l->alt references the original line! */
175 free(l);
179 static void
180 restore_cursor(struct tab *tab)
182 wmove(body, tab->s->curs_y, tab->s->curs_x);
185 static void
186 cmd_previous_line(int k)
188 struct tab *tab;
190 tab = current_tab();
191 tab->s->curs_y = MAX(0, tab->s->curs_y-1);
192 restore_cursor(tab);
195 static void
196 cmd_next_line(int k)
198 struct tab *tab;
200 tab = current_tab();
201 tab->s->curs_y = MIN(LINES-1, tab->s->curs_y+1);
202 restore_cursor(tab);
205 static void
206 cmd_forward_char(int k)
208 struct tab *tab;
210 tab = current_tab();
211 tab->s->curs_x = MIN(COLS-1, tab->s->curs_x+1);
212 restore_cursor(tab);
215 static void
216 cmd_backward_char(int k)
218 struct tab *tab;
220 tab = current_tab();
221 tab->s->curs_x = MAX(0, tab->s->curs_x-1);
222 restore_cursor(tab);
225 static void
226 cmd_redraw(int k)
228 clear();
229 redraw_tab(current_tab());
232 static void
233 cmd_scroll_up(int k)
235 struct tab *tab;
236 struct line *l;
238 tab = current_tab();
239 if (tab->s->line_off == 0)
240 return;
242 l = nth_line(tab, --tab->s->line_off);
243 wscrl(body, -1);
244 wmove(body, 0, 0);
245 print_line(l);
248 static void
249 cmd_scroll_down(int k)
251 struct tab *tab;
252 struct line *l;
253 size_t n;
255 tab = current_tab();
257 if (tab->s->line_max == 0 || tab->s->line_off == tab->s->line_max-1)
258 return;
260 tab->s->line_off++;
261 wscrl(body, 1);
263 if (tab->s->line_max - tab->s->line_off < body_lines)
264 return;
266 l = nth_line(tab, tab->s->line_off + body_lines-1);
267 wmove(body, body_lines-1, 0);
268 print_line(l);
271 static void
272 cmd_kill_telescope(int k)
274 event_loopbreak();
277 static void
278 cmd_unbound(int k)
280 wclear(minibuf);
281 wprintw(minibuf, "Unknown key %c", k);
282 restore_cursor(current_tab());
285 static struct line *
286 nth_line(struct tab *tab, size_t n)
288 struct line *l;
289 size_t i;
291 i = 0;
292 TAILQ_FOREACH(l, &tab->s->head, lines) {
293 if (i == n)
294 return l;
295 i++;
298 /* unreachable */
299 abort();
302 static struct tab *
303 current_tab(void)
305 struct tab *t;
307 TAILQ_FOREACH(t, &tabshead, tabs) {
308 if (t->flags & TAB_CURRENT)
309 return t;
312 /* unreachable */
313 abort();
316 static void
317 dispatch_stdio(int fd, short ev, void *d)
319 struct binding *b;
320 int k;
322 k = wgetch(body);
324 if (k == ERR)
325 return;
327 for (b = bindings; b->fn != NULL; ++b) {
328 if (k == b->key) {
329 b->fn(k);
330 goto done;
334 cmd_unbound(k);
336 done:
337 restore_cursor(current_tab());
338 wrefresh(tabline);
339 wrefresh(modeline);
340 wrefresh(minibuf);
342 wrefresh(body);
345 static void
346 handle_resize(int sig, short ev, void *d)
348 struct tab *tab;
350 endwin();
351 refresh();
352 clear();
354 /* move and resize the windows, in reverse order! */
356 mvwin(minibuf, LINES-2, 0);
357 wresize(minibuf, 1, COLS);
359 mvwin(modeline, LINES-2, 0);
360 wresize(modeline, 1, COLS);
362 wresize(body, LINES-3, COLS);
363 body_lines = LINES-3;
364 body_cols = COLS-1;
366 wresize(tabline, 1, COLS);
368 tab = current_tab();
370 wrap_page(tab);
371 redraw_tab(tab);
374 /*
375 * Helper function for wrap_text. Find the end of the current word
376 * and the end of the separator after the word.
377 */
378 static int
379 word_boundaries(const char *s, const char *sep, const char **endword, const char **endspc)
381 *endword = s;
382 *endword = s;
384 if (*s == '\0')
385 return 0;
387 /* find the end of the current world */
388 for (; *s != '\0'; ++s) {
389 if (strchr(sep, *s) != NULL)
390 break;
393 *endword = s;
395 /* find the end of the separator */
396 for (; *s != '\0'; ++s) {
397 if (strchr(sep, *s) == NULL)
398 break;
401 *endspc = s;
403 return 1;
406 static inline int
407 emitline(struct tab *tab, size_t zero, size_t *off, const struct line *l,
408 const char **line)
410 if (!push_line(tab, l, *line, *off - zero))
411 return 0;
412 *line += *off - zero;
413 *off = zero;
414 return 1;
417 static inline void
418 emitstr(const char **s, size_t len, size_t *off)
420 size_t i;
422 /* printw("%*s", ...) doesn't seem to respect the precision, so... */
423 for (i = 0; i < len; ++i)
424 addch((*s)[i]);
425 *off += len;
426 *s += len;
429 /*
430 * Build a list of visual line by wrapping the given line, assuming
431 * that when printed will have a leading prefix prfx.
433 * TODO: it considers each byte one cell on the screen!
434 */
435 static void
436 wrap_text(struct tab *tab, const char *prfx, struct line *l)
438 size_t zero, off, len, split;
439 const char *endword, *endspc, *line, *linestart;
441 zero = strlen(prfx);
442 off = zero;
443 line = l->line;
444 linestart = l->line;
446 while (word_boundaries(line, " \t-", &endword, &endspc)) {
447 len = endword - line;
448 if (off + len >= body_cols) {
449 emitline(tab, zero, &off, l, &linestart);
450 while (len >= body_cols) {
451 /* hard wrap */
452 emitline(tab, zero, &off, l, &linestart);
453 len -= body_cols-1;
454 line += body_cols-1;
457 if (len != 0)
458 off += len;
459 } else
460 off += len;
462 /* print the spaces iff not at bol */
463 len = endspc - endword;
464 /* line = endspc; */
465 if (off != zero) {
466 if (off + len >= body_cols) {
467 emitline(tab, zero, &off, l, &linestart);
468 linestart = endspc;
469 } else
470 off += len;
473 line = endspc;
476 emitline(tab, zero, &off, l, &linestart);
479 static int
480 hardwrap_text(struct tab *tab, struct line *l)
482 size_t off, len;
483 const char *linestart;
485 len = strlen(l->line);
486 off = 0;
487 linestart = l->line;
489 while (len >= COLS) {
490 len -= COLS-1;
491 off = COLS-1;
492 if (!emitline(tab, 0, &off, l, &linestart))
493 return 0;
496 return 1;
499 static int
500 wrap_page(struct tab *tab)
502 struct line *l;
504 empty_vlist(tab);
506 TAILQ_FOREACH(l, &tab->page.head, lines) {
507 switch (l->type) {
508 case LINE_TEXT:
509 wrap_text(tab, "", l);
510 break;
511 case LINE_LINK:
512 wrap_text(tab, "=> ", l);
513 break;
514 case LINE_TITLE_1:
515 wrap_text(tab, "# ", l);
516 break;
517 case LINE_TITLE_2:
518 wrap_text(tab, "## ", l);
519 break;
520 case LINE_TITLE_3:
521 wrap_text(tab, "### ", l);
522 break;
523 case LINE_ITEM:
524 wrap_text(tab, "* ", l);
525 break;
526 case LINE_QUOTE:
527 wrap_text(tab, "> ", l);
528 break;
529 case LINE_PRE_START:
530 case LINE_PRE_END:
531 push_line(tab, l, NULL, 0);
532 break;
533 case LINE_PRE_CONTENT:
534 hardwrap_text(tab, l);
535 break;
538 return 1;
541 static inline void
542 print_line(struct line *l)
544 switch (l->type) {
545 case LINE_TEXT:
546 break;
547 case LINE_LINK:
548 wprintw(body, "=> ");
549 break;
550 case LINE_TITLE_1:
551 wprintw(body, "# ");
552 break;
553 case LINE_TITLE_2:
554 wprintw(body, "## ");
555 break;
556 case LINE_TITLE_3:
557 wprintw(body, "### ");
558 break;
559 case LINE_ITEM:
560 wprintw(body, "* ");
561 break;
562 case LINE_QUOTE:
563 wprintw(body, "> ");
564 break;
565 case LINE_PRE_START:
566 case LINE_PRE_END:
567 wprintw(body, "```");
568 break;
569 case LINE_PRE_CONTENT:
570 break;
573 if (l->line != NULL)
574 wprintw(body, "%s", l->line);
577 static void
578 redraw_modeline(struct tab *tab)
580 int x, y, max_x, max_y;
581 const char *url = "TODO:url";
582 const char *mode = "text/gemini-mode";
584 wclear(modeline);
585 wattron(modeline, A_REVERSE);
586 wmove(modeline, 0, 0);
588 wprintw(modeline, "-- %s %s ", mode, url);
589 getyx(modeline, y, x);
590 getmaxyx(modeline, max_y, max_x);
592 (void)y;
593 (void)max_y;
595 for (; x < max_x; ++x)
596 waddstr(modeline, "-");
599 static void
600 redraw_tab(struct tab *tab)
602 struct line *l;
603 int line;
605 werase(body);
607 tab->s->line_off = MIN(tab->s->line_max, tab->s->line_off);
608 if (TAILQ_EMPTY(&tab->s->head))
609 return;
611 line = 0;
612 l = nth_line(tab, tab->s->line_off);
613 for (; l != NULL; l = TAILQ_NEXT(l, lines)) {
614 wmove(body, line, 0);
615 print_line(l);
616 line++;
617 if (line == body_lines)
618 break;
621 redraw_modeline(tab);
623 restore_cursor(tab);
624 wrefresh(tabline);
625 wrefresh(modeline);
626 wrefresh(minibuf);
628 wrefresh(body);
631 int
632 ui_init(void)
634 setlocale(LC_ALL, "");
636 initscr();
637 raw();
638 noecho();
640 nonl();
641 intrflush(stdscr, FALSE);
642 keypad(stdscr, TRUE);
644 if ((tabline = newwin(1, COLS, 0, 0)) == NULL)
645 return 0;
646 if ((body = newwin(LINES - 3, COLS, 1, 0)) == NULL)
647 return 0;
648 if ((modeline = newwin(1, COLS, LINES-2, 0)) == NULL)
649 return 0;
650 if ((minibuf = newwin(1, COLS, LINES-1, 0)) == NULL)
651 return 0;
653 body_lines = LINES-3;
654 body_cols = COLS;
656 scrollok(body, TRUE);
658 /* non-blocking input */
659 wtimeout(body, 0);
661 mvwprintw(body, 0, 0, "");
663 event_set(&stdioev, 0, EV_READ | EV_PERSIST, dispatch_stdio, NULL);
664 event_add(&stdioev, NULL);
666 signal_set(&winchev, SIGWINCH, handle_resize, NULL);
667 signal_add(&winchev, NULL);
669 return 1;
672 int
673 ui_on_new_tab(struct tab *tab)
675 struct tab *t;
677 if ((tab->s = calloc(1, sizeof(*t->s))) == NULL)
678 return 0;
680 TAILQ_INIT(&tab->s->head);
682 TAILQ_FOREACH(t, &tabshead, tabs) {
683 t->flags &= ~TAB_CURRENT;
685 tab->flags = TAB_CURRENT;
687 /* TODO: redraw the tab list */
688 /* TODO: switch to the new tab */
690 wmove(body, 0, 0);
692 return 1;
695 void
696 ui_on_tab_refresh(struct tab *tab)
698 if (!(tab->flags & TAB_CURRENT))
699 return;
701 wrap_page(tab);
702 redraw_tab(tab);
705 void
706 ui_end(void)
708 endwin();