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