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