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