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 int readkey(void);
54 static void dispatch_stdio(int, short, void*);
55 static void handle_clear_echoarea(int, short, void*);
56 static void handle_resize(int, short, void*);
57 static void handle_resize_nodelay(int, short, void*);
58 static void rearrange_windows(void);
59 static int wrap_page(struct buffer*, int);
60 static void line_prefix_and_text(struct vline *, char *, size_t, const char **, const char **);
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 /*
80 * Used to know when we're finished loading.
81 */
82 static int operating;
84 static int should_rearrange_windows;
85 static int too_small;
86 static int x_offset;
88 struct thiskey thiskey;
89 struct tab *current_tab;
91 static struct event resizeev;
92 static struct timeval resize_timer = { 0, 250000 };
94 static WINDOW *tabline, *body, *modeline, *echoarea, *minibuffer;
96 int body_lines, body_cols;
98 static WINDOW *help;
99 static struct buffer helpwin;
100 static int help_lines, help_cols;
102 static int side_window;
104 static struct event clechoev;
105 static struct timeval clechoev_timer = { 5, 0 };
106 static struct timeval loadingev_timer = { 0, 250000 };
108 static uint32_t tab_counter;
110 static char keybuf[64];
112 struct kmap global_map,
113 minibuffer_map,
114 *current_map,
115 *base_map;
117 int in_minibuffer;
119 static inline void
120 update_x_offset(void)
122 if (olivetti_mode && fill_column < body_cols)
123 x_offset = (body_cols - fill_column)/2;
124 else
125 x_offset = 0;
128 void
129 save_excursion(struct excursion *place, struct buffer *buffer)
131 place->curs_x = buffer->curs_x;
132 place->curs_y = buffer->curs_y;
133 place->line_off = buffer->line_off;
134 place->current_line = buffer->current_line;
135 place->cpoff = buffer->cpoff;
138 void
139 restore_excursion(struct excursion *place, struct buffer *buffer)
141 buffer->curs_x = place->curs_x;
142 buffer->curs_y = place->curs_y;
143 buffer->line_off = place->line_off;
144 buffer->current_line = place->current_line;
145 buffer->cpoff = place->cpoff;
148 static void
149 restore_curs_x(struct buffer *buffer)
151 struct vline *vl;
152 const char *prfx;
154 vl = buffer->current_line;
155 if (vl == NULL || vl->line == NULL)
156 buffer->curs_x = buffer->cpoff = 0;
157 else if (vl->parent->data != NULL)
158 buffer->curs_x = utf8_snwidth(vl->parent->data+1, buffer->cpoff) + 1;
159 else
160 buffer->curs_x = utf8_snwidth(vl->line, buffer->cpoff);
162 buffer->curs_x += x_offset;
164 if (vl == NULL)
165 return;
167 if (vl->parent->data != NULL)
168 buffer->curs_x += utf8_swidth_between(vl->parent->line, vl->parent->data);
169 else {
170 prfx = line_prefixes[vl->parent->type].prfx1;
171 buffer->curs_x += utf8_swidth(prfx);
175 void
176 global_key_unbound(void)
178 message("%s is undefined", keybuf);
181 struct buffer *
182 current_buffer(void)
184 if (in_minibuffer)
185 return &ministate.buffer;
186 return &current_tab->buffer;
189 static int
190 readkey(void)
192 uint32_t state = 0;
194 if ((thiskey.key = wgetch(body)) == ERR)
195 return 0;
197 thiskey.meta = thiskey.key == 27;
198 if (thiskey.meta) {
199 thiskey.key = wgetch(body);
200 if (thiskey.key == ERR || thiskey.key == 27) {
201 thiskey.meta = 0;
202 thiskey.key = 27;
206 thiskey.cp = 0;
207 if ((unsigned int)thiskey.key < UINT8_MAX) {
208 while (1) {
209 if (!utf8_decode(&state, &thiskey.cp, (uint8_t)thiskey.key))
210 break;
211 if ((thiskey.key = wgetch(body)) == ERR) {
212 message("Error decoding user input");
213 return 0;
218 return 1;
221 static void
222 dispatch_stdio(int fd, short ev, void *d)
224 struct keymap *k;
225 const char *keyname;
226 char tmp[5] = {0};
228 /* TODO: schedule a redraw? */
229 if (too_small)
230 return;
232 if (!readkey())
233 return;
235 if (keybuf[0] != '\0')
236 strlcat(keybuf, " ", sizeof(keybuf));
237 if (thiskey.meta)
238 strlcat(keybuf, "M-", sizeof(keybuf));
239 if (thiskey.cp != 0) {
240 utf8_encode(thiskey.cp, tmp);
241 strlcat(keybuf, tmp, sizeof(keybuf));
242 } else if ((keyname = unkbd(thiskey.key)) != NULL) {
243 strlcat(keybuf, keyname, sizeof(keybuf));
244 } else {
245 tmp[0] = thiskey.key;
246 strlcat(keybuf, tmp, sizeof(keybuf));
249 TAILQ_FOREACH(k, &current_map->m, keymaps) {
250 if (k->meta == thiskey.meta &&
251 k->key == thiskey.key) {
252 if (k->fn == NULL)
253 current_map = &k->map;
254 else {
255 current_map = base_map;
256 strlcpy(keybuf, "", sizeof(keybuf));
257 k->fn(current_buffer());
259 goto done;
263 if (current_map->unhandled_input != NULL)
264 current_map->unhandled_input();
265 else
266 global_key_unbound();
268 strlcpy(keybuf, "", sizeof(keybuf));
269 current_map = base_map;
271 done:
272 if (side_window)
273 recompute_help();
275 if (should_rearrange_windows)
276 rearrange_windows();
277 redraw_tab(current_tab);
280 static void
281 handle_clear_echoarea(int fd, short ev, void *d)
283 free(ministate.curmesg);
284 ministate.curmesg = NULL;
286 redraw_minibuffer();
287 place_cursor(0);
290 static void
291 handle_resize(int sig, short ev, void *d)
293 if (event_pending(&resizeev, EV_TIMEOUT, NULL)) {
294 event_del(&resizeev);
296 evtimer_set(&resizeev, handle_resize_nodelay, NULL);
297 evtimer_add(&resizeev, &resize_timer);
300 static void
301 handle_resize_nodelay(int s, short ev, void *d)
303 endwin();
304 refresh();
305 clear();
307 rearrange_windows();
310 static void
311 rearrange_windows(void)
313 int lines;
315 should_rearrange_windows = 0;
317 lines = LINES;
319 if ((too_small = lines < 15)) {
320 erase();
321 printw("Window too small.");
322 refresh();
323 return;
326 /* move and resize the windows, in reverse order! */
328 if (in_minibuffer == MB_COMPREAD) {
329 mvwin(minibuffer, lines-10, 0);
330 wresize(minibuffer, 10, COLS);
331 lines -= 10;
333 wrap_page(&ministate.compl.buffer, COLS);
336 mvwin(echoarea, --lines, 0);
337 wresize(echoarea, 1, COLS);
339 mvwin(modeline, --lines, 0);
340 wresize(modeline, 1, COLS);
342 body_lines = --lines;
343 body_cols = COLS;
345 if (side_window) {
346 help_cols = 0.3 * COLS;
347 help_lines = lines;
348 mvwin(help, 1, 0);
349 wresize(help, help_lines, help_cols);
351 wrap_page(&helpwin, help_cols);
353 body_cols = COLS - help_cols - 1;
354 mvwin(body, 1, help_cols);
355 } else
356 mvwin(body, 1, 0);
358 update_x_offset();
359 wresize(body, body_lines, body_cols);
361 wresize(tabline, 1, COLS);
363 wrap_page(&current_tab->buffer, body_cols);
364 redraw_tab(current_tab);
367 static int
368 wrap_page(struct buffer *buffer, int width)
370 struct line *l;
371 const struct line *top_orig, *orig;
372 struct vline *vl;
373 int pre_width;
374 const char *prfx;
376 top_orig = buffer->top_line == NULL ? NULL : buffer->top_line->parent;
377 orig = buffer->current_line == NULL ? NULL : buffer->current_line->parent;
379 buffer->top_line = NULL;
380 buffer->current_line = NULL;
382 buffer->force_redraw = 1;
383 buffer->curs_y = 0;
384 buffer->line_off = 0;
386 empty_vlist(buffer);
388 TAILQ_FOREACH(l, &buffer->page.head, lines) {
389 prfx = line_prefixes[l->type].prfx1;
390 switch (l->type) {
391 case LINE_TEXT:
392 case LINE_LINK:
393 case LINE_TITLE_1:
394 case LINE_TITLE_2:
395 case LINE_TITLE_3:
396 case LINE_ITEM:
397 case LINE_QUOTE:
398 case LINE_PRE_START:
399 case LINE_PRE_END:
400 wrap_text(buffer, prfx, l, MIN(fill_column, width));
401 break;
402 case LINE_PRE_CONTENT:
403 if (olivetti_mode)
404 pre_width = MIN(fill_column, width);
405 else
406 pre_width = width;
407 hardwrap_text(buffer, l, pre_width);
408 break;
409 case LINE_COMPL:
410 case LINE_COMPL_CURRENT:
411 wrap_one(buffer, prfx, l, width);
412 break;
415 if (top_orig == l && buffer->top_line == NULL) {
416 buffer->line_off = buffer->line_max-1;
417 buffer->top_line = TAILQ_LAST(&buffer->head, vhead);
419 while (1) {
420 vl = TAILQ_PREV(buffer->top_line, vhead, vlines);
421 if (vl == NULL || vl->parent != orig)
422 break;
423 buffer->top_line = vl;
424 buffer->line_off--;
428 if (orig == l && buffer->current_line == NULL) {
429 buffer->current_line = TAILQ_LAST(&buffer->head, vhead);
431 while (1) {
432 vl = TAILQ_PREV(buffer->current_line, vhead, vlines);
433 if (vl == NULL || vl->parent != orig)
434 break;
435 buffer->current_line = vl;
440 if (buffer->current_line == NULL)
441 buffer->current_line = TAILQ_FIRST(&buffer->head);
443 if (buffer->top_line == NULL)
444 buffer->top_line = buffer->current_line;
446 return 1;
449 static void
450 line_prefix_and_text(struct vline *vl, char *buf, size_t len,
451 const char **prfx_ret, const char **text_ret)
453 int type, i, cont, width;
454 char *space, *t;
456 if ((*text_ret = vl->line) == NULL)
457 *text_ret = "";
459 cont = vl->flags & L_CONTINUATION;
460 type = vl->parent->type;
461 if (!cont)
462 *prfx_ret = line_prefixes[type].prfx1;
463 else
464 *prfx_ret = line_prefixes[type].prfx2;
466 space = vl->parent->data;
467 if (!emojify_link || type != LINE_LINK || space == NULL)
468 return;
470 if (cont) {
471 memset(buf, 0, len);
472 width = utf8_swidth_between(vl->parent->line, space);
473 for (i = 0; i < width + 1; ++i)
474 strlcat(buf, " ", len);
475 } else {
476 strlcpy(buf, *text_ret, len);
477 if ((t = strchr(buf, ' ')) != NULL)
478 *t = '\0';
479 strlcat(buf, " ", len);
481 /* skip the emoji */
482 *text_ret += (space - vl->parent->line) + 1;
485 *prfx_ret = buf;
488 static inline void
489 print_vline_descr(int width, WINDOW *window, struct vline *vl)
491 int x, y, goal;
493 if (vl->parent->type != LINE_COMPL &&
494 vl->parent->type != LINE_COMPL_CURRENT)
495 return;
497 if (vl->parent->alt == NULL)
498 return;
500 (void)y;
501 getyx(window, y, x);
503 goal = width/2;
504 if (goal <= x)
505 wprintw(window, " ");
506 for (; goal > x; ++x)
507 wprintw(window, " ");
509 wprintw(window, "%s", vl->parent->alt);
512 /*
513 * Core part of the rendering. It prints a vline starting from the
514 * current cursor position. Printing a vline consists of skipping
515 * `off' columns (for olivetti-mode), print the correct prefix (which
516 * may be the emoji in case of emojified links-lines), printing the
517 * text itself, filling until width - off and filling off columns
518 * again.
519 */
520 static void
521 print_vline(int off, int width, WINDOW *window, struct vline *vl)
523 /*
524 * Believe me or not, I've seen emoji ten code points long!
525 * That means, to stay large, 4*10 bytes + NUL.
526 */
527 char emojibuf[41] = {0};
528 const char *text, *prfx;
529 struct line_face *f;
530 int i, left, x, y;
532 f = &line_faces[vl->parent->type];
534 /* unused, set by getyx */
535 (void)y;
537 line_prefix_and_text(vl, emojibuf, sizeof(emojibuf), &prfx, &text);
539 wattr_on(window, body_face.left, NULL);
540 for (i = 0; i < off; i++)
541 waddch(window, ' ');
542 wattr_off(window, body_face.left, NULL);
544 wattr_on(window, f->prefix, NULL);
545 wprintw(window, "%s", prfx);
546 wattr_off(window, f->prefix, NULL);
548 wattr_on(window, f->text, NULL);
549 wprintw(window, "%s", text);
550 print_vline_descr(width, window, vl);
551 wattr_off(window, f->text, NULL);
553 getyx(window, y, x);
555 left = width - x;
557 wattr_on(window, f->trail, NULL);
558 for (i = 0; i < left - off; ++i)
559 waddch(window, ' ');
560 wattr_off(window, f->trail, NULL);
562 wattr_on(window, body_face.right, NULL);
563 for (i = 0; i < off; i++)
564 waddch(window, ' ');
565 wattr_off(window, body_face.right, NULL);
569 static void
570 redraw_tabline(void)
572 struct tab *tab;
573 size_t toskip, ots, tabwidth, space, x;
574 int current, y, truncated, pair;
575 const char *title;
576 char buf[25];
578 x = 0;
580 /* unused, but setted by a getyx */
581 (void)y;
583 tabwidth = sizeof(buf)+1;
584 space = COLS-2;
586 toskip = 0;
587 TAILQ_FOREACH(tab, &tabshead, tabs) {
588 toskip++;
589 if (tab == current_tab)
590 break;
593 if (toskip * tabwidth < space)
594 toskip = 0;
595 else {
596 ots = toskip;
597 toskip--;
598 while (toskip != 0 &&
599 (ots - toskip+1) * tabwidth < space)
600 toskip--;
603 werase(tabline);
604 wattr_on(tabline, tab_face.background, NULL);
605 wprintw(tabline, toskip == 0 ? " " : "<");
606 wattr_off(tabline, tab_face.background, NULL);
608 truncated = 0;
609 TAILQ_FOREACH(tab, &tabshead, tabs) {
610 if (truncated)
611 break;
612 if (toskip != 0) {
613 toskip--;
614 continue;
617 getyx(tabline, y, x);
618 if (x + sizeof(buf)+2 >= (size_t)COLS)
619 truncated = 1;
621 current = tab == current_tab;
623 if (*(title = tab->buffer.page.title) == '\0')
624 title = tab->hist_cur->h;
626 if (tab->flags & TAB_URGENT)
627 strlcpy(buf, "!", sizeof(buf));
628 else
629 strlcpy(buf, " ", sizeof(buf));
631 if (strlcat(buf, title, sizeof(buf)) >= sizeof(buf)) {
632 /* truncation happens */
633 strlcpy(&buf[sizeof(buf)-4], "...", 4);
634 } else {
635 /* pad with spaces */
636 while (strlcat(buf, " ", sizeof(buf)) < sizeof(buf))
637 /* nop */ ;
640 pair = current ? tab_face.current : tab_face.tab;
641 wattr_on(tabline, pair, NULL);
642 wprintw(tabline, "%s", buf);
643 wattr_off(tabline, pair, NULL);
645 wattr_on(tabline, tab_face.background, NULL);
646 if (TAILQ_NEXT(tab, tabs) != NULL)
647 wprintw(tabline, "│");
648 wattr_off(tabline, tab_face.background, NULL);
651 wattr_on(tabline, tab_face.background, NULL);
652 for (; x < (size_t)COLS; ++x)
653 waddch(tabline, ' ');
654 if (truncated)
655 mvwprintw(tabline, 0, COLS-1, ">");
656 wattr_off(tabline, tab_face.background, NULL);
659 /*
660 * Compute the first visible line around vl. Try to search forward
661 * until the end of the buffer; if a visible line is not found, search
662 * backward. Return NULL if no viable line was found.
663 */
664 struct vline *
665 adjust_line(struct vline *vl, struct buffer *buffer)
667 struct vline *t;
669 if (vl == NULL)
670 return NULL;
672 if (!(vl->parent->flags & L_HIDDEN))
673 return vl;
675 /* search forward */
676 for (t = vl;
677 t != NULL && t->parent->flags & L_HIDDEN;
678 t = TAILQ_NEXT(t, vlines))
679 ; /* nop */
681 if (t != NULL)
682 return t;
684 /* search backward */
685 for (t = vl;
686 t != NULL && t->parent->flags & L_HIDDEN;
687 t = TAILQ_PREV(t, vhead, vlines))
688 ; /* nop */
690 return t;
693 static void
694 redraw_window(WINDOW *win, int off, int height, int width, struct buffer *buffer)
696 struct vline *vl;
697 int l, onscreen;
699 restore_curs_x(buffer);
701 /*
702 * TODO: ignoring buffer->force_update and always
703 * re-rendering. In theory we can recompute the y position
704 * without a re-render, and optimize here. It's not the only
705 * optimisation possible here, wscrl wolud also be an
706 * interesting one.
707 */
709 again:
710 werase(win);
711 buffer->curs_y = 0;
713 if (TAILQ_EMPTY(&buffer->head))
714 goto end;
716 if (buffer->top_line == NULL)
717 buffer->top_line = TAILQ_FIRST(&buffer->head);
719 buffer->top_line = adjust_line(buffer->top_line, buffer);
720 if (buffer->top_line == NULL)
721 goto end;
723 buffer->current_line = adjust_line(buffer->current_line, buffer);
725 l = 0;
726 onscreen = 0;
727 for (vl = buffer->top_line; vl != NULL; vl = TAILQ_NEXT(vl, vlines)) {
728 if (vl->parent->flags & L_HIDDEN)
729 continue;
731 wmove(win, l, 0);
732 print_vline(off, width, win, vl);
734 if (vl == buffer->current_line)
735 onscreen = 1;
737 if (!onscreen)
738 buffer->curs_y++;
740 l++;
741 if (l == height)
742 break;
745 if (!onscreen) {
746 for (; vl != NULL; vl = TAILQ_NEXT(vl, vlines)) {
747 if (vl == buffer->current_line)
748 break;
749 if (vl->parent->flags & L_HIDDEN)
750 continue;
751 buffer->line_off++;
752 buffer->top_line = TAILQ_NEXT(buffer->top_line, vlines);
755 if (vl != NULL)
756 goto again;
759 buffer->last_line_off = buffer->line_off;
760 buffer->force_redraw = 0;
761 end:
762 wmove(win, buffer->curs_y, buffer->curs_x);
765 static void
766 redraw_help(void)
768 redraw_window(help, 0, help_lines, help_cols, &helpwin);
771 static void
772 redraw_body(struct tab *tab)
774 static struct tab *last_tab;
776 if (last_tab != tab)
777 tab->buffer.force_redraw =1;
778 last_tab = tab;
780 redraw_window(body, x_offset, body_lines, body_cols, &tab->buffer);
783 static inline char
784 trust_status_char(enum trust_state ts)
786 switch (ts) {
787 case TS_UNKNOWN: return 'u';
788 case TS_UNTRUSTED: return '!';
789 case TS_TEMP_TRUSTED: return '!';
790 case TS_TRUSTED: return 'v';
791 case TS_VERIFIED: return 'V';
792 default: return 'X';
796 static void
797 redraw_modeline(struct tab *tab)
799 double pct;
800 int x, y, max_x, max_y;
801 const char *mode = tab->buffer.page.name;
802 const char *spin = "-\\|/";
804 werase(modeline);
805 wattr_on(modeline, modeline_face.background, NULL);
806 wmove(modeline, 0, 0);
808 wprintw(modeline, "-%c%c %s ",
809 spin[tab->loading_anim_step],
810 trust_status_char(tab->trust),
811 mode == NULL ? "(none)" : mode);
813 pct = (tab->buffer.line_off + tab->buffer.curs_y) * 100.0
814 / tab->buffer.line_max;
816 if (tab->buffer.line_max <= (size_t)body_lines)
817 wprintw(modeline, "All ");
818 else if (tab->buffer.line_off == 0)
819 wprintw(modeline, "Top ");
820 else if (tab->buffer.line_off + body_lines >= tab->buffer.line_max)
821 wprintw(modeline, "Bottom ");
822 else
823 wprintw(modeline, "%.0f%% ", pct);
825 wprintw(modeline, "%d/%d %s ",
826 tab->buffer.line_off + tab->buffer.curs_y,
827 tab->buffer.line_max,
828 tab->hist_cur->h);
830 getyx(modeline, y, x);
831 getmaxyx(modeline, max_y, max_x);
833 (void)y;
834 (void)max_y;
836 for (; x < max_x; ++x)
837 waddstr(modeline, "-");
839 wattr_off(modeline, modeline_face.background, NULL);
842 static void
843 redraw_minibuffer(void)
845 wattr_on(echoarea, minibuffer_face.background, NULL);
846 werase(echoarea);
848 if (in_minibuffer)
849 do_redraw_minibuffer();
850 else
851 do_redraw_echoarea();
853 if (in_minibuffer == MB_COMPREAD)
854 do_redraw_minibuffer_compl();
856 wattr_off(echoarea, minibuffer_face.background, NULL);
859 static void
860 do_redraw_echoarea(void)
862 struct vline *vl;
864 if (ministate.curmesg != NULL)
865 wprintw(echoarea, "%s", ministate.curmesg);
866 else if (*keybuf != '\0')
867 waddstr(echoarea, keybuf);
868 else {
869 /* If nothing else, show the URL at point */
870 vl = current_tab->buffer.current_line;
871 if (vl != NULL && vl->parent->type == LINE_LINK)
872 waddstr(echoarea, vl->parent->alt);
876 static void
877 do_redraw_minibuffer(void)
879 size_t off_y, off_x = 0;
880 const char *start, *c;
882 /* unused, set by getyx */
883 (void)off_y;
885 wmove(echoarea, 0, 0);
887 if (in_minibuffer == MB_COMPREAD)
888 wprintw(echoarea, "(%2d) ",
889 ministate.compl.buffer.line_max);
891 wprintw(echoarea, "%s", ministate.prompt);
892 if (ministate.hist_cur != NULL)
893 wprintw(echoarea, "(%zu/%zu) ",
894 ministate.hist_off + 1,
895 ministate.history->len);
897 getyx(echoarea, off_y, off_x);
899 start = ministate.hist_cur != NULL
900 ? ministate.hist_cur->h
901 : ministate.buf;
902 c = utf8_nth(ministate.buffer.current_line->line,
903 ministate.buffer.cpoff);
904 while (utf8_swidth_between(start, c) > (size_t)COLS/2) {
905 start = utf8_next_cp(start);
908 waddstr(echoarea, start);
910 if (ministate.curmesg != NULL)
911 wprintw(echoarea, " [%s]", ministate.curmesg);
913 wmove(echoarea, 0, off_x + utf8_swidth_between(start, c));
916 static void
917 do_redraw_minibuffer_compl(void)
919 redraw_window(minibuffer, 0, 10, body_cols,
920 &ministate.compl.buffer);
923 /*
924 * Place the cursor in the right ncurses window. If soft is 1, use
925 * wnoutrefresh (which shouldn't cause any I/O); otherwise use
926 * wrefresh.
927 */
928 static void
929 place_cursor(int soft)
931 int (*touch)(WINDOW *);
933 if (soft)
934 touch = wnoutrefresh;
935 else
936 touch = wrefresh;
938 if (in_minibuffer) {
939 touch(body);
940 touch(echoarea);
941 } else {
942 touch(echoarea);
943 touch(body);
947 static void
948 redraw_tab(struct tab *tab)
950 if (too_small)
951 return;
953 if (side_window) {
954 redraw_help();
955 wnoutrefresh(help);
958 redraw_tabline();
959 redraw_body(tab);
960 redraw_modeline(tab);
961 redraw_minibuffer();
963 wnoutrefresh(tabline);
964 wnoutrefresh(modeline);
966 if (in_minibuffer == MB_COMPREAD)
967 wnoutrefresh(minibuffer);
969 place_cursor(1);
971 doupdate();
973 if (set_title)
974 dprintf(1, "\033]0;%s - Telescope\a",
975 current_tab->buffer.page.title);
978 static void
979 emit_help_item(char *prfx, void *fn)
981 struct line *l;
982 struct cmd *cmd;
984 for (cmd = cmds; cmd->cmd != NULL; ++cmd) {
985 if (fn == cmd->fn)
986 break;
988 assert(cmd != NULL);
990 if ((l = calloc(1, sizeof(*l))) == NULL)
991 abort();
993 l->type = LINE_TEXT;
994 l->alt = NULL;
996 asprintf(&l->line, "%s %s", prfx, cmd->cmd);
998 if (TAILQ_EMPTY(&helpwin.page.head))
999 TAILQ_INSERT_HEAD(&helpwin.page.head, l, lines);
1000 else
1001 TAILQ_INSERT_TAIL(&helpwin.page.head, l, lines);
1004 static void
1005 rec_compute_help(struct kmap *keymap, char *prfx, size_t len)
1007 struct keymap *k;
1008 char p[32];
1009 const char *kn;
1011 TAILQ_FOREACH(k, &keymap->m, keymaps) {
1012 strlcpy(p, prfx, sizeof(p));
1013 if (*p != '\0')
1014 strlcat(p, " ", sizeof(p));
1015 if (k->meta)
1016 strlcat(p, "M-", sizeof(p));
1017 if ((kn = unkbd(k->key)) != NULL)
1018 strlcat(p, kn, sizeof(p));
1019 else
1020 strlcat(p, keyname(k->key), sizeof(p));
1022 if (k->fn == NULL)
1023 rec_compute_help(&k->map, p, sizeof(p));
1024 else
1025 emit_help_item(p, k->fn);
1029 static void
1030 recompute_help(void)
1032 char p[32] = { 0 };
1034 empty_vlist(&helpwin);
1035 empty_linelist(&helpwin);
1036 rec_compute_help(current_map, p, sizeof(p));
1037 wrap_page(&helpwin, help_cols);
1040 void
1041 vmessage(const char *fmt, va_list ap)
1043 if (evtimer_pending(&clechoev, NULL))
1044 evtimer_del(&clechoev);
1046 free(ministate.curmesg);
1047 ministate.curmesg = NULL;
1049 if (fmt != NULL) {
1050 evtimer_set(&clechoev, handle_clear_echoarea, NULL);
1051 evtimer_add(&clechoev, &clechoev_timer);
1053 /* TODO: what to do if the allocation fails here? */
1054 if (vasprintf(&ministate.curmesg, fmt, ap) == -1)
1055 ministate.curmesg = NULL;
1058 redraw_minibuffer();
1059 place_cursor(0);
1062 void
1063 message(const char *fmt, ...)
1065 va_list ap;
1067 va_start(ap, fmt);
1068 vmessage(fmt, ap);
1069 va_end(ap);
1072 void
1073 start_loading_anim(struct tab *tab)
1075 if (tab->loading_anim)
1076 return;
1077 tab->loading_anim = 1;
1078 evtimer_set(&tab->loadingev, update_loading_anim, tab);
1079 evtimer_add(&tab->loadingev, &loadingev_timer);
1082 static void
1083 update_loading_anim(int fd, short ev, void *d)
1085 struct tab *tab = d;
1087 tab->loading_anim_step = (tab->loading_anim_step+1)%4;
1089 if (tab == current_tab) {
1090 redraw_modeline(tab);
1091 wrefresh(modeline);
1092 wrefresh(body);
1093 if (in_minibuffer)
1094 wrefresh(echoarea);
1097 evtimer_add(&tab->loadingev, &loadingev_timer);
1100 static void
1101 stop_loading_anim(struct tab *tab)
1103 if (!tab->loading_anim)
1104 return;
1105 evtimer_del(&tab->loadingev);
1106 tab->loading_anim = 0;
1107 tab->loading_anim_step = 0;
1109 if (tab != current_tab)
1110 return;
1112 redraw_modeline(tab);
1114 wrefresh(modeline);
1115 wrefresh(body);
1116 if (in_minibuffer)
1117 wrefresh(echoarea);
1120 void
1121 load_url_in_tab(struct tab *tab, const char *url)
1123 if (!operating) {
1124 load_url(tab, url);
1125 return;
1128 message("Loading %s...", url);
1129 start_loading_anim(tab);
1130 load_url(tab, url);
1132 redraw_tab(tab);
1135 void
1136 switch_to_tab(struct tab *tab)
1138 current_tab = tab;
1139 tab->flags &= ~TAB_URGENT;
1141 if (operating && tab->flags & TAB_LAZY)
1142 load_url_in_tab(tab, tab->hist_cur->h);
1145 unsigned int
1146 tab_new_id(void)
1148 return tab_counter++;
1151 struct tab *
1152 new_tab(const char *url)
1154 struct tab *tab;
1156 if ((tab = calloc(1, sizeof(*tab))) == NULL) {
1157 event_loopbreak();
1158 return NULL;
1160 tab->fd = -1;
1162 TAILQ_INIT(&tab->hist.head);
1164 TAILQ_INIT(&tab->buffer.head);
1166 tab->id = tab_new_id();
1167 if (!operating)
1168 tab->flags |= TAB_LAZY;
1169 switch_to_tab(tab);
1171 if (TAILQ_EMPTY(&tabshead))
1172 TAILQ_INSERT_HEAD(&tabshead, tab, tabs);
1173 else
1174 TAILQ_INSERT_TAIL(&tabshead, tab, tabs);
1176 load_url_in_tab(tab, url);
1177 return tab;
1180 int
1181 ui_print_colors(void)
1183 int colors = 0, pairs = 0, can_change = 0;
1184 int columns = 16, lines, color, i, j;
1186 initscr();
1187 if (has_colors()) {
1188 start_color();
1189 use_default_colors();
1191 colors = COLORS;
1192 pairs = COLOR_PAIRS;
1193 can_change = can_change_color();
1195 endwin();
1197 printf("Term info:\n");
1198 printf("TERM=%s COLORS=%d COLOR_PAIRS=%d can_change_colors=%d\n",
1199 getenv("TERM"), colors, pairs, can_change);
1200 printf("\n");
1202 if (colors == 0) {
1203 printf("No color support\n");
1204 return 0;
1207 printf("Available colors:\n\n");
1208 lines = (colors - 1) / columns + 1;
1209 color = 0;
1210 for (i = 0; i < lines; ++i) {
1211 for (j = 0; j < columns; ++j, ++color) {
1212 printf("\033[0;38;5;%dm %03d", color, color);
1214 printf("\n");
1217 printf("\033[0m");
1218 fflush(stdout);
1219 return 0;
1222 int
1223 ui_init()
1225 setlocale(LC_ALL, "");
1227 TAILQ_INIT(&eecmd_history.head);
1228 TAILQ_INIT(&ir_history.head);
1229 TAILQ_INIT(&lu_history.head);
1231 ministate.line.type = LINE_TEXT;
1232 ministate.vline.parent = &ministate.line;
1233 ministate.buffer.current_line = &ministate.vline;
1235 /* initialize help window */
1236 TAILQ_INIT(&helpwin.head);
1238 base_map = &global_map;
1239 current_map = &global_map;
1241 initscr();
1243 if (enable_colors) {
1244 if (has_colors()) {
1245 start_color();
1246 use_default_colors();
1247 } else
1248 enable_colors = 0;
1251 config_apply_style();
1253 raw();
1254 noecho();
1255 nonl();
1256 intrflush(stdscr, FALSE);
1258 if ((tabline = newwin(1, COLS, 0, 0)) == NULL)
1259 return 0;
1260 if ((body = newwin(LINES - 3, COLS, 1, 0)) == NULL)
1261 return 0;
1262 if ((modeline = newwin(1, COLS, LINES-2, 0)) == NULL)
1263 return 0;
1264 if ((echoarea = newwin(1, COLS, LINES-1, 0)) == NULL)
1265 return 0;
1266 if ((minibuffer = newwin(1, COLS, LINES-1, 0)) == NULL)
1267 return 0;
1268 if ((help = newwin(1, 1, 1, 0)) == NULL)
1269 return 0;
1271 body_lines = LINES-3;
1272 body_cols = COLS;
1274 wbkgd(body, body_face.body);
1275 wbkgd(echoarea, minibuffer_face.background);
1277 update_x_offset();
1279 keypad(body, TRUE);
1280 scrollok(body, FALSE);
1282 /* non-blocking input */
1283 wtimeout(body, 0);
1285 mvwprintw(body, 0, 0, "");
1288 * Dummy so libevent2 won't complain that no event_base is set
1289 * when checking event_pending for the first time
1291 evtimer_set(&clechoev, handle_clear_echoarea, NULL);
1292 evtimer_add(&clechoev, &clechoev_timer);
1293 evtimer_set(&resizeev, handle_resize, NULL);
1294 evtimer_add(&resizeev, &resize_timer);
1296 event_set(&stdioev, 0, EV_READ | EV_PERSIST, dispatch_stdio, NULL);
1297 event_add(&stdioev, NULL);
1299 signal_set(&winchev, SIGWINCH, handle_resize, NULL);
1300 signal_add(&winchev, NULL);
1302 return 1;
1305 void
1306 ui_main_loop(void)
1308 operating = 1;
1309 switch_to_tab(current_tab);
1310 redraw_tab(current_tab);
1312 event_dispatch();
1315 void
1316 ui_on_tab_loaded(struct tab *tab)
1318 stop_loading_anim(tab);
1319 message("Loaded %s", tab->hist_cur->h);
1321 redraw_tabline();
1322 wrefresh(tabline);
1323 place_cursor(0);
1326 void
1327 ui_on_tab_refresh(struct tab *tab)
1329 wrap_page(&tab->buffer, body_cols);
1330 if (tab == current_tab)
1331 redraw_tab(tab);
1332 else
1333 tab->flags |= TAB_URGENT;
1336 const char *
1337 ui_keyname(int k)
1339 return keyname(k);
1342 void
1343 ui_toggle_side_window(void)
1345 side_window = !side_window;
1346 if (side_window)
1347 recompute_help();
1350 * ugly hack, but otherwise the window doesn't get updated
1351 * until I call rearrange_windows a second time (e.g. via
1352 * C-l). I will be happy to know why something like this is
1353 * needed.
1355 rearrange_windows();
1356 rearrange_windows();
1359 void
1360 ui_schedule_redraw(void)
1362 should_rearrange_windows = 1;
1365 void
1366 ui_require_input(struct tab *tab, int hide)
1368 /* TODO: hard-switching to another tab is ugly */
1369 switch_to_tab(tab);
1371 enter_minibuffer(ir_self_insert, ir_select, exit_minibuffer,
1372 &ir_history, NULL, NULL);
1373 strlcpy(ministate.prompt, "Input required: ",
1374 sizeof(ministate.prompt));
1375 redraw_tab(tab);
1378 void
1379 ui_yornp(const char *prompt, void (*fn)(int, struct tab *),
1380 struct tab *data)
1382 yornp(prompt, fn, data);
1383 redraw_tab(current_tab);
1386 void
1387 ui_read(const char *prompt, void (*fn)(const char*, struct tab *),
1388 struct tab *data)
1390 completing_read(prompt, fn, data);
1391 redraw_tab(current_tab);
1394 void
1395 ui_suspend(void)
1397 endwin();
1399 kill(getpid(), SIGSTOP);
1401 refresh();
1402 clear();
1403 rearrange_windows();
1406 void
1407 ui_end(void)
1409 endwin();