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