Lot's of cleanups and fixes
[tig] / tig.c
1 /**
2  * TIG(1)
3  * ======
4  *
5  * NAME
6  * ----
7  * tig - text-mode interface for git
8  *
9  * SYNOPSIS
10  * --------
11  * [verse]
12  * tig [options]
13  * tig [options] log  [git log options]
14  * tig [options] diff [git diff options]
15  * tig [options] <    [git log or git diff output]
16  *
17  * DESCRIPTION
18  * -----------
19  * Browse changes in a git repository.
20  **/
21
22 #ifndef DEBUG
23 #define NDEBUG
24 #endif
25
26 #ifndef VERSION
27 #define VERSION "tig-0.1"
28 #endif
29
30 #include <assert.h>
31 #include <errno.h>
32 #include <ctype.h>
33 #include <signal.h>
34 #include <stdarg.h>
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38 #include <time.h>
39
40 #include <curses.h>
41 #include <form.h>
42
43 static void die(const char *err, ...);
44 static void report(const char *msg, ...);
45
46 /* Some ascii-shorthands that fit into the ncurses namespace. */
47 #define KEY_TAB         9
48 #define KEY_ESC         27
49 #define KEY_DEL         127
50
51 /* View requests */
52 /* REQ_* values from form.h is used as a basis for user actions. */
53 enum request {
54         /* Offset new values relative to MAX_COMMAND from form.h. */
55         REQ_OFFSET = MAX_COMMAND,
56
57         /* XXX: Keep the view request first and in sync with views[]. */
58         REQ_DIFF,
59         REQ_LOG,
60         REQ_MAIN,
61
62         REQ_QUIT,
63         REQ_VERSION,
64         REQ_STOP,
65         REQ_UPDATE,
66         REQ_REDRAW,
67         REQ_FIRST_LINE,
68         REQ_LAST_LINE,
69         REQ_LINE_NUMBER,
70 };
71
72 /* The request are used for adressing the view array. */
73 #define VIEW_OFFSET(r)  ((r) - REQ_OFFSET - 1)
74
75 /* Size of symbolic or SHA1 ID. */
76 #define SIZEOF_REF      256
77
78 /* This color name can be used to refer to the default term colors. */
79 #define COLOR_DEFAULT   (-1)
80
81 /* The format and size of the date column in the main view. */
82 #define DATE_FORMAT     "%Y-%m-%d %H:%M"
83 #define DATE_COLS       (STRING_SIZE("2006-04-29 14:21") + 1)
84
85 /* The interval between line numbers. */
86 #define NUMBER_INTERVAL 5
87
88 #define ABS(x)          ((x) >= 0 ? (x) : -(x))
89 #define MIN(x, y)       ((x) < (y) ? (x) : (y))
90
91 #define ARRAY_SIZE(x)   (sizeof(x) / sizeof(x[0]))
92 #define STRING_SIZE(x)  (sizeof(x) - 1)
93
94 struct commit {
95         char id[41];
96         char title[75];
97         char author[75];
98         struct tm time;
99 };
100
101
102 static inline void
103 string_ncopy(char *dst, char *src, int dstlen)
104 {
105         strncpy(dst, src, dstlen - 1);
106         dst[dstlen - 1] = 0;
107 }
108
109 /* Shorthand for safely copying into a fixed buffer. */
110 #define string_copy(dst, src) \
111         string_ncopy(dst, src, sizeof(dst))
112
113
114 /**
115  * OPTIONS
116  * -------
117  **/
118
119 static int opt_line_number;
120 static int opt_request = REQ_MAIN;
121
122 char head_id[SIZEOF_REF] = "HEAD";
123 char commit_id[SIZEOF_REF] = "HEAD";
124
125 /* Returns the index of log or diff command or -1 to exit. */
126 static int
127 parse_options(int argc, char *argv[])
128 {
129         int i;
130
131         for (i = 1; i < argc; i++) {
132                 char *opt = argv[i];
133
134                 /**
135                  * log [options]::
136                  *      git log options.
137                  **/
138                 if (!strcmp(opt, "log")) {
139                         opt_request = REQ_LOG;
140                         return i;
141
142                 /**
143                  * diff [options]::
144                  *      git diff options.
145                  **/
146                 } else if (!strcmp(opt, "diff")) {
147                         opt_request = REQ_DIFF;
148                         return i;
149
150                 /**
151                  * -l::
152                  *      Start up in log view.
153                  **/
154                 } else if (!strcmp(opt, "-l")) {
155                         opt_request = REQ_LOG;
156
157                 /**
158                  * -d::
159                  *      Start up in diff view.
160                  **/
161                 } else if (!strcmp(opt, "-d")) {
162                         opt_request = REQ_DIFF;
163
164                 /**
165                  * -n, --line-number::
166                  *      Prefix line numbers in log and diff view.
167                  **/
168                 } else if (!strcmp(opt, "-n") ||
169                            !strcmp(opt, "--line-number")) {
170                         opt_line_number = 1;
171
172                 /**
173                  * -v, --version::
174                  *      Show version and exit.
175                  **/
176                 } else if (!strcmp(opt, "-v") ||
177                            !strcmp(opt, "--version")) {
178                         printf("tig version %s\n", VERSION);
179                         return -1;
180
181                 /**
182                  * ref::
183                  *      Commit reference, symbolic or raw SHA1 ID.
184                  **/
185                 } else if (opt[0] && opt[0] != '-') {
186                         string_copy(head_id, opt);
187                         string_copy(commit_id, opt);
188
189                 } else {
190                         die("unknown command '%s'", opt);
191                 }
192         }
193
194         return i;
195 }
196
197
198 /*
199  * Line-oriented content detection.
200  */
201
202 enum line_type {
203         LINE_DEFAULT,
204         LINE_AUTHOR,
205         LINE_AUTHOR_IDENT,
206         LINE_COMMIT,
207         LINE_COMMITTER,
208         LINE_CURSOR,
209         LINE_DATE,
210         LINE_DIFF,
211         LINE_DIFF_ADD,
212         LINE_DIFF_CHUNK,
213         LINE_DIFF_COPY,
214         LINE_DIFF_DEL,
215         LINE_DIFF_DISSIM,
216         LINE_DIFF_NEWMODE,
217         LINE_DIFF_OLDMODE,
218         LINE_DIFF_RENAME,
219         LINE_DIFF_SIM,
220         LINE_DIFF_TREE,
221         LINE_INDEX,
222         LINE_MAIN_AUTHOR,
223         LINE_MAIN_COMMIT,
224         LINE_MAIN_DATE,
225         LINE_MAIN_DELIM,
226         LINE_MERGE,
227         LINE_PARENT,
228         LINE_SIGNOFF,
229         LINE_STATUS,
230         LINE_TITLE,
231         LINE_TREE,
232 };
233
234 struct line_info {
235         enum line_type type;
236         char *line;
237         int linelen;
238
239         int fg;
240         int bg;
241         int attr;
242 };
243
244 #define LINE(type, line, fg, bg, attr) \
245         { LINE_##type, (line), STRING_SIZE(line), (fg), (bg), (attr) }
246
247 static struct line_info line_info[] = {
248         /* Diff markup */
249         LINE(DIFF,         "diff --git ",       COLOR_YELLOW,   COLOR_DEFAULT,  0),
250         LINE(INDEX,        "index ",            COLOR_BLUE,     COLOR_DEFAULT,  0),
251         LINE(DIFF_CHUNK,   "@@",                COLOR_MAGENTA,  COLOR_DEFAULT,  0),
252         LINE(DIFF_ADD,     "+",                 COLOR_GREEN,    COLOR_DEFAULT,  0),
253         LINE(DIFF_DEL,     "-",                 COLOR_RED,      COLOR_DEFAULT,  0),
254         LINE(DIFF_OLDMODE, "old mode ",         COLOR_YELLOW,   COLOR_DEFAULT,  0),
255         LINE(DIFF_NEWMODE, "new mode ",         COLOR_YELLOW,   COLOR_DEFAULT,  0),
256         LINE(DIFF_COPY,    "copy ",             COLOR_YELLOW,   COLOR_DEFAULT,  0),
257         LINE(DIFF_RENAME,  "rename ",           COLOR_YELLOW,   COLOR_DEFAULT,  0),
258         LINE(DIFF_SIM,     "similarity ",       COLOR_YELLOW,   COLOR_DEFAULT,  0),
259         LINE(DIFF_DISSIM,  "dissimilarity ",    COLOR_YELLOW,   COLOR_DEFAULT,  0),
260
261         /* Pretty print commit header */
262         LINE(AUTHOR,       "Author: ",          COLOR_CYAN,     COLOR_DEFAULT,  0),
263         LINE(MERGE,        "Merge: ",           COLOR_BLUE,     COLOR_DEFAULT,  0),
264         LINE(DATE,         "Date:   ",          COLOR_YELLOW,   COLOR_DEFAULT,  0),
265
266         /* Raw commit header */
267         LINE(COMMIT,       "commit ",           COLOR_GREEN,    COLOR_DEFAULT,  0),
268         LINE(PARENT,       "parent ",           COLOR_BLUE,     COLOR_DEFAULT,  0),
269         LINE(TREE,         "tree ",             COLOR_BLUE,     COLOR_DEFAULT,  0),
270         LINE(AUTHOR_IDENT, "author ",           COLOR_CYAN,     COLOR_DEFAULT,  0),
271         LINE(COMMITTER,    "committer ",        COLOR_MAGENTA,  COLOR_DEFAULT,  0),
272
273         /* Misc */
274         LINE(DIFF_TREE,    "diff-tree ",        COLOR_BLUE,     COLOR_DEFAULT,  0),
275         LINE(SIGNOFF,      "    Signed-off-by", COLOR_YELLOW,   COLOR_DEFAULT,  0),
276
277         /* UI colors */
278         LINE(DEFAULT,      "",  COLOR_DEFAULT,  COLOR_DEFAULT,  A_NORMAL),
279         LINE(CURSOR,       "",  COLOR_WHITE,    COLOR_GREEN,    A_BOLD),
280         LINE(STATUS,       "",  COLOR_GREEN,    COLOR_DEFAULT,  0),
281         LINE(TITLE,        "",  COLOR_YELLOW,   COLOR_BLUE,     A_BOLD),
282         LINE(MAIN_DATE,    "",  COLOR_BLUE,     COLOR_DEFAULT,  0),
283         LINE(MAIN_AUTHOR,  "",  COLOR_GREEN,    COLOR_DEFAULT,  0),
284         LINE(MAIN_COMMIT,  "",  COLOR_DEFAULT,  COLOR_DEFAULT,  0),
285         LINE(MAIN_DELIM,   "",  COLOR_MAGENTA,  COLOR_DEFAULT,  0),
286 };
287
288 static struct line_info *
289 get_line_info(char *line)
290 {
291         int linelen = strlen(line);
292         int i;
293
294         for (i = 0; i < ARRAY_SIZE(line_info); i++) {
295                 if (linelen < line_info[i].linelen
296                     || strncasecmp(line_info[i].line, line, line_info[i].linelen))
297                         continue;
298
299                 return &line_info[i];
300         }
301
302         return NULL;
303 }
304
305 static enum line_type
306 get_line_type(char *line)
307 {
308         struct line_info *info = get_line_info(line);
309
310         return info ? info->type : LINE_DEFAULT;
311 }
312
313 static int
314 get_line_attr(enum line_type type)
315 {
316         int i;
317
318         for (i = 0; i < ARRAY_SIZE(line_info); i++)
319                 if (line_info[i].type == type)
320                         return COLOR_PAIR(line_info[i].type) | line_info[i].attr;
321
322         return A_NORMAL;
323 }
324
325 static void
326 init_colors(void)
327 {
328         int default_bg = COLOR_BLACK;
329         int default_fg = COLOR_WHITE;
330         int i;
331
332         start_color();
333
334         if (use_default_colors() != ERR) {
335                 default_bg = -1;
336                 default_fg = -1;
337         }
338
339         for (i = 0; i < ARRAY_SIZE(line_info); i++) {
340                 struct line_info *info = &line_info[i];
341                 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
342                 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
343
344                 init_pair(info->type, fg, bg);
345         }
346 }
347
348
349 /**
350  * KEYS
351  * ----
352  *
353  * d::
354  *      diff
355  * l::
356  *      log
357  * q::
358  *      quit
359  * r::
360  *      redraw screen
361  * s::
362  *      stop all background loading
363  * j::
364  *      down
365  * k::
366  *      up
367  * h, ?::
368  *      help
369  * v::
370  *      version
371  **/
372
373 #define HELP "(d)iff, (l)og, (m)ain, (q)uit, (v)ersion, (h)elp"
374
375 struct keymap {
376         int alias;
377         int request;
378 };
379
380 struct keymap keymap[] = {
381         /* Cursor navigation */
382         { KEY_UP,       REQ_PREV_LINE },
383         { 'k',          REQ_PREV_LINE },
384         { KEY_DOWN,     REQ_NEXT_LINE },
385         { 'j',          REQ_NEXT_LINE },
386         { KEY_HOME,     REQ_FIRST_LINE },
387         { KEY_END,      REQ_LAST_LINE },
388         { KEY_NPAGE,    REQ_NEXT_PAGE },
389         { KEY_PPAGE,    REQ_PREV_PAGE },
390
391         /* Scrolling */
392         { KEY_IC,       REQ_SCR_BLINE }, /* scroll field backward a line */
393         { KEY_DC,       REQ_SCR_FLINE }, /* scroll field forward a line */
394         { 's',          REQ_SCR_FPAGE }, /* scroll field forward a page */
395         { 'w',          REQ_SCR_BPAGE }, /* scroll field backward a page */
396
397         /* View switching */
398         { 'd',          REQ_DIFF },
399         { 'l',          REQ_LOG },
400         { 'm',          REQ_MAIN },
401
402         /* Line number toggling */
403         { 'n',          REQ_LINE_NUMBER },
404         /* No input from wgetch() with nodelay() enabled. */
405         { ERR,          REQ_UPDATE },
406
407         /* Misc */
408         { KEY_ESC,      REQ_QUIT },
409         { 'q',          REQ_QUIT },
410         { 's',          REQ_STOP },
411         { 'v',          REQ_VERSION },
412         { 'r',          REQ_REDRAW },
413 };
414
415 static int
416 get_request(int request)
417 {
418         int i;
419
420         for (i = 0; i < ARRAY_SIZE(keymap); i++)
421                 if (keymap[i].alias == request)
422                         return keymap[i].request;
423
424         return request;
425 }
426
427
428 /*
429  * Viewer
430  */
431
432 struct view {
433         char *name;
434         char *cmd;
435         char *id;
436
437
438         /* Rendering */
439         int (*read)(struct view *, char *);
440         int (*draw)(struct view *, unsigned int);
441         size_t objsize;         /* Size of objects in the line index */
442
443         WINDOW *win;
444         int height, width;
445
446         /* Navigation */
447         unsigned long offset;   /* Offset of the window top */
448         unsigned long lineno;   /* Current line number */
449
450         /* Buffering */
451         unsigned long lines;    /* Total number of lines */
452         void **line;            /* Line index */
453
454         /* Loading */
455         FILE *pipe;
456 };
457
458 static int pager_draw(struct view *view, unsigned int lineno);
459 static int pager_read(struct view *view, char *line);
460
461 static int main_draw(struct view *view, unsigned int lineno);
462 static int main_read(struct view *view, char *line);
463
464 #define DIFF_CMD \
465         "git log --stat -n1 %s ; echo; " \
466         "git diff --find-copies-harder -B -C %s^ %s"
467
468 #define LOG_CMD \
469         "git log --stat -n100 %s"
470
471 #define MAIN_CMD \
472         "git log --stat --pretty=raw %s"
473
474 /* The status window is used for polling keystrokes. */
475 static WINDOW *status_win;
476 static WINDOW *title_win;
477
478 /* The number of loading views. Controls when nodelay should be in effect when
479  * polling user input. */
480 static unsigned int nloading;
481
482 static struct view views[] = {
483         { "diff",  DIFF_CMD,   commit_id,  pager_read,  pager_draw, sizeof(char) },
484         { "log",   LOG_CMD,    head_id,    pager_read,  pager_draw, sizeof(char) },
485         { "main",  MAIN_CMD,   head_id,    main_read,   main_draw,  sizeof(struct commit) },
486 };
487
488 /* The display array of active views and the index of the current view. */
489 static struct view *display[ARRAY_SIZE(views)];
490 static unsigned int current_view;
491
492 #define foreach_view(view, i) \
493         for (i = 0; i < sizeof(display) && (view = display[i]); i++)
494
495
496 static void
497 redraw_view_from(struct view *view, int lineno)
498 {
499         assert(0 <= lineno && lineno < view->height);
500
501         for (; lineno < view->height; lineno++) {
502                 if (!view->draw(view, lineno))
503                         break;
504         }
505
506         redrawwin(view->win);
507         wrefresh(view->win);
508 }
509
510 static void
511 redraw_view(struct view *view)
512 {
513         wclear(view->win);
514         redraw_view_from(view, 0);
515 }
516
517 static void
518 resize_view(struct view *view)
519 {
520         int lines, cols;
521
522         getmaxyx(stdscr, lines, cols);
523
524         if (view->win) {
525                 mvwin(view->win, 0, 0);
526                 wresize(view->win, lines - 2, cols);
527
528         } else {
529                 view->win = newwin(lines - 2, 0, 0, 0);
530                 if (!view->win) {
531                         report("failed to create %s view", view->name);
532                         return;
533                 }
534                 scrollok(view->win, TRUE);
535         }
536
537         getmaxyx(view->win, view->height, view->width);
538 }
539
540 /* FIXME: Fix percentage. */
541 static void
542 report_position(struct view *view, int all)
543 {
544         report(all ? "line %d of %d (%d%%)"
545                      : "line %d of %d",
546                view->lineno + 1,
547                view->lines,
548                view->lines ? (view->lineno + 1) * 100 / view->lines : 0);
549 }
550
551
552 static void
553 move_view(struct view *view, int lines)
554 {
555         /* The rendering expects the new offset. */
556         view->offset += lines;
557
558         assert(0 <= view->offset && view->offset < view->lines);
559         assert(lines);
560
561         /* Redraw the whole screen if scrolling is pointless. */
562         if (view->height < ABS(lines)) {
563                 redraw_view(view);
564
565         } else {
566                 int line = lines > 0 ? view->height - lines : 0;
567                 int end = line + ABS(lines);
568
569                 wscrl(view->win, lines);
570
571                 for (; line < end; line++) {
572                         if (!view->draw(view, line))
573                                 break;
574                 }
575         }
576
577         /* Move current line into the view. */
578         if (view->lineno < view->offset) {
579                 view->lineno = view->offset;
580                 view->draw(view, 0);
581
582         } else if (view->lineno >= view->offset + view->height) {
583                 view->lineno = view->offset + view->height - 1;
584                 view->draw(view, view->lineno - view->offset);
585         }
586
587         assert(view->offset <= view->lineno && view->lineno < view->lines);
588
589         redrawwin(view->win);
590         wrefresh(view->win);
591
592         report_position(view, lines);
593 }
594
595 static void
596 scroll_view(struct view *view, int request)
597 {
598         int lines = 1;
599
600         switch (request) {
601         case REQ_SCR_FPAGE:
602                 lines = view->height;
603         case REQ_SCR_FLINE:
604                 if (view->offset + lines > view->lines)
605                         lines = view->lines - view->offset;
606
607                 if (lines == 0 || view->offset + view->height >= view->lines) {
608                         report("already at last line");
609                         return;
610                 }
611                 break;
612
613         case REQ_SCR_BPAGE:
614                 lines = view->height;
615         case REQ_SCR_BLINE:
616                 if (lines > view->offset)
617                         lines = view->offset;
618
619                 if (lines == 0) {
620                         report("already at first line");
621                         return;
622                 }
623
624                 lines = -lines;
625                 break;
626         }
627
628         move_view(view, lines);
629 }
630
631 static void
632 navigate_view(struct view *view, int request)
633 {
634         int steps;
635
636         switch (request) {
637         case REQ_FIRST_LINE:
638                 steps = -view->lineno;
639                 break;
640
641         case REQ_LAST_LINE:
642                 steps = view->lines - view->lineno - 1;
643                 break;
644
645         case REQ_PREV_PAGE:
646                 steps = view->height > view->lineno
647                       ? -view->lineno : -view->height;
648                 break;
649
650         case REQ_NEXT_PAGE:
651                 steps = view->lineno + view->height >= view->lines
652                       ? view->lines - view->lineno - 1 : view->height;
653                 break;
654
655         case REQ_PREV_LINE:
656                 steps = -1;
657                 break;
658
659         case REQ_NEXT_LINE:
660                 steps = 1;
661                 break;
662         }
663
664         if (steps <= 0 && view->lineno == 0) {
665                 report("already at first line");
666                 return;
667
668         } else if (steps >= 0 && view->lineno + 1 == view->lines) {
669                 report("already at last line");
670                 return;
671         }
672
673         /* Move the current line */
674         view->lineno += steps;
675         assert(0 <= view->lineno && view->lineno < view->lines);
676
677         /* Repaint the old "current" line if we be scrolling */
678         if (ABS(steps) < view->height)
679                 view->draw(view, view->lineno - steps - view->offset);
680
681         /* Check whether the view needs to be scrolled */
682         if (view->lineno < view->offset ||
683             view->lineno >= view->offset + view->height) {
684                 if (steps < 0 && -steps > view->offset) {
685                         steps = -view->offset;
686
687                 } else if (steps > 0) {
688                         if (view->lineno == view->lines - 1 &&
689                             view->lines > view->height) {
690                                 steps = view->lines - view->offset - 1;
691                                 if (steps >= view->height)
692                                         steps -= view->height - 1;
693                         }
694                 }
695
696                 move_view(view, steps);
697                 return;
698         }
699
700         /* Draw the current line */
701         view->draw(view, view->lineno - view->offset);
702
703         redrawwin(view->win);
704         wrefresh(view->win);
705
706         report_position(view, view->height);
707 }
708
709
710
711 static bool
712 begin_update(struct view *view)
713 {
714         char buf[1024];
715
716         if (view->cmd) {
717                 char *id = view->id;
718
719                 if (snprintf(buf, sizeof(buf), view->cmd, id, id, id) < sizeof(buf))
720                         view->pipe = popen(buf, "r");
721
722                 if (!view->pipe)
723                         return FALSE;
724
725                 if (nloading++ == 0)
726                         nodelay(status_win, TRUE);
727         }
728
729         display[current_view] = view;
730
731         view->offset = 0;
732         view->lines  = 0;
733         view->lineno = 0;
734
735         return TRUE;
736 }
737
738 static void
739 end_update(struct view *view)
740 {
741         wattrset(view->win, A_NORMAL);
742         pclose(view->pipe);
743         view->pipe = NULL;
744
745         if (nloading-- == 1)
746                 nodelay(status_win, FALSE);
747 }
748
749 static int
750 update_view(struct view *view)
751 {
752         char buffer[BUFSIZ];
753         char *line;
754         void **tmp;
755         /* The number of lines to read. If too low it will cause too much
756          * redrawing (and possible flickering), if too high responsiveness
757          * will suffer. */
758         int lines = view->height;
759         int redraw_from = -1;
760
761         if (!view->pipe)
762                 return TRUE;
763
764         /* Only redraw if lines are visible. */
765         if (view->offset + view->height >= view->lines)
766                 redraw_from = view->lines - view->offset;
767
768         tmp = realloc(view->line, sizeof(*view->line) * (view->lines + lines));
769         if (!tmp)
770                 goto alloc_error;
771
772         view->line = tmp;
773
774         while ((line = fgets(buffer, sizeof(buffer), view->pipe))) {
775                 int linelen;
776
777                 linelen = strlen(line);
778                 if (linelen)
779                         line[linelen - 1] = 0;
780
781                 if (!view->read(view, line))
782                         goto alloc_error;
783
784                 if (lines-- == 1)
785                         break;
786         }
787
788         if (redraw_from >= 0) {
789                 /* If this is an incremental update, redraw the previous line
790                  * since for commits some members could have changed. */
791                 if (redraw_from > 0)
792                         redraw_from--;
793
794                 /* Incrementally draw avoids flickering. */
795                 redraw_view_from(view, redraw_from);
796         }
797
798         if (ferror(view->pipe)) {
799                 report("failed to read %s: %s", view->cmd, strerror(errno));
800                 goto end;
801
802         } else if (feof(view->pipe)) {
803                 report_position(view, 0);
804                 goto end;
805         }
806
807         return TRUE;
808
809 alloc_error:
810         report("allocation failure");
811
812 end:
813         end_update(view);
814         return FALSE;
815 }
816
817
818 static struct view *
819 switch_view(struct view *prev, int request)
820 {
821         struct view *view = &views[VIEW_OFFSET(request)];
822         struct view *displayed;
823         int i;
824
825         if (view == prev) {
826                 foreach_view (displayed, i) ;
827
828                 if (i == 1)
829                         report("already in %s view", view->name);
830                 else
831                         report("FIXME: Maximize");
832
833                 return view;
834
835         } else {
836                 foreach_view (displayed, i) {
837                         if (view == displayed) {
838                                 current_view = i;
839                                 report("new current view");
840                                 return view;
841                         }
842                 }
843         }
844
845         if (!view->win)
846                 resize_view(view);
847
848         /* Reload */
849
850         if (view->line) {
851                 for (i = 0; i < view->lines; i++)
852                         if (view->line[i])
853                                 free(view->line[i]);
854
855                 free(view->line);
856                 view->line = NULL;
857         }
858
859         if (prev && prev->pipe)
860                 end_update(prev);
861
862         if (begin_update(view)) {
863                 if (!view->cmd) {
864                         report("%s", HELP);
865                 } else {
866                         /* Clear the old view and let the incremental updating
867                          * refill the screen. */
868                         wclear(view->win);
869                         report("loading...");
870                 }
871         }
872
873         return view;
874 }
875
876
877 /* Process a keystroke */
878 static int
879 view_driver(struct view *view, int key)
880 {
881         int request = get_request(key);
882         int i;
883
884         switch (request) {
885         case REQ_NEXT_LINE:
886         case REQ_PREV_LINE:
887         case REQ_FIRST_LINE:
888         case REQ_LAST_LINE:
889         case REQ_NEXT_PAGE:
890         case REQ_PREV_PAGE:
891                 if (view)
892                         navigate_view(view, request);
893                 break;
894
895         case REQ_SCR_FLINE:
896         case REQ_SCR_BLINE:
897         case REQ_SCR_FPAGE:
898         case REQ_SCR_BPAGE:
899                 if (view)
900                         scroll_view(view, request);
901                 break;
902
903         case REQ_MAIN:
904         case REQ_LOG:
905         case REQ_DIFF:
906                 view = switch_view(view, request);
907                 break;
908
909         case REQ_LINE_NUMBER:
910                 opt_line_number = !opt_line_number;
911                 redraw_view(view);
912                 break;
913
914         case REQ_REDRAW:
915                 redraw_view(view);
916                 break;
917
918         case REQ_STOP:
919                 foreach_view (view, i) {
920                         if (view->pipe) {
921                                 end_update(view);
922                                 scroll_view(view, 0);
923                         }
924                 }
925                 break;
926
927         case REQ_VERSION:
928                 report("version %s", VERSION);
929                 return TRUE;
930
931         case REQ_UPDATE:
932                 doupdate();
933                 return TRUE;
934
935         case REQ_QUIT:
936                 return FALSE;
937
938         default:
939                 report(HELP);
940                 return TRUE;
941         }
942
943         return TRUE;
944 }
945
946
947 /*
948  * Rendering
949  */
950
951 static int
952 pager_draw(struct view *view, unsigned int lineno)
953 {
954         enum line_type type;
955         char *line;
956         int linelen;
957         int attr;
958
959         if (view->offset + lineno >= view->lines)
960                 return FALSE;
961
962         line = view->line[view->offset + lineno];
963         type = get_line_type(line);
964
965         if (view->offset + lineno == view->lineno) {
966                 if (type == LINE_COMMIT)
967                         string_copy(commit_id, line + 7);
968                 type = LINE_CURSOR;
969         }
970
971         attr = get_line_attr(type);
972         wattrset(view->win, attr);
973
974         linelen = strlen(line);
975         linelen = MIN(linelen, view->width);
976
977         if (opt_line_number) {
978                 unsigned int real_lineno = view->offset + lineno + 1;
979                 int col = 1;
980
981                 if (real_lineno == 1 || (real_lineno % NUMBER_INTERVAL) == 0)
982                         mvwprintw(view->win, lineno, 0, "%4d: ", real_lineno);
983                 else
984                         mvwaddstr(view->win, lineno, 0, "    : ");
985
986                 while (line) {
987                         if (*line == '\t') {
988                                 waddnstr(view->win, "        ", 8 - (col % 8));
989                                 col += 8 - (col % 8);
990                                 line++;
991
992                         } else {
993                                 char *tab = strchr(line, '\t');
994
995                                 if (tab)
996                                         waddnstr(view->win, line, tab - line);
997                                 else
998                                         waddstr(view->win, line);
999                                 col += tab - line;
1000                                 line = tab;
1001                         }
1002                 }
1003                 waddstr(view->win, line);
1004
1005         } else {
1006                 /* No empty lines makes cursor drawing and clearing implicit. */
1007                 if (!*line)
1008                         line = " ", linelen = 1;
1009                 mvwaddnstr(view->win, lineno, 0, line, linelen);
1010         }
1011
1012         return TRUE;
1013 }
1014
1015 static int
1016 pager_read(struct view *view, char *line)
1017 {
1018         view->line[view->lines] = strdup(line);
1019         if (!view->line[view->lines])
1020                 return FALSE;
1021
1022         view->lines++;
1023         return TRUE;
1024 }
1025
1026 static int
1027 main_draw(struct view *view, unsigned int lineno)
1028 {
1029         char buf[21];
1030         struct commit *commit;
1031         enum line_type type;
1032         int cols = 0;
1033         size_t timelen;
1034
1035         if (view->offset + lineno >= view->lines)
1036                 return FALSE;
1037
1038         commit = view->line[view->offset + lineno];
1039         if (!*commit->author)
1040                 return FALSE;
1041
1042         if (view->offset + lineno == view->lineno) {
1043                 string_copy(commit_id, commit->id);
1044                 type = LINE_CURSOR;
1045         } else {
1046                 type = LINE_MAIN_COMMIT;
1047         }
1048
1049         wmove(view->win, lineno, cols);
1050         wattrset(view->win, get_line_attr(LINE_MAIN_DATE));
1051
1052         timelen = strftime(buf, sizeof(buf), DATE_FORMAT, &commit->time);
1053         waddnstr(view->win, buf, timelen);
1054         waddstr(view->win, " ");
1055
1056         cols += DATE_COLS;
1057         wmove(view->win, lineno, cols);
1058         wattrset(view->win, get_line_attr(LINE_MAIN_AUTHOR));
1059
1060         if (strlen(commit->author) > 19) {
1061                 waddnstr(view->win, commit->author, 18);
1062                 wattrset(view->win, get_line_attr(LINE_MAIN_DELIM));
1063                 waddch(view->win, '~');
1064         } else {
1065                 waddstr(view->win, commit->author);
1066         }
1067
1068         cols += 20;
1069         wattrset(view->win, A_NORMAL);
1070         mvwaddch(view->win, lineno, cols, ACS_LTEE);
1071         wattrset(view->win, get_line_attr(type));
1072         mvwaddstr(view->win, lineno, cols + 2, commit->title);
1073         wattrset(view->win, A_NORMAL);
1074
1075         return TRUE;
1076 }
1077
1078 /* Reads git log --pretty=raw output and parses it into the commit struct. */
1079 static int
1080 main_read(struct view *view, char *line)
1081 {
1082         enum line_type type = get_line_type(line);
1083         struct commit *commit;
1084
1085         switch (type) {
1086         case LINE_COMMIT:
1087                 commit = calloc(1, sizeof(struct commit));
1088                 if (!commit)
1089                         return FALSE;
1090
1091                 line += STRING_SIZE("commit ");
1092
1093                 view->line[view->lines++] = commit;
1094                 string_copy(commit->id, line);
1095                 break;
1096
1097         case LINE_AUTHOR_IDENT:
1098         {
1099                 char *ident = line + STRING_SIZE("author ");
1100                 char *end = strchr(ident, '<');
1101
1102                 if (end) {
1103                         for (; end > ident && isspace(end[-1]); end--) ;
1104                         *end = 0;
1105                 }
1106
1107                 commit = view->line[view->lines - 1];
1108                 string_copy(commit->author, ident);
1109
1110                 /* Parse epoch and timezone */
1111                 if (end) {
1112                         char *secs = strchr(end + 1, '>');
1113                         char *zone;
1114                         time_t time;
1115
1116                         if (!secs || secs[1] != ' ')
1117                                 break;
1118
1119                         secs += 2;
1120                         time = (time_t) atol(secs);
1121                         zone = strchr(secs, ' ');
1122                         if (zone && strlen(zone) == STRING_SIZE(" +0700")) {
1123                                 long tz;
1124
1125                                 zone++;
1126                                 tz  = ('0' - zone[1]) * 60 * 60 * 10;
1127                                 tz += ('0' - zone[2]) * 60 * 60;
1128                                 tz += ('0' - zone[3]) * 60;
1129                                 tz += ('0' - zone[4]) * 60;
1130
1131                                 if (zone[0] == '-')
1132                                         tz = -tz;
1133
1134                                 time -= tz;
1135                         }
1136                         gmtime_r(&time, &commit->time);
1137                 }
1138                 break;
1139         }
1140         default:
1141                 /* Fill in the commit title */
1142                 commit = view->line[view->lines - 1];
1143                 if (commit->title[0] ||
1144                     strncmp(line, "    ", 4) ||
1145                     isspace(line[5]))
1146                         break;
1147
1148                 string_copy(commit->title, line + 4);
1149         }
1150
1151         return TRUE;
1152 }
1153
1154
1155 /*
1156  * Main
1157  */
1158
1159 static void
1160 quit(int sig)
1161 {
1162         if (status_win)
1163                 delwin(status_win);
1164         if (title_win)
1165                 delwin(title_win);
1166         endwin();
1167
1168         /* FIXME: Shutdown gracefully. */
1169
1170         exit(0);
1171 }
1172
1173 static void die(const char *err, ...)
1174 {
1175         va_list args;
1176
1177         endwin();
1178
1179         va_start(args, err);
1180         fputs("tig: ", stderr);
1181         vfprintf(stderr, err, args);
1182         fputs("\n", stderr);
1183         va_end(args);
1184
1185         exit(1);
1186 }
1187
1188 static void
1189 report(const char *msg, ...)
1190 {
1191         va_list args;
1192
1193         werase(title_win);
1194         wmove(title_win, 0, 0);
1195         wprintw(title_win, "commit %s", commit_id);
1196         wrefresh(title_win);
1197
1198         va_start(args, msg);
1199
1200         werase(status_win);
1201         wmove(status_win, 0, 0);
1202
1203 #if 0
1204         if (display[current_view])
1205                 wprintw(status_win, "%s %4s: ", commit_id, display[current_view]->name);
1206 #endif
1207         vwprintw(status_win, msg, args);
1208         wrefresh(status_win);
1209
1210         va_end(args);
1211 }
1212
1213 int
1214 main(int argc, char *argv[])
1215 {
1216         int x, y;
1217         int request;
1218         int git_cmd;
1219
1220         signal(SIGINT, quit);
1221
1222         git_cmd = parse_options(argc, argv);
1223         if (git_cmd < 0)
1224                 return 0;
1225         if (git_cmd < argc) {
1226                 die("opts");
1227         }
1228
1229         request = opt_request;
1230
1231         initscr();      /* initialize the curses library */
1232         nonl();         /* tell curses not to do NL->CR/NL on output */
1233         cbreak();       /* take input chars one at a time, no wait for \n */
1234         noecho();       /* don't echo input */
1235         leaveok(stdscr, TRUE);
1236         /* curs_set(0); */
1237
1238         if (has_colors())
1239                 init_colors();
1240
1241         getmaxyx(stdscr, y, x);
1242         status_win = newwin(1, 0, y - 1, 0);
1243         if (!status_win)
1244                 die("Failed to create status window");
1245
1246         title_win = newwin(1, 0, y - 2, 0);
1247         if (!title_win)
1248                 die("Failed to create title window");
1249
1250         /* Enable keyboard mapping */
1251         keypad(status_win, TRUE);
1252         wbkgdset(status_win, get_line_attr(LINE_STATUS));
1253         wbkgdset(title_win, get_line_attr(LINE_TITLE));
1254
1255         while (view_driver(display[current_view], request)) {
1256                 struct view *view;
1257                 int i;
1258
1259                 foreach_view (view, i) {
1260                         if (view->pipe) {
1261                                 update_view(view);
1262                         }
1263                 }
1264
1265                 /* Refresh, accept single keystroke of input */
1266                 request = wgetch(status_win);
1267                 if (request == KEY_RESIZE) {
1268                         int lines, cols;
1269
1270                         getmaxyx(stdscr, lines, cols);
1271
1272                         mvwin(status_win, lines - 1, 0);
1273                         wresize(status_win, 1, cols - 1);
1274
1275                         mvwin(title_win, lines - 2, 0);
1276                         wresize(title_win, 1, cols - 1);
1277                 }
1278         }
1279
1280         quit(0);
1281
1282         return 0;
1283 }
1284
1285 /**
1286  * BUGS
1287  * ----
1288  * Known bugs and problems:
1289  *
1290  * Redrawing of the main view while loading::
1291  *      If only part of a commit has been parsed not all fields will be visible
1292  *      or even redrawn when the whole commit have loaded. This can be
1293  *      triggered when continuously moving to the last line. Use 'r' to redraw
1294  *      the whole screen.
1295  *
1296  * TODO
1297  * ----
1298  * Features that should be explored.
1299  *
1300  * - Dynamic scaling of line number indentation.
1301  *
1302  * - Proper command line handling; ability to take the command that should be
1303  *   shown. Example:
1304  *
1305  *      $ tig log -p
1306  *
1307  * - Internal command line (exmode-inspired) which allows to specify what git
1308  *   log or git diff command to run. Example:
1309  *
1310  *      :log -p
1311  *
1312  * - Proper resizing support. I am yet to figure out whether catching SIGWINCH
1313  *   is preferred over using ncurses' built-in support for resizing.
1314  *
1315  * - Locale support.
1316  *
1317  * COPYRIGHT
1318  * ---------
1319  * Copyright (c) Jonas Fonseca, 2006
1320  *
1321  * This program is free software; you can redistribute it and/or modify
1322  * it under the terms of the GNU General Public License as published by
1323  * the Free Software Foundation; either version 2 of the License, or
1324  * (at your option) any later version.
1325  *
1326  * SEE ALSO
1327  * --------
1328  * [verse]
1329  * link:http://www.kernel.org/pub/software/scm/git/docs/[git(7)],
1330  * link:http://www.kernel.org/pub/software/scm/cogito/docs/[cogito(7)]
1331  * gitk(1): git repository browser written using tcl/tk,
1332  * gitview(1): git repository browser written using python/gtk.
1333  **/