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 p", cmd_previous_heading);
181 global_set_key("C-c n", cmd_next_heading);
183 global_set_key(">", cmd_load_url);
184 global_set_key("C-x C-f", cmd_load_url);
185 global_set_key("C-x M-f", cmd_load_current_url);
187 global_set_key("C-x t 0", cmd_tab_close);
188 global_set_key("C-x t 1", cmd_tab_close_other);
189 global_set_key("C-x t 2", cmd_tab_new);
190 global_set_key("C-x t o", cmd_tab_next);
191 global_set_key("C-x t O", cmd_tab_previous);
192 global_set_key("C-x t m", cmd_tab_move);
193 global_set_key("C-x t M", cmd_tab_move_to);
195 global_set_key("C-M-b", cmd_previous_page);
196 global_set_key("C-M-f", cmd_next_page);
198 global_set_key("<f7> a", cmd_bookmark_page);
199 global_set_key("<f7> <f7>", cmd_list_bookmarks);
201 /* vi/vi-like */
202 global_set_key("k", cmd_previous_line);
203 global_set_key("j", cmd_next_line);
204 global_set_key("l", cmd_forward_char);
205 global_set_key("h", cmd_backward_char);
206 global_set_key("{", cmd_backward_paragraph);
207 global_set_key("}", cmd_forward_paragraph);
208 global_set_key("^", cmd_move_beginning_of_line);
209 global_set_key("$", cmd_move_end_of_line);
211 global_set_key("K", cmd_scroll_line_up);
212 global_set_key("J", cmd_scroll_line_down);
214 global_set_key("g g", cmd_beginning_of_buffer);
215 global_set_key("G", cmd_end_of_buffer);
217 global_set_key("g D", cmd_tab_close);
218 global_set_key("g N", cmd_tab_new);
219 global_set_key("g t", cmd_tab_next);
220 global_set_key("g T", cmd_tab_previous);
221 global_set_key("g M-t", cmd_tab_move);
222 global_set_key("g M-T", cmd_tab_move_to);
224 global_set_key("H", cmd_previous_page);
225 global_set_key("L", cmd_next_page);
227 /* tmp */
228 global_set_key("q", cmd_kill_telescope);
230 global_set_key("esc", cmd_clear_minibuf);
232 global_set_key(":", cmd_execute_extended_command);
234 /* cua */
235 global_set_key("<up>", cmd_previous_line);
236 global_set_key("<down>", cmd_next_line);
237 global_set_key("<right>", cmd_forward_char);
238 global_set_key("<left>", cmd_backward_char);
239 global_set_key("<prior>", cmd_scroll_up);
240 global_set_key("<next>", cmd_scroll_down);
242 global_set_key("M-<left>", cmd_previous_page);
243 global_set_key("M-<right>", cmd_next_page);
245 /* "ncurses standard" */
246 global_set_key("C-l", cmd_redraw);
248 /* global */
249 global_set_key("<f1>", cmd_toggle_help);
250 global_set_key("C-m", cmd_push_button);
251 global_set_key("M-enter", cmd_push_button_new_tab);
252 global_set_key("M-tab", cmd_previous_button);
253 global_set_key("backtab", cmd_previous_button);
254 global_set_key("tab", cmd_next_button);
256 /* === minibuffer map === */
257 minibuffer_set_key("ret", cmd_mini_complete_and_exit);
258 minibuffer_set_key("C-g", cmd_mini_abort);
259 minibuffer_set_key("esc", cmd_mini_abort);
260 minibuffer_set_key("C-d", cmd_mini_delete_char);
261 minibuffer_set_key("del", cmd_mini_delete_backward_char);
262 minibuffer_set_key("backspace", cmd_mini_delete_backward_char);
263 minibuffer_set_key("C-h", cmd_mini_delete_backward_char);
265 minibuffer_set_key("C-b", cmd_backward_char);
266 minibuffer_set_key("C-f", cmd_forward_char);
267 minibuffer_set_key("<left>", cmd_backward_char);
268 minibuffer_set_key("<right>", cmd_forward_char);
269 minibuffer_set_key("C-e", cmd_move_end_of_line);
270 minibuffer_set_key("C-a", cmd_move_beginning_of_line);
271 minibuffer_set_key("<end>", cmd_move_end_of_line);
272 minibuffer_set_key("<home>", cmd_move_beginning_of_line);
273 minibuffer_set_key("C-k", cmd_mini_kill_line);
275 minibuffer_set_key("M-p", cmd_mini_previous_history_element);
276 minibuffer_set_key("M-n", cmd_mini_next_history_element);
277 minibuffer_set_key("<up>", cmd_mini_previous_history_element);
278 minibuffer_set_key("<down>", cmd_mini_next_history_element);
281 void
282 save_excursion(struct excursion *place, struct buffer *buffer)
284 place->curs_x = buffer->curs_x;
285 place->curs_y = buffer->curs_y;
286 place->line_off = buffer->line_off;
287 place->current_line = buffer->current_line;
288 place->cpoff = buffer->cpoff;
291 void
292 restore_excursion(struct excursion *place, struct buffer *buffer)
294 buffer->curs_x = place->curs_x;
295 buffer->curs_y = place->curs_y;
296 buffer->line_off = place->line_off;
297 buffer->current_line = place->current_line;
298 buffer->cpoff = place->cpoff;
301 void
302 restore_cursor(struct buffer *buffer)
304 struct vline *vl;
305 const char *prfx;
307 vl = buffer->current_line;
308 if (vl == NULL || vl->line == NULL)
309 buffer->curs_x = buffer->cpoff = 0;
310 else
311 buffer->curs_x = utf8_snwidth(vl->line, buffer->cpoff);
313 buffer->curs_x += x_offset;
315 if (vl != NULL) {
316 prfx = line_prefixes[vl->parent->type].prfx1;
317 buffer->curs_x += utf8_swidth(prfx);
321 static void
322 global_key_unbound(void)
324 message("%s is undefined", keybuf);
327 static void
328 minibuffer_hist_save_entry(void)
330 struct hist *hist;
332 if (ministate.history == NULL)
333 return;
335 if ((hist = calloc(1, sizeof(*hist))) == NULL)
336 abort();
338 strlcpy(hist->h, ministate.buf, sizeof(hist->h));
340 if (TAILQ_EMPTY(&ministate.history->head))
341 TAILQ_INSERT_HEAD(&ministate.history->head, hist, entries);
342 else
343 TAILQ_INSERT_TAIL(&ministate.history->head, hist, entries);
344 ministate.history->len++;
347 /*
348 * taint the minibuffer cache: if we're currently showing a history
349 * element, copy that to the current buf and reset the "history
350 * navigation" thing.
351 */
352 void
353 minibuffer_taint_hist(void)
355 if (ministate.hist_cur == NULL)
356 return;
358 strlcpy(ministate.buf, ministate.hist_cur->h, sizeof(ministate.buf));
359 ministate.hist_cur = NULL;
362 static void
363 minibuffer_self_insert(void)
365 char *c, tmp[5] = {0};
366 size_t len;
368 minibuffer_taint_hist();
370 if (thiskey.cp == 0)
371 return;
373 len = utf8_encode(thiskey.cp, tmp);
374 c = utf8_nth(ministate.buffer.current_line->line, ministate.buffer.cpoff);
375 if (c + len > ministate.buf + sizeof(ministate.buf) - 1)
376 return;
378 memmove(c + len, c, strlen(c)+1);
379 memcpy(c, tmp, len);
380 ministate.buffer.cpoff++;
383 void
384 eecmd_self_insert(void)
386 if (thiskey.meta || unicode_isspace(thiskey.cp) ||
387 !unicode_isgraph(thiskey.cp)) {
388 global_key_unbound();
389 return;
392 minibuffer_self_insert();
395 void
396 eecmd_select(void)
398 struct cmd *cmd;
400 for (cmd = cmds; cmd->cmd != NULL; ++cmd) {
401 if (!strcmp(cmd->cmd, ministate.buf)) {
402 exit_minibuffer();
403 minibuffer_hist_save_entry();
404 cmd->fn(current_buffer());
405 return;
409 message("No match");
412 void
413 ir_self_insert(void)
415 minibuffer_self_insert();
418 void
419 ir_select(void)
421 char buf[1025] = {0};
422 struct phos_uri uri;
423 struct tab *tab;
425 tab = current_tab();
427 exit_minibuffer();
428 minibuffer_hist_save_entry();
430 /* a bit ugly but... */
431 memcpy(&uri, &tab->uri, sizeof(tab->uri));
432 phos_uri_set_query(&uri, ministate.buf);
433 phos_serialize_uri(&uri, buf, sizeof(buf));
434 load_url_in_tab(tab, buf);
437 void
438 lu_self_insert(void)
440 if (thiskey.meta || unicode_isspace(thiskey.key) ||
441 !unicode_isgraph(thiskey.key)) {
442 global_key_unbound();
443 return;
446 minibuffer_self_insert();
449 void
450 lu_select(void)
452 exit_minibuffer();
453 minibuffer_hist_save_entry();
454 load_url_in_tab(current_tab(), ministate.buf);
457 void
458 bp_select(void)
460 exit_minibuffer();
461 if (*ministate.buf != '\0')
462 add_to_bookmarks(ministate.buf);
463 else
464 message("Abort.");
467 static void
468 yornp_self_insert(void)
470 if (thiskey.key != 'y' && thiskey.key != 'n') {
471 message("Please answer y or n");
472 return;
475 exit_minibuffer();
476 yornp_cb(thiskey.key == 'y', yornp_data);
479 static void
480 yornp_abort(void)
482 exit_minibuffer();
483 yornp_cb(0, yornp_data);
486 static void
487 read_self_insert(void)
489 if (thiskey.meta || !unicode_isgraph(thiskey.cp)) {
490 global_key_unbound();
491 return;
494 minibuffer_self_insert();
497 static void
498 read_abort(void)
500 exit_minibuffer();
501 read_cb(NULL, read_data);
504 static void
505 read_select(void)
507 exit_minibuffer();
508 minibuffer_hist_save_entry();
509 read_cb(ministate.buf, read_data);
512 static struct vline *
513 nth_line(struct buffer *buffer, size_t n)
515 struct vline *vl;
516 size_t i;
518 i = 0;
519 TAILQ_FOREACH(vl, &buffer->head, vlines) {
520 if (i == n)
521 return vl;
522 i++;
525 /* unreachable */
526 abort();
529 struct tab *
530 current_tab(void)
532 struct tab *t;
534 TAILQ_FOREACH(t, &tabshead, tabs) {
535 if (t->flags & TAB_CURRENT)
536 return t;
539 /* unreachable */
540 abort();
543 struct buffer *
544 current_buffer(void)
546 if (in_minibuffer)
547 return &ministate.buffer;
548 return &current_tab()->buffer;
551 static int
552 readkey(void)
554 uint32_t state = 0;
556 if ((thiskey.key = wgetch(body)) == ERR)
557 return 0;
559 thiskey.meta = thiskey.key == 27;
560 if (thiskey.meta) {
561 thiskey.key = wgetch(body);
562 if (thiskey.key == ERR || thiskey.key == 27) {
563 thiskey.meta = 0;
564 thiskey.key = 27;
568 thiskey.cp = 0;
569 if ((unsigned int)thiskey.key < UINT8_MAX) {
570 while (1) {
571 if (!utf8_decode(&state, &thiskey.cp, (uint8_t)thiskey.key))
572 break;
573 if ((thiskey.key = wgetch(body)) == ERR) {
574 message("Error decoding user input");
575 return 0;
580 return 1;
583 static void
584 dispatch_stdio(int fd, short ev, void *d)
586 struct keymap *k;
587 const char *keyname;
588 char tmp[5] = {0};
590 if (!readkey())
591 return;
593 if (keybuf[0] != '\0')
594 strlcat(keybuf, " ", sizeof(keybuf));
595 if (thiskey.meta)
596 strlcat(keybuf, "M-", sizeof(keybuf));
597 if (thiskey.cp != 0) {
598 utf8_encode(thiskey.cp, tmp);
599 strlcat(keybuf, tmp, sizeof(keybuf));
600 } else {
601 if ((keyname = unkbd(thiskey.key)) != NULL)
602 strlcat(keybuf, keyname, sizeof(keybuf));
603 else {
604 tmp[0] = thiskey.key;
605 strlcat(keybuf, tmp, sizeof(keybuf));
609 TAILQ_FOREACH(k, &current_map->m, keymaps) {
610 if (k->meta == thiskey.meta &&
611 k->key == thiskey.key) {
612 if (k->fn == NULL)
613 current_map = &k->map;
614 else {
615 current_map = base_map;
616 strlcpy(keybuf, "", sizeof(keybuf));
617 k->fn(current_buffer());
619 goto done;
623 if (current_map->unhandled_input != NULL)
624 current_map->unhandled_input();
625 else
626 global_key_unbound();
628 strlcpy(keybuf, "", sizeof(keybuf));
629 current_map = base_map;
631 done:
632 if (side_window)
633 recompute_help();
635 redraw_tab(current_tab());
638 static void
639 handle_clear_minibuf(int fd, short ev, void *d)
641 free(ministate.curmesg);
642 ministate.curmesg = NULL;
644 redraw_minibuffer();
645 if (in_minibuffer) {
646 wrefresh(body);
647 wrefresh(minibuf);
648 } else {
649 wrefresh(minibuf);
650 wrefresh(body);
654 static void
655 handle_resize(int sig, short ev, void *d)
657 if (event_pending(&resizeev, EV_TIMEOUT, NULL)) {
658 event_del(&resizeev);
660 evtimer_set(&resizeev, handle_resize_nodelay, NULL);
661 evtimer_add(&resizeev, &resize_timer);
664 static void
665 handle_resize_nodelay(int s, short ev, void *d)
667 struct tab *tab;
669 endwin();
670 refresh();
671 clear();
673 /* move and resize the windows, in reverse order! */
675 mvwin(minibuf, LINES-1, 0);
676 wresize(minibuf, 1, COLS);
678 mvwin(modeline, LINES-2, 0);
679 wresize(modeline, 1, COLS);
681 body_lines = LINES-3;
682 body_cols = COLS;
684 if (side_window) {
685 help_cols = 0.3 * COLS;
686 help_lines = LINES-3;
687 mvwin(help, 1, 0);
688 wresize(help, help_lines, help_cols);
690 wrap_page(&helpwin, help_cols);
692 body_cols = COLS - help_cols - 1;
693 mvwin(body, 1, help_cols);
694 } else
695 mvwin(body, 1, 0);
697 update_x_offset();
698 wresize(body, body_lines, body_cols);
700 wresize(tabline, 1, COLS);
702 tab = current_tab();
704 wrap_page(&tab->buffer, body_cols);
705 redraw_tab(tab);
708 static int
709 wrap_page(struct buffer *buffer, int width)
711 struct line *l;
712 const struct line *orig;
713 struct vline *vl;
714 int pre_width;
715 const char *prfx;
717 orig = buffer->current_line == NULL
718 ? NULL
719 : buffer->current_line->parent;
720 buffer->current_line = NULL;
722 buffer->force_redraw = 1;
723 buffer->curs_y = 0;
724 buffer->line_off = 0;
726 empty_vlist(buffer);
728 TAILQ_FOREACH(l, &buffer->page.head, lines) {
729 prfx = line_prefixes[l->type].prfx1;
730 switch (l->type) {
731 case LINE_TEXT:
732 case LINE_LINK:
733 case LINE_TITLE_1:
734 case LINE_TITLE_2:
735 case LINE_TITLE_3:
736 case LINE_ITEM:
737 case LINE_QUOTE:
738 case LINE_PRE_START:
739 case LINE_PRE_END:
740 wrap_text(buffer, prfx, l, MIN(fill_column, width));
741 break;
742 case LINE_PRE_CONTENT:
743 if (olivetti_mode)
744 pre_width = MIN(fill_column, width);
745 else
746 pre_width = width;
747 hardwrap_text(buffer, l, pre_width);
748 break;
751 if (orig == l && buffer->current_line == NULL) {
752 buffer->line_off = buffer->line_max-1;
753 buffer->current_line = TAILQ_LAST(&buffer->head, vhead);
755 while (1) {
756 vl = TAILQ_PREV(buffer->current_line, vhead, vlines);
757 if (vl == NULL || vl->parent != orig)
758 break;
759 buffer->current_line = vl;
760 buffer->line_off--;
765 if (buffer->current_line == NULL)
766 buffer->current_line = TAILQ_FIRST(&buffer->head);
768 return 1;
771 static void
772 print_vline(int off, int width, WINDOW *window, struct vline *vl)
774 const char *text;
775 const char *prfx;
776 struct line_face *f;
777 int i, left, x, y;
779 f = &line_faces[vl->parent->type];
781 /* unused, set by getyx */
782 (void)y;
784 if (!vl->flags)
785 prfx = line_prefixes[vl->parent->type].prfx1;
786 else
787 prfx = line_prefixes[vl->parent->type].prfx2;
789 text = vl->line;
790 if (text == NULL)
791 text = "";
793 wattr_on(window, body_face.left, NULL);
794 for (i = 0; i < off; i++)
795 waddch(window, ' ');
796 wattr_off(window, body_face.left, NULL);
798 wattr_on(window, f->prefix, NULL);
799 wprintw(window, "%s", prfx);
800 wattr_off(window, f->prefix, NULL);
802 wattr_on(window, f->text, NULL);
803 wprintw(window, "%s", text);
804 wattr_off(window, f->text, NULL);
806 getyx(window, y, x);
808 left = width - x;
810 wattr_on(window, f->trail, NULL);
811 for (i = 0; i < left - off - 1; ++i)
812 waddch(window, ' ');
813 wattr_off(window, f->trail, NULL);
815 wattr_on(window, body_face.right, NULL);
816 for (i = 0; i < off; i++)
817 waddch(window, ' ');
818 wattr_off(window, body_face.right, NULL);
822 static void
823 redraw_tabline(void)
825 struct tab *tab;
826 size_t toskip, ots, tabwidth, space, x;
827 int current, y, truncated;
828 const char *title;
829 char buf[25];
831 x = 0;
833 /* unused, but setted by a getyx */
834 (void)y;
836 tabwidth = sizeof(buf)+1;
837 space = COLS-2;
839 toskip = 0;
840 TAILQ_FOREACH(tab, &tabshead, tabs) {
841 toskip++;
842 if (tab->flags & TAB_CURRENT)
843 break;
846 if (toskip * tabwidth < space)
847 toskip = 0;
848 else {
849 ots = toskip;
850 toskip--;
851 while (toskip != 0 &&
852 (ots - toskip+1) * tabwidth < space)
853 toskip--;
856 werase(tabline);
857 wattr_on(tabline, tab_face.background, NULL);
858 wprintw(tabline, toskip == 0 ? " " : "<");
859 wattr_off(tabline, tab_face.background, NULL);
861 truncated = 0;
862 TAILQ_FOREACH(tab, &tabshead, tabs) {
863 if (truncated)
864 break;
865 if (toskip != 0) {
866 toskip--;
867 continue;
870 getyx(tabline, y, x);
871 if (x + sizeof(buf)+2 >= (size_t)COLS)
872 truncated = 1;
874 current = tab->flags & TAB_CURRENT;
876 if (*(title = tab->buffer.page.title) == '\0')
877 title = tab->hist_cur->h;
879 if (tab->flags & TAB_URGENT)
880 strlcpy(buf, "!", sizeof(buf));
881 else
882 strlcpy(buf, " ", sizeof(buf));
884 if (strlcat(buf, title, sizeof(buf)) >= sizeof(buf)) {
885 /* truncation happens */
886 strlcpy(&buf[sizeof(buf)-4], "...", 4);
887 } else {
888 /* pad with spaces */
889 while (strlcat(buf, " ", sizeof(buf)) < sizeof(buf))
890 /* nop */ ;
893 if (current)
894 wattr_on(tabline, tab_face.current, NULL);
895 else
896 wattr_on(tabline, tab_face.tab, NULL);
898 wprintw(tabline, "%s", buf);
899 if (TAILQ_NEXT(tab, tabs) != NULL)
900 wprintw(tabline, " ");
902 if (current)
903 wattr_off(tabline, tab_face.current, NULL);
904 else
905 wattr_off(tabline, tab_face.tab, NULL);
908 wattr_on(tabline, tab_face.background, NULL);
909 for (; x < (size_t)COLS; ++x)
910 waddch(tabline, ' ');
911 if (truncated)
912 mvwprintw(tabline, 0, COLS-1, ">");
913 wattr_off(tabline, tab_face.background, NULL);
916 static void
917 redraw_window(WINDOW *win, int height, int width, struct buffer *buffer)
919 struct vline *vl;
920 int l;
922 /*
923 * Don't bother redraw the body if nothing changed. Cursor
924 * movements count as "nothing changed" if it hasn't produced
925 * a scroll. Ensure that wmove is called though!
926 */
927 if (!buffer->force_redraw &&
928 buffer->last_line_off == buffer->line_off)
929 goto end;
931 werase(win);
933 buffer->line_off = MIN(buffer->line_max-1, buffer->line_off);
934 buffer->force_redraw = 0;
935 buffer->last_line_off = buffer->line_off;
937 if (TAILQ_EMPTY(&buffer->head))
938 goto end;
940 l = 0;
941 vl = nth_line(buffer, buffer->line_off);
942 for (; vl != NULL; vl = TAILQ_NEXT(vl, vlines)) {
943 wmove(win, l, 0);
944 print_vline(x_offset, width, win, vl);
945 l++;
946 if (l == height)
947 break;
950 end:
951 wmove(win, buffer->curs_y, buffer->curs_x);
954 static void
955 redraw_help(void)
957 redraw_window(help, help_lines, help_cols, &helpwin);
960 static void
961 redraw_body(struct tab *tab)
963 static struct tab *last_tab;
965 if (last_tab != tab)
966 tab->buffer.force_redraw =1;
967 last_tab = tab;
969 redraw_window(body, body_lines, body_cols, &tab->buffer);
972 static inline char
973 trust_status_char(enum trust_state ts)
975 switch (ts) {
976 case TS_UNKNOWN: return 'u';
977 case TS_UNTRUSTED: return '!';
978 case TS_TRUSTED: return 'v';
979 case TS_VERIFIED: return 'V';
980 default: return 'X';
984 static void
985 redraw_modeline(struct tab *tab)
987 double pct;
988 int x, y, max_x, max_y;
989 const char *mode = tab->buffer.page.name;
990 const char *spin = "-\\|/";
992 werase(modeline);
993 wattr_on(modeline, modeline_face.background, NULL);
994 wmove(modeline, 0, 0);
996 wprintw(modeline, "-%c%c %s ",
997 spin[tab->loading_anim_step],
998 trust_status_char(tab->trust),
999 mode == NULL ? "(none)" : mode);
1001 pct = (tab->buffer.line_off + tab->buffer.curs_y) * 100.0 / tab->buffer.line_max;
1003 if (tab->buffer.line_max <= (size_t)body_lines)
1004 wprintw(modeline, "All ");
1005 else if (tab->buffer.line_off == 0)
1006 wprintw(modeline, "Top ");
1007 else if (tab->buffer.line_off + body_lines >= tab->buffer.line_max)
1008 wprintw(modeline, "Bottom ");
1009 else
1010 wprintw(modeline, "%.0f%% ", pct);
1012 wprintw(modeline, "%d/%d %s ",
1013 tab->buffer.line_off + tab->buffer.curs_y,
1014 tab->buffer.line_max,
1015 tab->hist_cur->h);
1017 getyx(modeline, y, x);
1018 getmaxyx(modeline, max_y, max_x);
1020 (void)y;
1021 (void)max_y;
1023 for (; x < max_x; ++x)
1024 waddstr(modeline, "-");
1026 wattr_off(modeline, modeline_face.background, NULL);
1029 static void
1030 redraw_minibuffer(void)
1032 struct tab *tab;
1033 size_t off_y, off_x = 0;
1034 char *start = NULL, *c = NULL;
1036 /* unused, but set by getyx */
1037 (void)off_y;
1039 wattr_on(minibuf, minibuffer_face.background, NULL);
1040 werase(minibuf);
1042 if (in_minibuffer) {
1043 mvwprintw(minibuf, 0, 0, "%s", ministate.prompt);
1044 if (ministate.hist_cur != NULL)
1045 wprintw(minibuf, "(%zu/%zu) ",
1046 ministate.hist_off + 1,
1047 ministate.history->len);
1049 getyx(minibuf, off_y, off_x);
1051 start = ministate.hist_cur != NULL
1052 ? ministate.hist_cur->h
1053 : ministate.buf;
1054 c = utf8_nth(ministate.buffer.current_line->line,
1055 ministate.buffer.cpoff);
1056 while (utf8_swidth_between(start, c) > (size_t)COLS/2) {
1057 start = utf8_next_cp(start);
1060 waddstr(minibuf, start);
1063 if (ministate.curmesg != NULL)
1064 wprintw(minibuf, in_minibuffer ? " [%s]" : "%s",
1065 ministate.curmesg);
1067 if (!in_minibuffer && ministate.curmesg == NULL)
1068 waddstr(minibuf, keybuf);
1070 /* If nothing else, show the URL at point */
1071 if (!in_minibuffer && ministate.curmesg == NULL && *keybuf == '\0') {
1072 tab = current_tab();
1073 if (tab->buffer.current_line != NULL &&
1074 tab->buffer.current_line->parent->type == LINE_LINK)
1075 waddstr(minibuf, tab->buffer.current_line->parent->alt);
1078 if (in_minibuffer)
1079 wmove(minibuf, 0, off_x + utf8_swidth_between(start, c));
1081 wattr_off(minibuf, minibuffer_face.background, NULL);
1084 static void
1085 redraw_tab(struct tab *tab)
1087 if (side_window) {
1088 redraw_help();
1089 wnoutrefresh(help);
1092 restore_cursor(&tab->buffer);
1094 redraw_tabline();
1095 redraw_body(tab);
1096 redraw_modeline(tab);
1097 redraw_minibuffer();
1099 wnoutrefresh(tabline);
1100 wnoutrefresh(modeline);
1102 if (in_minibuffer) {
1103 wnoutrefresh(body);
1104 wnoutrefresh(minibuf);
1105 } else {
1106 wnoutrefresh(minibuf);
1107 wnoutrefresh(body);
1110 doupdate();
1113 static void
1114 emit_help_item(char *prfx, void *fn)
1116 struct line *l;
1117 struct cmd *cmd;
1119 for (cmd = cmds; cmd->cmd != NULL; ++cmd) {
1120 if (fn == cmd->fn)
1121 break;
1123 assert(cmd != NULL);
1125 if ((l = calloc(1, sizeof(*l))) == NULL)
1126 abort();
1128 l->type = LINE_TEXT;
1129 l->alt = NULL;
1131 asprintf(&l->line, "%s %s", prfx, cmd->cmd);
1133 if (TAILQ_EMPTY(&helpwin.page.head))
1134 TAILQ_INSERT_HEAD(&helpwin.page.head, l, lines);
1135 else
1136 TAILQ_INSERT_TAIL(&helpwin.page.head, l, lines);
1139 static void
1140 rec_compute_help(struct kmap *keymap, char *prfx, size_t len)
1142 struct keymap *k;
1143 char p[32];
1144 const char *kn;
1146 TAILQ_FOREACH(k, &keymap->m, keymaps) {
1147 strlcpy(p, prfx, sizeof(p));
1148 if (*p != '\0')
1149 strlcat(p, " ", sizeof(p));
1150 if (k->meta)
1151 strlcat(p, "M-", sizeof(p));
1152 if ((kn = unkbd(k->key)) != NULL)
1153 strlcat(p, kn, sizeof(p));
1154 else
1155 strlcat(p, keyname(k->key), sizeof(p));
1157 if (k->fn == NULL)
1158 rec_compute_help(&k->map, p, sizeof(p));
1159 else
1160 emit_help_item(p, k->fn);
1164 static void
1165 recompute_help(void)
1167 char p[32] = { 0 };
1169 empty_vlist(&helpwin);
1170 empty_linelist(&helpwin);
1171 rec_compute_help(current_map, p, sizeof(p));
1172 wrap_page(&helpwin, help_cols);
1175 void
1176 vmessage(const char *fmt, va_list ap)
1178 if (evtimer_pending(&clminibufev, NULL))
1179 evtimer_del(&clminibufev);
1181 free(ministate.curmesg);
1182 ministate.curmesg = NULL;
1184 if (fmt != NULL) {
1185 evtimer_set(&clminibufev, handle_clear_minibuf, NULL);
1186 evtimer_add(&clminibufev, &clminibufev_timer);
1188 /* TODO: what to do if the allocation fails here? */
1189 if (vasprintf(&ministate.curmesg, fmt, ap) == -1)
1190 ministate.curmesg = NULL;
1193 redraw_minibuffer();
1194 if (in_minibuffer) {
1195 wrefresh(body);
1196 wrefresh(minibuf);
1197 } else {
1198 wrefresh(minibuf);
1199 wrefresh(body);
1203 void
1204 message(const char *fmt, ...)
1206 va_list ap;
1208 va_start(ap, fmt);
1209 vmessage(fmt, ap);
1210 va_end(ap);
1213 void
1214 start_loading_anim(struct tab *tab)
1216 if (tab->loading_anim)
1217 return;
1218 tab->loading_anim = 1;
1219 evtimer_set(&tab->loadingev, update_loading_anim, tab);
1220 evtimer_add(&tab->loadingev, &loadingev_timer);
1223 static void
1224 update_loading_anim(int fd, short ev, void *d)
1226 struct tab *tab = d;
1228 tab->loading_anim_step = (tab->loading_anim_step+1)%4;
1230 if (tab->flags & TAB_CURRENT) {
1231 redraw_modeline(tab);
1232 wrefresh(modeline);
1233 wrefresh(body);
1234 if (in_minibuffer)
1235 wrefresh(minibuf);
1238 evtimer_add(&tab->loadingev, &loadingev_timer);
1241 static void
1242 stop_loading_anim(struct tab *tab)
1244 if (!tab->loading_anim)
1245 return;
1246 evtimer_del(&tab->loadingev);
1247 tab->loading_anim = 0;
1248 tab->loading_anim_step = 0;
1250 if (!(tab->flags & TAB_CURRENT))
1251 return;
1253 redraw_modeline(tab);
1255 wrefresh(modeline);
1256 wrefresh(body);
1257 if (in_minibuffer)
1258 wrefresh(minibuf);
1261 void
1262 load_url_in_tab(struct tab *tab, const char *url)
1264 message("Loading %s...", url);
1265 start_loading_anim(tab);
1266 load_url(tab, url);
1268 tab->buffer.curs_x = 0;
1269 tab->buffer.curs_y = 0;
1270 redraw_tab(tab);
1273 void
1274 enter_minibuffer(void (*self_insert_fn)(void), void (*donefn)(void),
1275 void (*abortfn)(void), struct histhead *hist)
1277 in_minibuffer = 1;
1278 base_map = &minibuffer_map;
1279 current_map = &minibuffer_map;
1281 base_map->unhandled_input = self_insert_fn;
1283 ministate.donefn = donefn;
1284 ministate.abortfn = abortfn;
1285 memset(ministate.buf, 0, sizeof(ministate.buf));
1286 ministate.buffer.current_line = &ministate.vline;
1287 ministate.buffer.current_line->line = ministate.buf;
1288 ministate.buffer.cpoff = 0;
1289 strlcpy(ministate.buf, "", sizeof(ministate.prompt));
1291 ministate.history = hist;
1292 ministate.hist_cur = NULL;
1293 ministate.hist_off = 0;
1296 void
1297 exit_minibuffer(void)
1299 werase(minibuf);
1301 in_minibuffer = 0;
1302 base_map = &global_map;
1303 current_map = &global_map;
1306 void
1307 switch_to_tab(struct tab *tab)
1309 struct tab *t;
1311 TAILQ_FOREACH(t, &tabshead, tabs) {
1312 t->flags &= ~TAB_CURRENT;
1315 tab->flags |= TAB_CURRENT;
1316 tab->flags &= ~TAB_URGENT;
1319 unsigned int
1320 tab_new_id(void)
1322 return tab_counter++;
1325 struct tab *
1326 new_tab(const char *url)
1328 struct tab *tab;
1330 if ((tab = calloc(1, sizeof(*tab))) == NULL) {
1331 event_loopbreak();
1332 return NULL;
1334 tab->fd = -1;
1336 TAILQ_INIT(&tab->hist.head);
1338 TAILQ_INIT(&tab->buffer.head);
1340 tab->id = tab_new_id();
1341 switch_to_tab(tab);
1343 if (TAILQ_EMPTY(&tabshead))
1344 TAILQ_INSERT_HEAD(&tabshead, tab, tabs);
1345 else
1346 TAILQ_INSERT_TAIL(&tabshead, tab, tabs);
1348 load_url_in_tab(tab, url);
1349 return tab;
1352 static void
1353 session_new_tab_cb(const char *url)
1355 new_tab(url);
1358 static void
1359 usage(void)
1361 fprintf(stderr, "USAGE: %s [-hn] [-c config] [url]\n", getprogname());
1362 fprintf(stderr, "version: " PACKAGE " " VERSION "\n");
1365 int
1366 ui_init(int argc, char * const *argv)
1368 char path[PATH_MAX];
1369 const char *url = NEW_TAB_URL;
1370 int ch, configtest = 0, fonf = 0;
1372 if (getenv("NO_COLOR") != NULL)
1373 enable_colors = 0;
1375 strlcpy(path, getenv("HOME"), sizeof(path));
1376 strlcat(path, "/.telescope/config", sizeof(path));
1378 while ((ch = getopt(argc, argv, "c:hn")) != -1) {
1379 switch (ch) {
1380 case 'c':
1381 fonf = 1;
1382 strlcpy(path, optarg, sizeof(path));
1383 break;
1384 case 'n':
1385 configtest = 1;
1386 break;
1387 case 'h':
1388 usage();
1389 return 0;
1390 default:
1391 usage();
1392 return 1;
1395 argc -= optind;
1396 argv += optind;
1398 config_init();
1399 parseconfig(path, fonf);
1400 if (configtest){
1401 puts("config OK");
1402 exit(0);
1405 if (argc != 0)
1406 url = argv[0];
1408 setlocale(LC_ALL, "");
1410 TAILQ_INIT(&global_map.m);
1411 global_map.unhandled_input = global_key_unbound;
1413 TAILQ_INIT(&minibuffer_map.m);
1415 TAILQ_INIT(&eecmd_history.head);
1416 TAILQ_INIT(&ir_history.head);
1417 TAILQ_INIT(&lu_history.head);
1419 ministate.line.type = LINE_TEXT;
1420 ministate.vline.parent = &ministate.line;
1421 ministate.buffer.current_line = &ministate.vline;
1423 /* initialize help window */
1424 TAILQ_INIT(&helpwin.head);
1426 base_map = &global_map;
1427 current_map = &global_map;
1428 load_default_keys();
1430 initscr();
1432 if (enable_colors) {
1433 if (has_colors()) {
1434 start_color();
1435 use_default_colors();
1436 } else
1437 enable_colors = 0;
1440 config_apply_style();
1442 raw();
1443 noecho();
1444 nonl();
1445 intrflush(stdscr, FALSE);
1447 if ((tabline = newwin(1, COLS, 0, 0)) == NULL)
1448 return 0;
1449 if ((body = newwin(LINES - 3, COLS, 1, 0)) == NULL)
1450 return 0;
1451 if ((modeline = newwin(1, COLS, LINES-2, 0)) == NULL)
1452 return 0;
1453 if ((minibuf = newwin(1, COLS, LINES-1, 0)) == NULL)
1454 return 0;
1455 if ((help = newwin(1, 1, 1, 0)) == NULL)
1456 return 0;
1458 body_lines = LINES-3;
1459 body_cols = COLS;
1461 wbkgd(body, body_face.body);
1463 update_x_offset();
1465 keypad(body, TRUE);
1466 scrollok(body, FALSE);
1468 /* non-blocking input */
1469 wtimeout(body, 0);
1471 mvwprintw(body, 0, 0, "");
1473 event_set(&stdioev, 0, EV_READ | EV_PERSIST, dispatch_stdio, NULL);
1474 event_add(&stdioev, NULL);
1476 signal_set(&winchev, SIGWINCH, handle_resize, NULL);
1477 signal_add(&winchev, NULL);
1479 load_last_session(session_new_tab_cb);
1480 if (strcmp(url, NEW_TAB_URL) || TAILQ_EMPTY(&tabshead))
1481 new_tab(url);
1483 return 1;
1486 void
1487 ui_on_tab_loaded(struct tab *tab)
1489 stop_loading_anim(tab);
1490 message("Loaded %s", tab->hist_cur->h);
1492 redraw_tabline();
1493 wrefresh(tabline);
1494 if (in_minibuffer)
1495 wrefresh(minibuf);
1496 else
1497 wrefresh(body);
1500 void
1501 ui_on_tab_refresh(struct tab *tab)
1503 wrap_page(&tab->buffer, body_cols);
1504 if (tab->flags & TAB_CURRENT) {
1505 restore_cursor(&tab->buffer);
1506 redraw_tab(tab);
1507 } else
1508 tab->flags |= TAB_URGENT;
1511 const char *
1512 ui_keyname(int k)
1514 return keyname(k);
1517 void
1518 ui_toggle_side_window(void)
1520 side_window = !side_window;
1521 if (side_window)
1522 recompute_help();
1525 * ugly hack, but otherwise the window doesn't get updated
1526 * until I call handle_resize a second time (i.e. C-l). I
1527 * will be happy to know why something like this is needed.
1529 handle_resize_nodelay(0, 0, NULL);
1530 handle_resize_nodelay(0, 0, NULL);
1533 void
1534 ui_schedule_redraw(void)
1536 handle_resize_nodelay(0, 0, NULL);
1539 void
1540 ui_require_input(struct tab *tab, int hide)
1542 /* TODO: hard-switching to another tab is ugly */
1543 switch_to_tab(tab);
1545 enter_minibuffer(ir_self_insert, ir_select, exit_minibuffer,
1546 &ir_history);
1547 strlcpy(ministate.prompt, "Input required: ",
1548 sizeof(ministate.prompt));
1549 redraw_tab(tab);
1552 void
1553 ui_yornp(const char *prompt, void (*fn)(int, unsigned int),
1554 unsigned int data)
1556 size_t len;
1558 if (in_minibuffer) {
1559 fn(0, data);
1560 return;
1563 yornp_cb = fn;
1564 yornp_data = data;
1565 enter_minibuffer(yornp_self_insert, yornp_self_insert,
1566 yornp_abort, NULL);
1568 len = sizeof(ministate.prompt);
1569 strlcpy(ministate.prompt, prompt, len);
1570 strlcat(ministate.prompt, " (y or n) ", len);
1571 redraw_tab(current_tab());
1574 void
1575 ui_read(const char *prompt, void (*fn)(const char*, unsigned int),
1576 unsigned int data)
1578 size_t len;
1580 if (in_minibuffer)
1581 return;
1583 read_cb = fn;
1584 read_data = data;
1585 enter_minibuffer(read_self_insert, read_select, read_abort,
1586 &read_history);
1588 len = sizeof(ministate.prompt);
1589 strlcpy(ministate.prompt, prompt, len);
1590 strlcat(ministate.prompt, ": ", len);
1591 redraw_tab(current_tab());
1594 void
1595 ui_end(void)
1597 endwin();