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 <ctype.h>
62 #include <curses.h>
63 #include <event.h>
64 #include <locale.h>
65 #include <signal.h>
66 #include <stdarg.h>
67 #include <stdlib.h>
68 #include <string.h>
69 #include <unistd.h>
71 #define TAB_CURRENT 0x1
73 #define MIN(a, b) ((a) < (b) ? (a) : (b))
74 #define MAX(a, b) ((a) > (b) ? (a) : (b))
76 struct kmap;
78 static struct event stdioev, winchev;
80 static int kbd(const char*);
81 static void kmap_define_key(struct kmap*, const char*, void(*)(struct tab*));
82 static void load_default_keys(void);
83 static int push_line(struct tab*, const struct line*, const char*, size_t);
84 static void empty_vlist(struct tab*);
85 static void restore_cursor(struct tab *);
87 static void cmd_previous_line(struct tab*);
88 static void cmd_next_line(struct tab*);
89 static void cmd_forward_char(struct tab*);
90 static void cmd_backward_char(struct tab*);
91 static void cmd_redraw(struct tab*);
92 static void cmd_scroll_line_down(struct tab*);
93 static void cmd_scroll_line_up(struct tab*);
94 static void cmd_scroll_up(struct tab*);
95 static void cmd_scroll_down(struct tab*);
96 static void cmd_kill_telescope(struct tab*);
97 static void cmd_push_button(struct tab*);
98 static void cmd_execute_extended_command(struct tab*);
99 static void cmd_tab_close(struct tab*);
100 static void cmd_tab_new(struct tab*);
101 static void cmd_tab_next(struct tab*);
102 static void cmd_tab_previous(struct tab*);
104 static void global_key_unbound(void);
106 static void cmd_mini_del(struct tab*);
107 static void cmd_mini_forward_char(struct tab*);
108 static void cmd_mini_backward_char(struct tab*);
109 static void cmd_mini_move_end_of_line(struct tab*);
110 static void cmd_mini_move_beginning_of_line(struct tab*);
111 static void cmd_mini_kill_line(struct tab*);
112 static void cmd_mini_abort();
113 static void cmd_mini_complete_and_exit();
115 static void eecmd_self_insert(void);
116 static void eecmd_select(void);
118 static struct line *nth_line(struct tab*, size_t);
119 static struct tab *current_tab(void);
120 static void dispatch_stdio(int, short, void*);
121 static void handle_clear_minibuf(int, short, void*);
122 static void handle_resize(int, short, void*);
123 static int word_bourdaries(const char*, const char*, const char**, const char**);
124 static void wrap_text(struct tab*, const char*, struct line*);
125 static int hardwrap_text(struct tab*, struct line*);
126 static int wrap_page(struct tab*);
127 static void print_line(struct line*);
128 static void redraw_tabline(void);
129 static void redraw_modeline(struct tab*);
130 static void redraw_minibuffer(void);
131 static void redraw_tab(struct tab*);
132 static void message(const char*, ...) __attribute__((format(printf, 1, 2)));
133 static void start_loading_anim(struct tab*);
134 static void update_loading_anim(int, short, void*);
135 static void stop_loading_anim(struct tab*);
136 static void load_url_in_tab(struct tab*, const char*);
137 static void enter_minibuffer(void(*)(void), void(*)(void), void(*)(void));
138 static void exit_minibuffer(void);
139 static void new_tab(void);
141 static struct { int meta, key; } thiskey;
143 static WINDOW *tabline, *body, *modeline, *minibuf;
144 static int body_lines, body_cols;
146 static struct event clminibufev;
147 static int clminibufev_set;
148 static struct timeval clminibufev_timer = { 5, 0 };
149 static struct timeval loadingev_timer = { 0, 250000 };
151 static uint32_t tab_counter;
153 struct ui_state {
154 int curs_x;
155 int curs_y;
156 size_t line_off;
157 size_t line_max;
159 short loading_anim;
160 short loading_anim_step;
161 struct event loadingev;
163 TAILQ_HEAD(, line) head;
164 };
166 static char keybuf[64];
168 #define CTRL(n) ((n)&0x1F)
170 struct keytable {
171 char *p;
172 int k;
173 } keytable[] = {
174 { "<up>", KEY_UP },
175 { "<down>", KEY_DOWN },
176 { "<left>", KEY_LEFT },
177 { "<right>", KEY_RIGHT },
178 { "<prior>", KEY_PPAGE },
179 { "<next>", KEY_NPAGE },
180 { "<home>", KEY_HOME },
181 { "<end>", KEY_END },
182 /* ... */
183 { "del", KEY_BACKSPACE },
184 { "esc", 27 },
185 { "space", ' ' },
186 { "spc", ' ' },
187 { "enter", CTRL('m') },
188 { "ret", CTRL('m' )},
189 { "tab", CTRL('i') },
190 /* ... */
191 { NULL, 0 },
192 };
194 struct kmap {
195 TAILQ_HEAD(map, keymap) m;
196 void (*unhandled_input)(void);
197 };
199 struct kmap global_map,
200 minibuffer_map,
201 *current_map,
202 *base_map;
204 struct keymap {
205 int meta;
206 int key;
207 struct kmap map;
208 void (*fn)(struct tab*);
210 TAILQ_ENTRY(keymap) keymaps;
211 };
213 static int in_minibuffer;
215 static struct {
216 char *curmesg;
218 char buf[1025];
219 size_t off, len;
220 char prompt[16];
221 void (*donefn)(void);
222 void (*abortfn)(void);
223 } ministate;
225 static int
226 kbd(const char *key)
228 struct keytable *t;
230 for (t = keytable; t->p != NULL; ++t) {
231 if (has_prefix(key, t->p))
232 return t->k;
235 return *key;
238 static const char *
239 unkbd(int k)
241 struct keytable *t;
243 for (t = keytable; t->p != NULL; ++t) {
244 if (k == t->k)
245 return t->p;
248 return NULL;
251 static void
252 kmap_define_key(struct kmap *map, const char *key, void (*fn)(struct tab*))
254 int ctrl, meta, k;
255 struct keymap *entry;
257 again:
258 if ((ctrl = has_prefix(key, "C-")))
259 key += 2;
260 if ((meta = has_prefix(key, "M-")))
261 key += 2;
262 if (*key == '\0')
263 _exit(1);
264 k = kbd(key);
266 if (ctrl)
267 k = CTRL(k);
269 /* skip key & spaces */
270 while (*key != '\0' && !isspace(*key))
271 ++key;
272 while (*key != '\0' && isspace(*key))
273 ++key;
275 TAILQ_FOREACH(entry, &map->m, keymaps) {
276 if (entry->meta == meta && entry->key == k) {
277 if (*key == '\0') {
278 entry->fn = fn;
279 return;
281 map = &entry->map;
282 goto again;
286 if ((entry = calloc(1, sizeof(*entry))) == NULL)
287 abort();
289 entry->meta = meta;
290 entry->key = k;
291 TAILQ_INIT(&entry->map.m);
293 if (TAILQ_EMPTY(&map->m))
294 TAILQ_INSERT_HEAD(&map->m, entry, keymaps);
295 else
296 TAILQ_INSERT_TAIL(&map->m, entry, keymaps);
298 if (*key != '\0') {
299 map = &entry->map;
300 goto again;
303 entry->fn = fn;
306 static inline void
307 global_set_key(const char *key, void (*fn)(struct tab*))
309 kmap_define_key(&global_map, key, fn);
312 static inline void
313 minibuffer_set_key(const char *key, void (*fn)(struct tab*))
315 kmap_define_key(&minibuffer_map, key, fn);
318 static void
319 load_default_keys(void)
321 /* === global map === */
323 /* emacs */
324 global_set_key("C-p", cmd_previous_line);
325 global_set_key("C-n", cmd_next_line);
326 global_set_key("C-f", cmd_forward_char);
327 global_set_key("C-b", cmd_backward_char);
329 global_set_key("M-v", cmd_scroll_up);
330 global_set_key("C-v", cmd_scroll_down);
332 global_set_key("C-x C-c", cmd_kill_telescope);
334 global_set_key("M-x", cmd_execute_extended_command);
336 global_set_key("C-x t 0", cmd_tab_close);
337 global_set_key("C-x t 2", cmd_tab_new);
338 global_set_key("C-x t o", cmd_tab_next);
339 global_set_key("C-x t O", cmd_tab_previous);
341 /* vi/vi-like */
342 global_set_key("k", cmd_previous_line);
343 global_set_key("j", cmd_next_line);
344 global_set_key("l", cmd_forward_char);
345 global_set_key("h", cmd_backward_char);
347 global_set_key("K", cmd_scroll_line_up);
348 global_set_key("J", cmd_scroll_line_down);
350 /* tmp */
351 global_set_key("q", cmd_kill_telescope);
353 global_set_key(":", cmd_execute_extended_command);
355 /* cua */
356 global_set_key("<up>", cmd_previous_line);
357 global_set_key("<down>", cmd_next_line);
358 global_set_key("<right>", cmd_forward_char);
359 global_set_key("<left>", cmd_backward_char);
360 global_set_key("<prior>", cmd_scroll_up);
361 global_set_key("<next>", cmd_scroll_down);
363 /* "ncurses standard" */
364 global_set_key("C-l", cmd_redraw);
366 /* global */
367 global_set_key("C-m", cmd_push_button);
369 /* === minibuffer map === */
370 minibuffer_set_key("ret", cmd_mini_complete_and_exit);
371 minibuffer_set_key("C-g", cmd_mini_abort);
372 minibuffer_set_key("esc", cmd_mini_abort);
373 minibuffer_set_key("del", cmd_mini_del);
375 minibuffer_set_key("C-f", cmd_mini_forward_char);
376 minibuffer_set_key("C-b", cmd_mini_backward_char);
377 minibuffer_set_key("C-e", cmd_mini_move_end_of_line);
378 minibuffer_set_key("C-a", cmd_mini_move_beginning_of_line);
379 minibuffer_set_key("<end>", cmd_mini_move_end_of_line);
380 minibuffer_set_key("<home>", cmd_mini_move_beginning_of_line);
381 minibuffer_set_key("C-k", cmd_mini_kill_line);
384 static int
385 push_line(struct tab *tab, const struct line *l, const char *buf, size_t len)
387 struct line *vl;
389 tab->s->line_max++;
391 if ((vl = calloc(1, sizeof(*vl))) == NULL)
392 return 0;
394 if (len != 0 && (vl->line = calloc(1, len+1)) == NULL) {
395 free(vl);
396 return 0;
399 vl->type = l->type;
400 if (len != 0)
401 memcpy(vl->line, buf, len);
402 vl->alt = l->alt;
404 if (TAILQ_EMPTY(&tab->s->head))
405 TAILQ_INSERT_HEAD(&tab->s->head, vl, lines);
406 else
407 TAILQ_INSERT_TAIL(&tab->s->head, vl, lines);
408 return 1;
411 static void
412 empty_vlist(struct tab *tab)
414 struct line *l, *t;
416 tab->s->line_max = 0;
418 TAILQ_FOREACH_SAFE(l, &tab->s->head, lines, t) {
419 TAILQ_REMOVE(&tab->s->head, l, lines);
420 free(l->line);
421 /* l->alt references the original line! */
422 free(l);
426 static void
427 restore_cursor(struct tab *tab)
429 wmove(body, tab->s->curs_y, tab->s->curs_x);
432 static void
433 cmd_previous_line(struct tab *tab)
435 if (--tab->s->curs_y < 0) {
436 tab->s->curs_y = 0;
437 cmd_scroll_line_up(tab);
440 restore_cursor(tab);
443 static void
444 cmd_next_line(struct tab *tab)
446 if (++tab->s->curs_y > body_lines-1) {
447 tab->s->curs_y = body_lines-1;
448 cmd_scroll_line_down(tab);
451 restore_cursor(tab);
454 static void
455 cmd_forward_char(struct tab *tab)
457 tab->s->curs_x = MIN(body_cols-1, tab->s->curs_x+1);
458 restore_cursor(tab);
461 static void
462 cmd_backward_char(struct tab *tab)
464 tab->s->curs_x = MAX(0, tab->s->curs_x-1);
465 restore_cursor(tab);
468 static void
469 cmd_redraw(struct tab *tab)
471 handle_resize(0, 0, NULL);
474 static void
475 cmd_scroll_line_up(struct tab *tab)
477 struct line *l;
479 if (tab->s->line_off == 0)
480 return;
482 l = nth_line(tab, --tab->s->line_off);
483 wscrl(body, -1);
484 wmove(body, 0, 0);
485 print_line(l);
488 static void
489 cmd_scroll_line_down(struct tab *tab)
491 struct line *l;
492 size_t n;
494 if (tab->s->line_max == 0 || tab->s->line_off == tab->s->line_max-1)
495 return;
497 tab->s->line_off++;
498 wscrl(body, 1);
500 if (tab->s->line_max - tab->s->line_off < body_lines)
501 return;
503 l = nth_line(tab, tab->s->line_off + body_lines-1);
504 wmove(body, body_lines-1, 0);
505 print_line(l);
508 static void
509 cmd_scroll_up(struct tab *tab)
511 size_t off;
513 off = body_lines+1;
515 for (; off > 0; --off)
516 cmd_scroll_line_up(tab);
519 static void
520 cmd_scroll_down(struct tab *tab)
522 ssize_t off;
524 off = tab->s->line_off + body_lines;
525 off = MIN(tab->s->line_max, off);
527 for (; off >= 0; --off)
528 cmd_scroll_line_down(tab);
531 static void
532 cmd_kill_telescope(struct tab *tab)
534 event_loopbreak();
537 static void
538 cmd_push_button(struct tab *tab)
540 struct line *l;
541 size_t nth;
543 nth = tab->s->line_off + tab->s->curs_y;
544 if (nth > tab->s->line_max)
545 return;
546 l = nth_line(tab, nth);
547 if (l->type != LINE_LINK)
548 return;
550 load_url_in_tab(tab, l->alt);
553 static void
554 cmd_execute_extended_command(struct tab *tab)
556 size_t len;
558 enter_minibuffer(eecmd_self_insert, eecmd_select, exit_minibuffer);
560 len = sizeof(ministate.prompt);
561 strlcpy(ministate.prompt, "", len);
563 if (thiskey.meta)
564 strlcat(ministate.prompt, "M-", len);
566 strlcat(ministate.prompt, keyname(thiskey.key), len);
567 strlcat(ministate.prompt, " ", len);
570 static void
571 cmd_tab_close(struct tab *tab)
573 struct tab *t;
575 if (TAILQ_PREV(tab, tabshead, tabs) == NULL &&
576 TAILQ_NEXT(tab, tabs) == NULL) {
577 message("Can't close the only tab.");
578 return;
581 stop_tab(tab);
583 t = TAILQ_PREV(tab, tabshead, tabs);
584 t->flags |= TAB_CURRENT;
586 TAILQ_REMOVE(&tabshead, tab, tabs);
588 free(tab->s);
589 free(tab);
592 static void
593 cmd_tab_new(struct tab *tab)
595 new_tab();
598 static void
599 cmd_tab_next(struct tab *tab)
601 struct tab *t;
603 tab->flags &= ~TAB_CURRENT;
605 if ((t = TAILQ_NEXT(tab, tabs)) == NULL)
606 t = TAILQ_FIRST(&tabshead);
607 t->flags |= TAB_CURRENT;
610 static void
611 cmd_tab_previous(struct tab *tab)
613 struct tab *t;
615 tab->flags &= ~TAB_CURRENT;
617 if ((t = TAILQ_PREV(tab, tabshead, tabs)) == NULL)
618 t = TAILQ_LAST(&tabshead, tabshead);
619 t->flags |= TAB_CURRENT;
622 static void
623 global_key_unbound(void)
625 message("%s is undefined", keybuf);
628 static void
629 cmd_mini_del(struct tab *tab)
631 if (ministate.len == 0 || ministate.off == 0)
632 return;
634 memmove(&ministate.buf[ministate.off-1],
635 &ministate.buf[ministate.off],
636 ministate.len - ministate.off + 1);
637 ministate.off--;
638 ministate.len--;
641 static void
642 cmd_mini_forward_char(struct tab *tab)
644 if (ministate.off == ministate.len)
645 return;
646 ministate.off++;
649 static void
650 cmd_mini_backward_char(struct tab *tab)
652 if (ministate.off == 0)
653 return;
654 ministate.off--;
657 static void
658 cmd_mini_move_end_of_line(struct tab *tab)
660 ministate.off = ministate.len;
663 static void
664 cmd_mini_move_beginning_of_line(struct tab *tab)
666 ministate.off = 0;
669 static void
670 cmd_mini_kill_line(struct tab *tab)
672 if (ministate.off == ministate.len)
673 return;
674 ministate.buf[ministate.off] = '\0';
675 ministate.len -= ministate.off;
678 static void
679 cmd_mini_abort(struct tab *tab)
681 ministate.abortfn();
684 static void
685 cmd_mini_complete_and_exit(struct tab *tab)
687 ministate.donefn();
690 static void
691 eecmd_self_insert(void)
693 if (thiskey.meta || isspace(thiskey.key) ||
694 !isgraph(thiskey.key)) {
695 global_key_unbound();
696 return;
699 if (ministate.len == sizeof(ministate.buf) -1)
700 return;
702 /* TODO: utf8 handling! */
704 memmove(&ministate.buf[ministate.off+1],
705 &ministate.buf[ministate.off],
706 ministate.len - ministate.off + 1);
707 ministate.buf[ministate.off] = thiskey.key;
708 ministate.off++;
709 ministate.len++;
712 static void
713 eecmd_select(void)
715 exit_minibuffer();
716 message("TODO: try to execute %s", ministate.buf);
719 static struct line *
720 nth_line(struct tab *tab, size_t n)
722 struct line *l;
723 size_t i;
725 i = 0;
726 TAILQ_FOREACH(l, &tab->s->head, lines) {
727 if (i == n)
728 return l;
729 i++;
732 /* unreachable */
733 abort();
736 static struct tab *
737 current_tab(void)
739 struct tab *t;
741 TAILQ_FOREACH(t, &tabshead, tabs) {
742 if (t->flags & TAB_CURRENT)
743 return t;
746 /* unreachable */
747 abort();
750 static void
751 dispatch_stdio(int fd, short ev, void *d)
753 struct tab *tab;
754 struct keymap *k;
755 const char *keyname;
756 char tmp[2] = {0};
758 thiskey.key = wgetch(body);
759 if (thiskey.key == ERR)
760 return;
761 if (thiskey.key == 27) {
762 /* TODO: make escape-time customizable */
764 thiskey.meta = 1;
765 thiskey.key = wgetch(body);
766 if (thiskey.key == ERR)
767 thiskey.key = 27;
768 } else
769 thiskey.meta = 0;
771 if (keybuf[0] != '\0')
772 strlcat(keybuf, " ", sizeof(keybuf));
773 if (thiskey.meta)
774 strlcat(keybuf, "M-", sizeof(keybuf));
775 if ((keyname = unkbd(thiskey.key)) != NULL)
776 strlcat(keybuf, keyname, sizeof(keybuf));
777 else {
778 tmp[0] = thiskey.key;
779 strlcat(keybuf, tmp, sizeof(keybuf));
782 TAILQ_FOREACH(k, &current_map->m, keymaps) {
783 if (k->meta == thiskey.meta &&
784 k->key == thiskey.key) {
785 if (k->fn == NULL)
786 current_map = &k->map;
787 else {
788 current_map = base_map;
789 strlcpy(keybuf, "", sizeof(keybuf));
790 k->fn(current_tab());
792 goto done;
796 if (current_map->unhandled_input != NULL)
797 current_map->unhandled_input();
798 else {
799 global_key_unbound();
802 strlcpy(keybuf, "", sizeof(keybuf));
803 current_map = base_map;
805 done:
806 tab = current_tab();
807 redraw_tabline();
808 redraw_modeline(tab);
809 redraw_minibuffer();
810 restore_cursor(tab);
811 wrefresh(tabline);
812 wrefresh(modeline);
814 if (in_minibuffer) {
815 wrefresh(body);
816 wrefresh(minibuf);
817 } else {
818 wrefresh(minibuf);
819 wrefresh(body);
823 static void
824 handle_clear_minibuf(int fd, short ev, void *d)
826 clminibufev_set = 0;
828 free(ministate.curmesg);
829 ministate.curmesg = NULL;
831 redraw_minibuffer();
832 if (in_minibuffer) {
833 wrefresh(body);
834 wrefresh(minibuf);
835 } else {
836 wrefresh(minibuf);
837 wrefresh(body);
841 static void
842 handle_resize(int sig, short ev, void *d)
844 struct tab *tab;
846 endwin();
847 refresh();
848 clear();
850 /* move and resize the windows, in reverse order! */
852 mvwin(minibuf, LINES-1, 0);
853 wresize(minibuf, 1, COLS);
855 mvwin(modeline, LINES-2, 0);
856 wresize(modeline, 1, COLS);
858 wresize(body, LINES-3, COLS);
859 body_lines = LINES-3;
860 body_cols = COLS;
862 wresize(tabline, 1, COLS);
864 tab = current_tab();
866 wrap_page(tab);
867 redraw_tab(tab);
870 /*
871 * Helper function for wrap_text. Find the end of the current word
872 * and the end of the separator after the word.
873 */
874 static int
875 word_boundaries(const char *s, const char *sep, const char **endword, const char **endspc)
877 *endword = s;
878 *endword = s;
880 if (*s == '\0')
881 return 0;
883 /* find the end of the current world */
884 for (; *s != '\0'; ++s) {
885 if (strchr(sep, *s) != NULL)
886 break;
889 *endword = s;
891 /* find the end of the separator */
892 for (; *s != '\0'; ++s) {
893 if (strchr(sep, *s) == NULL)
894 break;
897 *endspc = s;
899 return 1;
902 static inline int
903 emitline(struct tab *tab, size_t zero, size_t *off, const struct line *l,
904 const char **line)
906 if (!push_line(tab, l, *line, *off - zero))
907 return 0;
908 *line += *off - zero;
909 *off = zero;
910 return 1;
913 static inline void
914 emitstr(const char **s, size_t len, size_t *off)
916 size_t i;
918 /* printw("%*s", ...) doesn't seem to respect the precision, so... */
919 for (i = 0; i < len; ++i)
920 addch((*s)[i]);
921 *off += len;
922 *s += len;
925 /*
926 * Build a list of visual line by wrapping the given line, assuming
927 * that when printed will have a leading prefix prfx.
929 * TODO: it considers each byte one cell on the screen!
930 */
931 static void
932 wrap_text(struct tab *tab, const char *prfx, struct line *l)
934 size_t zero, off, len, split;
935 const char *endword, *endspc, *line, *linestart;
937 zero = strlen(prfx);
938 off = zero;
939 line = l->line;
940 linestart = l->line;
942 while (word_boundaries(line, " \t-", &endword, &endspc)) {
943 len = endword - line;
944 if (off + len >= body_cols) {
945 emitline(tab, zero, &off, l, &linestart);
946 while (len >= body_cols) {
947 /* hard wrap */
948 emitline(tab, zero, &off, l, &linestart);
949 len -= body_cols-1;
950 line += body_cols-1;
953 if (len != 0)
954 off += len;
955 } else
956 off += len;
958 /* print the spaces iff not at bol */
959 len = endspc - endword;
960 /* line = endspc; */
961 if (off != zero) {
962 if (off + len >= body_cols) {
963 emitline(tab, zero, &off, l, &linestart);
964 linestart = endspc;
965 } else
966 off += len;
969 line = endspc;
972 emitline(tab, zero, &off, l, &linestart);
975 static int
976 hardwrap_text(struct tab *tab, struct line *l)
978 size_t off, len;
979 const char *linestart;
981 len = strlen(l->line);
982 off = 0;
983 linestart = l->line;
985 while (len >= COLS) {
986 len -= COLS-1;
987 off = COLS-1;
988 if (!emitline(tab, 0, &off, l, &linestart))
989 return 0;
992 if (len != 0)
993 return emitline(tab, 0, &len, l, &linestart);
995 return 1;
998 static int
999 wrap_page(struct tab *tab)
1001 struct line *l;
1003 empty_vlist(tab);
1005 TAILQ_FOREACH(l, &tab->page.head, lines) {
1006 switch (l->type) {
1007 case LINE_TEXT:
1008 wrap_text(tab, "", l);
1009 break;
1010 case LINE_LINK:
1011 wrap_text(tab, "=> ", l);
1012 break;
1013 case LINE_TITLE_1:
1014 wrap_text(tab, "# ", l);
1015 break;
1016 case LINE_TITLE_2:
1017 wrap_text(tab, "## ", l);
1018 break;
1019 case LINE_TITLE_3:
1020 wrap_text(tab, "### ", l);
1021 break;
1022 case LINE_ITEM:
1023 wrap_text(tab, "* ", l);
1024 break;
1025 case LINE_QUOTE:
1026 wrap_text(tab, "> ", l);
1027 break;
1028 case LINE_PRE_START:
1029 case LINE_PRE_END:
1030 push_line(tab, l, NULL, 0);
1031 break;
1032 case LINE_PRE_CONTENT:
1033 hardwrap_text(tab, l);
1034 break;
1037 return 1;
1040 static inline void
1041 print_line(struct line *l)
1043 const char *text = l->line;
1045 if (text == NULL)
1046 text = "";
1048 switch (l->type) {
1049 case LINE_TEXT:
1050 wprintw(body, "%s", text);
1051 break;
1052 case LINE_LINK:
1053 wattron(body, A_UNDERLINE);
1054 wprintw(body, "=> %s", text);
1055 wattroff(body, A_UNDERLINE);
1056 return;
1057 case LINE_TITLE_1:
1058 wattron(body, A_BOLD);
1059 wprintw(body, "# %s", text);
1060 wattroff(body, A_BOLD);
1061 return;
1062 case LINE_TITLE_2:
1063 wattron(body, A_BOLD);
1064 wprintw(body, "## %s", text);
1065 wattroff(body, A_BOLD);
1066 return;
1067 case LINE_TITLE_3:
1068 wattron(body, A_BOLD);
1069 wprintw(body, "### %s", text);
1070 wattroff(body, A_BOLD);
1071 return;
1072 case LINE_ITEM:
1073 wprintw(body, "* %s", text);
1074 return;
1075 case LINE_QUOTE:
1076 wattron(body, A_DIM);
1077 wprintw(body, "> %s", text);
1078 wattroff(body, A_DIM);
1079 return;
1080 case LINE_PRE_START:
1081 case LINE_PRE_END:
1082 wprintw(body, "```");
1083 return;
1084 case LINE_PRE_CONTENT:
1085 wprintw(body, "%s", text);
1086 return;
1090 static void
1091 redraw_tabline(void)
1093 struct tab *tab;
1094 int current;
1096 wclear(tabline);
1097 wbkgd(tabline, A_REVERSE);
1099 wprintw(tabline, " ");
1100 TAILQ_FOREACH(tab, &tabshead, tabs) {
1101 current = tab->flags & TAB_CURRENT;
1102 wprintw(tabline, " %s%d:todo title ",
1103 current ? "*" : "", tab->id);
1107 static void
1108 redraw_modeline(struct tab *tab)
1110 double pct;
1111 int x, y, max_x, max_y;
1112 const char *mode = "text/gemini-mode";
1113 const char *spin = "-\\|/";
1115 wclear(modeline);
1116 wattron(modeline, A_REVERSE);
1117 wmove(modeline, 0, 0);
1119 wprintw(modeline, "-%c %s ",
1120 spin[tab->s->loading_anim_step], mode);
1122 pct = (tab->s->line_off + tab->s->curs_y) * 100.0 / tab->s->line_max;
1124 if (tab->s->line_max <= body_lines)
1125 wprintw(modeline, "All ");
1126 else if (tab->s->line_off == 0)
1127 wprintw(modeline, "Top ");
1128 else if (tab->s->line_off + body_lines >= tab->s->line_max)
1129 wprintw(modeline, "Bottom ");
1130 else
1131 wprintw(modeline, "%.0f%% ", pct);
1133 wprintw(modeline, "%d/%d %s ",
1134 tab->s->line_off + tab->s->curs_y,
1135 tab->s->line_max,
1136 tab->urlstr);
1138 getyx(modeline, y, x);
1139 getmaxyx(modeline, max_y, max_x);
1141 (void)y;
1142 (void)max_y;
1144 for (; x < max_x; ++x)
1145 waddstr(modeline, "-");
1148 static void
1149 redraw_minibuffer(void)
1151 size_t skip = 0, off = 0;
1153 wclear(minibuf);
1154 if (!in_minibuffer)
1155 goto message;
1157 off = strlen(ministate.prompt);
1159 while (ministate.off - skip > COLS / 2) {
1160 skip += MIN(ministate.off/4, 1);
1163 mvwprintw(minibuf, 0, 0, "%s%s", ministate.prompt,
1164 ministate.buf + skip);
1166 message:
1167 if (ministate.curmesg != NULL) {
1168 if (in_minibuffer)
1169 wprintw(minibuf, " [%s]", ministate.curmesg);
1170 else
1171 wprintw(minibuf, "%s", ministate.curmesg);
1174 wmove(minibuf, 0, off + ministate.off - skip);
1177 static void
1178 redraw_tab(struct tab *tab)
1180 struct line *l;
1181 int line;
1183 werase(body);
1185 tab->s->line_off = MIN(tab->s->line_max, tab->s->line_off);
1186 if (TAILQ_EMPTY(&tab->s->head))
1187 return;
1189 line = 0;
1190 l = nth_line(tab, tab->s->line_off);
1191 for (; l != NULL; l = TAILQ_NEXT(l, lines)) {
1192 wmove(body, line, 0);
1193 print_line(l);
1194 line++;
1195 if (line == body_lines)
1196 break;
1199 redraw_tabline();
1200 redraw_modeline(tab);
1201 redraw_minibuffer();
1203 restore_cursor(tab);
1204 wrefresh(tabline);
1205 wrefresh(modeline);
1207 if (in_minibuffer) {
1208 wrefresh(body);
1209 wrefresh(minibuf);
1210 } else {
1211 wrefresh(minibuf);
1212 wrefresh(body);
1216 static void
1217 message(const char *fmt, ...)
1219 va_list ap;
1221 if (clminibufev_set)
1222 evtimer_del(&clminibufev);
1223 evtimer_set(&clminibufev, handle_clear_minibuf, NULL);
1224 evtimer_add(&clminibufev, &clminibufev_timer);
1225 clminibufev_set = 1;
1227 va_start(ap, fmt);
1228 /* TODO: what to do if the allocation fails here? */
1229 if (vasprintf(&ministate.curmesg, fmt, ap) == -1)
1230 ministate.curmesg = NULL;
1231 va_end(ap);
1233 redraw_minibuffer();
1235 if (in_minibuffer) {
1236 wrefresh(body);
1237 wrefresh(minibuf);
1238 } else {
1239 wrefresh(minibuf);
1240 wrefresh(body);
1244 static void
1245 start_loading_anim(struct tab *tab)
1247 if (tab->s->loading_anim)
1248 return;
1249 tab->s->loading_anim = 1;
1250 evtimer_set(&tab->s->loadingev, update_loading_anim, tab);
1251 evtimer_add(&tab->s->loadingev, &loadingev_timer);
1254 static void
1255 update_loading_anim(int fd, short ev, void *d)
1257 struct tab *tab = d;
1259 tab->s->loading_anim_step = (tab->s->loading_anim_step+1)%4;
1261 redraw_modeline(tab);
1262 wrefresh(modeline);
1264 wrefresh(body);
1265 if (in_minibuffer)
1266 wrefresh(minibuf);
1268 evtimer_add(&tab->s->loadingev, &loadingev_timer);
1271 static void
1272 stop_loading_anim(struct tab *tab)
1274 if (!tab->s->loading_anim)
1275 return;
1276 evtimer_del(&tab->s->loadingev);
1277 tab->s->loading_anim = 0;
1278 tab->s->loading_anim_step = 0;
1280 redraw_modeline(tab);
1282 wrefresh(modeline);
1283 wrefresh(body);
1284 if (in_minibuffer)
1285 wrefresh(minibuf);
1288 static void
1289 load_url_in_tab(struct tab *tab, const char *url)
1291 empty_vlist(tab);
1292 message("Loading %s...", url);
1293 start_loading_anim(tab);
1294 load_url(tab, url);
1296 tab->s->curs_x = 0;
1297 tab->s->curs_y = 0;
1298 redraw_tab(tab);
1301 static void
1302 enter_minibuffer(void (*self_insert_fn)(void), void (*donefn)(void),
1303 void (*abortfn)(void))
1305 in_minibuffer = 1;
1306 base_map = &minibuffer_map;
1307 current_map = &minibuffer_map;
1309 base_map->unhandled_input = self_insert_fn;
1311 ministate.donefn = donefn;
1312 ministate.abortfn = abortfn;
1313 memset(ministate.buf, 0, sizeof(ministate.buf));
1314 ministate.off = 0;
1315 strlcpy(ministate.buf, "", sizeof(ministate.prompt));
1318 static void
1319 exit_minibuffer(void)
1321 wclear(minibuf);
1323 in_minibuffer = 0;
1324 base_map = &global_map;
1325 current_map = &global_map;
1328 static void
1329 new_tab(void)
1331 struct tab *tab, *t;
1332 const char *url = "about:new";
1334 if ((tab = calloc(1, sizeof(*tab))) == NULL)
1335 goto err;
1337 if ((tab->s = calloc(1, sizeof(*t->s))) == NULL)
1338 goto err;
1340 TAILQ_INIT(&tab->s->head);
1341 TAILQ_FOREACH(t, &tabshead, tabs) {
1342 t->flags &= ~TAB_CURRENT;
1345 tab->id = tab_counter++;
1346 tab->flags = TAB_CURRENT;
1348 if (TAILQ_EMPTY(&tabshead))
1349 TAILQ_INSERT_HEAD(&tabshead, tab, tabs);
1350 else
1351 TAILQ_INSERT_TAIL(&tabshead, tab, tabs);
1353 load_url_in_tab(tab, url);
1354 return;
1356 err:
1357 event_loopbreak();
1360 int
1361 ui_init(void)
1363 setlocale(LC_ALL, "");
1365 TAILQ_INIT(&global_map.m);
1366 global_map.unhandled_input = global_key_unbound;
1368 TAILQ_INIT(&minibuffer_map.m);
1370 base_map = &global_map;
1371 current_map = &global_map;
1372 load_default_keys();
1374 initscr();
1375 raw();
1376 noecho();
1378 nonl();
1379 intrflush(stdscr, FALSE);
1381 if ((tabline = newwin(1, COLS, 0, 0)) == NULL)
1382 return 0;
1383 if ((body = newwin(LINES - 3, COLS, 1, 0)) == NULL)
1384 return 0;
1385 if ((modeline = newwin(1, COLS, LINES-2, 0)) == NULL)
1386 return 0;
1387 if ((minibuf = newwin(1, COLS, LINES-1, 0)) == NULL)
1388 return 0;
1390 body_lines = LINES-3;
1391 body_cols = COLS;
1393 keypad(body, TRUE);
1394 scrollok(body, TRUE);
1396 /* non-blocking input */
1397 wtimeout(body, 0);
1399 mvwprintw(body, 0, 0, "");
1401 event_set(&stdioev, 0, EV_READ | EV_PERSIST, dispatch_stdio, NULL);
1402 event_add(&stdioev, NULL);
1404 signal_set(&winchev, SIGWINCH, handle_resize, NULL);
1405 signal_add(&winchev, NULL);
1407 new_tab();
1409 return 1;
1412 void
1413 ui_on_tab_loaded(struct tab *tab)
1415 stop_loading_anim(tab);
1416 message("Loaded %s", tab->urlstr);
1419 void
1420 ui_on_tab_refresh(struct tab *tab)
1422 if (!(tab->flags & TAB_CURRENT))
1423 return;
1425 wrap_page(tab);
1426 redraw_tab(tab);
1429 void
1430 ui_end(void)
1432 endwin();