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->top_line = buffer->top_line;
135 place->current_line = buffer->current_line;
136 place->cpoff = buffer->cpoff;
139 void
140 restore_excursion(struct excursion *place, struct buffer *buffer)
142 buffer->curs_x = place->curs_x;
143 buffer->curs_y = place->curs_y;
144 buffer->line_off = place->line_off;
145 buffer->top_line = place->top_line;
146 buffer->current_line = place->current_line;
147 buffer->cpoff = place->cpoff;
150 static void
151 restore_curs_x(struct buffer *buffer)
153 struct vline *vl;
154 const char *prfx;
156 vl = buffer->current_line;
157 if (vl == NULL || vl->line == NULL)
158 buffer->curs_x = buffer->cpoff = 0;
159 else if (vl->parent->data != NULL)
160 buffer->curs_x = utf8_snwidth(vl->parent->data+1, buffer->cpoff) + 1;
161 else
162 buffer->curs_x = utf8_snwidth(vl->line, buffer->cpoff);
164 buffer->curs_x += x_offset;
166 if (vl == NULL)
167 return;
169 if (vl->parent->data != NULL)
170 buffer->curs_x += utf8_swidth_between(vl->parent->line, vl->parent->data);
171 else {
172 prfx = line_prefixes[vl->parent->type].prfx1;
173 buffer->curs_x += utf8_swidth(prfx);
177 void
178 global_key_unbound(void)
180 message("%s is undefined", keybuf);
183 struct buffer *
184 current_buffer(void)
186 if (in_minibuffer)
187 return &ministate.buffer;
188 return &current_tab->buffer;
191 static int
192 readkey(void)
194 uint32_t state = 0;
196 if ((thiskey.key = wgetch(body)) == ERR)
197 return 0;
199 thiskey.meta = thiskey.key == 27;
200 if (thiskey.meta) {
201 thiskey.key = wgetch(body);
202 if (thiskey.key == ERR || thiskey.key == 27) {
203 thiskey.meta = 0;
204 thiskey.key = 27;
208 thiskey.cp = 0;
209 if ((unsigned int)thiskey.key < UINT8_MAX) {
210 while (1) {
211 if (!utf8_decode(&state, &thiskey.cp, (uint8_t)thiskey.key))
212 break;
213 if ((thiskey.key = wgetch(body)) == ERR) {
214 message("Error decoding user input");
215 return 0;
220 return 1;
223 static void
224 dispatch_stdio(int fd, short ev, void *d)
226 struct keymap *k;
227 const char *keyname;
228 char tmp[5] = {0};
230 /* TODO: schedule a redraw? */
231 if (too_small)
232 return;
234 if (!readkey())
235 return;
237 if (keybuf[0] != '\0')
238 strlcat(keybuf, " ", sizeof(keybuf));
239 if (thiskey.meta)
240 strlcat(keybuf, "M-", sizeof(keybuf));
241 if (thiskey.cp != 0) {
242 utf8_encode(thiskey.cp, tmp);
243 strlcat(keybuf, tmp, sizeof(keybuf));
244 } else if ((keyname = unkbd(thiskey.key)) != NULL) {
245 strlcat(keybuf, keyname, sizeof(keybuf));
246 } else {
247 tmp[0] = thiskey.key;
248 strlcat(keybuf, tmp, sizeof(keybuf));
251 TAILQ_FOREACH(k, &current_map->m, keymaps) {
252 if (k->meta == thiskey.meta &&
253 k->key == thiskey.key) {
254 if (k->fn == NULL)
255 current_map = &k->map;
256 else {
257 current_map = base_map;
258 strlcpy(keybuf, "", sizeof(keybuf));
259 k->fn(current_buffer());
261 goto done;
265 if (current_map->unhandled_input != NULL)
266 current_map->unhandled_input();
267 else
268 global_key_unbound();
270 strlcpy(keybuf, "", sizeof(keybuf));
271 current_map = base_map;
273 done:
274 if (side_window)
275 recompute_help();
277 if (should_rearrange_windows)
278 rearrange_windows();
279 redraw_tab(current_tab);
282 static void
283 handle_clear_echoarea(int fd, short ev, void *d)
285 free(ministate.curmesg);
286 ministate.curmesg = NULL;
288 redraw_minibuffer();
289 place_cursor(0);
292 static void
293 handle_resize(int sig, short ev, void *d)
295 if (event_pending(&resizeev, EV_TIMEOUT, NULL)) {
296 event_del(&resizeev);
298 evtimer_set(&resizeev, handle_resize_nodelay, NULL);
299 evtimer_add(&resizeev, &resize_timer);
302 static void
303 handle_resize_nodelay(int s, short ev, void *d)
305 endwin();
306 refresh();
307 clear();
309 rearrange_windows();
312 static void
313 rearrange_windows(void)
315 int lines;
317 should_rearrange_windows = 0;
319 lines = LINES;
321 if ((too_small = lines < 15)) {
322 erase();
323 printw("Window too small.");
324 refresh();
325 return;
328 /* move and resize the windows, in reverse order! */
330 if (in_minibuffer == MB_COMPREAD) {
331 mvwin(minibuffer, lines-10, 0);
332 wresize(minibuffer, 10, COLS);
333 lines -= 10;
335 wrap_page(&ministate.compl.buffer, COLS);
338 mvwin(echoarea, --lines, 0);
339 wresize(echoarea, 1, COLS);
341 mvwin(modeline, --lines, 0);
342 wresize(modeline, 1, COLS);
344 body_lines = --lines;
345 body_cols = COLS;
347 if (side_window) {
348 help_cols = 0.3 * COLS;
349 help_lines = lines;
350 mvwin(help, 1, 0);
351 wresize(help, help_lines, help_cols);
353 wrap_page(&helpwin, help_cols);
355 body_cols = COLS - help_cols - 1;
356 mvwin(body, 1, help_cols);
357 } else
358 mvwin(body, 1, 0);
360 update_x_offset();
361 wresize(body, body_lines, body_cols);
363 wresize(tabline, 1, COLS);
365 wrap_page(&current_tab->buffer, body_cols);
366 redraw_tab(current_tab);
369 static int
370 wrap_page(struct buffer *buffer, int width)
372 struct line *l;
373 const struct line *top_orig, *orig;
374 struct vline *vl;
375 int pre_width;
376 const char *prfx;
378 top_orig = buffer->top_line == NULL ? NULL : buffer->top_line->parent;
379 orig = buffer->current_line == NULL ? NULL : buffer->current_line->parent;
381 buffer->top_line = NULL;
382 buffer->current_line = NULL;
384 buffer->force_redraw = 1;
385 buffer->curs_y = 0;
386 buffer->line_off = 0;
388 empty_vlist(buffer);
390 TAILQ_FOREACH(l, &buffer->page.head, lines) {
391 prfx = line_prefixes[l->type].prfx1;
392 switch (l->type) {
393 case LINE_TEXT:
394 case LINE_LINK:
395 case LINE_TITLE_1:
396 case LINE_TITLE_2:
397 case LINE_TITLE_3:
398 case LINE_ITEM:
399 case LINE_QUOTE:
400 case LINE_PRE_START:
401 case LINE_PRE_END:
402 wrap_text(buffer, prfx, l, MIN(fill_column, width));
403 break;
404 case LINE_PRE_CONTENT:
405 if (olivetti_mode)
406 pre_width = MIN(fill_column, width);
407 else
408 pre_width = width;
409 hardwrap_text(buffer, l, pre_width);
410 break;
411 case LINE_COMPL:
412 case LINE_COMPL_CURRENT:
413 wrap_one(buffer, prfx, l, width);
414 break;
417 if (top_orig == l && buffer->top_line == NULL) {
418 buffer->line_off = buffer->line_max-1;
419 buffer->top_line = TAILQ_LAST(&buffer->head, vhead);
421 while (1) {
422 vl = TAILQ_PREV(buffer->top_line, vhead, vlines);
423 if (vl == NULL || vl->parent != orig)
424 break;
425 buffer->top_line = vl;
426 buffer->line_off--;
430 if (orig == l && buffer->current_line == NULL) {
431 buffer->current_line = TAILQ_LAST(&buffer->head, vhead);
433 while (1) {
434 vl = TAILQ_PREV(buffer->current_line, vhead, vlines);
435 if (vl == NULL || vl->parent != orig)
436 break;
437 buffer->current_line = vl;
442 if (buffer->current_line == NULL)
443 buffer->current_line = TAILQ_FIRST(&buffer->head);
445 if (buffer->top_line == NULL)
446 buffer->top_line = buffer->current_line;
448 return 1;
451 static void
452 line_prefix_and_text(struct vline *vl, char *buf, size_t len,
453 const char **prfx_ret, const char **text_ret)
455 int type, i, cont, width;
456 char *space, *t;
458 if ((*text_ret = vl->line) == NULL)
459 *text_ret = "";
461 cont = vl->flags & L_CONTINUATION;
462 type = vl->parent->type;
463 if (!cont)
464 *prfx_ret = line_prefixes[type].prfx1;
465 else
466 *prfx_ret = line_prefixes[type].prfx2;
468 space = vl->parent->data;
469 if (!emojify_link || type != LINE_LINK || space == NULL)
470 return;
472 if (cont) {
473 memset(buf, 0, len);
474 width = utf8_swidth_between(vl->parent->line, space);
475 for (i = 0; i < width + 1; ++i)
476 strlcat(buf, " ", len);
477 } else {
478 strlcpy(buf, *text_ret, len);
479 if ((t = strchr(buf, ' ')) != NULL)
480 *t = '\0';
481 strlcat(buf, " ", len);
483 /* skip the emoji */
484 *text_ret += (space - vl->parent->line) + 1;
487 *prfx_ret = buf;
490 static inline void
491 print_vline_descr(int width, WINDOW *window, struct vline *vl)
493 int x, y, goal;
495 if (vl->parent->type != LINE_COMPL &&
496 vl->parent->type != LINE_COMPL_CURRENT)
497 return;
499 if (vl->parent->alt == NULL)
500 return;
502 (void)y;
503 getyx(window, y, x);
505 goal = width/2;
506 if (goal <= x)
507 wprintw(window, " ");
508 for (; goal > x; ++x)
509 wprintw(window, " ");
511 wprintw(window, "%s", vl->parent->alt);
514 /*
515 * Core part of the rendering. It prints a vline starting from the
516 * current cursor position. Printing a vline consists of skipping
517 * `off' columns (for olivetti-mode), print the correct prefix (which
518 * may be the emoji in case of emojified links-lines), printing the
519 * text itself, filling until width - off and filling off columns
520 * again.
521 */
522 static void
523 print_vline(int off, int width, WINDOW *window, struct vline *vl)
525 /*
526 * Believe me or not, I've seen emoji ten code points long!
527 * That means, to stay large, 4*10 bytes + NUL.
528 */
529 char emojibuf[41] = {0};
530 const char *text, *prfx;
531 struct line_face *f;
532 int i, left, x, y;
534 f = &line_faces[vl->parent->type];
536 /* unused, set by getyx */
537 (void)y;
539 line_prefix_and_text(vl, emojibuf, sizeof(emojibuf), &prfx, &text);
541 wattr_on(window, body_face.left, NULL);
542 for (i = 0; i < off; i++)
543 waddch(window, ' ');
544 wattr_off(window, body_face.left, NULL);
546 wattr_on(window, f->prefix, NULL);
547 wprintw(window, "%s", prfx);
548 wattr_off(window, f->prefix, NULL);
550 wattr_on(window, f->text, NULL);
551 wprintw(window, "%s", text);
552 print_vline_descr(width, window, vl);
553 wattr_off(window, f->text, NULL);
555 getyx(window, y, x);
557 left = width - x;
559 wattr_on(window, f->trail, NULL);
560 for (i = 0; i < left - off; ++i)
561 waddch(window, ' ');
562 wattr_off(window, f->trail, NULL);
564 wattr_on(window, body_face.right, NULL);
565 for (i = 0; i < off; i++)
566 waddch(window, ' ');
567 wattr_off(window, body_face.right, NULL);
571 static void
572 redraw_tabline(void)
574 struct tab *tab;
575 size_t toskip, ots, tabwidth, space, x;
576 int current, y, truncated, pair;
577 const char *title;
578 char buf[25];
580 x = 0;
582 /* unused, but setted by a getyx */
583 (void)y;
585 tabwidth = sizeof(buf)+1;
586 space = COLS-2;
588 toskip = 0;
589 TAILQ_FOREACH(tab, &tabshead, tabs) {
590 toskip++;
591 if (tab == current_tab)
592 break;
595 if (toskip * tabwidth < space)
596 toskip = 0;
597 else {
598 ots = toskip;
599 toskip--;
600 while (toskip != 0 &&
601 (ots - toskip+1) * tabwidth < space)
602 toskip--;
605 werase(tabline);
606 wattr_on(tabline, tab_face.background, NULL);
607 wprintw(tabline, toskip == 0 ? " " : "<");
608 wattr_off(tabline, tab_face.background, NULL);
610 truncated = 0;
611 TAILQ_FOREACH(tab, &tabshead, tabs) {
612 if (truncated)
613 break;
614 if (toskip != 0) {
615 toskip--;
616 continue;
619 getyx(tabline, y, x);
620 if (x + sizeof(buf)+2 >= (size_t)COLS)
621 truncated = 1;
623 current = tab == current_tab;
625 if (*(title = tab->buffer.page.title) == '\0')
626 title = tab->hist_cur->h;
628 if (tab->flags & TAB_URGENT)
629 strlcpy(buf, "!", sizeof(buf));
630 else
631 strlcpy(buf, " ", sizeof(buf));
633 if (strlcat(buf, title, sizeof(buf)) >= sizeof(buf)) {
634 /* truncation happens */
635 strlcpy(&buf[sizeof(buf)-4], "...", 4);
636 } else {
637 /* pad with spaces */
638 while (strlcat(buf, " ", sizeof(buf)) < sizeof(buf))
639 /* nop */ ;
642 pair = current ? tab_face.current : tab_face.tab;
643 wattr_on(tabline, pair, NULL);
644 wprintw(tabline, "%s", buf);
645 wattr_off(tabline, pair, NULL);
647 wattr_on(tabline, tab_face.background, NULL);
648 if (TAILQ_NEXT(tab, tabs) != NULL)
649 wprintw(tabline, "│");
650 wattr_off(tabline, tab_face.background, NULL);
653 wattr_on(tabline, tab_face.background, NULL);
654 for (; x < (size_t)COLS; ++x)
655 waddch(tabline, ' ');
656 if (truncated)
657 mvwprintw(tabline, 0, COLS-1, ">");
658 wattr_off(tabline, tab_face.background, NULL);
661 /*
662 * Compute the first visible line around vl. Try to search forward
663 * until the end of the buffer; if a visible line is not found, search
664 * backward. Return NULL if no viable line was found.
665 */
666 struct vline *
667 adjust_line(struct vline *vl, struct buffer *buffer)
669 struct vline *t;
671 if (vl == NULL)
672 return NULL;
674 if (!(vl->parent->flags & L_HIDDEN))
675 return vl;
677 /* search forward */
678 for (t = vl;
679 t != NULL && t->parent->flags & L_HIDDEN;
680 t = TAILQ_NEXT(t, vlines))
681 ; /* nop */
683 if (t != NULL)
684 return t;
686 /* search backward */
687 for (t = vl;
688 t != NULL && t->parent->flags & L_HIDDEN;
689 t = TAILQ_PREV(t, vhead, vlines))
690 ; /* nop */
692 return t;
695 static void
696 redraw_window(WINDOW *win, int off, int height, int width, struct buffer *buffer)
698 struct vline *vl;
699 int l, onscreen;
701 restore_curs_x(buffer);
703 /*
704 * TODO: ignoring buffer->force_update and always
705 * re-rendering. In theory we can recompute the y position
706 * without a re-render, and optimize here. It's not the only
707 * optimisation possible here, wscrl wolud also be an
708 * interesting one.
709 */
711 again:
712 werase(win);
713 buffer->curs_y = 0;
715 if (TAILQ_EMPTY(&buffer->head))
716 goto end;
718 if (buffer->top_line == NULL)
719 buffer->top_line = TAILQ_FIRST(&buffer->head);
721 buffer->top_line = adjust_line(buffer->top_line, buffer);
722 if (buffer->top_line == NULL)
723 goto end;
725 buffer->current_line = adjust_line(buffer->current_line, buffer);
727 l = 0;
728 onscreen = 0;
729 for (vl = buffer->top_line; vl != NULL; vl = TAILQ_NEXT(vl, vlines)) {
730 if (vl->parent->flags & L_HIDDEN)
731 continue;
733 wmove(win, l, 0);
734 print_vline(off, width, win, vl);
736 if (vl == buffer->current_line)
737 onscreen = 1;
739 if (!onscreen)
740 buffer->curs_y++;
742 l++;
743 if (l == height)
744 break;
747 if (!onscreen) {
748 for (; vl != NULL; vl = TAILQ_NEXT(vl, vlines)) {
749 if (vl == buffer->current_line)
750 break;
751 if (vl->parent->flags & L_HIDDEN)
752 continue;
753 buffer->line_off++;
754 buffer->top_line = TAILQ_NEXT(buffer->top_line, vlines);
757 if (vl != NULL)
758 goto again;
761 buffer->last_line_off = buffer->line_off;
762 buffer->force_redraw = 0;
763 end:
764 wmove(win, buffer->curs_y, buffer->curs_x);
767 static void
768 redraw_help(void)
770 redraw_window(help, 0, help_lines, help_cols, &helpwin);
773 static void
774 redraw_body(struct tab *tab)
776 static struct tab *last_tab;
778 if (last_tab != tab)
779 tab->buffer.force_redraw =1;
780 last_tab = tab;
782 redraw_window(body, x_offset, body_lines, body_cols, &tab->buffer);
785 static inline char
786 trust_status_char(enum trust_state ts)
788 switch (ts) {
789 case TS_UNKNOWN: return 'u';
790 case TS_UNTRUSTED: return '!';
791 case TS_TEMP_TRUSTED: return '!';
792 case TS_TRUSTED: return 'v';
793 case TS_VERIFIED: return 'V';
794 default: return 'X';
798 static void
799 redraw_modeline(struct tab *tab)
801 double pct;
802 int x, y, max_x, max_y;
803 const char *mode = tab->buffer.page.name;
804 const char *spin = "-\\|/";
806 werase(modeline);
807 wattr_on(modeline, modeline_face.background, NULL);
808 wmove(modeline, 0, 0);
810 wprintw(modeline, "-%c%c %s ",
811 spin[tab->loading_anim_step],
812 trust_status_char(tab->trust),
813 mode == NULL ? "(none)" : mode);
815 pct = (tab->buffer.line_off + tab->buffer.curs_y) * 100.0
816 / tab->buffer.line_max;
818 if (tab->buffer.line_max <= (size_t)body_lines)
819 wprintw(modeline, "All ");
820 else if (tab->buffer.line_off == 0)
821 wprintw(modeline, "Top ");
822 else if (tab->buffer.line_off + body_lines >= tab->buffer.line_max)
823 wprintw(modeline, "Bottom ");
824 else
825 wprintw(modeline, "%.0f%% ", pct);
827 wprintw(modeline, "%d/%d %s ",
828 tab->buffer.line_off + tab->buffer.curs_y,
829 tab->buffer.line_max,
830 tab->hist_cur->h);
832 getyx(modeline, y, x);
833 getmaxyx(modeline, max_y, max_x);
835 (void)y;
836 (void)max_y;
838 for (; x < max_x; ++x)
839 waddstr(modeline, "-");
841 wattr_off(modeline, modeline_face.background, NULL);
844 static void
845 redraw_minibuffer(void)
847 wattr_on(echoarea, minibuffer_face.background, NULL);
848 werase(echoarea);
850 if (in_minibuffer)
851 do_redraw_minibuffer();
852 else
853 do_redraw_echoarea();
855 if (in_minibuffer == MB_COMPREAD)
856 do_redraw_minibuffer_compl();
858 wattr_off(echoarea, minibuffer_face.background, NULL);
861 static void
862 do_redraw_echoarea(void)
864 struct vline *vl;
866 if (ministate.curmesg != NULL)
867 wprintw(echoarea, "%s", ministate.curmesg);
868 else if (*keybuf != '\0')
869 waddstr(echoarea, keybuf);
870 else {
871 /* If nothing else, show the URL at point */
872 vl = current_tab->buffer.current_line;
873 if (vl != NULL && vl->parent->type == LINE_LINK)
874 waddstr(echoarea, vl->parent->alt);
878 static void
879 do_redraw_minibuffer(void)
881 size_t off_y, off_x = 0;
882 const char *start, *c;
884 /* unused, set by getyx */
885 (void)off_y;
887 wmove(echoarea, 0, 0);
889 if (in_minibuffer == MB_COMPREAD)
890 wprintw(echoarea, "(%2d) ",
891 ministate.compl.buffer.line_max);
893 wprintw(echoarea, "%s", ministate.prompt);
894 if (ministate.hist_cur != NULL)
895 wprintw(echoarea, "(%zu/%zu) ",
896 ministate.hist_off + 1,
897 ministate.history->len);
899 getyx(echoarea, off_y, off_x);
901 start = ministate.hist_cur != NULL
902 ? ministate.hist_cur->h
903 : ministate.buf;
904 c = utf8_nth(ministate.buffer.current_line->line,
905 ministate.buffer.cpoff);
906 while (utf8_swidth_between(start, c) > (size_t)COLS/2) {
907 start = utf8_next_cp(start);
910 waddstr(echoarea, start);
912 if (ministate.curmesg != NULL)
913 wprintw(echoarea, " [%s]", ministate.curmesg);
915 wmove(echoarea, 0, off_x + utf8_swidth_between(start, c));
918 static void
919 do_redraw_minibuffer_compl(void)
921 redraw_window(minibuffer, 0, 10, body_cols,
922 &ministate.compl.buffer);
925 /*
926 * Place the cursor in the right ncurses window. If soft is 1, use
927 * wnoutrefresh (which shouldn't cause any I/O); otherwise use
928 * wrefresh.
929 */
930 static void
931 place_cursor(int soft)
933 int (*touch)(WINDOW *);
935 if (soft)
936 touch = wnoutrefresh;
937 else
938 touch = wrefresh;
940 if (in_minibuffer) {
941 touch(body);
942 touch(echoarea);
943 } else {
944 touch(echoarea);
945 touch(body);
949 static void
950 redraw_tab(struct tab *tab)
952 if (too_small)
953 return;
955 if (side_window) {
956 redraw_help();
957 wnoutrefresh(help);
960 redraw_tabline();
961 redraw_body(tab);
962 redraw_modeline(tab);
963 redraw_minibuffer();
965 wnoutrefresh(tabline);
966 wnoutrefresh(modeline);
968 if (in_minibuffer == MB_COMPREAD)
969 wnoutrefresh(minibuffer);
971 place_cursor(1);
973 doupdate();
975 if (set_title)
976 dprintf(1, "\033]0;%s - Telescope\a",
977 current_tab->buffer.page.title);
980 static void
981 emit_help_item(char *prfx, void *fn)
983 struct line *l;
984 struct cmd *cmd;
986 for (cmd = cmds; cmd->cmd != NULL; ++cmd) {
987 if (fn == cmd->fn)
988 break;
990 assert(cmd != NULL);
992 if ((l = calloc(1, sizeof(*l))) == NULL)
993 abort();
995 l->type = LINE_TEXT;
996 l->alt = NULL;
998 asprintf(&l->line, "%s %s", prfx, cmd->cmd);
1000 if (TAILQ_EMPTY(&helpwin.page.head))
1001 TAILQ_INSERT_HEAD(&helpwin.page.head, l, lines);
1002 else
1003 TAILQ_INSERT_TAIL(&helpwin.page.head, l, lines);
1006 static void
1007 rec_compute_help(struct kmap *keymap, char *prfx, size_t len)
1009 struct keymap *k;
1010 char p[32];
1011 const char *kn;
1013 TAILQ_FOREACH(k, &keymap->m, keymaps) {
1014 strlcpy(p, prfx, sizeof(p));
1015 if (*p != '\0')
1016 strlcat(p, " ", sizeof(p));
1017 if (k->meta)
1018 strlcat(p, "M-", sizeof(p));
1019 if ((kn = unkbd(k->key)) != NULL)
1020 strlcat(p, kn, sizeof(p));
1021 else
1022 strlcat(p, keyname(k->key), sizeof(p));
1024 if (k->fn == NULL)
1025 rec_compute_help(&k->map, p, sizeof(p));
1026 else
1027 emit_help_item(p, k->fn);
1031 static void
1032 recompute_help(void)
1034 char p[32] = { 0 };
1036 empty_vlist(&helpwin);
1037 empty_linelist(&helpwin);
1038 rec_compute_help(current_map, p, sizeof(p));
1039 wrap_page(&helpwin, help_cols);
1042 void
1043 vmessage(const char *fmt, va_list ap)
1045 if (evtimer_pending(&clechoev, NULL))
1046 evtimer_del(&clechoev);
1048 free(ministate.curmesg);
1049 ministate.curmesg = NULL;
1051 if (fmt != NULL) {
1052 evtimer_set(&clechoev, handle_clear_echoarea, NULL);
1053 evtimer_add(&clechoev, &clechoev_timer);
1055 /* TODO: what to do if the allocation fails here? */
1056 if (vasprintf(&ministate.curmesg, fmt, ap) == -1)
1057 ministate.curmesg = NULL;
1060 redraw_minibuffer();
1061 place_cursor(0);
1064 void
1065 message(const char *fmt, ...)
1067 va_list ap;
1069 va_start(ap, fmt);
1070 vmessage(fmt, ap);
1071 va_end(ap);
1074 void
1075 start_loading_anim(struct tab *tab)
1077 if (tab->loading_anim)
1078 return;
1079 tab->loading_anim = 1;
1080 evtimer_set(&tab->loadingev, update_loading_anim, tab);
1081 evtimer_add(&tab->loadingev, &loadingev_timer);
1084 static void
1085 update_loading_anim(int fd, short ev, void *d)
1087 struct tab *tab = d;
1089 tab->loading_anim_step = (tab->loading_anim_step+1)%4;
1091 if (tab == current_tab) {
1092 redraw_modeline(tab);
1093 wrefresh(modeline);
1094 wrefresh(body);
1095 if (in_minibuffer)
1096 wrefresh(echoarea);
1099 evtimer_add(&tab->loadingev, &loadingev_timer);
1102 static void
1103 stop_loading_anim(struct tab *tab)
1105 if (!tab->loading_anim)
1106 return;
1107 evtimer_del(&tab->loadingev);
1108 tab->loading_anim = 0;
1109 tab->loading_anim_step = 0;
1111 if (tab != current_tab)
1112 return;
1114 redraw_modeline(tab);
1116 wrefresh(modeline);
1117 wrefresh(body);
1118 if (in_minibuffer)
1119 wrefresh(echoarea);
1122 void
1123 load_url_in_tab(struct tab *tab, const char *url)
1125 if (!operating) {
1126 load_url(tab, url);
1127 return;
1130 message("Loading %s...", url);
1131 start_loading_anim(tab);
1132 load_url(tab, url);
1134 redraw_tab(tab);
1137 void
1138 switch_to_tab(struct tab *tab)
1140 current_tab = tab;
1141 tab->flags &= ~TAB_URGENT;
1143 if (operating && tab->flags & TAB_LAZY)
1144 load_url_in_tab(tab, tab->hist_cur->h);
1147 unsigned int
1148 tab_new_id(void)
1150 return tab_counter++;
1153 struct tab *
1154 new_tab(const char *url)
1156 struct tab *tab;
1158 if ((tab = calloc(1, sizeof(*tab))) == NULL) {
1159 event_loopbreak();
1160 return NULL;
1162 tab->fd = -1;
1164 TAILQ_INIT(&tab->hist.head);
1166 TAILQ_INIT(&tab->buffer.head);
1168 tab->id = tab_new_id();
1169 if (!operating)
1170 tab->flags |= TAB_LAZY;
1171 switch_to_tab(tab);
1173 if (TAILQ_EMPTY(&tabshead))
1174 TAILQ_INSERT_HEAD(&tabshead, tab, tabs);
1175 else
1176 TAILQ_INSERT_TAIL(&tabshead, tab, tabs);
1178 load_url_in_tab(tab, url);
1179 return tab;
1182 int
1183 ui_print_colors(void)
1185 int colors = 0, pairs = 0, can_change = 0;
1186 int columns = 16, lines, color, i, j;
1188 initscr();
1189 if (has_colors()) {
1190 start_color();
1191 use_default_colors();
1193 colors = COLORS;
1194 pairs = COLOR_PAIRS;
1195 can_change = can_change_color();
1197 endwin();
1199 printf("Term info:\n");
1200 printf("TERM=%s COLORS=%d COLOR_PAIRS=%d can_change_colors=%d\n",
1201 getenv("TERM"), colors, pairs, can_change);
1202 printf("\n");
1204 if (colors == 0) {
1205 printf("No color support\n");
1206 return 0;
1209 printf("Available colors:\n\n");
1210 lines = (colors - 1) / columns + 1;
1211 color = 0;
1212 for (i = 0; i < lines; ++i) {
1213 for (j = 0; j < columns; ++j, ++color) {
1214 printf("\033[0;38;5;%dm %03d", color, color);
1216 printf("\n");
1219 printf("\033[0m");
1220 fflush(stdout);
1221 return 0;
1224 int
1225 ui_init()
1227 setlocale(LC_ALL, "");
1229 TAILQ_INIT(&eecmd_history.head);
1230 TAILQ_INIT(&ir_history.head);
1231 TAILQ_INIT(&lu_history.head);
1233 ministate.line.type = LINE_TEXT;
1234 ministate.vline.parent = &ministate.line;
1235 ministate.buffer.current_line = &ministate.vline;
1237 /* initialize help window */
1238 TAILQ_INIT(&helpwin.head);
1240 base_map = &global_map;
1241 current_map = &global_map;
1243 initscr();
1245 if (enable_colors) {
1246 if (has_colors()) {
1247 start_color();
1248 use_default_colors();
1249 } else
1250 enable_colors = 0;
1253 config_apply_style();
1255 raw();
1256 noecho();
1257 nonl();
1258 intrflush(stdscr, FALSE);
1260 if ((tabline = newwin(1, COLS, 0, 0)) == NULL)
1261 return 0;
1262 if ((body = newwin(LINES - 3, COLS, 1, 0)) == NULL)
1263 return 0;
1264 if ((modeline = newwin(1, COLS, LINES-2, 0)) == NULL)
1265 return 0;
1266 if ((echoarea = newwin(1, COLS, LINES-1, 0)) == NULL)
1267 return 0;
1268 if ((minibuffer = newwin(1, COLS, LINES-1, 0)) == NULL)
1269 return 0;
1270 if ((help = newwin(1, 1, 1, 0)) == NULL)
1271 return 0;
1273 body_lines = LINES-3;
1274 body_cols = COLS;
1276 wbkgd(body, body_face.body);
1277 wbkgd(echoarea, minibuffer_face.background);
1279 update_x_offset();
1281 keypad(body, TRUE);
1282 scrollok(body, FALSE);
1284 /* non-blocking input */
1285 wtimeout(body, 0);
1287 mvwprintw(body, 0, 0, "");
1290 * Dummy so libevent2 won't complain that no event_base is set
1291 * when checking event_pending for the first time
1293 evtimer_set(&clechoev, handle_clear_echoarea, NULL);
1294 evtimer_add(&clechoev, &clechoev_timer);
1295 evtimer_set(&resizeev, handle_resize, NULL);
1296 evtimer_add(&resizeev, &resize_timer);
1298 event_set(&stdioev, 0, EV_READ | EV_PERSIST, dispatch_stdio, NULL);
1299 event_add(&stdioev, NULL);
1301 signal_set(&winchev, SIGWINCH, handle_resize, NULL);
1302 signal_add(&winchev, NULL);
1304 return 1;
1307 void
1308 ui_main_loop(void)
1310 operating = 1;
1311 switch_to_tab(current_tab);
1312 redraw_tab(current_tab);
1314 event_dispatch();
1317 void
1318 ui_on_tab_loaded(struct tab *tab)
1320 stop_loading_anim(tab);
1321 message("Loaded %s", tab->hist_cur->h);
1323 redraw_tabline();
1324 wrefresh(tabline);
1325 place_cursor(0);
1328 void
1329 ui_on_tab_refresh(struct tab *tab)
1331 wrap_page(&tab->buffer, body_cols);
1332 if (tab == current_tab)
1333 redraw_tab(tab);
1334 else
1335 tab->flags |= TAB_URGENT;
1338 const char *
1339 ui_keyname(int k)
1341 return keyname(k);
1344 void
1345 ui_toggle_side_window(void)
1347 side_window = !side_window;
1348 if (side_window)
1349 recompute_help();
1352 * ugly hack, but otherwise the window doesn't get updated
1353 * until I call rearrange_windows a second time (e.g. via
1354 * C-l). I will be happy to know why something like this is
1355 * needed.
1357 rearrange_windows();
1358 rearrange_windows();
1361 void
1362 ui_schedule_redraw(void)
1364 should_rearrange_windows = 1;
1367 void
1368 ui_require_input(struct tab *tab, int hide)
1370 /* TODO: hard-switching to another tab is ugly */
1371 switch_to_tab(tab);
1373 enter_minibuffer(ir_self_insert, ir_select, exit_minibuffer,
1374 &ir_history, NULL, NULL);
1375 strlcpy(ministate.prompt, "Input required: ",
1376 sizeof(ministate.prompt));
1377 redraw_tab(tab);
1380 void
1381 ui_yornp(const char *prompt, void (*fn)(int, struct tab *),
1382 struct tab *data)
1384 yornp(prompt, fn, data);
1385 redraw_tab(current_tab);
1388 void
1389 ui_read(const char *prompt, void (*fn)(const char*, struct tab *),
1390 struct tab *data)
1392 completing_read(prompt, fn, data);
1393 redraw_tab(current_tab);
1396 void
1397 ui_suspend(void)
1399 endwin();
1401 kill(getpid(), SIGSTOP);
1403 refresh();
1404 clear();
1405 rearrange_windows();
1408 void
1409 ui_end(void)
1411 endwin();