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_beginning_of_buffer(struct tab*);
97 static void cmd_end_of_buffer(struct tab*);
98 static void cmd_kill_telescope(struct tab*);
99 static void cmd_push_button(struct tab*);
100 static void cmd_execute_extended_command(struct tab*);
101 static void cmd_tab_close(struct tab*);
102 static void cmd_tab_new(struct tab*);
103 static void cmd_tab_next(struct tab*);
104 static void cmd_tab_previous(struct tab*);
105 static void cmd_load_url(struct tab*);
106 static void cmd_load_current_url(struct tab*);
108 static void global_key_unbound(void);
110 static void cmd_mini_del(struct tab*);
111 static void cmd_mini_forward_char(struct tab*);
112 static void cmd_mini_backward_char(struct tab*);
113 static void cmd_mini_move_end_of_line(struct tab*);
114 static void cmd_mini_move_beginning_of_line(struct tab*);
115 static void cmd_mini_kill_line(struct tab*);
116 static void cmd_mini_abort();
117 static void cmd_mini_complete_and_exit();
119 static void minibuffer_self_insert(void);
120 static void eecmd_self_insert(void);
121 static void eecmd_select(void);
122 static void ir_self_insert(void);
123 static void ir_select(void);
124 static void lu_self_insert(void);
125 static void lu_select(void);
127 static struct line *nth_line(struct tab*, size_t);
128 static struct tab *current_tab(void);
129 static void dispatch_stdio(int, short, void*);
130 static void handle_clear_minibuf(int, short, void*);
131 static void handle_resize(int, short, void*);
132 static int word_bourdaries(const char*, const char*, const char**, const char**);
133 static void wrap_text(struct tab*, const char*, struct line*);
134 static int hardwrap_text(struct tab*, struct line*);
135 static int wrap_page(struct tab*);
136 static void print_line(struct line*);
137 static void redraw_tabline(void);
138 static void redraw_body(struct tab*);
139 static void redraw_modeline(struct tab*);
140 static void redraw_minibuffer(void);
141 static void redraw_tab(struct tab*);
142 static void message(const char*, ...) __attribute__((format(printf, 1, 2)));
143 static void start_loading_anim(struct tab*);
144 static void update_loading_anim(int, short, void*);
145 static void stop_loading_anim(struct tab*);
146 static void load_url_in_tab(struct tab*, const char*);
147 static void enter_minibuffer(void(*)(void), void(*)(void), void(*)(void));
148 static void exit_minibuffer(void);
149 static void switch_to_tab(struct tab*);
150 static void new_tab(void);
152 static struct { int meta, key; } thiskey;
154 static WINDOW *tabline, *body, *modeline, *minibuf;
155 static int body_lines, body_cols;
157 static struct event clminibufev;
158 static int clminibufev_set;
159 static struct timeval clminibufev_timer = { 5, 0 };
160 static struct timeval loadingev_timer = { 0, 250000 };
162 static uint32_t tab_counter;
164 struct ui_state {
165 int curs_x;
166 int curs_y;
167 size_t line_off;
168 size_t line_max;
170 short loading_anim;
171 short loading_anim_step;
172 struct event loadingev;
174 TAILQ_HEAD(, line) head;
175 };
177 static char keybuf[64];
179 #define CTRL(n) ((n)&0x1F)
181 struct keytable {
182 char *p;
183 int k;
184 } keytable[] = {
185 { "<up>", KEY_UP },
186 { "<down>", KEY_DOWN },
187 { "<left>", KEY_LEFT },
188 { "<right>", KEY_RIGHT },
189 { "<prior>", KEY_PPAGE },
190 { "<next>", KEY_NPAGE },
191 { "<home>", KEY_HOME },
192 { "<end>", KEY_END },
193 /* ... */
194 { "del", KEY_BACKSPACE },
195 { "esc", 27 },
196 { "space", ' ' },
197 { "spc", ' ' },
198 { "enter", CTRL('m') },
199 { "ret", CTRL('m' )},
200 { "tab", CTRL('i') },
201 /* ... */
202 { NULL, 0 },
203 };
205 struct kmap {
206 TAILQ_HEAD(map, keymap) m;
207 void (*unhandled_input)(void);
208 };
210 struct kmap global_map,
211 minibuffer_map,
212 *current_map,
213 *base_map;
215 struct keymap {
216 int meta;
217 int key;
218 struct kmap map;
219 void (*fn)(struct tab*);
221 TAILQ_ENTRY(keymap) keymaps;
222 };
224 static int in_minibuffer;
226 static struct {
227 char *curmesg;
229 char buf[1025];
230 size_t off, len;
231 char prompt[32];
232 void (*donefn)(void);
233 void (*abortfn)(void);
234 } ministate;
236 static int
237 kbd(const char *key)
239 struct keytable *t;
241 for (t = keytable; t->p != NULL; ++t) {
242 if (has_prefix(key, t->p))
243 return t->k;
246 return *key;
249 static const char *
250 unkbd(int k)
252 struct keytable *t;
254 for (t = keytable; t->p != NULL; ++t) {
255 if (k == t->k)
256 return t->p;
259 return NULL;
262 static void
263 kmap_define_key(struct kmap *map, const char *key, void (*fn)(struct tab*))
265 int ctrl, meta, k;
266 struct keymap *entry;
268 again:
269 if ((ctrl = has_prefix(key, "C-")))
270 key += 2;
271 if ((meta = has_prefix(key, "M-")))
272 key += 2;
273 if (*key == '\0')
274 _exit(1);
275 k = kbd(key);
277 if (ctrl)
278 k = CTRL(k);
280 /* skip key & spaces */
281 while (*key != '\0' && !isspace(*key))
282 ++key;
283 while (*key != '\0' && isspace(*key))
284 ++key;
286 TAILQ_FOREACH(entry, &map->m, keymaps) {
287 if (entry->meta == meta && entry->key == k) {
288 if (*key == '\0') {
289 entry->fn = fn;
290 return;
292 map = &entry->map;
293 goto again;
297 if ((entry = calloc(1, sizeof(*entry))) == NULL)
298 abort();
300 entry->meta = meta;
301 entry->key = k;
302 TAILQ_INIT(&entry->map.m);
304 if (TAILQ_EMPTY(&map->m))
305 TAILQ_INSERT_HEAD(&map->m, entry, keymaps);
306 else
307 TAILQ_INSERT_TAIL(&map->m, entry, keymaps);
309 if (*key != '\0') {
310 map = &entry->map;
311 goto again;
314 entry->fn = fn;
317 static inline void
318 global_set_key(const char *key, void (*fn)(struct tab*))
320 kmap_define_key(&global_map, key, fn);
323 static inline void
324 minibuffer_set_key(const char *key, void (*fn)(struct tab*))
326 kmap_define_key(&minibuffer_map, key, fn);
329 static void
330 load_default_keys(void)
332 /* === global map === */
334 /* emacs */
335 global_set_key("C-p", cmd_previous_line);
336 global_set_key("C-n", cmd_next_line);
337 global_set_key("C-f", cmd_forward_char);
338 global_set_key("C-b", cmd_backward_char);
340 global_set_key("M-v", cmd_scroll_up);
341 global_set_key("C-v", cmd_scroll_down);
343 global_set_key("C-x C-c", cmd_kill_telescope);
345 global_set_key("M-x", cmd_execute_extended_command);
346 global_set_key("C-x C-f", cmd_load_url);
347 global_set_key("C-x M-f", cmd_load_current_url);
349 global_set_key("C-x t 0", cmd_tab_close);
350 global_set_key("C-x t 2", cmd_tab_new);
351 global_set_key("C-x t o", cmd_tab_next);
352 global_set_key("C-x t O", cmd_tab_previous);
354 global_set_key("M-<", cmd_beginning_of_buffer);
355 global_set_key("M->", cmd_end_of_buffer);
357 /* vi/vi-like */
358 global_set_key("k", cmd_previous_line);
359 global_set_key("j", cmd_next_line);
360 global_set_key("l", cmd_forward_char);
361 global_set_key("h", cmd_backward_char);
363 global_set_key("K", cmd_scroll_line_up);
364 global_set_key("J", cmd_scroll_line_down);
366 global_set_key("g g", cmd_beginning_of_buffer);
367 global_set_key("G", cmd_end_of_buffer);
369 /* tmp */
370 global_set_key("q", cmd_kill_telescope);
372 global_set_key(":", cmd_execute_extended_command);
374 /* cua */
375 global_set_key("<up>", cmd_previous_line);
376 global_set_key("<down>", cmd_next_line);
377 global_set_key("<right>", cmd_forward_char);
378 global_set_key("<left>", cmd_backward_char);
379 global_set_key("<prior>", cmd_scroll_up);
380 global_set_key("<next>", cmd_scroll_down);
382 /* "ncurses standard" */
383 global_set_key("C-l", cmd_redraw);
385 /* global */
386 global_set_key("C-m", cmd_push_button);
388 /* === minibuffer map === */
389 minibuffer_set_key("ret", cmd_mini_complete_and_exit);
390 minibuffer_set_key("C-g", cmd_mini_abort);
391 minibuffer_set_key("esc", cmd_mini_abort);
392 minibuffer_set_key("del", cmd_mini_del);
394 minibuffer_set_key("C-f", cmd_mini_forward_char);
395 minibuffer_set_key("C-b", cmd_mini_backward_char);
396 minibuffer_set_key("C-e", cmd_mini_move_end_of_line);
397 minibuffer_set_key("C-a", cmd_mini_move_beginning_of_line);
398 minibuffer_set_key("<end>", cmd_mini_move_end_of_line);
399 minibuffer_set_key("<home>", cmd_mini_move_beginning_of_line);
400 minibuffer_set_key("C-k", cmd_mini_kill_line);
403 static int
404 push_line(struct tab *tab, const struct line *l, const char *buf, size_t len)
406 struct line *vl;
408 tab->s->line_max++;
410 if ((vl = calloc(1, sizeof(*vl))) == NULL)
411 return 0;
413 if (len != 0 && (vl->line = calloc(1, len+1)) == NULL) {
414 free(vl);
415 return 0;
418 vl->type = l->type;
419 if (len != 0)
420 memcpy(vl->line, buf, len);
421 vl->alt = l->alt;
423 if (TAILQ_EMPTY(&tab->s->head))
424 TAILQ_INSERT_HEAD(&tab->s->head, vl, lines);
425 else
426 TAILQ_INSERT_TAIL(&tab->s->head, vl, lines);
427 return 1;
430 static void
431 empty_vlist(struct tab *tab)
433 struct line *l, *t;
435 tab->s->line_max = 0;
437 TAILQ_FOREACH_SAFE(l, &tab->s->head, lines, t) {
438 TAILQ_REMOVE(&tab->s->head, l, lines);
439 free(l->line);
440 /* l->alt references the original line! */
441 free(l);
445 static void
446 restore_cursor(struct tab *tab)
448 wmove(body, tab->s->curs_y, tab->s->curs_x);
451 static void
452 cmd_previous_line(struct tab *tab)
454 if (--tab->s->curs_y < 0) {
455 tab->s->curs_y = 0;
456 cmd_scroll_line_up(tab);
459 restore_cursor(tab);
462 static void
463 cmd_next_line(struct tab *tab)
465 if (tab->s->line_off + tab->s->curs_y >= tab->s->line_max)
466 return;
468 if (++tab->s->curs_y > body_lines-1) {
469 tab->s->curs_y = body_lines-1;
470 cmd_scroll_line_down(tab);
473 restore_cursor(tab);
476 static void
477 cmd_forward_char(struct tab *tab)
479 tab->s->curs_x = MIN(body_cols-1, tab->s->curs_x+1);
480 restore_cursor(tab);
483 static void
484 cmd_backward_char(struct tab *tab)
486 tab->s->curs_x = MAX(0, tab->s->curs_x-1);
487 restore_cursor(tab);
490 static void
491 cmd_redraw(struct tab *tab)
493 handle_resize(0, 0, NULL);
496 static void
497 cmd_scroll_line_up(struct tab *tab)
499 struct line *l;
501 if (tab->s->line_off == 0)
502 return;
504 l = nth_line(tab, --tab->s->line_off);
505 wscrl(body, -1);
506 wmove(body, 0, 0);
507 print_line(l);
510 static void
511 cmd_scroll_line_down(struct tab *tab)
513 struct line *l;
514 size_t n;
516 if (tab->s->line_max == 0 || tab->s->line_off == tab->s->line_max-1)
517 return;
519 tab->s->line_off++;
520 wscrl(body, 1);
522 if (tab->s->line_max - tab->s->line_off < body_lines)
523 return;
525 l = nth_line(tab, tab->s->line_off + body_lines-1);
526 wmove(body, body_lines-1, 0);
527 print_line(l);
530 static void
531 cmd_scroll_up(struct tab *tab)
533 size_t off;
535 off = body_lines+1;
537 for (; off > 0; --off)
538 cmd_scroll_line_up(tab);
541 static void
542 cmd_scroll_down(struct tab *tab)
544 ssize_t off;
546 off = tab->s->line_off + body_lines;
547 off = MIN(tab->s->line_max, off);
549 for (; off >= 0; --off)
550 cmd_scroll_line_down(tab);
553 static void
554 cmd_beginning_of_buffer(struct tab *tab)
556 tab->s->line_off = 0;
557 tab->s->curs_y = 0;
558 redraw_body(tab);
561 static void
562 cmd_end_of_buffer(struct tab *tab)
564 ssize_t off;
566 off = tab->s->line_max - body_lines;
567 off = MAX(0, off);
569 tab->s->line_off = off;
570 tab->s->curs_y = MIN(body_lines, tab->s->line_max);
572 redraw_body(tab);
575 static void
576 cmd_kill_telescope(struct tab *tab)
578 event_loopbreak();
581 static void
582 cmd_push_button(struct tab *tab)
584 struct line *l;
585 size_t nth;
587 nth = tab->s->line_off + tab->s->curs_y;
588 if (nth > tab->s->line_max)
589 return;
590 l = nth_line(tab, nth);
591 if (l->type != LINE_LINK)
592 return;
594 load_url_in_tab(tab, l->alt);
597 static void
598 cmd_execute_extended_command(struct tab *tab)
600 size_t len;
602 enter_minibuffer(eecmd_self_insert, eecmd_select, exit_minibuffer);
604 len = sizeof(ministate.prompt);
605 strlcpy(ministate.prompt, "", len);
607 if (thiskey.meta)
608 strlcat(ministate.prompt, "M-", len);
610 strlcat(ministate.prompt, keyname(thiskey.key), len);
611 strlcat(ministate.prompt, " ", len);
614 static void
615 cmd_tab_close(struct tab *tab)
617 struct tab *t;
619 if (TAILQ_PREV(tab, tabshead, tabs) == NULL &&
620 TAILQ_NEXT(tab, tabs) == NULL) {
621 message("Can't close the only tab.");
622 return;
625 stop_tab(tab);
627 t = TAILQ_PREV(tab, tabshead, tabs);
628 t->flags |= TAB_CURRENT;
630 TAILQ_REMOVE(&tabshead, tab, tabs);
632 free(tab->s);
633 free(tab);
636 static void
637 cmd_tab_new(struct tab *tab)
639 new_tab();
642 static void
643 cmd_tab_next(struct tab *tab)
645 struct tab *t;
647 tab->flags &= ~TAB_CURRENT;
649 if ((t = TAILQ_NEXT(tab, tabs)) == NULL)
650 t = TAILQ_FIRST(&tabshead);
651 t->flags |= TAB_CURRENT;
654 static void
655 cmd_tab_previous(struct tab *tab)
657 struct tab *t;
659 tab->flags &= ~TAB_CURRENT;
661 if ((t = TAILQ_PREV(tab, tabshead, tabs)) == NULL)
662 t = TAILQ_LAST(&tabshead, tabshead);
663 t->flags |= TAB_CURRENT;
666 static void
667 cmd_load_url(struct tab *tab)
669 enter_minibuffer(lu_self_insert, lu_select, exit_minibuffer);
670 strlcpy(ministate.prompt, "Load URL: ", sizeof(ministate.prompt));
673 static void
674 cmd_load_current_url(struct tab *tab)
676 enter_minibuffer(lu_self_insert, lu_select, exit_minibuffer);
677 strlcpy(ministate.prompt, "Load URL: ", sizeof(ministate.prompt));
678 strlcpy(ministate.buf, tab->urlstr, sizeof(ministate.buf));
679 ministate.off = strlen(tab->urlstr);
680 ministate.len = ministate.off;
683 static void
684 global_key_unbound(void)
686 message("%s is undefined", keybuf);
689 static void
690 cmd_mini_del(struct tab *tab)
692 if (ministate.len == 0 || ministate.off == 0)
693 return;
695 memmove(&ministate.buf[ministate.off-1],
696 &ministate.buf[ministate.off],
697 ministate.len - ministate.off + 1);
698 ministate.off--;
699 ministate.len--;
702 static void
703 cmd_mini_forward_char(struct tab *tab)
705 if (ministate.off == ministate.len)
706 return;
707 ministate.off++;
710 static void
711 cmd_mini_backward_char(struct tab *tab)
713 if (ministate.off == 0)
714 return;
715 ministate.off--;
718 static void
719 cmd_mini_move_end_of_line(struct tab *tab)
721 ministate.off = ministate.len;
724 static void
725 cmd_mini_move_beginning_of_line(struct tab *tab)
727 ministate.off = 0;
730 static void
731 cmd_mini_kill_line(struct tab *tab)
733 if (ministate.off == ministate.len)
734 return;
735 ministate.buf[ministate.off] = '\0';
736 ministate.len -= ministate.off;
739 static void
740 cmd_mini_abort(struct tab *tab)
742 ministate.abortfn();
745 static void
746 cmd_mini_complete_and_exit(struct tab *tab)
748 ministate.donefn();
751 static void
752 minibuffer_self_insert(void)
754 if (ministate.len == sizeof(ministate.buf) -1)
755 return;
757 /* TODO: utf8 handling! */
759 memmove(&ministate.buf[ministate.off+1],
760 &ministate.buf[ministate.off],
761 ministate.len - ministate.off + 1);
762 ministate.buf[ministate.off] = thiskey.key;
763 ministate.off++;
764 ministate.len++;
767 static void
768 eecmd_self_insert(void)
770 if (thiskey.meta || isspace(thiskey.key) ||
771 !isgraph(thiskey.key)) {
772 global_key_unbound();
773 return;
776 minibuffer_self_insert();
779 static void
780 eecmd_select(void)
782 exit_minibuffer();
783 message("TODO: try to execute %s", ministate.buf);
786 static void
787 ir_self_insert(void)
789 minibuffer_self_insert();
792 static void
793 ir_select(void)
795 char buf[1025] = {0};
796 struct url url;
797 struct tab *tab;
799 tab = current_tab();
801 exit_minibuffer();
803 /* a bit ugly but... */
804 memcpy(&url, &tab->url, sizeof(tab->url));
805 url_set_query(&url, ministate.buf);
806 url_unparse(&url, buf, sizeof(buf));
807 load_url_in_tab(tab, buf);
810 static void
811 lu_self_insert(void)
813 if (thiskey.meta || isspace(thiskey.key) ||
814 !isgraph(thiskey.key)) {
815 global_key_unbound();
816 return;
819 minibuffer_self_insert();
822 static void
823 lu_select(void)
825 exit_minibuffer();
826 load_url_in_tab(current_tab(), ministate.buf);
829 static struct line *
830 nth_line(struct tab *tab, size_t n)
832 struct line *l;
833 size_t i;
835 i = 0;
836 TAILQ_FOREACH(l, &tab->s->head, lines) {
837 if (i == n)
838 return l;
839 i++;
842 /* unreachable */
843 abort();
846 static struct tab *
847 current_tab(void)
849 struct tab *t;
851 TAILQ_FOREACH(t, &tabshead, tabs) {
852 if (t->flags & TAB_CURRENT)
853 return t;
856 /* unreachable */
857 abort();
860 static void
861 dispatch_stdio(int fd, short ev, void *d)
863 struct tab *tab;
864 struct keymap *k;
865 const char *keyname;
866 char tmp[2] = {0};
868 thiskey.key = wgetch(body);
869 if (thiskey.key == ERR)
870 return;
871 if (thiskey.key == 27) {
872 /* TODO: make escape-time customizable */
874 thiskey.meta = 1;
875 thiskey.key = wgetch(body);
876 if (thiskey.key == ERR)
877 thiskey.key = 27;
878 } else
879 thiskey.meta = 0;
881 if (keybuf[0] != '\0')
882 strlcat(keybuf, " ", sizeof(keybuf));
883 if (thiskey.meta)
884 strlcat(keybuf, "M-", sizeof(keybuf));
885 if ((keyname = unkbd(thiskey.key)) != NULL)
886 strlcat(keybuf, keyname, sizeof(keybuf));
887 else {
888 tmp[0] = thiskey.key;
889 strlcat(keybuf, tmp, sizeof(keybuf));
892 TAILQ_FOREACH(k, &current_map->m, keymaps) {
893 if (k->meta == thiskey.meta &&
894 k->key == thiskey.key) {
895 if (k->fn == NULL)
896 current_map = &k->map;
897 else {
898 current_map = base_map;
899 strlcpy(keybuf, "", sizeof(keybuf));
900 k->fn(current_tab());
902 goto done;
906 if (current_map->unhandled_input != NULL)
907 current_map->unhandled_input();
908 else {
909 global_key_unbound();
912 strlcpy(keybuf, "", sizeof(keybuf));
913 current_map = base_map;
915 done:
916 tab = current_tab();
917 redraw_tabline();
918 redraw_modeline(tab);
919 redraw_minibuffer();
920 restore_cursor(tab);
921 wrefresh(tabline);
922 wrefresh(modeline);
924 if (in_minibuffer) {
925 wrefresh(body);
926 wrefresh(minibuf);
927 } else {
928 wrefresh(minibuf);
929 wrefresh(body);
933 static void
934 handle_clear_minibuf(int fd, short ev, void *d)
936 clminibufev_set = 0;
938 free(ministate.curmesg);
939 ministate.curmesg = NULL;
941 redraw_minibuffer();
942 if (in_minibuffer) {
943 wrefresh(body);
944 wrefresh(minibuf);
945 } else {
946 wrefresh(minibuf);
947 wrefresh(body);
951 static void
952 handle_resize(int sig, short ev, void *d)
954 struct tab *tab;
956 endwin();
957 refresh();
958 clear();
960 /* move and resize the windows, in reverse order! */
962 mvwin(minibuf, LINES-1, 0);
963 wresize(minibuf, 1, COLS);
965 mvwin(modeline, LINES-2, 0);
966 wresize(modeline, 1, COLS);
968 wresize(body, LINES-3, COLS);
969 body_lines = LINES-3;
970 body_cols = COLS;
972 wresize(tabline, 1, COLS);
974 tab = current_tab();
976 wrap_page(tab);
977 redraw_tab(tab);
980 /*
981 * Helper function for wrap_text. Find the end of the current word
982 * and the end of the separator after the word.
983 */
984 static int
985 word_boundaries(const char *s, const char *sep, const char **endword, const char **endspc)
987 *endword = s;
988 *endword = s;
990 if (*s == '\0')
991 return 0;
993 /* find the end of the current world */
994 for (; *s != '\0'; ++s) {
995 if (strchr(sep, *s) != NULL)
996 break;
999 *endword = s;
1001 /* find the end of the separator */
1002 for (; *s != '\0'; ++s) {
1003 if (strchr(sep, *s) == NULL)
1004 break;
1007 *endspc = s;
1009 return 1;
1012 static inline int
1013 emitline(struct tab *tab, size_t zero, size_t *off, const struct line *l,
1014 const char **line)
1016 if (!push_line(tab, l, *line, *off - zero))
1017 return 0;
1018 *line += *off - zero;
1019 *off = zero;
1020 return 1;
1023 static inline void
1024 emitstr(const char **s, size_t len, size_t *off)
1026 size_t i;
1028 /* printw("%*s", ...) doesn't seem to respect the precision, so... */
1029 for (i = 0; i < len; ++i)
1030 addch((*s)[i]);
1031 *off += len;
1032 *s += len;
1036 * Build a list of visual line by wrapping the given line, assuming
1037 * that when printed will have a leading prefix prfx.
1039 * TODO: it considers each byte one cell on the screen!
1041 static void
1042 wrap_text(struct tab *tab, const char *prfx, struct line *l)
1044 size_t zero, off, len, split;
1045 const char *endword, *endspc, *line, *linestart;
1047 zero = strlen(prfx);
1048 off = zero;
1049 line = l->line;
1050 linestart = l->line;
1052 while (word_boundaries(line, " \t-", &endword, &endspc)) {
1053 len = endword - line;
1054 if (off + len >= body_cols) {
1055 emitline(tab, zero, &off, l, &linestart);
1056 while (len >= body_cols) {
1057 /* hard wrap */
1058 emitline(tab, zero, &off, l, &linestart);
1059 len -= body_cols-1;
1060 line += body_cols-1;
1063 if (len != 0)
1064 off += len;
1065 } else
1066 off += len;
1068 /* print the spaces iff not at bol */
1069 len = endspc - endword;
1070 /* line = endspc; */
1071 if (off != zero) {
1072 if (off + len >= body_cols) {
1073 emitline(tab, zero, &off, l, &linestart);
1074 linestart = endspc;
1075 } else
1076 off += len;
1079 line = endspc;
1082 emitline(tab, zero, &off, l, &linestart);
1085 static int
1086 hardwrap_text(struct tab *tab, struct line *l)
1088 size_t off, len;
1089 const char *linestart;
1091 len = strlen(l->line);
1092 off = 0;
1093 linestart = l->line;
1095 while (len >= COLS) {
1096 len -= COLS-1;
1097 off = COLS-1;
1098 if (!emitline(tab, 0, &off, l, &linestart))
1099 return 0;
1102 if (len != 0)
1103 return emitline(tab, 0, &len, l, &linestart);
1105 return 1;
1108 static int
1109 wrap_page(struct tab *tab)
1111 struct line *l;
1113 empty_vlist(tab);
1115 TAILQ_FOREACH(l, &tab->page.head, lines) {
1116 switch (l->type) {
1117 case LINE_TEXT:
1118 wrap_text(tab, "", l);
1119 break;
1120 case LINE_LINK:
1121 wrap_text(tab, "=> ", l);
1122 break;
1123 case LINE_TITLE_1:
1124 wrap_text(tab, "# ", l);
1125 break;
1126 case LINE_TITLE_2:
1127 wrap_text(tab, "## ", l);
1128 break;
1129 case LINE_TITLE_3:
1130 wrap_text(tab, "### ", l);
1131 break;
1132 case LINE_ITEM:
1133 wrap_text(tab, "* ", l);
1134 break;
1135 case LINE_QUOTE:
1136 wrap_text(tab, "> ", l);
1137 break;
1138 case LINE_PRE_START:
1139 case LINE_PRE_END:
1140 push_line(tab, l, NULL, 0);
1141 break;
1142 case LINE_PRE_CONTENT:
1143 hardwrap_text(tab, l);
1144 break;
1147 return 1;
1150 static inline void
1151 print_line(struct line *l)
1153 const char *text = l->line;
1155 if (text == NULL)
1156 text = "";
1158 switch (l->type) {
1159 case LINE_TEXT:
1160 wprintw(body, "%s", text);
1161 break;
1162 case LINE_LINK:
1163 wattron(body, A_UNDERLINE);
1164 wprintw(body, "=> %s", text);
1165 wattroff(body, A_UNDERLINE);
1166 return;
1167 case LINE_TITLE_1:
1168 wattron(body, A_BOLD);
1169 wprintw(body, "# %s", text);
1170 wattroff(body, A_BOLD);
1171 return;
1172 case LINE_TITLE_2:
1173 wattron(body, A_BOLD);
1174 wprintw(body, "## %s", text);
1175 wattroff(body, A_BOLD);
1176 return;
1177 case LINE_TITLE_3:
1178 wattron(body, A_BOLD);
1179 wprintw(body, "### %s", text);
1180 wattroff(body, A_BOLD);
1181 return;
1182 case LINE_ITEM:
1183 wprintw(body, "* %s", text);
1184 return;
1185 case LINE_QUOTE:
1186 wattron(body, A_DIM);
1187 wprintw(body, "> %s", text);
1188 wattroff(body, A_DIM);
1189 return;
1190 case LINE_PRE_START:
1191 case LINE_PRE_END:
1192 wprintw(body, "```");
1193 return;
1194 case LINE_PRE_CONTENT:
1195 wprintw(body, "%s", text);
1196 return;
1200 static void
1201 redraw_tabline(void)
1203 struct tab *tab;
1204 int current;
1206 wclear(tabline);
1207 wbkgd(tabline, A_REVERSE);
1209 wprintw(tabline, " ");
1210 TAILQ_FOREACH(tab, &tabshead, tabs) {
1211 current = tab->flags & TAB_CURRENT;
1212 wprintw(tabline, " %s%d:todo title ",
1213 current ? "*" : "", tab->id);
1217 static void
1218 redraw_modeline(struct tab *tab)
1220 double pct;
1221 int x, y, max_x, max_y;
1222 const char *mode = "text/gemini-mode";
1223 const char *spin = "-\\|/";
1225 wclear(modeline);
1226 wattron(modeline, A_REVERSE);
1227 wmove(modeline, 0, 0);
1229 wprintw(modeline, "-%c %s ",
1230 spin[tab->s->loading_anim_step], mode);
1232 pct = (tab->s->line_off + tab->s->curs_y) * 100.0 / tab->s->line_max;
1234 if (tab->s->line_max <= body_lines)
1235 wprintw(modeline, "All ");
1236 else if (tab->s->line_off == 0)
1237 wprintw(modeline, "Top ");
1238 else if (tab->s->line_off + body_lines >= tab->s->line_max)
1239 wprintw(modeline, "Bottom ");
1240 else
1241 wprintw(modeline, "%.0f%% ", pct);
1243 wprintw(modeline, "%d/%d %s ",
1244 tab->s->line_off + tab->s->curs_y,
1245 tab->s->line_max,
1246 tab->urlstr);
1248 getyx(modeline, y, x);
1249 getmaxyx(modeline, max_y, max_x);
1251 (void)y;
1252 (void)max_y;
1254 for (; x < max_x; ++x)
1255 waddstr(modeline, "-");
1258 static void
1259 redraw_minibuffer(void)
1261 size_t skip = 0, off = 0;
1263 wclear(minibuf);
1264 if (!in_minibuffer)
1265 goto message;
1267 off = strlen(ministate.prompt);
1269 while (ministate.off - skip > COLS / 2) {
1270 skip += MIN(ministate.off/4, 1);
1273 mvwprintw(minibuf, 0, 0, "%s%s", ministate.prompt,
1274 ministate.buf + skip);
1276 message:
1277 if (ministate.curmesg != NULL) {
1278 if (in_minibuffer)
1279 wprintw(minibuf, " [%s]", ministate.curmesg);
1280 else
1281 wprintw(minibuf, "%s", ministate.curmesg);
1284 wmove(minibuf, 0, off + ministate.off - skip);
1287 static void
1288 redraw_tab(struct tab *tab)
1290 redraw_tabline();
1291 redraw_body(tab);
1292 redraw_modeline(tab);
1293 redraw_minibuffer();
1295 restore_cursor(tab);
1296 wrefresh(tabline);
1297 wrefresh(modeline);
1299 if (in_minibuffer) {
1300 wrefresh(body);
1301 wrefresh(minibuf);
1302 } else {
1303 wrefresh(minibuf);
1304 wrefresh(body);
1308 static void
1309 redraw_body(struct tab *tab)
1311 struct line *l;
1312 int line;
1314 werase(body);
1316 tab->s->line_off = MIN(tab->s->line_max, tab->s->line_off);
1317 if (TAILQ_EMPTY(&tab->s->head))
1318 return;
1320 line = 0;
1321 l = nth_line(tab, tab->s->line_off);
1322 for (; l != NULL; l = TAILQ_NEXT(l, lines)) {
1323 wmove(body, line, 0);
1324 print_line(l);
1325 line++;
1326 if (line == body_lines)
1327 break;
1331 static void
1332 message(const char *fmt, ...)
1334 va_list ap;
1336 if (clminibufev_set)
1337 evtimer_del(&clminibufev);
1338 evtimer_set(&clminibufev, handle_clear_minibuf, NULL);
1339 evtimer_add(&clminibufev, &clminibufev_timer);
1340 clminibufev_set = 1;
1342 va_start(ap, fmt);
1343 /* TODO: what to do if the allocation fails here? */
1344 if (vasprintf(&ministate.curmesg, fmt, ap) == -1)
1345 ministate.curmesg = NULL;
1346 va_end(ap);
1348 redraw_minibuffer();
1350 if (in_minibuffer) {
1351 wrefresh(body);
1352 wrefresh(minibuf);
1353 } else {
1354 wrefresh(minibuf);
1355 wrefresh(body);
1359 static void
1360 start_loading_anim(struct tab *tab)
1362 if (tab->s->loading_anim)
1363 return;
1364 tab->s->loading_anim = 1;
1365 evtimer_set(&tab->s->loadingev, update_loading_anim, tab);
1366 evtimer_add(&tab->s->loadingev, &loadingev_timer);
1369 static void
1370 update_loading_anim(int fd, short ev, void *d)
1372 struct tab *tab = d;
1374 tab->s->loading_anim_step = (tab->s->loading_anim_step+1)%4;
1376 redraw_modeline(tab);
1377 wrefresh(modeline);
1379 wrefresh(body);
1380 if (in_minibuffer)
1381 wrefresh(minibuf);
1383 evtimer_add(&tab->s->loadingev, &loadingev_timer);
1386 static void
1387 stop_loading_anim(struct tab *tab)
1389 if (!tab->s->loading_anim)
1390 return;
1391 evtimer_del(&tab->s->loadingev);
1392 tab->s->loading_anim = 0;
1393 tab->s->loading_anim_step = 0;
1395 redraw_modeline(tab);
1397 wrefresh(modeline);
1398 wrefresh(body);
1399 if (in_minibuffer)
1400 wrefresh(minibuf);
1403 static void
1404 load_url_in_tab(struct tab *tab, const char *url)
1406 empty_vlist(tab);
1407 message("Loading %s...", url);
1408 start_loading_anim(tab);
1409 load_url(tab, url);
1411 tab->s->curs_x = 0;
1412 tab->s->curs_y = 0;
1413 redraw_tab(tab);
1416 static void
1417 enter_minibuffer(void (*self_insert_fn)(void), void (*donefn)(void),
1418 void (*abortfn)(void))
1420 in_minibuffer = 1;
1421 base_map = &minibuffer_map;
1422 current_map = &minibuffer_map;
1424 base_map->unhandled_input = self_insert_fn;
1426 ministate.donefn = donefn;
1427 ministate.abortfn = abortfn;
1428 memset(ministate.buf, 0, sizeof(ministate.buf));
1429 ministate.off = 0;
1430 strlcpy(ministate.buf, "", sizeof(ministate.prompt));
1433 static void
1434 exit_minibuffer(void)
1436 wclear(minibuf);
1438 in_minibuffer = 0;
1439 base_map = &global_map;
1440 current_map = &global_map;
1443 static void
1444 switch_to_tab(struct tab *tab)
1446 struct tab *t;
1448 TAILQ_FOREACH(t, &tabshead, tabs) {
1449 t->flags &= ~TAB_CURRENT;
1452 tab->flags |= TAB_CURRENT;
1455 static void
1456 new_tab(void)
1458 struct tab *tab, *t;
1459 const char *url = "about:new";
1461 if ((tab = calloc(1, sizeof(*tab))) == NULL)
1462 goto err;
1464 if ((tab->s = calloc(1, sizeof(*t->s))) == NULL)
1465 goto err;
1467 TAILQ_INIT(&tab->s->head);
1469 tab->id = tab_counter++;
1470 switch_to_tab(tab);
1472 if (TAILQ_EMPTY(&tabshead))
1473 TAILQ_INSERT_HEAD(&tabshead, tab, tabs);
1474 else
1475 TAILQ_INSERT_TAIL(&tabshead, tab, tabs);
1477 load_url_in_tab(tab, url);
1478 return;
1480 err:
1481 event_loopbreak();
1484 int
1485 ui_init(void)
1487 setlocale(LC_ALL, "");
1489 TAILQ_INIT(&global_map.m);
1490 global_map.unhandled_input = global_key_unbound;
1492 TAILQ_INIT(&minibuffer_map.m);
1494 base_map = &global_map;
1495 current_map = &global_map;
1496 load_default_keys();
1498 initscr();
1499 raw();
1500 noecho();
1502 nonl();
1503 intrflush(stdscr, FALSE);
1505 if ((tabline = newwin(1, COLS, 0, 0)) == NULL)
1506 return 0;
1507 if ((body = newwin(LINES - 3, COLS, 1, 0)) == NULL)
1508 return 0;
1509 if ((modeline = newwin(1, COLS, LINES-2, 0)) == NULL)
1510 return 0;
1511 if ((minibuf = newwin(1, COLS, LINES-1, 0)) == NULL)
1512 return 0;
1514 body_lines = LINES-3;
1515 body_cols = COLS;
1517 keypad(body, TRUE);
1518 scrollok(body, TRUE);
1520 /* non-blocking input */
1521 wtimeout(body, 0);
1523 mvwprintw(body, 0, 0, "");
1525 event_set(&stdioev, 0, EV_READ | EV_PERSIST, dispatch_stdio, NULL);
1526 event_add(&stdioev, NULL);
1528 signal_set(&winchev, SIGWINCH, handle_resize, NULL);
1529 signal_add(&winchev, NULL);
1531 new_tab();
1533 return 1;
1536 void
1537 ui_on_tab_loaded(struct tab *tab)
1539 stop_loading_anim(tab);
1540 message("Loaded %s", tab->urlstr);
1543 void
1544 ui_on_tab_refresh(struct tab *tab)
1546 if (!(tab->flags & TAB_CURRENT))
1547 return;
1549 wrap_page(tab);
1550 redraw_tab(tab);
1553 void
1554 ui_require_input(struct tab *tab, int hide)
1556 /* TODO: hard-switching to another tab is ugly */
1557 switch_to_tab(tab);
1559 enter_minibuffer(ir_self_insert, ir_select, exit_minibuffer);
1560 strlcpy(ministate.prompt, "Input required: ",
1561 sizeof(ministate.prompt));
1562 redraw_tab(tab);
1565 void
1566 ui_end(void)
1568 endwin();