Replace screen-update action with noop action named "none"
[tig] / tig.c
1 /* Copyright (c) 2006 Jonas Fonseca <fonseca@diku.dk>
2 *
3 * This program is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU General Public License as
5 * published by the Free Software Foundation; either version 2 of
6 * the License, or (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 */
13
14 #ifndef VERSION
15 #define VERSION "tig-0.4.git"
16 #endif
17
18 #ifndef DEBUG
19 #define NDEBUG
20 #endif
21
22 #include <assert.h>
23 #include <errno.h>
24 #include <ctype.h>
25 #include <signal.h>
26 #include <stdarg.h>
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <unistd.h>
31 #include <time.h>
32
33 #include <locale.h>
34 #include <langinfo.h>
35 #include <iconv.h>
36
37 #include <curses.h>
38
39 #if __GNUC__ >= 3
40 #define __NORETURN __attribute__((__noreturn__))
41 #else
42 #define __NORETURN
43 #endif
44
45 static void __NORETURN die(const char *err, ...);
46 static void report(const char *msg, ...);
47 static int read_properties(FILE *pipe, const char *separators, int (*read)(char *, int, char *, int));
48 static void set_nonblocking_input(bool loading);
49 static size_t utf8_length(const char *string, size_t max_width, int *coloffset, int *trimmed);
50
51 #define ABS(x) ((x) >= 0 ? (x) : -(x))
52 #define MIN(x, y) ((x) < (y) ? (x) : (y))
53
54 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
55 #define STRING_SIZE(x) (sizeof(x) - 1)
56
57 #define SIZEOF_STR 1024 /* Default string size. */
58 #define SIZEOF_REF 256 /* Size of symbolic or SHA1 ID. */
59 #define SIZEOF_REVGRAPH 19 /* Size of revision ancestry graphics. */
60
61 /* This color name can be used to refer to the default term colors. */
62 #define COLOR_DEFAULT (-1)
63
64 #define ICONV_NONE ((iconv_t) -1)
65
66 /* The format and size of the date column in the main view. */
67 #define DATE_FORMAT "%Y-%m-%d %H:%M"
68 #define DATE_COLS STRING_SIZE("2006-04-29 14:21 ")
69
70 #define AUTHOR_COLS 20
71
72 /* The default interval between line numbers. */
73 #define NUMBER_INTERVAL 1
74
75 #define TABSIZE 8
76
77 #define SCALE_SPLIT_VIEW(height) ((height) * 2 / 3)
78
79 #define TIG_LS_REMOTE \
80 "git ls-remote . 2>/dev/null"
81
82 #define TIG_DIFF_CMD \
83 "git show --root --patch-with-stat --find-copies-harder -B -C %s 2>/dev/null"
84
85 #define TIG_LOG_CMD \
86 "git log --cc --stat -n100 %s 2>/dev/null"
87
88 #define TIG_MAIN_CMD \
89 "git log --topo-order --pretty=raw %s 2>/dev/null"
90
91 /* XXX: Needs to be defined to the empty string. */
92 #define TIG_HELP_CMD ""
93 #define TIG_PAGER_CMD ""
94
95 /* Some ascii-shorthands fitted into the ncurses namespace. */
96 #define KEY_TAB '\t'
97 #define KEY_RETURN '\r'
98 #define KEY_ESC 27
99
100
101 struct ref {
102 char *name; /* Ref name; tag or head names are shortened. */
103 char id[41]; /* Commit SHA1 ID */
104 unsigned int tag:1; /* Is it a tag? */
105 unsigned int next:1; /* For ref lists: are there more refs? */
106 };
107
108 static struct ref **get_refs(char *id);
109
110 struct int_map {
111 const char *name;
112 int namelen;
113 int value;
114 };
115
116 static int
117 set_from_int_map(struct int_map *map, size_t map_size,
118 int *value, const char *name, int namelen)
119 {
120
121 int i;
122
123 for (i = 0; i < map_size; i++)
124 if (namelen == map[i].namelen &&
125 !strncasecmp(name, map[i].name, namelen)) {
126 *value = map[i].value;
127 return OK;
128 }
129
130 return ERR;
131 }
132
133
134 /*
135 * String helpers
136 */
137
138 static inline void
139 string_ncopy(char *dst, const char *src, int dstlen)
140 {
141 strncpy(dst, src, dstlen - 1);
142 dst[dstlen - 1] = 0;
143
144 }
145
146 /* Shorthand for safely copying into a fixed buffer. */
147 #define string_copy(dst, src) \
148 string_ncopy(dst, src, sizeof(dst))
149
150 static char *
151 chomp_string(char *name)
152 {
153 int namelen;
154
155 while (isspace(*name))
156 name++;
157
158 namelen = strlen(name) - 1;
159 while (namelen > 0 && isspace(name[namelen]))
160 name[namelen--] = 0;
161
162 return name;
163 }
164
165 static bool
166 string_nformat(char *buf, size_t bufsize, int *bufpos, const char *fmt, ...)
167 {
168 va_list args;
169 int pos = bufpos ? *bufpos : 0;
170
171 va_start(args, fmt);
172 pos += vsnprintf(buf + pos, bufsize - pos, fmt, args);
173 va_end(args);
174
175 if (bufpos)
176 *bufpos = pos;
177
178 return pos >= bufsize ? FALSE : TRUE;
179 }
180
181 #define string_format(buf, fmt, args...) \
182 string_nformat(buf, sizeof(buf), NULL, fmt, args)
183
184 #define string_format_from(buf, from, fmt, args...) \
185 string_nformat(buf, sizeof(buf), from, fmt, args)
186
187 static int
188 string_enum_compare(const char *str1, const char *str2, int len)
189 {
190 size_t i;
191
192 #define string_enum_sep(x) ((x) == '-' || (x) == '_' || (x) == '.')
193
194 /* Diff-Header == DIFF_HEADER */
195 for (i = 0; i < len; i++) {
196 if (toupper(str1[i]) == toupper(str2[i]))
197 continue;
198
199 if (string_enum_sep(str1[i]) &&
200 string_enum_sep(str2[i]))
201 continue;
202
203 return str1[i] - str2[i];
204 }
205
206 return 0;
207 }
208
209 /* Shell quoting
210 *
211 * NOTE: The following is a slightly modified copy of the git project's shell
212 * quoting routines found in the quote.c file.
213 *
214 * Help to copy the thing properly quoted for the shell safety. any single
215 * quote is replaced with '\'', any exclamation point is replaced with '\!',
216 * and the whole thing is enclosed in a
217 *
218 * E.g.
219 * original sq_quote result
220 * name ==> name ==> 'name'
221 * a b ==> a b ==> 'a b'
222 * a'b ==> a'\''b ==> 'a'\''b'
223 * a!b ==> a'\!'b ==> 'a'\!'b'
224 */
225
226 static size_t
227 sq_quote(char buf[SIZEOF_STR], size_t bufsize, const char *src)
228 {
229 char c;
230
231 #define BUFPUT(x) do { if (bufsize < SIZEOF_STR) buf[bufsize++] = (x); } while (0)
232
233 BUFPUT('\'');
234 while ((c = *src++)) {
235 if (c == '\'' || c == '!') {
236 BUFPUT('\'');
237 BUFPUT('\\');
238 BUFPUT(c);
239 BUFPUT('\'');
240 } else {
241 BUFPUT(c);
242 }
243 }
244 BUFPUT('\'');
245
246 return bufsize;
247 }
248
249
250 /*
251 * User requests
252 */
253
254 #define REQ_INFO \
255 /* XXX: Keep the view request first and in sync with views[]. */ \
256 REQ_GROUP("View switching") \
257 REQ_(VIEW_MAIN, "Show main view"), \
258 REQ_(VIEW_DIFF, "Show diff view"), \
259 REQ_(VIEW_LOG, "Show log view"), \
260 REQ_(VIEW_HELP, "Show help page"), \
261 REQ_(VIEW_PAGER, "Show pager view"), \
262 \
263 REQ_GROUP("View manipulation") \
264 REQ_(ENTER, "Enter current line and scroll"), \
265 REQ_(NEXT, "Move to next"), \
266 REQ_(PREVIOUS, "Move to previous"), \
267 REQ_(VIEW_NEXT, "Move focus to next view"), \
268 REQ_(VIEW_CLOSE, "Close the current view"), \
269 REQ_(QUIT, "Close all views and quit"), \
270 \
271 REQ_GROUP("Cursor navigation") \
272 REQ_(MOVE_UP, "Move cursor one line up"), \
273 REQ_(MOVE_DOWN, "Move cursor one line down"), \
274 REQ_(MOVE_PAGE_DOWN, "Move cursor one page down"), \
275 REQ_(MOVE_PAGE_UP, "Move cursor one page up"), \
276 REQ_(MOVE_FIRST_LINE, "Move cursor to first line"), \
277 REQ_(MOVE_LAST_LINE, "Move cursor to last line"), \
278 \
279 REQ_GROUP("Scrolling") \
280 REQ_(SCROLL_LINE_UP, "Scroll one line up"), \
281 REQ_(SCROLL_LINE_DOWN, "Scroll one line down"), \
282 REQ_(SCROLL_PAGE_UP, "Scroll one page up"), \
283 REQ_(SCROLL_PAGE_DOWN, "Scroll one page down"), \
284 \
285 REQ_GROUP("Misc") \
286 REQ_(NONE, "Do nothing"), \
287 REQ_(PROMPT, "Bring up the prompt"), \
288 REQ_(SCREEN_REDRAW, "Redraw the screen"), \
289 REQ_(SCREEN_RESIZE, "Resize the screen"), \
290 REQ_(SHOW_VERSION, "Show version information"), \
291 REQ_(STOP_LOADING, "Stop all loading views"), \
292 REQ_(TOGGLE_LINENO, "Toggle line numbers"), \
293 REQ_(TOGGLE_REV_GRAPH, "Toggle revision graph visualization")
294
295
296 /* User action requests. */
297 enum request {
298 #define REQ_GROUP(help)
299 #define REQ_(req, help) REQ_##req
300
301 /* Offset all requests to avoid conflicts with ncurses getch values. */
302 REQ_OFFSET = KEY_MAX + 1,
303 REQ_INFO,
304 REQ_UNKNOWN,
305
306 #undef REQ_GROUP
307 #undef REQ_
308 };
309
310 struct request_info {
311 enum request request;
312 char *name;
313 int namelen;
314 char *help;
315 };
316
317 static struct request_info req_info[] = {
318 #define REQ_GROUP(help) { 0, NULL, 0, (help) },
319 #define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
320 REQ_INFO
321 #undef REQ_GROUP
322 #undef REQ_
323 };
324
325 static enum request
326 get_request(const char *name)
327 {
328 int namelen = strlen(name);
329 int i;
330
331 for (i = 0; i < ARRAY_SIZE(req_info); i++)
332 if (req_info[i].namelen == namelen &&
333 !string_enum_compare(req_info[i].name, name, namelen))
334 return req_info[i].request;
335
336 return REQ_UNKNOWN;
337 }
338
339
340 /*
341 * Options
342 */
343
344 static const char usage[] =
345 VERSION " (" __DATE__ ")\n"
346 "\n"
347 "Usage: tig [options]\n"
348 " or: tig [options] [--] [git log options]\n"
349 " or: tig [options] log [git log options]\n"
350 " or: tig [options] diff [git diff options]\n"
351 " or: tig [options] show [git show options]\n"
352 " or: tig [options] < [git command output]\n"
353 "\n"
354 "Options:\n"
355 " -l Start up in log view\n"
356 " -d Start up in diff view\n"
357 " -n[I], --line-number[=I] Show line numbers with given interval\n"
358 " -b[N], --tab-size[=N] Set number of spaces for tab expansion\n"
359 " -- Mark end of tig options\n"
360 " -v, --version Show version and exit\n"
361 " -h, --help Show help message and exit\n";
362
363 /* Option and state variables. */
364 static bool opt_line_number = FALSE;
365 static bool opt_rev_graph = TRUE;
366 static int opt_num_interval = NUMBER_INTERVAL;
367 static int opt_tab_size = TABSIZE;
368 static enum request opt_request = REQ_VIEW_MAIN;
369 static char opt_cmd[SIZEOF_STR] = "";
370 static FILE *opt_pipe = NULL;
371 static char opt_encoding[20] = "UTF-8";
372 static bool opt_utf8 = TRUE;
373 static char opt_codeset[20] = "UTF-8";
374 static iconv_t opt_iconv = ICONV_NONE;
375
376 enum option_type {
377 OPT_NONE,
378 OPT_INT,
379 };
380
381 static bool
382 check_option(char *opt, char short_name, char *name, enum option_type type, ...)
383 {
384 va_list args;
385 char *value = "";
386 int *number;
387
388 if (opt[0] != '-')
389 return FALSE;
390
391 if (opt[1] == '-') {
392 int namelen = strlen(name);
393
394 opt += 2;
395
396 if (strncmp(opt, name, namelen))
397 return FALSE;
398
399 if (opt[namelen] == '=')
400 value = opt + namelen + 1;
401
402 } else {
403 if (!short_name || opt[1] != short_name)
404 return FALSE;
405 value = opt + 2;
406 }
407
408 va_start(args, type);
409 if (type == OPT_INT) {
410 number = va_arg(args, int *);
411 if (isdigit(*value))
412 *number = atoi(value);
413 }
414 va_end(args);
415
416 return TRUE;
417 }
418
419 /* Returns the index of log or diff command or -1 to exit. */
420 static bool
421 parse_options(int argc, char *argv[])
422 {
423 int i;
424
425 for (i = 1; i < argc; i++) {
426 char *opt = argv[i];
427
428 if (!strcmp(opt, "-l")) {
429 opt_request = REQ_VIEW_LOG;
430 continue;
431 }
432
433 if (!strcmp(opt, "-d")) {
434 opt_request = REQ_VIEW_DIFF;
435 continue;
436 }
437
438 if (check_option(opt, 'n', "line-number", OPT_INT, &opt_num_interval)) {
439 opt_line_number = TRUE;
440 continue;
441 }
442
443 if (check_option(opt, 'b', "tab-size", OPT_INT, &opt_tab_size)) {
444 opt_tab_size = MIN(opt_tab_size, TABSIZE);
445 continue;
446 }
447
448 if (check_option(opt, 'v', "version", OPT_NONE)) {
449 printf("tig version %s\n", VERSION);
450 return FALSE;
451 }
452
453 if (check_option(opt, 'h', "help", OPT_NONE)) {
454 printf(usage);
455 return FALSE;
456 }
457
458 if (!strcmp(opt, "--")) {
459 i++;
460 break;
461 }
462
463 if (!strcmp(opt, "log") ||
464 !strcmp(opt, "diff") ||
465 !strcmp(opt, "show")) {
466 opt_request = opt[0] == 'l'
467 ? REQ_VIEW_LOG : REQ_VIEW_DIFF;
468 break;
469 }
470
471 if (opt[0] && opt[0] != '-')
472 break;
473
474 die("unknown option '%s'\n\n%s", opt, usage);
475 }
476
477 if (!isatty(STDIN_FILENO)) {
478 opt_request = REQ_VIEW_PAGER;
479 opt_pipe = stdin;
480
481 } else if (i < argc) {
482 size_t buf_size;
483
484 if (opt_request == REQ_VIEW_MAIN)
485 /* XXX: This is vulnerable to the user overriding
486 * options required for the main view parser. */
487 string_copy(opt_cmd, "git log --stat --pretty=raw");
488 else
489 string_copy(opt_cmd, "git");
490 buf_size = strlen(opt_cmd);
491
492 while (buf_size < sizeof(opt_cmd) && i < argc) {
493 opt_cmd[buf_size++] = ' ';
494 buf_size = sq_quote(opt_cmd, buf_size, argv[i++]);
495 }
496
497 if (buf_size >= sizeof(opt_cmd))
498 die("command too long");
499
500 opt_cmd[buf_size] = 0;
501
502 }
503
504 if (*opt_encoding && strcasecmp(opt_encoding, "UTF-8"))
505 opt_utf8 = FALSE;
506
507 return TRUE;
508 }
509
510
511 /*
512 * Line-oriented content detection.
513 */
514
515 #define LINE_INFO \
516 LINE(DIFF_HEADER, "diff --git ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
517 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
518 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
519 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
520 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
521 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
522 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
523 LINE(DIFF_COPY_FROM, "copy from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
524 LINE(DIFF_COPY_TO, "copy to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
525 LINE(DIFF_RENAME_FROM, "rename from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
526 LINE(DIFF_RENAME_TO, "rename to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
527 LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
528 LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
529 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
530 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
531 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
532 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
533 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
534 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
535 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
536 LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
537 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
538 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
539 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
540 LINE(AUTHOR, "author ", COLOR_CYAN, COLOR_DEFAULT, 0), \
541 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
542 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
543 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
544 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
545 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
546 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
547 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
548 LINE(MAIN_DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
549 LINE(MAIN_AUTHOR, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
550 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
551 LINE(MAIN_DELIM, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
552 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
553 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
554
555 enum line_type {
556 #define LINE(type, line, fg, bg, attr) \
557 LINE_##type
558 LINE_INFO
559 #undef LINE
560 };
561
562 struct line_info {
563 const char *name; /* Option name. */
564 int namelen; /* Size of option name. */
565 const char *line; /* The start of line to match. */
566 int linelen; /* Size of string to match. */
567 int fg, bg, attr; /* Color and text attributes for the lines. */
568 };
569
570 static struct line_info line_info[] = {
571 #define LINE(type, line, fg, bg, attr) \
572 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
573 LINE_INFO
574 #undef LINE
575 };
576
577 static enum line_type
578 get_line_type(char *line)
579 {
580 int linelen = strlen(line);
581 enum line_type type;
582
583 for (type = 0; type < ARRAY_SIZE(line_info); type++)
584 /* Case insensitive search matches Signed-off-by lines better. */
585 if (linelen >= line_info[type].linelen &&
586 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
587 return type;
588
589 return LINE_DEFAULT;
590 }
591
592 static inline int
593 get_line_attr(enum line_type type)
594 {
595 assert(type < ARRAY_SIZE(line_info));
596 return COLOR_PAIR(type) | line_info[type].attr;
597 }
598
599 static struct line_info *
600 get_line_info(char *name, int namelen)
601 {
602 enum line_type type;
603
604 for (type = 0; type < ARRAY_SIZE(line_info); type++)
605 if (namelen == line_info[type].namelen &&
606 !string_enum_compare(line_info[type].name, name, namelen))
607 return &line_info[type];
608
609 return NULL;
610 }
611
612 static void
613 init_colors(void)
614 {
615 int default_bg = COLOR_BLACK;
616 int default_fg = COLOR_WHITE;
617 enum line_type type;
618
619 start_color();
620
621 if (use_default_colors() != ERR) {
622 default_bg = -1;
623 default_fg = -1;
624 }
625
626 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
627 struct line_info *info = &line_info[type];
628 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
629 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
630
631 init_pair(type, fg, bg);
632 }
633 }
634
635 struct line {
636 enum line_type type;
637 void *data; /* User data */
638 };
639
640
641 /*
642 * Keys
643 */
644
645 struct keybinding {
646 int alias;
647 enum request request;
648 struct keybinding *next;
649 };
650
651 static struct keybinding default_keybindings[] = {
652 /* View switching */
653 { 'm', REQ_VIEW_MAIN },
654 { 'd', REQ_VIEW_DIFF },
655 { 'l', REQ_VIEW_LOG },
656 { 'p', REQ_VIEW_PAGER },
657 { 'h', REQ_VIEW_HELP },
658 { '?', REQ_VIEW_HELP },
659
660 /* View manipulation */
661 { 'q', REQ_VIEW_CLOSE },
662 { KEY_TAB, REQ_VIEW_NEXT },
663 { KEY_RETURN, REQ_ENTER },
664 { KEY_UP, REQ_PREVIOUS },
665 { KEY_DOWN, REQ_NEXT },
666
667 /* Cursor navigation */
668 { 'k', REQ_MOVE_UP },
669 { 'j', REQ_MOVE_DOWN },
670 { KEY_HOME, REQ_MOVE_FIRST_LINE },
671 { KEY_END, REQ_MOVE_LAST_LINE },
672 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
673 { ' ', REQ_MOVE_PAGE_DOWN },
674 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
675 { 'b', REQ_MOVE_PAGE_UP },
676 { '-', REQ_MOVE_PAGE_UP },
677
678 /* Scrolling */
679 { KEY_IC, REQ_SCROLL_LINE_UP },
680 { KEY_DC, REQ_SCROLL_LINE_DOWN },
681 { 'w', REQ_SCROLL_PAGE_UP },
682 { 's', REQ_SCROLL_PAGE_DOWN },
683
684 /* Misc */
685 { 'Q', REQ_QUIT },
686 { 'z', REQ_STOP_LOADING },
687 { 'v', REQ_SHOW_VERSION },
688 { 'r', REQ_SCREEN_REDRAW },
689 { 'n', REQ_TOGGLE_LINENO },
690 { 'g', REQ_TOGGLE_REV_GRAPH },
691 { ':', REQ_PROMPT },
692
693 /* wgetch() with nodelay() enabled returns ERR when there's no input. */
694 { ERR, REQ_NONE },
695
696 /* Using the ncurses SIGWINCH handler. */
697 { KEY_RESIZE, REQ_SCREEN_RESIZE },
698 };
699
700 #define KEYMAP_INFO \
701 KEYMAP_(GENERIC), \
702 KEYMAP_(MAIN), \
703 KEYMAP_(DIFF), \
704 KEYMAP_(LOG), \
705 KEYMAP_(PAGER), \
706 KEYMAP_(HELP) \
707
708 enum keymap {
709 #define KEYMAP_(name) KEYMAP_##name
710 KEYMAP_INFO
711 #undef KEYMAP_
712 };
713
714 static struct int_map keymap_table[] = {
715 #define KEYMAP_(name) { #name, STRING_SIZE(#name), KEYMAP_##name }
716 KEYMAP_INFO
717 #undef KEYMAP_
718 };
719
720 #define set_keymap(map, name) \
721 set_from_int_map(keymap_table, ARRAY_SIZE(keymap_table), map, name, strlen(name))
722
723 static struct keybinding *keybindings[ARRAY_SIZE(keymap_table)];
724
725 static void
726 add_keybinding(enum keymap keymap, enum request request, int key)
727 {
728 struct keybinding *keybinding;
729
730 keybinding = calloc(1, sizeof(*keybinding));
731 if (!keybinding)
732 die("Failed to allocate keybinding");
733
734 keybinding->alias = key;
735 keybinding->request = request;
736 keybinding->next = keybindings[keymap];
737 keybindings[keymap] = keybinding;
738 }
739
740 /* Looks for a key binding first in the given map, then in the generic map, and
741 * lastly in the default keybindings. */
742 static enum request
743 get_keybinding(enum keymap keymap, int key)
744 {
745 struct keybinding *kbd;
746 int i;
747
748 for (kbd = keybindings[keymap]; kbd; kbd = kbd->next)
749 if (kbd->alias == key)
750 return kbd->request;
751
752 for (kbd = keybindings[KEYMAP_GENERIC]; kbd; kbd = kbd->next)
753 if (kbd->alias == key)
754 return kbd->request;
755
756 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
757 if (default_keybindings[i].alias == key)
758 return default_keybindings[i].request;
759
760 return (enum request) key;
761 }
762
763
764 struct key {
765 char *name;
766 int value;
767 };
768
769 static struct key key_table[] = {
770 { "Enter", KEY_RETURN },
771 { "Space", ' ' },
772 { "Backspace", KEY_BACKSPACE },
773 { "Tab", KEY_TAB },
774 { "Escape", KEY_ESC },
775 { "Left", KEY_LEFT },
776 { "Right", KEY_RIGHT },
777 { "Up", KEY_UP },
778 { "Down", KEY_DOWN },
779 { "Insert", KEY_IC },
780 { "Delete", KEY_DC },
781 { "Hash", '#' },
782 { "Home", KEY_HOME },
783 { "End", KEY_END },
784 { "PageUp", KEY_PPAGE },
785 { "PageDown", KEY_NPAGE },
786 { "F1", KEY_F(1) },
787 { "F2", KEY_F(2) },
788 { "F3", KEY_F(3) },
789 { "F4", KEY_F(4) },
790 { "F5", KEY_F(5) },
791 { "F6", KEY_F(6) },
792 { "F7", KEY_F(7) },
793 { "F8", KEY_F(8) },
794 { "F9", KEY_F(9) },
795 { "F10", KEY_F(10) },
796 { "F11", KEY_F(11) },
797 { "F12", KEY_F(12) },
798 };
799
800 static int
801 get_key_value(const char *name)
802 {
803 int i;
804
805 for (i = 0; i < ARRAY_SIZE(key_table); i++)
806 if (!strcasecmp(key_table[i].name, name))
807 return key_table[i].value;
808
809 if (strlen(name) == 1 && isprint(*name))
810 return (int) *name;
811
812 return ERR;
813 }
814
815 static char *
816 get_key(enum request request)
817 {
818 static char buf[BUFSIZ];
819 static char key_char[] = "'X'";
820 int pos = 0;
821 char *sep = " ";
822 int i;
823
824 buf[pos] = 0;
825
826 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
827 struct keybinding *keybinding = &default_keybindings[i];
828 char *seq = NULL;
829 int key;
830
831 if (keybinding->request != request)
832 continue;
833
834 for (key = 0; key < ARRAY_SIZE(key_table); key++)
835 if (key_table[key].value == keybinding->alias)
836 seq = key_table[key].name;
837
838 if (seq == NULL &&
839 keybinding->alias < 127 &&
840 isprint(keybinding->alias)) {
841 key_char[1] = (char) keybinding->alias;
842 seq = key_char;
843 }
844
845 if (!seq)
846 seq = "'?'";
847
848 if (!string_format_from(buf, &pos, "%s%s", sep, seq))
849 return "Too many keybindings!";
850 sep = ", ";
851 }
852
853 return buf;
854 }
855
856
857 /*
858 * User config file handling.
859 */
860
861 static struct int_map color_map[] = {
862 #define COLOR_MAP(name) { #name, STRING_SIZE(#name), COLOR_##name }
863 COLOR_MAP(DEFAULT),
864 COLOR_MAP(BLACK),
865 COLOR_MAP(BLUE),
866 COLOR_MAP(CYAN),
867 COLOR_MAP(GREEN),
868 COLOR_MAP(MAGENTA),
869 COLOR_MAP(RED),
870 COLOR_MAP(WHITE),
871 COLOR_MAP(YELLOW),
872 };
873
874 #define set_color(color, name) \
875 set_from_int_map(color_map, ARRAY_SIZE(color_map), color, name, strlen(name))
876
877 static struct int_map attr_map[] = {
878 #define ATTR_MAP(name) { #name, STRING_SIZE(#name), A_##name }
879 ATTR_MAP(NORMAL),
880 ATTR_MAP(BLINK),
881 ATTR_MAP(BOLD),
882 ATTR_MAP(DIM),
883 ATTR_MAP(REVERSE),
884 ATTR_MAP(STANDOUT),
885 ATTR_MAP(UNDERLINE),
886 };
887
888 #define set_attribute(attr, name) \
889 set_from_int_map(attr_map, ARRAY_SIZE(attr_map), attr, name, strlen(name))
890
891 static int config_lineno;
892 static bool config_errors;
893 static char *config_msg;
894
895 /* Wants: object fgcolor bgcolor [attr] */
896 static int
897 option_color_command(int argc, char *argv[])
898 {
899 struct line_info *info;
900
901 if (argc != 3 && argc != 4) {
902 config_msg = "Wrong number of arguments given to color command";
903 return ERR;
904 }
905
906 info = get_line_info(argv[0], strlen(argv[0]));
907 if (!info) {
908 config_msg = "Unknown color name";
909 return ERR;
910 }
911
912 if (set_color(&info->fg, argv[1]) == ERR ||
913 set_color(&info->bg, argv[2]) == ERR) {
914 config_msg = "Unknown color";
915 return ERR;
916 }
917
918 if (argc == 4 && set_attribute(&info->attr, argv[3]) == ERR) {
919 config_msg = "Unknown attribute";
920 return ERR;
921 }
922
923 return OK;
924 }
925
926 /* Wants: name = value */
927 static int
928 option_set_command(int argc, char *argv[])
929 {
930 if (argc != 3) {
931 config_msg = "Wrong number of arguments given to set command";
932 return ERR;
933 }
934
935 if (strcmp(argv[1], "=")) {
936 config_msg = "No value assigned";
937 return ERR;
938 }
939
940 if (!strcmp(argv[0], "show-rev-graph")) {
941 opt_rev_graph = (!strcmp(argv[2], "1") ||
942 !strcmp(argv[2], "true") ||
943 !strcmp(argv[2], "yes"));
944 return OK;
945 }
946
947 if (!strcmp(argv[0], "line-number-interval")) {
948 opt_num_interval = atoi(argv[2]);
949 return OK;
950 }
951
952 if (!strcmp(argv[0], "tab-size")) {
953 opt_tab_size = atoi(argv[2]);
954 return OK;
955 }
956
957 if (!strcmp(argv[0], "commit-encoding")) {
958 char *arg = argv[2];
959 int delimiter = *arg;
960 int i;
961
962 switch (delimiter) {
963 case '"':
964 case '\'':
965 for (arg++, i = 0; arg[i]; i++)
966 if (arg[i] == delimiter) {
967 arg[i] = 0;
968 break;
969 }
970 default:
971 string_copy(opt_encoding, arg);
972 return OK;
973 }
974 }
975
976 config_msg = "Unknown variable name";
977 return ERR;
978 }
979
980 /* Wants: mode request key */
981 static int
982 option_bind_command(int argc, char *argv[])
983 {
984 enum request request;
985 int keymap;
986 int key;
987
988 if (argc != 3) {
989 config_msg = "Wrong number of arguments given to bind command";
990 return ERR;
991 }
992
993 if (set_keymap(&keymap, argv[0]) == ERR) {
994 config_msg = "Unknown key map";
995 return ERR;
996 }
997
998 key = get_key_value(argv[1]);
999 if (key == ERR) {
1000 config_msg = "Unknown key";
1001 return ERR;
1002 }
1003
1004 request = get_request(argv[2]);
1005 if (request == REQ_UNKNOWN) {
1006 config_msg = "Unknown request name";
1007 return ERR;
1008 }
1009
1010 add_keybinding(keymap, request, key);
1011
1012 return OK;
1013 }
1014
1015 static int
1016 set_option(char *opt, char *value)
1017 {
1018 char *argv[16];
1019 int valuelen;
1020 int argc = 0;
1021
1022 /* Tokenize */
1023 while (argc < ARRAY_SIZE(argv) && (valuelen = strcspn(value, " \t"))) {
1024 argv[argc++] = value;
1025
1026 value += valuelen;
1027 if (!*value)
1028 break;
1029
1030 *value++ = 0;
1031 while (isspace(*value))
1032 value++;
1033 }
1034
1035 if (!strcmp(opt, "color"))
1036 return option_color_command(argc, argv);
1037
1038 if (!strcmp(opt, "set"))
1039 return option_set_command(argc, argv);
1040
1041 if (!strcmp(opt, "bind"))
1042 return option_bind_command(argc, argv);
1043
1044 config_msg = "Unknown option command";
1045 return ERR;
1046 }
1047
1048 static int
1049 read_option(char *opt, int optlen, char *value, int valuelen)
1050 {
1051 int status = OK;
1052
1053 config_lineno++;
1054 config_msg = "Internal error";
1055
1056 /* Check for comment markers, since read_properties() will
1057 * only ensure opt and value are split at first " \t". */
1058 optlen = strcspn(opt, "#");
1059 if (optlen == 0)
1060 return OK;
1061
1062 if (opt[optlen] != 0) {
1063 config_msg = "No option value";
1064 status = ERR;
1065
1066 } else {
1067 /* Look for comment endings in the value. */
1068 int len = strcspn(value, "#");
1069
1070 if (len < valuelen) {
1071 valuelen = len;
1072 value[valuelen] = 0;
1073 }
1074
1075 status = set_option(opt, value);
1076 }
1077
1078 if (status == ERR) {
1079 fprintf(stderr, "Error on line %d, near '%.*s': %s\n",
1080 config_lineno, optlen, opt, config_msg);
1081 config_errors = TRUE;
1082 }
1083
1084 /* Always keep going if errors are encountered. */
1085 return OK;
1086 }
1087
1088 static int
1089 load_options(void)
1090 {
1091 char *home = getenv("HOME");
1092 char buf[SIZEOF_STR];
1093 FILE *file;
1094
1095 config_lineno = 0;
1096 config_errors = FALSE;
1097
1098 if (!home || !string_format(buf, "%s/.tigrc", home))
1099 return ERR;
1100
1101 /* It's ok that the file doesn't exist. */
1102 file = fopen(buf, "r");
1103 if (!file)
1104 return OK;
1105
1106 if (read_properties(file, " \t", read_option) == ERR ||
1107 config_errors == TRUE)
1108 fprintf(stderr, "Errors while loading %s.\n", buf);
1109
1110 return OK;
1111 }
1112
1113
1114 /*
1115 * The viewer
1116 */
1117
1118 struct view;
1119 struct view_ops;
1120
1121 /* The display array of active views and the index of the current view. */
1122 static struct view *display[2];
1123 static unsigned int current_view;
1124
1125 #define foreach_view(view, i) \
1126 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1127
1128 #define displayed_views() (display[1] != NULL ? 2 : 1)
1129
1130 /* Current head and commit ID */
1131 static char ref_commit[SIZEOF_REF] = "HEAD";
1132 static char ref_head[SIZEOF_REF] = "HEAD";
1133
1134 struct view {
1135 const char *name; /* View name */
1136 const char *cmd_fmt; /* Default command line format */
1137 const char *cmd_env; /* Command line set via environment */
1138 const char *id; /* Points to either of ref_{head,commit} */
1139
1140 struct view_ops *ops; /* View operations */
1141
1142 enum keymap keymap; /* What keymap does this view have */
1143
1144 char cmd[SIZEOF_STR]; /* Command buffer */
1145 char ref[SIZEOF_REF]; /* Hovered commit reference */
1146 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
1147
1148 int height, width; /* The width and height of the main window */
1149 WINDOW *win; /* The main window */
1150 WINDOW *title; /* The title window living below the main window */
1151
1152 /* Navigation */
1153 unsigned long offset; /* Offset of the window top */
1154 unsigned long lineno; /* Current line number */
1155
1156 /* If non-NULL, points to the view that opened this view. If this view
1157 * is closed tig will switch back to the parent view. */
1158 struct view *parent;
1159
1160 /* Buffering */
1161 unsigned long lines; /* Total number of lines */
1162 struct line *line; /* Line index */
1163 unsigned long line_size;/* Total number of allocated lines */
1164 unsigned int digits; /* Number of digits in the lines member. */
1165
1166 /* Loading */
1167 FILE *pipe;
1168 time_t start_time;
1169 };
1170
1171 struct view_ops {
1172 /* What type of content being displayed. Used in the title bar. */
1173 const char *type;
1174 /* Draw one line; @lineno must be < view->height. */
1175 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1176 /* Read one line; updates view->line. */
1177 bool (*read)(struct view *view, char *data);
1178 /* Depending on view, change display based on current line. */
1179 bool (*enter)(struct view *view, struct line *line);
1180 };
1181
1182 static struct view_ops pager_ops;
1183 static struct view_ops main_ops;
1184
1185 #define VIEW_STR(name, cmd, env, ref, ops, map) \
1186 { name, cmd, #env, ref, ops, map}
1187
1188 #define VIEW_(id, name, ops, ref) \
1189 VIEW_STR(name, TIG_##id##_CMD, TIG_##id##_CMD, ref, ops, KEYMAP_##id)
1190
1191
1192 static struct view views[] = {
1193 VIEW_(MAIN, "main", &main_ops, ref_head),
1194 VIEW_(DIFF, "diff", &pager_ops, ref_commit),
1195 VIEW_(LOG, "log", &pager_ops, ref_head),
1196 VIEW_(HELP, "help", &pager_ops, "static"),
1197 VIEW_(PAGER, "pager", &pager_ops, "static"),
1198 };
1199
1200 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
1201
1202
1203 static bool
1204 draw_view_line(struct view *view, unsigned int lineno)
1205 {
1206 if (view->offset + lineno >= view->lines)
1207 return FALSE;
1208
1209 return view->ops->draw(view, &view->line[view->offset + lineno], lineno);
1210 }
1211
1212 static void
1213 redraw_view_from(struct view *view, int lineno)
1214 {
1215 assert(0 <= lineno && lineno < view->height);
1216
1217 for (; lineno < view->height; lineno++) {
1218 if (!draw_view_line(view, lineno))
1219 break;
1220 }
1221
1222 redrawwin(view->win);
1223 wrefresh(view->win);
1224 }
1225
1226 static void
1227 redraw_view(struct view *view)
1228 {
1229 wclear(view->win);
1230 redraw_view_from(view, 0);
1231 }
1232
1233
1234 static void
1235 update_view_title(struct view *view)
1236 {
1237 if (view == display[current_view])
1238 wbkgdset(view->title, get_line_attr(LINE_TITLE_FOCUS));
1239 else
1240 wbkgdset(view->title, get_line_attr(LINE_TITLE_BLUR));
1241
1242 werase(view->title);
1243 wmove(view->title, 0, 0);
1244
1245 if (*view->ref)
1246 wprintw(view->title, "[%s] %s", view->name, view->ref);
1247 else
1248 wprintw(view->title, "[%s]", view->name);
1249
1250 if (view->lines || view->pipe) {
1251 unsigned int view_lines = view->offset + view->height;
1252 unsigned int lines = view->lines
1253 ? MIN(view_lines, view->lines) * 100 / view->lines
1254 : 0;
1255
1256 wprintw(view->title, " - %s %d of %d (%d%%)",
1257 view->ops->type,
1258 view->lineno + 1,
1259 view->lines,
1260 lines);
1261 }
1262
1263 if (view->pipe) {
1264 time_t secs = time(NULL) - view->start_time;
1265
1266 /* Three git seconds are a long time ... */
1267 if (secs > 2)
1268 wprintw(view->title, " %lds", secs);
1269 }
1270
1271 wmove(view->title, 0, view->width - 1);
1272 wrefresh(view->title);
1273 }
1274
1275 static void
1276 resize_display(void)
1277 {
1278 int offset, i;
1279 struct view *base = display[0];
1280 struct view *view = display[1] ? display[1] : display[0];
1281
1282 /* Setup window dimensions */
1283
1284 getmaxyx(stdscr, base->height, base->width);
1285
1286 /* Make room for the status window. */
1287 base->height -= 1;
1288
1289 if (view != base) {
1290 /* Horizontal split. */
1291 view->width = base->width;
1292 view->height = SCALE_SPLIT_VIEW(base->height);
1293 base->height -= view->height;
1294
1295 /* Make room for the title bar. */
1296 view->height -= 1;
1297 }
1298
1299 /* Make room for the title bar. */
1300 base->height -= 1;
1301
1302 offset = 0;
1303
1304 foreach_view (view, i) {
1305 if (!view->win) {
1306 view->win = newwin(view->height, 0, offset, 0);
1307 if (!view->win)
1308 die("Failed to create %s view", view->name);
1309
1310 scrollok(view->win, TRUE);
1311
1312 view->title = newwin(1, 0, offset + view->height, 0);
1313 if (!view->title)
1314 die("Failed to create title window");
1315
1316 } else {
1317 wresize(view->win, view->height, view->width);
1318 mvwin(view->win, offset, 0);
1319 mvwin(view->title, offset + view->height, 0);
1320 }
1321
1322 offset += view->height + 1;
1323 }
1324 }
1325
1326 static void
1327 redraw_display(void)
1328 {
1329 struct view *view;
1330 int i;
1331
1332 foreach_view (view, i) {
1333 redraw_view(view);
1334 update_view_title(view);
1335 }
1336 }
1337
1338 static void
1339 update_display_cursor(void)
1340 {
1341 struct view *view = display[current_view];
1342
1343 /* Move the cursor to the right-most column of the cursor line.
1344 *
1345 * XXX: This could turn out to be a bit expensive, but it ensures that
1346 * the cursor does not jump around. */
1347 if (view->lines) {
1348 wmove(view->win, view->lineno - view->offset, view->width - 1);
1349 wrefresh(view->win);
1350 }
1351 }
1352
1353 /*
1354 * Navigation
1355 */
1356
1357 /* Scrolling backend */
1358 static void
1359 do_scroll_view(struct view *view, int lines, bool redraw)
1360 {
1361 /* The rendering expects the new offset. */
1362 view->offset += lines;
1363
1364 assert(0 <= view->offset && view->offset < view->lines);
1365 assert(lines);
1366
1367 /* Redraw the whole screen if scrolling is pointless. */
1368 if (view->height < ABS(lines)) {
1369 redraw_view(view);
1370
1371 } else {
1372 int line = lines > 0 ? view->height - lines : 0;
1373 int end = line + ABS(lines);
1374
1375 wscrl(view->win, lines);
1376
1377 for (; line < end; line++) {
1378 if (!draw_view_line(view, line))
1379 break;
1380 }
1381 }
1382
1383 /* Move current line into the view. */
1384 if (view->lineno < view->offset) {
1385 view->lineno = view->offset;
1386 draw_view_line(view, 0);
1387
1388 } else if (view->lineno >= view->offset + view->height) {
1389 if (view->lineno == view->offset + view->height) {
1390 /* Clear the hidden line so it doesn't show if the view
1391 * is scrolled up. */
1392 wmove(view->win, view->height, 0);
1393 wclrtoeol(view->win);
1394 }
1395 view->lineno = view->offset + view->height - 1;
1396 draw_view_line(view, view->lineno - view->offset);
1397 }
1398
1399 assert(view->offset <= view->lineno && view->lineno < view->lines);
1400
1401 if (!redraw)
1402 return;
1403
1404 redrawwin(view->win);
1405 wrefresh(view->win);
1406 report("");
1407 }
1408
1409 /* Scroll frontend */
1410 static void
1411 scroll_view(struct view *view, enum request request)
1412 {
1413 int lines = 1;
1414
1415 switch (request) {
1416 case REQ_SCROLL_PAGE_DOWN:
1417 lines = view->height;
1418 case REQ_SCROLL_LINE_DOWN:
1419 if (view->offset + lines > view->lines)
1420 lines = view->lines - view->offset;
1421
1422 if (lines == 0 || view->offset + view->height >= view->lines) {
1423 report("Cannot scroll beyond the last line");
1424 return;
1425 }
1426 break;
1427
1428 case REQ_SCROLL_PAGE_UP:
1429 lines = view->height;
1430 case REQ_SCROLL_LINE_UP:
1431 if (lines > view->offset)
1432 lines = view->offset;
1433
1434 if (lines == 0) {
1435 report("Cannot scroll beyond the first line");
1436 return;
1437 }
1438
1439 lines = -lines;
1440 break;
1441
1442 default:
1443 die("request %d not handled in switch", request);
1444 }
1445
1446 do_scroll_view(view, lines, TRUE);
1447 }
1448
1449 /* Cursor moving */
1450 static void
1451 move_view(struct view *view, enum request request, bool redraw)
1452 {
1453 int steps;
1454
1455 switch (request) {
1456 case REQ_MOVE_FIRST_LINE:
1457 steps = -view->lineno;
1458 break;
1459
1460 case REQ_MOVE_LAST_LINE:
1461 steps = view->lines - view->lineno - 1;
1462 break;
1463
1464 case REQ_MOVE_PAGE_UP:
1465 steps = view->height > view->lineno
1466 ? -view->lineno : -view->height;
1467 break;
1468
1469 case REQ_MOVE_PAGE_DOWN:
1470 steps = view->lineno + view->height >= view->lines
1471 ? view->lines - view->lineno - 1 : view->height;
1472 break;
1473
1474 case REQ_MOVE_UP:
1475 steps = -1;
1476 break;
1477
1478 case REQ_MOVE_DOWN:
1479 steps = 1;
1480 break;
1481
1482 default:
1483 die("request %d not handled in switch", request);
1484 }
1485
1486 if (steps <= 0 && view->lineno == 0) {
1487 report("Cannot move beyond the first line");
1488 return;
1489
1490 } else if (steps >= 0 && view->lineno + 1 >= view->lines) {
1491 report("Cannot move beyond the last line");
1492 return;
1493 }
1494
1495 /* Move the current line */
1496 view->lineno += steps;
1497 assert(0 <= view->lineno && view->lineno < view->lines);
1498
1499 /* Repaint the old "current" line if we be scrolling */
1500 if (ABS(steps) < view->height) {
1501 int prev_lineno = view->lineno - steps - view->offset;
1502
1503 wmove(view->win, prev_lineno, 0);
1504 wclrtoeol(view->win);
1505 draw_view_line(view, prev_lineno);
1506 }
1507
1508 /* Check whether the view needs to be scrolled */
1509 if (view->lineno < view->offset ||
1510 view->lineno >= view->offset + view->height) {
1511 if (steps < 0 && -steps > view->offset) {
1512 steps = -view->offset;
1513
1514 } else if (steps > 0) {
1515 if (view->lineno == view->lines - 1 &&
1516 view->lines > view->height) {
1517 steps = view->lines - view->offset - 1;
1518 if (steps >= view->height)
1519 steps -= view->height - 1;
1520 }
1521 }
1522
1523 do_scroll_view(view, steps, redraw);
1524 return;
1525 }
1526
1527 /* Draw the current line */
1528 draw_view_line(view, view->lineno - view->offset);
1529
1530 if (!redraw)
1531 return;
1532
1533 redrawwin(view->win);
1534 wrefresh(view->win);
1535 report("");
1536 }
1537
1538
1539 /*
1540 * Incremental updating
1541 */
1542
1543 static void
1544 end_update(struct view *view)
1545 {
1546 if (!view->pipe)
1547 return;
1548 set_nonblocking_input(FALSE);
1549 if (view->pipe == stdin)
1550 fclose(view->pipe);
1551 else
1552 pclose(view->pipe);
1553 view->pipe = NULL;
1554 }
1555
1556 static bool
1557 begin_update(struct view *view)
1558 {
1559 const char *id = view->id;
1560
1561 if (view->pipe)
1562 end_update(view);
1563
1564 if (opt_cmd[0]) {
1565 string_copy(view->cmd, opt_cmd);
1566 opt_cmd[0] = 0;
1567 /* When running random commands, the view ref could have become
1568 * invalid so clear it. */
1569 view->ref[0] = 0;
1570 } else {
1571 const char *format = view->cmd_env ? view->cmd_env : view->cmd_fmt;
1572
1573 if (!string_format(view->cmd, format, id, id, id, id, id))
1574 return FALSE;
1575 }
1576
1577 /* Special case for the pager view. */
1578 if (opt_pipe) {
1579 view->pipe = opt_pipe;
1580 opt_pipe = NULL;
1581 } else {
1582 view->pipe = popen(view->cmd, "r");
1583 }
1584
1585 if (!view->pipe)
1586 return FALSE;
1587
1588 set_nonblocking_input(TRUE);
1589
1590 view->offset = 0;
1591 view->lines = 0;
1592 view->lineno = 0;
1593 string_copy(view->vid, id);
1594
1595 if (view->line) {
1596 int i;
1597
1598 for (i = 0; i < view->lines; i++)
1599 if (view->line[i].data)
1600 free(view->line[i].data);
1601
1602 free(view->line);
1603 view->line = NULL;
1604 }
1605
1606 view->start_time = time(NULL);
1607
1608 return TRUE;
1609 }
1610
1611 static struct line *
1612 realloc_lines(struct view *view, size_t line_size)
1613 {
1614 struct line *tmp = realloc(view->line, sizeof(*view->line) * line_size);
1615
1616 if (!tmp)
1617 return NULL;
1618
1619 view->line = tmp;
1620 view->line_size = line_size;
1621 return view->line;
1622 }
1623
1624 static bool
1625 update_view(struct view *view)
1626 {
1627 char in_buffer[BUFSIZ];
1628 char out_buffer[BUFSIZ * 2];
1629 char *line;
1630 /* The number of lines to read. If too low it will cause too much
1631 * redrawing (and possible flickering), if too high responsiveness
1632 * will suffer. */
1633 unsigned long lines = view->height;
1634 int redraw_from = -1;
1635
1636 if (!view->pipe)
1637 return TRUE;
1638
1639 /* Only redraw if lines are visible. */
1640 if (view->offset + view->height >= view->lines)
1641 redraw_from = view->lines - view->offset;
1642
1643 if (!realloc_lines(view, view->lines + lines))
1644 goto alloc_error;
1645
1646 while ((line = fgets(in_buffer, sizeof(in_buffer), view->pipe))) {
1647 size_t linelen = strlen(line);
1648
1649 if (linelen)
1650 line[linelen - 1] = 0;
1651
1652 if (opt_iconv != ICONV_NONE) {
1653 char *inbuf = line;
1654 size_t inlen = linelen;
1655
1656 char *outbuf = out_buffer;
1657 size_t outlen = sizeof(out_buffer);
1658
1659 size_t ret;
1660
1661 ret = iconv(opt_iconv, &inbuf, &inlen, &outbuf, &outlen);
1662 if (ret != (size_t) -1) {
1663 line = out_buffer;
1664 linelen = strlen(out_buffer);
1665 }
1666 }
1667
1668 if (!view->ops->read(view, line))
1669 goto alloc_error;
1670
1671 if (lines-- == 1)
1672 break;
1673 }
1674
1675 {
1676 int digits;
1677
1678 lines = view->lines;
1679 for (digits = 0; lines; digits++)
1680 lines /= 10;
1681
1682 /* Keep the displayed view in sync with line number scaling. */
1683 if (digits != view->digits) {
1684 view->digits = digits;
1685 redraw_from = 0;
1686 }
1687 }
1688
1689 if (redraw_from >= 0) {
1690 /* If this is an incremental update, redraw the previous line
1691 * since for commits some members could have changed when
1692 * loading the main view. */
1693 if (redraw_from > 0)
1694 redraw_from--;
1695
1696 /* Incrementally draw avoids flickering. */
1697 redraw_view_from(view, redraw_from);
1698 }
1699
1700 /* Update the title _after_ the redraw so that if the redraw picks up a
1701 * commit reference in view->ref it'll be available here. */
1702 update_view_title(view);
1703
1704 if (ferror(view->pipe)) {
1705 report("Failed to read: %s", strerror(errno));
1706 goto end;
1707
1708 } else if (feof(view->pipe)) {
1709 report("");
1710 goto end;
1711 }
1712
1713 return TRUE;
1714
1715 alloc_error:
1716 report("Allocation failure");
1717
1718 end:
1719 end_update(view);
1720 return FALSE;
1721 }
1722
1723
1724 /*
1725 * View opening
1726 */
1727
1728 static void open_help_view(struct view *view)
1729 {
1730 char buf[BUFSIZ];
1731 int lines = ARRAY_SIZE(req_info) + 2;
1732 int i;
1733
1734 if (view->lines > 0)
1735 return;
1736
1737 for (i = 0; i < ARRAY_SIZE(req_info); i++)
1738 if (!req_info[i].request)
1739 lines++;
1740
1741 view->line = calloc(lines, sizeof(*view->line));
1742 if (!view->line) {
1743 report("Allocation failure");
1744 return;
1745 }
1746
1747 view->ops->read(view, "Quick reference for tig keybindings:");
1748
1749 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
1750 char *key;
1751
1752 if (!req_info[i].request) {
1753 view->ops->read(view, "");
1754 view->ops->read(view, req_info[i].help);
1755 continue;
1756 }
1757
1758 key = get_key(req_info[i].request);
1759 if (!string_format(buf, "%-25s %s", key, req_info[i].help))
1760 continue;
1761
1762 view->ops->read(view, buf);
1763 }
1764 }
1765
1766 enum open_flags {
1767 OPEN_DEFAULT = 0, /* Use default view switching. */
1768 OPEN_SPLIT = 1, /* Split current view. */
1769 OPEN_BACKGROUNDED = 2, /* Backgrounded. */
1770 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
1771 };
1772
1773 static void
1774 open_view(struct view *prev, enum request request, enum open_flags flags)
1775 {
1776 bool backgrounded = !!(flags & OPEN_BACKGROUNDED);
1777 bool split = !!(flags & OPEN_SPLIT);
1778 bool reload = !!(flags & OPEN_RELOAD);
1779 struct view *view = VIEW(request);
1780 int nviews = displayed_views();
1781 struct view *base_view = display[0];
1782
1783 if (view == prev && nviews == 1 && !reload) {
1784 report("Already in %s view", view->name);
1785 return;
1786 }
1787
1788 if (view == VIEW(REQ_VIEW_HELP)) {
1789 open_help_view(view);
1790
1791 } else if ((reload || strcmp(view->vid, view->id)) &&
1792 !begin_update(view)) {
1793 report("Failed to load %s view", view->name);
1794 return;
1795 }
1796
1797 if (split) {
1798 display[1] = view;
1799 if (!backgrounded)
1800 current_view = 1;
1801 } else {
1802 /* Maximize the current view. */
1803 memset(display, 0, sizeof(display));
1804 current_view = 0;
1805 display[current_view] = view;
1806 }
1807
1808 /* Resize the view when switching between split- and full-screen,
1809 * or when switching between two different full-screen views. */
1810 if (nviews != displayed_views() ||
1811 (nviews == 1 && base_view != display[0]))
1812 resize_display();
1813
1814 if (split && prev->lineno - prev->offset >= prev->height) {
1815 /* Take the title line into account. */
1816 int lines = prev->lineno - prev->offset - prev->height + 1;
1817
1818 /* Scroll the view that was split if the current line is
1819 * outside the new limited view. */
1820 do_scroll_view(prev, lines, TRUE);
1821 }
1822
1823 if (prev && view != prev) {
1824 if (split && !backgrounded) {
1825 /* "Blur" the previous view. */
1826 update_view_title(prev);
1827 }
1828
1829 view->parent = prev;
1830 }
1831
1832 if (view->pipe && view->lines == 0) {
1833 /* Clear the old view and let the incremental updating refill
1834 * the screen. */
1835 wclear(view->win);
1836 report("");
1837 } else {
1838 redraw_view(view);
1839 report("");
1840 }
1841
1842 /* If the view is backgrounded the above calls to report()
1843 * won't redraw the view title. */
1844 if (backgrounded)
1845 update_view_title(view);
1846 }
1847
1848
1849 /*
1850 * User request switch noodle
1851 */
1852
1853 static int
1854 view_driver(struct view *view, enum request request)
1855 {
1856 int i;
1857
1858 switch (request) {
1859 case REQ_MOVE_UP:
1860 case REQ_MOVE_DOWN:
1861 case REQ_MOVE_PAGE_UP:
1862 case REQ_MOVE_PAGE_DOWN:
1863 case REQ_MOVE_FIRST_LINE:
1864 case REQ_MOVE_LAST_LINE:
1865 move_view(view, request, TRUE);
1866 break;
1867
1868 case REQ_SCROLL_LINE_DOWN:
1869 case REQ_SCROLL_LINE_UP:
1870 case REQ_SCROLL_PAGE_DOWN:
1871 case REQ_SCROLL_PAGE_UP:
1872 scroll_view(view, request);
1873 break;
1874
1875 case REQ_VIEW_MAIN:
1876 case REQ_VIEW_DIFF:
1877 case REQ_VIEW_LOG:
1878 case REQ_VIEW_HELP:
1879 case REQ_VIEW_PAGER:
1880 open_view(view, request, OPEN_DEFAULT);
1881 break;
1882
1883 case REQ_NEXT:
1884 case REQ_PREVIOUS:
1885 request = request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
1886
1887 if (view == VIEW(REQ_VIEW_DIFF) &&
1888 view->parent == VIEW(REQ_VIEW_MAIN)) {
1889 bool redraw = display[1] == view;
1890
1891 view = view->parent;
1892 move_view(view, request, redraw);
1893 if (redraw)
1894 update_view_title(view);
1895 } else {
1896 move_view(view, request, TRUE);
1897 break;
1898 }
1899 /* Fall-through */
1900
1901 case REQ_ENTER:
1902 if (!view->lines) {
1903 report("Nothing to enter");
1904 break;
1905 }
1906 return view->ops->enter(view, &view->line[view->lineno]);
1907
1908 case REQ_VIEW_NEXT:
1909 {
1910 int nviews = displayed_views();
1911 int next_view = (current_view + 1) % nviews;
1912
1913 if (next_view == current_view) {
1914 report("Only one view is displayed");
1915 break;
1916 }
1917
1918 current_view = next_view;
1919 /* Blur out the title of the previous view. */
1920 update_view_title(view);
1921 report("");
1922 break;
1923 }
1924 case REQ_TOGGLE_LINENO:
1925 opt_line_number = !opt_line_number;
1926 redraw_display();
1927 break;
1928
1929 case REQ_TOGGLE_REV_GRAPH:
1930 opt_rev_graph = !opt_rev_graph;
1931 redraw_display();
1932 break;
1933
1934 case REQ_PROMPT:
1935 /* Always reload^Wrerun commands from the prompt. */
1936 open_view(view, opt_request, OPEN_RELOAD);
1937 break;
1938
1939 case REQ_STOP_LOADING:
1940 for (i = 0; i < ARRAY_SIZE(views); i++) {
1941 view = &views[i];
1942 if (view->pipe)
1943 report("Stopped loading the %s view", view->name),
1944 end_update(view);
1945 }
1946 break;
1947
1948 case REQ_SHOW_VERSION:
1949 report("%s (built %s)", VERSION, __DATE__);
1950 return TRUE;
1951
1952 case REQ_SCREEN_RESIZE:
1953 resize_display();
1954 /* Fall-through */
1955 case REQ_SCREEN_REDRAW:
1956 redraw_display();
1957 break;
1958
1959 case REQ_NONE:
1960 doupdate();
1961 return TRUE;
1962
1963 case REQ_VIEW_CLOSE:
1964 /* XXX: Mark closed views by letting view->parent point to the
1965 * view itself. Parents to closed view should never be
1966 * followed. */
1967 if (view->parent &&
1968 view->parent->parent != view->parent) {
1969 memset(display, 0, sizeof(display));
1970 current_view = 0;
1971 display[current_view] = view->parent;
1972 view->parent = view;
1973 resize_display();
1974 redraw_display();
1975 break;
1976 }
1977 /* Fall-through */
1978 case REQ_QUIT:
1979 return FALSE;
1980
1981 default:
1982 /* An unknown key will show most commonly used commands. */
1983 report("Unknown key, press 'h' for help");
1984 return TRUE;
1985 }
1986
1987 return TRUE;
1988 }
1989
1990
1991 /*
1992 * Pager backend
1993 */
1994
1995 static bool
1996 pager_draw(struct view *view, struct line *line, unsigned int lineno)
1997 {
1998 char *text = line->data;
1999 enum line_type type = line->type;
2000 int textlen = strlen(text);
2001 int attr;
2002
2003 wmove(view->win, lineno, 0);
2004
2005 if (view->offset + lineno == view->lineno) {
2006 if (type == LINE_COMMIT) {
2007 string_copy(view->ref, text + 7);
2008 string_copy(ref_commit, view->ref);
2009 }
2010
2011 type = LINE_CURSOR;
2012 wchgat(view->win, -1, 0, type, NULL);
2013 }
2014
2015 attr = get_line_attr(type);
2016 wattrset(view->win, attr);
2017
2018 if (opt_line_number || opt_tab_size < TABSIZE) {
2019 static char spaces[] = " ";
2020 int col_offset = 0, col = 0;
2021
2022 if (opt_line_number) {
2023 unsigned long real_lineno = view->offset + lineno + 1;
2024
2025 if (real_lineno == 1 ||
2026 (real_lineno % opt_num_interval) == 0) {
2027 wprintw(view->win, "%.*d", view->digits, real_lineno);
2028
2029 } else {
2030 waddnstr(view->win, spaces,
2031 MIN(view->digits, STRING_SIZE(spaces)));
2032 }
2033 waddstr(view->win, ": ");
2034 col_offset = view->digits + 2;
2035 }
2036
2037 while (text && col_offset + col < view->width) {
2038 int cols_max = view->width - col_offset - col;
2039 char *pos = text;
2040 int cols;
2041
2042 if (*text == '\t') {
2043 text++;
2044 assert(sizeof(spaces) > TABSIZE);
2045 pos = spaces;
2046 cols = opt_tab_size - (col % opt_tab_size);
2047
2048 } else {
2049 text = strchr(text, '\t');
2050 cols = line ? text - pos : strlen(pos);
2051 }
2052
2053 waddnstr(view->win, pos, MIN(cols, cols_max));
2054 col += cols;
2055 }
2056
2057 } else {
2058 int col = 0, pos = 0;
2059
2060 for (; pos < textlen && col < view->width; pos++, col++)
2061 if (text[pos] == '\t')
2062 col += TABSIZE - (col % TABSIZE) - 1;
2063
2064 waddnstr(view->win, text, pos);
2065 }
2066
2067 return TRUE;
2068 }
2069
2070 static bool
2071 add_describe_ref(char *buf, int *bufpos, char *commit_id, const char *sep)
2072 {
2073 char refbuf[SIZEOF_STR];
2074 char *ref = NULL;
2075 FILE *pipe;
2076
2077 if (!string_format(refbuf, "git describe %s", commit_id))
2078 return TRUE;
2079
2080 pipe = popen(refbuf, "r");
2081 if (!pipe)
2082 return TRUE;
2083
2084 if ((ref = fgets(refbuf, sizeof(refbuf), pipe)))
2085 ref = chomp_string(ref);
2086 pclose(pipe);
2087
2088 if (!ref || !*ref)
2089 return TRUE;
2090
2091 /* This is the only fatal call, since it can "corrupt" the buffer. */
2092 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
2093 return FALSE;
2094
2095 return TRUE;
2096 }
2097
2098 static void
2099 add_pager_refs(struct view *view, struct line *line)
2100 {
2101 char buf[SIZEOF_STR];
2102 char *commit_id = line->data + STRING_SIZE("commit ");
2103 struct ref **refs;
2104 int bufpos = 0, refpos = 0;
2105 const char *sep = "Refs: ";
2106 bool is_tag = FALSE;
2107
2108 assert(line->type == LINE_COMMIT);
2109
2110 refs = get_refs(commit_id);
2111 if (!refs) {
2112 if (view == VIEW(REQ_VIEW_DIFF))
2113 goto try_add_describe_ref;
2114 return;
2115 }
2116
2117 do {
2118 struct ref *ref = refs[refpos];
2119 char *fmt = ref->tag ? "%s[%s]" : "%s%s";
2120
2121 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
2122 return;
2123 sep = ", ";
2124 if (ref->tag)
2125 is_tag = TRUE;
2126 } while (refs[refpos++]->next);
2127
2128 if (!is_tag && view == VIEW(REQ_VIEW_DIFF)) {
2129 try_add_describe_ref:
2130 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
2131 return;
2132 }
2133
2134 if (!realloc_lines(view, view->line_size + 1))
2135 return;
2136
2137 line = &view->line[view->lines];
2138 line->data = strdup(buf);
2139 if (!line->data)
2140 return;
2141
2142 line->type = LINE_PP_REFS;
2143 view->lines++;
2144 }
2145
2146 static bool
2147 pager_read(struct view *view, char *data)
2148 {
2149 struct line *line = &view->line[view->lines];
2150
2151 line->data = strdup(data);
2152 if (!line->data)
2153 return FALSE;
2154
2155 line->type = get_line_type(line->data);
2156 view->lines++;
2157
2158 if (line->type == LINE_COMMIT &&
2159 (view == VIEW(REQ_VIEW_DIFF) ||
2160 view == VIEW(REQ_VIEW_LOG)))
2161 add_pager_refs(view, line);
2162
2163 return TRUE;
2164 }
2165
2166 static bool
2167 pager_enter(struct view *view, struct line *line)
2168 {
2169 int split = 0;
2170
2171 if (line->type == LINE_COMMIT &&
2172 (view == VIEW(REQ_VIEW_LOG) ||
2173 view == VIEW(REQ_VIEW_PAGER))) {
2174 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
2175 split = 1;
2176 }
2177
2178 /* Always scroll the view even if it was split. That way
2179 * you can use Enter to scroll through the log view and
2180 * split open each commit diff. */
2181 scroll_view(view, REQ_SCROLL_LINE_DOWN);
2182
2183 /* FIXME: A minor workaround. Scrolling the view will call report("")
2184 * but if we are scrolling a non-current view this won't properly
2185 * update the view title. */
2186 if (split)
2187 update_view_title(view);
2188
2189 return TRUE;
2190 }
2191
2192 static struct view_ops pager_ops = {
2193 "line",
2194 pager_draw,
2195 pager_read,
2196 pager_enter,
2197 };
2198
2199
2200 /*
2201 * Main view backend
2202 */
2203
2204 struct commit {
2205 char id[41]; /* SHA1 ID. */
2206 char title[75]; /* First line of the commit message. */
2207 char author[75]; /* Author of the commit. */
2208 struct tm time; /* Date from the author ident. */
2209 struct ref **refs; /* Repository references. */
2210 chtype graph[SIZEOF_REVGRAPH]; /* Ancestry chain graphics. */
2211 size_t graph_size; /* The width of the graph array. */
2212 };
2213
2214 static bool
2215 main_draw(struct view *view, struct line *line, unsigned int lineno)
2216 {
2217 char buf[DATE_COLS + 1];
2218 struct commit *commit = line->data;
2219 enum line_type type;
2220 int col = 0;
2221 size_t timelen;
2222 size_t authorlen;
2223 int trimmed = 1;
2224
2225 if (!*commit->author)
2226 return FALSE;
2227
2228 wmove(view->win, lineno, col);
2229
2230 if (view->offset + lineno == view->lineno) {
2231 string_copy(view->ref, commit->id);
2232 string_copy(ref_commit, view->ref);
2233 type = LINE_CURSOR;
2234 wattrset(view->win, get_line_attr(type));
2235 wchgat(view->win, -1, 0, type, NULL);
2236
2237 } else {
2238 type = LINE_MAIN_COMMIT;
2239 wattrset(view->win, get_line_attr(LINE_MAIN_DATE));
2240 }
2241
2242 timelen = strftime(buf, sizeof(buf), DATE_FORMAT, &commit->time);
2243 waddnstr(view->win, buf, timelen);
2244 waddstr(view->win, " ");
2245
2246 col += DATE_COLS;
2247 wmove(view->win, lineno, col);
2248 if (type != LINE_CURSOR)
2249 wattrset(view->win, get_line_attr(LINE_MAIN_AUTHOR));
2250
2251 if (opt_utf8) {
2252 authorlen = utf8_length(commit->author, AUTHOR_COLS - 2, &col, &trimmed);
2253 } else {
2254 authorlen = strlen(commit->author);
2255 if (authorlen > AUTHOR_COLS - 2) {
2256 authorlen = AUTHOR_COLS - 2;
2257 trimmed = 1;
2258 }
2259 }
2260
2261 if (trimmed) {
2262 waddnstr(view->win, commit->author, authorlen);
2263 if (type != LINE_CURSOR)
2264 wattrset(view->win, get_line_attr(LINE_MAIN_DELIM));
2265 waddch(view->win, '~');
2266 } else {
2267 waddstr(view->win, commit->author);
2268 }
2269
2270 col += AUTHOR_COLS;
2271 if (type != LINE_CURSOR)
2272 wattrset(view->win, A_NORMAL);
2273
2274 if (opt_rev_graph && commit->graph_size) {
2275 size_t i;
2276
2277 wmove(view->win, lineno, col);
2278 /* Using waddch() instead of waddnstr() ensures that
2279 * they'll be rendered correctly for the cursor line. */
2280 for (i = 0; i < commit->graph_size; i++)
2281 waddch(view->win, commit->graph[i]);
2282
2283 col += commit->graph_size + 1;
2284 }
2285
2286 wmove(view->win, lineno, col);
2287
2288 if (commit->refs) {
2289 size_t i = 0;
2290
2291 do {
2292 if (type == LINE_CURSOR)
2293 ;
2294 else if (commit->refs[i]->tag)
2295 wattrset(view->win, get_line_attr(LINE_MAIN_TAG));
2296 else
2297 wattrset(view->win, get_line_attr(LINE_MAIN_REF));
2298 waddstr(view->win, "[");
2299 waddstr(view->win, commit->refs[i]->name);
2300 waddstr(view->win, "]");
2301 if (type != LINE_CURSOR)
2302 wattrset(view->win, A_NORMAL);
2303 waddstr(view->win, " ");
2304 col += strlen(commit->refs[i]->name) + STRING_SIZE("[] ");
2305 } while (commit->refs[i++]->next);
2306 }
2307
2308 if (type != LINE_CURSOR)
2309 wattrset(view->win, get_line_attr(type));
2310
2311 {
2312 int titlelen = strlen(commit->title);
2313
2314 if (col + titlelen > view->width)
2315 titlelen = view->width - col;
2316
2317 waddnstr(view->win, commit->title, titlelen);
2318 }
2319
2320 return TRUE;
2321 }
2322
2323 /* Reads git log --pretty=raw output and parses it into the commit struct. */
2324 static bool
2325 main_read(struct view *view, char *line)
2326 {
2327 enum line_type type = get_line_type(line);
2328 struct commit *commit = view->lines
2329 ? view->line[view->lines - 1].data : NULL;
2330
2331 switch (type) {
2332 case LINE_COMMIT:
2333 commit = calloc(1, sizeof(struct commit));
2334 if (!commit)
2335 return FALSE;
2336
2337 line += STRING_SIZE("commit ");
2338
2339 view->line[view->lines++].data = commit;
2340 string_copy(commit->id, line);
2341 commit->refs = get_refs(commit->id);
2342 commit->graph[commit->graph_size++] = ACS_LTEE;
2343 break;
2344
2345 case LINE_AUTHOR:
2346 {
2347 char *ident = line + STRING_SIZE("author ");
2348 char *end = strchr(ident, '<');
2349
2350 if (!commit)
2351 break;
2352
2353 if (end) {
2354 char *email = end + 1;
2355
2356 for (; end > ident && isspace(end[-1]); end--) ;
2357
2358 if (end == ident && *email) {
2359 ident = email;
2360 end = strchr(ident, '>');
2361 for (; end > ident && isspace(end[-1]); end--) ;
2362 }
2363 *end = 0;
2364 }
2365
2366 /* End is NULL or ident meaning there's no author. */
2367 if (end <= ident)
2368 ident = "Unknown";
2369
2370 string_copy(commit->author, ident);
2371
2372 /* Parse epoch and timezone */
2373 if (end) {
2374 char *secs = strchr(end + 1, '>');
2375 char *zone;
2376 time_t time;
2377
2378 if (!secs || secs[1] != ' ')
2379 break;
2380
2381 secs += 2;
2382 time = (time_t) atol(secs);
2383 zone = strchr(secs, ' ');
2384 if (zone && strlen(zone) == STRING_SIZE(" +0700")) {
2385 long tz;
2386
2387 zone++;
2388 tz = ('0' - zone[1]) * 60 * 60 * 10;
2389 tz += ('0' - zone[2]) * 60 * 60;
2390 tz += ('0' - zone[3]) * 60;
2391 tz += ('0' - zone[4]) * 60;
2392
2393 if (zone[0] == '-')
2394 tz = -tz;
2395
2396 time -= tz;
2397 }
2398 gmtime_r(&time, &commit->time);
2399 }
2400 break;
2401 }
2402 default:
2403 if (!commit)
2404 break;
2405
2406 /* Fill in the commit title if it has not already been set. */
2407 if (commit->title[0])
2408 break;
2409
2410 /* Require titles to start with a non-space character at the
2411 * offset used by git log. */
2412 /* FIXME: More gracefull handling of titles; append "..." to
2413 * shortened titles, etc. */
2414 if (strncmp(line, " ", 4) ||
2415 isspace(line[4]))
2416 break;
2417
2418 string_copy(commit->title, line + 4);
2419 }
2420
2421 return TRUE;
2422 }
2423
2424 static bool
2425 main_enter(struct view *view, struct line *line)
2426 {
2427 enum open_flags flags = display[0] == view ? OPEN_SPLIT : OPEN_DEFAULT;
2428
2429 open_view(view, REQ_VIEW_DIFF, flags);
2430 return TRUE;
2431 }
2432
2433 static struct view_ops main_ops = {
2434 "commit",
2435 main_draw,
2436 main_read,
2437 main_enter,
2438 };
2439
2440
2441 /*
2442 * Unicode / UTF-8 handling
2443 *
2444 * NOTE: Much of the following code for dealing with unicode is derived from
2445 * ELinks' UTF-8 code developed by Scrool <scroolik@gmail.com>. Origin file is
2446 * src/intl/charset.c from the utf8 branch commit elinks-0.11.0-g31f2c28.
2447 */
2448
2449 /* I've (over)annotated a lot of code snippets because I am not entirely
2450 * confident that the approach taken by this small UTF-8 interface is correct.
2451 * --jonas */
2452
2453 static inline int
2454 unicode_width(unsigned long c)
2455 {
2456 if (c >= 0x1100 &&
2457 (c <= 0x115f /* Hangul Jamo */
2458 || c == 0x2329
2459 || c == 0x232a
2460 || (c >= 0x2e80 && c <= 0xa4cf && c != 0x303f)
2461 /* CJK ... Yi */
2462 || (c >= 0xac00 && c <= 0xd7a3) /* Hangul Syllables */
2463 || (c >= 0xf900 && c <= 0xfaff) /* CJK Compatibility Ideographs */
2464 || (c >= 0xfe30 && c <= 0xfe6f) /* CJK Compatibility Forms */
2465 || (c >= 0xff00 && c <= 0xff60) /* Fullwidth Forms */
2466 || (c >= 0xffe0 && c <= 0xffe6)
2467 || (c >= 0x20000 && c <= 0x2fffd)
2468 || (c >= 0x30000 && c <= 0x3fffd)))
2469 return 2;
2470
2471 return 1;
2472 }
2473
2474 /* Number of bytes used for encoding a UTF-8 character indexed by first byte.
2475 * Illegal bytes are set one. */
2476 static const unsigned char utf8_bytes[256] = {
2477 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,
2478 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,
2479 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,
2480 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,
2481 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,
2482 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,
2483 2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,
2484 3,3,3,3,3,3,3,3, 3,3,3,3,3,3,3,3, 4,4,4,4,4,4,4,4, 5,5,5,5,6,6,1,1,
2485 };
2486
2487 /* Decode UTF-8 multi-byte representation into a unicode character. */
2488 static inline unsigned long
2489 utf8_to_unicode(const char *string, size_t length)
2490 {
2491 unsigned long unicode;
2492
2493 switch (length) {
2494 case 1:
2495 unicode = string[0];
2496 break;
2497 case 2:
2498 unicode = (string[0] & 0x1f) << 6;
2499 unicode += (string[1] & 0x3f);
2500 break;
2501 case 3:
2502 unicode = (string[0] & 0x0f) << 12;
2503 unicode += ((string[1] & 0x3f) << 6);
2504 unicode += (string[2] & 0x3f);
2505 break;
2506 case 4:
2507 unicode = (string[0] & 0x0f) << 18;
2508 unicode += ((string[1] & 0x3f) << 12);
2509 unicode += ((string[2] & 0x3f) << 6);
2510 unicode += (string[3] & 0x3f);
2511 break;
2512 case 5:
2513 unicode = (string[0] & 0x0f) << 24;
2514 unicode += ((string[1] & 0x3f) << 18);
2515 unicode += ((string[2] & 0x3f) << 12);
2516 unicode += ((string[3] & 0x3f) << 6);
2517 unicode += (string[4] & 0x3f);
2518 break;
2519 case 6:
2520 unicode = (string[0] & 0x01) << 30;
2521 unicode += ((string[1] & 0x3f) << 24);
2522 unicode += ((string[2] & 0x3f) << 18);
2523 unicode += ((string[3] & 0x3f) << 12);
2524 unicode += ((string[4] & 0x3f) << 6);
2525 unicode += (string[5] & 0x3f);
2526 break;
2527 default:
2528 die("Invalid unicode length");
2529 }
2530
2531 /* Invalid characters could return the special 0xfffd value but NUL
2532 * should be just as good. */
2533 return unicode > 0xffff ? 0 : unicode;
2534 }
2535
2536 /* Calculates how much of string can be shown within the given maximum width
2537 * and sets trimmed parameter to non-zero value if all of string could not be
2538 * shown.
2539 *
2540 * Additionally, adds to coloffset how many many columns to move to align with
2541 * the expected position. Takes into account how multi-byte and double-width
2542 * characters will effect the cursor position.
2543 *
2544 * Returns the number of bytes to output from string to satisfy max_width. */
2545 static size_t
2546 utf8_length(const char *string, size_t max_width, int *coloffset, int *trimmed)
2547 {
2548 const char *start = string;
2549 const char *end = strchr(string, '\0');
2550 size_t mbwidth = 0;
2551 size_t width = 0;
2552
2553 *trimmed = 0;
2554
2555 while (string < end) {
2556 int c = *(unsigned char *) string;
2557 unsigned char bytes = utf8_bytes[c];
2558 size_t ucwidth;
2559 unsigned long unicode;
2560
2561 if (string + bytes > end)
2562 break;
2563
2564 /* Change representation to figure out whether
2565 * it is a single- or double-width character. */
2566
2567 unicode = utf8_to_unicode(string, bytes);
2568 /* FIXME: Graceful handling of invalid unicode character. */
2569 if (!unicode)
2570 break;
2571
2572 ucwidth = unicode_width(unicode);
2573 width += ucwidth;
2574 if (width > max_width) {
2575 *trimmed = 1;
2576 break;
2577 }
2578
2579 /* The column offset collects the differences between the
2580 * number of bytes encoding a character and the number of
2581 * columns will be used for rendering said character.
2582 *
2583 * So if some character A is encoded in 2 bytes, but will be
2584 * represented on the screen using only 1 byte this will and up
2585 * adding 1 to the multi-byte column offset.
2586 *
2587 * Assumes that no double-width character can be encoding in
2588 * less than two bytes. */
2589 if (bytes > ucwidth)
2590 mbwidth += bytes - ucwidth;
2591
2592 string += bytes;
2593 }
2594
2595 *coloffset += mbwidth;
2596
2597 return string - start;
2598 }
2599
2600
2601 /*
2602 * Status management
2603 */
2604
2605 /* Whether or not the curses interface has been initialized. */
2606 static bool cursed = FALSE;
2607
2608 /* The status window is used for polling keystrokes. */
2609 static WINDOW *status_win;
2610
2611 /* Update status and title window. */
2612 static void
2613 report(const char *msg, ...)
2614 {
2615 static bool empty = TRUE;
2616 struct view *view = display[current_view];
2617
2618 if (!empty || *msg) {
2619 va_list args;
2620
2621 va_start(args, msg);
2622
2623 werase(status_win);
2624 wmove(status_win, 0, 0);
2625 if (*msg) {
2626 vwprintw(status_win, msg, args);
2627 empty = FALSE;
2628 } else {
2629 empty = TRUE;
2630 }
2631 wrefresh(status_win);
2632
2633 va_end(args);
2634 }
2635
2636 update_view_title(view);
2637 update_display_cursor();
2638 }
2639
2640 /* Controls when nodelay should be in effect when polling user input. */
2641 static void
2642 set_nonblocking_input(bool loading)
2643 {
2644 static unsigned int loading_views;
2645
2646 if ((loading == FALSE && loading_views-- == 1) ||
2647 (loading == TRUE && loading_views++ == 0))
2648 nodelay(status_win, loading);
2649 }
2650
2651 static void
2652 init_display(void)
2653 {
2654 int x, y;
2655
2656 /* Initialize the curses library */
2657 if (isatty(STDIN_FILENO)) {
2658 cursed = !!initscr();
2659 } else {
2660 /* Leave stdin and stdout alone when acting as a pager. */
2661 FILE *io = fopen("/dev/tty", "r+");
2662
2663 if (!io)
2664 die("Failed to open /dev/tty");
2665 cursed = !!newterm(NULL, io, io);
2666 }
2667
2668 if (!cursed)
2669 die("Failed to initialize curses");
2670
2671 nonl(); /* Tell curses not to do NL->CR/NL on output */
2672 cbreak(); /* Take input chars one at a time, no wait for \n */
2673 noecho(); /* Don't echo input */
2674 leaveok(stdscr, TRUE);
2675
2676 if (has_colors())
2677 init_colors();
2678
2679 getmaxyx(stdscr, y, x);
2680 status_win = newwin(1, 0, y - 1, 0);
2681 if (!status_win)
2682 die("Failed to create status window");
2683
2684 /* Enable keyboard mapping */
2685 keypad(status_win, TRUE);
2686 wbkgdset(status_win, get_line_attr(LINE_STATUS));
2687 }
2688
2689 static char *
2690 read_prompt(const char *prompt)
2691 {
2692 enum { READING, STOP, CANCEL } status = READING;
2693 static char buf[sizeof(opt_cmd) - STRING_SIZE("git \0")];
2694 int pos = 0;
2695
2696 while (status == READING) {
2697 struct view *view;
2698 int i, key;
2699
2700 foreach_view (view, i)
2701 update_view(view);
2702
2703 report("%s%.*s", prompt, pos, buf);
2704 /* Refresh, accept single keystroke of input */
2705 key = wgetch(status_win);
2706 switch (key) {
2707 case KEY_RETURN:
2708 case KEY_ENTER:
2709 case '\n':
2710 status = pos ? STOP : CANCEL;
2711 break;
2712
2713 case KEY_BACKSPACE:
2714 if (pos > 0)
2715 pos--;
2716 else
2717 status = CANCEL;
2718 break;
2719
2720 case KEY_ESC:
2721 status = CANCEL;
2722 break;
2723
2724 case ERR:
2725 break;
2726
2727 default:
2728 if (pos >= sizeof(buf)) {
2729 report("Input string too long");
2730 return NULL;
2731 }
2732
2733 if (isprint(key))
2734 buf[pos++] = (char) key;
2735 }
2736 }
2737
2738 if (status == CANCEL) {
2739 /* Clear the status window */
2740 report("");
2741 return NULL;
2742 }
2743
2744 buf[pos++] = 0;
2745
2746 return buf;
2747 }
2748
2749 /*
2750 * Repository references
2751 */
2752
2753 static struct ref *refs;
2754 static size_t refs_size;
2755
2756 /* Id <-> ref store */
2757 static struct ref ***id_refs;
2758 static size_t id_refs_size;
2759
2760 static struct ref **
2761 get_refs(char *id)
2762 {
2763 struct ref ***tmp_id_refs;
2764 struct ref **ref_list = NULL;
2765 size_t ref_list_size = 0;
2766 size_t i;
2767
2768 for (i = 0; i < id_refs_size; i++)
2769 if (!strcmp(id, id_refs[i][0]->id))
2770 return id_refs[i];
2771
2772 tmp_id_refs = realloc(id_refs, (id_refs_size + 1) * sizeof(*id_refs));
2773 if (!tmp_id_refs)
2774 return NULL;
2775
2776 id_refs = tmp_id_refs;
2777
2778 for (i = 0; i < refs_size; i++) {
2779 struct ref **tmp;
2780
2781 if (strcmp(id, refs[i].id))
2782 continue;
2783
2784 tmp = realloc(ref_list, (ref_list_size + 1) * sizeof(*ref_list));
2785 if (!tmp) {
2786 if (ref_list)
2787 free(ref_list);
2788 return NULL;
2789 }
2790
2791 ref_list = tmp;
2792 if (ref_list_size > 0)
2793 ref_list[ref_list_size - 1]->next = 1;
2794 ref_list[ref_list_size] = &refs[i];
2795
2796 /* XXX: The properties of the commit chains ensures that we can
2797 * safely modify the shared ref. The repo references will
2798 * always be similar for the same id. */
2799 ref_list[ref_list_size]->next = 0;
2800 ref_list_size++;
2801 }
2802
2803 if (ref_list)
2804 id_refs[id_refs_size++] = ref_list;
2805
2806 return ref_list;
2807 }
2808
2809 static int
2810 read_ref(char *id, int idlen, char *name, int namelen)
2811 {
2812 struct ref *ref;
2813 bool tag = FALSE;
2814
2815 if (!strncmp(name, "refs/tags/", STRING_SIZE("refs/tags/"))) {
2816 /* Commits referenced by tags has "^{}" appended. */
2817 if (name[namelen - 1] != '}')
2818 return OK;
2819
2820 while (namelen > 0 && name[namelen] != '^')
2821 namelen--;
2822
2823 tag = TRUE;
2824 namelen -= STRING_SIZE("refs/tags/");
2825 name += STRING_SIZE("refs/tags/");
2826
2827 } else if (!strncmp(name, "refs/heads/", STRING_SIZE("refs/heads/"))) {
2828 namelen -= STRING_SIZE("refs/heads/");
2829 name += STRING_SIZE("refs/heads/");
2830
2831 } else if (!strcmp(name, "HEAD")) {
2832 return OK;
2833 }
2834
2835 refs = realloc(refs, sizeof(*refs) * (refs_size + 1));
2836 if (!refs)
2837 return ERR;
2838
2839 ref = &refs[refs_size++];
2840 ref->name = malloc(namelen + 1);
2841 if (!ref->name)
2842 return ERR;
2843
2844 strncpy(ref->name, name, namelen);
2845 ref->name[namelen] = 0;
2846 ref->tag = tag;
2847 string_copy(ref->id, id);
2848
2849 return OK;
2850 }
2851
2852 static int
2853 load_refs(void)
2854 {
2855 const char *cmd_env = getenv("TIG_LS_REMOTE");
2856 const char *cmd = cmd_env && *cmd_env ? cmd_env : TIG_LS_REMOTE;
2857
2858 return read_properties(popen(cmd, "r"), "\t", read_ref);
2859 }
2860
2861 static int
2862 read_repo_config_option(char *name, int namelen, char *value, int valuelen)
2863 {
2864 if (!strcmp(name, "i18n.commitencoding"))
2865 string_copy(opt_encoding, value);
2866
2867 return OK;
2868 }
2869
2870 static int
2871 load_repo_config(void)
2872 {
2873 return read_properties(popen("git repo-config --list", "r"),
2874 "=", read_repo_config_option);
2875 }
2876
2877 static int
2878 read_properties(FILE *pipe, const char *separators,
2879 int (*read_property)(char *, int, char *, int))
2880 {
2881 char buffer[BUFSIZ];
2882 char *name;
2883 int state = OK;
2884
2885 if (!pipe)
2886 return ERR;
2887
2888 while (state == OK && (name = fgets(buffer, sizeof(buffer), pipe))) {
2889 char *value;
2890 size_t namelen;
2891 size_t valuelen;
2892
2893 name = chomp_string(name);
2894 namelen = strcspn(name, separators);
2895
2896 if (name[namelen]) {
2897 name[namelen] = 0;
2898 value = chomp_string(name + namelen + 1);
2899 valuelen = strlen(value);
2900
2901 } else {
2902 value = "";
2903 valuelen = 0;
2904 }
2905
2906 state = read_property(name, namelen, value, valuelen);
2907 }
2908
2909 if (state != ERR && ferror(pipe))
2910 state = ERR;
2911
2912 pclose(pipe);
2913
2914 return state;
2915 }
2916
2917
2918 /*
2919 * Main
2920 */
2921
2922 static void __NORETURN
2923 quit(int sig)
2924 {
2925 /* XXX: Restore tty modes and let the OS cleanup the rest! */
2926 if (cursed)
2927 endwin();
2928 exit(0);
2929 }
2930
2931 static void __NORETURN
2932 die(const char *err, ...)
2933 {
2934 va_list args;
2935
2936 endwin();
2937
2938 va_start(args, err);
2939 fputs("tig: ", stderr);
2940 vfprintf(stderr, err, args);
2941 fputs("\n", stderr);
2942 va_end(args);
2943
2944 exit(1);
2945 }
2946
2947 int
2948 main(int argc, char *argv[])
2949 {
2950 struct view *view;
2951 enum request request;
2952 size_t i;
2953
2954 signal(SIGINT, quit);
2955
2956 if (setlocale(LC_ALL, "")) {
2957 string_copy(opt_codeset, nl_langinfo(CODESET));
2958 }
2959
2960 if (load_options() == ERR)
2961 die("Failed to load user config.");
2962
2963 /* Load the repo config file so options can be overwritten from
2964 * the command line. */
2965 if (load_repo_config() == ERR)
2966 die("Failed to load repo config.");
2967
2968 if (!parse_options(argc, argv))
2969 return 0;
2970
2971 if (*opt_codeset && strcmp(opt_codeset, opt_encoding)) {
2972 opt_iconv = iconv_open(opt_codeset, opt_encoding);
2973 if (opt_iconv == (iconv_t) -1)
2974 die("Failed to initialize character set conversion");
2975 }
2976
2977 if (load_refs() == ERR)
2978 die("Failed to load refs.");
2979
2980 /* Require a git repository unless when running in pager mode. */
2981 if (refs_size == 0 && opt_request != REQ_VIEW_PAGER)
2982 die("Not a git repository");
2983
2984 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
2985 view->cmd_env = getenv(view->cmd_env);
2986
2987 request = opt_request;
2988
2989 init_display();
2990
2991 while (view_driver(display[current_view], request)) {
2992 int key;
2993 int i;
2994
2995 foreach_view (view, i)
2996 update_view(view);
2997
2998 /* Refresh, accept single keystroke of input */
2999 key = wgetch(status_win);
3000
3001 request = get_keybinding(display[current_view]->keymap, key);
3002
3003 /* Some low-level request handling. This keeps access to
3004 * status_win restricted. */
3005 switch (request) {
3006 case REQ_PROMPT:
3007 {
3008 char *cmd = read_prompt(":");
3009
3010 if (cmd && string_format(opt_cmd, "git %s", cmd)) {
3011 if (strncmp(cmd, "show", 4) && isspace(cmd[4])) {
3012 opt_request = REQ_VIEW_DIFF;
3013 } else {
3014 opt_request = REQ_VIEW_PAGER;
3015 }
3016 break;
3017 }
3018
3019 request = REQ_NONE;
3020 break;
3021 }
3022 case REQ_SCREEN_RESIZE:
3023 {
3024 int height, width;
3025
3026 getmaxyx(stdscr, height, width);
3027
3028 /* Resize the status view and let the view driver take
3029 * care of resizing the displayed views. */
3030 wresize(status_win, 1, width);
3031 mvwin(status_win, height - 1, 0);
3032 wrefresh(status_win);
3033 break;
3034 }
3035 default:
3036 break;
3037 }
3038 }
3039
3040 quit(0);
3041
3042 return 0;
3043 }