Add support for converting from git encoding to locale encoding
[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_REF 256 /* Size of symbolic or SHA1 ID. */
58 #define SIZEOF_CMD 1024 /* Size of command buffer. */
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_CMD], size_t bufsize, const char *src)
228 {
229 char c;
230
231 #define BUFPUT(x) do { if (bufsize < SIZEOF_CMD) 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_(PROMPT, "Bring up the prompt"), \
287 REQ_(SCREEN_UPDATE, "Update the screen"), \
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_CMD] = "";
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_SCREEN_UPDATE },
695
696 /* Use 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[1024];
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_CMD]; /* 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_SCREEN_UPDATE:
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 void
2071 add_pager_refs(struct view *view, struct line *line)
2072 {
2073 char buf[1024];
2074 char *data = line->data;
2075 struct ref **refs;
2076 int bufpos = 0, refpos = 0;
2077 const char *sep = "Refs: ";
2078
2079 assert(line->type == LINE_COMMIT);
2080
2081 refs = get_refs(data + STRING_SIZE("commit "));
2082 if (!refs)
2083 return;
2084
2085 do {
2086 struct ref *ref = refs[refpos];
2087 char *fmt = ref->tag ? "%s[%s]" : "%s%s";
2088
2089 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
2090 return;
2091 sep = ", ";
2092 } while (refs[refpos++]->next);
2093
2094 if (!realloc_lines(view, view->line_size + 1))
2095 return;
2096
2097 line = &view->line[view->lines];
2098 line->data = strdup(buf);
2099 if (!line->data)
2100 return;
2101
2102 line->type = LINE_PP_REFS;
2103 view->lines++;
2104 }
2105
2106 static bool
2107 pager_read(struct view *view, char *data)
2108 {
2109 struct line *line = &view->line[view->lines];
2110
2111 line->data = strdup(data);
2112 if (!line->data)
2113 return FALSE;
2114
2115 line->type = get_line_type(line->data);
2116 view->lines++;
2117
2118 if (line->type == LINE_COMMIT &&
2119 (view == VIEW(REQ_VIEW_DIFF) ||
2120 view == VIEW(REQ_VIEW_LOG)))
2121 add_pager_refs(view, line);
2122
2123 return TRUE;
2124 }
2125
2126 static bool
2127 pager_enter(struct view *view, struct line *line)
2128 {
2129 int split = 0;
2130
2131 if (line->type == LINE_COMMIT &&
2132 (view == VIEW(REQ_VIEW_LOG) ||
2133 view == VIEW(REQ_VIEW_PAGER))) {
2134 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
2135 split = 1;
2136 }
2137
2138 /* Always scroll the view even if it was split. That way
2139 * you can use Enter to scroll through the log view and
2140 * split open each commit diff. */
2141 scroll_view(view, REQ_SCROLL_LINE_DOWN);
2142
2143 /* FIXME: A minor workaround. Scrolling the view will call report("")
2144 * but if we are scrolling a non-current view this won't properly
2145 * update the view title. */
2146 if (split)
2147 update_view_title(view);
2148
2149 return TRUE;
2150 }
2151
2152 static struct view_ops pager_ops = {
2153 "line",
2154 pager_draw,
2155 pager_read,
2156 pager_enter,
2157 };
2158
2159
2160 /*
2161 * Main view backend
2162 */
2163
2164 struct commit {
2165 char id[41]; /* SHA1 ID. */
2166 char title[75]; /* First line of the commit message. */
2167 char author[75]; /* Author of the commit. */
2168 struct tm time; /* Date from the author ident. */
2169 struct ref **refs; /* Repository references. */
2170 chtype graph[SIZEOF_REVGRAPH]; /* Ancestry chain graphics. */
2171 size_t graph_size; /* The width of the graph array. */
2172 };
2173
2174 static bool
2175 main_draw(struct view *view, struct line *line, unsigned int lineno)
2176 {
2177 char buf[DATE_COLS + 1];
2178 struct commit *commit = line->data;
2179 enum line_type type;
2180 int col = 0;
2181 size_t timelen;
2182 size_t authorlen;
2183 int trimmed = 1;
2184
2185 if (!*commit->author)
2186 return FALSE;
2187
2188 wmove(view->win, lineno, col);
2189
2190 if (view->offset + lineno == view->lineno) {
2191 string_copy(view->ref, commit->id);
2192 string_copy(ref_commit, view->ref);
2193 type = LINE_CURSOR;
2194 wattrset(view->win, get_line_attr(type));
2195 wchgat(view->win, -1, 0, type, NULL);
2196
2197 } else {
2198 type = LINE_MAIN_COMMIT;
2199 wattrset(view->win, get_line_attr(LINE_MAIN_DATE));
2200 }
2201
2202 timelen = strftime(buf, sizeof(buf), DATE_FORMAT, &commit->time);
2203 waddnstr(view->win, buf, timelen);
2204 waddstr(view->win, " ");
2205
2206 col += DATE_COLS;
2207 wmove(view->win, lineno, col);
2208 if (type != LINE_CURSOR)
2209 wattrset(view->win, get_line_attr(LINE_MAIN_AUTHOR));
2210
2211 if (opt_utf8) {
2212 authorlen = utf8_length(commit->author, AUTHOR_COLS - 2, &col, &trimmed);
2213 } else {
2214 authorlen = strlen(commit->author);
2215 if (authorlen > AUTHOR_COLS - 2) {
2216 authorlen = AUTHOR_COLS - 2;
2217 trimmed = 1;
2218 }
2219 }
2220
2221 if (trimmed) {
2222 waddnstr(view->win, commit->author, authorlen);
2223 if (type != LINE_CURSOR)
2224 wattrset(view->win, get_line_attr(LINE_MAIN_DELIM));
2225 waddch(view->win, '~');
2226 } else {
2227 waddstr(view->win, commit->author);
2228 }
2229
2230 col += AUTHOR_COLS;
2231 if (type != LINE_CURSOR)
2232 wattrset(view->win, A_NORMAL);
2233
2234 if (opt_rev_graph && commit->graph_size) {
2235 size_t i;
2236
2237 wmove(view->win, lineno, col);
2238 /* Using waddch() instead of waddnstr() ensures that
2239 * they'll be rendered correctly for the cursor line. */
2240 for (i = 0; i < commit->graph_size; i++)
2241 waddch(view->win, commit->graph[i]);
2242
2243 col += commit->graph_size + 1;
2244 }
2245
2246 wmove(view->win, lineno, col);
2247
2248 if (commit->refs) {
2249 size_t i = 0;
2250
2251 do {
2252 if (type == LINE_CURSOR)
2253 ;
2254 else if (commit->refs[i]->tag)
2255 wattrset(view->win, get_line_attr(LINE_MAIN_TAG));
2256 else
2257 wattrset(view->win, get_line_attr(LINE_MAIN_REF));
2258 waddstr(view->win, "[");
2259 waddstr(view->win, commit->refs[i]->name);
2260 waddstr(view->win, "]");
2261 if (type != LINE_CURSOR)
2262 wattrset(view->win, A_NORMAL);
2263 waddstr(view->win, " ");
2264 col += strlen(commit->refs[i]->name) + STRING_SIZE("[] ");
2265 } while (commit->refs[i++]->next);
2266 }
2267
2268 if (type != LINE_CURSOR)
2269 wattrset(view->win, get_line_attr(type));
2270
2271 {
2272 int titlelen = strlen(commit->title);
2273
2274 if (col + titlelen > view->width)
2275 titlelen = view->width - col;
2276
2277 waddnstr(view->win, commit->title, titlelen);
2278 }
2279
2280 return TRUE;
2281 }
2282
2283 /* Reads git log --pretty=raw output and parses it into the commit struct. */
2284 static bool
2285 main_read(struct view *view, char *line)
2286 {
2287 enum line_type type = get_line_type(line);
2288 struct commit *commit = view->lines
2289 ? view->line[view->lines - 1].data : NULL;
2290
2291 switch (type) {
2292 case LINE_COMMIT:
2293 commit = calloc(1, sizeof(struct commit));
2294 if (!commit)
2295 return FALSE;
2296
2297 line += STRING_SIZE("commit ");
2298
2299 view->line[view->lines++].data = commit;
2300 string_copy(commit->id, line);
2301 commit->refs = get_refs(commit->id);
2302 commit->graph[commit->graph_size++] = ACS_LTEE;
2303 break;
2304
2305 case LINE_AUTHOR:
2306 {
2307 char *ident = line + STRING_SIZE("author ");
2308 char *end = strchr(ident, '<');
2309
2310 if (!commit)
2311 break;
2312
2313 if (end) {
2314 char *email = end + 1;
2315
2316 for (; end > ident && isspace(end[-1]); end--) ;
2317
2318 if (end == ident && *email) {
2319 ident = email;
2320 end = strchr(ident, '>');
2321 for (; end > ident && isspace(end[-1]); end--) ;
2322 }
2323 *end = 0;
2324 }
2325
2326 /* End is NULL or ident meaning there's no author. */
2327 if (end <= ident)
2328 ident = "Unknown";
2329
2330 string_copy(commit->author, ident);
2331
2332 /* Parse epoch and timezone */
2333 if (end) {
2334 char *secs = strchr(end + 1, '>');
2335 char *zone;
2336 time_t time;
2337
2338 if (!secs || secs[1] != ' ')
2339 break;
2340
2341 secs += 2;
2342 time = (time_t) atol(secs);
2343 zone = strchr(secs, ' ');
2344 if (zone && strlen(zone) == STRING_SIZE(" +0700")) {
2345 long tz;
2346
2347 zone++;
2348 tz = ('0' - zone[1]) * 60 * 60 * 10;
2349 tz += ('0' - zone[2]) * 60 * 60;
2350 tz += ('0' - zone[3]) * 60;
2351 tz += ('0' - zone[4]) * 60;
2352
2353 if (zone[0] == '-')
2354 tz = -tz;
2355
2356 time -= tz;
2357 }
2358 gmtime_r(&time, &commit->time);
2359 }
2360 break;
2361 }
2362 default:
2363 if (!commit)
2364 break;
2365
2366 /* Fill in the commit title if it has not already been set. */
2367 if (commit->title[0])
2368 break;
2369
2370 /* Require titles to start with a non-space character at the
2371 * offset used by git log. */
2372 /* FIXME: More gracefull handling of titles; append "..." to
2373 * shortened titles, etc. */
2374 if (strncmp(line, " ", 4) ||
2375 isspace(line[4]))
2376 break;
2377
2378 string_copy(commit->title, line + 4);
2379 }
2380
2381 return TRUE;
2382 }
2383
2384 static bool
2385 main_enter(struct view *view, struct line *line)
2386 {
2387 enum open_flags flags = display[0] == view ? OPEN_SPLIT : OPEN_DEFAULT;
2388
2389 open_view(view, REQ_VIEW_DIFF, flags);
2390 return TRUE;
2391 }
2392
2393 static struct view_ops main_ops = {
2394 "commit",
2395 main_draw,
2396 main_read,
2397 main_enter,
2398 };
2399
2400
2401 /*
2402 * Unicode / UTF-8 handling
2403 *
2404 * NOTE: Much of the following code for dealing with unicode is derived from
2405 * ELinks' UTF-8 code developed by Scrool <scroolik@gmail.com>. Origin file is
2406 * src/intl/charset.c from the utf8 branch commit elinks-0.11.0-g31f2c28.
2407 */
2408
2409 /* I've (over)annotated a lot of code snippets because I am not entirely
2410 * confident that the approach taken by this small UTF-8 interface is correct.
2411 * --jonas */
2412
2413 static inline int
2414 unicode_width(unsigned long c)
2415 {
2416 if (c >= 0x1100 &&
2417 (c <= 0x115f /* Hangul Jamo */
2418 || c == 0x2329
2419 || c == 0x232a
2420 || (c >= 0x2e80 && c <= 0xa4cf && c != 0x303f)
2421 /* CJK ... Yi */
2422 || (c >= 0xac00 && c <= 0xd7a3) /* Hangul Syllables */
2423 || (c >= 0xf900 && c <= 0xfaff) /* CJK Compatibility Ideographs */
2424 || (c >= 0xfe30 && c <= 0xfe6f) /* CJK Compatibility Forms */
2425 || (c >= 0xff00 && c <= 0xff60) /* Fullwidth Forms */
2426 || (c >= 0xffe0 && c <= 0xffe6)
2427 || (c >= 0x20000 && c <= 0x2fffd)
2428 || (c >= 0x30000 && c <= 0x3fffd)))
2429 return 2;
2430
2431 return 1;
2432 }
2433
2434 /* Number of bytes used for encoding a UTF-8 character indexed by first byte.
2435 * Illegal bytes are set one. */
2436 static const unsigned char utf8_bytes[256] = {
2437 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,
2438 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,
2439 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,
2440 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,
2441 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,
2442 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,
2443 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,
2444 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,
2445 };
2446
2447 /* Decode UTF-8 multi-byte representation into a unicode character. */
2448 static inline unsigned long
2449 utf8_to_unicode(const char *string, size_t length)
2450 {
2451 unsigned long unicode;
2452
2453 switch (length) {
2454 case 1:
2455 unicode = string[0];
2456 break;
2457 case 2:
2458 unicode = (string[0] & 0x1f) << 6;
2459 unicode += (string[1] & 0x3f);
2460 break;
2461 case 3:
2462 unicode = (string[0] & 0x0f) << 12;
2463 unicode += ((string[1] & 0x3f) << 6);
2464 unicode += (string[2] & 0x3f);
2465 break;
2466 case 4:
2467 unicode = (string[0] & 0x0f) << 18;
2468 unicode += ((string[1] & 0x3f) << 12);
2469 unicode += ((string[2] & 0x3f) << 6);
2470 unicode += (string[3] & 0x3f);
2471 break;
2472 case 5:
2473 unicode = (string[0] & 0x0f) << 24;
2474 unicode += ((string[1] & 0x3f) << 18);
2475 unicode += ((string[2] & 0x3f) << 12);
2476 unicode += ((string[3] & 0x3f) << 6);
2477 unicode += (string[4] & 0x3f);
2478 break;
2479 case 6:
2480 unicode = (string[0] & 0x01) << 30;
2481 unicode += ((string[1] & 0x3f) << 24);
2482 unicode += ((string[2] & 0x3f) << 18);
2483 unicode += ((string[3] & 0x3f) << 12);
2484 unicode += ((string[4] & 0x3f) << 6);
2485 unicode += (string[5] & 0x3f);
2486 break;
2487 default:
2488 die("Invalid unicode length");
2489 }
2490
2491 /* Invalid characters could return the special 0xfffd value but NUL
2492 * should be just as good. */
2493 return unicode > 0xffff ? 0 : unicode;
2494 }
2495
2496 /* Calculates how much of string can be shown within the given maximum width
2497 * and sets trimmed parameter to non-zero value if all of string could not be
2498 * shown.
2499 *
2500 * Additionally, adds to coloffset how many many columns to move to align with
2501 * the expected position. Takes into account how multi-byte and double-width
2502 * characters will effect the cursor position.
2503 *
2504 * Returns the number of bytes to output from string to satisfy max_width. */
2505 static size_t
2506 utf8_length(const char *string, size_t max_width, int *coloffset, int *trimmed)
2507 {
2508 const char *start = string;
2509 const char *end = strchr(string, '\0');
2510 size_t mbwidth = 0;
2511 size_t width = 0;
2512
2513 *trimmed = 0;
2514
2515 while (string < end) {
2516 int c = *(unsigned char *) string;
2517 unsigned char bytes = utf8_bytes[c];
2518 size_t ucwidth;
2519 unsigned long unicode;
2520
2521 if (string + bytes > end)
2522 break;
2523
2524 /* Change representation to figure out whether
2525 * it is a single- or double-width character. */
2526
2527 unicode = utf8_to_unicode(string, bytes);
2528 /* FIXME: Graceful handling of invalid unicode character. */
2529 if (!unicode)
2530 break;
2531
2532 ucwidth = unicode_width(unicode);
2533 width += ucwidth;
2534 if (width > max_width) {
2535 *trimmed = 1;
2536 break;
2537 }
2538
2539 /* The column offset collects the differences between the
2540 * number of bytes encoding a character and the number of
2541 * columns will be used for rendering said character.
2542 *
2543 * So if some character A is encoded in 2 bytes, but will be
2544 * represented on the screen using only 1 byte this will and up
2545 * adding 1 to the multi-byte column offset.
2546 *
2547 * Assumes that no double-width character can be encoding in
2548 * less than two bytes. */
2549 if (bytes > ucwidth)
2550 mbwidth += bytes - ucwidth;
2551
2552 string += bytes;
2553 }
2554
2555 *coloffset += mbwidth;
2556
2557 return string - start;
2558 }
2559
2560
2561 /*
2562 * Status management
2563 */
2564
2565 /* Whether or not the curses interface has been initialized. */
2566 static bool cursed = FALSE;
2567
2568 /* The status window is used for polling keystrokes. */
2569 static WINDOW *status_win;
2570
2571 /* Update status and title window. */
2572 static void
2573 report(const char *msg, ...)
2574 {
2575 static bool empty = TRUE;
2576 struct view *view = display[current_view];
2577
2578 if (!empty || *msg) {
2579 va_list args;
2580
2581 va_start(args, msg);
2582
2583 werase(status_win);
2584 wmove(status_win, 0, 0);
2585 if (*msg) {
2586 vwprintw(status_win, msg, args);
2587 empty = FALSE;
2588 } else {
2589 empty = TRUE;
2590 }
2591 wrefresh(status_win);
2592
2593 va_end(args);
2594 }
2595
2596 update_view_title(view);
2597 update_display_cursor();
2598 }
2599
2600 /* Controls when nodelay should be in effect when polling user input. */
2601 static void
2602 set_nonblocking_input(bool loading)
2603 {
2604 static unsigned int loading_views;
2605
2606 if ((loading == FALSE && loading_views-- == 1) ||
2607 (loading == TRUE && loading_views++ == 0))
2608 nodelay(status_win, loading);
2609 }
2610
2611 static void
2612 init_display(void)
2613 {
2614 int x, y;
2615
2616 /* Initialize the curses library */
2617 if (isatty(STDIN_FILENO)) {
2618 cursed = !!initscr();
2619 } else {
2620 /* Leave stdin and stdout alone when acting as a pager. */
2621 FILE *io = fopen("/dev/tty", "r+");
2622
2623 if (!io)
2624 die("Failed to open /dev/tty");
2625 cursed = !!newterm(NULL, io, io);
2626 }
2627
2628 if (!cursed)
2629 die("Failed to initialize curses");
2630
2631 nonl(); /* Tell curses not to do NL->CR/NL on output */
2632 cbreak(); /* Take input chars one at a time, no wait for \n */
2633 noecho(); /* Don't echo input */
2634 leaveok(stdscr, TRUE);
2635
2636 if (has_colors())
2637 init_colors();
2638
2639 getmaxyx(stdscr, y, x);
2640 status_win = newwin(1, 0, y - 1, 0);
2641 if (!status_win)
2642 die("Failed to create status window");
2643
2644 /* Enable keyboard mapping */
2645 keypad(status_win, TRUE);
2646 wbkgdset(status_win, get_line_attr(LINE_STATUS));
2647 }
2648
2649 static int
2650 read_prompt(void)
2651 {
2652 enum { READING, STOP, CANCEL } status = READING;
2653 char buf[sizeof(opt_cmd) - STRING_SIZE("git \0")];
2654 int pos = 0;
2655
2656 while (status == READING) {
2657 struct view *view;
2658 int i, key;
2659
2660 foreach_view (view, i)
2661 update_view(view);
2662
2663 report(":%.*s", pos, buf);
2664 /* Refresh, accept single keystroke of input */
2665 key = wgetch(status_win);
2666 switch (key) {
2667 case KEY_RETURN:
2668 case KEY_ENTER:
2669 case '\n':
2670 status = pos ? STOP : CANCEL;
2671 break;
2672
2673 case KEY_BACKSPACE:
2674 if (pos > 0)
2675 pos--;
2676 else
2677 status = CANCEL;
2678 break;
2679
2680 case KEY_ESC:
2681 status = CANCEL;
2682 break;
2683
2684 case ERR:
2685 break;
2686
2687 default:
2688 if (pos >= sizeof(buf)) {
2689 report("Input string too long");
2690 return ERR;
2691 }
2692
2693 if (isprint(key))
2694 buf[pos++] = (char) key;
2695 }
2696 }
2697
2698 if (status == CANCEL) {
2699 /* Clear the status window */
2700 report("");
2701 return ERR;
2702 }
2703
2704 buf[pos++] = 0;
2705 if (!string_format(opt_cmd, "git %s", buf))
2706 return ERR;
2707 opt_request = REQ_VIEW_PAGER;
2708
2709 return OK;
2710 }
2711
2712 /*
2713 * Repository references
2714 */
2715
2716 static struct ref *refs;
2717 static size_t refs_size;
2718
2719 /* Id <-> ref store */
2720 static struct ref ***id_refs;
2721 static size_t id_refs_size;
2722
2723 static struct ref **
2724 get_refs(char *id)
2725 {
2726 struct ref ***tmp_id_refs;
2727 struct ref **ref_list = NULL;
2728 size_t ref_list_size = 0;
2729 size_t i;
2730
2731 for (i = 0; i < id_refs_size; i++)
2732 if (!strcmp(id, id_refs[i][0]->id))
2733 return id_refs[i];
2734
2735 tmp_id_refs = realloc(id_refs, (id_refs_size + 1) * sizeof(*id_refs));
2736 if (!tmp_id_refs)
2737 return NULL;
2738
2739 id_refs = tmp_id_refs;
2740
2741 for (i = 0; i < refs_size; i++) {
2742 struct ref **tmp;
2743
2744 if (strcmp(id, refs[i].id))
2745 continue;
2746
2747 tmp = realloc(ref_list, (ref_list_size + 1) * sizeof(*ref_list));
2748 if (!tmp) {
2749 if (ref_list)
2750 free(ref_list);
2751 return NULL;
2752 }
2753
2754 ref_list = tmp;
2755 if (ref_list_size > 0)
2756 ref_list[ref_list_size - 1]->next = 1;
2757 ref_list[ref_list_size] = &refs[i];
2758
2759 /* XXX: The properties of the commit chains ensures that we can
2760 * safely modify the shared ref. The repo references will
2761 * always be similar for the same id. */
2762 ref_list[ref_list_size]->next = 0;
2763 ref_list_size++;
2764 }
2765
2766 if (ref_list)
2767 id_refs[id_refs_size++] = ref_list;
2768
2769 return ref_list;
2770 }
2771
2772 static int
2773 read_ref(char *id, int idlen, char *name, int namelen)
2774 {
2775 struct ref *ref;
2776 bool tag = FALSE;
2777
2778 if (!strncmp(name, "refs/tags/", STRING_SIZE("refs/tags/"))) {
2779 /* Commits referenced by tags has "^{}" appended. */
2780 if (name[namelen - 1] != '}')
2781 return OK;
2782
2783 while (namelen > 0 && name[namelen] != '^')
2784 namelen--;
2785
2786 tag = TRUE;
2787 namelen -= STRING_SIZE("refs/tags/");
2788 name += STRING_SIZE("refs/tags/");
2789
2790 } else if (!strncmp(name, "refs/heads/", STRING_SIZE("refs/heads/"))) {
2791 namelen -= STRING_SIZE("refs/heads/");
2792 name += STRING_SIZE("refs/heads/");
2793
2794 } else if (!strcmp(name, "HEAD")) {
2795 return OK;
2796 }
2797
2798 refs = realloc(refs, sizeof(*refs) * (refs_size + 1));
2799 if (!refs)
2800 return ERR;
2801
2802 ref = &refs[refs_size++];
2803 ref->name = malloc(namelen + 1);
2804 if (!ref->name)
2805 return ERR;
2806
2807 strncpy(ref->name, name, namelen);
2808 ref->name[namelen] = 0;
2809 ref->tag = tag;
2810 string_copy(ref->id, id);
2811
2812 return OK;
2813 }
2814
2815 static int
2816 load_refs(void)
2817 {
2818 const char *cmd_env = getenv("TIG_LS_REMOTE");
2819 const char *cmd = cmd_env && *cmd_env ? cmd_env : TIG_LS_REMOTE;
2820
2821 return read_properties(popen(cmd, "r"), "\t", read_ref);
2822 }
2823
2824 static int
2825 read_repo_config_option(char *name, int namelen, char *value, int valuelen)
2826 {
2827 if (!strcmp(name, "i18n.commitencoding"))
2828 string_copy(opt_encoding, value);
2829
2830 return OK;
2831 }
2832
2833 static int
2834 load_repo_config(void)
2835 {
2836 return read_properties(popen("git repo-config --list", "r"),
2837 "=", read_repo_config_option);
2838 }
2839
2840 static int
2841 read_properties(FILE *pipe, const char *separators,
2842 int (*read_property)(char *, int, char *, int))
2843 {
2844 char buffer[BUFSIZ];
2845 char *name;
2846 int state = OK;
2847
2848 if (!pipe)
2849 return ERR;
2850
2851 while (state == OK && (name = fgets(buffer, sizeof(buffer), pipe))) {
2852 char *value;
2853 size_t namelen;
2854 size_t valuelen;
2855
2856 name = chomp_string(name);
2857 namelen = strcspn(name, separators);
2858
2859 if (name[namelen]) {
2860 name[namelen] = 0;
2861 value = chomp_string(name + namelen + 1);
2862 valuelen = strlen(value);
2863
2864 } else {
2865 value = "";
2866 valuelen = 0;
2867 }
2868
2869 state = read_property(name, namelen, value, valuelen);
2870 }
2871
2872 if (state != ERR && ferror(pipe))
2873 state = ERR;
2874
2875 pclose(pipe);
2876
2877 return state;
2878 }
2879
2880
2881 /*
2882 * Main
2883 */
2884
2885 static void __NORETURN
2886 quit(int sig)
2887 {
2888 /* XXX: Restore tty modes and let the OS cleanup the rest! */
2889 if (cursed)
2890 endwin();
2891 exit(0);
2892 }
2893
2894 static void __NORETURN
2895 die(const char *err, ...)
2896 {
2897 va_list args;
2898
2899 endwin();
2900
2901 va_start(args, err);
2902 fputs("tig: ", stderr);
2903 vfprintf(stderr, err, args);
2904 fputs("\n", stderr);
2905 va_end(args);
2906
2907 exit(1);
2908 }
2909
2910 int
2911 main(int argc, char *argv[])
2912 {
2913 struct view *view;
2914 enum request request;
2915 size_t i;
2916
2917 signal(SIGINT, quit);
2918
2919 if (setlocale(LC_ALL, "")) {
2920 string_copy(opt_codeset, nl_langinfo(CODESET));
2921 }
2922
2923 if (load_options() == ERR)
2924 die("Failed to load user config.");
2925
2926 /* Load the repo config file so options can be overwritten from
2927 * the command line. */
2928 if (load_repo_config() == ERR)
2929 die("Failed to load repo config.");
2930
2931 if (!parse_options(argc, argv))
2932 return 0;
2933
2934 if (*opt_codeset && strcmp(opt_codeset, opt_encoding)) {
2935 opt_iconv = iconv_open(opt_codeset, opt_encoding);
2936 if (opt_iconv == (iconv_t) -1)
2937 die("Failed to initialize character set conversion");
2938 }
2939
2940 if (load_refs() == ERR)
2941 die("Failed to load refs.");
2942
2943 /* Require a git repository unless when running in pager mode. */
2944 if (refs_size == 0 && opt_request != REQ_VIEW_PAGER)
2945 die("Not a git repository");
2946
2947 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
2948 view->cmd_env = getenv(view->cmd_env);
2949
2950 request = opt_request;
2951
2952 init_display();
2953
2954 while (view_driver(display[current_view], request)) {
2955 int key;
2956 int i;
2957
2958 foreach_view (view, i)
2959 update_view(view);
2960
2961 /* Refresh, accept single keystroke of input */
2962 key = wgetch(status_win);
2963
2964 request = get_keybinding(display[current_view]->keymap, key);
2965
2966 /* Some low-level request handling. This keeps access to
2967 * status_win restricted. */
2968 switch (request) {
2969 case REQ_PROMPT:
2970 if (read_prompt() == ERR)
2971 request = REQ_SCREEN_UPDATE;
2972 break;
2973
2974 case REQ_SCREEN_RESIZE:
2975 {
2976 int height, width;
2977
2978 getmaxyx(stdscr, height, width);
2979
2980 /* Resize the status view and let the view driver take
2981 * care of resizing the displayed views. */
2982 wresize(status_win, 1, width);
2983 mvwin(status_win, height - 1, 0);
2984 wrefresh(status_win);
2985 break;
2986 }
2987 default:
2988 break;
2989 }
2990 }
2991
2992 quit(0);
2993
2994 return 0;
2995 }