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