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 minibuf_histhead;
78 static struct event stdioev, winchev;
80 static void load_default_keys(void);
81 static int push_line(struct tab*, const struct line*, const char*, size_t, int);
82 static void empty_vlist(struct tab*);
83 static void restore_cursor(struct tab *);
85 static void cmd_previous_line(struct tab*);
86 static void cmd_next_line(struct tab*);
87 static void cmd_forward_char(struct tab*);
88 static void cmd_backward_char(struct tab*);
89 static void cmd_move_beginning_of_line(struct tab*);
90 static void cmd_move_end_of_line(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_push_button_new_tab(struct tab*);
101 static void cmd_clear_minibuf(struct tab*);
102 static void cmd_execute_extended_command(struct tab*);
103 static void cmd_tab_close(struct tab*);
104 static void cmd_tab_new(struct tab*);
105 static void cmd_tab_next(struct tab*);
106 static void cmd_tab_previous(struct tab*);
107 static void cmd_load_url(struct tab*);
108 static void cmd_load_current_url(struct tab*);
110 static void global_key_unbound(void);
112 static void cmd_mini_delete_char(struct tab*);
113 static void cmd_mini_delete_backward_char(struct tab*);
114 static void cmd_mini_forward_char(struct tab*);
115 static void cmd_mini_backward_char(struct tab*);
116 static void cmd_mini_move_end_of_line(struct tab*);
117 static void cmd_mini_move_beginning_of_line(struct tab*);
118 static void cmd_mini_kill_line(struct tab*);
119 static void cmd_mini_abort(struct tab*);
120 static void cmd_mini_complete_and_exit(struct tab*);
121 static void cmd_mini_previous_history_element(struct tab*);
122 static void cmd_mini_next_history_element(struct tab*);
124 static void minibuffer_hist_save_entry(void);
125 static void minibuffer_taint_hist(void);
126 static void minibuffer_self_insert(void);
127 static void eecmd_self_insert(void);
128 static void eecmd_select(void);
129 static void ir_self_insert(void);
130 static void ir_select(void);
131 static void lu_self_insert(void);
132 static void lu_select(void);
134 static struct line *nth_line(struct tab*, size_t);
135 static struct tab *current_tab(void);
136 static void dispatch_stdio(int, short, void*);
137 static void handle_clear_minibuf(int, short, void*);
138 static void handle_resize(int, short, void*);
139 static int word_bourdaries(const char*, const char*, const char**, const char**);
140 static void wrap_text(struct tab*, const char*, struct line*);
141 static int hardwrap_text(struct tab*, struct line*);
142 static int wrap_page(struct tab*);
143 static void print_line(struct line*);
144 static void redraw_tabline(void);
145 static void redraw_body(struct tab*);
146 static void redraw_modeline(struct tab*);
147 static void redraw_minibuffer(void);
148 static void redraw_tab(struct tab*);
149 static void message(const char*, ...) __attribute__((format(printf, 1, 2)));
150 static void start_loading_anim(struct tab*);
151 static void update_loading_anim(int, short, void*);
152 static void stop_loading_anim(struct tab*);
153 static void load_url_in_tab(struct tab*, const char*);
154 static void enter_minibuffer(void(*)(void), void(*)(void), void(*)(void), struct minibuf_histhead*);
155 static void exit_minibuffer(void);
156 static void switch_to_tab(struct tab*);
157 static struct tab *new_tab(void);
159 static struct { int meta, key; } thiskey;
161 static WINDOW *tabline, *body, *modeline, *minibuf;
162 static int body_lines, body_cols;
164 static struct event clminibufev;
165 static int clminibufev_set;
166 static struct timeval clminibufev_timer = { 5, 0 };
167 static struct timeval loadingev_timer = { 0, 250000 };
169 static uint32_t tab_counter;
171 struct ui_state {
172 int curs_x;
173 int curs_y;
174 size_t line_off;
175 size_t line_max;
177 short loading_anim;
178 short loading_anim_step;
179 struct event loadingev;
181 TAILQ_HEAD(, line) head;
182 };
184 static char keybuf[64];
186 struct kmap global_map,
187 minibuffer_map,
188 *current_map,
189 *base_map;
191 /* TODO: limit to a maximum number of entries */
192 struct minibuf_histhead {
193 TAILQ_HEAD(mhisthead, minibuf_hist) head;
194 size_t len;
195 };
196 struct minibuf_hist {
197 char h[1025];
198 TAILQ_ENTRY(minibuf_hist) entries;
199 };
201 static struct minibuf_histhead eecmd_history,
202 ir_history,
203 lu_history;
205 static int in_minibuffer;
207 static struct {
208 char *curmesg;
210 char buf[1025];
211 size_t off, len;
212 char prompt[32];
213 void (*donefn)(void);
214 void (*abortfn)(void);
216 struct minibuf_histhead *history;
217 struct minibuf_hist *hist_cur;
218 size_t hist_off;
219 } ministate;
221 struct lineprefix {
222 const char *prfx1;
223 const char *prfx2;
224 } line_prefixes[] = {
225 [LINE_TEXT] = { "", "" },
226 [LINE_LINK] = { "=> ", " " },
227 [LINE_TITLE_1] = { "# ", " " },
228 [LINE_TITLE_2] = { "## ", " " },
229 [LINE_TITLE_3] = { "### ", " " },
230 [LINE_ITEM] = { "* ", " " },
231 [LINE_QUOTE] = { "> ", "> " },
232 [LINE_PRE_START] = { "```", "```" },
233 [LINE_PRE_CONTENT] = { "", "" },
234 [LINE_PRE_END] = { "```", "```" },
235 };
237 struct line_face {
238 int prop;
239 } line_faces[] = {
240 [LINE_TEXT] = { 0 },
241 [LINE_LINK] = { A_UNDERLINE },
242 [LINE_TITLE_1] = { A_BOLD },
243 [LINE_TITLE_2] = { A_BOLD },
244 [LINE_TITLE_3] = { A_BOLD },
245 [LINE_ITEM] = { 0 },
246 [LINE_QUOTE] = { A_DIM },
247 [LINE_PRE_START] = { 0 },
248 [LINE_PRE_CONTENT] = { 0 },
249 [LINE_PRE_END] = { 0 },
250 };
252 static inline void
253 global_set_key(const char *key, void (*fn)(struct tab*))
255 if (!kmap_define_key(&global_map, key, fn))
256 _exit(1);
259 static inline void
260 minibuffer_set_key(const char *key, void (*fn)(struct tab*))
262 if (!kmap_define_key(&minibuffer_map, key, fn))
263 _exit(1);
266 static void
267 load_default_keys(void)
269 /* === global map === */
271 /* emacs */
272 global_set_key("C-p", cmd_previous_line);
273 global_set_key("C-n", cmd_next_line);
274 global_set_key("C-f", cmd_forward_char);
275 global_set_key("C-b", cmd_backward_char);
276 global_set_key("C-a", cmd_move_beginning_of_line);
277 global_set_key("C-e", cmd_move_end_of_line);
279 global_set_key("M-v", cmd_scroll_up);
280 global_set_key("C-v", cmd_scroll_down);
281 global_set_key("M-space", cmd_scroll_up);
282 global_set_key("space", cmd_scroll_down);
284 global_set_key("C-x C-c", cmd_kill_telescope);
286 global_set_key("C-g", cmd_clear_minibuf);
288 global_set_key("M-x", cmd_execute_extended_command);
289 global_set_key("C-x C-f", cmd_load_url);
290 global_set_key("C-x M-f", cmd_load_current_url);
292 global_set_key("C-x t 0", cmd_tab_close);
293 global_set_key("C-x t 2", cmd_tab_new);
294 global_set_key("C-x t o", cmd_tab_next);
295 global_set_key("C-x t O", cmd_tab_previous);
297 global_set_key("M-<", cmd_beginning_of_buffer);
298 global_set_key("M->", cmd_end_of_buffer);
300 /* vi/vi-like */
301 global_set_key("k", cmd_previous_line);
302 global_set_key("j", cmd_next_line);
303 global_set_key("l", cmd_forward_char);
304 global_set_key("h", cmd_backward_char);
305 global_set_key("^", cmd_move_beginning_of_line);
306 global_set_key("$", cmd_move_end_of_line);
308 global_set_key("K", cmd_scroll_line_up);
309 global_set_key("J", cmd_scroll_line_down);
311 global_set_key("g g", cmd_beginning_of_buffer);
312 global_set_key("G", cmd_end_of_buffer);
314 /* tmp */
315 global_set_key("q", cmd_kill_telescope);
317 global_set_key("esc", cmd_clear_minibuf);
319 global_set_key(":", cmd_execute_extended_command);
321 /* cua */
322 global_set_key("<up>", cmd_previous_line);
323 global_set_key("<down>", cmd_next_line);
324 global_set_key("<right>", cmd_forward_char);
325 global_set_key("<left>", cmd_backward_char);
326 global_set_key("<prior>", cmd_scroll_up);
327 global_set_key("<next>", cmd_scroll_down);
329 /* "ncurses standard" */
330 global_set_key("C-l", cmd_redraw);
332 /* global */
333 global_set_key("C-m", cmd_push_button);
334 global_set_key("M-enter", cmd_push_button_new_tab);
336 /* === minibuffer map === */
337 minibuffer_set_key("ret", cmd_mini_complete_and_exit);
338 minibuffer_set_key("C-g", cmd_mini_abort);
339 minibuffer_set_key("esc", cmd_mini_abort);
340 minibuffer_set_key("C-d", cmd_mini_delete_char);
341 minibuffer_set_key("del", cmd_mini_delete_backward_char);
343 minibuffer_set_key("C-f", cmd_mini_forward_char);
344 minibuffer_set_key("C-b", cmd_mini_backward_char);
345 minibuffer_set_key("<right>", cmd_mini_forward_char);
346 minibuffer_set_key("<left>", cmd_mini_backward_char);
347 minibuffer_set_key("C-e", cmd_mini_move_end_of_line);
348 minibuffer_set_key("C-a", cmd_mini_move_beginning_of_line);
349 minibuffer_set_key("<end>", cmd_mini_move_end_of_line);
350 minibuffer_set_key("<home>", cmd_mini_move_beginning_of_line);
351 minibuffer_set_key("C-k", cmd_mini_kill_line);
353 minibuffer_set_key("M-p", cmd_mini_previous_history_element);
354 minibuffer_set_key("M-n", cmd_mini_next_history_element);
355 minibuffer_set_key("<up>", cmd_mini_previous_history_element);
356 minibuffer_set_key("<down>", cmd_mini_next_history_element);
359 static int
360 push_line(struct tab *tab, const struct line *l, const char *buf, size_t len, int cont)
362 struct line *vl;
364 tab->s->line_max++;
366 if ((vl = calloc(1, sizeof(*vl))) == NULL)
367 return 0;
369 if (len != 0 && (vl->line = calloc(1, len+1)) == NULL) {
370 free(vl);
371 return 0;
374 vl->type = l->type;
375 if (len != 0)
376 memcpy(vl->line, buf, len);
377 vl->alt = l->alt;
378 vl->flags = cont;
380 if (TAILQ_EMPTY(&tab->s->head))
381 TAILQ_INSERT_HEAD(&tab->s->head, vl, lines);
382 else
383 TAILQ_INSERT_TAIL(&tab->s->head, vl, lines);
384 return 1;
387 static void
388 empty_vlist(struct tab *tab)
390 struct line *l, *t;
392 tab->s->line_max = 0;
394 TAILQ_FOREACH_SAFE(l, &tab->s->head, lines, t) {
395 TAILQ_REMOVE(&tab->s->head, l, lines);
396 free(l->line);
397 /* l->alt references the original line! */
398 free(l);
402 static void
403 restore_cursor(struct tab *tab)
405 wmove(body, tab->s->curs_y, tab->s->curs_x);
408 static void
409 cmd_previous_line(struct tab *tab)
411 if (--tab->s->curs_y < 0) {
412 tab->s->curs_y = 0;
413 cmd_scroll_line_up(tab);
416 restore_cursor(tab);
419 static void
420 cmd_next_line(struct tab *tab)
422 if (tab->s->line_off + tab->s->curs_y >= tab->s->line_max)
423 return;
425 if (++tab->s->curs_y > body_lines-1) {
426 tab->s->curs_y = body_lines-1;
427 cmd_scroll_line_down(tab);
430 restore_cursor(tab);
433 static void
434 cmd_forward_char(struct tab *tab)
436 tab->s->curs_x = MIN(body_cols-1, tab->s->curs_x+1);
437 restore_cursor(tab);
440 static void
441 cmd_backward_char(struct tab *tab)
443 tab->s->curs_x = MAX(0, tab->s->curs_x-1);
444 restore_cursor(tab);
447 static void
448 cmd_move_beginning_of_line(struct tab *tab)
450 tab->s->curs_x = 0;
451 restore_cursor(tab);
454 static void
455 cmd_move_end_of_line(struct tab *tab)
457 struct line *line;
458 size_t off;
459 const char *prfx;
461 off = tab->s->line_off + tab->s->curs_y;
462 if (off >= tab->s->line_max) {
463 tab->s->curs_x = 0;
464 goto end;
467 line = nth_line(tab, off);
468 if (line->line != NULL)
469 tab->s->curs_x = strlen(line->line);
470 else
471 tab->s->curs_x = 0;
473 prfx = line_prefixes[line->type].prfx1;
474 tab->s->curs_x += strlen(prfx);
476 end:
477 restore_cursor(tab);
480 static void
481 cmd_redraw(struct tab *tab)
483 handle_resize(0, 0, NULL);
486 static void
487 cmd_scroll_line_up(struct tab *tab)
489 struct line *l;
491 if (tab->s->line_off == 0)
492 return;
494 l = nth_line(tab, --tab->s->line_off);
495 wscrl(body, -1);
496 wmove(body, 0, 0);
497 print_line(l);
500 static void
501 cmd_scroll_line_down(struct tab *tab)
503 struct line *l;
504 size_t n;
506 if (tab->s->line_max == 0 || tab->s->line_off == tab->s->line_max-1)
507 return;
509 tab->s->line_off++;
510 wscrl(body, 1);
512 if (tab->s->line_max - tab->s->line_off < body_lines)
513 return;
515 l = nth_line(tab, tab->s->line_off + body_lines-1);
516 wmove(body, body_lines-1, 0);
517 print_line(l);
520 static void
521 cmd_scroll_up(struct tab *tab)
523 size_t off;
525 off = body_lines+1;
527 for (; off > 0; --off)
528 cmd_scroll_line_up(tab);
531 static void
532 cmd_scroll_down(struct tab *tab)
534 size_t off;
536 off = body_lines+1;
538 for (; off > 0; --off)
539 cmd_scroll_line_down(tab);
542 static void
543 cmd_beginning_of_buffer(struct tab *tab)
545 tab->s->line_off = 0;
546 tab->s->curs_y = 0;
547 redraw_body(tab);
550 static void
551 cmd_end_of_buffer(struct tab *tab)
553 ssize_t off;
555 off = tab->s->line_max - body_lines;
556 off = MAX(0, off);
558 tab->s->line_off = off;
559 tab->s->curs_y = MIN(body_lines, tab->s->line_max);
561 redraw_body(tab);
564 static void
565 cmd_kill_telescope(struct tab *tab)
567 event_loopbreak();
570 static void
571 cmd_push_button(struct tab *tab)
573 struct line *l;
574 size_t nth;
576 nth = tab->s->line_off + tab->s->curs_y;
577 if (nth >= tab->s->line_max)
578 return;
579 l = nth_line(tab, nth);
580 if (l->type != LINE_LINK)
581 return;
583 load_url_in_tab(tab, l->alt);
586 static void
587 cmd_push_button_new_tab(struct tab *tab)
589 struct tab *t;
590 struct line *l;
591 size_t nth;
593 nth = tab->s->line_off + tab->s->curs_y;
594 if (nth > tab->s->line_max)
595 return;
596 l = nth_line(tab, nth);
597 if (l->type != LINE_LINK)
598 return;
600 t = new_tab();
601 memcpy(&t->url, &tab->url, sizeof(tab->url));
602 memcpy(&t->urlstr, &tab->urlstr, sizeof(tab->urlstr));
603 load_url_in_tab(t, l->alt);
606 static void
607 cmd_clear_minibuf(struct tab *tab)
609 handle_clear_minibuf(0, 0, NULL);
612 static void
613 cmd_execute_extended_command(struct tab *tab)
615 size_t len;
617 enter_minibuffer(eecmd_self_insert, eecmd_select, exit_minibuffer,
618 &eecmd_history);
620 len = sizeof(ministate.prompt);
621 strlcpy(ministate.prompt, "", len);
623 if (thiskey.meta)
624 strlcat(ministate.prompt, "M-", len);
626 strlcat(ministate.prompt, keyname(thiskey.key), len);
627 strlcat(ministate.prompt, " ", len);
630 static void
631 cmd_tab_close(struct tab *tab)
633 struct tab *t;
635 if (TAILQ_PREV(tab, tabshead, tabs) == NULL &&
636 TAILQ_NEXT(tab, tabs) == NULL) {
637 message("Can't close the only tab.");
638 return;
641 stop_tab(tab);
643 t = TAILQ_PREV(tab, tabshead, tabs);
644 t->flags |= TAB_CURRENT;
646 TAILQ_REMOVE(&tabshead, tab, tabs);
648 free(tab->s);
649 free(tab);
652 static void
653 cmd_tab_new(struct tab *tab)
655 new_tab();
658 static void
659 cmd_tab_next(struct tab *tab)
661 struct tab *t;
663 tab->flags &= ~TAB_CURRENT;
665 if ((t = TAILQ_NEXT(tab, tabs)) == NULL)
666 t = TAILQ_FIRST(&tabshead);
667 t->flags |= TAB_CURRENT;
670 static void
671 cmd_tab_previous(struct tab *tab)
673 struct tab *t;
675 tab->flags &= ~TAB_CURRENT;
677 if ((t = TAILQ_PREV(tab, tabshead, tabs)) == NULL)
678 t = TAILQ_LAST(&tabshead, tabshead);
679 t->flags |= TAB_CURRENT;
682 static void
683 cmd_load_url(struct tab *tab)
685 enter_minibuffer(lu_self_insert, lu_select, exit_minibuffer,
686 &lu_history);
687 strlcpy(ministate.prompt, "Load URL: ", sizeof(ministate.prompt));
690 static void
691 cmd_load_current_url(struct tab *tab)
693 enter_minibuffer(lu_self_insert, lu_select, exit_minibuffer,
694 &lu_history);
695 strlcpy(ministate.prompt, "Load URL: ", sizeof(ministate.prompt));
696 strlcpy(ministate.buf, tab->urlstr, sizeof(ministate.buf));
697 ministate.off = strlen(tab->urlstr);
698 ministate.len = ministate.off;
701 static void
702 global_key_unbound(void)
704 message("%s is undefined", keybuf);
707 static void
708 cmd_mini_delete_char(struct tab *tab)
710 minibuffer_taint_hist();
712 if (ministate.len == 0 || ministate.off == ministate.len)
713 return;
715 memmove(&ministate.buf[ministate.off],
716 &ministate.buf[ministate.off+1],
717 ministate.len - ministate.off + 1);
718 ministate.len--;
721 static void
722 cmd_mini_delete_backward_char(struct tab *tab)
724 minibuffer_taint_hist();
726 if (ministate.len == 0 || ministate.off == 0)
727 return;
729 memmove(&ministate.buf[ministate.off-1],
730 &ministate.buf[ministate.off],
731 ministate.len - ministate.off + 1);
732 ministate.off--;
733 ministate.len--;
736 static void
737 cmd_mini_forward_char(struct tab *tab)
739 if (ministate.off == ministate.len)
740 return;
741 ministate.off++;
744 static void
745 cmd_mini_backward_char(struct tab *tab)
747 if (ministate.off == 0)
748 return;
749 ministate.off--;
752 static void
753 cmd_mini_move_end_of_line(struct tab *tab)
755 ministate.off = ministate.len;
758 static void
759 cmd_mini_move_beginning_of_line(struct tab *tab)
761 ministate.off = 0;
764 static void
765 cmd_mini_kill_line(struct tab *tab)
767 minibuffer_taint_hist();
769 if (ministate.off == ministate.len)
770 return;
771 ministate.buf[ministate.off] = '\0';
772 ministate.len -= ministate.off;
775 static void
776 cmd_mini_abort(struct tab *tab)
778 ministate.abortfn();
781 static void
782 cmd_mini_complete_and_exit(struct tab *tab)
784 minibuffer_taint_hist();
785 ministate.donefn();
788 static void
789 cmd_mini_previous_history_element(struct tab *tab)
791 if (ministate.history == NULL) {
792 message("No history");
793 return;
796 if (ministate.hist_cur == NULL ||
797 (ministate.hist_cur = TAILQ_PREV(ministate.hist_cur, mhisthead, entries)) == NULL) {
798 ministate.hist_cur = TAILQ_LAST(&ministate.history->head, mhisthead);
799 ministate.hist_off = ministate.history->len - 1;
800 if (ministate.hist_cur == NULL)
801 message("No prev item");
802 } else {
803 ministate.hist_off--;
806 if (ministate.hist_cur != NULL) {
807 ministate.off = 0;
808 ministate.len = strlen(ministate.hist_cur->h);
812 static void
813 cmd_mini_next_history_element(struct tab *tab)
815 if (ministate.history == NULL) {
816 message("No history");
817 return;
820 if (ministate.hist_cur == NULL ||
821 (ministate.hist_cur = TAILQ_NEXT(ministate.hist_cur, entries)) == NULL) {
822 ministate.hist_cur = TAILQ_FIRST(&ministate.history->head);
823 ministate.hist_off = 0;
824 if (ministate.hist_cur == NULL)
825 message("No next item");
826 } else {
827 ministate.hist_off++;
830 if (ministate.hist_cur != NULL) {
831 ministate.off = 0;
832 ministate.len = strlen(ministate.hist_cur->h);
836 static void
837 minibuffer_hist_save_entry(void)
839 struct minibuf_hist *hist;
841 if (ministate.history == NULL)
842 return;
844 if ((hist = calloc(1, sizeof(*hist))) == NULL)
845 abort();
847 strlcpy(hist->h, ministate.buf, sizeof(hist->h));
849 if (TAILQ_EMPTY(&ministate.history->head))
850 TAILQ_INSERT_HEAD(&ministate.history->head, hist, entries);
851 else
852 TAILQ_INSERT_TAIL(&ministate.history->head, hist, entries);
853 ministate.history->len++;
856 /*
857 * taint the minibuffer cache: if we're currently showing a history
858 * element, copy that to the current buf and reset the "history
859 * navigation" thing.
860 */
861 static void
862 minibuffer_taint_hist(void)
864 if (ministate.hist_cur == NULL)
865 return;
867 strlcpy(ministate.buf, ministate.hist_cur->h, sizeof(ministate.buf));
868 ministate.hist_cur = NULL;
871 static void
872 minibuffer_self_insert(void)
874 minibuffer_taint_hist();
876 if (ministate.len == sizeof(ministate.buf) -1)
877 return;
879 /* TODO: utf8 handling! */
881 memmove(&ministate.buf[ministate.off+1],
882 &ministate.buf[ministate.off],
883 ministate.len - ministate.off + 1);
884 ministate.buf[ministate.off] = thiskey.key;
885 ministate.off++;
886 ministate.len++;
889 static void
890 eecmd_self_insert(void)
892 if (thiskey.meta || isspace(thiskey.key) ||
893 !isgraph(thiskey.key)) {
894 global_key_unbound();
895 return;
898 minibuffer_self_insert();
901 static void
902 eecmd_select(void)
904 exit_minibuffer();
905 minibuffer_hist_save_entry();
906 message("TODO: try to execute %s", ministate.buf);
909 static void
910 ir_self_insert(void)
912 minibuffer_self_insert();
915 static void
916 ir_select(void)
918 char buf[1025] = {0};
919 struct url url;
920 struct tab *tab;
922 tab = current_tab();
924 exit_minibuffer();
925 minibuffer_hist_save_entry();
927 /* a bit ugly but... */
928 memcpy(&url, &tab->url, sizeof(tab->url));
929 url_set_query(&url, ministate.buf);
930 url_unparse(&url, buf, sizeof(buf));
931 load_url_in_tab(tab, buf);
934 static void
935 lu_self_insert(void)
937 if (thiskey.meta || isspace(thiskey.key) ||
938 !isgraph(thiskey.key)) {
939 global_key_unbound();
940 return;
943 minibuffer_self_insert();
946 static void
947 lu_select(void)
949 exit_minibuffer();
950 minibuffer_hist_save_entry();
951 load_url_in_tab(current_tab(), ministate.buf);
954 static struct line *
955 nth_line(struct tab *tab, size_t n)
957 struct line *l;
958 size_t i;
960 i = 0;
961 TAILQ_FOREACH(l, &tab->s->head, lines) {
962 if (i == n)
963 return l;
964 i++;
967 /* unreachable */
968 abort();
971 static struct tab *
972 current_tab(void)
974 struct tab *t;
976 TAILQ_FOREACH(t, &tabshead, tabs) {
977 if (t->flags & TAB_CURRENT)
978 return t;
981 /* unreachable */
982 abort();
985 static void
986 dispatch_stdio(int fd, short ev, void *d)
988 struct tab *tab;
989 struct keymap *k;
990 const char *keyname;
991 char tmp[2] = {0};
993 thiskey.key = wgetch(body);
994 if (thiskey.key == ERR)
995 return;
996 if (thiskey.key == 27) {
997 /* TODO: make escape-time customizable */
999 thiskey.meta = 1;
1000 thiskey.key = wgetch(body);
1001 if (thiskey.key == ERR || thiskey.key == 27) {
1002 thiskey.meta = 0;
1003 thiskey.key = 27;
1005 } else
1006 thiskey.meta = 0;
1008 if (keybuf[0] != '\0')
1009 strlcat(keybuf, " ", sizeof(keybuf));
1010 if (thiskey.meta)
1011 strlcat(keybuf, "M-", sizeof(keybuf));
1012 if ((keyname = unkbd(thiskey.key)) != NULL)
1013 strlcat(keybuf, keyname, sizeof(keybuf));
1014 else {
1015 tmp[0] = thiskey.key;
1016 strlcat(keybuf, tmp, sizeof(keybuf));
1019 TAILQ_FOREACH(k, &current_map->m, keymaps) {
1020 if (k->meta == thiskey.meta &&
1021 k->key == thiskey.key) {
1022 if (k->fn == NULL)
1023 current_map = &k->map;
1024 else {
1025 current_map = base_map;
1026 strlcpy(keybuf, "", sizeof(keybuf));
1027 k->fn(current_tab());
1029 goto done;
1033 if (current_map->unhandled_input != NULL)
1034 current_map->unhandled_input();
1035 else {
1036 global_key_unbound();
1039 strlcpy(keybuf, "", sizeof(keybuf));
1040 current_map = base_map;
1042 done:
1043 redraw_tab(current_tab());
1046 static void
1047 handle_clear_minibuf(int fd, short ev, void *d)
1049 clminibufev_set = 0;
1051 free(ministate.curmesg);
1052 ministate.curmesg = NULL;
1054 redraw_minibuffer();
1055 if (in_minibuffer) {
1056 wrefresh(body);
1057 wrefresh(minibuf);
1058 } else {
1059 wrefresh(minibuf);
1060 wrefresh(body);
1064 static void
1065 handle_resize(int sig, short ev, void *d)
1067 struct tab *tab;
1069 endwin();
1070 refresh();
1071 clear();
1073 /* move and resize the windows, in reverse order! */
1075 mvwin(minibuf, LINES-1, 0);
1076 wresize(minibuf, 1, COLS);
1078 mvwin(modeline, LINES-2, 0);
1079 wresize(modeline, 1, COLS);
1081 wresize(body, LINES-3, COLS);
1082 body_lines = LINES-3;
1083 body_cols = COLS;
1085 wresize(tabline, 1, COLS);
1087 tab = current_tab();
1089 wrap_page(tab);
1090 redraw_tab(tab);
1094 * Helper function for wrap_text. Find the end of the current word
1095 * and the end of the separator after the word.
1097 static int
1098 word_boundaries(const char *s, const char *sep, const char **endword, const char **endspc)
1100 *endword = s;
1101 *endword = s;
1103 if (*s == '\0')
1104 return 0;
1106 /* find the end of the current world */
1107 for (; *s != '\0'; ++s) {
1108 if (strchr(sep, *s) != NULL)
1109 break;
1112 *endword = s;
1114 /* find the end of the separator */
1115 for (; *s != '\0'; ++s) {
1116 if (strchr(sep, *s) == NULL)
1117 break;
1120 *endspc = s;
1122 return 1;
1125 static inline int
1126 emitline(struct tab *tab, size_t zero, size_t *off, const struct line *l,
1127 const char **line, int *cont)
1129 if (!push_line(tab, l, *line, *off - zero, *cont))
1130 return 0;
1131 if (!*cont)
1132 *cont = 1;
1133 *line += *off - zero;
1134 *off = zero;
1135 return 1;
1138 static inline void
1139 emitstr(const char **s, size_t len, size_t *off)
1141 size_t i;
1143 /* printw("%*s", ...) doesn't seem to respect the precision, so... */
1144 for (i = 0; i < len; ++i)
1145 addch((*s)[i]);
1146 *off += len;
1147 *s += len;
1151 * Build a list of visual line by wrapping the given line, assuming
1152 * that when printed will have a leading prefix prfx.
1154 * TODO: it considers each byte one cell on the screen!
1156 static void
1157 wrap_text(struct tab *tab, const char *prfx, struct line *l)
1159 size_t zero, off, len, split;
1160 int cont = 0;
1161 const char *endword, *endspc, *line, *linestart;
1163 zero = strlen(prfx);
1164 off = zero;
1165 line = l->line;
1166 linestart = l->line;
1168 while (word_boundaries(line, " \t-", &endword, &endspc)) {
1169 len = endword - line;
1170 if (off + len >= body_cols) {
1171 emitline(tab, zero, &off, l, &linestart, &cont);
1172 while (len >= body_cols) {
1173 /* hard wrap */
1174 emitline(tab, zero, &off, l, &linestart, &cont);
1175 len -= body_cols-1;
1176 line += body_cols-1;
1179 if (len != 0)
1180 off += len;
1181 } else
1182 off += len;
1184 /* print the spaces iff not at bol */
1185 len = endspc - endword;
1186 /* line = endspc; */
1187 if (off != zero) {
1188 if (off + len >= body_cols) {
1189 emitline(tab, zero, &off, l, &linestart, &cont);
1190 linestart = endspc;
1191 } else
1192 off += len;
1195 line = endspc;
1198 emitline(tab, zero, &off, l, &linestart, &cont);
1201 static int
1202 hardwrap_text(struct tab *tab, struct line *l)
1204 size_t off, len;
1205 int cont;
1206 const char *linestart;
1208 if (l->line == NULL)
1209 return emitline(tab, 0, &off, l, &linestart, &cont);
1211 len = strlen(l->line);
1212 off = 0;
1213 linestart = l->line;
1215 while (len >= COLS) {
1216 len -= COLS-1;
1217 off = COLS-1;
1218 if (!emitline(tab, 0, &off, l, &linestart, &cont))
1219 return 0;
1222 if (len != 0)
1223 return emitline(tab, 0, &len, l, &linestart, &cont);
1225 return 1;
1228 static int
1229 wrap_page(struct tab *tab)
1231 struct line *l;
1232 const char *prfx;
1234 empty_vlist(tab);
1236 TAILQ_FOREACH(l, &tab->page.head, lines) {
1237 prfx = line_prefixes[l->type].prfx1;
1238 switch (l->type) {
1239 case LINE_TEXT:
1240 case LINE_LINK:
1241 case LINE_TITLE_1:
1242 case LINE_TITLE_2:
1243 case LINE_TITLE_3:
1244 case LINE_ITEM:
1245 case LINE_QUOTE:
1246 wrap_text(tab, prfx, l);
1247 break;
1248 case LINE_PRE_START:
1249 case LINE_PRE_END:
1250 push_line(tab, l, NULL, 0, 0);
1251 break;
1252 case LINE_PRE_CONTENT:
1253 hardwrap_text(tab, l);
1254 break;
1257 return 1;
1260 static inline void
1261 print_line(struct line *l)
1263 const char *text = l->line;
1264 const char *prfx;
1265 int face = line_faces[l->type].prop;
1267 if (!l->flags)
1268 prfx = line_prefixes[l->type].prfx1;
1269 else
1270 prfx = line_prefixes[l->type].prfx2;
1272 if (text == NULL)
1273 text = "";
1275 if (face != 0)
1276 wattron(body, face);
1277 wprintw(body, "%s%s", prfx, text);
1278 if (face != 0)
1279 wattroff(body, face);
1282 static void
1283 redraw_tabline(void)
1285 struct tab *tab;
1286 int current;
1288 werase(tabline);
1289 wbkgd(tabline, A_REVERSE);
1291 wprintw(tabline, " ");
1292 TAILQ_FOREACH(tab, &tabshead, tabs) {
1293 current = tab->flags & TAB_CURRENT;
1295 if (current)
1296 wattron(tabline, A_UNDERLINE);
1298 wprintw(tabline, "%s%d:todo title ",
1299 current ? "*" : " ", tab->id);
1301 if (current)
1302 wattroff(tabline, A_UNDERLINE);
1306 static void
1307 redraw_modeline(struct tab *tab)
1309 double pct;
1310 int x, y, max_x, max_y;
1311 const char *mode = tab->page.name;
1312 const char *spin = "-\\|/";
1314 werase(modeline);
1315 wattron(modeline, A_REVERSE);
1316 wmove(modeline, 0, 0);
1318 wprintw(modeline, "-%c %s-mode ",
1319 spin[tab->s->loading_anim_step], mode);
1321 pct = (tab->s->line_off + tab->s->curs_y) * 100.0 / tab->s->line_max;
1323 if (tab->s->line_max <= body_lines)
1324 wprintw(modeline, "All ");
1325 else if (tab->s->line_off == 0)
1326 wprintw(modeline, "Top ");
1327 else if (tab->s->line_off + body_lines >= tab->s->line_max)
1328 wprintw(modeline, "Bottom ");
1329 else
1330 wprintw(modeline, "%.0f%% ", pct);
1332 wprintw(modeline, "%d/%d %s ",
1333 tab->s->line_off + tab->s->curs_y,
1334 tab->s->line_max,
1335 tab->urlstr);
1337 getyx(modeline, y, x);
1338 getmaxyx(modeline, max_y, max_x);
1340 (void)y;
1341 (void)max_y;
1343 for (; x < max_x; ++x)
1344 waddstr(modeline, "-");
1347 static void
1348 redraw_minibuffer(void)
1350 size_t skip = 0, off_x = 0, off_y = 0;
1352 werase(minibuf);
1353 if (in_minibuffer) {
1354 mvwprintw(minibuf, 0, 0, "%s", ministate.prompt);
1355 if (ministate.hist_cur != NULL)
1356 wprintw(minibuf, "(%zu/%zu) ",
1357 ministate.hist_off + 1,
1358 ministate.history->len);
1360 getyx(minibuf, off_y, off_x);
1362 while (ministate.off - skip > COLS / 2) {
1363 skip += MIN(ministate.off/4, 1);
1366 if (ministate.hist_cur != NULL)
1367 wprintw(minibuf, "%s", ministate.hist_cur->h + skip);
1368 else
1369 wprintw(minibuf, "%s", ministate.buf + skip);
1372 if (ministate.curmesg != NULL) {
1373 if (in_minibuffer)
1374 wprintw(minibuf, " [%s]", ministate.curmesg);
1375 else
1376 wprintw(minibuf, "%s", ministate.curmesg);
1379 if (!in_minibuffer && ministate.curmesg == NULL)
1380 wprintw(minibuf, "%s", keybuf);
1382 if (in_minibuffer)
1383 wmove(minibuf, 0, off_x + ministate.off - skip);
1386 static void
1387 redraw_tab(struct tab *tab)
1389 redraw_tabline();
1390 redraw_body(tab);
1391 redraw_modeline(tab);
1392 redraw_minibuffer();
1394 restore_cursor(tab);
1395 wrefresh(tabline);
1396 wrefresh(modeline);
1398 if (in_minibuffer) {
1399 wrefresh(body);
1400 wrefresh(minibuf);
1401 } else {
1402 wrefresh(minibuf);
1403 wrefresh(body);
1407 static void
1408 redraw_body(struct tab *tab)
1410 struct line *l;
1411 int line;
1413 werase(body);
1415 tab->s->line_off = MIN(tab->s->line_max, tab->s->line_off);
1416 if (TAILQ_EMPTY(&tab->s->head))
1417 return;
1419 line = 0;
1420 l = nth_line(tab, tab->s->line_off);
1421 for (; l != NULL; l = TAILQ_NEXT(l, lines)) {
1422 wmove(body, line, 0);
1423 print_line(l);
1424 line++;
1425 if (line == body_lines)
1426 break;
1430 static void
1431 message(const char *fmt, ...)
1433 va_list ap;
1435 if (clminibufev_set)
1436 evtimer_del(&clminibufev);
1437 evtimer_set(&clminibufev, handle_clear_minibuf, NULL);
1438 evtimer_add(&clminibufev, &clminibufev_timer);
1439 clminibufev_set = 1;
1441 free(ministate.curmesg);
1443 va_start(ap, fmt);
1444 /* TODO: what to do if the allocation fails here? */
1445 if (vasprintf(&ministate.curmesg, fmt, ap) == -1)
1446 ministate.curmesg = NULL;
1447 va_end(ap);
1449 redraw_minibuffer();
1451 if (in_minibuffer) {
1452 wrefresh(body);
1453 wrefresh(minibuf);
1454 } else {
1455 wrefresh(minibuf);
1456 wrefresh(body);
1460 static void
1461 start_loading_anim(struct tab *tab)
1463 if (tab->s->loading_anim)
1464 return;
1465 tab->s->loading_anim = 1;
1466 evtimer_set(&tab->s->loadingev, update_loading_anim, tab);
1467 evtimer_add(&tab->s->loadingev, &loadingev_timer);
1470 static void
1471 update_loading_anim(int fd, short ev, void *d)
1473 struct tab *tab = d;
1475 tab->s->loading_anim_step = (tab->s->loading_anim_step+1)%4;
1477 redraw_modeline(tab);
1478 wrefresh(modeline);
1480 wrefresh(body);
1481 if (in_minibuffer)
1482 wrefresh(minibuf);
1484 evtimer_add(&tab->s->loadingev, &loadingev_timer);
1487 static void
1488 stop_loading_anim(struct tab *tab)
1490 if (!tab->s->loading_anim)
1491 return;
1492 evtimer_del(&tab->s->loadingev);
1493 tab->s->loading_anim = 0;
1494 tab->s->loading_anim_step = 0;
1496 redraw_modeline(tab);
1498 wrefresh(modeline);
1499 wrefresh(body);
1500 if (in_minibuffer)
1501 wrefresh(minibuf);
1504 static void
1505 load_url_in_tab(struct tab *tab, const char *url)
1507 empty_vlist(tab);
1508 message("Loading %s...", url);
1509 start_loading_anim(tab);
1510 load_url(tab, url);
1512 tab->s->curs_x = 0;
1513 tab->s->curs_y = 0;
1514 redraw_tab(tab);
1517 static void
1518 enter_minibuffer(void (*self_insert_fn)(void), void (*donefn)(void),
1519 void (*abortfn)(void), struct minibuf_histhead *hist)
1521 in_minibuffer = 1;
1522 base_map = &minibuffer_map;
1523 current_map = &minibuffer_map;
1525 base_map->unhandled_input = self_insert_fn;
1527 ministate.donefn = donefn;
1528 ministate.abortfn = abortfn;
1529 memset(ministate.buf, 0, sizeof(ministate.buf));
1530 ministate.off = 0;
1531 ministate.len = 0;
1532 strlcpy(ministate.buf, "", sizeof(ministate.prompt));
1534 ministate.history = hist;
1535 ministate.hist_cur = NULL;
1536 ministate.hist_off = 0;
1539 static void
1540 exit_minibuffer(void)
1542 werase(minibuf);
1544 in_minibuffer = 0;
1545 base_map = &global_map;
1546 current_map = &global_map;
1549 static void
1550 switch_to_tab(struct tab *tab)
1552 struct tab *t;
1554 TAILQ_FOREACH(t, &tabshead, tabs) {
1555 t->flags &= ~TAB_CURRENT;
1558 tab->flags |= TAB_CURRENT;
1561 static struct tab *
1562 new_tab(void)
1564 struct tab *tab, *t;
1565 const char *url = "about:new";
1567 if ((tab = calloc(1, sizeof(*tab))) == NULL)
1568 goto err;
1570 if ((tab->s = calloc(1, sizeof(*t->s))) == NULL)
1571 goto err;
1573 TAILQ_INIT(&tab->s->head);
1575 tab->id = tab_counter++;
1576 switch_to_tab(tab);
1578 if (TAILQ_EMPTY(&tabshead))
1579 TAILQ_INSERT_HEAD(&tabshead, tab, tabs);
1580 else
1581 TAILQ_INSERT_TAIL(&tabshead, tab, tabs);
1583 load_url_in_tab(tab, url);
1584 return tab;
1586 err:
1587 event_loopbreak();
1588 return NULL;
1591 int
1592 ui_init(void)
1594 setlocale(LC_ALL, "");
1596 TAILQ_INIT(&global_map.m);
1597 global_map.unhandled_input = global_key_unbound;
1599 TAILQ_INIT(&minibuffer_map.m);
1601 TAILQ_INIT(&eecmd_history.head);
1602 TAILQ_INIT(&ir_history.head);
1603 TAILQ_INIT(&lu_history.head);
1605 base_map = &global_map;
1606 current_map = &global_map;
1607 load_default_keys();
1609 initscr();
1610 raw();
1611 noecho();
1613 nonl();
1614 intrflush(stdscr, FALSE);
1616 if ((tabline = newwin(1, COLS, 0, 0)) == NULL)
1617 return 0;
1618 if ((body = newwin(LINES - 3, COLS, 1, 0)) == NULL)
1619 return 0;
1620 if ((modeline = newwin(1, COLS, LINES-2, 0)) == NULL)
1621 return 0;
1622 if ((minibuf = newwin(1, COLS, LINES-1, 0)) == NULL)
1623 return 0;
1625 body_lines = LINES-3;
1626 body_cols = COLS;
1628 keypad(body, TRUE);
1629 scrollok(body, TRUE);
1631 /* non-blocking input */
1632 wtimeout(body, 0);
1634 mvwprintw(body, 0, 0, "");
1636 event_set(&stdioev, 0, EV_READ | EV_PERSIST, dispatch_stdio, NULL);
1637 event_add(&stdioev, NULL);
1639 signal_set(&winchev, SIGWINCH, handle_resize, NULL);
1640 signal_add(&winchev, NULL);
1642 new_tab();
1644 return 1;
1647 void
1648 ui_on_tab_loaded(struct tab *tab)
1650 stop_loading_anim(tab);
1651 message("Loaded %s", tab->urlstr);
1654 void
1655 ui_on_tab_refresh(struct tab *tab)
1657 if (!(tab->flags & TAB_CURRENT))
1658 return;
1660 wrap_page(tab);
1661 redraw_tab(tab);
1664 void
1665 ui_require_input(struct tab *tab, int hide)
1667 /* TODO: hard-switching to another tab is ugly */
1668 switch_to_tab(tab);
1670 enter_minibuffer(ir_self_insert, ir_select, exit_minibuffer,
1671 &ir_history);
1672 strlcpy(ministate.prompt, "Input required: ",
1673 sizeof(ministate.prompt));
1674 redraw_tab(tab);
1677 void
1678 ui_end(void)
1680 endwin();