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 * Text scrolling
21 * ==============
22 *
23 * ncurses allows you to scroll a window, but when a line goes out of
24 * the visible area it's forgotten. We keep a list of formatted lines
25 * (``visual lines'') that we know fits in the window, and draw them.
26 * This way is easy to scroll: just call wscrl and then render the
27 * first/last line!
28 *
29 * This means that on every resize we have to clear our list of lines
30 * and re-render everything. A clever approach would be to do this
31 * ``on-demand'', but it's still missing.
32 *
33 */
35 #include "telescope.h"
36 #include "cmd.gen.h"
38 #include <assert.h>
39 #include <curses.h>
40 #include <event.h>
41 #include <limits.h>
42 #include <locale.h>
43 #include <signal.h>
44 #include <stdarg.h>
45 #include <stdlib.h>
46 #include <string.h>
47 #include <unistd.h>
49 static struct event stdioev, winchev;
51 static void load_default_keys(void);
53 static void global_key_unbound(void);
54 static void minibuffer_hist_save_entry(void);
55 static void minibuffer_self_insert(void);
56 static void yornp_self_insert(void);
57 static void yornp_abort(void);
58 static void read_self_insert(void);
59 static void read_abort(void);
60 static void read_select(void);
62 static struct vline *nth_line(struct buffer*, size_t);
63 static struct buffer *current_buffer(void);
64 static int readkey(void);
65 static void dispatch_stdio(int, short, void*);
66 static void handle_clear_minibuf(int, short, void*);
67 static void handle_resize(int, short, void*);
68 static void handle_resize_nodelay(int, short, void*);
69 static int wrap_page(struct buffer*, int);
70 static void print_vline(int, int, WINDOW*, struct vline*);
71 static void redraw_tabline(void);
72 static void redraw_window(WINDOW*, int, int, struct buffer*);
73 static void redraw_help(void);
74 static void redraw_body(struct tab*);
75 static void redraw_modeline(struct tab*);
76 static void redraw_minibuffer(void);
77 static void redraw_tab(struct tab*);
78 static void emit_help_item(char*, void*);
79 static void rec_compute_help(struct kmap*, char*, size_t);
80 static void recompute_help(void);
81 static void update_loading_anim(int, short, void*);
82 static void stop_loading_anim(struct tab*);
83 static void session_new_tab_cb(const char*);
84 static void usage(void);
86 static int x_offset;
88 struct thiskey thiskey;
90 static struct event resizeev;
91 static struct timeval resize_timer = { 0, 250000 };
93 static WINDOW *tabline, *body, *modeline, *minibuf;
95 int body_lines, body_cols;
97 static WINDOW *help;
98 static struct buffer helpwin;
99 static int help_lines, help_cols;
101 static int side_window;
103 static struct event clminibufev;
104 static struct timeval clminibufev_timer = { 5, 0 };
105 static struct timeval loadingev_timer = { 0, 250000 };
107 static uint32_t tab_counter;
109 static char keybuf[64];
111 static void (*yornp_cb)(int, unsigned int);
112 static unsigned int yornp_data;
114 static void (*read_cb)(const char*, unsigned int);
115 static unsigned int read_data;
117 struct kmap global_map,
118 minibuffer_map,
119 *current_map,
120 *base_map;
122 struct histhead eecmd_history,
123 ir_history,
124 lu_history,
125 read_history;
127 int in_minibuffer;
129 struct ministate ministate;
131 static inline void
132 update_x_offset(void)
134 if (olivetti_mode && fill_column < body_cols)
135 x_offset = (body_cols - fill_column)/2;
136 else
137 x_offset = 0;
140 static inline void
141 global_set_key(const char *key, void (*fn)(struct buffer*))
143 if (!kmap_define_key(&global_map, key, fn))
144 _exit(1);
147 static inline void
148 minibuffer_set_key(const char *key, void (*fn)(struct buffer*))
150 if (!kmap_define_key(&minibuffer_map, key, fn))
151 _exit(1);
154 static void
155 load_default_keys(void)
157 /* === global map === */
159 /* emacs */
160 global_set_key("C-p", cmd_previous_line);
161 global_set_key("C-n", cmd_next_line);
162 global_set_key("C-f", cmd_forward_char);
163 global_set_key("C-b", cmd_backward_char);
164 global_set_key("M-{", cmd_backward_paragraph);
165 global_set_key("M-}", cmd_forward_paragraph);
166 global_set_key("C-a", cmd_move_beginning_of_line);
167 global_set_key("C-e", cmd_move_end_of_line);
169 global_set_key("M-v", cmd_scroll_up);
170 global_set_key("C-v", cmd_scroll_down);
171 global_set_key("M-space", cmd_scroll_up);
172 global_set_key("space", cmd_scroll_down);
174 global_set_key("M-<", cmd_beginning_of_buffer);
175 global_set_key("M->", cmd_end_of_buffer);
177 global_set_key("C-x C-c", cmd_kill_telescope);
179 global_set_key("C-g", cmd_clear_minibuf);
181 global_set_key("M-x", cmd_execute_extended_command);
182 global_set_key("C-x C-f", cmd_load_url);
183 global_set_key("C-x M-f", cmd_load_current_url);
185 global_set_key("C-x t 0", cmd_tab_close);
186 global_set_key("C-x t 1", cmd_tab_close_other);
187 global_set_key("C-x t 2", cmd_tab_new);
188 global_set_key("C-x t o", cmd_tab_next);
189 global_set_key("C-x t O", cmd_tab_previous);
190 global_set_key("C-x t m", cmd_tab_move);
191 global_set_key("C-x t M", cmd_tab_move_to);
193 global_set_key("C-M-b", cmd_previous_page);
194 global_set_key("C-M-f", cmd_next_page);
196 global_set_key("<f7> a", cmd_bookmark_page);
197 global_set_key("<f7> <f7>", cmd_list_bookmarks);
199 /* vi/vi-like */
200 global_set_key("k", cmd_previous_line);
201 global_set_key("j", cmd_next_line);
202 global_set_key("l", cmd_forward_char);
203 global_set_key("h", cmd_backward_char);
204 global_set_key("{", cmd_backward_paragraph);
205 global_set_key("}", cmd_forward_paragraph);
206 global_set_key("^", cmd_move_beginning_of_line);
207 global_set_key("$", cmd_move_end_of_line);
209 global_set_key("K", cmd_scroll_line_up);
210 global_set_key("J", cmd_scroll_line_down);
212 global_set_key("g g", cmd_beginning_of_buffer);
213 global_set_key("G", cmd_end_of_buffer);
215 global_set_key("g D", cmd_tab_close);
216 global_set_key("g N", cmd_tab_new);
217 global_set_key("g t", cmd_tab_next);
218 global_set_key("g T", cmd_tab_previous);
219 global_set_key("g M-t", cmd_tab_move);
220 global_set_key("g M-T", cmd_tab_move_to);
222 global_set_key("H", cmd_previous_page);
223 global_set_key("L", cmd_next_page);
225 /* tmp */
226 global_set_key("q", cmd_kill_telescope);
228 global_set_key("esc", cmd_clear_minibuf);
230 global_set_key(":", cmd_execute_extended_command);
232 /* cua */
233 global_set_key("<up>", cmd_previous_line);
234 global_set_key("<down>", cmd_next_line);
235 global_set_key("<right>", cmd_forward_char);
236 global_set_key("<left>", cmd_backward_char);
237 global_set_key("<prior>", cmd_scroll_up);
238 global_set_key("<next>", cmd_scroll_down);
240 global_set_key("M-<left>", cmd_previous_page);
241 global_set_key("M-<right>", cmd_next_page);
243 /* "ncurses standard" */
244 global_set_key("C-l", cmd_redraw);
246 /* global */
247 global_set_key("<f1>", cmd_toggle_help);
248 global_set_key("C-m", cmd_push_button);
249 global_set_key("M-enter", cmd_push_button_new_tab);
250 global_set_key("M-tab", cmd_previous_button);
251 global_set_key("backtab", cmd_previous_button);
252 global_set_key("tab", cmd_next_button);
254 /* === minibuffer map === */
255 minibuffer_set_key("ret", cmd_mini_complete_and_exit);
256 minibuffer_set_key("C-g", cmd_mini_abort);
257 minibuffer_set_key("esc", cmd_mini_abort);
258 minibuffer_set_key("C-d", cmd_mini_delete_char);
259 minibuffer_set_key("del", cmd_mini_delete_backward_char);
260 minibuffer_set_key("backspace", cmd_mini_delete_backward_char);
261 minibuffer_set_key("C-h", cmd_mini_delete_backward_char);
263 minibuffer_set_key("C-b", cmd_backward_char);
264 minibuffer_set_key("C-f", cmd_forward_char);
265 minibuffer_set_key("<left>", cmd_backward_char);
266 minibuffer_set_key("<right>", cmd_forward_char);
267 minibuffer_set_key("C-e", cmd_move_end_of_line);
268 minibuffer_set_key("C-a", cmd_move_beginning_of_line);
269 minibuffer_set_key("<end>", cmd_move_end_of_line);
270 minibuffer_set_key("<home>", cmd_move_beginning_of_line);
271 minibuffer_set_key("C-k", cmd_mini_kill_line);
273 minibuffer_set_key("M-p", cmd_mini_previous_history_element);
274 minibuffer_set_key("M-n", cmd_mini_next_history_element);
275 minibuffer_set_key("<up>", cmd_mini_previous_history_element);
276 minibuffer_set_key("<down>", cmd_mini_next_history_element);
279 void
280 save_excursion(struct excursion *place, struct buffer *buffer)
282 place->curs_x = buffer->curs_x;
283 place->curs_y = buffer->curs_y;
284 place->line_off = buffer->line_off;
285 place->current_line = buffer->current_line;
286 place->cpoff = buffer->cpoff;
289 void
290 restore_excursion(struct excursion *place, struct buffer *buffer)
292 buffer->curs_x = place->curs_x;
293 buffer->curs_y = place->curs_y;
294 buffer->line_off = place->line_off;
295 buffer->current_line = place->current_line;
296 buffer->cpoff = place->cpoff;
299 void
300 restore_cursor(struct buffer *buffer)
302 struct vline *vl;
303 const char *prfx;
305 vl = buffer->current_line;
306 if (vl == NULL || vl->line == NULL)
307 buffer->curs_x = buffer->cpoff = 0;
308 else
309 buffer->curs_x = utf8_snwidth(vl->line, buffer->cpoff);
311 buffer->curs_x += x_offset;
313 if (vl != NULL) {
314 prfx = line_prefixes[vl->parent->type].prfx1;
315 buffer->curs_x += utf8_swidth(prfx);
319 static void
320 global_key_unbound(void)
322 message("%s is undefined", keybuf);
325 static void
326 minibuffer_hist_save_entry(void)
328 struct hist *hist;
330 if (ministate.history == NULL)
331 return;
333 if ((hist = calloc(1, sizeof(*hist))) == NULL)
334 abort();
336 strlcpy(hist->h, ministate.buf, sizeof(hist->h));
338 if (TAILQ_EMPTY(&ministate.history->head))
339 TAILQ_INSERT_HEAD(&ministate.history->head, hist, entries);
340 else
341 TAILQ_INSERT_TAIL(&ministate.history->head, hist, entries);
342 ministate.history->len++;
345 /*
346 * taint the minibuffer cache: if we're currently showing a history
347 * element, copy that to the current buf and reset the "history
348 * navigation" thing.
349 */
350 void
351 minibuffer_taint_hist(void)
353 if (ministate.hist_cur == NULL)
354 return;
356 strlcpy(ministate.buf, ministate.hist_cur->h, sizeof(ministate.buf));
357 ministate.hist_cur = NULL;
360 static void
361 minibuffer_self_insert(void)
363 char *c, tmp[5] = {0};
364 size_t len;
366 minibuffer_taint_hist();
368 if (thiskey.cp == 0)
369 return;
371 len = utf8_encode(thiskey.cp, tmp);
372 c = utf8_nth(ministate.buffer.current_line->line, ministate.buffer.cpoff);
373 if (c + len > ministate.buf + sizeof(ministate.buf) - 1)
374 return;
376 memmove(c + len, c, strlen(c)+1);
377 memcpy(c, tmp, len);
378 ministate.buffer.cpoff++;
381 void
382 eecmd_self_insert(void)
384 if (thiskey.meta || unicode_isspace(thiskey.cp) ||
385 !unicode_isgraph(thiskey.cp)) {
386 global_key_unbound();
387 return;
390 minibuffer_self_insert();
393 void
394 eecmd_select(void)
396 struct cmds *cmd;
398 for (cmd = cmds; cmd->cmd != NULL; ++cmd) {
399 if (!strcmp(cmd->cmd, ministate.buf)) {
400 exit_minibuffer();
401 minibuffer_hist_save_entry();
402 cmd->fn(current_buffer());
403 return;
407 message("No match");
410 void
411 ir_self_insert(void)
413 minibuffer_self_insert();
416 void
417 ir_select(void)
419 char buf[1025] = {0};
420 struct phos_uri uri;
421 struct tab *tab;
423 tab = current_tab();
425 exit_minibuffer();
426 minibuffer_hist_save_entry();
428 /* a bit ugly but... */
429 memcpy(&uri, &tab->uri, sizeof(tab->uri));
430 phos_uri_set_query(&uri, ministate.buf);
431 phos_serialize_uri(&uri, buf, sizeof(buf));
432 load_url_in_tab(tab, buf);
435 void
436 lu_self_insert(void)
438 if (thiskey.meta || unicode_isspace(thiskey.key) ||
439 !unicode_isgraph(thiskey.key)) {
440 global_key_unbound();
441 return;
444 minibuffer_self_insert();
447 void
448 lu_select(void)
450 exit_minibuffer();
451 minibuffer_hist_save_entry();
452 load_url_in_tab(current_tab(), ministate.buf);
455 void
456 bp_select(void)
458 exit_minibuffer();
459 if (*ministate.buf != '\0')
460 add_to_bookmarks(ministate.buf);
461 else
462 message("Abort.");
465 static void
466 yornp_self_insert(void)
468 if (thiskey.key != 'y' && thiskey.key != 'n') {
469 message("Please answer y or n");
470 return;
473 exit_minibuffer();
474 yornp_cb(thiskey.key == 'y', yornp_data);
477 static void
478 yornp_abort(void)
480 exit_minibuffer();
481 yornp_cb(0, yornp_data);
484 static void
485 read_self_insert(void)
487 if (thiskey.meta || !unicode_isgraph(thiskey.cp)) {
488 global_key_unbound();
489 return;
492 minibuffer_self_insert();
495 static void
496 read_abort(void)
498 exit_minibuffer();
499 read_cb(NULL, read_data);
502 static void
503 read_select(void)
505 exit_minibuffer();
506 minibuffer_hist_save_entry();
507 read_cb(ministate.buf, read_data);
510 static struct vline *
511 nth_line(struct buffer *buffer, size_t n)
513 struct vline *vl;
514 size_t i;
516 i = 0;
517 TAILQ_FOREACH(vl, &buffer->head, vlines) {
518 if (i == n)
519 return vl;
520 i++;
523 /* unreachable */
524 abort();
527 struct tab *
528 current_tab(void)
530 struct tab *t;
532 TAILQ_FOREACH(t, &tabshead, tabs) {
533 if (t->flags & TAB_CURRENT)
534 return t;
537 /* unreachable */
538 abort();
541 struct buffer *
542 current_buffer(void)
544 if (in_minibuffer)
545 return &ministate.buffer;
546 return &current_tab()->buffer;
549 static int
550 readkey(void)
552 uint32_t state = 0;
554 if ((thiskey.key = wgetch(body)) == ERR)
555 return 0;
557 thiskey.meta = thiskey.key == 27;
558 if (thiskey.meta) {
559 thiskey.key = wgetch(body);
560 if (thiskey.key == ERR || thiskey.key == 27) {
561 thiskey.meta = 0;
562 thiskey.key = 27;
566 thiskey.cp = 0;
567 if ((unsigned int)thiskey.key < UINT8_MAX) {
568 while (1) {
569 if (!utf8_decode(&state, &thiskey.cp, (uint8_t)thiskey.key))
570 break;
571 if ((thiskey.key = wgetch(body)) == ERR) {
572 message("Error decoding user input");
573 return 0;
578 return 1;
581 static void
582 dispatch_stdio(int fd, short ev, void *d)
584 struct keymap *k;
585 const char *keyname;
586 char tmp[5] = {0};
588 if (!readkey())
589 return;
591 if (keybuf[0] != '\0')
592 strlcat(keybuf, " ", sizeof(keybuf));
593 if (thiskey.meta)
594 strlcat(keybuf, "M-", sizeof(keybuf));
595 if (thiskey.cp != 0) {
596 utf8_encode(thiskey.cp, tmp);
597 strlcat(keybuf, tmp, sizeof(keybuf));
598 } else {
599 if ((keyname = unkbd(thiskey.key)) != NULL)
600 strlcat(keybuf, keyname, sizeof(keybuf));
601 else {
602 tmp[0] = thiskey.key;
603 strlcat(keybuf, tmp, sizeof(keybuf));
607 TAILQ_FOREACH(k, &current_map->m, keymaps) {
608 if (k->meta == thiskey.meta &&
609 k->key == thiskey.key) {
610 if (k->fn == NULL)
611 current_map = &k->map;
612 else {
613 current_map = base_map;
614 strlcpy(keybuf, "", sizeof(keybuf));
615 k->fn(current_buffer());
617 goto done;
621 if (current_map->unhandled_input != NULL)
622 current_map->unhandled_input();
623 else
624 global_key_unbound();
626 strlcpy(keybuf, "", sizeof(keybuf));
627 current_map = base_map;
629 done:
630 if (side_window)
631 recompute_help();
633 redraw_tab(current_tab());
636 static void
637 handle_clear_minibuf(int fd, short ev, void *d)
639 free(ministate.curmesg);
640 ministate.curmesg = NULL;
642 redraw_minibuffer();
643 if (in_minibuffer) {
644 wrefresh(body);
645 wrefresh(minibuf);
646 } else {
647 wrefresh(minibuf);
648 wrefresh(body);
652 static void
653 handle_resize(int sig, short ev, void *d)
655 if (event_pending(&resizeev, EV_TIMEOUT, NULL)) {
656 event_del(&resizeev);
658 evtimer_set(&resizeev, handle_resize_nodelay, NULL);
659 evtimer_add(&resizeev, &resize_timer);
662 static void
663 handle_resize_nodelay(int s, short ev, void *d)
665 struct tab *tab;
667 endwin();
668 refresh();
669 clear();
671 /* move and resize the windows, in reverse order! */
673 mvwin(minibuf, LINES-1, 0);
674 wresize(minibuf, 1, COLS);
676 mvwin(modeline, LINES-2, 0);
677 wresize(modeline, 1, COLS);
679 body_lines = LINES-3;
680 body_cols = COLS;
682 if (side_window) {
683 help_cols = 0.3 * COLS;
684 help_lines = LINES-3;
685 mvwin(help, 1, 0);
686 wresize(help, help_lines, help_cols);
688 wrap_page(&helpwin, help_cols);
690 body_cols = COLS - help_cols - 1;
691 mvwin(body, 1, help_cols);
692 } else
693 mvwin(body, 1, 0);
695 update_x_offset();
696 wresize(body, body_lines, body_cols);
698 wresize(tabline, 1, COLS);
700 tab = current_tab();
702 wrap_page(&tab->buffer, body_cols);
703 redraw_tab(tab);
706 static int
707 wrap_page(struct buffer *buffer, int width)
709 struct line *l;
710 const struct line *orig;
711 struct vline *vl;
712 int pre_width;
713 const char *prfx;
715 orig = buffer->current_line == NULL
716 ? NULL
717 : buffer->current_line->parent;
718 buffer->current_line = NULL;
720 buffer->force_redraw = 1;
721 buffer->curs_y = 0;
722 buffer->line_off = 0;
724 empty_vlist(buffer);
726 TAILQ_FOREACH(l, &buffer->page.head, lines) {
727 prfx = line_prefixes[l->type].prfx1;
728 switch (l->type) {
729 case LINE_TEXT:
730 case LINE_LINK:
731 case LINE_TITLE_1:
732 case LINE_TITLE_2:
733 case LINE_TITLE_3:
734 case LINE_ITEM:
735 case LINE_QUOTE:
736 case LINE_PRE_START:
737 case LINE_PRE_END:
738 wrap_text(buffer, prfx, l, MIN(fill_column, width));
739 break;
740 case LINE_PRE_CONTENT:
741 if (olivetti_mode)
742 pre_width = MIN(fill_column, width);
743 else
744 pre_width = width;
745 hardwrap_text(buffer, l, pre_width);
746 break;
749 if (orig == l && buffer->current_line == NULL) {
750 buffer->line_off = buffer->line_max-1;
751 buffer->current_line = TAILQ_LAST(&buffer->head, vhead);
753 while (1) {
754 vl = TAILQ_PREV(buffer->current_line, vhead, vlines);
755 if (vl == NULL || vl->parent != orig)
756 break;
757 buffer->current_line = vl;
758 buffer->line_off--;
763 if (buffer->current_line == NULL)
764 buffer->current_line = TAILQ_FIRST(&buffer->head);
766 return 1;
769 static void
770 print_vline(int off, int width, WINDOW *window, struct vline *vl)
772 const char *text = vl->line;
773 const char *prfx;
774 int prefix_face = line_faces[vl->parent->type].prefix_prop;
775 int text_face = line_faces[vl->parent->type].text_prop;
776 int trail_face = line_faces[vl->parent->type].trail_prop;
777 int i, left, x, y;
779 /* unused, set by getyx */
780 (void)y;
782 if (!vl->flags)
783 prfx = line_prefixes[vl->parent->type].prfx1;
784 else
785 prfx = line_prefixes[vl->parent->type].prfx2;
787 if (text == NULL)
788 text = "";
790 wattr_on(window, body_face.left, NULL);
791 for (i = 0; i < off; i++)
792 waddch(window, ' ');
793 wattr_off(window, body_face.left, NULL);
795 wattr_on(window, prefix_face, NULL);
796 wprintw(window, "%s", prfx);
797 wattr_off(window, prefix_face, NULL);
799 wattr_on(window, text_face, NULL);
800 wprintw(window, "%s", text);
801 wattr_off(window, text_face, NULL);
803 getyx(window, y, x);
805 left = width - x;
807 wattr_on(window, trail_face, NULL);
808 for (i = 0; i < left - off - 1; ++i)
809 waddch(window, ' ');
810 wattr_off(window, trail_face, NULL);
812 wattr_on(window, body_face.right, NULL);
813 for (i = 0; i < off; i++)
814 waddch(window, ' ');
815 wattr_off(window, body_face.right, NULL);
819 static void
820 redraw_tabline(void)
822 struct tab *tab;
823 size_t toskip, ots, tabwidth, space, x;
824 int current, y, truncated;
825 const char *title;
826 char buf[25];
828 x = 0;
830 /* unused, but setted by a getyx */
831 (void)y;
833 tabwidth = sizeof(buf)+1;
834 space = COLS-2;
836 toskip = 0;
837 TAILQ_FOREACH(tab, &tabshead, tabs) {
838 toskip++;
839 if (tab->flags & TAB_CURRENT)
840 break;
843 if (toskip * tabwidth < space)
844 toskip = 0;
845 else {
846 ots = toskip;
847 toskip--;
848 while (toskip != 0 &&
849 (ots - toskip+1) * tabwidth < space)
850 toskip--;
853 werase(tabline);
854 wattr_on(tabline, tab_face.background, NULL);
855 wprintw(tabline, toskip == 0 ? " " : "<");
856 wattr_off(tabline, tab_face.background, NULL);
858 truncated = 0;
859 TAILQ_FOREACH(tab, &tabshead, tabs) {
860 if (truncated)
861 break;
862 if (toskip != 0) {
863 toskip--;
864 continue;
867 getyx(tabline, y, x);
868 if (x + sizeof(buf)+2 >= (size_t)COLS)
869 truncated = 1;
871 current = tab->flags & TAB_CURRENT;
873 if (*(title = tab->buffer.page.title) == '\0')
874 title = tab->hist_cur->h;
876 if (tab->flags & TAB_URGENT)
877 strlcpy(buf, "!", sizeof(buf));
878 else
879 strlcpy(buf, " ", sizeof(buf));
881 if (strlcat(buf, title, sizeof(buf)) >= sizeof(buf)) {
882 /* truncation happens */
883 strlcpy(&buf[sizeof(buf)-4], "...", 4);
884 } else {
885 /* pad with spaces */
886 while (strlcat(buf, " ", sizeof(buf)) < sizeof(buf))
887 /* nop */ ;
890 if (current)
891 wattr_on(tabline, tab_face.current, NULL);
892 else
893 wattr_on(tabline, tab_face.tab, NULL);
895 wprintw(tabline, "%s", buf);
896 if (TAILQ_NEXT(tab, tabs) != NULL)
897 wprintw(tabline, " ");
899 if (current)
900 wattr_off(tabline, tab_face.current, NULL);
901 else
902 wattr_off(tabline, tab_face.tab, NULL);
905 wattr_on(tabline, tab_face.background, NULL);
906 for (; x < (size_t)COLS; ++x)
907 waddch(tabline, ' ');
908 if (truncated)
909 mvwprintw(tabline, 0, COLS-1, ">");
910 wattr_off(tabline, tab_face.background, NULL);
913 static void
914 redraw_window(WINDOW *win, int height, int width, struct buffer *buffer)
916 struct vline *vl;
917 int l;
919 /*
920 * Don't bother redraw the body if nothing changed. Cursor
921 * movements count as "nothing changed" if it hasn't produced
922 * a scroll. Ensure that wmove is called though!
923 */
924 if (!buffer->force_redraw &&
925 buffer->last_line_off == buffer->line_off)
926 goto end;
928 werase(win);
930 buffer->line_off = MIN(buffer->line_max-1, buffer->line_off);
931 buffer->force_redraw = 0;
932 buffer->last_line_off = buffer->line_off;
934 if (TAILQ_EMPTY(&buffer->head))
935 goto end;
937 l = 0;
938 vl = nth_line(buffer, buffer->line_off);
939 for (; vl != NULL; vl = TAILQ_NEXT(vl, vlines)) {
940 wmove(win, l, 0);
941 print_vline(x_offset, width, win, vl);
942 l++;
943 if (l == height)
944 break;
947 end:
948 wmove(win, buffer->curs_y, buffer->curs_x);
951 static void
952 redraw_help(void)
954 redraw_window(help, help_lines, help_cols, &helpwin);
957 static void
958 redraw_body(struct tab *tab)
960 static struct tab *last_tab;
962 if (last_tab != tab)
963 tab->buffer.force_redraw =1;
964 last_tab = tab;
966 redraw_window(body, body_lines, body_cols, &tab->buffer);
969 static inline char
970 trust_status_char(enum trust_state ts)
972 switch (ts) {
973 case TS_UNKNOWN: return 'u';
974 case TS_UNTRUSTED: return '!';
975 case TS_TRUSTED: return 'v';
976 case TS_VERIFIED: return 'V';
977 default: return 'X';
981 static void
982 redraw_modeline(struct tab *tab)
984 double pct;
985 int x, y, max_x, max_y;
986 const char *mode = tab->buffer.page.name;
987 const char *spin = "-\\|/";
989 werase(modeline);
990 wattr_on(modeline, modeline_face.background, NULL);
991 wmove(modeline, 0, 0);
993 wprintw(modeline, "-%c%c %s ",
994 spin[tab->loading_anim_step],
995 trust_status_char(tab->trust),
996 mode == NULL ? "(none)" : mode);
998 pct = (tab->buffer.line_off + tab->buffer.curs_y) * 100.0 / tab->buffer.line_max;
1000 if (tab->buffer.line_max <= (size_t)body_lines)
1001 wprintw(modeline, "All ");
1002 else if (tab->buffer.line_off == 0)
1003 wprintw(modeline, "Top ");
1004 else if (tab->buffer.line_off + body_lines >= tab->buffer.line_max)
1005 wprintw(modeline, "Bottom ");
1006 else
1007 wprintw(modeline, "%.0f%% ", pct);
1009 wprintw(modeline, "%d/%d %s ",
1010 tab->buffer.line_off + tab->buffer.curs_y,
1011 tab->buffer.line_max,
1012 tab->hist_cur->h);
1014 getyx(modeline, y, x);
1015 getmaxyx(modeline, max_y, max_x);
1017 (void)y;
1018 (void)max_y;
1020 for (; x < max_x; ++x)
1021 waddstr(modeline, "-");
1023 wattr_off(modeline, modeline_face.background, NULL);
1026 static void
1027 redraw_minibuffer(void)
1029 struct tab *tab;
1030 size_t off_y, off_x = 0;
1031 char *start = NULL, *c = NULL;
1033 /* unused, but set by getyx */
1034 (void)off_y;
1036 wattr_on(minibuf, minibuffer_face.background, NULL);
1037 werase(minibuf);
1039 if (in_minibuffer) {
1040 mvwprintw(minibuf, 0, 0, "%s", ministate.prompt);
1041 if (ministate.hist_cur != NULL)
1042 wprintw(minibuf, "(%zu/%zu) ",
1043 ministate.hist_off + 1,
1044 ministate.history->len);
1046 getyx(minibuf, off_y, off_x);
1048 start = ministate.hist_cur != NULL
1049 ? ministate.hist_cur->h
1050 : ministate.buf;
1051 c = utf8_nth(ministate.buffer.current_line->line,
1052 ministate.buffer.cpoff);
1053 while (utf8_swidth_between(start, c) > (size_t)COLS/2) {
1054 start = utf8_next_cp(start);
1057 waddstr(minibuf, start);
1060 if (ministate.curmesg != NULL)
1061 wprintw(minibuf, in_minibuffer ? " [%s]" : "%s",
1062 ministate.curmesg);
1064 if (!in_minibuffer && ministate.curmesg == NULL)
1065 waddstr(minibuf, keybuf);
1067 /* If nothing else, show the URL at point */
1068 if (!in_minibuffer && ministate.curmesg == NULL && *keybuf == '\0') {
1069 tab = current_tab();
1070 if (tab->buffer.current_line != NULL &&
1071 tab->buffer.current_line->parent->type == LINE_LINK)
1072 waddstr(minibuf, tab->buffer.current_line->parent->alt);
1075 if (in_minibuffer)
1076 wmove(minibuf, 0, off_x + utf8_swidth_between(start, c));
1078 wattr_off(minibuf, minibuffer_face.background, NULL);
1081 static void
1082 redraw_tab(struct tab *tab)
1084 if (side_window) {
1085 redraw_help();
1086 wnoutrefresh(help);
1089 restore_cursor(&tab->buffer);
1091 redraw_tabline();
1092 redraw_body(tab);
1093 redraw_modeline(tab);
1094 redraw_minibuffer();
1096 wnoutrefresh(tabline);
1097 wnoutrefresh(modeline);
1099 if (in_minibuffer) {
1100 wnoutrefresh(body);
1101 wnoutrefresh(minibuf);
1102 } else {
1103 wnoutrefresh(minibuf);
1104 wnoutrefresh(body);
1107 doupdate();
1110 static void
1111 emit_help_item(char *prfx, void *fn)
1113 struct line *l;
1114 struct cmds *cmd;
1116 for (cmd = cmds; cmd->cmd != NULL; ++cmd) {
1117 if (fn == cmd->fn)
1118 break;
1120 assert(cmd != NULL);
1122 if ((l = calloc(1, sizeof(*l))) == NULL)
1123 abort();
1125 l->type = LINE_TEXT;
1126 l->alt = NULL;
1128 asprintf(&l->line, "%s %s", prfx, cmd->cmd);
1130 if (TAILQ_EMPTY(&helpwin.page.head))
1131 TAILQ_INSERT_HEAD(&helpwin.page.head, l, lines);
1132 else
1133 TAILQ_INSERT_TAIL(&helpwin.page.head, l, lines);
1136 static void
1137 rec_compute_help(struct kmap *keymap, char *prfx, size_t len)
1139 struct keymap *k;
1140 char p[32];
1141 const char *kn;
1143 TAILQ_FOREACH(k, &keymap->m, keymaps) {
1144 strlcpy(p, prfx, sizeof(p));
1145 if (*p != '\0')
1146 strlcat(p, " ", sizeof(p));
1147 if (k->meta)
1148 strlcat(p, "M-", sizeof(p));
1149 if ((kn = unkbd(k->key)) != NULL)
1150 strlcat(p, kn, sizeof(p));
1151 else
1152 strlcat(p, keyname(k->key), sizeof(p));
1154 if (k->fn == NULL)
1155 rec_compute_help(&k->map, p, sizeof(p));
1156 else
1157 emit_help_item(p, k->fn);
1161 static void
1162 recompute_help(void)
1164 char p[32] = { 0 };
1166 empty_vlist(&helpwin);
1167 empty_linelist(&helpwin);
1168 rec_compute_help(current_map, p, sizeof(p));
1169 wrap_page(&helpwin, help_cols);
1172 void
1173 vmessage(const char *fmt, va_list ap)
1175 if (evtimer_pending(&clminibufev, NULL))
1176 evtimer_del(&clminibufev);
1178 free(ministate.curmesg);
1179 ministate.curmesg = NULL;
1181 if (fmt != NULL) {
1182 evtimer_set(&clminibufev, handle_clear_minibuf, NULL);
1183 evtimer_add(&clminibufev, &clminibufev_timer);
1185 /* TODO: what to do if the allocation fails here? */
1186 if (vasprintf(&ministate.curmesg, fmt, ap) == -1)
1187 ministate.curmesg = NULL;
1190 redraw_minibuffer();
1191 if (in_minibuffer) {
1192 wrefresh(body);
1193 wrefresh(minibuf);
1194 } else {
1195 wrefresh(minibuf);
1196 wrefresh(body);
1200 void
1201 message(const char *fmt, ...)
1203 va_list ap;
1205 va_start(ap, fmt);
1206 vmessage(fmt, ap);
1207 va_end(ap);
1210 void
1211 start_loading_anim(struct tab *tab)
1213 if (tab->loading_anim)
1214 return;
1215 tab->loading_anim = 1;
1216 evtimer_set(&tab->loadingev, update_loading_anim, tab);
1217 evtimer_add(&tab->loadingev, &loadingev_timer);
1220 static void
1221 update_loading_anim(int fd, short ev, void *d)
1223 struct tab *tab = d;
1225 tab->loading_anim_step = (tab->loading_anim_step+1)%4;
1227 if (tab->flags & TAB_CURRENT) {
1228 redraw_modeline(tab);
1229 wrefresh(modeline);
1230 wrefresh(body);
1231 if (in_minibuffer)
1232 wrefresh(minibuf);
1235 evtimer_add(&tab->loadingev, &loadingev_timer);
1238 static void
1239 stop_loading_anim(struct tab *tab)
1241 if (!tab->loading_anim)
1242 return;
1243 evtimer_del(&tab->loadingev);
1244 tab->loading_anim = 0;
1245 tab->loading_anim_step = 0;
1247 if (!(tab->flags & TAB_CURRENT))
1248 return;
1250 redraw_modeline(tab);
1252 wrefresh(modeline);
1253 wrefresh(body);
1254 if (in_minibuffer)
1255 wrefresh(minibuf);
1258 void
1259 load_url_in_tab(struct tab *tab, const char *url)
1261 message("Loading %s...", url);
1262 start_loading_anim(tab);
1263 load_url(tab, url);
1265 tab->buffer.curs_x = 0;
1266 tab->buffer.curs_y = 0;
1267 redraw_tab(tab);
1270 void
1271 enter_minibuffer(void (*self_insert_fn)(void), void (*donefn)(void),
1272 void (*abortfn)(void), struct histhead *hist)
1274 in_minibuffer = 1;
1275 base_map = &minibuffer_map;
1276 current_map = &minibuffer_map;
1278 base_map->unhandled_input = self_insert_fn;
1280 ministate.donefn = donefn;
1281 ministate.abortfn = abortfn;
1282 memset(ministate.buf, 0, sizeof(ministate.buf));
1283 ministate.buffer.current_line = &ministate.vline;
1284 ministate.buffer.current_line->line = ministate.buf;
1285 ministate.buffer.cpoff = 0;
1286 strlcpy(ministate.buf, "", sizeof(ministate.prompt));
1288 ministate.history = hist;
1289 ministate.hist_cur = NULL;
1290 ministate.hist_off = 0;
1293 void
1294 exit_minibuffer(void)
1296 werase(minibuf);
1298 in_minibuffer = 0;
1299 base_map = &global_map;
1300 current_map = &global_map;
1303 void
1304 switch_to_tab(struct tab *tab)
1306 struct tab *t;
1308 TAILQ_FOREACH(t, &tabshead, tabs) {
1309 t->flags &= ~TAB_CURRENT;
1312 tab->flags |= TAB_CURRENT;
1313 tab->flags &= ~TAB_URGENT;
1316 unsigned int
1317 tab_new_id(void)
1319 return tab_counter++;
1322 struct tab *
1323 new_tab(const char *url)
1325 struct tab *tab;
1327 if ((tab = calloc(1, sizeof(*tab))) == NULL) {
1328 event_loopbreak();
1329 return NULL;
1331 tab->fd = -1;
1333 TAILQ_INIT(&tab->hist.head);
1335 TAILQ_INIT(&tab->buffer.head);
1337 tab->id = tab_new_id();
1338 switch_to_tab(tab);
1340 if (TAILQ_EMPTY(&tabshead))
1341 TAILQ_INSERT_HEAD(&tabshead, tab, tabs);
1342 else
1343 TAILQ_INSERT_TAIL(&tabshead, tab, tabs);
1345 load_url_in_tab(tab, url);
1346 return tab;
1349 static void
1350 session_new_tab_cb(const char *url)
1352 new_tab(url);
1355 static void
1356 usage(void)
1358 fprintf(stderr, "USAGE: %s [-hn] [-c config] [url]\n", getprogname());
1359 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
1362 int
1363 ui_init(int argc, char * const *argv)
1365 char path[PATH_MAX];
1366 const char *url = NEW_TAB_URL;
1367 int ch, configtest = 0, fonf = 0;
1369 if (getenv("NO_COLOR") != NULL)
1370 enable_colors = 0;
1372 strlcpy(path, getenv("HOME"), sizeof(path));
1373 strlcat(path, "/.telescope/config", sizeof(path));
1375 while ((ch = getopt(argc, argv, "c:hn")) != -1) {
1376 switch (ch) {
1377 case 'c':
1378 fonf = 1;
1379 strlcpy(path, optarg, sizeof(path));
1380 break;
1381 case 'n':
1382 configtest = 1;
1383 break;
1384 case 'h':
1385 usage();
1386 return 0;
1387 default:
1388 usage();
1389 return 1;
1392 argc -= optind;
1393 argv += optind;
1395 config_init();
1396 parseconfig(path, fonf);
1397 if (configtest){
1398 puts("config OK");
1399 exit(0);
1402 if (argc != 0)
1403 url = argv[0];
1405 setlocale(LC_ALL, "");
1407 TAILQ_INIT(&global_map.m);
1408 global_map.unhandled_input = global_key_unbound;
1410 TAILQ_INIT(&minibuffer_map.m);
1412 TAILQ_INIT(&eecmd_history.head);
1413 TAILQ_INIT(&ir_history.head);
1414 TAILQ_INIT(&lu_history.head);
1416 ministate.line.type = LINE_TEXT;
1417 ministate.vline.parent = &ministate.line;
1418 ministate.buffer.current_line = &ministate.vline;
1420 /* initialize help window */
1421 TAILQ_INIT(&helpwin.head);
1423 base_map = &global_map;
1424 current_map = &global_map;
1425 load_default_keys();
1427 initscr();
1429 if (enable_colors) {
1430 if (has_colors()) {
1431 start_color();
1432 use_default_colors();
1433 } else
1434 enable_colors = 0;
1437 config_apply_style();
1439 raw();
1440 noecho();
1441 nonl();
1442 intrflush(stdscr, FALSE);
1444 if ((tabline = newwin(1, COLS, 0, 0)) == NULL)
1445 return 0;
1446 if ((body = newwin(LINES - 3, COLS, 1, 0)) == NULL)
1447 return 0;
1448 if ((modeline = newwin(1, COLS, LINES-2, 0)) == NULL)
1449 return 0;
1450 if ((minibuf = newwin(1, COLS, LINES-1, 0)) == NULL)
1451 return 0;
1452 if ((help = newwin(1, 1, 1, 0)) == NULL)
1453 return 0;
1455 body_lines = LINES-3;
1456 body_cols = COLS;
1458 wbkgd(body, body_face.body);
1460 update_x_offset();
1462 keypad(body, TRUE);
1463 scrollok(body, FALSE);
1465 /* non-blocking input */
1466 wtimeout(body, 0);
1468 mvwprintw(body, 0, 0, "");
1470 event_set(&stdioev, 0, EV_READ | EV_PERSIST, dispatch_stdio, NULL);
1471 event_add(&stdioev, NULL);
1473 signal_set(&winchev, SIGWINCH, handle_resize, NULL);
1474 signal_add(&winchev, NULL);
1476 load_last_session(session_new_tab_cb);
1477 if (strcmp(url, NEW_TAB_URL) || TAILQ_EMPTY(&tabshead))
1478 new_tab(url);
1480 return 1;
1483 void
1484 ui_on_tab_loaded(struct tab *tab)
1486 stop_loading_anim(tab);
1487 message("Loaded %s", tab->hist_cur->h);
1489 redraw_tabline();
1490 wrefresh(tabline);
1491 if (in_minibuffer)
1492 wrefresh(minibuf);
1493 else
1494 wrefresh(body);
1497 void
1498 ui_on_tab_refresh(struct tab *tab)
1500 wrap_page(&tab->buffer, body_cols);
1501 if (tab->flags & TAB_CURRENT) {
1502 restore_cursor(&tab->buffer);
1503 redraw_tab(tab);
1504 } else
1505 tab->flags |= TAB_URGENT;
1508 const char *
1509 ui_keyname(int k)
1511 return keyname(k);
1514 void
1515 ui_toggle_side_window(void)
1517 side_window = !side_window;
1518 if (side_window)
1519 recompute_help();
1522 * ugly hack, but otherwise the window doesn't get updated
1523 * until I call handle_resize a second time (i.e. C-l). I
1524 * will be happy to know why something like this is needed.
1526 handle_resize_nodelay(0, 0, NULL);
1527 handle_resize_nodelay(0, 0, NULL);
1530 void
1531 ui_schedule_redraw(void)
1533 handle_resize_nodelay(0, 0, NULL);
1536 void
1537 ui_require_input(struct tab *tab, int hide)
1539 /* TODO: hard-switching to another tab is ugly */
1540 switch_to_tab(tab);
1542 enter_minibuffer(ir_self_insert, ir_select, exit_minibuffer,
1543 &ir_history);
1544 strlcpy(ministate.prompt, "Input required: ",
1545 sizeof(ministate.prompt));
1546 redraw_tab(tab);
1549 void
1550 ui_yornp(const char *prompt, void (*fn)(int, unsigned int),
1551 unsigned int data)
1553 size_t len;
1555 if (in_minibuffer) {
1556 fn(0, data);
1557 return;
1560 yornp_cb = fn;
1561 yornp_data = data;
1562 enter_minibuffer(yornp_self_insert, yornp_self_insert,
1563 yornp_abort, NULL);
1565 len = sizeof(ministate.prompt);
1566 strlcpy(ministate.prompt, prompt, len);
1567 strlcat(ministate.prompt, " (y or n) ", len);
1568 redraw_tab(current_tab());
1571 void
1572 ui_read(const char *prompt, void (*fn)(const char*, unsigned int),
1573 unsigned int data)
1575 size_t len;
1577 if (in_minibuffer)
1578 return;
1580 read_cb = fn;
1581 read_data = data;
1582 enter_minibuffer(read_self_insert, read_select, read_abort,
1583 &read_history);
1585 len = sizeof(ministate.prompt);
1586 strlcpy(ministate.prompt, prompt, len);
1587 strlcat(ministate.prompt, ": ", len);
1588 redraw_tab(current_tab());
1591 void
1592 ui_end(void)
1594 endwin();