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 *
27 * This means that on every resize we have to clear our list of lines
28 * and re-render everything. A clever approach would be to do this
29 * ``on-demand'', but it's still missing.
30 *
31 */
33 #include "telescope.h"
35 #include <assert.h>
36 #include <curses.h>
37 #include <event.h>
38 #include <limits.h>
39 #include <locale.h>
40 #include <signal.h>
41 #include <stdarg.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <unistd.h>
46 static struct event stdioev, winchev;
48 static void load_default_keys(void);
50 static void global_key_unbound(void);
51 static void minibuffer_hist_save_entry(void);
52 static void minibuffer_self_insert(void);
53 static void yornp_self_insert(void);
54 static void yornp_abort(void);
55 static void read_self_insert(void);
56 static void read_abort(void);
57 static void read_select(void);
59 static struct vline *nth_line(struct buffer*, size_t);
60 static struct buffer *current_buffer(void);
61 static int readkey(void);
62 static void dispatch_stdio(int, short, void*);
63 static void handle_clear_minibuf(int, short, void*);
64 static void handle_resize(int, short, void*);
65 static void handle_resize_nodelay(int, short, void*);
66 static int wrap_page(struct buffer*, int);
67 static void print_vline(int, int, WINDOW*, struct vline*);
68 static void redraw_tabline(void);
69 static void redraw_window(WINDOW*, int, int, struct buffer*);
70 static void redraw_help(void);
71 static void redraw_body(struct tab*);
72 static void redraw_modeline(struct tab*);
73 static void redraw_minibuffer(void);
74 static void redraw_tab(struct tab*);
75 static void emit_help_item(char*, void*);
76 static void rec_compute_help(struct kmap*, char*, size_t);
77 static void recompute_help(void);
78 static void update_loading_anim(int, short, void*);
79 static void stop_loading_anim(struct tab*);
80 static void session_new_tab_cb(const char*);
81 static void usage(void);
83 static int x_offset;
85 struct thiskey thiskey;
87 static struct event resizeev;
88 static struct timeval resize_timer = { 0, 250000 };
90 static WINDOW *tabline, *body, *modeline, *minibuf;
92 int body_lines, body_cols;
94 static WINDOW *help;
95 static struct buffer helpwin;
96 static int help_lines, help_cols;
98 static int side_window;
100 static struct event clminibufev;
101 static struct timeval clminibufev_timer = { 5, 0 };
102 static struct timeval loadingev_timer = { 0, 250000 };
104 static uint32_t tab_counter;
106 static char keybuf[64];
108 static void (*yornp_cb)(int, unsigned int);
109 static unsigned int yornp_data;
111 static void (*read_cb)(const char*, unsigned int);
112 static unsigned int read_data;
114 struct kmap global_map,
115 minibuffer_map,
116 *current_map,
117 *base_map;
119 struct histhead eecmd_history,
120 ir_history,
121 lu_history,
122 read_history;
124 int in_minibuffer;
126 struct ministate ministate;
128 static inline void
129 update_x_offset(void)
131 if (olivetti_mode && fill_column < body_cols)
132 x_offset = (body_cols - fill_column)/2;
133 else
134 x_offset = 0;
137 static inline void
138 global_set_key(const char *key, void (*fn)(struct buffer*))
140 if (!kmap_define_key(&global_map, key, fn))
141 _exit(1);
144 static inline void
145 minibuffer_set_key(const char *key, void (*fn)(struct buffer*))
147 if (!kmap_define_key(&minibuffer_map, key, fn))
148 _exit(1);
151 static void
152 load_default_keys(void)
154 /* === global map === */
156 /* emacs */
157 global_set_key("C-p", cmd_previous_line);
158 global_set_key("C-n", cmd_next_line);
159 global_set_key("C-f", cmd_forward_char);
160 global_set_key("C-b", cmd_backward_char);
161 global_set_key("M-{", cmd_backward_paragraph);
162 global_set_key("M-}", cmd_forward_paragraph);
163 global_set_key("C-a", cmd_move_beginning_of_line);
164 global_set_key("C-e", cmd_move_end_of_line);
166 global_set_key("M-v", cmd_scroll_up);
167 global_set_key("C-v", cmd_scroll_down);
168 global_set_key("M-space", cmd_scroll_up);
169 global_set_key("space", cmd_scroll_down);
171 global_set_key("M-<", cmd_beginning_of_buffer);
172 global_set_key("M->", cmd_end_of_buffer);
174 global_set_key("C-x C-c", cmd_kill_telescope);
176 global_set_key("C-g", cmd_clear_minibuf);
178 global_set_key("M-x", cmd_execute_extended_command);
180 global_set_key("C-c {", cmd_dec_fill_column);
181 global_set_key("C-c }", cmd_inc_fill_column);
183 global_set_key("C-c p", cmd_previous_heading);
184 global_set_key("C-c n", cmd_next_heading);
186 global_set_key(">", cmd_load_url);
187 global_set_key("C-x C-f", cmd_load_url);
188 global_set_key("C-x M-f", cmd_load_current_url);
190 global_set_key("C-x t 0", cmd_tab_close);
191 global_set_key("C-x t 1", cmd_tab_close_other);
192 global_set_key("C-x t 2", cmd_tab_new);
193 global_set_key("C-x t o", cmd_tab_next);
194 global_set_key("C-x t O", cmd_tab_previous);
195 global_set_key("C-x t m", cmd_tab_move);
196 global_set_key("C-x t M", cmd_tab_move_to);
198 global_set_key("C-M-b", cmd_previous_page);
199 global_set_key("C-M-f", cmd_next_page);
201 global_set_key("<f7> a", cmd_bookmark_page);
202 global_set_key("<f7> <f7>", cmd_list_bookmarks);
204 /* vi/vi-like */
205 global_set_key("k", cmd_previous_line);
206 global_set_key("j", cmd_next_line);
207 global_set_key("l", cmd_forward_char);
208 global_set_key("h", cmd_backward_char);
209 global_set_key("{", cmd_backward_paragraph);
210 global_set_key("}", cmd_forward_paragraph);
211 global_set_key("^", cmd_move_beginning_of_line);
212 global_set_key("$", cmd_move_end_of_line);
214 global_set_key("K", cmd_scroll_line_up);
215 global_set_key("J", cmd_scroll_line_down);
217 global_set_key("g g", cmd_beginning_of_buffer);
218 global_set_key("G", cmd_end_of_buffer);
220 global_set_key("g D", cmd_tab_close);
221 global_set_key("g N", cmd_tab_new);
222 global_set_key("g t", cmd_tab_next);
223 global_set_key("g T", cmd_tab_previous);
224 global_set_key("g M-t", cmd_tab_move);
225 global_set_key("g M-T", cmd_tab_move_to);
227 global_set_key("H", cmd_previous_page);
228 global_set_key("L", cmd_next_page);
230 /* tmp */
231 global_set_key("q", cmd_kill_telescope);
233 global_set_key("esc", cmd_clear_minibuf);
235 global_set_key(":", cmd_execute_extended_command);
237 /* cua */
238 global_set_key("<up>", cmd_previous_line);
239 global_set_key("<down>", cmd_next_line);
240 global_set_key("<right>", cmd_forward_char);
241 global_set_key("<left>", cmd_backward_char);
242 global_set_key("<prior>", cmd_scroll_up);
243 global_set_key("<next>", cmd_scroll_down);
245 global_set_key("M-<left>", cmd_previous_page);
246 global_set_key("M-<right>", cmd_next_page);
248 /* "ncurses standard" */
249 global_set_key("C-l", cmd_redraw);
251 /* global */
252 global_set_key("<f1>", cmd_toggle_help);
253 global_set_key("C-m", cmd_push_button);
254 global_set_key("M-enter", cmd_push_button_new_tab);
255 global_set_key("M-tab", cmd_previous_button);
256 global_set_key("backtab", cmd_previous_button);
257 global_set_key("tab", cmd_next_button);
259 /* === minibuffer map === */
260 minibuffer_set_key("ret", cmd_mini_complete_and_exit);
261 minibuffer_set_key("C-g", cmd_mini_abort);
262 minibuffer_set_key("esc", cmd_mini_abort);
263 minibuffer_set_key("C-d", cmd_mini_delete_char);
264 minibuffer_set_key("del", cmd_mini_delete_backward_char);
265 minibuffer_set_key("backspace", cmd_mini_delete_backward_char);
266 minibuffer_set_key("C-h", cmd_mini_delete_backward_char);
268 minibuffer_set_key("C-b", cmd_backward_char);
269 minibuffer_set_key("C-f", cmd_forward_char);
270 minibuffer_set_key("<left>", cmd_backward_char);
271 minibuffer_set_key("<right>", cmd_forward_char);
272 minibuffer_set_key("C-e", cmd_move_end_of_line);
273 minibuffer_set_key("C-a", cmd_move_beginning_of_line);
274 minibuffer_set_key("<end>", cmd_move_end_of_line);
275 minibuffer_set_key("<home>", cmd_move_beginning_of_line);
276 minibuffer_set_key("C-k", cmd_mini_kill_line);
278 minibuffer_set_key("M-p", cmd_mini_previous_history_element);
279 minibuffer_set_key("M-n", cmd_mini_next_history_element);
280 minibuffer_set_key("<up>", cmd_mini_previous_history_element);
281 minibuffer_set_key("<down>", cmd_mini_next_history_element);
284 void
285 save_excursion(struct excursion *place, struct buffer *buffer)
287 place->curs_x = buffer->curs_x;
288 place->curs_y = buffer->curs_y;
289 place->line_off = buffer->line_off;
290 place->current_line = buffer->current_line;
291 place->cpoff = buffer->cpoff;
294 void
295 restore_excursion(struct excursion *place, struct buffer *buffer)
297 buffer->curs_x = place->curs_x;
298 buffer->curs_y = place->curs_y;
299 buffer->line_off = place->line_off;
300 buffer->current_line = place->current_line;
301 buffer->cpoff = place->cpoff;
304 void
305 restore_cursor(struct buffer *buffer)
307 struct vline *vl;
308 const char *prfx;
310 vl = buffer->current_line;
311 if (vl == NULL || vl->line == NULL)
312 buffer->curs_x = buffer->cpoff = 0;
313 else
314 buffer->curs_x = utf8_snwidth(vl->line, buffer->cpoff);
316 buffer->curs_x += x_offset;
318 if (vl != NULL) {
319 prfx = line_prefixes[vl->parent->type].prfx1;
320 buffer->curs_x += utf8_swidth(prfx);
324 static void
325 global_key_unbound(void)
327 message("%s is undefined", keybuf);
330 static void
331 minibuffer_hist_save_entry(void)
333 struct hist *hist;
335 if (ministate.history == NULL)
336 return;
338 if ((hist = calloc(1, sizeof(*hist))) == NULL)
339 abort();
341 strlcpy(hist->h, ministate.buf, sizeof(hist->h));
343 if (TAILQ_EMPTY(&ministate.history->head))
344 TAILQ_INSERT_HEAD(&ministate.history->head, hist, entries);
345 else
346 TAILQ_INSERT_TAIL(&ministate.history->head, hist, entries);
347 ministate.history->len++;
350 /*
351 * taint the minibuffer cache: if we're currently showing a history
352 * element, copy that to the current buf and reset the "history
353 * navigation" thing.
354 */
355 void
356 minibuffer_taint_hist(void)
358 if (ministate.hist_cur == NULL)
359 return;
361 strlcpy(ministate.buf, ministate.hist_cur->h, sizeof(ministate.buf));
362 ministate.hist_cur = NULL;
365 static void
366 minibuffer_self_insert(void)
368 char *c, tmp[5] = {0};
369 size_t len;
371 minibuffer_taint_hist();
373 if (thiskey.cp == 0)
374 return;
376 len = utf8_encode(thiskey.cp, tmp);
377 c = utf8_nth(ministate.buffer.current_line->line, ministate.buffer.cpoff);
378 if (c + len > ministate.buf + sizeof(ministate.buf) - 1)
379 return;
381 memmove(c + len, c, strlen(c)+1);
382 memcpy(c, tmp, len);
383 ministate.buffer.cpoff++;
386 void
387 eecmd_self_insert(void)
389 if (thiskey.meta || unicode_isspace(thiskey.cp) ||
390 !unicode_isgraph(thiskey.cp)) {
391 global_key_unbound();
392 return;
395 minibuffer_self_insert();
398 void
399 eecmd_select(void)
401 struct cmd *cmd;
403 for (cmd = cmds; cmd->cmd != NULL; ++cmd) {
404 if (!strcmp(cmd->cmd, ministate.buf)) {
405 exit_minibuffer();
406 minibuffer_hist_save_entry();
407 cmd->fn(current_buffer());
408 return;
412 message("No match");
415 void
416 ir_self_insert(void)
418 minibuffer_self_insert();
421 void
422 ir_select(void)
424 char buf[1025] = {0};
425 struct phos_uri uri;
426 struct tab *tab;
428 tab = current_tab();
430 exit_minibuffer();
431 minibuffer_hist_save_entry();
433 /* a bit ugly but... */
434 memcpy(&uri, &tab->uri, sizeof(tab->uri));
435 phos_uri_set_query(&uri, ministate.buf);
436 phos_serialize_uri(&uri, buf, sizeof(buf));
437 load_url_in_tab(tab, buf);
440 void
441 lu_self_insert(void)
443 if (thiskey.meta || unicode_isspace(thiskey.key) ||
444 !unicode_isgraph(thiskey.key)) {
445 global_key_unbound();
446 return;
449 minibuffer_self_insert();
452 void
453 lu_select(void)
455 exit_minibuffer();
456 minibuffer_hist_save_entry();
457 load_url_in_tab(current_tab(), ministate.buf);
460 void
461 bp_select(void)
463 exit_minibuffer();
464 if (*ministate.buf != '\0')
465 add_to_bookmarks(ministate.buf);
466 else
467 message("Abort.");
470 static void
471 yornp_self_insert(void)
473 if (thiskey.key != 'y' && thiskey.key != 'n') {
474 message("Please answer y or n");
475 return;
478 exit_minibuffer();
479 yornp_cb(thiskey.key == 'y', yornp_data);
482 static void
483 yornp_abort(void)
485 exit_minibuffer();
486 yornp_cb(0, yornp_data);
489 static void
490 read_self_insert(void)
492 if (thiskey.meta || !unicode_isgraph(thiskey.cp)) {
493 global_key_unbound();
494 return;
497 minibuffer_self_insert();
500 static void
501 read_abort(void)
503 exit_minibuffer();
504 read_cb(NULL, read_data);
507 static void
508 read_select(void)
510 exit_minibuffer();
511 minibuffer_hist_save_entry();
512 read_cb(ministate.buf, read_data);
515 static struct vline *
516 nth_line(struct buffer *buffer, size_t n)
518 struct vline *vl;
519 size_t i;
521 i = 0;
522 TAILQ_FOREACH(vl, &buffer->head, vlines) {
523 if (i == n)
524 return vl;
525 i++;
528 /* unreachable */
529 abort();
532 struct tab *
533 current_tab(void)
535 struct tab *t;
537 TAILQ_FOREACH(t, &tabshead, tabs) {
538 if (t->flags & TAB_CURRENT)
539 return t;
542 /* unreachable */
543 abort();
546 struct buffer *
547 current_buffer(void)
549 if (in_minibuffer)
550 return &ministate.buffer;
551 return &current_tab()->buffer;
554 static int
555 readkey(void)
557 uint32_t state = 0;
559 if ((thiskey.key = wgetch(body)) == ERR)
560 return 0;
562 thiskey.meta = thiskey.key == 27;
563 if (thiskey.meta) {
564 thiskey.key = wgetch(body);
565 if (thiskey.key == ERR || thiskey.key == 27) {
566 thiskey.meta = 0;
567 thiskey.key = 27;
571 thiskey.cp = 0;
572 if ((unsigned int)thiskey.key < UINT8_MAX) {
573 while (1) {
574 if (!utf8_decode(&state, &thiskey.cp, (uint8_t)thiskey.key))
575 break;
576 if ((thiskey.key = wgetch(body)) == ERR) {
577 message("Error decoding user input");
578 return 0;
583 return 1;
586 static void
587 dispatch_stdio(int fd, short ev, void *d)
589 struct keymap *k;
590 const char *keyname;
591 char tmp[5] = {0};
593 if (!readkey())
594 return;
596 if (keybuf[0] != '\0')
597 strlcat(keybuf, " ", sizeof(keybuf));
598 if (thiskey.meta)
599 strlcat(keybuf, "M-", sizeof(keybuf));
600 if (thiskey.cp != 0) {
601 utf8_encode(thiskey.cp, tmp);
602 strlcat(keybuf, tmp, sizeof(keybuf));
603 } else {
604 if ((keyname = unkbd(thiskey.key)) != NULL)
605 strlcat(keybuf, keyname, sizeof(keybuf));
606 else {
607 tmp[0] = thiskey.key;
608 strlcat(keybuf, tmp, sizeof(keybuf));
612 TAILQ_FOREACH(k, &current_map->m, keymaps) {
613 if (k->meta == thiskey.meta &&
614 k->key == thiskey.key) {
615 if (k->fn == NULL)
616 current_map = &k->map;
617 else {
618 current_map = base_map;
619 strlcpy(keybuf, "", sizeof(keybuf));
620 k->fn(current_buffer());
622 goto done;
626 if (current_map->unhandled_input != NULL)
627 current_map->unhandled_input();
628 else
629 global_key_unbound();
631 strlcpy(keybuf, "", sizeof(keybuf));
632 current_map = base_map;
634 done:
635 if (side_window)
636 recompute_help();
638 redraw_tab(current_tab());
641 static void
642 handle_clear_minibuf(int fd, short ev, void *d)
644 free(ministate.curmesg);
645 ministate.curmesg = NULL;
647 redraw_minibuffer();
648 if (in_minibuffer) {
649 wrefresh(body);
650 wrefresh(minibuf);
651 } else {
652 wrefresh(minibuf);
653 wrefresh(body);
657 static void
658 handle_resize(int sig, short ev, void *d)
660 if (event_pending(&resizeev, EV_TIMEOUT, NULL)) {
661 event_del(&resizeev);
663 evtimer_set(&resizeev, handle_resize_nodelay, NULL);
664 evtimer_add(&resizeev, &resize_timer);
667 static void
668 handle_resize_nodelay(int s, short ev, void *d)
670 struct tab *tab;
672 endwin();
673 refresh();
674 clear();
676 /* move and resize the windows, in reverse order! */
678 mvwin(minibuf, LINES-1, 0);
679 wresize(minibuf, 1, COLS);
681 mvwin(modeline, LINES-2, 0);
682 wresize(modeline, 1, COLS);
684 body_lines = LINES-3;
685 body_cols = COLS;
687 if (side_window) {
688 help_cols = 0.3 * COLS;
689 help_lines = LINES-3;
690 mvwin(help, 1, 0);
691 wresize(help, help_lines, help_cols);
693 wrap_page(&helpwin, help_cols);
695 body_cols = COLS - help_cols - 1;
696 mvwin(body, 1, help_cols);
697 } else
698 mvwin(body, 1, 0);
700 update_x_offset();
701 wresize(body, body_lines, body_cols);
703 wresize(tabline, 1, COLS);
705 tab = current_tab();
707 wrap_page(&tab->buffer, body_cols);
708 redraw_tab(tab);
711 static int
712 wrap_page(struct buffer *buffer, int width)
714 struct line *l;
715 const struct line *orig;
716 struct vline *vl;
717 int pre_width;
718 const char *prfx;
720 orig = buffer->current_line == NULL
721 ? NULL
722 : buffer->current_line->parent;
723 buffer->current_line = NULL;
725 buffer->force_redraw = 1;
726 buffer->curs_y = 0;
727 buffer->line_off = 0;
729 empty_vlist(buffer);
731 TAILQ_FOREACH(l, &buffer->page.head, lines) {
732 prfx = line_prefixes[l->type].prfx1;
733 switch (l->type) {
734 case LINE_TEXT:
735 case LINE_LINK:
736 case LINE_TITLE_1:
737 case LINE_TITLE_2:
738 case LINE_TITLE_3:
739 case LINE_ITEM:
740 case LINE_QUOTE:
741 case LINE_PRE_START:
742 case LINE_PRE_END:
743 wrap_text(buffer, prfx, l, MIN(fill_column, width));
744 break;
745 case LINE_PRE_CONTENT:
746 if (olivetti_mode)
747 pre_width = MIN(fill_column, width);
748 else
749 pre_width = width;
750 hardwrap_text(buffer, l, pre_width);
751 break;
754 if (orig == l && buffer->current_line == NULL) {
755 buffer->line_off = buffer->line_max-1;
756 buffer->current_line = TAILQ_LAST(&buffer->head, vhead);
758 while (1) {
759 vl = TAILQ_PREV(buffer->current_line, vhead, vlines);
760 if (vl == NULL || vl->parent != orig)
761 break;
762 buffer->current_line = vl;
763 buffer->line_off--;
768 if (buffer->current_line == NULL)
769 buffer->current_line = TAILQ_FIRST(&buffer->head);
771 return 1;
774 static void
775 print_vline(int off, int width, WINDOW *window, struct vline *vl)
777 const char *text;
778 const char *prfx;
779 struct line_face *f;
780 int i, left, x, y;
782 f = &line_faces[vl->parent->type];
784 /* unused, set by getyx */
785 (void)y;
787 if (!vl->flags)
788 prfx = line_prefixes[vl->parent->type].prfx1;
789 else
790 prfx = line_prefixes[vl->parent->type].prfx2;
792 text = vl->line;
793 if (text == NULL)
794 text = "";
796 wattr_on(window, body_face.left, NULL);
797 for (i = 0; i < off; i++)
798 waddch(window, ' ');
799 wattr_off(window, body_face.left, NULL);
801 wattr_on(window, f->prefix, NULL);
802 wprintw(window, "%s", prfx);
803 wattr_off(window, f->prefix, NULL);
805 wattr_on(window, f->text, NULL);
806 wprintw(window, "%s", text);
807 wattr_off(window, f->text, NULL);
809 getyx(window, y, x);
811 left = width - x;
813 wattr_on(window, f->trail, NULL);
814 for (i = 0; i < left - off - 1; ++i)
815 waddch(window, ' ');
816 wattr_off(window, f->trail, NULL);
818 wattr_on(window, body_face.right, NULL);
819 for (i = 0; i < off; i++)
820 waddch(window, ' ');
821 wattr_off(window, body_face.right, NULL);
825 static void
826 redraw_tabline(void)
828 struct tab *tab;
829 size_t toskip, ots, tabwidth, space, x;
830 int current, y, truncated;
831 const char *title;
832 char buf[25];
834 x = 0;
836 /* unused, but setted by a getyx */
837 (void)y;
839 tabwidth = sizeof(buf)+1;
840 space = COLS-2;
842 toskip = 0;
843 TAILQ_FOREACH(tab, &tabshead, tabs) {
844 toskip++;
845 if (tab->flags & TAB_CURRENT)
846 break;
849 if (toskip * tabwidth < space)
850 toskip = 0;
851 else {
852 ots = toskip;
853 toskip--;
854 while (toskip != 0 &&
855 (ots - toskip+1) * tabwidth < space)
856 toskip--;
859 werase(tabline);
860 wattr_on(tabline, tab_face.background, NULL);
861 wprintw(tabline, toskip == 0 ? " " : "<");
862 wattr_off(tabline, tab_face.background, NULL);
864 truncated = 0;
865 TAILQ_FOREACH(tab, &tabshead, tabs) {
866 if (truncated)
867 break;
868 if (toskip != 0) {
869 toskip--;
870 continue;
873 getyx(tabline, y, x);
874 if (x + sizeof(buf)+2 >= (size_t)COLS)
875 truncated = 1;
877 current = tab->flags & TAB_CURRENT;
879 if (*(title = tab->buffer.page.title) == '\0')
880 title = tab->hist_cur->h;
882 if (tab->flags & TAB_URGENT)
883 strlcpy(buf, "!", sizeof(buf));
884 else
885 strlcpy(buf, " ", sizeof(buf));
887 if (strlcat(buf, title, sizeof(buf)) >= sizeof(buf)) {
888 /* truncation happens */
889 strlcpy(&buf[sizeof(buf)-4], "...", 4);
890 } else {
891 /* pad with spaces */
892 while (strlcat(buf, " ", sizeof(buf)) < sizeof(buf))
893 /* nop */ ;
896 if (current)
897 wattr_on(tabline, tab_face.current, NULL);
898 else
899 wattr_on(tabline, tab_face.tab, NULL);
901 wprintw(tabline, "%s", buf);
902 if (TAILQ_NEXT(tab, tabs) != NULL)
903 wprintw(tabline, " ");
905 if (current)
906 wattr_off(tabline, tab_face.current, NULL);
907 else
908 wattr_off(tabline, tab_face.tab, NULL);
911 wattr_on(tabline, tab_face.background, NULL);
912 for (; x < (size_t)COLS; ++x)
913 waddch(tabline, ' ');
914 if (truncated)
915 mvwprintw(tabline, 0, COLS-1, ">");
916 wattr_off(tabline, tab_face.background, NULL);
919 static void
920 redraw_window(WINDOW *win, int height, int width, struct buffer *buffer)
922 struct vline *vl;
923 int l;
925 /*
926 * Don't bother redraw the body if nothing changed. Cursor
927 * movements count as "nothing changed" if it hasn't produced
928 * a scroll. Ensure that wmove is called though!
929 */
930 if (!buffer->force_redraw &&
931 buffer->last_line_off == buffer->line_off)
932 goto end;
934 werase(win);
936 buffer->line_off = MIN(buffer->line_max-1, buffer->line_off);
937 buffer->force_redraw = 0;
938 buffer->last_line_off = buffer->line_off;
940 if (TAILQ_EMPTY(&buffer->head))
941 goto end;
943 l = 0;
944 vl = nth_line(buffer, buffer->line_off);
945 for (; vl != NULL; vl = TAILQ_NEXT(vl, vlines)) {
946 wmove(win, l, 0);
947 print_vline(x_offset, width, win, vl);
948 l++;
949 if (l == height)
950 break;
953 end:
954 wmove(win, buffer->curs_y, buffer->curs_x);
957 static void
958 redraw_help(void)
960 redraw_window(help, help_lines, help_cols, &helpwin);
963 static void
964 redraw_body(struct tab *tab)
966 static struct tab *last_tab;
968 if (last_tab != tab)
969 tab->buffer.force_redraw =1;
970 last_tab = tab;
972 redraw_window(body, body_lines, body_cols, &tab->buffer);
975 static inline char
976 trust_status_char(enum trust_state ts)
978 switch (ts) {
979 case TS_UNKNOWN: return 'u';
980 case TS_UNTRUSTED: return '!';
981 case TS_TRUSTED: return 'v';
982 case TS_VERIFIED: return 'V';
983 default: return 'X';
987 static void
988 redraw_modeline(struct tab *tab)
990 double pct;
991 int x, y, max_x, max_y;
992 const char *mode = tab->buffer.page.name;
993 const char *spin = "-\\|/";
995 werase(modeline);
996 wattr_on(modeline, modeline_face.background, NULL);
997 wmove(modeline, 0, 0);
999 wprintw(modeline, "-%c%c %s ",
1000 spin[tab->loading_anim_step],
1001 trust_status_char(tab->trust),
1002 mode == NULL ? "(none)" : mode);
1004 pct = (tab->buffer.line_off + tab->buffer.curs_y) * 100.0 / tab->buffer.line_max;
1006 if (tab->buffer.line_max <= (size_t)body_lines)
1007 wprintw(modeline, "All ");
1008 else if (tab->buffer.line_off == 0)
1009 wprintw(modeline, "Top ");
1010 else if (tab->buffer.line_off + body_lines >= tab->buffer.line_max)
1011 wprintw(modeline, "Bottom ");
1012 else
1013 wprintw(modeline, "%.0f%% ", pct);
1015 wprintw(modeline, "%d/%d %s ",
1016 tab->buffer.line_off + tab->buffer.curs_y,
1017 tab->buffer.line_max,
1018 tab->hist_cur->h);
1020 getyx(modeline, y, x);
1021 getmaxyx(modeline, max_y, max_x);
1023 (void)y;
1024 (void)max_y;
1026 for (; x < max_x; ++x)
1027 waddstr(modeline, "-");
1029 wattr_off(modeline, modeline_face.background, NULL);
1032 static void
1033 redraw_minibuffer(void)
1035 struct tab *tab;
1036 size_t off_y, off_x = 0;
1037 char *start = NULL, *c = NULL;
1039 /* unused, but set by getyx */
1040 (void)off_y;
1042 wattr_on(minibuf, minibuffer_face.background, NULL);
1043 werase(minibuf);
1045 if (in_minibuffer) {
1046 mvwprintw(minibuf, 0, 0, "%s", ministate.prompt);
1047 if (ministate.hist_cur != NULL)
1048 wprintw(minibuf, "(%zu/%zu) ",
1049 ministate.hist_off + 1,
1050 ministate.history->len);
1052 getyx(minibuf, off_y, off_x);
1054 start = ministate.hist_cur != NULL
1055 ? ministate.hist_cur->h
1056 : ministate.buf;
1057 c = utf8_nth(ministate.buffer.current_line->line,
1058 ministate.buffer.cpoff);
1059 while (utf8_swidth_between(start, c) > (size_t)COLS/2) {
1060 start = utf8_next_cp(start);
1063 waddstr(minibuf, start);
1066 if (ministate.curmesg != NULL)
1067 wprintw(minibuf, in_minibuffer ? " [%s]" : "%s",
1068 ministate.curmesg);
1070 if (!in_minibuffer && ministate.curmesg == NULL)
1071 waddstr(minibuf, keybuf);
1073 /* If nothing else, show the URL at point */
1074 if (!in_minibuffer && ministate.curmesg == NULL && *keybuf == '\0') {
1075 tab = current_tab();
1076 if (tab->buffer.current_line != NULL &&
1077 tab->buffer.current_line->parent->type == LINE_LINK)
1078 waddstr(minibuf, tab->buffer.current_line->parent->alt);
1081 if (in_minibuffer)
1082 wmove(minibuf, 0, off_x + utf8_swidth_between(start, c));
1084 wattr_off(minibuf, minibuffer_face.background, NULL);
1087 static void
1088 redraw_tab(struct tab *tab)
1090 if (side_window) {
1091 redraw_help();
1092 wnoutrefresh(help);
1095 restore_cursor(&tab->buffer);
1097 redraw_tabline();
1098 redraw_body(tab);
1099 redraw_modeline(tab);
1100 redraw_minibuffer();
1102 wnoutrefresh(tabline);
1103 wnoutrefresh(modeline);
1105 if (in_minibuffer) {
1106 wnoutrefresh(body);
1107 wnoutrefresh(minibuf);
1108 } else {
1109 wnoutrefresh(minibuf);
1110 wnoutrefresh(body);
1113 doupdate();
1116 static void
1117 emit_help_item(char *prfx, void *fn)
1119 struct line *l;
1120 struct cmd *cmd;
1122 for (cmd = cmds; cmd->cmd != NULL; ++cmd) {
1123 if (fn == cmd->fn)
1124 break;
1126 assert(cmd != NULL);
1128 if ((l = calloc(1, sizeof(*l))) == NULL)
1129 abort();
1131 l->type = LINE_TEXT;
1132 l->alt = NULL;
1134 asprintf(&l->line, "%s %s", prfx, cmd->cmd);
1136 if (TAILQ_EMPTY(&helpwin.page.head))
1137 TAILQ_INSERT_HEAD(&helpwin.page.head, l, lines);
1138 else
1139 TAILQ_INSERT_TAIL(&helpwin.page.head, l, lines);
1142 static void
1143 rec_compute_help(struct kmap *keymap, char *prfx, size_t len)
1145 struct keymap *k;
1146 char p[32];
1147 const char *kn;
1149 TAILQ_FOREACH(k, &keymap->m, keymaps) {
1150 strlcpy(p, prfx, sizeof(p));
1151 if (*p != '\0')
1152 strlcat(p, " ", sizeof(p));
1153 if (k->meta)
1154 strlcat(p, "M-", sizeof(p));
1155 if ((kn = unkbd(k->key)) != NULL)
1156 strlcat(p, kn, sizeof(p));
1157 else
1158 strlcat(p, keyname(k->key), sizeof(p));
1160 if (k->fn == NULL)
1161 rec_compute_help(&k->map, p, sizeof(p));
1162 else
1163 emit_help_item(p, k->fn);
1167 static void
1168 recompute_help(void)
1170 char p[32] = { 0 };
1172 empty_vlist(&helpwin);
1173 empty_linelist(&helpwin);
1174 rec_compute_help(current_map, p, sizeof(p));
1175 wrap_page(&helpwin, help_cols);
1178 void
1179 vmessage(const char *fmt, va_list ap)
1181 if (evtimer_pending(&clminibufev, NULL))
1182 evtimer_del(&clminibufev);
1184 free(ministate.curmesg);
1185 ministate.curmesg = NULL;
1187 if (fmt != NULL) {
1188 evtimer_set(&clminibufev, handle_clear_minibuf, NULL);
1189 evtimer_add(&clminibufev, &clminibufev_timer);
1191 /* TODO: what to do if the allocation fails here? */
1192 if (vasprintf(&ministate.curmesg, fmt, ap) == -1)
1193 ministate.curmesg = NULL;
1196 redraw_minibuffer();
1197 if (in_minibuffer) {
1198 wrefresh(body);
1199 wrefresh(minibuf);
1200 } else {
1201 wrefresh(minibuf);
1202 wrefresh(body);
1206 void
1207 message(const char *fmt, ...)
1209 va_list ap;
1211 va_start(ap, fmt);
1212 vmessage(fmt, ap);
1213 va_end(ap);
1216 void
1217 start_loading_anim(struct tab *tab)
1219 if (tab->loading_anim)
1220 return;
1221 tab->loading_anim = 1;
1222 evtimer_set(&tab->loadingev, update_loading_anim, tab);
1223 evtimer_add(&tab->loadingev, &loadingev_timer);
1226 static void
1227 update_loading_anim(int fd, short ev, void *d)
1229 struct tab *tab = d;
1231 tab->loading_anim_step = (tab->loading_anim_step+1)%4;
1233 if (tab->flags & TAB_CURRENT) {
1234 redraw_modeline(tab);
1235 wrefresh(modeline);
1236 wrefresh(body);
1237 if (in_minibuffer)
1238 wrefresh(minibuf);
1241 evtimer_add(&tab->loadingev, &loadingev_timer);
1244 static void
1245 stop_loading_anim(struct tab *tab)
1247 if (!tab->loading_anim)
1248 return;
1249 evtimer_del(&tab->loadingev);
1250 tab->loading_anim = 0;
1251 tab->loading_anim_step = 0;
1253 if (!(tab->flags & TAB_CURRENT))
1254 return;
1256 redraw_modeline(tab);
1258 wrefresh(modeline);
1259 wrefresh(body);
1260 if (in_minibuffer)
1261 wrefresh(minibuf);
1264 void
1265 load_url_in_tab(struct tab *tab, const char *url)
1267 message("Loading %s...", url);
1268 start_loading_anim(tab);
1269 load_url(tab, url);
1271 tab->buffer.curs_x = 0;
1272 tab->buffer.curs_y = 0;
1273 redraw_tab(tab);
1276 void
1277 enter_minibuffer(void (*self_insert_fn)(void), void (*donefn)(void),
1278 void (*abortfn)(void), struct histhead *hist)
1280 in_minibuffer = 1;
1281 base_map = &minibuffer_map;
1282 current_map = &minibuffer_map;
1284 base_map->unhandled_input = self_insert_fn;
1286 ministate.donefn = donefn;
1287 ministate.abortfn = abortfn;
1288 memset(ministate.buf, 0, sizeof(ministate.buf));
1289 ministate.buffer.current_line = &ministate.vline;
1290 ministate.buffer.current_line->line = ministate.buf;
1291 ministate.buffer.cpoff = 0;
1292 strlcpy(ministate.buf, "", sizeof(ministate.prompt));
1294 ministate.history = hist;
1295 ministate.hist_cur = NULL;
1296 ministate.hist_off = 0;
1299 void
1300 exit_minibuffer(void)
1302 werase(minibuf);
1304 in_minibuffer = 0;
1305 base_map = &global_map;
1306 current_map = &global_map;
1309 void
1310 switch_to_tab(struct tab *tab)
1312 struct tab *t;
1314 TAILQ_FOREACH(t, &tabshead, tabs) {
1315 t->flags &= ~TAB_CURRENT;
1318 tab->flags |= TAB_CURRENT;
1319 tab->flags &= ~TAB_URGENT;
1322 unsigned int
1323 tab_new_id(void)
1325 return tab_counter++;
1328 struct tab *
1329 new_tab(const char *url)
1331 struct tab *tab;
1333 if ((tab = calloc(1, sizeof(*tab))) == NULL) {
1334 event_loopbreak();
1335 return NULL;
1337 tab->fd = -1;
1339 TAILQ_INIT(&tab->hist.head);
1341 TAILQ_INIT(&tab->buffer.head);
1343 tab->id = tab_new_id();
1344 switch_to_tab(tab);
1346 if (TAILQ_EMPTY(&tabshead))
1347 TAILQ_INSERT_HEAD(&tabshead, tab, tabs);
1348 else
1349 TAILQ_INSERT_TAIL(&tabshead, tab, tabs);
1351 load_url_in_tab(tab, url);
1352 return tab;
1355 static void
1356 session_new_tab_cb(const char *url)
1358 new_tab(url);
1361 static void
1362 usage(void)
1364 fprintf(stderr, "USAGE: %s [-hn] [-c config] [url]\n", getprogname());
1365 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
1368 int
1369 ui_init(int argc, char * const *argv)
1371 char path[PATH_MAX];
1372 const char *url = NEW_TAB_URL;
1373 int ch, configtest = 0, fonf = 0;
1375 if (getenv("NO_COLOR") != NULL)
1376 enable_colors = 0;
1378 strlcpy(path, getenv("HOME"), sizeof(path));
1379 strlcat(path, "/.telescope/config", sizeof(path));
1381 while ((ch = getopt(argc, argv, "c:hn")) != -1) {
1382 switch (ch) {
1383 case 'c':
1384 fonf = 1;
1385 strlcpy(path, optarg, sizeof(path));
1386 break;
1387 case 'n':
1388 configtest = 1;
1389 break;
1390 case 'h':
1391 usage();
1392 return 0;
1393 default:
1394 usage();
1395 return 1;
1398 argc -= optind;
1399 argv += optind;
1401 /* setup keys before reading the config */
1402 TAILQ_INIT(&global_map.m);
1403 global_map.unhandled_input = global_key_unbound;
1405 TAILQ_INIT(&minibuffer_map.m);
1407 load_default_keys();
1409 config_init();
1410 parseconfig(path, fonf);
1411 if (configtest){
1412 puts("config OK");
1413 exit(0);
1416 if (argc != 0)
1417 url = argv[0];
1419 setlocale(LC_ALL, "");
1421 TAILQ_INIT(&eecmd_history.head);
1422 TAILQ_INIT(&ir_history.head);
1423 TAILQ_INIT(&lu_history.head);
1425 ministate.line.type = LINE_TEXT;
1426 ministate.vline.parent = &ministate.line;
1427 ministate.buffer.current_line = &ministate.vline;
1429 /* initialize help window */
1430 TAILQ_INIT(&helpwin.head);
1432 base_map = &global_map;
1433 current_map = &global_map;
1435 initscr();
1437 if (enable_colors) {
1438 if (has_colors()) {
1439 start_color();
1440 use_default_colors();
1441 } else
1442 enable_colors = 0;
1445 config_apply_style();
1447 raw();
1448 noecho();
1449 nonl();
1450 intrflush(stdscr, FALSE);
1452 if ((tabline = newwin(1, COLS, 0, 0)) == NULL)
1453 return 0;
1454 if ((body = newwin(LINES - 3, COLS, 1, 0)) == NULL)
1455 return 0;
1456 if ((modeline = newwin(1, COLS, LINES-2, 0)) == NULL)
1457 return 0;
1458 if ((minibuf = newwin(1, COLS, LINES-1, 0)) == NULL)
1459 return 0;
1460 if ((help = newwin(1, 1, 1, 0)) == NULL)
1461 return 0;
1463 body_lines = LINES-3;
1464 body_cols = COLS;
1466 wbkgd(body, body_face.body);
1467 wbkgd(minibuf, minibuffer_face.background);
1469 update_x_offset();
1471 keypad(body, TRUE);
1472 scrollok(body, FALSE);
1474 /* non-blocking input */
1475 wtimeout(body, 0);
1477 mvwprintw(body, 0, 0, "");
1479 event_set(&stdioev, 0, EV_READ | EV_PERSIST, dispatch_stdio, NULL);
1480 event_add(&stdioev, NULL);
1482 signal_set(&winchev, SIGWINCH, handle_resize, NULL);
1483 signal_add(&winchev, NULL);
1485 load_last_session(session_new_tab_cb);
1486 if (strcmp(url, NEW_TAB_URL) || TAILQ_EMPTY(&tabshead))
1487 new_tab(url);
1489 return 1;
1492 void
1493 ui_on_tab_loaded(struct tab *tab)
1495 stop_loading_anim(tab);
1496 message("Loaded %s", tab->hist_cur->h);
1498 redraw_tabline();
1499 wrefresh(tabline);
1500 if (in_minibuffer)
1501 wrefresh(minibuf);
1502 else
1503 wrefresh(body);
1506 void
1507 ui_on_tab_refresh(struct tab *tab)
1509 wrap_page(&tab->buffer, body_cols);
1510 if (tab->flags & TAB_CURRENT) {
1511 restore_cursor(&tab->buffer);
1512 redraw_tab(tab);
1513 } else
1514 tab->flags |= TAB_URGENT;
1517 const char *
1518 ui_keyname(int k)
1520 return keyname(k);
1523 void
1524 ui_toggle_side_window(void)
1526 side_window = !side_window;
1527 if (side_window)
1528 recompute_help();
1531 * ugly hack, but otherwise the window doesn't get updated
1532 * until I call handle_resize a second time (i.e. C-l). I
1533 * will be happy to know why something like this is needed.
1535 handle_resize_nodelay(0, 0, NULL);
1536 handle_resize_nodelay(0, 0, NULL);
1539 void
1540 ui_schedule_redraw(void)
1542 handle_resize_nodelay(0, 0, NULL);
1545 void
1546 ui_require_input(struct tab *tab, int hide)
1548 /* TODO: hard-switching to another tab is ugly */
1549 switch_to_tab(tab);
1551 enter_minibuffer(ir_self_insert, ir_select, exit_minibuffer,
1552 &ir_history);
1553 strlcpy(ministate.prompt, "Input required: ",
1554 sizeof(ministate.prompt));
1555 redraw_tab(tab);
1558 void
1559 ui_yornp(const char *prompt, void (*fn)(int, unsigned int),
1560 unsigned int data)
1562 size_t len;
1564 if (in_minibuffer) {
1565 fn(0, data);
1566 return;
1569 yornp_cb = fn;
1570 yornp_data = data;
1571 enter_minibuffer(yornp_self_insert, yornp_self_insert,
1572 yornp_abort, NULL);
1574 len = sizeof(ministate.prompt);
1575 strlcpy(ministate.prompt, prompt, len);
1576 strlcat(ministate.prompt, " (y or n) ", len);
1577 redraw_tab(current_tab());
1580 void
1581 ui_read(const char *prompt, void (*fn)(const char*, unsigned int),
1582 unsigned int data)
1584 size_t len;
1586 if (in_minibuffer)
1587 return;
1589 read_cb = fn;
1590 read_data = data;
1591 enter_minibuffer(read_self_insert, read_select, read_abort,
1592 &read_history);
1594 len = sizeof(ministate.prompt);
1595 strlcpy(ministate.prompt, prompt, len);
1596 strlcat(ministate.prompt, ": ", len);
1597 redraw_tab(current_tab());
1600 void
1601 ui_end(void)
1603 endwin();