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;
77 struct minibuf_histhead;
79 static struct event stdioev, winchev;
81 static int kbd(const char*);
82 static void kmap_define_key(struct kmap*, const char*, void(*)(struct tab*));
83 static void load_default_keys(void);
84 static int push_line(struct tab*, const struct line*, const char*, size_t);
85 static void empty_vlist(struct tab*);
86 static void restore_cursor(struct tab *);
88 static void cmd_previous_line(struct tab*);
89 static void cmd_next_line(struct tab*);
90 static void cmd_forward_char(struct tab*);
91 static void cmd_backward_char(struct tab*);
92 static void cmd_move_beginning_of_line(struct tab*);
93 static void cmd_move_end_of_line(struct tab*);
94 static void cmd_redraw(struct tab*);
95 static void cmd_scroll_line_down(struct tab*);
96 static void cmd_scroll_line_up(struct tab*);
97 static void cmd_scroll_up(struct tab*);
98 static void cmd_scroll_down(struct tab*);
99 static void cmd_beginning_of_buffer(struct tab*);
100 static void cmd_end_of_buffer(struct tab*);
101 static void cmd_kill_telescope(struct tab*);
102 static void cmd_push_button(struct tab*);
103 static void cmd_clear_minibuf(struct tab*);
104 static void cmd_execute_extended_command(struct tab*);
105 static void cmd_tab_close(struct tab*);
106 static void cmd_tab_new(struct tab*);
107 static void cmd_tab_next(struct tab*);
108 static void cmd_tab_previous(struct tab*);
109 static void cmd_load_url(struct tab*);
110 static void cmd_load_current_url(struct tab*);
112 static void global_key_unbound(void);
114 static void cmd_mini_del(struct tab*);
115 static void cmd_mini_forward_char(struct tab*);
116 static void cmd_mini_backward_char(struct tab*);
117 static void cmd_mini_move_end_of_line(struct tab*);
118 static void cmd_mini_move_beginning_of_line(struct tab*);
119 static void cmd_mini_kill_line(struct tab*);
120 static void cmd_mini_abort(struct tab*);
121 static void cmd_mini_complete_and_exit(struct tab*);
122 static void cmd_mini_previous_history_element(struct tab*);
123 static void cmd_mini_next_history_element(struct tab*);
125 static void minibuffer_hist_save_entry(void);
126 static void minibuffer_taint_hist(void);
127 static void minibuffer_self_insert(void);
128 static void eecmd_self_insert(void);
129 static void eecmd_select(void);
130 static void ir_self_insert(void);
131 static void ir_select(void);
132 static void lu_self_insert(void);
133 static void lu_select(void);
135 static struct line *nth_line(struct tab*, size_t);
136 static struct tab *current_tab(void);
137 static void dispatch_stdio(int, short, void*);
138 static void handle_clear_minibuf(int, short, void*);
139 static void handle_resize(int, short, void*);
140 static int word_bourdaries(const char*, const char*, const char**, const char**);
141 static void wrap_text(struct tab*, const char*, struct line*);
142 static int hardwrap_text(struct tab*, struct line*);
143 static int wrap_page(struct tab*);
144 static void print_line(struct line*);
145 static void redraw_tabline(void);
146 static void redraw_body(struct tab*);
147 static void redraw_modeline(struct tab*);
148 static void redraw_minibuffer(void);
149 static void redraw_tab(struct tab*);
150 static void message(const char*, ...) __attribute__((format(printf, 1, 2)));
151 static void start_loading_anim(struct tab*);
152 static void update_loading_anim(int, short, void*);
153 static void stop_loading_anim(struct tab*);
154 static void load_url_in_tab(struct tab*, const char*);
155 static void enter_minibuffer(void(*)(void), void(*)(void), void(*)(void), struct minibuf_histhead*);
156 static void exit_minibuffer(void);
157 static void switch_to_tab(struct tab*);
158 static void new_tab(void);
160 static struct { int meta, key; } thiskey;
162 static WINDOW *tabline, *body, *modeline, *minibuf;
163 static int body_lines, body_cols;
165 static struct event clminibufev;
166 static int clminibufev_set;
167 static struct timeval clminibufev_timer = { 5, 0 };
168 static struct timeval loadingev_timer = { 0, 250000 };
170 static uint32_t tab_counter;
172 struct ui_state {
173 int curs_x;
174 int curs_y;
175 size_t line_off;
176 size_t line_max;
178 short loading_anim;
179 short loading_anim_step;
180 struct event loadingev;
182 TAILQ_HEAD(, line) head;
183 };
185 static char keybuf[64];
187 #define CTRL(n) ((n)&0x1F)
189 struct keytable {
190 char *p;
191 int k;
192 } keytable[] = {
193 { "<up>", KEY_UP },
194 { "<down>", KEY_DOWN },
195 { "<left>", KEY_LEFT },
196 { "<right>", KEY_RIGHT },
197 { "<prior>", KEY_PPAGE },
198 { "<next>", KEY_NPAGE },
199 { "<home>", KEY_HOME },
200 { "<end>", KEY_END },
201 /* ... */
202 { "del", KEY_BACKSPACE },
203 { "esc", 27 },
204 { "space", ' ' },
205 { "spc", ' ' },
206 { "enter", CTRL('m') },
207 { "ret", CTRL('m' )},
208 { "tab", CTRL('i') },
209 /* ... */
210 { NULL, 0 },
211 };
213 struct kmap {
214 TAILQ_HEAD(map, keymap) m;
215 void (*unhandled_input)(void);
216 };
218 struct kmap global_map,
219 minibuffer_map,
220 *current_map,
221 *base_map;
223 struct keymap {
224 int meta;
225 int key;
226 struct kmap map;
227 void (*fn)(struct tab*);
229 TAILQ_ENTRY(keymap) keymaps;
230 };
232 /* TODO: limit to a maximum number of entries */
233 struct minibuf_histhead {
234 TAILQ_HEAD(mhisthead, minibuf_hist) head;
235 size_t len;
236 };
237 struct minibuf_hist {
238 char h[1025];
239 TAILQ_ENTRY(minibuf_hist) entries;
240 };
242 static struct minibuf_histhead eecmd_history,
243 ir_history,
244 lu_history;
246 static int in_minibuffer;
248 static struct {
249 char *curmesg;
251 char buf[1025];
252 size_t off, len;
253 char prompt[32];
254 void (*donefn)(void);
255 void (*abortfn)(void);
257 struct minibuf_histhead *history;
258 struct minibuf_hist *hist_cur;
259 size_t hist_off;
260 } ministate;
262 struct lineprefix {
263 const char *prfx1;
264 const char *prfx2;
265 } line_prefixes[] = {
266 [LINE_TEXT] = { "", "" },
267 [LINE_LINK] = { "=> ", " " },
268 [LINE_TITLE_1] = { "# ", " " },
269 [LINE_TITLE_2] = { "## ", " " },
270 [LINE_TITLE_3] = { "### ", " " },
271 [LINE_ITEM] = { "* ", " " },
272 [LINE_QUOTE] = { "> ", "> " },
273 [LINE_PRE_START] = { "```", "```" },
274 [LINE_PRE_CONTENT] = { "", "" },
275 [LINE_PRE_END] = { "```", "```" },
276 };
278 struct line_face {
279 int prop;
280 } line_faces[] = {
281 [LINE_TEXT] = { 0 },
282 [LINE_LINK] = { A_UNDERLINE },
283 [LINE_TITLE_1] = { A_BOLD },
284 [LINE_TITLE_2] = { A_BOLD },
285 [LINE_TITLE_3] = { A_BOLD },
286 [LINE_ITEM] = { 0 },
287 [LINE_QUOTE] = { A_DIM },
288 [LINE_PRE_START] = { 0 },
289 [LINE_PRE_CONTENT] = { 0 },
290 [LINE_PRE_END] = { 0 },
291 };
293 static int
294 kbd(const char *key)
296 struct keytable *t;
298 for (t = keytable; t->p != NULL; ++t) {
299 if (has_prefix(key, t->p))
300 return t->k;
303 return *key;
306 static const char *
307 unkbd(int k)
309 struct keytable *t;
311 for (t = keytable; t->p != NULL; ++t) {
312 if (k == t->k)
313 return t->p;
316 return NULL;
319 static void
320 kmap_define_key(struct kmap *map, const char *key, void (*fn)(struct tab*))
322 int ctrl, meta, k;
323 struct keymap *entry;
325 again:
326 if ((ctrl = has_prefix(key, "C-")))
327 key += 2;
328 if ((meta = has_prefix(key, "M-")))
329 key += 2;
330 if (*key == '\0')
331 _exit(1);
332 k = kbd(key);
334 if (ctrl)
335 k = CTRL(k);
337 /* skip key & spaces */
338 while (*key != '\0' && !isspace(*key))
339 ++key;
340 while (*key != '\0' && isspace(*key))
341 ++key;
343 TAILQ_FOREACH(entry, &map->m, keymaps) {
344 if (entry->meta == meta && entry->key == k) {
345 if (*key == '\0') {
346 entry->fn = fn;
347 return;
349 map = &entry->map;
350 goto again;
354 if ((entry = calloc(1, sizeof(*entry))) == NULL)
355 abort();
357 entry->meta = meta;
358 entry->key = k;
359 TAILQ_INIT(&entry->map.m);
361 if (TAILQ_EMPTY(&map->m))
362 TAILQ_INSERT_HEAD(&map->m, entry, keymaps);
363 else
364 TAILQ_INSERT_TAIL(&map->m, entry, keymaps);
366 if (*key != '\0') {
367 map = &entry->map;
368 goto again;
371 entry->fn = fn;
374 static inline void
375 global_set_key(const char *key, void (*fn)(struct tab*))
377 kmap_define_key(&global_map, key, fn);
380 static inline void
381 minibuffer_set_key(const char *key, void (*fn)(struct tab*))
383 kmap_define_key(&minibuffer_map, key, fn);
386 static void
387 load_default_keys(void)
389 /* === global map === */
391 /* emacs */
392 global_set_key("C-p", cmd_previous_line);
393 global_set_key("C-n", cmd_next_line);
394 global_set_key("C-f", cmd_forward_char);
395 global_set_key("C-b", cmd_backward_char);
396 global_set_key("C-a", cmd_move_beginning_of_line);
397 global_set_key("C-e", cmd_move_end_of_line);
399 global_set_key("M-v", cmd_scroll_up);
400 global_set_key("C-v", cmd_scroll_down);
402 global_set_key("C-x C-c", cmd_kill_telescope);
404 global_set_key("C-g", cmd_clear_minibuf);
406 global_set_key("M-x", cmd_execute_extended_command);
407 global_set_key("C-x C-f", cmd_load_url);
408 global_set_key("C-x M-f", cmd_load_current_url);
410 global_set_key("C-x t 0", cmd_tab_close);
411 global_set_key("C-x t 2", cmd_tab_new);
412 global_set_key("C-x t o", cmd_tab_next);
413 global_set_key("C-x t O", cmd_tab_previous);
415 global_set_key("M-<", cmd_beginning_of_buffer);
416 global_set_key("M->", cmd_end_of_buffer);
418 /* vi/vi-like */
419 global_set_key("k", cmd_previous_line);
420 global_set_key("j", cmd_next_line);
421 global_set_key("l", cmd_forward_char);
422 global_set_key("h", cmd_backward_char);
423 global_set_key("^", cmd_move_beginning_of_line);
424 global_set_key("$", cmd_move_end_of_line);
426 global_set_key("K", cmd_scroll_line_up);
427 global_set_key("J", cmd_scroll_line_down);
429 global_set_key("g g", cmd_beginning_of_buffer);
430 global_set_key("G", cmd_end_of_buffer);
432 /* tmp */
433 global_set_key("q", cmd_kill_telescope);
435 global_set_key("esc", cmd_clear_minibuf);
437 global_set_key(":", cmd_execute_extended_command);
439 /* cua */
440 global_set_key("<up>", cmd_previous_line);
441 global_set_key("<down>", cmd_next_line);
442 global_set_key("<right>", cmd_forward_char);
443 global_set_key("<left>", cmd_backward_char);
444 global_set_key("<prior>", cmd_scroll_up);
445 global_set_key("<next>", cmd_scroll_down);
447 /* "ncurses standard" */
448 global_set_key("C-l", cmd_redraw);
450 /* global */
451 global_set_key("C-m", cmd_push_button);
453 /* === minibuffer map === */
454 minibuffer_set_key("ret", cmd_mini_complete_and_exit);
455 minibuffer_set_key("C-g", cmd_mini_abort);
456 minibuffer_set_key("esc", cmd_mini_abort);
457 minibuffer_set_key("del", cmd_mini_del);
459 minibuffer_set_key("C-f", cmd_mini_forward_char);
460 minibuffer_set_key("C-b", cmd_mini_backward_char);
461 minibuffer_set_key("C-e", cmd_mini_move_end_of_line);
462 minibuffer_set_key("C-a", cmd_mini_move_beginning_of_line);
463 minibuffer_set_key("<end>", cmd_mini_move_end_of_line);
464 minibuffer_set_key("<home>", cmd_mini_move_beginning_of_line);
465 minibuffer_set_key("C-k", cmd_mini_kill_line);
467 minibuffer_set_key("M-p", cmd_mini_previous_history_element);
468 minibuffer_set_key("M-n", cmd_mini_next_history_element);
469 minibuffer_set_key("<up>", cmd_mini_previous_history_element);
470 minibuffer_set_key("<down>", cmd_mini_next_history_element);
473 static int
474 push_line(struct tab *tab, const struct line *l, const char *buf, size_t len)
476 struct line *vl;
478 tab->s->line_max++;
480 if ((vl = calloc(1, sizeof(*vl))) == NULL)
481 return 0;
483 if (len != 0 && (vl->line = calloc(1, len+1)) == NULL) {
484 free(vl);
485 return 0;
488 vl->type = l->type;
489 if (len != 0)
490 memcpy(vl->line, buf, len);
491 vl->alt = l->alt;
493 if (TAILQ_EMPTY(&tab->s->head))
494 TAILQ_INSERT_HEAD(&tab->s->head, vl, lines);
495 else
496 TAILQ_INSERT_TAIL(&tab->s->head, vl, lines);
497 return 1;
500 static void
501 empty_vlist(struct tab *tab)
503 struct line *l, *t;
505 tab->s->line_max = 0;
507 TAILQ_FOREACH_SAFE(l, &tab->s->head, lines, t) {
508 TAILQ_REMOVE(&tab->s->head, l, lines);
509 free(l->line);
510 /* l->alt references the original line! */
511 free(l);
515 static void
516 restore_cursor(struct tab *tab)
518 wmove(body, tab->s->curs_y, tab->s->curs_x);
521 static void
522 cmd_previous_line(struct tab *tab)
524 if (--tab->s->curs_y < 0) {
525 tab->s->curs_y = 0;
526 cmd_scroll_line_up(tab);
529 restore_cursor(tab);
532 static void
533 cmd_next_line(struct tab *tab)
535 if (tab->s->line_off + tab->s->curs_y >= tab->s->line_max)
536 return;
538 if (++tab->s->curs_y > body_lines-1) {
539 tab->s->curs_y = body_lines-1;
540 cmd_scroll_line_down(tab);
543 restore_cursor(tab);
546 static void
547 cmd_forward_char(struct tab *tab)
549 tab->s->curs_x = MIN(body_cols-1, tab->s->curs_x+1);
550 restore_cursor(tab);
553 static void
554 cmd_backward_char(struct tab *tab)
556 tab->s->curs_x = MAX(0, tab->s->curs_x-1);
557 restore_cursor(tab);
560 static void
561 cmd_move_beginning_of_line(struct tab *tab)
563 tab->s->curs_x = 0;
564 restore_cursor(tab);
567 static void
568 cmd_move_end_of_line(struct tab *tab)
570 struct line *line;
571 size_t off;
572 const char *prfx;
574 off = tab->s->line_off + tab->s->curs_y;
575 if (off >= tab->s->line_max) {
576 tab->s->curs_x = 0;
577 goto end;
580 line = nth_line(tab, off);
581 if (line->line != NULL)
582 tab->s->curs_x = strlen(line->line);
583 else
584 tab->s->curs_x = 0;
586 prfx = line_prefixes[line->type].prfx1;
587 tab->s->curs_x += strlen(prfx);
589 end:
590 restore_cursor(tab);
593 static void
594 cmd_redraw(struct tab *tab)
596 handle_resize(0, 0, NULL);
599 static void
600 cmd_scroll_line_up(struct tab *tab)
602 struct line *l;
604 if (tab->s->line_off == 0)
605 return;
607 l = nth_line(tab, --tab->s->line_off);
608 wscrl(body, -1);
609 wmove(body, 0, 0);
610 print_line(l);
613 static void
614 cmd_scroll_line_down(struct tab *tab)
616 struct line *l;
617 size_t n;
619 if (tab->s->line_max == 0 || tab->s->line_off == tab->s->line_max-1)
620 return;
622 tab->s->line_off++;
623 wscrl(body, 1);
625 if (tab->s->line_max - tab->s->line_off < body_lines)
626 return;
628 l = nth_line(tab, tab->s->line_off + body_lines-1);
629 wmove(body, body_lines-1, 0);
630 print_line(l);
633 static void
634 cmd_scroll_up(struct tab *tab)
636 size_t off;
638 off = body_lines+1;
640 for (; off > 0; --off)
641 cmd_scroll_line_up(tab);
644 static void
645 cmd_scroll_down(struct tab *tab)
647 ssize_t off;
649 off = tab->s->line_off + body_lines;
650 off = MIN(tab->s->line_max, off);
652 for (; off >= 0; --off)
653 cmd_scroll_line_down(tab);
656 static void
657 cmd_beginning_of_buffer(struct tab *tab)
659 tab->s->line_off = 0;
660 tab->s->curs_y = 0;
661 redraw_body(tab);
664 static void
665 cmd_end_of_buffer(struct tab *tab)
667 ssize_t off;
669 off = tab->s->line_max - body_lines;
670 off = MAX(0, off);
672 tab->s->line_off = off;
673 tab->s->curs_y = MIN(body_lines, tab->s->line_max);
675 redraw_body(tab);
678 static void
679 cmd_kill_telescope(struct tab *tab)
681 event_loopbreak();
684 static void
685 cmd_push_button(struct tab *tab)
687 struct line *l;
688 size_t nth;
690 nth = tab->s->line_off + tab->s->curs_y;
691 if (nth > tab->s->line_max)
692 return;
693 l = nth_line(tab, nth);
694 if (l->type != LINE_LINK)
695 return;
697 load_url_in_tab(tab, l->alt);
700 static void
701 cmd_clear_minibuf(struct tab *tab)
703 handle_clear_minibuf(0, 0, NULL);
706 static void
707 cmd_execute_extended_command(struct tab *tab)
709 size_t len;
711 enter_minibuffer(eecmd_self_insert, eecmd_select, exit_minibuffer,
712 &eecmd_history);
714 len = sizeof(ministate.prompt);
715 strlcpy(ministate.prompt, "", len);
717 if (thiskey.meta)
718 strlcat(ministate.prompt, "M-", len);
720 strlcat(ministate.prompt, keyname(thiskey.key), len);
721 strlcat(ministate.prompt, " ", len);
724 static void
725 cmd_tab_close(struct tab *tab)
727 struct tab *t;
729 if (TAILQ_PREV(tab, tabshead, tabs) == NULL &&
730 TAILQ_NEXT(tab, tabs) == NULL) {
731 message("Can't close the only tab.");
732 return;
735 stop_tab(tab);
737 t = TAILQ_PREV(tab, tabshead, tabs);
738 t->flags |= TAB_CURRENT;
740 TAILQ_REMOVE(&tabshead, tab, tabs);
742 free(tab->s);
743 free(tab);
746 static void
747 cmd_tab_new(struct tab *tab)
749 new_tab();
752 static void
753 cmd_tab_next(struct tab *tab)
755 struct tab *t;
757 tab->flags &= ~TAB_CURRENT;
759 if ((t = TAILQ_NEXT(tab, tabs)) == NULL)
760 t = TAILQ_FIRST(&tabshead);
761 t->flags |= TAB_CURRENT;
764 static void
765 cmd_tab_previous(struct tab *tab)
767 struct tab *t;
769 tab->flags &= ~TAB_CURRENT;
771 if ((t = TAILQ_PREV(tab, tabshead, tabs)) == NULL)
772 t = TAILQ_LAST(&tabshead, tabshead);
773 t->flags |= TAB_CURRENT;
776 static void
777 cmd_load_url(struct tab *tab)
779 enter_minibuffer(lu_self_insert, lu_select, exit_minibuffer,
780 &lu_history);
781 strlcpy(ministate.prompt, "Load URL: ", sizeof(ministate.prompt));
784 static void
785 cmd_load_current_url(struct tab *tab)
787 enter_minibuffer(lu_self_insert, lu_select, exit_minibuffer,
788 &lu_history);
789 strlcpy(ministate.prompt, "Load URL: ", sizeof(ministate.prompt));
790 strlcpy(ministate.buf, tab->urlstr, sizeof(ministate.buf));
791 ministate.off = strlen(tab->urlstr);
792 ministate.len = ministate.off;
795 static void
796 global_key_unbound(void)
798 message("%s is undefined", keybuf);
801 static void
802 cmd_mini_del(struct tab *tab)
804 if (ministate.len == 0 || ministate.off == 0)
805 return;
807 memmove(&ministate.buf[ministate.off-1],
808 &ministate.buf[ministate.off],
809 ministate.len - ministate.off + 1);
810 ministate.off--;
811 ministate.len--;
814 static void
815 cmd_mini_forward_char(struct tab *tab)
817 if (ministate.off == ministate.len)
818 return;
819 ministate.off++;
822 static void
823 cmd_mini_backward_char(struct tab *tab)
825 if (ministate.off == 0)
826 return;
827 ministate.off--;
830 static void
831 cmd_mini_move_end_of_line(struct tab *tab)
833 ministate.off = ministate.len;
836 static void
837 cmd_mini_move_beginning_of_line(struct tab *tab)
839 ministate.off = 0;
842 static void
843 cmd_mini_kill_line(struct tab *tab)
845 if (ministate.off == ministate.len)
846 return;
847 ministate.buf[ministate.off] = '\0';
848 ministate.len -= ministate.off;
851 static void
852 cmd_mini_abort(struct tab *tab)
854 ministate.abortfn();
857 static void
858 cmd_mini_complete_and_exit(struct tab *tab)
860 minibuffer_taint_hist();
861 ministate.donefn();
864 static void
865 cmd_mini_previous_history_element(struct tab *tab)
867 if (ministate.history == NULL) {
868 message("No history");
869 return;
872 if (ministate.hist_cur == NULL ||
873 (ministate.hist_cur = TAILQ_PREV(ministate.hist_cur, mhisthead, entries)) == NULL) {
874 ministate.hist_cur = TAILQ_LAST(&ministate.history->head, mhisthead);
875 ministate.hist_off = ministate.history->len - 1;
876 if (ministate.hist_cur == NULL)
877 message("No prev item");
878 } else {
879 ministate.hist_off--;
882 if (ministate.hist_cur != NULL) {
883 ministate.off = 0;
884 ministate.len = strlen(ministate.hist_cur->h);
888 static void
889 cmd_mini_next_history_element(struct tab *tab)
891 if (ministate.history == NULL) {
892 message("No history");
893 return;
896 if (ministate.hist_cur == NULL ||
897 (ministate.hist_cur = TAILQ_NEXT(ministate.hist_cur, entries)) == NULL) {
898 ministate.hist_cur = TAILQ_FIRST(&ministate.history->head);
899 ministate.hist_off = 0;
900 if (ministate.hist_cur == NULL)
901 message("No next item");
902 } else {
903 ministate.hist_off++;
906 if (ministate.hist_cur != NULL) {
907 ministate.off = 0;
908 ministate.len = strlen(ministate.hist_cur->h);
912 static void
913 minibuffer_hist_save_entry(void)
915 struct minibuf_hist *hist;
917 if (ministate.history == NULL)
918 return;
920 if ((hist = calloc(1, sizeof(*hist))) == NULL)
921 abort();
923 strlcpy(hist->h, ministate.buf, sizeof(hist->h));
925 if (TAILQ_EMPTY(&ministate.history->head))
926 TAILQ_INSERT_HEAD(&ministate.history->head, hist, entries);
927 else
928 TAILQ_INSERT_TAIL(&ministate.history->head, hist, entries);
929 ministate.history->len++;
932 /*
933 * taint the minibuffer cache: if we're currently showing a history
934 * element, copy that to the current buf and reset the "history
935 * navigation" thing.
936 */
937 static void
938 minibuffer_taint_hist(void)
940 if (ministate.hist_cur == NULL)
941 return;
943 strlcpy(ministate.buf, ministate.hist_cur->h, sizeof(ministate.buf));
944 ministate.hist_cur = NULL;
947 static void
948 minibuffer_self_insert(void)
950 minibuffer_taint_hist();
952 if (ministate.len == sizeof(ministate.buf) -1)
953 return;
955 /* TODO: utf8 handling! */
957 memmove(&ministate.buf[ministate.off+1],
958 &ministate.buf[ministate.off],
959 ministate.len - ministate.off + 1);
960 ministate.buf[ministate.off] = thiskey.key;
961 ministate.off++;
962 ministate.len++;
965 static void
966 eecmd_self_insert(void)
968 if (thiskey.meta || isspace(thiskey.key) ||
969 !isgraph(thiskey.key)) {
970 global_key_unbound();
971 return;
974 minibuffer_self_insert();
977 static void
978 eecmd_select(void)
980 exit_minibuffer();
981 minibuffer_hist_save_entry();
982 message("TODO: try to execute %s", ministate.buf);
985 static void
986 ir_self_insert(void)
988 minibuffer_self_insert();
991 static void
992 ir_select(void)
994 char buf[1025] = {0};
995 struct url url;
996 struct tab *tab;
998 tab = current_tab();
1000 exit_minibuffer();
1001 minibuffer_hist_save_entry();
1003 /* a bit ugly but... */
1004 memcpy(&url, &tab->url, sizeof(tab->url));
1005 url_set_query(&url, ministate.buf);
1006 url_unparse(&url, buf, sizeof(buf));
1007 load_url_in_tab(tab, buf);
1010 static void
1011 lu_self_insert(void)
1013 if (thiskey.meta || isspace(thiskey.key) ||
1014 !isgraph(thiskey.key)) {
1015 global_key_unbound();
1016 return;
1019 minibuffer_self_insert();
1022 static void
1023 lu_select(void)
1025 exit_minibuffer();
1026 minibuffer_hist_save_entry();
1027 load_url_in_tab(current_tab(), ministate.buf);
1030 static struct line *
1031 nth_line(struct tab *tab, size_t n)
1033 struct line *l;
1034 size_t i;
1036 i = 0;
1037 TAILQ_FOREACH(l, &tab->s->head, lines) {
1038 if (i == n)
1039 return l;
1040 i++;
1043 /* unreachable */
1044 abort();
1047 static struct tab *
1048 current_tab(void)
1050 struct tab *t;
1052 TAILQ_FOREACH(t, &tabshead, tabs) {
1053 if (t->flags & TAB_CURRENT)
1054 return t;
1057 /* unreachable */
1058 abort();
1061 static void
1062 dispatch_stdio(int fd, short ev, void *d)
1064 struct tab *tab;
1065 struct keymap *k;
1066 const char *keyname;
1067 char tmp[2] = {0};
1069 thiskey.key = wgetch(body);
1070 if (thiskey.key == ERR)
1071 return;
1072 if (thiskey.key == 27) {
1073 /* TODO: make escape-time customizable */
1075 thiskey.meta = 1;
1076 thiskey.key = wgetch(body);
1077 if (thiskey.key == ERR || thiskey.key == 27) {
1078 thiskey.meta = 0;
1079 thiskey.key = 27;
1081 } else
1082 thiskey.meta = 0;
1084 if (keybuf[0] != '\0')
1085 strlcat(keybuf, " ", sizeof(keybuf));
1086 if (thiskey.meta)
1087 strlcat(keybuf, "M-", sizeof(keybuf));
1088 if ((keyname = unkbd(thiskey.key)) != NULL)
1089 strlcat(keybuf, keyname, sizeof(keybuf));
1090 else {
1091 tmp[0] = thiskey.key;
1092 strlcat(keybuf, tmp, sizeof(keybuf));
1095 TAILQ_FOREACH(k, &current_map->m, keymaps) {
1096 if (k->meta == thiskey.meta &&
1097 k->key == thiskey.key) {
1098 if (k->fn == NULL)
1099 current_map = &k->map;
1100 else {
1101 current_map = base_map;
1102 strlcpy(keybuf, "", sizeof(keybuf));
1103 k->fn(current_tab());
1105 goto done;
1109 if (current_map->unhandled_input != NULL)
1110 current_map->unhandled_input();
1111 else {
1112 global_key_unbound();
1115 strlcpy(keybuf, "", sizeof(keybuf));
1116 current_map = base_map;
1118 done:
1119 redraw_tab(current_tab());
1122 static void
1123 handle_clear_minibuf(int fd, short ev, void *d)
1125 clminibufev_set = 0;
1127 free(ministate.curmesg);
1128 ministate.curmesg = NULL;
1130 redraw_minibuffer();
1131 if (in_minibuffer) {
1132 wrefresh(body);
1133 wrefresh(minibuf);
1134 } else {
1135 wrefresh(minibuf);
1136 wrefresh(body);
1140 static void
1141 handle_resize(int sig, short ev, void *d)
1143 struct tab *tab;
1145 endwin();
1146 refresh();
1147 clear();
1149 /* move and resize the windows, in reverse order! */
1151 mvwin(minibuf, LINES-1, 0);
1152 wresize(minibuf, 1, COLS);
1154 mvwin(modeline, LINES-2, 0);
1155 wresize(modeline, 1, COLS);
1157 wresize(body, LINES-3, COLS);
1158 body_lines = LINES-3;
1159 body_cols = COLS;
1161 wresize(tabline, 1, COLS);
1163 tab = current_tab();
1165 wrap_page(tab);
1166 redraw_tab(tab);
1170 * Helper function for wrap_text. Find the end of the current word
1171 * and the end of the separator after the word.
1173 static int
1174 word_boundaries(const char *s, const char *sep, const char **endword, const char **endspc)
1176 *endword = s;
1177 *endword = s;
1179 if (*s == '\0')
1180 return 0;
1182 /* find the end of the current world */
1183 for (; *s != '\0'; ++s) {
1184 if (strchr(sep, *s) != NULL)
1185 break;
1188 *endword = s;
1190 /* find the end of the separator */
1191 for (; *s != '\0'; ++s) {
1192 if (strchr(sep, *s) == NULL)
1193 break;
1196 *endspc = s;
1198 return 1;
1201 static inline int
1202 emitline(struct tab *tab, size_t zero, size_t *off, const struct line *l,
1203 const char **line)
1205 if (!push_line(tab, l, *line, *off - zero))
1206 return 0;
1207 *line += *off - zero;
1208 *off = zero;
1209 return 1;
1212 static inline void
1213 emitstr(const char **s, size_t len, size_t *off)
1215 size_t i;
1217 /* printw("%*s", ...) doesn't seem to respect the precision, so... */
1218 for (i = 0; i < len; ++i)
1219 addch((*s)[i]);
1220 *off += len;
1221 *s += len;
1225 * Build a list of visual line by wrapping the given line, assuming
1226 * that when printed will have a leading prefix prfx.
1228 * TODO: it considers each byte one cell on the screen!
1230 static void
1231 wrap_text(struct tab *tab, const char *prfx, struct line *l)
1233 size_t zero, off, len, split;
1234 const char *endword, *endspc, *line, *linestart;
1236 zero = strlen(prfx);
1237 off = zero;
1238 line = l->line;
1239 linestart = l->line;
1241 while (word_boundaries(line, " \t-", &endword, &endspc)) {
1242 len = endword - line;
1243 if (off + len >= body_cols) {
1244 emitline(tab, zero, &off, l, &linestart);
1245 while (len >= body_cols) {
1246 /* hard wrap */
1247 emitline(tab, zero, &off, l, &linestart);
1248 len -= body_cols-1;
1249 line += body_cols-1;
1252 if (len != 0)
1253 off += len;
1254 } else
1255 off += len;
1257 /* print the spaces iff not at bol */
1258 len = endspc - endword;
1259 /* line = endspc; */
1260 if (off != zero) {
1261 if (off + len >= body_cols) {
1262 emitline(tab, zero, &off, l, &linestart);
1263 linestart = endspc;
1264 } else
1265 off += len;
1268 line = endspc;
1271 emitline(tab, zero, &off, l, &linestart);
1274 static int
1275 hardwrap_text(struct tab *tab, struct line *l)
1277 size_t off, len;
1278 const char *linestart;
1280 len = strlen(l->line);
1281 off = 0;
1282 linestart = l->line;
1284 while (len >= COLS) {
1285 len -= COLS-1;
1286 off = COLS-1;
1287 if (!emitline(tab, 0, &off, l, &linestart))
1288 return 0;
1291 if (len != 0)
1292 return emitline(tab, 0, &len, l, &linestart);
1294 return 1;
1297 static int
1298 wrap_page(struct tab *tab)
1300 struct line *l;
1301 const char *prfx;
1303 empty_vlist(tab);
1305 TAILQ_FOREACH(l, &tab->page.head, lines) {
1306 prfx = line_prefixes[l->type].prfx1;
1307 switch (l->type) {
1308 case LINE_TEXT:
1309 case LINE_LINK:
1310 case LINE_TITLE_1:
1311 case LINE_TITLE_2:
1312 case LINE_TITLE_3:
1313 case LINE_ITEM:
1314 case LINE_QUOTE:
1315 wrap_text(tab, prfx, l);
1316 break;
1317 case LINE_PRE_START:
1318 case LINE_PRE_END:
1319 push_line(tab, l, NULL, 0);
1320 break;
1321 case LINE_PRE_CONTENT:
1322 hardwrap_text(tab, l);
1323 break;
1326 return 1;
1329 static inline void
1330 print_line(struct line *l)
1332 const char *text = l->line;
1333 const char *prfx = line_prefixes[l->type].prfx1;
1334 int face = line_faces[l->type].prop;
1336 if (text == NULL)
1337 text = "";
1339 if (face != 0)
1340 wattron(body, face);
1341 wprintw(body, "%s%s", prfx, text);
1342 if (face != 0)
1343 wattroff(body, face);
1346 static void
1347 redraw_tabline(void)
1349 struct tab *tab;
1350 int current;
1352 wclear(tabline);
1353 wbkgd(tabline, A_REVERSE);
1355 wprintw(tabline, " ");
1356 TAILQ_FOREACH(tab, &tabshead, tabs) {
1357 current = tab->flags & TAB_CURRENT;
1359 if (current)
1360 wattron(tabline, A_UNDERLINE);
1362 wprintw(tabline, "%s%d:todo title ",
1363 current ? "*" : " ", tab->id);
1365 if (current)
1366 wattroff(tabline, A_UNDERLINE);
1370 static void
1371 redraw_modeline(struct tab *tab)
1373 double pct;
1374 int x, y, max_x, max_y;
1375 const char *mode = "text/gemini-mode";
1376 const char *spin = "-\\|/";
1378 wclear(modeline);
1379 wattron(modeline, A_REVERSE);
1380 wmove(modeline, 0, 0);
1382 wprintw(modeline, "-%c %s ",
1383 spin[tab->s->loading_anim_step], mode);
1385 pct = (tab->s->line_off + tab->s->curs_y) * 100.0 / tab->s->line_max;
1387 if (tab->s->line_max <= body_lines)
1388 wprintw(modeline, "All ");
1389 else if (tab->s->line_off == 0)
1390 wprintw(modeline, "Top ");
1391 else if (tab->s->line_off + body_lines >= tab->s->line_max)
1392 wprintw(modeline, "Bottom ");
1393 else
1394 wprintw(modeline, "%.0f%% ", pct);
1396 wprintw(modeline, "%d/%d %s ",
1397 tab->s->line_off + tab->s->curs_y,
1398 tab->s->line_max,
1399 tab->urlstr);
1401 getyx(modeline, y, x);
1402 getmaxyx(modeline, max_y, max_x);
1404 (void)y;
1405 (void)max_y;
1407 for (; x < max_x; ++x)
1408 waddstr(modeline, "-");
1411 static void
1412 redraw_minibuffer(void)
1414 size_t skip = 0, off_x = 0, off_y = 0;
1416 wclear(minibuf);
1417 if (in_minibuffer) {
1418 mvwprintw(minibuf, 0, 0, "%s", ministate.prompt);
1419 if (ministate.hist_cur != NULL)
1420 wprintw(minibuf, "(%zu/%zu) ",
1421 ministate.hist_off + 1,
1422 ministate.history->len);
1424 getyx(minibuf, off_y, off_x);
1426 while (ministate.off - skip > COLS / 2) {
1427 skip += MIN(ministate.off/4, 1);
1430 if (ministate.hist_cur != NULL)
1431 wprintw(minibuf, "%s", ministate.hist_cur->h + skip);
1432 else
1433 wprintw(minibuf, "%s", ministate.buf + skip);
1436 if (ministate.curmesg != NULL) {
1437 if (in_minibuffer)
1438 wprintw(minibuf, " [%s]", ministate.curmesg);
1439 else
1440 wprintw(minibuf, "%s", ministate.curmesg);
1443 wmove(minibuf, 0, off_x + ministate.off - skip);
1446 static void
1447 redraw_tab(struct tab *tab)
1449 redraw_tabline();
1450 redraw_body(tab);
1451 redraw_modeline(tab);
1452 redraw_minibuffer();
1454 restore_cursor(tab);
1455 wrefresh(tabline);
1456 wrefresh(modeline);
1458 if (in_minibuffer) {
1459 wrefresh(body);
1460 wrefresh(minibuf);
1461 } else {
1462 wrefresh(minibuf);
1463 wrefresh(body);
1467 static void
1468 redraw_body(struct tab *tab)
1470 struct line *l;
1471 int line;
1473 werase(body);
1475 tab->s->line_off = MIN(tab->s->line_max, tab->s->line_off);
1476 if (TAILQ_EMPTY(&tab->s->head))
1477 return;
1479 line = 0;
1480 l = nth_line(tab, tab->s->line_off);
1481 for (; l != NULL; l = TAILQ_NEXT(l, lines)) {
1482 wmove(body, line, 0);
1483 print_line(l);
1484 line++;
1485 if (line == body_lines)
1486 break;
1490 static void
1491 message(const char *fmt, ...)
1493 va_list ap;
1495 if (clminibufev_set)
1496 evtimer_del(&clminibufev);
1497 evtimer_set(&clminibufev, handle_clear_minibuf, NULL);
1498 evtimer_add(&clminibufev, &clminibufev_timer);
1499 clminibufev_set = 1;
1501 va_start(ap, fmt);
1502 /* TODO: what to do if the allocation fails here? */
1503 if (vasprintf(&ministate.curmesg, fmt, ap) == -1)
1504 ministate.curmesg = NULL;
1505 va_end(ap);
1507 redraw_minibuffer();
1509 if (in_minibuffer) {
1510 wrefresh(body);
1511 wrefresh(minibuf);
1512 } else {
1513 wrefresh(minibuf);
1514 wrefresh(body);
1518 static void
1519 start_loading_anim(struct tab *tab)
1521 if (tab->s->loading_anim)
1522 return;
1523 tab->s->loading_anim = 1;
1524 evtimer_set(&tab->s->loadingev, update_loading_anim, tab);
1525 evtimer_add(&tab->s->loadingev, &loadingev_timer);
1528 static void
1529 update_loading_anim(int fd, short ev, void *d)
1531 struct tab *tab = d;
1533 tab->s->loading_anim_step = (tab->s->loading_anim_step+1)%4;
1535 redraw_modeline(tab);
1536 wrefresh(modeline);
1538 wrefresh(body);
1539 if (in_minibuffer)
1540 wrefresh(minibuf);
1542 evtimer_add(&tab->s->loadingev, &loadingev_timer);
1545 static void
1546 stop_loading_anim(struct tab *tab)
1548 if (!tab->s->loading_anim)
1549 return;
1550 evtimer_del(&tab->s->loadingev);
1551 tab->s->loading_anim = 0;
1552 tab->s->loading_anim_step = 0;
1554 redraw_modeline(tab);
1556 wrefresh(modeline);
1557 wrefresh(body);
1558 if (in_minibuffer)
1559 wrefresh(minibuf);
1562 static void
1563 load_url_in_tab(struct tab *tab, const char *url)
1565 empty_vlist(tab);
1566 message("Loading %s...", url);
1567 start_loading_anim(tab);
1568 load_url(tab, url);
1570 tab->s->curs_x = 0;
1571 tab->s->curs_y = 0;
1572 redraw_tab(tab);
1575 static void
1576 enter_minibuffer(void (*self_insert_fn)(void), void (*donefn)(void),
1577 void (*abortfn)(void), struct minibuf_histhead *hist)
1579 in_minibuffer = 1;
1580 base_map = &minibuffer_map;
1581 current_map = &minibuffer_map;
1583 base_map->unhandled_input = self_insert_fn;
1585 ministate.donefn = donefn;
1586 ministate.abortfn = abortfn;
1587 memset(ministate.buf, 0, sizeof(ministate.buf));
1588 ministate.off = 0;
1589 strlcpy(ministate.buf, "", sizeof(ministate.prompt));
1591 ministate.history = hist;
1592 ministate.hist_cur = NULL;
1593 ministate.hist_off = 0;
1596 static void
1597 exit_minibuffer(void)
1599 wclear(minibuf);
1601 in_minibuffer = 0;
1602 base_map = &global_map;
1603 current_map = &global_map;
1606 static void
1607 switch_to_tab(struct tab *tab)
1609 struct tab *t;
1611 TAILQ_FOREACH(t, &tabshead, tabs) {
1612 t->flags &= ~TAB_CURRENT;
1615 tab->flags |= TAB_CURRENT;
1618 static void
1619 new_tab(void)
1621 struct tab *tab, *t;
1622 const char *url = "about:new";
1624 if ((tab = calloc(1, sizeof(*tab))) == NULL)
1625 goto err;
1627 if ((tab->s = calloc(1, sizeof(*t->s))) == NULL)
1628 goto err;
1630 TAILQ_INIT(&tab->s->head);
1632 tab->id = tab_counter++;
1633 switch_to_tab(tab);
1635 if (TAILQ_EMPTY(&tabshead))
1636 TAILQ_INSERT_HEAD(&tabshead, tab, tabs);
1637 else
1638 TAILQ_INSERT_TAIL(&tabshead, tab, tabs);
1640 load_url_in_tab(tab, url);
1641 return;
1643 err:
1644 event_loopbreak();
1647 int
1648 ui_init(void)
1650 setlocale(LC_ALL, "");
1652 TAILQ_INIT(&global_map.m);
1653 global_map.unhandled_input = global_key_unbound;
1655 TAILQ_INIT(&minibuffer_map.m);
1657 TAILQ_INIT(&eecmd_history.head);
1658 TAILQ_INIT(&ir_history.head);
1659 TAILQ_INIT(&lu_history.head);
1661 base_map = &global_map;
1662 current_map = &global_map;
1663 load_default_keys();
1665 initscr();
1666 raw();
1667 noecho();
1669 nonl();
1670 intrflush(stdscr, FALSE);
1672 if ((tabline = newwin(1, COLS, 0, 0)) == NULL)
1673 return 0;
1674 if ((body = newwin(LINES - 3, COLS, 1, 0)) == NULL)
1675 return 0;
1676 if ((modeline = newwin(1, COLS, LINES-2, 0)) == NULL)
1677 return 0;
1678 if ((minibuf = newwin(1, COLS, LINES-1, 0)) == NULL)
1679 return 0;
1681 body_lines = LINES-3;
1682 body_cols = COLS;
1684 keypad(body, TRUE);
1685 scrollok(body, TRUE);
1687 /* non-blocking input */
1688 wtimeout(body, 0);
1690 mvwprintw(body, 0, 0, "");
1692 event_set(&stdioev, 0, EV_READ | EV_PERSIST, dispatch_stdio, NULL);
1693 event_add(&stdioev, NULL);
1695 signal_set(&winchev, SIGWINCH, handle_resize, NULL);
1696 signal_add(&winchev, NULL);
1698 new_tab();
1700 return 1;
1703 void
1704 ui_on_tab_loaded(struct tab *tab)
1706 stop_loading_anim(tab);
1707 message("Loaded %s", tab->urlstr);
1710 void
1711 ui_on_tab_refresh(struct tab *tab)
1713 if (!(tab->flags & TAB_CURRENT))
1714 return;
1716 wrap_page(tab);
1717 redraw_tab(tab);
1720 void
1721 ui_require_input(struct tab *tab, int hide)
1723 /* TODO: hard-switching to another tab is ugly */
1724 switch_to_tab(tab);
1726 enter_minibuffer(ir_self_insert, ir_select, exit_minibuffer,
1727 &ir_history);
1728 strlcpy(ministate.prompt, "Input required: ",
1729 sizeof(ministate.prompt));
1730 redraw_tab(tab);
1733 void
1734 ui_end(void)
1736 endwin();