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