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