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