Only save commit tag refs; move line type info to view->ops; switch silently
[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                 /* What type of content being displayed. Used in the
686                  * title bar. */
687                 char *type;
688                 /* Draw one line; @lineno must be < view->height. */
689                 bool (*draw)(struct view *view, unsigned int lineno);
690                 /* Read one line; updates view->line. */
691                 bool (*read)(struct view *view, char *line);
692                 /* Depending on view, change display based on current line. */
693                 bool (*enter)(struct view *view);
694         } *ops;
695
696         char cmd[SIZEOF_CMD];   /* Command buffer */
697         char ref[SIZEOF_REF];   /* Hovered commit reference */
698         char vid[SIZEOF_REF];   /* View ID. Set to id member when updating. */
699
700         int height, width;      /* The width and height of the main window */
701         WINDOW *win;            /* The main window */
702         WINDOW *title;          /* The title window living below the main window */
703
704         /* Navigation */
705         unsigned long offset;   /* Offset of the window top */
706         unsigned long lineno;   /* Current line number */
707
708         /* Buffering */
709         unsigned long lines;    /* Total number of lines */
710         void **line;            /* Line index; each line contains user data */
711         unsigned int digits;    /* Number of digits in the lines member. */
712
713         /* Loading */
714         FILE *pipe;
715         time_t start_time;
716 };
717
718 static struct view_ops pager_ops;
719 static struct view_ops main_ops;
720
721 char ref_head[SIZEOF_REF]       = "HEAD";
722 char ref_commit[SIZEOF_REF]     = "HEAD";
723
724 #define VIEW_STR(name, cmd, env, ref, objsize, ops) \
725         { name, cmd, #env, ref, objsize, ops }
726
727 #define VIEW_(id, name, ops, ref, objsize) \
728         VIEW_STR(name, TIG_##id##_CMD,  TIG_##id##_CMD, ref, objsize, ops)
729
730 static struct view views[] = {
731         VIEW_(MAIN,  "main",  &main_ops,  ref_head,   sizeof(struct commit)),
732         VIEW_(DIFF,  "diff",  &pager_ops, ref_commit, sizeof(char)),
733         VIEW_(LOG,   "log",   &pager_ops, ref_head,   sizeof(char)),
734         VIEW_(HELP,  "help",  &pager_ops, ref_head,   sizeof(char)),
735         VIEW_(PAGER, "pager", &pager_ops, "static",   sizeof(char)),
736 };
737
738 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
739
740 /* The display array of active views and the index of the current view. */
741 static struct view *display[2];
742 static unsigned int current_view;
743
744 #define foreach_view(view, i) \
745         for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
746
747
748 static void
749 redraw_view_from(struct view *view, int lineno)
750 {
751         assert(0 <= lineno && lineno < view->height);
752
753         for (; lineno < view->height; lineno++) {
754                 if (!view->ops->draw(view, lineno))
755                         break;
756         }
757
758         redrawwin(view->win);
759         wrefresh(view->win);
760 }
761
762 static void
763 redraw_view(struct view *view)
764 {
765         wclear(view->win);
766         redraw_view_from(view, 0);
767 }
768
769 static void
770 resize_display(void)
771 {
772         int offset, i;
773         struct view *base = display[0];
774         struct view *view = display[1] ? display[1] : display[0];
775
776         /* Setup window dimensions */
777
778         getmaxyx(stdscr, base->height, base->width);
779
780         /* Make room for the status window. */
781         base->height -= 1;
782
783         if (view != base) {
784                 /* Horizontal split. */
785                 view->width   = base->width;
786                 view->height  = SCALE_SPLIT_VIEW(base->height);
787                 base->height -= view->height;
788
789                 /* Make room for the title bar. */
790                 view->height -= 1;
791         }
792
793         /* Make room for the title bar. */
794         base->height -= 1;
795
796         offset = 0;
797
798         foreach_view (view, i) {
799                 if (!view->win) {
800                         view->win = newwin(view->height, 0, offset, 0);
801                         if (!view->win)
802                                 die("Failed to create %s view", view->name);
803
804                         scrollok(view->win, TRUE);
805
806                         view->title = newwin(1, 0, offset + view->height, 0);
807                         if (!view->title)
808                                 die("Failed to create title window");
809
810                 } else {
811                         wresize(view->win, view->height, view->width);
812                         mvwin(view->win,   offset, 0);
813                         mvwin(view->title, offset + view->height, 0);
814                         wrefresh(view->win);
815                 }
816
817                 offset += view->height + 1;
818         }
819 }
820
821 static void
822 update_view_title(struct view *view)
823 {
824         if (view == display[current_view])
825                 wbkgdset(view->title, get_line_attr(LINE_TITLE_FOCUS));
826         else
827                 wbkgdset(view->title, get_line_attr(LINE_TITLE_BLUR));
828
829         werase(view->title);
830         wmove(view->title, 0, 0);
831
832         /* [main] ref: 334b506... - commit 6 of 4383 (0%) */
833
834         if (*view->ref)
835                 wprintw(view->title, "[%s] ref: %s", view->name, view->ref);
836         else
837                 wprintw(view->title, "[%s]", view->name);
838
839         if (view->lines) {
840                 wprintw(view->title, " - %s %d of %d (%d%%)",
841                         view->ops->type,
842                         view->lineno + 1,
843                         view->lines,
844                         (view->lineno + 1) * 100 / view->lines);
845         }
846
847         wrefresh(view->title);
848 }
849
850 /*
851  * Navigation
852  */
853
854 /* Scrolling backend */
855 static void
856 do_scroll_view(struct view *view, int lines)
857 {
858         /* The rendering expects the new offset. */
859         view->offset += lines;
860
861         assert(0 <= view->offset && view->offset < view->lines);
862         assert(lines);
863
864         /* Redraw the whole screen if scrolling is pointless. */
865         if (view->height < ABS(lines)) {
866                 redraw_view(view);
867
868         } else {
869                 int line = lines > 0 ? view->height - lines : 0;
870                 int end = line + ABS(lines);
871
872                 wscrl(view->win, lines);
873
874                 for (; line < end; line++) {
875                         if (!view->ops->draw(view, line))
876                                 break;
877                 }
878         }
879
880         /* Move current line into the view. */
881         if (view->lineno < view->offset) {
882                 view->lineno = view->offset;
883                 view->ops->draw(view, 0);
884
885         } else if (view->lineno >= view->offset + view->height) {
886                 view->lineno = view->offset + view->height - 1;
887                 view->ops->draw(view, view->lineno - view->offset);
888         }
889
890         assert(view->offset <= view->lineno && view->lineno < view->lines);
891
892         redrawwin(view->win);
893         wrefresh(view->win);
894         report("");
895 }
896
897 /* Scroll frontend */
898 static void
899 scroll_view(struct view *view, enum request request)
900 {
901         int lines = 1;
902
903         switch (request) {
904         case REQ_SCROLL_PAGE_DOWN:
905                 lines = view->height;
906         case REQ_SCROLL_LINE_DOWN:
907                 if (view->offset + lines > view->lines)
908                         lines = view->lines - view->offset;
909
910                 if (lines == 0 || view->offset + view->height >= view->lines) {
911                         report("Cannot scroll beyond the last line");
912                         return;
913                 }
914                 break;
915
916         case REQ_SCROLL_PAGE_UP:
917                 lines = view->height;
918         case REQ_SCROLL_LINE_UP:
919                 if (lines > view->offset)
920                         lines = view->offset;
921
922                 if (lines == 0) {
923                         report("Cannot scroll beyond the first line");
924                         return;
925                 }
926
927                 lines = -lines;
928                 break;
929
930         default:
931                 die("request %d not handled in switch", request);
932         }
933
934         do_scroll_view(view, lines);
935 }
936
937 /* Cursor moving */
938 static void
939 move_view(struct view *view, enum request request)
940 {
941         int steps;
942
943         switch (request) {
944         case REQ_MOVE_FIRST_LINE:
945                 steps = -view->lineno;
946                 break;
947
948         case REQ_MOVE_LAST_LINE:
949                 steps = view->lines - view->lineno - 1;
950                 break;
951
952         case REQ_MOVE_PAGE_UP:
953                 steps = view->height > view->lineno
954                       ? -view->lineno : -view->height;
955                 break;
956
957         case REQ_MOVE_PAGE_DOWN:
958                 steps = view->lineno + view->height >= view->lines
959                       ? view->lines - view->lineno - 1 : view->height;
960                 break;
961
962         case REQ_MOVE_UP:
963                 steps = -1;
964                 break;
965
966         case REQ_MOVE_DOWN:
967                 steps = 1;
968                 break;
969
970         default:
971                 die("request %d not handled in switch", request);
972         }
973
974         if (steps <= 0 && view->lineno == 0) {
975                 report("Cannot move beyond the first line");
976                 return;
977
978         } else if (steps >= 0 && view->lineno + 1 >= view->lines) {
979                 report("Cannot move beyond the last line");
980                 return;
981         }
982
983         /* Move the current line */
984         view->lineno += steps;
985         assert(0 <= view->lineno && view->lineno < view->lines);
986
987         /* Repaint the old "current" line if we be scrolling */
988         if (ABS(steps) < view->height) {
989                 int prev_lineno = view->lineno - steps - view->offset;
990
991                 wmove(view->win, prev_lineno, 0);
992                 wclrtoeol(view->win);
993                 view->ops->draw(view, prev_lineno);
994         }
995
996         /* Check whether the view needs to be scrolled */
997         if (view->lineno < view->offset ||
998             view->lineno >= view->offset + view->height) {
999                 if (steps < 0 && -steps > view->offset) {
1000                         steps = -view->offset;
1001
1002                 } else if (steps > 0) {
1003                         if (view->lineno == view->lines - 1 &&
1004                             view->lines > view->height) {
1005                                 steps = view->lines - view->offset - 1;
1006                                 if (steps >= view->height)
1007                                         steps -= view->height - 1;
1008                         }
1009                 }
1010
1011                 do_scroll_view(view, steps);
1012                 return;
1013         }
1014
1015         /* Draw the current line */
1016         view->ops->draw(view, view->lineno - view->offset);
1017
1018         redrawwin(view->win);
1019         wrefresh(view->win);
1020         report("");
1021 }
1022
1023
1024 /*
1025  * Incremental updating
1026  */
1027
1028 static bool
1029 begin_update(struct view *view)
1030 {
1031         char *id = view->id;
1032
1033         if (opt_cmd[0]) {
1034                 string_copy(view->cmd, opt_cmd);
1035                 opt_cmd[0] = 0;
1036                 /* When running random commands, the view ref could have become
1037                  * invalid so clear it. */
1038                 view->ref[0] = 0;
1039         } else {
1040                 char *format = view->cmd_env ? view->cmd_env : view->cmd_fmt;
1041
1042                 if (snprintf(view->cmd, sizeof(view->cmd), format,
1043                              id, id, id, id, id) >= sizeof(view->cmd))
1044                         return FALSE;
1045         }
1046
1047         /* Special case for the pager view. */
1048         if (opt_pipe) {
1049                 view->pipe = opt_pipe;
1050                 opt_pipe = NULL;
1051         } else {
1052                 view->pipe = popen(view->cmd, "r");
1053         }
1054
1055         if (!view->pipe)
1056                 return FALSE;
1057
1058         set_nonblocking_input(TRUE);
1059
1060         view->offset = 0;
1061         view->lines  = 0;
1062         view->lineno = 0;
1063         string_copy(view->vid, id);
1064
1065         if (view->line) {
1066                 int i;
1067
1068                 for (i = 0; i < view->lines; i++)
1069                         if (view->line[i])
1070                                 free(view->line[i]);
1071
1072                 free(view->line);
1073                 view->line = NULL;
1074         }
1075
1076         view->start_time = time(NULL);
1077
1078         return TRUE;
1079 }
1080
1081 static void
1082 end_update(struct view *view)
1083 {
1084         if (!view->pipe)
1085                 return;
1086         set_nonblocking_input(FALSE);
1087         if (view->pipe == stdin)
1088                 fclose(view->pipe);
1089         else
1090                 pclose(view->pipe);
1091         view->pipe = NULL;
1092 }
1093
1094 static bool
1095 update_view(struct view *view)
1096 {
1097         char buffer[BUFSIZ];
1098         char *line;
1099         void **tmp;
1100         /* The number of lines to read. If too low it will cause too much
1101          * redrawing (and possible flickering), if too high responsiveness
1102          * will suffer. */
1103         unsigned long lines = view->height;
1104         int redraw_from = -1;
1105
1106         if (!view->pipe)
1107                 return TRUE;
1108
1109         /* Only redraw if lines are visible. */
1110         if (view->offset + view->height >= view->lines)
1111                 redraw_from = view->lines - view->offset;
1112
1113         tmp = realloc(view->line, sizeof(*view->line) * (view->lines + lines));
1114         if (!tmp)
1115                 goto alloc_error;
1116
1117         view->line = tmp;
1118
1119         while ((line = fgets(buffer, sizeof(buffer), view->pipe))) {
1120                 int linelen = strlen(line);
1121
1122                 if (linelen)
1123                         line[linelen - 1] = 0;
1124
1125                 if (!view->ops->read(view, line))
1126                         goto alloc_error;
1127
1128                 if (lines-- == 1)
1129                         break;
1130         }
1131
1132         {
1133                 int digits;
1134
1135                 lines = view->lines;
1136                 for (digits = 0; lines; digits++)
1137                         lines /= 10;
1138
1139                 /* Keep the displayed view in sync with line number scaling. */
1140                 if (digits != view->digits) {
1141                         view->digits = digits;
1142                         redraw_from = 0;
1143                 }
1144         }
1145
1146         if (redraw_from >= 0) {
1147                 /* If this is an incremental update, redraw the previous line
1148                  * since for commits some members could have changed when
1149                  * loading the main view. */
1150                 if (redraw_from > 0)
1151                         redraw_from--;
1152
1153                 /* Incrementally draw avoids flickering. */
1154                 redraw_view_from(view, redraw_from);
1155         }
1156
1157         /* Update the title _after_ the redraw so that if the redraw picks up a
1158          * commit reference in view->ref it'll be available here. */
1159         update_view_title(view);
1160
1161         if (ferror(view->pipe)) {
1162                 report("Failed to read: %s", strerror(errno));
1163                 goto end;
1164
1165         } else if (feof(view->pipe)) {
1166                 time_t secs = time(NULL) - view->start_time;
1167
1168                 if (view == VIEW(REQ_VIEW_HELP)) {
1169                         report("%s", HELP);
1170                         goto end;
1171                 }
1172
1173                 report("Loaded %d lines in %ld second%s", view->lines, secs,
1174                        secs == 1 ? "" : "s");
1175                 goto end;
1176         }
1177
1178         return TRUE;
1179
1180 alloc_error:
1181         report("Allocation failure");
1182
1183 end:
1184         end_update(view);
1185         return FALSE;
1186 }
1187
1188 enum open_flags {
1189         OPEN_DEFAULT = 0,       /* Use default view switching. */
1190         OPEN_SPLIT = 1,         /* Split current view. */
1191         OPEN_BACKGROUNDED = 2,  /* Backgrounded. */
1192         OPEN_RELOAD = 4,        /* Reload view even if it is the current. */
1193 };
1194
1195 static void
1196 open_view(struct view *prev, enum request request, enum open_flags flags)
1197 {
1198         bool backgrounded = !!(flags & OPEN_BACKGROUNDED);
1199         bool split = !!(flags & OPEN_SPLIT);
1200         bool reload = !!(flags & OPEN_RELOAD);
1201         struct view *view = VIEW(request);
1202         struct view *displayed;
1203         int nviews;
1204
1205         /* Cycle between displayed views and count the views. */
1206         foreach_view (displayed, nviews) {
1207                 if (prev != view &&
1208                     view == displayed &&
1209                     !strcmp(view->vid, prev->vid)) {
1210                         current_view = nviews;
1211                         /* Blur out the title of the previous view. */
1212                         update_view_title(prev);
1213                         report("");
1214                         return;
1215                 }
1216         }
1217
1218         if (view == prev && nviews == 1 && !reload) {
1219                 report("Already in %s view", view->name);
1220                 return;
1221         }
1222
1223         if ((reload || strcmp(view->vid, view->id)) &&
1224             !begin_update(view)) {
1225                 report("Failed to load %s view", view->name);
1226                 return;
1227         }
1228
1229         if (split) {
1230                 display[current_view + 1] = view;
1231                 if (!backgrounded)
1232                         current_view++;
1233         } else {
1234                 /* Maximize the current view. */
1235                 memset(display, 0, sizeof(display));
1236                 current_view = 0;
1237                 display[current_view] = view;
1238         }
1239
1240         resize_display();
1241
1242         if (split && prev->lineno - prev->offset >= prev->height) {
1243                 /* Take the title line into account. */
1244                 int lines = prev->lineno - prev->offset - prev->height + 1;
1245
1246                 /* Scroll the view that was split if the current line is
1247                  * outside the new limited view. */
1248                 do_scroll_view(prev, lines);
1249         }
1250
1251         if (prev && view != prev) {
1252                 /* "Blur" the previous view. */
1253                 update_view_title(prev);
1254
1255                 /* Continue loading split views in the background. */
1256                 if (!split)
1257                         end_update(prev);
1258         }
1259
1260         if (view->pipe) {
1261                 /* Clear the old view and let the incremental updating refill
1262                  * the screen. */
1263                 wclear(view->win);
1264                 report("Loading...");
1265         } else {
1266                 redraw_view(view);
1267                 report("");
1268         }
1269 }
1270
1271
1272 /*
1273  * User request switch noodle
1274  */
1275
1276 static int
1277 view_driver(struct view *view, enum request request)
1278 {
1279         int i;
1280
1281         switch (request) {
1282         case REQ_MOVE_UP:
1283         case REQ_MOVE_DOWN:
1284         case REQ_MOVE_PAGE_UP:
1285         case REQ_MOVE_PAGE_DOWN:
1286         case REQ_MOVE_FIRST_LINE:
1287         case REQ_MOVE_LAST_LINE:
1288                 move_view(view, request);
1289                 break;
1290
1291         case REQ_SCROLL_LINE_DOWN:
1292         case REQ_SCROLL_LINE_UP:
1293         case REQ_SCROLL_PAGE_DOWN:
1294         case REQ_SCROLL_PAGE_UP:
1295                 scroll_view(view, request);
1296                 break;
1297
1298         case REQ_VIEW_MAIN:
1299         case REQ_VIEW_DIFF:
1300         case REQ_VIEW_LOG:
1301         case REQ_VIEW_HELP:
1302         case REQ_VIEW_PAGER:
1303                 open_view(view, request, OPEN_DEFAULT);
1304                 break;
1305
1306         case REQ_ENTER:
1307                 if (!view->lines) {
1308                         report("Nothing to enter");
1309                         break;
1310                 }
1311                 return view->ops->enter(view);
1312
1313         case REQ_VIEW_NEXT:
1314         {
1315                 int nviews = display[1] ? 2 : 1;
1316                 int next_view = (current_view + 1) % nviews;
1317
1318                 if (next_view == current_view) {
1319                         report("Only one view is displayed");
1320                         break;
1321                 }
1322
1323                 current_view = next_view;
1324                 /* Blur out the title of the previous view. */
1325                 update_view_title(view);
1326                 report("");
1327                 break;
1328         }
1329         case REQ_TOGGLE_LINE_NUMBERS:
1330                 opt_line_number = !opt_line_number;
1331                 redraw_view(view);
1332                 break;
1333
1334         case REQ_PROMPT:
1335                 /* Always reload^Wrerun commands from the prompt. */
1336                 open_view(view, opt_request, OPEN_RELOAD);
1337                 break;
1338
1339         case REQ_STOP_LOADING:
1340                 foreach_view (view, i) {
1341                         if (view->pipe)
1342                                 report("Stopped loaded of %s view", view->name),
1343                         end_update(view);
1344                 }
1345                 break;
1346
1347         case REQ_SHOW_VERSION:
1348                 report("Version: %s", VERSION);
1349                 return TRUE;
1350
1351         case REQ_SCREEN_RESIZE:
1352                 resize_display();
1353                 /* Fall-through */
1354         case REQ_SCREEN_REDRAW:
1355                 foreach_view (view, i) {
1356                         redraw_view(view);
1357                         update_view_title(view);
1358                 }
1359                 break;
1360
1361         case REQ_SCREEN_UPDATE:
1362                 doupdate();
1363                 return TRUE;
1364
1365         case REQ_QUIT:
1366                 return FALSE;
1367
1368         default:
1369                 /* An unknown key will show most commonly used commands. */
1370                 report("%s", HELP);
1371                 return TRUE;
1372         }
1373
1374         return TRUE;
1375 }
1376
1377
1378 /*
1379  * View backend handlers
1380  */
1381
1382 static bool
1383 pager_draw(struct view *view, unsigned int lineno)
1384 {
1385         enum line_type type;
1386         char *line;
1387         int linelen;
1388         int attr;
1389
1390         if (view->offset + lineno >= view->lines)
1391                 return FALSE;
1392
1393         line = view->line[view->offset + lineno];
1394         type = get_line_type(line);
1395
1396         if (view->offset + lineno == view->lineno) {
1397                 if (type == LINE_COMMIT) {
1398                         string_copy(view->ref, line + 7);
1399                         string_copy(ref_commit, view->ref);
1400                 }
1401
1402                 type = LINE_CURSOR;
1403         }
1404
1405         attr = get_line_attr(type);
1406         wattrset(view->win, attr);
1407
1408         linelen = strlen(line);
1409         linelen = MIN(linelen, view->width);
1410
1411         if (opt_line_number) {
1412                 static char indent[] = "                    ";
1413                 unsigned long real_lineno = view->offset + lineno + 1;
1414                 int col = 0;
1415
1416                 if (real_lineno == 1 || (real_lineno % opt_num_interval) == 0)
1417                         mvwprintw(view->win, lineno, 0, "%.*d", view->digits, real_lineno);
1418
1419                 else if (view->digits < sizeof(indent))
1420                         mvwaddnstr(view->win, lineno, 0, indent, view->digits);
1421
1422                 waddstr(view->win, ": ");
1423
1424                 while (line) {
1425                         if (*line == '\t') {
1426                                 waddnstr(view->win, "        ", 8 - (col % 8));
1427                                 col += 8 - (col % 8);
1428                                 line++;
1429
1430                         } else {
1431                                 char *tab = strchr(line, '\t');
1432
1433                                 if (tab)
1434                                         waddnstr(view->win, line, tab - line);
1435                                 else
1436                                         waddstr(view->win, line);
1437                                 col += tab - line;
1438                                 line = tab;
1439                         }
1440                 }
1441                 waddstr(view->win, line);
1442
1443         } else {
1444 #if 0
1445                 /* NOTE: Code for only highlighting the text on the cursor line.
1446                  * Kept since I've not yet decided whether to highlight the
1447                  * entire line or not. --fonseca */
1448                 /* No empty lines makes cursor drawing and clearing implicit. */
1449                 if (!*line)
1450                         line = " ", linelen = 1;
1451 #endif
1452                 mvwaddnstr(view->win, lineno, 0, line, linelen);
1453         }
1454
1455         /* Paint the rest of the line if it's the cursor line. */
1456         if (type == LINE_CURSOR)
1457                 wchgat(view->win, -1, 0, type, NULL);
1458
1459         return TRUE;
1460 }
1461
1462 static bool
1463 pager_read(struct view *view, char *line)
1464 {
1465         view->line[view->lines] = strdup(line);
1466         if (!view->line[view->lines])
1467                 return FALSE;
1468
1469         view->lines++;
1470         return TRUE;
1471 }
1472
1473 static bool
1474 pager_enter(struct view *view)
1475 {
1476         char *line = view->line[view->lineno];
1477
1478         if (get_line_type(line) == LINE_COMMIT) {
1479                 open_view(view, REQ_VIEW_DIFF, OPEN_DEFAULT);
1480         }
1481
1482         return TRUE;
1483 }
1484
1485 static struct view_ops pager_ops = {
1486         "line",
1487         pager_draw,
1488         pager_read,
1489         pager_enter,
1490 };
1491
1492
1493 static struct ref **get_refs(char *id);
1494
1495 static bool
1496 main_draw(struct view *view, unsigned int lineno)
1497 {
1498         char buf[DATE_COLS + 1];
1499         struct commit *commit;
1500         enum line_type type;
1501         int cols = 0;
1502         size_t timelen;
1503
1504         if (view->offset + lineno >= view->lines)
1505                 return FALSE;
1506
1507         commit = view->line[view->offset + lineno];
1508         if (!*commit->author)
1509                 return FALSE;
1510
1511         if (view->offset + lineno == view->lineno) {
1512                 string_copy(view->ref, commit->id);
1513                 string_copy(ref_commit, view->ref);
1514                 type = LINE_CURSOR;
1515         } else {
1516                 type = LINE_MAIN_COMMIT;
1517         }
1518
1519         wmove(view->win, lineno, cols);
1520         wattrset(view->win, get_line_attr(LINE_MAIN_DATE));
1521
1522         timelen = strftime(buf, sizeof(buf), DATE_FORMAT, &commit->time);
1523         waddnstr(view->win, buf, timelen);
1524         waddstr(view->win, " ");
1525
1526         cols += DATE_COLS;
1527         wmove(view->win, lineno, cols);
1528         wattrset(view->win, get_line_attr(LINE_MAIN_AUTHOR));
1529
1530         if (strlen(commit->author) > 19) {
1531                 waddnstr(view->win, commit->author, 18);
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         cols += 20;
1539         wattrset(view->win, A_NORMAL);
1540         mvwaddch(view->win, lineno, cols, ACS_LTEE);
1541         wmove(view->win, lineno, cols + 2);
1542
1543         if (commit->refs) {
1544                 size_t i = 0;
1545
1546                 do {
1547                         if (commit->refs[i]->tag)
1548                                 wattrset(view->win, get_line_attr(LINE_MAIN_TAG));
1549                         else
1550                                 wattrset(view->win, get_line_attr(LINE_MAIN_REF));
1551                         waddstr(view->win, "[");
1552                         waddstr(view->win, commit->refs[i]->name);
1553                         waddstr(view->win, "]");
1554                         wattrset(view->win, A_NORMAL);
1555                         waddstr(view->win, " ");
1556                 } while (commit->refs[i++]->next);
1557         }
1558
1559         wattrset(view->win, get_line_attr(type));
1560         waddstr(view->win, commit->title);
1561         wattrset(view->win, A_NORMAL);
1562
1563         return TRUE;
1564 }
1565
1566 /* Reads git log --pretty=raw output and parses it into the commit struct. */
1567 static bool
1568 main_read(struct view *view, char *line)
1569 {
1570         enum line_type type = get_line_type(line);
1571         struct commit *commit;
1572
1573         switch (type) {
1574         case LINE_COMMIT:
1575                 commit = calloc(1, sizeof(struct commit));
1576                 if (!commit)
1577                         return FALSE;
1578
1579                 line += STRING_SIZE("commit ");
1580
1581                 view->line[view->lines++] = commit;
1582                 string_copy(commit->id, line);
1583                 commit->refs = get_refs(commit->id);
1584                 break;
1585
1586         case LINE_AUTHOR:
1587         {
1588                 char *ident = line + STRING_SIZE("author ");
1589                 char *end = strchr(ident, '<');
1590
1591                 if (end) {
1592                         for (; end > ident && isspace(end[-1]); end--) ;
1593                         *end = 0;
1594                 }
1595
1596                 commit = view->line[view->lines - 1];
1597                 string_copy(commit->author, ident);
1598
1599                 /* Parse epoch and timezone */
1600                 if (end) {
1601                         char *secs = strchr(end + 1, '>');
1602                         char *zone;
1603                         time_t time;
1604
1605                         if (!secs || secs[1] != ' ')
1606                                 break;
1607
1608                         secs += 2;
1609                         time = (time_t) atol(secs);
1610                         zone = strchr(secs, ' ');
1611                         if (zone && strlen(zone) == STRING_SIZE(" +0700")) {
1612                                 long tz;
1613
1614                                 zone++;
1615                                 tz  = ('0' - zone[1]) * 60 * 60 * 10;
1616                                 tz += ('0' - zone[2]) * 60 * 60;
1617                                 tz += ('0' - zone[3]) * 60;
1618                                 tz += ('0' - zone[4]) * 60;
1619
1620                                 if (zone[0] == '-')
1621                                         tz = -tz;
1622
1623                                 time -= tz;
1624                         }
1625                         gmtime_r(&time, &commit->time);
1626                 }
1627                 break;
1628         }
1629         default:
1630                 /* We should only ever end up here if there has already been a
1631                  * commit line, however, be safe. */
1632                 if (view->lines == 0)
1633                         break;
1634
1635                 /* Fill in the commit title if it has not already been set. */
1636                 commit = view->line[view->lines - 1];
1637                 if (commit->title[0])
1638                         break;
1639
1640                 /* Require titles to start with a non-space character at the
1641                  * offset used by git log. */
1642                 /* FIXME: More gracefull handling of titles; append "..." to
1643                  * shortened titles, etc. */
1644                 if (strncmp(line, "    ", 4) ||
1645                     isspace(line[4]))
1646                         break;
1647
1648                 string_copy(commit->title, line + 4);
1649         }
1650
1651         return TRUE;
1652 }
1653
1654 static bool
1655 main_enter(struct view *view)
1656 {
1657         open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT | OPEN_BACKGROUNDED);
1658         return TRUE;
1659 }
1660
1661 static struct view_ops main_ops = {
1662         "commit",
1663         main_draw,
1664         main_read,
1665         main_enter,
1666 };
1667
1668
1669 /*
1670  * Status management
1671  */
1672
1673 /* Whether or not the curses interface has been initialized. */
1674 bool cursed = FALSE;
1675
1676 /* The status window is used for polling keystrokes. */
1677 static WINDOW *status_win;
1678
1679 /* Update status and title window. */
1680 static void
1681 report(const char *msg, ...)
1682 {
1683         va_list args;
1684
1685         /* Update the title window first, so the cursor ends up in the status
1686          * window. */
1687         update_view_title(display[current_view]);
1688
1689         va_start(args, msg);
1690
1691         werase(status_win);
1692         wmove(status_win, 0, 0);
1693         if (*msg)
1694                 vwprintw(status_win, msg, args);
1695         wrefresh(status_win);
1696
1697         va_end(args);
1698 }
1699
1700 /* Controls when nodelay should be in effect when polling user input. */
1701 static void
1702 set_nonblocking_input(bool loading)
1703 {
1704         /* The number of loading views. */
1705         static unsigned int nloading;
1706
1707         if ((loading == FALSE && nloading-- == 1) ||
1708             (loading == TRUE  && nloading++ == 0))
1709                 nodelay(status_win, loading);
1710 }
1711
1712 static void
1713 init_display(void)
1714 {
1715         int x, y;
1716
1717         /* Initialize the curses library */
1718         if (isatty(STDIN_FILENO)) {
1719                 cursed = !!initscr();
1720         } else {
1721                 /* Leave stdin and stdout alone when acting as a pager. */
1722                 FILE *io = fopen("/dev/tty", "r+");
1723
1724                 cursed = !!newterm(NULL, io, io);
1725         }
1726
1727         if (!cursed)
1728                 die("Failed to initialize curses");
1729
1730         nonl();         /* Tell curses not to do NL->CR/NL on output */
1731         cbreak();       /* Take input chars one at a time, no wait for \n */
1732         noecho();       /* Don't echo input */
1733         leaveok(stdscr, TRUE);
1734
1735         if (has_colors())
1736                 init_colors();
1737
1738         getmaxyx(stdscr, y, x);
1739         status_win = newwin(1, 0, y - 1, 0);
1740         if (!status_win)
1741                 die("Failed to create status window");
1742
1743         /* Enable keyboard mapping */
1744         keypad(status_win, TRUE);
1745         wbkgdset(status_win, get_line_attr(LINE_STATUS));
1746 }
1747
1748
1749 /*
1750  * Repository references
1751  */
1752
1753 static struct ref *refs;
1754 size_t refs_size;
1755
1756 static struct ref **
1757 get_refs(char *id)
1758 {
1759         struct ref **id_refs = NULL;
1760         size_t id_refs_size = 0;
1761         size_t i;
1762
1763         for (i = 0; i < refs_size; i++) {
1764                 struct ref **tmp;
1765
1766                 if (strcmp(id, refs[i].id))
1767                         continue;
1768
1769                 tmp = realloc(id_refs, (id_refs_size + 1) * sizeof(*id_refs));
1770                 if (!tmp) {
1771                         if (id_refs)
1772                                 free(id_refs);
1773                         return NULL;
1774                 }
1775
1776                 id_refs = tmp;
1777                 if (id_refs_size > 0)
1778                         id_refs[id_refs_size - 1]->next = 1;
1779                 id_refs[id_refs_size] = &refs[i];
1780
1781                 /* XXX: The properties of the commit chains ensures that we can
1782                  * safely modify the shared ref. The repo references will
1783                  * always be similar for the same id. */
1784                 id_refs[id_refs_size]->next = 0;
1785                 id_refs_size++;
1786         }
1787
1788         return id_refs;
1789 }
1790
1791 static int
1792 load_refs(void)
1793 {
1794         char *cmd_env = getenv("TIG_LS_REMOTE");
1795         char *cmd = cmd_env ? cmd_env : TIG_LS_REMOTE;
1796         FILE *pipe = popen(cmd, "r");
1797         char buffer[BUFSIZ];
1798         char *line;
1799
1800         if (!pipe)
1801                 return ERR;
1802
1803         while ((line = fgets(buffer, sizeof(buffer), pipe))) {
1804                 char *name = strchr(line, '\t');
1805                 struct ref *ref;
1806                 int namelen;
1807                 bool tag = FALSE;
1808                 bool tag_commit = FALSE;
1809
1810                 if (!name)
1811                         continue;
1812
1813                 *name++ = 0;
1814                 namelen = strlen(name) - 1;
1815                 if (name[namelen - 1] == '}') {
1816                         while (namelen > 0 && name[namelen] != '^')
1817                                 namelen--;
1818                         if (namelen > 0)
1819                                 tag_commit = TRUE;
1820                 }
1821                 name[namelen] = 0;
1822
1823                 if (!strncmp(name, "refs/tags/", STRING_SIZE("refs/tags/"))) {
1824                         if (!tag_commit)
1825                                 continue;
1826                         name += STRING_SIZE("refs/tags/");
1827                         tag = TRUE;
1828
1829                 } else if (!strncmp(name, "refs/heads/", STRING_SIZE("refs/heads/"))) {
1830                         name += STRING_SIZE("refs/heads/");
1831
1832                 } else if (!strcmp(name, "HEAD")) {
1833                         continue;
1834                 }
1835
1836                 refs = realloc(refs, sizeof(*refs) * (refs_size + 1));
1837                 if (!refs)
1838                         return ERR;
1839
1840                 ref = &refs[refs_size++];
1841                 ref->tag = tag;
1842                 ref->name = strdup(name);
1843                 if (!ref->name)
1844                         return ERR;
1845
1846                 string_copy(ref->id, line);
1847         }
1848
1849         if (ferror(pipe))
1850                 return ERR;
1851
1852         pclose(pipe);
1853
1854         return OK;
1855 }
1856
1857 /*
1858  * Main
1859  */
1860
1861 static void
1862 quit(int sig)
1863 {
1864         /* XXX: Restore tty modes and let the OS cleanup the rest! */
1865         if (cursed)
1866                 endwin();
1867         exit(0);
1868 }
1869
1870 static void die(const char *err, ...)
1871 {
1872         va_list args;
1873
1874         endwin();
1875
1876         va_start(args, err);
1877         fputs("tig: ", stderr);
1878         vfprintf(stderr, err, args);
1879         fputs("\n", stderr);
1880         va_end(args);
1881
1882         exit(1);
1883 }
1884
1885 int
1886 main(int argc, char *argv[])
1887 {
1888         struct view *view;
1889         enum request request;
1890         size_t i;
1891
1892         signal(SIGINT, quit);
1893
1894         if (!parse_options(argc, argv))
1895                 return 0;
1896
1897         if (load_refs() == ERR)
1898                 die("Failed to load refs.");
1899
1900         for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
1901                 view->cmd_env = getenv(view->cmd_env);
1902
1903         request = opt_request;
1904
1905         init_display();
1906
1907         while (view_driver(display[current_view], request)) {
1908                 int key;
1909                 int i;
1910
1911                 foreach_view (view, i)
1912                         update_view(view);
1913
1914                 /* Refresh, accept single keystroke of input */
1915                 key = wgetch(status_win);
1916                 request = get_request(key);
1917
1918                 /* Some low-level request handling. This keeps handling of
1919                  * status_win restricted. */
1920                 switch (request) {
1921                 case REQ_PROMPT:
1922                         report(":");
1923                         /* Temporarily switch to line-oriented and echoed
1924                          * input. */
1925                         nocbreak();
1926                         echo();
1927
1928                         if (wgetnstr(status_win, opt_cmd + 4, sizeof(opt_cmd) - 4) == OK) {
1929                                 memcpy(opt_cmd, "git ", 4);
1930                                 opt_request = REQ_VIEW_PAGER;
1931                         } else {
1932                                 request = ERR;
1933                         }
1934
1935                         noecho();
1936                         cbreak();
1937                         break;
1938
1939                 case REQ_SCREEN_RESIZE:
1940                 {
1941                         int height, width;
1942
1943                         getmaxyx(stdscr, height, width);
1944
1945                         /* Resize the status view and let the view driver take
1946                          * care of resizing the displayed views. */
1947                         wresize(status_win, 1, width);
1948                         mvwin(status_win, height - 1, 0);
1949                         wrefresh(status_win);
1950                         break;
1951                 }
1952                 default:
1953                         break;
1954                 }
1955         }
1956
1957         quit(0);
1958
1959         return 0;
1960 }
1961
1962 /**
1963  * TODO
1964  * ----
1965  * Features that should be explored.
1966  *
1967  * - Searching.
1968  *
1969  * - Locale support.
1970  *
1971  * COPYRIGHT
1972  * ---------
1973  * Copyright (c) Jonas Fonseca <fonseca@diku.dk>, 2006
1974  *
1975  * This program is free software; you can redistribute it and/or modify
1976  * it under the terms of the GNU General Public License as published by
1977  * the Free Software Foundation; either version 2 of the License, or
1978  * (at your option) any later version.
1979  *
1980  * SEE ALSO
1981  * --------
1982  * [verse]
1983  * link:http://www.kernel.org/pub/software/scm/git/docs/[git(7)],
1984  * link:http://www.kernel.org/pub/software/scm/cogito/docs/[cogito(7)]
1985  * gitk(1): git repository browser written using tcl/tk,
1986  * gitview(1): git repository browser written using python/gtk.
1987  **/