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 <assert.h>
34 #include <curses.h>
35 #include <event.h>
36 #include <locale.h>
37 #include <signal.h>
38 #include <stdarg.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <unistd.h>
43 #include "defaults.h"
44 #include "minibuffer.h"
45 #include "telescope.h"
46 #include "ui.h"
47 #include "utf8.h"
49 static struct event stdioev, winchev;
51 static void restore_curs_x(struct buffer *);
53 static struct vline *nth_line(struct buffer*, size_t);
54 static int readkey(void);
55 static void dispatch_stdio(int, short, void*);
56 static void handle_clear_echoarea(int, short, void*);
57 static void handle_resize(int, short, void*);
58 static void handle_resize_nodelay(int, short, void*);
59 static void rearrange_windows(void);
60 static int wrap_page(struct buffer*, int);
61 static void print_vline(int, int, WINDOW*, struct vline*);
62 static void redraw_tabline(void);
63 static void redraw_window(WINDOW*, int, int, int, struct buffer*);
64 static void redraw_help(void);
65 static void redraw_body(struct tab*);
66 static void redraw_modeline(struct tab*);
67 static void redraw_minibuffer(void);
68 static void do_redraw_echoarea(void);
69 static void do_redraw_minibuffer(void);
70 static void do_redraw_minibuffer_compl(void);
71 static void place_cursor(int);
72 static void redraw_tab(struct tab*);
73 static void emit_help_item(char*, void*);
74 static void rec_compute_help(struct kmap*, char*, size_t);
75 static void recompute_help(void);
76 static void update_loading_anim(int, short, void*);
77 static void stop_loading_anim(struct tab*);
79 static int should_rearrange_windows;
80 static int too_small;
81 static int x_offset;
83 struct thiskey thiskey;
85 static struct event resizeev;
86 static struct timeval resize_timer = { 0, 250000 };
88 static WINDOW *tabline, *body, *modeline, *echoarea, *minibuffer;
90 int body_lines, body_cols;
92 static WINDOW *help;
93 static struct buffer helpwin;
94 static int help_lines, help_cols;
96 static int side_window;
98 static struct event clechoev;
99 static struct timeval clechoev_timer = { 5, 0 };
100 static struct timeval loadingev_timer = { 0, 250000 };
102 static uint32_t tab_counter;
104 static char keybuf[64];
106 struct kmap global_map,
107 minibuffer_map,
108 *current_map,
109 *base_map;
111 int in_minibuffer;
113 static inline void
114 update_x_offset(void)
116 if (olivetti_mode && fill_column < body_cols)
117 x_offset = (body_cols - fill_column)/2;
118 else
119 x_offset = 0;
122 void
123 save_excursion(struct excursion *place, struct buffer *buffer)
125 place->curs_x = buffer->curs_x;
126 place->curs_y = buffer->curs_y;
127 place->line_off = buffer->line_off;
128 place->current_line = buffer->current_line;
129 place->cpoff = buffer->cpoff;
132 void
133 restore_excursion(struct excursion *place, struct buffer *buffer)
135 buffer->curs_x = place->curs_x;
136 buffer->curs_y = place->curs_y;
137 buffer->line_off = place->line_off;
138 buffer->current_line = place->current_line;
139 buffer->cpoff = place->cpoff;
142 static void
143 restore_curs_x(struct buffer *buffer)
145 struct vline *vl;
146 const char *prfx;
148 vl = buffer->current_line;
149 if (vl == NULL || vl->line == NULL)
150 buffer->curs_x = buffer->cpoff = 0;
151 else if (vl->parent->data != NULL)
152 buffer->curs_x = utf8_snwidth(vl->parent->data+1, buffer->cpoff) + 1;
153 else
154 buffer->curs_x = utf8_snwidth(vl->line, buffer->cpoff);
156 buffer->curs_x += x_offset;
158 if (vl != NULL) {
159 prfx = line_prefixes[vl->parent->type].prfx1;
160 buffer->curs_x += utf8_swidth(prfx);
164 void
165 global_key_unbound(void)
167 message("%s is undefined", keybuf);
170 static struct vline *
171 nth_line(struct buffer *buffer, size_t n)
173 struct vline *vl;
174 size_t i;
176 i = 0;
177 TAILQ_FOREACH(vl, &buffer->head, vlines) {
178 if (i == n)
179 return vl;
180 i++;
183 /* unreachable */
184 abort();
187 struct tab *
188 current_tab(void)
190 struct tab *t;
192 TAILQ_FOREACH(t, &tabshead, tabs) {
193 if (t->flags & TAB_CURRENT)
194 return t;
197 /* unreachable */
198 abort();
201 struct buffer *
202 current_buffer(void)
204 if (in_minibuffer)
205 return &ministate.buffer;
206 return &current_tab()->buffer;
209 static int
210 readkey(void)
212 uint32_t state = 0;
214 if ((thiskey.key = wgetch(body)) == ERR)
215 return 0;
217 thiskey.meta = thiskey.key == 27;
218 if (thiskey.meta) {
219 thiskey.key = wgetch(body);
220 if (thiskey.key == ERR || thiskey.key == 27) {
221 thiskey.meta = 0;
222 thiskey.key = 27;
226 thiskey.cp = 0;
227 if ((unsigned int)thiskey.key < UINT8_MAX) {
228 while (1) {
229 if (!utf8_decode(&state, &thiskey.cp, (uint8_t)thiskey.key))
230 break;
231 if ((thiskey.key = wgetch(body)) == ERR) {
232 message("Error decoding user input");
233 return 0;
238 return 1;
241 static void
242 dispatch_stdio(int fd, short ev, void *d)
244 struct keymap *k;
245 const char *keyname;
246 char tmp[5] = {0};
248 /* TODO: schedule a redraw? */
249 if (too_small)
250 return;
252 if (!readkey())
253 return;
255 if (keybuf[0] != '\0')
256 strlcat(keybuf, " ", sizeof(keybuf));
257 if (thiskey.meta)
258 strlcat(keybuf, "M-", sizeof(keybuf));
259 if (thiskey.cp != 0) {
260 utf8_encode(thiskey.cp, tmp);
261 strlcat(keybuf, tmp, sizeof(keybuf));
262 } else if ((keyname = unkbd(thiskey.key)) != NULL) {
263 strlcat(keybuf, keyname, sizeof(keybuf));
264 } else {
265 tmp[0] = thiskey.key;
266 strlcat(keybuf, tmp, sizeof(keybuf));
269 TAILQ_FOREACH(k, &current_map->m, keymaps) {
270 if (k->meta == thiskey.meta &&
271 k->key == thiskey.key) {
272 if (k->fn == NULL)
273 current_map = &k->map;
274 else {
275 current_map = base_map;
276 strlcpy(keybuf, "", sizeof(keybuf));
277 k->fn(current_buffer());
279 goto done;
283 if (current_map->unhandled_input != NULL)
284 current_map->unhandled_input();
285 else
286 global_key_unbound();
288 strlcpy(keybuf, "", sizeof(keybuf));
289 current_map = base_map;
291 done:
292 if (side_window)
293 recompute_help();
295 if (should_rearrange_windows)
296 rearrange_windows();
297 redraw_tab(current_tab());
300 static void
301 handle_clear_echoarea(int fd, short ev, void *d)
303 free(ministate.curmesg);
304 ministate.curmesg = NULL;
306 redraw_minibuffer();
307 place_cursor(0);
310 static void
311 handle_resize(int sig, short ev, void *d)
313 if (event_pending(&resizeev, EV_TIMEOUT, NULL)) {
314 event_del(&resizeev);
316 evtimer_set(&resizeev, handle_resize_nodelay, NULL);
317 evtimer_add(&resizeev, &resize_timer);
320 static void
321 handle_resize_nodelay(int s, short ev, void *d)
323 endwin();
324 refresh();
325 clear();
327 rearrange_windows();
330 static void
331 rearrange_windows(void)
333 struct tab *tab;
334 int lines;
336 should_rearrange_windows = 0;
338 lines = LINES;
340 if ((too_small = lines < 15)) {
341 erase();
342 printw("Window too small.");
343 refresh();
344 return;
347 /* move and resize the windows, in reverse order! */
349 if (in_minibuffer == MB_COMPREAD) {
350 mvwin(minibuffer, lines-10, 0);
351 wresize(minibuffer, 10, COLS);
352 lines -= 10;
354 wrap_page(&ministate.compl.buffer, COLS);
357 mvwin(echoarea, --lines, 0);
358 wresize(echoarea, 1, COLS);
360 mvwin(modeline, --lines, 0);
361 wresize(modeline, 1, COLS);
363 body_lines = --lines;
364 body_cols = COLS;
366 if (side_window) {
367 help_cols = 0.3 * COLS;
368 help_lines = lines;
369 mvwin(help, 1, 0);
370 wresize(help, help_lines, help_cols);
372 wrap_page(&helpwin, help_cols);
374 body_cols = COLS - help_cols - 1;
375 mvwin(body, 1, help_cols);
376 } else
377 mvwin(body, 1, 0);
379 update_x_offset();
380 wresize(body, body_lines, body_cols);
382 wresize(tabline, 1, COLS);
384 tab = current_tab();
386 wrap_page(&tab->buffer, body_cols);
387 redraw_tab(tab);
390 static int
391 wrap_page(struct buffer *buffer, int width)
393 struct line *l;
394 const struct line *top_orig, *orig;
395 struct vline *vl;
396 int pre_width;
397 const char *prfx;
399 top_orig = buffer->top_line == NULL ? NULL : buffer->top_line->parent;
400 orig = buffer->current_line == NULL ? NULL : buffer->current_line->parent;
402 buffer->top_line = NULL;
403 buffer->current_line = NULL;
405 buffer->force_redraw = 1;
406 buffer->curs_y = 0;
407 buffer->line_off = 0;
409 empty_vlist(buffer);
411 TAILQ_FOREACH(l, &buffer->page.head, lines) {
412 prfx = line_prefixes[l->type].prfx1;
413 switch (l->type) {
414 case LINE_TEXT:
415 case LINE_LINK:
416 case LINE_TITLE_1:
417 case LINE_TITLE_2:
418 case LINE_TITLE_3:
419 case LINE_ITEM:
420 case LINE_QUOTE:
421 case LINE_PRE_START:
422 case LINE_PRE_END:
423 wrap_text(buffer, prfx, l, MIN(fill_column, width));
424 break;
425 case LINE_PRE_CONTENT:
426 if (olivetti_mode)
427 pre_width = MIN(fill_column, width);
428 else
429 pre_width = width;
430 hardwrap_text(buffer, l, pre_width);
431 break;
432 case LINE_COMPL:
433 case LINE_COMPL_CURRENT:
434 wrap_one(buffer, prfx, l, width);
435 break;
438 if (top_orig == l && buffer->top_line == NULL) {
439 buffer->line_off = buffer->line_max-1;
440 buffer->top_line = TAILQ_LAST(&buffer->head, vhead);
442 while (1) {
443 vl = TAILQ_PREV(buffer->top_line, vhead, vlines);
444 if (vl == NULL || vl->parent != orig)
445 break;
446 buffer->top_line = vl;
447 buffer->line_off--;
451 if (orig == l && buffer->current_line == NULL) {
452 buffer->current_line = TAILQ_LAST(&buffer->head, vhead);
454 while (1) {
455 vl = TAILQ_PREV(buffer->current_line, vhead, vlines);
456 if (vl == NULL || vl->parent != orig)
457 break;
458 buffer->current_line = vl;
463 if (buffer->current_line == NULL)
464 buffer->current_line = TAILQ_FIRST(&buffer->head);
466 if (buffer->top_line == NULL)
467 buffer->top_line = buffer->current_line;
469 return 1;
472 /*
473 * Core part of the rendering. It prints a vline starting from the
474 * current cursor position. Printing a vline consists of skipping
475 * `off' columns (for olivetti-mode), print the correct prefix (which
476 * may be the emoji in case of emojified links-lines), printing the
477 * text itself, filling until width - off and filling off columns
478 * again.
479 */
480 static void
481 print_vline(int off, int width, WINDOW *window, struct vline *vl)
483 /*
484 * Believe me or not, I've seen emoji ten code points long!
485 * That means, to stay large, 4*10 bytes + NUL.
486 */
487 char emojibuf[41] = {0};
488 char *space, *t;
489 const char *text, *prfx;
490 struct line_face *f;
491 int i, left, x, y, emojified, cont;
492 long len = sizeof(emojibuf);
494 f = &line_faces[vl->parent->type];
496 /* unused, set by getyx */
497 (void)y;
499 cont = vl->flags & L_CONTINUATION;
500 if (!cont)
501 prfx = line_prefixes[vl->parent->type].prfx1;
502 else
503 prfx = line_prefixes[vl->parent->type].prfx2;
505 text = vl->line;
506 if (text == NULL)
507 text = "";
509 wattr_on(window, body_face.left, NULL);
510 for (i = 0; i < off; i++)
511 waddch(window, ' ');
512 wattr_off(window, body_face.left, NULL);
514 wattr_on(window, f->prefix, NULL);
515 emojified = 0;
516 space = vl->parent->data;
517 if (vl->parent->type == LINE_LINK && space != NULL) {
518 emojified = 1;
519 if (cont) {
520 len = utf8_swidth_between(vl->parent->line, space) + 1;
521 for (i = 0; i < len; ++i)
522 wprintw(window, " ");
523 } else {
524 strlcpy(emojibuf, text, sizeof(emojibuf));
525 if ((t = strchr(emojibuf, ' ')) != NULL)
526 *t = '\0';
527 wprintw(window, "%s ", emojibuf);
529 } else {
530 wprintw(window, "%s", prfx);
532 wattr_off(window, f->prefix, NULL);
534 wattr_on(window, f->text, NULL);
535 if (emojified && !cont)
536 wprintw(window, "%s", text + (space - vl->parent->line) + 1);
537 else
538 wprintw(window, "%s", text);
539 wattr_off(window, f->text, NULL);
541 getyx(window, y, x);
543 left = width - x;
545 wattr_on(window, f->trail, NULL);
546 for (i = 0; i < left - off; ++i)
547 waddch(window, ' ');
548 wattr_off(window, f->trail, NULL);
550 wattr_on(window, body_face.right, NULL);
551 for (i = 0; i < off; i++)
552 waddch(window, ' ');
553 wattr_off(window, body_face.right, NULL);
557 static void
558 redraw_tabline(void)
560 struct tab *tab;
561 size_t toskip, ots, tabwidth, space, x;
562 int current, y, truncated;
563 const char *title;
564 char buf[25];
566 x = 0;
568 /* unused, but setted by a getyx */
569 (void)y;
571 tabwidth = sizeof(buf)+1;
572 space = COLS-2;
574 toskip = 0;
575 TAILQ_FOREACH(tab, &tabshead, tabs) {
576 toskip++;
577 if (tab->flags & TAB_CURRENT)
578 break;
581 if (toskip * tabwidth < space)
582 toskip = 0;
583 else {
584 ots = toskip;
585 toskip--;
586 while (toskip != 0 &&
587 (ots - toskip+1) * tabwidth < space)
588 toskip--;
591 werase(tabline);
592 wattr_on(tabline, tab_face.background, NULL);
593 wprintw(tabline, toskip == 0 ? " " : "<");
594 wattr_off(tabline, tab_face.background, NULL);
596 truncated = 0;
597 TAILQ_FOREACH(tab, &tabshead, tabs) {
598 if (truncated)
599 break;
600 if (toskip != 0) {
601 toskip--;
602 continue;
605 getyx(tabline, y, x);
606 if (x + sizeof(buf)+2 >= (size_t)COLS)
607 truncated = 1;
609 current = tab->flags & TAB_CURRENT;
611 if (*(title = tab->buffer.page.title) == '\0')
612 title = tab->hist_cur->h;
614 if (tab->flags & TAB_URGENT)
615 strlcpy(buf, "!", sizeof(buf));
616 else
617 strlcpy(buf, " ", sizeof(buf));
619 if (strlcat(buf, title, sizeof(buf)) >= sizeof(buf)) {
620 /* truncation happens */
621 strlcpy(&buf[sizeof(buf)-4], "...", 4);
622 } else {
623 /* pad with spaces */
624 while (strlcat(buf, " ", sizeof(buf)) < sizeof(buf))
625 /* nop */ ;
628 if (current)
629 wattr_on(tabline, tab_face.current, NULL);
630 else
631 wattr_on(tabline, tab_face.tab, NULL);
633 wprintw(tabline, "%s", buf);
634 if (TAILQ_NEXT(tab, tabs) != NULL)
635 wprintw(tabline, " ");
637 if (current)
638 wattr_off(tabline, tab_face.current, NULL);
639 else
640 wattr_off(tabline, tab_face.tab, NULL);
643 wattr_on(tabline, tab_face.background, NULL);
644 for (; x < (size_t)COLS; ++x)
645 waddch(tabline, ' ');
646 if (truncated)
647 mvwprintw(tabline, 0, COLS-1, ">");
648 wattr_off(tabline, tab_face.background, NULL);
651 /*
652 * Compute the first visible line around vl. Try to search forward
653 * until the end of the buffer; if a visible line is not found, search
654 * backward. Return NULL if no viable line was found.
655 */
656 struct vline *
657 adjust_line(struct vline *vl, struct buffer *buffer)
659 struct vline *t;
661 if (vl == NULL)
662 return NULL;
664 if (!(vl->parent->flags & L_HIDDEN))
665 return vl;
667 /* search forward */
668 for (t = vl;
669 t != NULL && t->parent->flags & L_HIDDEN;
670 t = TAILQ_NEXT(t, vlines))
671 ; /* nop */
673 if (t != NULL)
674 return t;
676 /* search backward */
677 for (t = vl;
678 t != NULL && t->parent->flags & L_HIDDEN;
679 t = TAILQ_PREV(t, vhead, vlines))
680 ; /* nop */
682 return t;
685 static void
686 redraw_window(WINDOW *win, int off, int height, int width, struct buffer *buffer)
688 struct vline *vl;
689 int l, onscreen;
691 restore_curs_x(buffer);
693 /*
694 * TODO: ignoring buffer->force_update and always
695 * re-rendering. In theory we can recompute the y position
696 * without a re-render, and optimize here. It's not the only
697 * optimisation possible here, wscrl wolud also be an
698 * interesting one.
699 */
701 again:
702 werase(win);
703 buffer->curs_y = 0;
705 if (TAILQ_EMPTY(&buffer->head))
706 goto end;
708 if (buffer->top_line == NULL)
709 buffer->top_line = TAILQ_FIRST(&buffer->head);
711 buffer->top_line = adjust_line(buffer->top_line, buffer);
712 if (buffer->top_line == NULL)
713 goto end;
715 buffer->current_line = adjust_line(buffer->current_line, buffer);
717 l = 0;
718 onscreen = 0;
719 for (vl = buffer->top_line; vl != NULL; vl = TAILQ_NEXT(vl, vlines)) {
720 if (vl->parent->flags & L_HIDDEN)
721 continue;
723 wmove(win, l, 0);
724 print_vline(off, width, win, vl);
726 if (vl == buffer->current_line)
727 onscreen = 1;
729 if (!onscreen)
730 buffer->curs_y++;
732 l++;
733 if (l == height)
734 break;
737 if (!onscreen) {
738 for (; vl != NULL; vl = TAILQ_NEXT(vl, vlines)) {
739 if (vl == buffer->current_line)
740 break;
741 if (vl->parent->flags & L_HIDDEN)
742 continue;
743 buffer->line_off++;
744 buffer->top_line = TAILQ_NEXT(buffer->top_line, vlines);
747 if (vl != NULL)
748 goto again;
751 buffer->last_line_off = buffer->line_off;
752 buffer->force_redraw = 0;
753 end:
754 wmove(win, buffer->curs_y, buffer->curs_x);
757 static void
758 redraw_help(void)
760 redraw_window(help, 0, help_lines, help_cols, &helpwin);
763 static void
764 redraw_body(struct tab *tab)
766 static struct tab *last_tab;
768 if (last_tab != tab)
769 tab->buffer.force_redraw =1;
770 last_tab = tab;
772 redraw_window(body, x_offset, body_lines, body_cols, &tab->buffer);
775 static inline char
776 trust_status_char(enum trust_state ts)
778 switch (ts) {
779 case TS_UNKNOWN: return 'u';
780 case TS_UNTRUSTED: return '!';
781 case TS_TEMP_TRUSTED: return '!';
782 case TS_TRUSTED: return 'v';
783 case TS_VERIFIED: return 'V';
784 default: return 'X';
788 static void
789 redraw_modeline(struct tab *tab)
791 double pct;
792 int x, y, max_x, max_y;
793 const char *mode = tab->buffer.page.name;
794 const char *spin = "-\\|/";
796 werase(modeline);
797 wattr_on(modeline, modeline_face.background, NULL);
798 wmove(modeline, 0, 0);
800 wprintw(modeline, "-%c%c %s ",
801 spin[tab->loading_anim_step],
802 trust_status_char(tab->trust),
803 mode == NULL ? "(none)" : mode);
805 pct = (tab->buffer.line_off + tab->buffer.curs_y) * 100.0
806 / tab->buffer.line_max;
808 if (tab->buffer.line_max <= (size_t)body_lines)
809 wprintw(modeline, "All ");
810 else if (tab->buffer.line_off == 0)
811 wprintw(modeline, "Top ");
812 else if (tab->buffer.line_off + body_lines >= tab->buffer.line_max)
813 wprintw(modeline, "Bottom ");
814 else
815 wprintw(modeline, "%.0f%% ", pct);
817 wprintw(modeline, "%d/%d %s ",
818 tab->buffer.line_off + tab->buffer.curs_y,
819 tab->buffer.line_max,
820 tab->hist_cur->h);
822 getyx(modeline, y, x);
823 getmaxyx(modeline, max_y, max_x);
825 (void)y;
826 (void)max_y;
828 for (; x < max_x; ++x)
829 waddstr(modeline, "-");
831 wattr_off(modeline, modeline_face.background, NULL);
834 static void
835 redraw_minibuffer(void)
837 wattr_on(echoarea, minibuffer_face.background, NULL);
838 werase(echoarea);
840 if (in_minibuffer)
841 do_redraw_minibuffer();
842 else
843 do_redraw_echoarea();
845 if (in_minibuffer == MB_COMPREAD)
846 do_redraw_minibuffer_compl();
848 wattr_off(echoarea, minibuffer_face.background, NULL);
851 static void
852 do_redraw_echoarea(void)
854 struct tab *tab;
856 if (ministate.curmesg != NULL)
857 wprintw(echoarea, "%s", ministate.curmesg);
858 else if (*keybuf != '\0')
859 waddstr(echoarea, keybuf);
860 else {
861 /* If nothing else, show the URL at point */
862 tab = current_tab();
863 if (tab->buffer.current_line != NULL &&
864 tab->buffer.current_line->parent->type == LINE_LINK)
865 waddstr(echoarea,
866 tab->buffer.current_line->parent->alt);
870 static void
871 do_redraw_minibuffer(void)
873 size_t off_y, off_x = 0;
874 const char *start, *c;
876 /* unused, set by getyx */
877 (void)off_y;
879 wmove(echoarea, 0, 0);
881 if (in_minibuffer == MB_COMPREAD)
882 wprintw(echoarea, "(%2d) ",
883 ministate.compl.buffer.line_max);
885 wprintw(echoarea, "%s", ministate.prompt);
886 if (ministate.hist_cur != NULL)
887 wprintw(echoarea, "(%zu/%zu) ",
888 ministate.hist_off + 1,
889 ministate.history->len);
891 getyx(echoarea, off_y, off_x);
893 start = ministate.hist_cur != NULL
894 ? ministate.hist_cur->h
895 : ministate.buf;
896 c = utf8_nth(ministate.buffer.current_line->line,
897 ministate.buffer.cpoff);
898 while (utf8_swidth_between(start, c) > (size_t)COLS/2) {
899 start = utf8_next_cp(start);
902 waddstr(echoarea, start);
904 if (ministate.curmesg != NULL)
905 wprintw(echoarea, " [%s]", ministate.curmesg);
907 wmove(echoarea, 0, off_x + utf8_swidth_between(start, c));
910 static void
911 do_redraw_minibuffer_compl(void)
913 redraw_window(minibuffer, 0, 10, body_cols,
914 &ministate.compl.buffer);
917 /*
918 * Place the cursor in the right ncurses window. If soft is 1, use
919 * wnoutrefresh (which shouldn't cause any I/O); otherwise use
920 * wrefresh.
921 */
922 static void
923 place_cursor(int soft)
925 int (*touch)(WINDOW *);
927 if (soft)
928 touch = wnoutrefresh;
929 else
930 touch = wrefresh;
932 if (in_minibuffer) {
933 touch(body);
934 touch(echoarea);
935 } else {
936 touch(echoarea);
937 touch(body);
941 static void
942 redraw_tab(struct tab *tab)
944 if (too_small)
945 return;
947 if (side_window) {
948 redraw_help();
949 wnoutrefresh(help);
952 redraw_tabline();
953 redraw_body(tab);
954 redraw_modeline(tab);
955 redraw_minibuffer();
957 wnoutrefresh(tabline);
958 wnoutrefresh(modeline);
960 if (in_minibuffer == MB_COMPREAD)
961 wnoutrefresh(minibuffer);
963 place_cursor(1);
965 doupdate();
968 static void
969 emit_help_item(char *prfx, void *fn)
971 struct line *l;
972 struct cmd *cmd;
974 for (cmd = cmds; cmd->cmd != NULL; ++cmd) {
975 if (fn == cmd->fn)
976 break;
978 assert(cmd != NULL);
980 if ((l = calloc(1, sizeof(*l))) == NULL)
981 abort();
983 l->type = LINE_TEXT;
984 l->alt = NULL;
986 asprintf(&l->line, "%s %s", prfx, cmd->cmd);
988 if (TAILQ_EMPTY(&helpwin.page.head))
989 TAILQ_INSERT_HEAD(&helpwin.page.head, l, lines);
990 else
991 TAILQ_INSERT_TAIL(&helpwin.page.head, l, lines);
994 static void
995 rec_compute_help(struct kmap *keymap, char *prfx, size_t len)
997 struct keymap *k;
998 char p[32];
999 const char *kn;
1001 TAILQ_FOREACH(k, &keymap->m, keymaps) {
1002 strlcpy(p, prfx, sizeof(p));
1003 if (*p != '\0')
1004 strlcat(p, " ", sizeof(p));
1005 if (k->meta)
1006 strlcat(p, "M-", sizeof(p));
1007 if ((kn = unkbd(k->key)) != NULL)
1008 strlcat(p, kn, sizeof(p));
1009 else
1010 strlcat(p, keyname(k->key), sizeof(p));
1012 if (k->fn == NULL)
1013 rec_compute_help(&k->map, p, sizeof(p));
1014 else
1015 emit_help_item(p, k->fn);
1019 static void
1020 recompute_help(void)
1022 char p[32] = { 0 };
1024 empty_vlist(&helpwin);
1025 empty_linelist(&helpwin);
1026 rec_compute_help(current_map, p, sizeof(p));
1027 wrap_page(&helpwin, help_cols);
1030 void
1031 vmessage(const char *fmt, va_list ap)
1033 if (evtimer_pending(&clechoev, NULL))
1034 evtimer_del(&clechoev);
1036 free(ministate.curmesg);
1037 ministate.curmesg = NULL;
1039 if (fmt != NULL) {
1040 evtimer_set(&clechoev, handle_clear_echoarea, NULL);
1041 evtimer_add(&clechoev, &clechoev_timer);
1043 /* TODO: what to do if the allocation fails here? */
1044 if (vasprintf(&ministate.curmesg, fmt, ap) == -1)
1045 ministate.curmesg = NULL;
1048 redraw_minibuffer();
1049 place_cursor(0);
1052 void
1053 message(const char *fmt, ...)
1055 va_list ap;
1057 va_start(ap, fmt);
1058 vmessage(fmt, ap);
1059 va_end(ap);
1062 void
1063 start_loading_anim(struct tab *tab)
1065 if (tab->loading_anim)
1066 return;
1067 tab->loading_anim = 1;
1068 evtimer_set(&tab->loadingev, update_loading_anim, tab);
1069 evtimer_add(&tab->loadingev, &loadingev_timer);
1072 static void
1073 update_loading_anim(int fd, short ev, void *d)
1075 struct tab *tab = d;
1077 tab->loading_anim_step = (tab->loading_anim_step+1)%4;
1079 if (tab->flags & TAB_CURRENT) {
1080 redraw_modeline(tab);
1081 wrefresh(modeline);
1082 wrefresh(body);
1083 if (in_minibuffer)
1084 wrefresh(echoarea);
1087 evtimer_add(&tab->loadingev, &loadingev_timer);
1090 static void
1091 stop_loading_anim(struct tab *tab)
1093 if (!tab->loading_anim)
1094 return;
1095 evtimer_del(&tab->loadingev);
1096 tab->loading_anim = 0;
1097 tab->loading_anim_step = 0;
1099 if (!(tab->flags & TAB_CURRENT))
1100 return;
1102 redraw_modeline(tab);
1104 wrefresh(modeline);
1105 wrefresh(body);
1106 if (in_minibuffer)
1107 wrefresh(echoarea);
1110 void
1111 load_url_in_tab(struct tab *tab, const char *url)
1113 message("Loading %s...", url);
1114 start_loading_anim(tab);
1115 load_url(tab, url);
1117 tab->buffer.curs_x = 0;
1118 tab->buffer.curs_y = 0;
1119 redraw_tab(tab);
1122 void
1123 switch_to_tab(struct tab *tab)
1125 struct tab *t;
1127 TAILQ_FOREACH(t, &tabshead, tabs) {
1128 t->flags &= ~TAB_CURRENT;
1131 tab->flags |= TAB_CURRENT;
1132 tab->flags &= ~TAB_URGENT;
1135 unsigned int
1136 tab_new_id(void)
1138 return tab_counter++;
1141 struct tab *
1142 new_tab(const char *url)
1144 struct tab *tab;
1146 if ((tab = calloc(1, sizeof(*tab))) == NULL) {
1147 event_loopbreak();
1148 return NULL;
1150 tab->fd = -1;
1152 TAILQ_INIT(&tab->hist.head);
1154 TAILQ_INIT(&tab->buffer.head);
1156 tab->id = tab_new_id();
1157 switch_to_tab(tab);
1159 if (TAILQ_EMPTY(&tabshead))
1160 TAILQ_INSERT_HEAD(&tabshead, tab, tabs);
1161 else
1162 TAILQ_INSERT_TAIL(&tabshead, tab, tabs);
1164 load_url_in_tab(tab, url);
1165 return tab;
1168 int
1169 ui_print_colors(void)
1171 int colors = 0, pairs = 0, can_change = 0;
1172 int columns = 16, lines, color, i, j;
1174 initscr();
1175 if (has_colors()) {
1176 start_color();
1177 use_default_colors();
1179 colors = COLORS;
1180 pairs = COLOR_PAIRS;
1181 can_change = can_change_color();
1183 endwin();
1185 printf("Term info:\n");
1186 printf("TERM=%s COLORS=%d COLOR_PAIRS=%d can_change_colors=%d\n",
1187 getenv("TERM"), colors, pairs, can_change);
1188 printf("\n");
1190 if (colors == 0) {
1191 printf("No color support\n");
1192 return 0;
1195 printf("Available colors:\n\n");
1196 lines = (colors - 1) / columns + 1;
1197 color = 0;
1198 for (i = 0; i < lines; ++i) {
1199 for (j = 0; j < columns; ++j, ++color) {
1200 printf("\033[0;38;5;%dm %03d", color, color);
1202 printf("\n");
1205 printf("\033[0m");
1206 fflush(stdout);
1207 return 0;
1210 int
1211 ui_init()
1213 setlocale(LC_ALL, "");
1215 TAILQ_INIT(&eecmd_history.head);
1216 TAILQ_INIT(&ir_history.head);
1217 TAILQ_INIT(&lu_history.head);
1219 ministate.line.type = LINE_TEXT;
1220 ministate.vline.parent = &ministate.line;
1221 ministate.buffer.current_line = &ministate.vline;
1223 /* initialize help window */
1224 TAILQ_INIT(&helpwin.head);
1226 base_map = &global_map;
1227 current_map = &global_map;
1229 initscr();
1231 if (enable_colors) {
1232 if (has_colors()) {
1233 start_color();
1234 use_default_colors();
1235 } else
1236 enable_colors = 0;
1239 config_apply_style();
1241 raw();
1242 noecho();
1243 nonl();
1244 intrflush(stdscr, FALSE);
1246 if ((tabline = newwin(1, COLS, 0, 0)) == NULL)
1247 return 0;
1248 if ((body = newwin(LINES - 3, COLS, 1, 0)) == NULL)
1249 return 0;
1250 if ((modeline = newwin(1, COLS, LINES-2, 0)) == NULL)
1251 return 0;
1252 if ((echoarea = newwin(1, COLS, LINES-1, 0)) == NULL)
1253 return 0;
1254 if ((minibuffer = newwin(1, COLS, LINES-1, 0)) == NULL)
1255 return 0;
1256 if ((help = newwin(1, 1, 1, 0)) == NULL)
1257 return 0;
1259 body_lines = LINES-3;
1260 body_cols = COLS;
1262 wbkgd(body, body_face.body);
1263 wbkgd(echoarea, minibuffer_face.background);
1265 update_x_offset();
1267 keypad(body, TRUE);
1268 scrollok(body, FALSE);
1270 /* non-blocking input */
1271 wtimeout(body, 0);
1273 mvwprintw(body, 0, 0, "");
1276 * Dummy so libevent2 won't complain that no event_base is set
1277 * when checking event_pending for the first time
1279 evtimer_set(&clechoev, handle_clear_echoarea, NULL);
1280 evtimer_add(&clechoev, &clechoev_timer);
1281 evtimer_set(&resizeev, handle_resize, NULL);
1282 evtimer_add(&resizeev, &resize_timer);
1284 event_set(&stdioev, 0, EV_READ | EV_PERSIST, dispatch_stdio, NULL);
1285 event_add(&stdioev, NULL);
1287 signal_set(&winchev, SIGWINCH, handle_resize, NULL);
1288 signal_add(&winchev, NULL);
1290 return 1;
1293 void
1294 ui_on_tab_loaded(struct tab *tab)
1296 stop_loading_anim(tab);
1297 message("Loaded %s", tab->hist_cur->h);
1299 redraw_tabline();
1300 wrefresh(tabline);
1301 place_cursor(0);
1304 void
1305 ui_on_tab_refresh(struct tab *tab)
1307 wrap_page(&tab->buffer, body_cols);
1308 if (tab->flags & TAB_CURRENT)
1309 redraw_tab(tab);
1310 else
1311 tab->flags |= TAB_URGENT;
1314 const char *
1315 ui_keyname(int k)
1317 return keyname(k);
1320 void
1321 ui_toggle_side_window(void)
1323 side_window = !side_window;
1324 if (side_window)
1325 recompute_help();
1328 * ugly hack, but otherwise the window doesn't get updated
1329 * until I call rearrange_windows a second time (e.g. via
1330 * C-l). I will be happy to know why something like this is
1331 * needed.
1333 rearrange_windows();
1334 rearrange_windows();
1337 void
1338 ui_schedule_redraw(void)
1340 should_rearrange_windows = 1;
1343 void
1344 ui_require_input(struct tab *tab, int hide)
1346 /* TODO: hard-switching to another tab is ugly */
1347 switch_to_tab(tab);
1349 enter_minibuffer(ir_self_insert, ir_select, exit_minibuffer,
1350 &ir_history, NULL, NULL);
1351 strlcpy(ministate.prompt, "Input required: ",
1352 sizeof(ministate.prompt));
1353 redraw_tab(tab);
1356 void
1357 ui_yornp(const char *prompt, void (*fn)(int, struct tab *),
1358 struct tab *data)
1360 yornp(prompt, fn, data);
1361 redraw_tab(current_tab());
1364 void
1365 ui_read(const char *prompt, void (*fn)(const char*, struct tab *),
1366 struct tab *data)
1368 completing_read(prompt, fn, data);
1369 redraw_tab(current_tab());
1372 void
1373 ui_suspend(void)
1375 endwin();
1377 kill(getpid(), SIGSTOP);
1379 refresh();
1380 clear();
1381 rearrange_windows();
1384 void
1385 ui_end(void)
1387 endwin();