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