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*);
103 static void cmd_load_url(struct tab*);
104 static void cmd_load_current_url(struct tab*);
106 static void global_key_unbound(void);
108 static void cmd_mini_del(struct tab*);
109 static void cmd_mini_forward_char(struct tab*);
110 static void cmd_mini_backward_char(struct tab*);
111 static void cmd_mini_move_end_of_line(struct tab*);
112 static void cmd_mini_move_beginning_of_line(struct tab*);
113 static void cmd_mini_kill_line(struct tab*);
114 static void cmd_mini_abort();
115 static void cmd_mini_complete_and_exit();
117 static void minibuffer_self_insert(void);
118 static void eecmd_self_insert(void);
119 static void eecmd_select(void);
120 static void ir_self_insert(void);
121 static void ir_select(void);
122 static void lu_self_insert(void);
123 static void lu_select(void);
126 static struct line *nth_line(struct tab*, size_t);
127 static struct tab *current_tab(void);
128 static void dispatch_stdio(int, short, void*);
129 static void handle_clear_minibuf(int, short, void*);
130 static void handle_resize(int, short, void*);
131 static int word_bourdaries(const char*, const char*, const char**, const char**);
132 static void wrap_text(struct tab*, const char*, struct line*);
133 static int hardwrap_text(struct tab*, struct line*);
134 static int wrap_page(struct tab*);
135 static void print_line(struct line*);
136 static void redraw_tabline(void);
137 static void redraw_modeline(struct tab*);
138 static void redraw_minibuffer(void);
139 static void redraw_tab(struct tab*);
140 static void message(const char*, ...) __attribute__((format(printf, 1, 2)));
141 static void start_loading_anim(struct tab*);
142 static void update_loading_anim(int, short, void*);
143 static void stop_loading_anim(struct tab*);
144 static void load_url_in_tab(struct tab*, const char*);
145 static void enter_minibuffer(void(*)(void), void(*)(void), void(*)(void));
146 static void exit_minibuffer(void);
147 static void switch_to_tab(struct tab*);
148 static void new_tab(void);
150 static struct { int meta, key; } thiskey;
152 static WINDOW *tabline, *body, *modeline, *minibuf;
153 static int body_lines, body_cols;
155 static struct event clminibufev;
156 static int clminibufev_set;
157 static struct timeval clminibufev_timer = { 5, 0 };
158 static struct timeval loadingev_timer = { 0, 250000 };
160 static uint32_t tab_counter;
162 struct ui_state {
163 int curs_x;
164 int curs_y;
165 size_t line_off;
166 size_t line_max;
168 short loading_anim;
169 short loading_anim_step;
170 struct event loadingev;
172 TAILQ_HEAD(, line) head;
173 };
175 static char keybuf[64];
177 #define CTRL(n) ((n)&0x1F)
179 struct keytable {
180 char *p;
181 int k;
182 } keytable[] = {
183 { "<up>", KEY_UP },
184 { "<down>", KEY_DOWN },
185 { "<left>", KEY_LEFT },
186 { "<right>", KEY_RIGHT },
187 { "<prior>", KEY_PPAGE },
188 { "<next>", KEY_NPAGE },
189 { "<home>", KEY_HOME },
190 { "<end>", KEY_END },
191 /* ... */
192 { "del", KEY_BACKSPACE },
193 { "esc", 27 },
194 { "space", ' ' },
195 { "spc", ' ' },
196 { "enter", CTRL('m') },
197 { "ret", CTRL('m' )},
198 { "tab", CTRL('i') },
199 /* ... */
200 { NULL, 0 },
201 };
203 struct kmap {
204 TAILQ_HEAD(map, keymap) m;
205 void (*unhandled_input)(void);
206 };
208 struct kmap global_map,
209 minibuffer_map,
210 *current_map,
211 *base_map;
213 struct keymap {
214 int meta;
215 int key;
216 struct kmap map;
217 void (*fn)(struct tab*);
219 TAILQ_ENTRY(keymap) keymaps;
220 };
222 static int in_minibuffer;
224 static struct {
225 char *curmesg;
227 char buf[1025];
228 size_t off, len;
229 char prompt[32];
230 void (*donefn)(void);
231 void (*abortfn)(void);
232 } ministate;
234 static int
235 kbd(const char *key)
237 struct keytable *t;
239 for (t = keytable; t->p != NULL; ++t) {
240 if (has_prefix(key, t->p))
241 return t->k;
244 return *key;
247 static const char *
248 unkbd(int k)
250 struct keytable *t;
252 for (t = keytable; t->p != NULL; ++t) {
253 if (k == t->k)
254 return t->p;
257 return NULL;
260 static void
261 kmap_define_key(struct kmap *map, const char *key, void (*fn)(struct tab*))
263 int ctrl, meta, k;
264 struct keymap *entry;
266 again:
267 if ((ctrl = has_prefix(key, "C-")))
268 key += 2;
269 if ((meta = has_prefix(key, "M-")))
270 key += 2;
271 if (*key == '\0')
272 _exit(1);
273 k = kbd(key);
275 if (ctrl)
276 k = CTRL(k);
278 /* skip key & spaces */
279 while (*key != '\0' && !isspace(*key))
280 ++key;
281 while (*key != '\0' && isspace(*key))
282 ++key;
284 TAILQ_FOREACH(entry, &map->m, keymaps) {
285 if (entry->meta == meta && entry->key == k) {
286 if (*key == '\0') {
287 entry->fn = fn;
288 return;
290 map = &entry->map;
291 goto again;
295 if ((entry = calloc(1, sizeof(*entry))) == NULL)
296 abort();
298 entry->meta = meta;
299 entry->key = k;
300 TAILQ_INIT(&entry->map.m);
302 if (TAILQ_EMPTY(&map->m))
303 TAILQ_INSERT_HEAD(&map->m, entry, keymaps);
304 else
305 TAILQ_INSERT_TAIL(&map->m, entry, keymaps);
307 if (*key != '\0') {
308 map = &entry->map;
309 goto again;
312 entry->fn = fn;
315 static inline void
316 global_set_key(const char *key, void (*fn)(struct tab*))
318 kmap_define_key(&global_map, key, fn);
321 static inline void
322 minibuffer_set_key(const char *key, void (*fn)(struct tab*))
324 kmap_define_key(&minibuffer_map, key, fn);
327 static void
328 load_default_keys(void)
330 /* === global map === */
332 /* emacs */
333 global_set_key("C-p", cmd_previous_line);
334 global_set_key("C-n", cmd_next_line);
335 global_set_key("C-f", cmd_forward_char);
336 global_set_key("C-b", cmd_backward_char);
338 global_set_key("M-v", cmd_scroll_up);
339 global_set_key("C-v", cmd_scroll_down);
341 global_set_key("C-x C-c", cmd_kill_telescope);
343 global_set_key("M-x", cmd_execute_extended_command);
344 global_set_key("C-x C-f", cmd_load_url);
345 global_set_key("C-x M-f", cmd_load_current_url);
347 global_set_key("C-x t 0", cmd_tab_close);
348 global_set_key("C-x t 2", cmd_tab_new);
349 global_set_key("C-x t o", cmd_tab_next);
350 global_set_key("C-x t O", cmd_tab_previous);
352 /* vi/vi-like */
353 global_set_key("k", cmd_previous_line);
354 global_set_key("j", cmd_next_line);
355 global_set_key("l", cmd_forward_char);
356 global_set_key("h", cmd_backward_char);
358 global_set_key("K", cmd_scroll_line_up);
359 global_set_key("J", cmd_scroll_line_down);
361 /* tmp */
362 global_set_key("q", cmd_kill_telescope);
364 global_set_key(":", cmd_execute_extended_command);
366 /* cua */
367 global_set_key("<up>", cmd_previous_line);
368 global_set_key("<down>", cmd_next_line);
369 global_set_key("<right>", cmd_forward_char);
370 global_set_key("<left>", cmd_backward_char);
371 global_set_key("<prior>", cmd_scroll_up);
372 global_set_key("<next>", cmd_scroll_down);
374 /* "ncurses standard" */
375 global_set_key("C-l", cmd_redraw);
377 /* global */
378 global_set_key("C-m", cmd_push_button);
380 /* === minibuffer map === */
381 minibuffer_set_key("ret", cmd_mini_complete_and_exit);
382 minibuffer_set_key("C-g", cmd_mini_abort);
383 minibuffer_set_key("esc", cmd_mini_abort);
384 minibuffer_set_key("del", cmd_mini_del);
386 minibuffer_set_key("C-f", cmd_mini_forward_char);
387 minibuffer_set_key("C-b", cmd_mini_backward_char);
388 minibuffer_set_key("C-e", cmd_mini_move_end_of_line);
389 minibuffer_set_key("C-a", cmd_mini_move_beginning_of_line);
390 minibuffer_set_key("<end>", cmd_mini_move_end_of_line);
391 minibuffer_set_key("<home>", cmd_mini_move_beginning_of_line);
392 minibuffer_set_key("C-k", cmd_mini_kill_line);
395 static int
396 push_line(struct tab *tab, const struct line *l, const char *buf, size_t len)
398 struct line *vl;
400 tab->s->line_max++;
402 if ((vl = calloc(1, sizeof(*vl))) == NULL)
403 return 0;
405 if (len != 0 && (vl->line = calloc(1, len+1)) == NULL) {
406 free(vl);
407 return 0;
410 vl->type = l->type;
411 if (len != 0)
412 memcpy(vl->line, buf, len);
413 vl->alt = l->alt;
415 if (TAILQ_EMPTY(&tab->s->head))
416 TAILQ_INSERT_HEAD(&tab->s->head, vl, lines);
417 else
418 TAILQ_INSERT_TAIL(&tab->s->head, vl, lines);
419 return 1;
422 static void
423 empty_vlist(struct tab *tab)
425 struct line *l, *t;
427 tab->s->line_max = 0;
429 TAILQ_FOREACH_SAFE(l, &tab->s->head, lines, t) {
430 TAILQ_REMOVE(&tab->s->head, l, lines);
431 free(l->line);
432 /* l->alt references the original line! */
433 free(l);
437 static void
438 restore_cursor(struct tab *tab)
440 wmove(body, tab->s->curs_y, tab->s->curs_x);
443 static void
444 cmd_previous_line(struct tab *tab)
446 if (--tab->s->curs_y < 0) {
447 tab->s->curs_y = 0;
448 cmd_scroll_line_up(tab);
451 restore_cursor(tab);
454 static void
455 cmd_next_line(struct tab *tab)
457 if (++tab->s->curs_y > body_lines-1) {
458 tab->s->curs_y = body_lines-1;
459 cmd_scroll_line_down(tab);
462 restore_cursor(tab);
465 static void
466 cmd_forward_char(struct tab *tab)
468 tab->s->curs_x = MIN(body_cols-1, tab->s->curs_x+1);
469 restore_cursor(tab);
472 static void
473 cmd_backward_char(struct tab *tab)
475 tab->s->curs_x = MAX(0, tab->s->curs_x-1);
476 restore_cursor(tab);
479 static void
480 cmd_redraw(struct tab *tab)
482 handle_resize(0, 0, NULL);
485 static void
486 cmd_scroll_line_up(struct tab *tab)
488 struct line *l;
490 if (tab->s->line_off == 0)
491 return;
493 l = nth_line(tab, --tab->s->line_off);
494 wscrl(body, -1);
495 wmove(body, 0, 0);
496 print_line(l);
499 static void
500 cmd_scroll_line_down(struct tab *tab)
502 struct line *l;
503 size_t n;
505 if (tab->s->line_max == 0 || tab->s->line_off == tab->s->line_max-1)
506 return;
508 tab->s->line_off++;
509 wscrl(body, 1);
511 if (tab->s->line_max - tab->s->line_off < body_lines)
512 return;
514 l = nth_line(tab, tab->s->line_off + body_lines-1);
515 wmove(body, body_lines-1, 0);
516 print_line(l);
519 static void
520 cmd_scroll_up(struct tab *tab)
522 size_t off;
524 off = body_lines+1;
526 for (; off > 0; --off)
527 cmd_scroll_line_up(tab);
530 static void
531 cmd_scroll_down(struct tab *tab)
533 ssize_t off;
535 off = tab->s->line_off + body_lines;
536 off = MIN(tab->s->line_max, off);
538 for (; off >= 0; --off)
539 cmd_scroll_line_down(tab);
542 static void
543 cmd_kill_telescope(struct tab *tab)
545 event_loopbreak();
548 static void
549 cmd_push_button(struct tab *tab)
551 struct line *l;
552 size_t nth;
554 nth = tab->s->line_off + tab->s->curs_y;
555 if (nth > tab->s->line_max)
556 return;
557 l = nth_line(tab, nth);
558 if (l->type != LINE_LINK)
559 return;
561 load_url_in_tab(tab, l->alt);
564 static void
565 cmd_execute_extended_command(struct tab *tab)
567 size_t len;
569 enter_minibuffer(eecmd_self_insert, eecmd_select, exit_minibuffer);
571 len = sizeof(ministate.prompt);
572 strlcpy(ministate.prompt, "", len);
574 if (thiskey.meta)
575 strlcat(ministate.prompt, "M-", len);
577 strlcat(ministate.prompt, keyname(thiskey.key), len);
578 strlcat(ministate.prompt, " ", len);
581 static void
582 cmd_tab_close(struct tab *tab)
584 struct tab *t;
586 if (TAILQ_PREV(tab, tabshead, tabs) == NULL &&
587 TAILQ_NEXT(tab, tabs) == NULL) {
588 message("Can't close the only tab.");
589 return;
592 stop_tab(tab);
594 t = TAILQ_PREV(tab, tabshead, tabs);
595 t->flags |= TAB_CURRENT;
597 TAILQ_REMOVE(&tabshead, tab, tabs);
599 free(tab->s);
600 free(tab);
603 static void
604 cmd_tab_new(struct tab *tab)
606 new_tab();
609 static void
610 cmd_tab_next(struct tab *tab)
612 struct tab *t;
614 tab->flags &= ~TAB_CURRENT;
616 if ((t = TAILQ_NEXT(tab, tabs)) == NULL)
617 t = TAILQ_FIRST(&tabshead);
618 t->flags |= TAB_CURRENT;
621 static void
622 cmd_tab_previous(struct tab *tab)
624 struct tab *t;
626 tab->flags &= ~TAB_CURRENT;
628 if ((t = TAILQ_PREV(tab, tabshead, tabs)) == NULL)
629 t = TAILQ_LAST(&tabshead, tabshead);
630 t->flags |= TAB_CURRENT;
633 static void
634 cmd_load_url(struct tab *tab)
636 enter_minibuffer(lu_self_insert, lu_select, exit_minibuffer);
637 strlcpy(ministate.prompt, "Load URL: ", sizeof(ministate.prompt));
640 static void
641 cmd_load_current_url(struct tab *tab)
643 enter_minibuffer(lu_self_insert, lu_select, exit_minibuffer);
644 strlcpy(ministate.prompt, "Load URL: ", sizeof(ministate.prompt));
645 strlcpy(ministate.buf, tab->urlstr, sizeof(ministate.buf));
646 ministate.off = strlen(tab->urlstr);
647 ministate.len = ministate.off;
650 static void
651 global_key_unbound(void)
653 message("%s is undefined", keybuf);
656 static void
657 cmd_mini_del(struct tab *tab)
659 if (ministate.len == 0 || ministate.off == 0)
660 return;
662 memmove(&ministate.buf[ministate.off-1],
663 &ministate.buf[ministate.off],
664 ministate.len - ministate.off + 1);
665 ministate.off--;
666 ministate.len--;
669 static void
670 cmd_mini_forward_char(struct tab *tab)
672 if (ministate.off == ministate.len)
673 return;
674 ministate.off++;
677 static void
678 cmd_mini_backward_char(struct tab *tab)
680 if (ministate.off == 0)
681 return;
682 ministate.off--;
685 static void
686 cmd_mini_move_end_of_line(struct tab *tab)
688 ministate.off = ministate.len;
691 static void
692 cmd_mini_move_beginning_of_line(struct tab *tab)
694 ministate.off = 0;
697 static void
698 cmd_mini_kill_line(struct tab *tab)
700 if (ministate.off == ministate.len)
701 return;
702 ministate.buf[ministate.off] = '\0';
703 ministate.len -= ministate.off;
706 static void
707 cmd_mini_abort(struct tab *tab)
709 ministate.abortfn();
712 static void
713 cmd_mini_complete_and_exit(struct tab *tab)
715 ministate.donefn();
718 static void
719 minibuffer_self_insert(void)
721 if (ministate.len == sizeof(ministate.buf) -1)
722 return;
724 /* TODO: utf8 handling! */
726 memmove(&ministate.buf[ministate.off+1],
727 &ministate.buf[ministate.off],
728 ministate.len - ministate.off + 1);
729 ministate.buf[ministate.off] = thiskey.key;
730 ministate.off++;
731 ministate.len++;
734 static void
735 eecmd_self_insert(void)
737 if (thiskey.meta || isspace(thiskey.key) ||
738 !isgraph(thiskey.key)) {
739 global_key_unbound();
740 return;
743 minibuffer_self_insert();
746 static void
747 eecmd_select(void)
749 exit_minibuffer();
750 message("TODO: try to execute %s", ministate.buf);
753 static void
754 ir_self_insert(void)
756 minibuffer_self_insert();
759 static void
760 ir_select(void)
762 char buf[1025] = {0};
763 struct url url;
764 struct tab *tab;
766 tab = current_tab();
768 exit_minibuffer();
770 /* a bit ugly but... */
771 memcpy(&url, &tab->url, sizeof(tab->url));
772 url_set_query(&url, ministate.buf);
773 url_unparse(&url, buf, sizeof(buf));
774 load_url_in_tab(tab, buf);
777 static void
778 lu_self_insert(void)
780 if (thiskey.meta || isspace(thiskey.key) ||
781 !isgraph(thiskey.key)) {
782 global_key_unbound();
783 return;
786 minibuffer_self_insert();
789 static void
790 lu_select(void)
792 exit_minibuffer();
793 load_url_in_tab(current_tab(), ministate.buf);
796 static struct line *
797 nth_line(struct tab *tab, size_t n)
799 struct line *l;
800 size_t i;
802 i = 0;
803 TAILQ_FOREACH(l, &tab->s->head, lines) {
804 if (i == n)
805 return l;
806 i++;
809 /* unreachable */
810 abort();
813 static struct tab *
814 current_tab(void)
816 struct tab *t;
818 TAILQ_FOREACH(t, &tabshead, tabs) {
819 if (t->flags & TAB_CURRENT)
820 return t;
823 /* unreachable */
824 abort();
827 static void
828 dispatch_stdio(int fd, short ev, void *d)
830 struct tab *tab;
831 struct keymap *k;
832 const char *keyname;
833 char tmp[2] = {0};
835 thiskey.key = wgetch(body);
836 if (thiskey.key == ERR)
837 return;
838 if (thiskey.key == 27) {
839 /* TODO: make escape-time customizable */
841 thiskey.meta = 1;
842 thiskey.key = wgetch(body);
843 if (thiskey.key == ERR)
844 thiskey.key = 27;
845 } else
846 thiskey.meta = 0;
848 if (keybuf[0] != '\0')
849 strlcat(keybuf, " ", sizeof(keybuf));
850 if (thiskey.meta)
851 strlcat(keybuf, "M-", sizeof(keybuf));
852 if ((keyname = unkbd(thiskey.key)) != NULL)
853 strlcat(keybuf, keyname, sizeof(keybuf));
854 else {
855 tmp[0] = thiskey.key;
856 strlcat(keybuf, tmp, sizeof(keybuf));
859 TAILQ_FOREACH(k, &current_map->m, keymaps) {
860 if (k->meta == thiskey.meta &&
861 k->key == thiskey.key) {
862 if (k->fn == NULL)
863 current_map = &k->map;
864 else {
865 current_map = base_map;
866 strlcpy(keybuf, "", sizeof(keybuf));
867 k->fn(current_tab());
869 goto done;
873 if (current_map->unhandled_input != NULL)
874 current_map->unhandled_input();
875 else {
876 global_key_unbound();
879 strlcpy(keybuf, "", sizeof(keybuf));
880 current_map = base_map;
882 done:
883 tab = current_tab();
884 redraw_tabline();
885 redraw_modeline(tab);
886 redraw_minibuffer();
887 restore_cursor(tab);
888 wrefresh(tabline);
889 wrefresh(modeline);
891 if (in_minibuffer) {
892 wrefresh(body);
893 wrefresh(minibuf);
894 } else {
895 wrefresh(minibuf);
896 wrefresh(body);
900 static void
901 handle_clear_minibuf(int fd, short ev, void *d)
903 clminibufev_set = 0;
905 free(ministate.curmesg);
906 ministate.curmesg = NULL;
908 redraw_minibuffer();
909 if (in_minibuffer) {
910 wrefresh(body);
911 wrefresh(minibuf);
912 } else {
913 wrefresh(minibuf);
914 wrefresh(body);
918 static void
919 handle_resize(int sig, short ev, void *d)
921 struct tab *tab;
923 endwin();
924 refresh();
925 clear();
927 /* move and resize the windows, in reverse order! */
929 mvwin(minibuf, LINES-1, 0);
930 wresize(minibuf, 1, COLS);
932 mvwin(modeline, LINES-2, 0);
933 wresize(modeline, 1, COLS);
935 wresize(body, LINES-3, COLS);
936 body_lines = LINES-3;
937 body_cols = COLS;
939 wresize(tabline, 1, COLS);
941 tab = current_tab();
943 wrap_page(tab);
944 redraw_tab(tab);
947 /*
948 * Helper function for wrap_text. Find the end of the current word
949 * and the end of the separator after the word.
950 */
951 static int
952 word_boundaries(const char *s, const char *sep, const char **endword, const char **endspc)
954 *endword = s;
955 *endword = s;
957 if (*s == '\0')
958 return 0;
960 /* find the end of the current world */
961 for (; *s != '\0'; ++s) {
962 if (strchr(sep, *s) != NULL)
963 break;
966 *endword = s;
968 /* find the end of the separator */
969 for (; *s != '\0'; ++s) {
970 if (strchr(sep, *s) == NULL)
971 break;
974 *endspc = s;
976 return 1;
979 static inline int
980 emitline(struct tab *tab, size_t zero, size_t *off, const struct line *l,
981 const char **line)
983 if (!push_line(tab, l, *line, *off - zero))
984 return 0;
985 *line += *off - zero;
986 *off = zero;
987 return 1;
990 static inline void
991 emitstr(const char **s, size_t len, size_t *off)
993 size_t i;
995 /* printw("%*s", ...) doesn't seem to respect the precision, so... */
996 for (i = 0; i < len; ++i)
997 addch((*s)[i]);
998 *off += len;
999 *s += len;
1003 * Build a list of visual line by wrapping the given line, assuming
1004 * that when printed will have a leading prefix prfx.
1006 * TODO: it considers each byte one cell on the screen!
1008 static void
1009 wrap_text(struct tab *tab, const char *prfx, struct line *l)
1011 size_t zero, off, len, split;
1012 const char *endword, *endspc, *line, *linestart;
1014 zero = strlen(prfx);
1015 off = zero;
1016 line = l->line;
1017 linestart = l->line;
1019 while (word_boundaries(line, " \t-", &endword, &endspc)) {
1020 len = endword - line;
1021 if (off + len >= body_cols) {
1022 emitline(tab, zero, &off, l, &linestart);
1023 while (len >= body_cols) {
1024 /* hard wrap */
1025 emitline(tab, zero, &off, l, &linestart);
1026 len -= body_cols-1;
1027 line += body_cols-1;
1030 if (len != 0)
1031 off += len;
1032 } else
1033 off += len;
1035 /* print the spaces iff not at bol */
1036 len = endspc - endword;
1037 /* line = endspc; */
1038 if (off != zero) {
1039 if (off + len >= body_cols) {
1040 emitline(tab, zero, &off, l, &linestart);
1041 linestart = endspc;
1042 } else
1043 off += len;
1046 line = endspc;
1049 emitline(tab, zero, &off, l, &linestart);
1052 static int
1053 hardwrap_text(struct tab *tab, struct line *l)
1055 size_t off, len;
1056 const char *linestart;
1058 len = strlen(l->line);
1059 off = 0;
1060 linestart = l->line;
1062 while (len >= COLS) {
1063 len -= COLS-1;
1064 off = COLS-1;
1065 if (!emitline(tab, 0, &off, l, &linestart))
1066 return 0;
1069 if (len != 0)
1070 return emitline(tab, 0, &len, l, &linestart);
1072 return 1;
1075 static int
1076 wrap_page(struct tab *tab)
1078 struct line *l;
1080 empty_vlist(tab);
1082 TAILQ_FOREACH(l, &tab->page.head, lines) {
1083 switch (l->type) {
1084 case LINE_TEXT:
1085 wrap_text(tab, "", l);
1086 break;
1087 case LINE_LINK:
1088 wrap_text(tab, "=> ", l);
1089 break;
1090 case LINE_TITLE_1:
1091 wrap_text(tab, "# ", l);
1092 break;
1093 case LINE_TITLE_2:
1094 wrap_text(tab, "## ", l);
1095 break;
1096 case LINE_TITLE_3:
1097 wrap_text(tab, "### ", l);
1098 break;
1099 case LINE_ITEM:
1100 wrap_text(tab, "* ", l);
1101 break;
1102 case LINE_QUOTE:
1103 wrap_text(tab, "> ", l);
1104 break;
1105 case LINE_PRE_START:
1106 case LINE_PRE_END:
1107 push_line(tab, l, NULL, 0);
1108 break;
1109 case LINE_PRE_CONTENT:
1110 hardwrap_text(tab, l);
1111 break;
1114 return 1;
1117 static inline void
1118 print_line(struct line *l)
1120 const char *text = l->line;
1122 if (text == NULL)
1123 text = "";
1125 switch (l->type) {
1126 case LINE_TEXT:
1127 wprintw(body, "%s", text);
1128 break;
1129 case LINE_LINK:
1130 wattron(body, A_UNDERLINE);
1131 wprintw(body, "=> %s", text);
1132 wattroff(body, A_UNDERLINE);
1133 return;
1134 case LINE_TITLE_1:
1135 wattron(body, A_BOLD);
1136 wprintw(body, "# %s", text);
1137 wattroff(body, A_BOLD);
1138 return;
1139 case LINE_TITLE_2:
1140 wattron(body, A_BOLD);
1141 wprintw(body, "## %s", text);
1142 wattroff(body, A_BOLD);
1143 return;
1144 case LINE_TITLE_3:
1145 wattron(body, A_BOLD);
1146 wprintw(body, "### %s", text);
1147 wattroff(body, A_BOLD);
1148 return;
1149 case LINE_ITEM:
1150 wprintw(body, "* %s", text);
1151 return;
1152 case LINE_QUOTE:
1153 wattron(body, A_DIM);
1154 wprintw(body, "> %s", text);
1155 wattroff(body, A_DIM);
1156 return;
1157 case LINE_PRE_START:
1158 case LINE_PRE_END:
1159 wprintw(body, "```");
1160 return;
1161 case LINE_PRE_CONTENT:
1162 wprintw(body, "%s", text);
1163 return;
1167 static void
1168 redraw_tabline(void)
1170 struct tab *tab;
1171 int current;
1173 wclear(tabline);
1174 wbkgd(tabline, A_REVERSE);
1176 wprintw(tabline, " ");
1177 TAILQ_FOREACH(tab, &tabshead, tabs) {
1178 current = tab->flags & TAB_CURRENT;
1179 wprintw(tabline, " %s%d:todo title ",
1180 current ? "*" : "", tab->id);
1184 static void
1185 redraw_modeline(struct tab *tab)
1187 double pct;
1188 int x, y, max_x, max_y;
1189 const char *mode = "text/gemini-mode";
1190 const char *spin = "-\\|/";
1192 wclear(modeline);
1193 wattron(modeline, A_REVERSE);
1194 wmove(modeline, 0, 0);
1196 wprintw(modeline, "-%c %s ",
1197 spin[tab->s->loading_anim_step], mode);
1199 pct = (tab->s->line_off + tab->s->curs_y) * 100.0 / tab->s->line_max;
1201 if (tab->s->line_max <= body_lines)
1202 wprintw(modeline, "All ");
1203 else if (tab->s->line_off == 0)
1204 wprintw(modeline, "Top ");
1205 else if (tab->s->line_off + body_lines >= tab->s->line_max)
1206 wprintw(modeline, "Bottom ");
1207 else
1208 wprintw(modeline, "%.0f%% ", pct);
1210 wprintw(modeline, "%d/%d %s ",
1211 tab->s->line_off + tab->s->curs_y,
1212 tab->s->line_max,
1213 tab->urlstr);
1215 getyx(modeline, y, x);
1216 getmaxyx(modeline, max_y, max_x);
1218 (void)y;
1219 (void)max_y;
1221 for (; x < max_x; ++x)
1222 waddstr(modeline, "-");
1225 static void
1226 redraw_minibuffer(void)
1228 size_t skip = 0, off = 0;
1230 wclear(minibuf);
1231 if (!in_minibuffer)
1232 goto message;
1234 off = strlen(ministate.prompt);
1236 while (ministate.off - skip > COLS / 2) {
1237 skip += MIN(ministate.off/4, 1);
1240 mvwprintw(minibuf, 0, 0, "%s%s", ministate.prompt,
1241 ministate.buf + skip);
1243 message:
1244 if (ministate.curmesg != NULL) {
1245 if (in_minibuffer)
1246 wprintw(minibuf, " [%s]", ministate.curmesg);
1247 else
1248 wprintw(minibuf, "%s", ministate.curmesg);
1251 wmove(minibuf, 0, off + ministate.off - skip);
1254 static void
1255 redraw_tab(struct tab *tab)
1257 struct line *l;
1258 int line;
1260 werase(body);
1262 tab->s->line_off = MIN(tab->s->line_max, tab->s->line_off);
1263 if (TAILQ_EMPTY(&tab->s->head))
1264 return;
1266 line = 0;
1267 l = nth_line(tab, tab->s->line_off);
1268 for (; l != NULL; l = TAILQ_NEXT(l, lines)) {
1269 wmove(body, line, 0);
1270 print_line(l);
1271 line++;
1272 if (line == body_lines)
1273 break;
1276 redraw_tabline();
1277 redraw_modeline(tab);
1278 redraw_minibuffer();
1280 restore_cursor(tab);
1281 wrefresh(tabline);
1282 wrefresh(modeline);
1284 if (in_minibuffer) {
1285 wrefresh(body);
1286 wrefresh(minibuf);
1287 } else {
1288 wrefresh(minibuf);
1289 wrefresh(body);
1293 static void
1294 message(const char *fmt, ...)
1296 va_list ap;
1298 if (clminibufev_set)
1299 evtimer_del(&clminibufev);
1300 evtimer_set(&clminibufev, handle_clear_minibuf, NULL);
1301 evtimer_add(&clminibufev, &clminibufev_timer);
1302 clminibufev_set = 1;
1304 va_start(ap, fmt);
1305 /* TODO: what to do if the allocation fails here? */
1306 if (vasprintf(&ministate.curmesg, fmt, ap) == -1)
1307 ministate.curmesg = NULL;
1308 va_end(ap);
1310 redraw_minibuffer();
1312 if (in_minibuffer) {
1313 wrefresh(body);
1314 wrefresh(minibuf);
1315 } else {
1316 wrefresh(minibuf);
1317 wrefresh(body);
1321 static void
1322 start_loading_anim(struct tab *tab)
1324 if (tab->s->loading_anim)
1325 return;
1326 tab->s->loading_anim = 1;
1327 evtimer_set(&tab->s->loadingev, update_loading_anim, tab);
1328 evtimer_add(&tab->s->loadingev, &loadingev_timer);
1331 static void
1332 update_loading_anim(int fd, short ev, void *d)
1334 struct tab *tab = d;
1336 tab->s->loading_anim_step = (tab->s->loading_anim_step+1)%4;
1338 redraw_modeline(tab);
1339 wrefresh(modeline);
1341 wrefresh(body);
1342 if (in_minibuffer)
1343 wrefresh(minibuf);
1345 evtimer_add(&tab->s->loadingev, &loadingev_timer);
1348 static void
1349 stop_loading_anim(struct tab *tab)
1351 if (!tab->s->loading_anim)
1352 return;
1353 evtimer_del(&tab->s->loadingev);
1354 tab->s->loading_anim = 0;
1355 tab->s->loading_anim_step = 0;
1357 redraw_modeline(tab);
1359 wrefresh(modeline);
1360 wrefresh(body);
1361 if (in_minibuffer)
1362 wrefresh(minibuf);
1365 static void
1366 load_url_in_tab(struct tab *tab, const char *url)
1368 empty_vlist(tab);
1369 message("Loading %s...", url);
1370 start_loading_anim(tab);
1371 load_url(tab, url);
1373 tab->s->curs_x = 0;
1374 tab->s->curs_y = 0;
1375 redraw_tab(tab);
1378 static void
1379 enter_minibuffer(void (*self_insert_fn)(void), void (*donefn)(void),
1380 void (*abortfn)(void))
1382 in_minibuffer = 1;
1383 base_map = &minibuffer_map;
1384 current_map = &minibuffer_map;
1386 base_map->unhandled_input = self_insert_fn;
1388 ministate.donefn = donefn;
1389 ministate.abortfn = abortfn;
1390 memset(ministate.buf, 0, sizeof(ministate.buf));
1391 ministate.off = 0;
1392 strlcpy(ministate.buf, "", sizeof(ministate.prompt));
1395 static void
1396 exit_minibuffer(void)
1398 wclear(minibuf);
1400 in_minibuffer = 0;
1401 base_map = &global_map;
1402 current_map = &global_map;
1405 static void
1406 switch_to_tab(struct tab *tab)
1408 struct tab *t;
1410 TAILQ_FOREACH(t, &tabshead, tabs) {
1411 t->flags &= ~TAB_CURRENT;
1414 tab->flags |= TAB_CURRENT;
1417 static void
1418 new_tab(void)
1420 struct tab *tab, *t;
1421 const char *url = "about:new";
1423 if ((tab = calloc(1, sizeof(*tab))) == NULL)
1424 goto err;
1426 if ((tab->s = calloc(1, sizeof(*t->s))) == NULL)
1427 goto err;
1429 TAILQ_INIT(&tab->s->head);
1431 tab->id = tab_counter++;
1432 switch_to_tab(tab);
1434 if (TAILQ_EMPTY(&tabshead))
1435 TAILQ_INSERT_HEAD(&tabshead, tab, tabs);
1436 else
1437 TAILQ_INSERT_TAIL(&tabshead, tab, tabs);
1439 load_url_in_tab(tab, url);
1440 return;
1442 err:
1443 event_loopbreak();
1446 int
1447 ui_init(void)
1449 setlocale(LC_ALL, "");
1451 TAILQ_INIT(&global_map.m);
1452 global_map.unhandled_input = global_key_unbound;
1454 TAILQ_INIT(&minibuffer_map.m);
1456 base_map = &global_map;
1457 current_map = &global_map;
1458 load_default_keys();
1460 initscr();
1461 raw();
1462 noecho();
1464 nonl();
1465 intrflush(stdscr, FALSE);
1467 if ((tabline = newwin(1, COLS, 0, 0)) == NULL)
1468 return 0;
1469 if ((body = newwin(LINES - 3, COLS, 1, 0)) == NULL)
1470 return 0;
1471 if ((modeline = newwin(1, COLS, LINES-2, 0)) == NULL)
1472 return 0;
1473 if ((minibuf = newwin(1, COLS, LINES-1, 0)) == NULL)
1474 return 0;
1476 body_lines = LINES-3;
1477 body_cols = COLS;
1479 keypad(body, TRUE);
1480 scrollok(body, TRUE);
1482 /* non-blocking input */
1483 wtimeout(body, 0);
1485 mvwprintw(body, 0, 0, "");
1487 event_set(&stdioev, 0, EV_READ | EV_PERSIST, dispatch_stdio, NULL);
1488 event_add(&stdioev, NULL);
1490 signal_set(&winchev, SIGWINCH, handle_resize, NULL);
1491 signal_add(&winchev, NULL);
1493 new_tab();
1495 return 1;
1498 void
1499 ui_on_tab_loaded(struct tab *tab)
1501 stop_loading_anim(tab);
1502 message("Loaded %s", tab->urlstr);
1505 void
1506 ui_on_tab_refresh(struct tab *tab)
1508 if (!(tab->flags & TAB_CURRENT))
1509 return;
1511 wrap_page(tab);
1512 redraw_tab(tab);
1515 void
1516 ui_require_input(struct tab *tab, int hide)
1518 /* TODO: hard-switching to another tab is ugly */
1519 switch_to_tab(tab);
1521 enter_minibuffer(ir_self_insert, ir_select, exit_minibuffer);
1522 strlcpy(ministate.prompt, "Input required: ",
1523 sizeof(ministate.prompt));
1524 redraw_tab(tab);
1527 void
1528 ui_end(void)
1530 endwin();