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 restore_cursor(struct buffer *buffer)
282 struct vline *vl;
283 const char *prfx;
285 vl = buffer->current_line;
286 if (vl == NULL || vl->line == NULL)
287 buffer->curs_x = buffer->cpoff = 0;
288 else
289 buffer->curs_x = utf8_snwidth(vl->line, buffer->cpoff);
291 buffer->curs_x += x_offset;
293 if (vl != NULL) {
294 prfx = line_prefixes[vl->parent->type].prfx1;
295 buffer->curs_x += utf8_swidth(prfx);
299 static void
300 global_key_unbound(void)
302 message("%s is undefined", keybuf);
305 static void
306 minibuffer_hist_save_entry(void)
308 struct hist *hist;
310 if (ministate.history == NULL)
311 return;
313 if ((hist = calloc(1, sizeof(*hist))) == NULL)
314 abort();
316 strlcpy(hist->h, ministate.buf, sizeof(hist->h));
318 if (TAILQ_EMPTY(&ministate.history->head))
319 TAILQ_INSERT_HEAD(&ministate.history->head, hist, entries);
320 else
321 TAILQ_INSERT_TAIL(&ministate.history->head, hist, entries);
322 ministate.history->len++;
325 /*
326 * taint the minibuffer cache: if we're currently showing a history
327 * element, copy that to the current buf and reset the "history
328 * navigation" thing.
329 */
330 void
331 minibuffer_taint_hist(void)
333 if (ministate.hist_cur == NULL)
334 return;
336 strlcpy(ministate.buf, ministate.hist_cur->h, sizeof(ministate.buf));
337 ministate.hist_cur = NULL;
340 static void
341 minibuffer_self_insert(void)
343 char *c, tmp[5] = {0};
344 size_t len;
346 minibuffer_taint_hist();
348 if (thiskey.cp == 0)
349 return;
351 len = utf8_encode(thiskey.cp, tmp);
352 c = utf8_nth(ministate.buffer.current_line->line, ministate.buffer.cpoff);
353 if (c + len > ministate.buf + sizeof(ministate.buf) - 1)
354 return;
356 memmove(c + len, c, strlen(c)+1);
357 memcpy(c, tmp, len);
358 ministate.buffer.cpoff++;
361 void
362 eecmd_self_insert(void)
364 if (thiskey.meta || unicode_isspace(thiskey.cp) ||
365 !unicode_isgraph(thiskey.cp)) {
366 global_key_unbound();
367 return;
370 minibuffer_self_insert();
373 void
374 eecmd_select(void)
376 struct cmds *cmd;
378 for (cmd = cmds; cmd->cmd != NULL; ++cmd) {
379 if (!strcmp(cmd->cmd, ministate.buf)) {
380 exit_minibuffer();
381 minibuffer_hist_save_entry();
382 cmd->fn(current_buffer());
383 return;
387 message("No match");
390 void
391 ir_self_insert(void)
393 minibuffer_self_insert();
396 void
397 ir_select(void)
399 char buf[1025] = {0};
400 struct phos_uri uri;
401 struct tab *tab;
403 tab = current_tab();
405 exit_minibuffer();
406 minibuffer_hist_save_entry();
408 /* a bit ugly but... */
409 memcpy(&uri, &tab->uri, sizeof(tab->uri));
410 phos_uri_set_query(&uri, ministate.buf);
411 phos_serialize_uri(&uri, buf, sizeof(buf));
412 load_url_in_tab(tab, buf);
415 void
416 lu_self_insert(void)
418 if (thiskey.meta || unicode_isspace(thiskey.key) ||
419 !unicode_isgraph(thiskey.key)) {
420 global_key_unbound();
421 return;
424 minibuffer_self_insert();
427 void
428 lu_select(void)
430 exit_minibuffer();
431 minibuffer_hist_save_entry();
432 load_url_in_tab(current_tab(), ministate.buf);
435 void
436 bp_select(void)
438 exit_minibuffer();
439 if (*ministate.buf != '\0')
440 add_to_bookmarks(ministate.buf);
441 else
442 message("Abort.");
445 static void
446 yornp_self_insert(void)
448 if (thiskey.key != 'y' && thiskey.key != 'n') {
449 message("Please answer y or n");
450 return;
453 exit_minibuffer();
454 yornp_cb(thiskey.key == 'y', yornp_data);
457 static void
458 yornp_abort(void)
460 exit_minibuffer();
461 yornp_cb(0, yornp_data);
464 static void
465 read_self_insert(void)
467 if (thiskey.meta || !unicode_isgraph(thiskey.cp)) {
468 global_key_unbound();
469 return;
472 minibuffer_self_insert();
475 static void
476 read_abort(void)
478 exit_minibuffer();
479 read_cb(NULL, read_data);
482 static void
483 read_select(void)
485 exit_minibuffer();
486 minibuffer_hist_save_entry();
487 read_cb(ministate.buf, read_data);
490 static struct vline *
491 nth_line(struct buffer *buffer, size_t n)
493 struct vline *vl;
494 size_t i;
496 i = 0;
497 TAILQ_FOREACH(vl, &buffer->head, vlines) {
498 if (i == n)
499 return vl;
500 i++;
503 /* unreachable */
504 abort();
507 struct tab *
508 current_tab(void)
510 struct tab *t;
512 TAILQ_FOREACH(t, &tabshead, tabs) {
513 if (t->flags & TAB_CURRENT)
514 return t;
517 /* unreachable */
518 abort();
521 struct buffer *
522 current_buffer(void)
524 if (in_minibuffer)
525 return &ministate.buffer;
526 return &current_tab()->buffer;
529 static int
530 readkey(void)
532 uint32_t state = 0;
534 if ((thiskey.key = wgetch(body)) == ERR)
535 return 0;
537 thiskey.meta = thiskey.key == 27;
538 if (thiskey.meta) {
539 thiskey.key = wgetch(body);
540 if (thiskey.key == ERR || thiskey.key == 27) {
541 thiskey.meta = 0;
542 thiskey.key = 27;
546 thiskey.cp = 0;
547 if ((unsigned int)thiskey.key < UINT8_MAX) {
548 while (1) {
549 if (!utf8_decode(&state, &thiskey.cp, (uint8_t)thiskey.key))
550 break;
551 if ((thiskey.key = wgetch(body)) == ERR) {
552 message("Error decoding user input");
553 return 0;
558 return 1;
561 static void
562 dispatch_stdio(int fd, short ev, void *d)
564 struct keymap *k;
565 const char *keyname;
566 char tmp[5] = {0};
568 if (!readkey())
569 return;
571 if (keybuf[0] != '\0')
572 strlcat(keybuf, " ", sizeof(keybuf));
573 if (thiskey.meta)
574 strlcat(keybuf, "M-", sizeof(keybuf));
575 if (thiskey.cp != 0) {
576 utf8_encode(thiskey.cp, tmp);
577 strlcat(keybuf, tmp, sizeof(keybuf));
578 } else {
579 if ((keyname = unkbd(thiskey.key)) != NULL)
580 strlcat(keybuf, keyname, sizeof(keybuf));
581 else {
582 tmp[0] = thiskey.key;
583 strlcat(keybuf, tmp, sizeof(keybuf));
587 TAILQ_FOREACH(k, &current_map->m, keymaps) {
588 if (k->meta == thiskey.meta &&
589 k->key == thiskey.key) {
590 if (k->fn == NULL)
591 current_map = &k->map;
592 else {
593 current_map = base_map;
594 strlcpy(keybuf, "", sizeof(keybuf));
595 k->fn(current_buffer());
597 goto done;
601 if (current_map->unhandled_input != NULL)
602 current_map->unhandled_input();
603 else
604 global_key_unbound();
606 strlcpy(keybuf, "", sizeof(keybuf));
607 current_map = base_map;
609 done:
610 if (side_window)
611 recompute_help();
613 redraw_tab(current_tab());
616 static void
617 handle_clear_minibuf(int fd, short ev, void *d)
619 free(ministate.curmesg);
620 ministate.curmesg = NULL;
622 redraw_minibuffer();
623 if (in_minibuffer) {
624 wrefresh(body);
625 wrefresh(minibuf);
626 } else {
627 wrefresh(minibuf);
628 wrefresh(body);
632 static void
633 handle_resize(int sig, short ev, void *d)
635 if (event_pending(&resizeev, EV_TIMEOUT, NULL)) {
636 event_del(&resizeev);
638 evtimer_set(&resizeev, handle_resize_nodelay, NULL);
639 evtimer_add(&resizeev, &resize_timer);
642 static void
643 handle_resize_nodelay(int s, short ev, void *d)
645 struct tab *tab;
647 endwin();
648 refresh();
649 clear();
651 /* move and resize the windows, in reverse order! */
653 mvwin(minibuf, LINES-1, 0);
654 wresize(minibuf, 1, COLS);
656 mvwin(modeline, LINES-2, 0);
657 wresize(modeline, 1, COLS);
659 body_lines = LINES-3;
660 body_cols = COLS;
662 if (side_window) {
663 help_cols = 0.3 * COLS;
664 help_lines = LINES-3;
665 mvwin(help, 1, 0);
666 wresize(help, help_lines, help_cols);
668 wrap_page(&helpwin, help_cols);
670 body_cols = COLS - help_cols - 1;
671 mvwin(body, 1, help_cols);
672 } else
673 mvwin(body, 1, 0);
675 update_x_offset();
676 wresize(body, body_lines, body_cols);
678 wresize(tabline, 1, COLS);
680 tab = current_tab();
682 wrap_page(&tab->buffer, body_cols);
683 redraw_tab(tab);
686 static int
687 wrap_page(struct buffer *buffer, int width)
689 struct line *l;
690 const struct line *orig;
691 struct vline *vl;
692 int pre_width;
693 const char *prfx;
695 orig = buffer->current_line == NULL
696 ? NULL
697 : buffer->current_line->parent;
698 buffer->current_line = NULL;
700 buffer->force_redraw = 1;
701 buffer->curs_y = 0;
702 buffer->line_off = 0;
704 empty_vlist(buffer);
706 TAILQ_FOREACH(l, &buffer->page.head, lines) {
707 prfx = line_prefixes[l->type].prfx1;
708 switch (l->type) {
709 case LINE_TEXT:
710 case LINE_LINK:
711 case LINE_TITLE_1:
712 case LINE_TITLE_2:
713 case LINE_TITLE_3:
714 case LINE_ITEM:
715 case LINE_QUOTE:
716 case LINE_PRE_START:
717 case LINE_PRE_END:
718 wrap_text(buffer, prfx, l, MIN(fill_column, width));
719 break;
720 case LINE_PRE_CONTENT:
721 if (olivetti_mode)
722 pre_width = MIN(fill_column, width);
723 else
724 pre_width = width;
725 hardwrap_text(buffer, l, pre_width);
726 break;
729 if (orig == l && buffer->current_line == NULL) {
730 buffer->line_off = buffer->line_max-1;
731 buffer->current_line = TAILQ_LAST(&buffer->head, vhead);
733 while (1) {
734 vl = TAILQ_PREV(buffer->current_line, vhead, vlines);
735 if (vl == NULL || vl->parent != orig)
736 break;
737 buffer->current_line = vl;
738 buffer->line_off--;
743 if (buffer->current_line == NULL)
744 buffer->current_line = TAILQ_FIRST(&buffer->head);
746 return 1;
749 static void
750 print_vline(int off, int width, WINDOW *window, struct vline *vl)
752 const char *text = vl->line;
753 const char *prfx;
754 int prefix_face = line_faces[vl->parent->type].prefix_prop;
755 int text_face = line_faces[vl->parent->type].text_prop;
756 int trail_face = line_faces[vl->parent->type].trail_prop;
757 int i, left, x, y;
759 /* unused, set by getyx */
760 (void)y;
762 if (!vl->flags)
763 prfx = line_prefixes[vl->parent->type].prfx1;
764 else
765 prfx = line_prefixes[vl->parent->type].prfx2;
767 if (text == NULL)
768 text = "";
770 wattron(window, body_face.left);
771 for (i = 0; i < off; i++)
772 waddch(window, ' ');
773 wattroff(window, body_face.left);
775 wattron(window, prefix_face);
776 wprintw(window, "%s", prfx);
777 wattroff(window, prefix_face);
779 wattron(window, text_face);
780 wprintw(window, "%s", text);
781 wattroff(window, text_face);
783 getyx(window, y, x);
785 left = width - x;
787 wattron(window, trail_face);
788 for (i = 0; i < left - off - 1; ++i)
789 waddch(window, ' ');
790 wattroff(window, trail_face);
792 wattron(window, body_face.right);
793 for (i = 0; i < off; i++)
794 waddch(window, ' ');
795 wattroff(window, body_face.right);
799 static void
800 redraw_tabline(void)
802 struct tab *tab;
803 size_t toskip, ots, tabwidth, space, x;
804 int current, y, truncated;
805 const char *title;
806 char buf[25];
808 x = 0;
810 /* unused, but setted by a getyx */
811 (void)y;
813 tabwidth = sizeof(buf)+1;
814 space = COLS-2;
816 toskip = 0;
817 TAILQ_FOREACH(tab, &tabshead, tabs) {
818 toskip++;
819 if (tab->flags & TAB_CURRENT)
820 break;
823 if (toskip * tabwidth < space)
824 toskip = 0;
825 else {
826 ots = toskip;
827 toskip--;
828 while (toskip != 0 &&
829 (ots - toskip+1) * tabwidth < space)
830 toskip--;
833 werase(tabline);
834 wattron(tabline, tab_face.background);
835 wprintw(tabline, toskip == 0 ? " " : "<");
836 wattroff(tabline, tab_face.background);
838 truncated = 0;
839 TAILQ_FOREACH(tab, &tabshead, tabs) {
840 if (truncated)
841 break;
842 if (toskip != 0) {
843 toskip--;
844 continue;
847 getyx(tabline, y, x);
848 if (x + sizeof(buf)+2 >= (size_t)COLS)
849 truncated = 1;
851 current = tab->flags & TAB_CURRENT;
853 if (*(title = tab->buffer.page.title) == '\0')
854 title = tab->hist_cur->h;
856 if (tab->flags & TAB_URGENT)
857 strlcpy(buf, "!", sizeof(buf));
858 else
859 strlcpy(buf, " ", sizeof(buf));
861 if (strlcat(buf, title, sizeof(buf)) >= sizeof(buf)) {
862 /* truncation happens */
863 strlcpy(&buf[sizeof(buf)-4], "...", 4);
864 } else {
865 /* pad with spaces */
866 while (strlcat(buf, " ", sizeof(buf)) < sizeof(buf))
867 /* nop */ ;
870 if (current)
871 wattron(tabline, tab_face.current);
872 else
873 wattron(tabline, tab_face.tab);
875 wprintw(tabline, "%s", buf);
876 if (TAILQ_NEXT(tab, tabs) != NULL)
877 wprintw(tabline, " ");
879 if (current)
880 wattroff(tabline, tab_face.current);
881 else
882 wattroff(tabline, tab_face.tab);
885 wattron(tabline, tab_face.background);
886 for (; x < (size_t)COLS; ++x)
887 waddch(tabline, ' ');
888 if (truncated)
889 mvwprintw(tabline, 0, COLS-1, ">");
890 wattroff(tabline, tab_face.background);
893 static void
894 redraw_window(WINDOW *win, int height, int width, struct buffer *buffer)
896 struct vline *vl;
897 int l;
899 /*
900 * Don't bother redraw the body if nothing changed. Cursor
901 * movements count as "nothing changed" if it hasn't produced
902 * a scroll. Ensure that wmove is called though!
903 */
904 if (!buffer->force_redraw &&
905 buffer->last_line_off == buffer->line_off)
906 goto end;
908 werase(win);
910 buffer->line_off = MIN(buffer->line_max-1, buffer->line_off);
911 buffer->force_redraw = 0;
912 buffer->last_line_off = buffer->line_off;
914 if (TAILQ_EMPTY(&buffer->head))
915 goto end;
917 l = 0;
918 vl = nth_line(buffer, buffer->line_off);
919 for (; vl != NULL; vl = TAILQ_NEXT(vl, vlines)) {
920 wmove(win, l, 0);
921 print_vline(x_offset, width, win, vl);
922 l++;
923 if (l == height)
924 break;
927 end:
928 wmove(win, buffer->curs_y, buffer->curs_x);
931 static void
932 redraw_help(void)
934 redraw_window(help, help_lines, help_cols, &helpwin);
937 static void
938 redraw_body(struct tab *tab)
940 static struct tab *last_tab;
942 if (last_tab != tab)
943 tab->buffer.force_redraw =1;
944 last_tab = tab;
946 redraw_window(body, body_lines, body_cols, &tab->buffer);
949 static inline char
950 trust_status_char(enum trust_state ts)
952 switch (ts) {
953 case TS_UNKNOWN: return 'u';
954 case TS_UNTRUSTED: return '!';
955 case TS_TRUSTED: return 'v';
956 case TS_VERIFIED: return 'V';
957 default: return 'X';
961 static void
962 redraw_modeline(struct tab *tab)
964 double pct;
965 int x, y, max_x, max_y;
966 const char *mode = tab->buffer.page.name;
967 const char *spin = "-\\|/";
969 werase(modeline);
970 wattron(modeline, modeline_face.background);
971 wmove(modeline, 0, 0);
973 wprintw(modeline, "-%c%c %s ",
974 spin[tab->loading_anim_step],
975 trust_status_char(tab->trust),
976 mode == NULL ? "(none)" : mode);
978 pct = (tab->buffer.line_off + tab->buffer.curs_y) * 100.0 / tab->buffer.line_max;
980 if (tab->buffer.line_max <= (size_t)body_lines)
981 wprintw(modeline, "All ");
982 else if (tab->buffer.line_off == 0)
983 wprintw(modeline, "Top ");
984 else if (tab->buffer.line_off + body_lines >= tab->buffer.line_max)
985 wprintw(modeline, "Bottom ");
986 else
987 wprintw(modeline, "%.0f%% ", pct);
989 wprintw(modeline, "%d/%d %s ",
990 tab->buffer.line_off + tab->buffer.curs_y,
991 tab->buffer.line_max,
992 tab->hist_cur->h);
994 getyx(modeline, y, x);
995 getmaxyx(modeline, max_y, max_x);
997 (void)y;
998 (void)max_y;
1000 for (; x < max_x; ++x)
1001 waddstr(modeline, "-");
1003 wattroff(modeline, modeline_face.background);
1006 static void
1007 redraw_minibuffer(void)
1009 struct tab *tab;
1010 size_t off_y, off_x = 0;
1011 char *start = NULL, *c = NULL;
1013 /* unused, but set by getyx */
1014 (void)off_y;
1016 wattron(minibuf, minibuffer_face.background);
1017 werase(minibuf);
1019 if (in_minibuffer) {
1020 mvwprintw(minibuf, 0, 0, "%s", ministate.prompt);
1021 if (ministate.hist_cur != NULL)
1022 wprintw(minibuf, "(%zu/%zu) ",
1023 ministate.hist_off + 1,
1024 ministate.history->len);
1026 getyx(minibuf, off_y, off_x);
1028 start = ministate.hist_cur != NULL
1029 ? ministate.hist_cur->h
1030 : ministate.buf;
1031 c = utf8_nth(ministate.buffer.current_line->line,
1032 ministate.buffer.cpoff);
1033 while (utf8_swidth_between(start, c) > (size_t)COLS/2) {
1034 start = utf8_next_cp(start);
1037 waddstr(minibuf, start);
1040 if (ministate.curmesg != NULL)
1041 wprintw(minibuf, in_minibuffer ? " [%s]" : "%s",
1042 ministate.curmesg);
1044 if (!in_minibuffer && ministate.curmesg == NULL)
1045 waddstr(minibuf, keybuf);
1047 /* If nothing else, show the URL at point */
1048 if (!in_minibuffer && ministate.curmesg == NULL && *keybuf == '\0') {
1049 tab = current_tab();
1050 if (tab->buffer.current_line != NULL &&
1051 tab->buffer.current_line->parent->type == LINE_LINK)
1052 waddstr(minibuf, tab->buffer.current_line->parent->alt);
1055 if (in_minibuffer)
1056 wmove(minibuf, 0, off_x + utf8_swidth_between(start, c));
1058 wattroff(minibuf, minibuffer_face.background);
1061 static void
1062 redraw_tab(struct tab *tab)
1064 if (side_window) {
1065 redraw_help();
1066 wnoutrefresh(help);
1069 restore_cursor(&tab->buffer);
1071 redraw_tabline();
1072 redraw_body(tab);
1073 redraw_modeline(tab);
1074 redraw_minibuffer();
1076 wnoutrefresh(tabline);
1077 wnoutrefresh(modeline);
1079 if (in_minibuffer) {
1080 wnoutrefresh(body);
1081 wnoutrefresh(minibuf);
1082 } else {
1083 wnoutrefresh(minibuf);
1084 wnoutrefresh(body);
1087 doupdate();
1090 static void
1091 emit_help_item(char *prfx, void *fn)
1093 struct line *l;
1094 struct cmds *cmd;
1096 for (cmd = cmds; cmd->cmd != NULL; ++cmd) {
1097 if (fn == cmd->fn)
1098 break;
1100 assert(cmd != NULL);
1102 if ((l = calloc(1, sizeof(*l))) == NULL)
1103 abort();
1105 l->type = LINE_TEXT;
1106 l->alt = NULL;
1108 asprintf(&l->line, "%s %s", prfx, cmd->cmd);
1110 if (TAILQ_EMPTY(&helpwin.page.head))
1111 TAILQ_INSERT_HEAD(&helpwin.page.head, l, lines);
1112 else
1113 TAILQ_INSERT_TAIL(&helpwin.page.head, l, lines);
1116 static void
1117 rec_compute_help(struct kmap *keymap, char *prfx, size_t len)
1119 struct keymap *k;
1120 char p[32];
1121 const char *kn;
1123 TAILQ_FOREACH(k, &keymap->m, keymaps) {
1124 strlcpy(p, prfx, sizeof(p));
1125 if (*p != '\0')
1126 strlcat(p, " ", sizeof(p));
1127 if (k->meta)
1128 strlcat(p, "M-", sizeof(p));
1129 if ((kn = unkbd(k->key)) != NULL)
1130 strlcat(p, kn, sizeof(p));
1131 else
1132 strlcat(p, keyname(k->key), sizeof(p));
1134 if (k->fn == NULL)
1135 rec_compute_help(&k->map, p, sizeof(p));
1136 else
1137 emit_help_item(p, k->fn);
1141 static void
1142 recompute_help(void)
1144 char p[32] = { 0 };
1146 empty_vlist(&helpwin);
1147 empty_linelist(&helpwin);
1148 rec_compute_help(current_map, p, sizeof(p));
1149 wrap_page(&helpwin, help_cols);
1152 void
1153 vmessage(const char *fmt, va_list ap)
1155 if (evtimer_pending(&clminibufev, NULL))
1156 evtimer_del(&clminibufev);
1158 free(ministate.curmesg);
1159 ministate.curmesg = NULL;
1161 if (fmt != NULL) {
1162 evtimer_set(&clminibufev, handle_clear_minibuf, NULL);
1163 evtimer_add(&clminibufev, &clminibufev_timer);
1165 /* TODO: what to do if the allocation fails here? */
1166 if (vasprintf(&ministate.curmesg, fmt, ap) == -1)
1167 ministate.curmesg = NULL;
1170 redraw_minibuffer();
1171 if (in_minibuffer) {
1172 wrefresh(body);
1173 wrefresh(minibuf);
1174 } else {
1175 wrefresh(minibuf);
1176 wrefresh(body);
1180 void
1181 message(const char *fmt, ...)
1183 va_list ap;
1185 va_start(ap, fmt);
1186 vmessage(fmt, ap);
1187 va_end(ap);
1190 void
1191 start_loading_anim(struct tab *tab)
1193 if (tab->loading_anim)
1194 return;
1195 tab->loading_anim = 1;
1196 evtimer_set(&tab->loadingev, update_loading_anim, tab);
1197 evtimer_add(&tab->loadingev, &loadingev_timer);
1200 static void
1201 update_loading_anim(int fd, short ev, void *d)
1203 struct tab *tab = d;
1205 tab->loading_anim_step = (tab->loading_anim_step+1)%4;
1207 if (tab->flags & TAB_CURRENT) {
1208 redraw_modeline(tab);
1209 wrefresh(modeline);
1210 wrefresh(body);
1211 if (in_minibuffer)
1212 wrefresh(minibuf);
1215 evtimer_add(&tab->loadingev, &loadingev_timer);
1218 static void
1219 stop_loading_anim(struct tab *tab)
1221 if (!tab->loading_anim)
1222 return;
1223 evtimer_del(&tab->loadingev);
1224 tab->loading_anim = 0;
1225 tab->loading_anim_step = 0;
1227 if (!(tab->flags & TAB_CURRENT))
1228 return;
1230 redraw_modeline(tab);
1232 wrefresh(modeline);
1233 wrefresh(body);
1234 if (in_minibuffer)
1235 wrefresh(minibuf);
1238 void
1239 load_url_in_tab(struct tab *tab, const char *url)
1241 message("Loading %s...", url);
1242 start_loading_anim(tab);
1243 load_url(tab, url);
1245 tab->buffer.curs_x = 0;
1246 tab->buffer.curs_y = 0;
1247 redraw_tab(tab);
1250 void
1251 enter_minibuffer(void (*self_insert_fn)(void), void (*donefn)(void),
1252 void (*abortfn)(void), struct histhead *hist)
1254 in_minibuffer = 1;
1255 base_map = &minibuffer_map;
1256 current_map = &minibuffer_map;
1258 base_map->unhandled_input = self_insert_fn;
1260 ministate.donefn = donefn;
1261 ministate.abortfn = abortfn;
1262 memset(ministate.buf, 0, sizeof(ministate.buf));
1263 ministate.buffer.current_line = &ministate.vline;
1264 ministate.buffer.current_line->line = ministate.buf;
1265 ministate.buffer.cpoff = 0;
1266 strlcpy(ministate.buf, "", sizeof(ministate.prompt));
1268 ministate.history = hist;
1269 ministate.hist_cur = NULL;
1270 ministate.hist_off = 0;
1273 void
1274 exit_minibuffer(void)
1276 werase(minibuf);
1278 in_minibuffer = 0;
1279 base_map = &global_map;
1280 current_map = &global_map;
1283 void
1284 switch_to_tab(struct tab *tab)
1286 struct tab *t;
1288 TAILQ_FOREACH(t, &tabshead, tabs) {
1289 t->flags &= ~TAB_CURRENT;
1292 tab->flags |= TAB_CURRENT;
1293 tab->flags &= ~TAB_URGENT;
1296 unsigned int
1297 tab_new_id(void)
1299 return tab_counter++;
1302 struct tab *
1303 new_tab(const char *url)
1305 struct tab *tab;
1307 if ((tab = calloc(1, sizeof(*tab))) == NULL) {
1308 event_loopbreak();
1309 return NULL;
1311 tab->fd = -1;
1313 TAILQ_INIT(&tab->hist.head);
1315 TAILQ_INIT(&tab->buffer.head);
1317 tab->id = tab_new_id();
1318 switch_to_tab(tab);
1320 if (TAILQ_EMPTY(&tabshead))
1321 TAILQ_INSERT_HEAD(&tabshead, tab, tabs);
1322 else
1323 TAILQ_INSERT_TAIL(&tabshead, tab, tabs);
1325 load_url_in_tab(tab, url);
1326 return tab;
1329 static void
1330 session_new_tab_cb(const char *url)
1332 new_tab(url);
1335 static void
1336 usage(void)
1338 fprintf(stderr, "USAGE: %s [-hn] [-c config] [url]\n", getprogname());
1339 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
1342 int
1343 ui_init(int argc, char * const *argv)
1345 char path[PATH_MAX];
1346 const char *url = NEW_TAB_URL;
1347 int ch, configtest = 0, fonf = 0;
1349 if (getenv("NO_COLOR") != NULL)
1350 enable_colors = 0;
1352 strlcpy(path, getenv("HOME"), sizeof(path));
1353 strlcat(path, "/.telescope/config", sizeof(path));
1355 while ((ch = getopt(argc, argv, "c:hn")) != -1) {
1356 switch (ch) {
1357 case 'c':
1358 fonf = 1;
1359 strlcpy(path, optarg, sizeof(path));
1360 break;
1361 case 'n':
1362 configtest = 1;
1363 break;
1364 case 'h':
1365 usage();
1366 return 0;
1367 default:
1368 usage();
1369 return 1;
1372 argc -= optind;
1373 argv += optind;
1375 config_init();
1376 parseconfig(path, fonf);
1377 if (configtest){
1378 puts("config OK");
1379 exit(0);
1382 if (argc != 0)
1383 url = argv[0];
1385 setlocale(LC_ALL, "");
1387 TAILQ_INIT(&global_map.m);
1388 global_map.unhandled_input = global_key_unbound;
1390 TAILQ_INIT(&minibuffer_map.m);
1392 TAILQ_INIT(&eecmd_history.head);
1393 TAILQ_INIT(&ir_history.head);
1394 TAILQ_INIT(&lu_history.head);
1396 ministate.line.type = LINE_TEXT;
1397 ministate.vline.parent = &ministate.line;
1398 ministate.buffer.current_line = &ministate.vline;
1400 /* initialize help window */
1401 TAILQ_INIT(&helpwin.head);
1403 base_map = &global_map;
1404 current_map = &global_map;
1405 load_default_keys();
1407 initscr();
1409 if (enable_colors) {
1410 if (has_colors()) {
1411 start_color();
1412 use_default_colors();
1413 config_apply_colors();
1414 } else
1415 enable_colors = 0;
1418 raw();
1419 noecho();
1420 nonl();
1421 intrflush(stdscr, FALSE);
1423 if ((tabline = newwin(1, COLS, 0, 0)) == NULL)
1424 return 0;
1425 if ((body = newwin(LINES - 3, COLS, 1, 0)) == NULL)
1426 return 0;
1427 if ((modeline = newwin(1, COLS, LINES-2, 0)) == NULL)
1428 return 0;
1429 if ((minibuf = newwin(1, COLS, LINES-1, 0)) == NULL)
1430 return 0;
1431 if ((help = newwin(1, 1, 1, 0)) == NULL)
1432 return 0;
1434 body_lines = LINES-3;
1435 body_cols = COLS;
1437 wbkgd(body, body_face.body);
1439 update_x_offset();
1441 keypad(body, TRUE);
1442 scrollok(body, FALSE);
1444 /* non-blocking input */
1445 wtimeout(body, 0);
1447 mvwprintw(body, 0, 0, "");
1449 event_set(&stdioev, 0, EV_READ | EV_PERSIST, dispatch_stdio, NULL);
1450 event_add(&stdioev, NULL);
1452 signal_set(&winchev, SIGWINCH, handle_resize, NULL);
1453 signal_add(&winchev, NULL);
1455 load_last_session(session_new_tab_cb);
1456 if (strcmp(url, NEW_TAB_URL) || TAILQ_EMPTY(&tabshead))
1457 new_tab(url);
1459 return 1;
1462 void
1463 ui_on_tab_loaded(struct tab *tab)
1465 stop_loading_anim(tab);
1466 message("Loaded %s", tab->hist_cur->h);
1468 redraw_tabline();
1469 wrefresh(tabline);
1470 if (in_minibuffer)
1471 wrefresh(minibuf);
1472 else
1473 wrefresh(body);
1476 void
1477 ui_on_tab_refresh(struct tab *tab)
1479 wrap_page(&tab->buffer, body_cols);
1480 if (tab->flags & TAB_CURRENT) {
1481 restore_cursor(&tab->buffer);
1482 redraw_tab(tab);
1483 } else
1484 tab->flags |= TAB_URGENT;
1487 const char *
1488 ui_keyname(int k)
1490 return keyname(k);
1493 void
1494 ui_toggle_side_window(void)
1496 side_window = !side_window;
1497 if (side_window)
1498 recompute_help();
1501 * ugly hack, but otherwise the window doesn't get updated
1502 * until I call handle_resize a second time (i.e. C-l). I
1503 * will be happy to know why something like this is needed.
1505 handle_resize_nodelay(0, 0, NULL);
1506 handle_resize_nodelay(0, 0, NULL);
1509 void
1510 ui_schedule_redraw(void)
1512 handle_resize_nodelay(0, 0, NULL);
1515 void
1516 ui_require_input(struct tab *tab, int hide)
1518 /* TODO: hard-switching to another tab is ugly */
1519 switch_to_tab(tab);
1521 enter_minibuffer(ir_self_insert, ir_select, exit_minibuffer,
1522 &ir_history);
1523 strlcpy(ministate.prompt, "Input required: ",
1524 sizeof(ministate.prompt));
1525 redraw_tab(tab);
1528 void
1529 ui_yornp(const char *prompt, void (*fn)(int, unsigned int),
1530 unsigned int data)
1532 size_t len;
1534 if (in_minibuffer) {
1535 fn(0, data);
1536 return;
1539 yornp_cb = fn;
1540 yornp_data = data;
1541 enter_minibuffer(yornp_self_insert, yornp_self_insert,
1542 yornp_abort, NULL);
1544 len = sizeof(ministate.prompt);
1545 strlcpy(ministate.prompt, prompt, len);
1546 strlcat(ministate.prompt, " (y or n) ", len);
1547 redraw_tab(current_tab());
1550 void
1551 ui_read(const char *prompt, void (*fn)(const char*, unsigned int),
1552 unsigned int data)
1554 size_t len;
1556 if (in_minibuffer)
1557 return;
1559 read_cb = fn;
1560 read_data = data;
1561 enter_minibuffer(read_self_insert, read_select, read_abort,
1562 &read_history);
1564 len = sizeof(ministate.prompt);
1565 strlcpy(ministate.prompt, prompt, len);
1566 strlcat(ministate.prompt, ": ", len);
1567 redraw_tab(current_tab());
1570 void
1571 ui_end(void)
1573 endwin();