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, *text;
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 text = vl->parent->data;
161 buffer->curs_x = utf8_snwidth(text + 1, buffer->cpoff) + 1;
162 } else
163 buffer->curs_x = utf8_snwidth(vl->line, buffer->cpoff);
165 buffer->curs_x += x_offset;
167 if (vl == NULL)
168 return;
170 if (vl->parent->data != NULL)
171 buffer->curs_x += utf8_swidth_between(vl->parent->line, vl->parent->data);
172 else {
173 prfx = line_prefixes[vl->parent->type].prfx1;
174 buffer->curs_x += utf8_swidth(prfx);
178 void
179 global_key_unbound(void)
181 message("%s is undefined", keybuf);
184 struct buffer *
185 current_buffer(void)
187 if (in_minibuffer)
188 return &ministate.buffer;
189 return &current_tab->buffer;
192 static int
193 readkey(void)
195 uint32_t state = 0;
197 if ((thiskey.key = wgetch(body)) == ERR)
198 return 0;
200 thiskey.meta = thiskey.key == 27;
201 if (thiskey.meta) {
202 thiskey.key = wgetch(body);
203 if (thiskey.key == ERR || thiskey.key == 27) {
204 thiskey.meta = 0;
205 thiskey.key = 27;
209 thiskey.cp = 0;
210 if ((unsigned int)thiskey.key < UINT8_MAX) {
211 while (1) {
212 if (!utf8_decode(&state, &thiskey.cp, (uint8_t)thiskey.key))
213 break;
214 if ((thiskey.key = wgetch(body)) == ERR) {
215 message("Error decoding user input");
216 return 0;
221 return 1;
224 static void
225 dispatch_stdio(int fd, short ev, void *d)
227 struct keymap *k;
228 const char *keyname;
229 char tmp[5] = {0};
231 /* TODO: schedule a redraw? */
232 if (too_small)
233 return;
235 if (!readkey())
236 return;
238 if (keybuf[0] != '\0')
239 strlcat(keybuf, " ", sizeof(keybuf));
240 if (thiskey.meta)
241 strlcat(keybuf, "M-", sizeof(keybuf));
242 if (thiskey.cp != 0) {
243 utf8_encode(thiskey.cp, tmp);
244 strlcat(keybuf, tmp, sizeof(keybuf));
245 } else if ((keyname = unkbd(thiskey.key)) != NULL) {
246 strlcat(keybuf, keyname, sizeof(keybuf));
247 } else {
248 tmp[0] = thiskey.key;
249 strlcat(keybuf, tmp, sizeof(keybuf));
252 TAILQ_FOREACH(k, &current_map->m, keymaps) {
253 if (k->meta == thiskey.meta &&
254 k->key == thiskey.key) {
255 if (k->fn == NULL)
256 current_map = &k->map;
257 else {
258 current_map = base_map;
259 strlcpy(keybuf, "", sizeof(keybuf));
260 k->fn(current_buffer());
262 goto done;
266 if (current_map->unhandled_input != NULL)
267 current_map->unhandled_input();
268 else
269 global_key_unbound();
271 strlcpy(keybuf, "", sizeof(keybuf));
272 current_map = base_map;
274 done:
275 if (side_window)
276 recompute_help();
278 if (should_rearrange_windows)
279 rearrange_windows();
280 redraw_tab(current_tab);
283 static void
284 handle_clear_echoarea(int fd, short ev, void *d)
286 free(ministate.curmesg);
287 ministate.curmesg = NULL;
289 redraw_minibuffer();
290 place_cursor(0);
293 static void
294 handle_resize(int sig, short ev, void *d)
296 if (event_pending(&resizeev, EV_TIMEOUT, NULL)) {
297 event_del(&resizeev);
299 evtimer_set(&resizeev, handle_resize_nodelay, NULL);
300 evtimer_add(&resizeev, &resize_timer);
303 static void
304 handle_resize_nodelay(int s, short ev, void *d)
306 endwin();
307 refresh();
308 clear();
310 rearrange_windows();
313 static void
314 rearrange_windows(void)
316 int lines;
318 should_rearrange_windows = 0;
320 lines = LINES;
322 if ((too_small = lines < 15)) {
323 erase();
324 printw("Window too small.");
325 refresh();
326 return;
329 /* move and resize the windows, in reverse order! */
331 if (in_minibuffer == MB_COMPREAD) {
332 mvwin(minibuffer, lines-10, 0);
333 wresize(minibuffer, 10, COLS);
334 lines -= 10;
336 wrap_page(&ministate.compl.buffer, COLS);
339 mvwin(echoarea, --lines, 0);
340 wresize(echoarea, 1, COLS);
342 mvwin(modeline, --lines, 0);
343 wresize(modeline, 1, COLS);
345 body_lines = --lines;
346 body_cols = COLS;
348 if (side_window) {
349 help_cols = 0.3 * COLS;
350 help_lines = lines;
351 mvwin(help, 1, 0);
352 wresize(help, help_lines, help_cols);
354 wrap_page(&helpwin, help_cols);
356 body_cols = COLS - help_cols - 1;
357 mvwin(body, 1, help_cols);
358 } else
359 mvwin(body, 1, 0);
361 update_x_offset();
362 wresize(body, body_lines, body_cols);
364 wresize(tabline, 1, COLS);
366 wrap_page(&current_tab->buffer, body_cols);
367 redraw_tab(current_tab);
370 static int
371 wrap_page(struct buffer *buffer, int width)
373 struct line *l;
374 const struct line *top_orig, *orig;
375 struct vline *vl;
376 int pre_width;
377 const char *prfx;
379 top_orig = buffer->top_line == NULL ? NULL : buffer->top_line->parent;
380 orig = buffer->current_line == NULL ? NULL : buffer->current_line->parent;
382 buffer->top_line = NULL;
383 buffer->current_line = NULL;
385 buffer->force_redraw = 1;
386 buffer->curs_y = 0;
387 buffer->line_off = 0;
389 empty_vlist(buffer);
391 TAILQ_FOREACH(l, &buffer->page.head, lines) {
392 prfx = line_prefixes[l->type].prfx1;
393 switch (l->type) {
394 case LINE_TEXT:
395 case LINE_LINK:
396 case LINE_TITLE_1:
397 case LINE_TITLE_2:
398 case LINE_TITLE_3:
399 case LINE_ITEM:
400 case LINE_QUOTE:
401 case LINE_PRE_START:
402 case LINE_PRE_END:
403 wrap_text(buffer, prfx, l, MIN(fill_column, width));
404 break;
405 case LINE_PRE_CONTENT:
406 if (olivetti_mode)
407 pre_width = MIN(fill_column, width);
408 else
409 pre_width = width;
410 hardwrap_text(buffer, l, pre_width);
411 break;
412 case LINE_COMPL:
413 case LINE_COMPL_CURRENT:
414 wrap_one(buffer, prfx, l, width);
415 break;
418 if (top_orig == l && buffer->top_line == NULL) {
419 buffer->line_off = buffer->line_max-1;
420 buffer->top_line = TAILQ_LAST(&buffer->head, vhead);
422 while (1) {
423 vl = TAILQ_PREV(buffer->top_line, vhead, vlines);
424 if (vl == NULL || vl->parent != orig)
425 break;
426 buffer->top_line = vl;
427 buffer->line_off--;
431 if (orig == l && buffer->current_line == NULL) {
432 buffer->current_line = TAILQ_LAST(&buffer->head, vhead);
434 while (1) {
435 vl = TAILQ_PREV(buffer->current_line, vhead, vlines);
436 if (vl == NULL || vl->parent != orig)
437 break;
438 buffer->current_line = vl;
443 if (buffer->current_line == NULL)
444 buffer->current_line = TAILQ_FIRST(&buffer->head);
446 if (buffer->top_line == NULL)
447 buffer->top_line = buffer->current_line;
449 return 1;
452 static void
453 line_prefix_and_text(struct vline *vl, char *buf, size_t len,
454 const char **prfx_ret, const char **text_ret)
456 int type, i, cont, width;
457 char *space, *t;
459 if ((*text_ret = vl->line) == NULL)
460 *text_ret = "";
462 cont = vl->flags & L_CONTINUATION;
463 type = vl->parent->type;
464 if (!cont)
465 *prfx_ret = line_prefixes[type].prfx1;
466 else
467 *prfx_ret = line_prefixes[type].prfx2;
469 space = vl->parent->data;
470 if (!emojify_link || type != LINE_LINK || space == NULL)
471 return;
473 if (cont) {
474 memset(buf, 0, len);
475 width = utf8_swidth_between(vl->parent->line, space);
476 for (i = 0; i < width + 1; ++i)
477 strlcat(buf, " ", len);
478 } else {
479 strlcpy(buf, *text_ret, len);
480 if ((t = strchr(buf, ' ')) != NULL)
481 *t = '\0';
482 strlcat(buf, " ", len);
484 /* skip the emoji */
485 *text_ret += (space - vl->parent->line) + 1;
488 *prfx_ret = buf;
491 static inline void
492 print_vline_descr(int width, WINDOW *window, struct vline *vl)
494 int x, y, goal;
496 if (vl->parent->type != LINE_COMPL &&
497 vl->parent->type != LINE_COMPL_CURRENT)
498 return;
500 if (vl->parent->alt == NULL)
501 return;
503 (void)y;
504 getyx(window, y, x);
506 goal = width/2;
507 if (goal <= x)
508 wprintw(window, " ");
509 for (; goal > x; ++x)
510 wprintw(window, " ");
512 wprintw(window, "%s", vl->parent->alt);
515 /*
516 * Core part of the rendering. It prints a vline starting from the
517 * current cursor position. Printing a vline consists of skipping
518 * `off' columns (for olivetti-mode), print the correct prefix (which
519 * may be the emoji in case of emojified links-lines), printing the
520 * text itself, filling until width - off and filling off columns
521 * again.
522 */
523 static void
524 print_vline(int off, int width, WINDOW *window, struct vline *vl)
526 /*
527 * Believe me or not, I've seen emoji ten code points long!
528 * That means, to stay large, 4*10 bytes + NUL.
529 */
530 char emojibuf[41] = {0};
531 const char *text, *prfx;
532 struct line_face *f;
533 int i, left, x, y;
535 f = &line_faces[vl->parent->type];
537 /* unused, set by getyx */
538 (void)y;
540 line_prefix_and_text(vl, emojibuf, sizeof(emojibuf), &prfx, &text);
542 wattr_on(window, body_face.left, NULL);
543 for (i = 0; i < off; i++)
544 waddch(window, ' ');
545 wattr_off(window, body_face.left, NULL);
547 wattr_on(window, f->prefix, NULL);
548 wprintw(window, "%s", prfx);
549 wattr_off(window, f->prefix, NULL);
551 wattr_on(window, f->text, NULL);
552 wprintw(window, "%s", text);
553 print_vline_descr(width, window, vl);
554 wattr_off(window, f->text, NULL);
556 getyx(window, y, x);
558 left = width - x;
560 wattr_on(window, f->trail, NULL);
561 for (i = 0; i < left - off; ++i)
562 waddch(window, ' ');
563 wattr_off(window, f->trail, NULL);
565 wattr_on(window, body_face.right, NULL);
566 for (i = 0; i < off; i++)
567 waddch(window, ' ');
568 wattr_off(window, body_face.right, NULL);
572 static void
573 redraw_tabline(void)
575 struct tab *tab;
576 size_t toskip, ots, tabwidth, space, x;
577 int current, y, truncated, pair;
578 const char *title;
579 char buf[25];
581 x = 0;
583 /* unused, but setted by a getyx */
584 (void)y;
586 tabwidth = sizeof(buf)+1;
587 space = COLS-2;
589 toskip = 0;
590 TAILQ_FOREACH(tab, &tabshead, tabs) {
591 toskip++;
592 if (tab == current_tab)
593 break;
596 if (toskip * tabwidth < space)
597 toskip = 0;
598 else {
599 ots = toskip;
600 toskip--;
601 while (toskip != 0 &&
602 (ots - toskip+1) * tabwidth < space)
603 toskip--;
606 werase(tabline);
607 wattr_on(tabline, tab_face.background, NULL);
608 wprintw(tabline, toskip == 0 ? " " : "<");
609 wattr_off(tabline, tab_face.background, NULL);
611 truncated = 0;
612 TAILQ_FOREACH(tab, &tabshead, tabs) {
613 if (truncated)
614 break;
615 if (toskip != 0) {
616 toskip--;
617 continue;
620 getyx(tabline, y, x);
621 if (x + sizeof(buf)+2 >= (size_t)COLS)
622 truncated = 1;
624 current = tab == current_tab;
626 if (*(title = tab->buffer.page.title) == '\0')
627 title = tab->hist_cur->h;
629 if (tab->flags & TAB_URGENT)
630 strlcpy(buf, "!", sizeof(buf));
631 else
632 strlcpy(buf, " ", sizeof(buf));
634 if (strlcat(buf, title, sizeof(buf)) >= sizeof(buf)) {
635 /* truncation happens */
636 strlcpy(&buf[sizeof(buf)-4], "...", 4);
637 } else {
638 /* pad with spaces */
639 while (strlcat(buf, " ", sizeof(buf)) < sizeof(buf))
640 /* nop */ ;
643 pair = current ? tab_face.current : tab_face.tab;
644 wattr_on(tabline, pair, NULL);
645 wprintw(tabline, "%s", buf);
646 wattr_off(tabline, pair, NULL);
648 wattr_on(tabline, tab_face.background, NULL);
649 if (TAILQ_NEXT(tab, tabs) != NULL)
650 wprintw(tabline, "│");
651 wattr_off(tabline, tab_face.background, NULL);
654 wattr_on(tabline, tab_face.background, NULL);
655 for (; x < (size_t)COLS; ++x)
656 waddch(tabline, ' ');
657 if (truncated)
658 mvwprintw(tabline, 0, COLS-1, ">");
659 wattr_off(tabline, tab_face.background, NULL);
662 /*
663 * Compute the first visible line around vl. Try to search forward
664 * until the end of the buffer; if a visible line is not found, search
665 * backward. Return NULL if no viable line was found.
666 */
667 struct vline *
668 adjust_line(struct vline *vl, struct buffer *buffer)
670 struct vline *t;
672 if (vl == NULL)
673 return NULL;
675 if (!(vl->parent->flags & L_HIDDEN))
676 return vl;
678 /* search forward */
679 for (t = vl;
680 t != NULL && t->parent->flags & L_HIDDEN;
681 t = TAILQ_NEXT(t, vlines))
682 ; /* nop */
684 if (t != NULL)
685 return t;
687 /* search backward */
688 for (t = vl;
689 t != NULL && t->parent->flags & L_HIDDEN;
690 t = TAILQ_PREV(t, vhead, vlines))
691 ; /* nop */
693 return t;
696 static void
697 redraw_window(WINDOW *win, int off, int height, int width, struct buffer *buffer)
699 struct vline *vl;
700 int l, onscreen;
702 restore_curs_x(buffer);
704 /*
705 * TODO: ignoring buffer->force_update and always
706 * re-rendering. In theory we can recompute the y position
707 * without a re-render, and optimize here. It's not the only
708 * optimisation possible here, wscrl wolud also be an
709 * interesting one.
710 */
712 again:
713 werase(win);
714 buffer->curs_y = 0;
716 if (TAILQ_EMPTY(&buffer->head))
717 goto end;
719 if (buffer->top_line == NULL)
720 buffer->top_line = TAILQ_FIRST(&buffer->head);
722 buffer->top_line = adjust_line(buffer->top_line, buffer);
723 if (buffer->top_line == NULL)
724 goto end;
726 buffer->current_line = adjust_line(buffer->current_line, buffer);
728 l = 0;
729 onscreen = 0;
730 for (vl = buffer->top_line; vl != NULL; vl = TAILQ_NEXT(vl, vlines)) {
731 if (vl->parent->flags & L_HIDDEN)
732 continue;
734 wmove(win, l, 0);
735 print_vline(off, width, win, vl);
737 if (vl == buffer->current_line)
738 onscreen = 1;
740 if (!onscreen)
741 buffer->curs_y++;
743 l++;
744 if (l == height)
745 break;
748 if (!onscreen) {
749 for (; vl != NULL; vl = TAILQ_NEXT(vl, vlines)) {
750 if (vl == buffer->current_line)
751 break;
752 if (vl->parent->flags & L_HIDDEN)
753 continue;
754 buffer->line_off++;
755 buffer->top_line = TAILQ_NEXT(buffer->top_line, vlines);
758 if (vl != NULL)
759 goto again;
762 buffer->last_line_off = buffer->line_off;
763 buffer->force_redraw = 0;
764 end:
765 wmove(win, buffer->curs_y, buffer->curs_x);
768 static void
769 redraw_help(void)
771 redraw_window(help, 0, help_lines, help_cols, &helpwin);
774 static void
775 redraw_body(struct tab *tab)
777 static struct tab *last_tab;
779 if (last_tab != tab)
780 tab->buffer.force_redraw =1;
781 last_tab = tab;
783 redraw_window(body, x_offset, body_lines, body_cols, &tab->buffer);
786 static inline char
787 trust_status_char(enum trust_state ts)
789 switch (ts) {
790 case TS_UNKNOWN: return 'u';
791 case TS_UNTRUSTED: return '!';
792 case TS_TEMP_TRUSTED: return '!';
793 case TS_TRUSTED: return 'v';
794 case TS_VERIFIED: return 'V';
795 default: return 'X';
799 static void
800 redraw_modeline(struct tab *tab)
802 double pct;
803 int x, y, max_x, max_y;
804 const char *mode = tab->buffer.page.name;
805 const char *spin = "-\\|/";
807 werase(modeline);
808 wattr_on(modeline, modeline_face.background, NULL);
809 wmove(modeline, 0, 0);
811 wprintw(modeline, "-%c%c %s ",
812 spin[tab->loading_anim_step],
813 trust_status_char(tab->trust),
814 mode == NULL ? "(none)" : mode);
816 pct = (tab->buffer.line_off + tab->buffer.curs_y) * 100.0
817 / tab->buffer.line_max;
819 if (tab->buffer.line_max <= (size_t)body_lines)
820 wprintw(modeline, "All ");
821 else if (tab->buffer.line_off == 0)
822 wprintw(modeline, "Top ");
823 else if (tab->buffer.line_off + body_lines >= tab->buffer.line_max)
824 wprintw(modeline, "Bottom ");
825 else
826 wprintw(modeline, "%.0f%% ", pct);
828 wprintw(modeline, "%d/%d %s ",
829 tab->buffer.line_off + tab->buffer.curs_y,
830 tab->buffer.line_max,
831 tab->hist_cur->h);
833 getyx(modeline, y, x);
834 getmaxyx(modeline, max_y, max_x);
836 (void)y;
837 (void)max_y;
839 for (; x < max_x; ++x)
840 waddstr(modeline, "-");
842 wattr_off(modeline, modeline_face.background, NULL);
845 static void
846 redraw_minibuffer(void)
848 wattr_on(echoarea, minibuffer_face.background, NULL);
849 werase(echoarea);
851 if (in_minibuffer)
852 do_redraw_minibuffer();
853 else
854 do_redraw_echoarea();
856 if (in_minibuffer == MB_COMPREAD)
857 do_redraw_minibuffer_compl();
859 wattr_off(echoarea, minibuffer_face.background, NULL);
862 static void
863 do_redraw_echoarea(void)
865 struct vline *vl;
867 if (ministate.curmesg != NULL)
868 wprintw(echoarea, "%s", ministate.curmesg);
869 else if (*keybuf != '\0')
870 waddstr(echoarea, keybuf);
871 else {
872 /* If nothing else, show the URL at point */
873 vl = current_tab->buffer.current_line;
874 if (vl != NULL && vl->parent->type == LINE_LINK)
875 waddstr(echoarea, vl->parent->alt);
879 static void
880 do_redraw_minibuffer(void)
882 size_t off_y, off_x = 0;
883 const char *start, *c;
885 /* unused, set by getyx */
886 (void)off_y;
888 wmove(echoarea, 0, 0);
890 if (in_minibuffer == MB_COMPREAD)
891 wprintw(echoarea, "(%2d) ",
892 ministate.compl.buffer.line_max);
894 wprintw(echoarea, "%s", ministate.prompt);
895 if (ministate.hist_cur != NULL)
896 wprintw(echoarea, "(%zu/%zu) ",
897 ministate.hist_off + 1,
898 ministate.history->len);
900 getyx(echoarea, off_y, off_x);
902 start = ministate.hist_cur != NULL
903 ? ministate.hist_cur->h
904 : ministate.buf;
905 c = utf8_nth(ministate.buffer.current_line->line,
906 ministate.buffer.cpoff);
907 while (utf8_swidth_between(start, c) > (size_t)COLS/2) {
908 start = utf8_next_cp(start);
911 waddstr(echoarea, start);
913 if (ministate.curmesg != NULL)
914 wprintw(echoarea, " [%s]", ministate.curmesg);
916 wmove(echoarea, 0, off_x + utf8_swidth_between(start, c));
919 static void
920 do_redraw_minibuffer_compl(void)
922 redraw_window(minibuffer, 0, 10, body_cols,
923 &ministate.compl.buffer);
926 /*
927 * Place the cursor in the right ncurses window. If soft is 1, use
928 * wnoutrefresh (which shouldn't cause any I/O); otherwise use
929 * wrefresh.
930 */
931 static void
932 place_cursor(int soft)
934 int (*touch)(WINDOW *);
936 if (soft)
937 touch = wnoutrefresh;
938 else
939 touch = wrefresh;
941 if (in_minibuffer) {
942 touch(body);
943 touch(echoarea);
944 } else {
945 touch(echoarea);
946 touch(body);
950 static void
951 redraw_tab(struct tab *tab)
953 if (too_small)
954 return;
956 if (side_window) {
957 redraw_help();
958 wnoutrefresh(help);
961 redraw_tabline();
962 redraw_body(tab);
963 redraw_modeline(tab);
964 redraw_minibuffer();
966 wnoutrefresh(tabline);
967 wnoutrefresh(modeline);
969 if (in_minibuffer == MB_COMPREAD)
970 wnoutrefresh(minibuffer);
972 place_cursor(1);
974 doupdate();
976 if (set_title)
977 dprintf(1, "\033]0;%s - Telescope\a",
978 current_tab->buffer.page.title);
981 static void
982 emit_help_item(char *prfx, void *fn)
984 struct line *l;
985 struct cmd *cmd;
987 for (cmd = cmds; cmd->cmd != NULL; ++cmd) {
988 if (fn == cmd->fn)
989 break;
991 assert(cmd != NULL);
993 if ((l = calloc(1, sizeof(*l))) == NULL)
994 abort();
996 l->type = LINE_TEXT;
997 l->alt = NULL;
999 asprintf(&l->line, "%s %s", prfx, cmd->cmd);
1001 if (TAILQ_EMPTY(&helpwin.page.head))
1002 TAILQ_INSERT_HEAD(&helpwin.page.head, l, lines);
1003 else
1004 TAILQ_INSERT_TAIL(&helpwin.page.head, l, lines);
1007 static void
1008 rec_compute_help(struct kmap *keymap, char *prfx, size_t len)
1010 struct keymap *k;
1011 char p[32];
1012 const char *kn;
1014 TAILQ_FOREACH(k, &keymap->m, keymaps) {
1015 strlcpy(p, prfx, sizeof(p));
1016 if (*p != '\0')
1017 strlcat(p, " ", sizeof(p));
1018 if (k->meta)
1019 strlcat(p, "M-", sizeof(p));
1020 if ((kn = unkbd(k->key)) != NULL)
1021 strlcat(p, kn, sizeof(p));
1022 else
1023 strlcat(p, keyname(k->key), sizeof(p));
1025 if (k->fn == NULL)
1026 rec_compute_help(&k->map, p, sizeof(p));
1027 else
1028 emit_help_item(p, k->fn);
1032 static void
1033 recompute_help(void)
1035 char p[32] = { 0 };
1037 empty_vlist(&helpwin);
1038 empty_linelist(&helpwin);
1039 rec_compute_help(current_map, p, sizeof(p));
1040 wrap_page(&helpwin, help_cols);
1043 void
1044 vmessage(const char *fmt, va_list ap)
1046 if (evtimer_pending(&clechoev, NULL))
1047 evtimer_del(&clechoev);
1049 free(ministate.curmesg);
1050 ministate.curmesg = NULL;
1052 if (fmt != NULL) {
1053 evtimer_set(&clechoev, handle_clear_echoarea, NULL);
1054 evtimer_add(&clechoev, &clechoev_timer);
1056 /* TODO: what to do if the allocation fails here? */
1057 if (vasprintf(&ministate.curmesg, fmt, ap) == -1)
1058 ministate.curmesg = NULL;
1061 redraw_minibuffer();
1062 place_cursor(0);
1065 void
1066 message(const char *fmt, ...)
1068 va_list ap;
1070 va_start(ap, fmt);
1071 vmessage(fmt, ap);
1072 va_end(ap);
1075 void
1076 start_loading_anim(struct tab *tab)
1078 if (tab->loading_anim)
1079 return;
1080 tab->loading_anim = 1;
1081 evtimer_set(&tab->loadingev, update_loading_anim, tab);
1082 evtimer_add(&tab->loadingev, &loadingev_timer);
1085 static void
1086 update_loading_anim(int fd, short ev, void *d)
1088 struct tab *tab = d;
1090 tab->loading_anim_step = (tab->loading_anim_step+1)%4;
1092 if (tab == current_tab) {
1093 redraw_modeline(tab);
1094 wrefresh(modeline);
1095 wrefresh(body);
1096 if (in_minibuffer)
1097 wrefresh(echoarea);
1100 evtimer_add(&tab->loadingev, &loadingev_timer);
1103 static void
1104 stop_loading_anim(struct tab *tab)
1106 if (!tab->loading_anim)
1107 return;
1108 evtimer_del(&tab->loadingev);
1109 tab->loading_anim = 0;
1110 tab->loading_anim_step = 0;
1112 if (tab != current_tab)
1113 return;
1115 redraw_modeline(tab);
1117 wrefresh(modeline);
1118 wrefresh(body);
1119 if (in_minibuffer)
1120 wrefresh(echoarea);
1123 void
1124 load_url_in_tab(struct tab *tab, const char *url)
1126 if (!operating) {
1127 load_url(tab, url);
1128 return;
1131 message("Loading %s...", url);
1132 start_loading_anim(tab);
1133 load_url(tab, url);
1135 redraw_tab(tab);
1138 void
1139 switch_to_tab(struct tab *tab)
1141 current_tab = tab;
1142 tab->flags &= ~TAB_URGENT;
1144 if (operating && tab->flags & TAB_LAZY)
1145 load_url_in_tab(tab, tab->hist_cur->h);
1148 unsigned int
1149 tab_new_id(void)
1151 return tab_counter++;
1154 struct tab *
1155 new_tab(const char *url)
1157 struct tab *tab;
1159 if ((tab = calloc(1, sizeof(*tab))) == NULL) {
1160 event_loopbreak();
1161 return NULL;
1163 tab->fd = -1;
1165 TAILQ_INIT(&tab->hist.head);
1167 TAILQ_INIT(&tab->buffer.head);
1169 tab->id = tab_new_id();
1170 if (!operating)
1171 tab->flags |= TAB_LAZY;
1172 switch_to_tab(tab);
1174 if (TAILQ_EMPTY(&tabshead))
1175 TAILQ_INSERT_HEAD(&tabshead, tab, tabs);
1176 else
1177 TAILQ_INSERT_TAIL(&tabshead, tab, tabs);
1179 load_url_in_tab(tab, url);
1180 return tab;
1183 int
1184 ui_print_colors(void)
1186 int colors = 0, pairs = 0, can_change = 0;
1187 int columns = 16, lines, color, i, j;
1189 initscr();
1190 if (has_colors()) {
1191 start_color();
1192 use_default_colors();
1194 colors = COLORS;
1195 pairs = COLOR_PAIRS;
1196 can_change = can_change_color();
1198 endwin();
1200 printf("Term info:\n");
1201 printf("TERM=%s COLORS=%d COLOR_PAIRS=%d can_change_colors=%d\n",
1202 getenv("TERM"), colors, pairs, can_change);
1203 printf("\n");
1205 if (colors == 0) {
1206 printf("No color support\n");
1207 return 0;
1210 printf("Available colors:\n\n");
1211 lines = (colors - 1) / columns + 1;
1212 color = 0;
1213 for (i = 0; i < lines; ++i) {
1214 for (j = 0; j < columns; ++j, ++color) {
1215 printf("\033[0;38;5;%dm %03d", color, color);
1217 printf("\n");
1220 printf("\033[0m");
1221 fflush(stdout);
1222 return 0;
1225 int
1226 ui_init()
1228 setlocale(LC_ALL, "");
1230 TAILQ_INIT(&eecmd_history.head);
1231 TAILQ_INIT(&ir_history.head);
1232 TAILQ_INIT(&lu_history.head);
1234 ministate.line.type = LINE_TEXT;
1235 ministate.vline.parent = &ministate.line;
1236 ministate.buffer.current_line = &ministate.vline;
1238 /* initialize help window */
1239 TAILQ_INIT(&helpwin.head);
1241 base_map = &global_map;
1242 current_map = &global_map;
1244 initscr();
1246 if (enable_colors) {
1247 if (has_colors()) {
1248 start_color();
1249 use_default_colors();
1250 } else
1251 enable_colors = 0;
1254 config_apply_style();
1256 raw();
1257 noecho();
1258 nonl();
1259 intrflush(stdscr, FALSE);
1261 if ((tabline = newwin(1, COLS, 0, 0)) == NULL)
1262 return 0;
1263 if ((body = newwin(LINES - 3, COLS, 1, 0)) == NULL)
1264 return 0;
1265 if ((modeline = newwin(1, COLS, LINES-2, 0)) == NULL)
1266 return 0;
1267 if ((echoarea = newwin(1, COLS, LINES-1, 0)) == NULL)
1268 return 0;
1269 if ((minibuffer = newwin(1, COLS, LINES-1, 0)) == NULL)
1270 return 0;
1271 if ((help = newwin(1, 1, 1, 0)) == NULL)
1272 return 0;
1274 body_lines = LINES-3;
1275 body_cols = COLS;
1277 wbkgd(body, body_face.body);
1278 wbkgd(echoarea, minibuffer_face.background);
1280 update_x_offset();
1282 keypad(body, TRUE);
1283 scrollok(body, FALSE);
1285 /* non-blocking input */
1286 wtimeout(body, 0);
1288 mvwprintw(body, 0, 0, "");
1291 * Dummy so libevent2 won't complain that no event_base is set
1292 * when checking event_pending for the first time
1294 evtimer_set(&clechoev, handle_clear_echoarea, NULL);
1295 evtimer_set(&resizeev, handle_resize, NULL);
1297 event_set(&stdioev, 0, EV_READ | EV_PERSIST, dispatch_stdio, NULL);
1298 event_add(&stdioev, NULL);
1300 signal_set(&winchev, SIGWINCH, handle_resize, NULL);
1301 signal_add(&winchev, NULL);
1303 return 1;
1306 void
1307 ui_main_loop(void)
1309 operating = 1;
1310 switch_to_tab(current_tab);
1311 redraw_tab(current_tab);
1313 event_dispatch();
1316 void
1317 ui_on_tab_loaded(struct tab *tab)
1319 stop_loading_anim(tab);
1320 message("Loaded %s", tab->hist_cur->h);
1322 redraw_tabline();
1323 wrefresh(tabline);
1324 place_cursor(0);
1327 void
1328 ui_on_tab_refresh(struct tab *tab)
1330 wrap_page(&tab->buffer, body_cols);
1331 if (tab == current_tab)
1332 redraw_tab(tab);
1333 else
1334 tab->flags |= TAB_URGENT;
1337 const char *
1338 ui_keyname(int k)
1340 return keyname(k);
1343 void
1344 ui_toggle_side_window(void)
1346 side_window = !side_window;
1347 if (side_window)
1348 recompute_help();
1351 * ugly hack, but otherwise the window doesn't get updated
1352 * until I call rearrange_windows a second time (e.g. via
1353 * C-l). I will be happy to know why something like this is
1354 * needed.
1356 rearrange_windows();
1357 rearrange_windows();
1360 void
1361 ui_schedule_redraw(void)
1363 should_rearrange_windows = 1;
1366 void
1367 ui_require_input(struct tab *tab, int hide)
1369 /* TODO: hard-switching to another tab is ugly */
1370 switch_to_tab(tab);
1372 enter_minibuffer(ir_self_insert, ir_select, exit_minibuffer,
1373 &ir_history, NULL, NULL);
1374 strlcpy(ministate.prompt, "Input required: ",
1375 sizeof(ministate.prompt));
1376 redraw_tab(tab);
1379 void
1380 ui_yornp(const char *prompt, void (*fn)(int, struct tab *),
1381 struct tab *data)
1383 yornp(prompt, fn, data);
1384 redraw_tab(current_tab);
1387 void
1388 ui_read(const char *prompt, void (*fn)(const char*, struct tab *),
1389 struct tab *data)
1391 completing_read(prompt, fn, data);
1392 redraw_tab(current_tab);
1395 void
1396 ui_suspend(void)
1398 endwin();
1400 kill(getpid(), SIGSTOP);
1402 refresh();
1403 clear();
1404 rearrange_windows();
1407 void
1408 ui_end(void)
1410 endwin();