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