chiark / gitweb /
Lots of minor UI improvements
[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_WHITE,    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 --cc --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
541 static void
542 move_view(struct view *view, int lines)
543 {
544         /* The rendering expects the new offset. */
545         view->offset += lines;
546
547         assert(0 <= view->offset && view->offset < view->lines);
548         assert(lines);
549
550         /* Redraw the whole screen if scrolling is pointless. */
551         if (view->height < ABS(lines)) {
552                 redraw_view(view);
553
554         } else {
555                 int line = lines > 0 ? view->height - lines : 0;
556                 int end = line + ABS(lines);
557
558                 wscrl(view->win, lines);
559
560                 for (; line < end; line++) {
561                         if (!view->draw(view, line))
562                                 break;
563                 }
564         }
565
566         /* Move current line into the view. */
567         if (view->lineno < view->offset) {
568                 view->lineno = view->offset;
569                 view->draw(view, 0);
570
571         } else if (view->lineno >= view->offset + view->height) {
572                 view->lineno = view->offset + view->height - 1;
573                 view->draw(view, view->lineno - view->offset);
574         }
575
576         assert(view->offset <= view->lineno && view->lineno < view->lines);
577
578         redrawwin(view->win);
579         wrefresh(view->win);
580         report("");
581 }
582
583 static void
584 scroll_view(struct view *view, int request)
585 {
586         int lines = 1;
587
588         switch (request) {
589         case REQ_SCR_FPAGE:
590                 lines = view->height;
591         case REQ_SCR_FLINE:
592                 if (view->offset + lines > view->lines)
593                         lines = view->lines - view->offset;
594
595                 if (lines == 0 || view->offset + view->height >= view->lines) {
596                         report("already at last line");
597                         return;
598                 }
599                 break;
600
601         case REQ_SCR_BPAGE:
602                 lines = view->height;
603         case REQ_SCR_BLINE:
604                 if (lines > view->offset)
605                         lines = view->offset;
606
607                 if (lines == 0) {
608                         report("already at first line");
609                         return;
610                 }
611
612                 lines = -lines;
613                 break;
614         }
615
616         move_view(view, lines);
617 }
618
619 static void
620 navigate_view(struct view *view, int request)
621 {
622         int steps;
623
624         switch (request) {
625         case REQ_FIRST_LINE:
626                 steps = -view->lineno;
627                 break;
628
629         case REQ_LAST_LINE:
630                 steps = view->lines - view->lineno - 1;
631                 break;
632
633         case REQ_PREV_PAGE:
634                 steps = view->height > view->lineno
635                       ? -view->lineno : -view->height;
636                 break;
637
638         case REQ_NEXT_PAGE:
639                 steps = view->lineno + view->height >= view->lines
640                       ? view->lines - view->lineno - 1 : view->height;
641                 break;
642
643         case REQ_PREV_LINE:
644                 steps = -1;
645                 break;
646
647         case REQ_NEXT_LINE:
648                 steps = 1;
649                 break;
650         }
651
652         if (steps <= 0 && view->lineno == 0) {
653                 report("already at first line");
654                 return;
655
656         } else if (steps >= 0 && view->lineno + 1 == view->lines) {
657                 report("already at last line");
658                 return;
659         }
660
661         /* Move the current line */
662         view->lineno += steps;
663         assert(0 <= view->lineno && view->lineno < view->lines);
664
665         /* Repaint the old "current" line if we be scrolling */
666         if (ABS(steps) < view->height)
667                 view->draw(view, view->lineno - steps - view->offset);
668
669         /* Check whether the view needs to be scrolled */
670         if (view->lineno < view->offset ||
671             view->lineno >= view->offset + view->height) {
672                 if (steps < 0 && -steps > view->offset) {
673                         steps = -view->offset;
674
675                 } else if (steps > 0) {
676                         if (view->lineno == view->lines - 1 &&
677                             view->lines > view->height) {
678                                 steps = view->lines - view->offset - 1;
679                                 if (steps >= view->height)
680                                         steps -= view->height - 1;
681                         }
682                 }
683
684                 move_view(view, steps);
685                 return;
686         }
687
688         /* Draw the current line */
689         view->draw(view, view->lineno - view->offset);
690
691         redrawwin(view->win);
692         wrefresh(view->win);
693         report("");
694 }
695
696
697
698 static bool
699 begin_update(struct view *view)
700 {
701         char buf[1024];
702
703         if (view->cmd) {
704                 char *id = view->id;
705
706                 if (snprintf(buf, sizeof(buf), view->cmd, id, id, id) < sizeof(buf))
707                         view->pipe = popen(buf, "r");
708
709                 if (!view->pipe)
710                         return FALSE;
711
712                 if (nloading++ == 0)
713                         nodelay(status_win, TRUE);
714         }
715
716         display[current_view] = view;
717
718         view->offset = 0;
719         view->lines  = 0;
720         view->lineno = 0;
721
722         return TRUE;
723 }
724
725 static void
726 end_update(struct view *view)
727 {
728         wattrset(view->win, A_NORMAL);
729         pclose(view->pipe);
730         view->pipe = NULL;
731
732         if (nloading-- == 1)
733                 nodelay(status_win, FALSE);
734 }
735
736 static int
737 update_view(struct view *view)
738 {
739         char buffer[BUFSIZ];
740         char *line;
741         void **tmp;
742         /* The number of lines to read. If too low it will cause too much
743          * redrawing (and possible flickering), if too high responsiveness
744          * will suffer. */
745         int lines = view->height;
746         int redraw_from = -1;
747
748         if (!view->pipe)
749                 return TRUE;
750
751         /* Only redraw if lines are visible. */
752         if (view->offset + view->height >= view->lines)
753                 redraw_from = view->lines - view->offset;
754
755         tmp = realloc(view->line, sizeof(*view->line) * (view->lines + lines));
756         if (!tmp)
757                 goto alloc_error;
758
759         view->line = tmp;
760
761         while ((line = fgets(buffer, sizeof(buffer), view->pipe))) {
762                 int linelen;
763
764                 linelen = strlen(line);
765                 if (linelen)
766                         line[linelen - 1] = 0;
767
768                 if (!view->read(view, line))
769                         goto alloc_error;
770
771                 if (lines-- == 1)
772                         break;
773         }
774
775         if (redraw_from >= 0) {
776                 /* If this is an incremental update, redraw the previous line
777                  * since for commits some members could have changed. */
778                 if (redraw_from > 0)
779                         redraw_from--;
780
781                 /* Incrementally draw avoids flickering. */
782                 redraw_view_from(view, redraw_from);
783         }
784
785         if (ferror(view->pipe)) {
786                 report("failed to read %s: %s", view->cmd, strerror(errno));
787                 goto end;
788
789         } else if (feof(view->pipe)) {
790                 report("loaded %d lines", view->lines);
791                 goto end;
792         }
793
794         return TRUE;
795
796 alloc_error:
797         report("allocation failure");
798
799 end:
800         end_update(view);
801         return FALSE;
802 }
803
804
805 static struct view *
806 switch_view(struct view *prev, int request)
807 {
808         struct view *view = &views[VIEW_OFFSET(request)];
809         struct view *displayed;
810         int i;
811
812         if (view == prev) {
813                 foreach_view (displayed, i) ;
814
815                 if (i == 1)
816                         report("already in %s view", view->name);
817                 else
818                         report("FIXME: Maximize");
819
820                 return view;
821
822         } else {
823                 foreach_view (displayed, i) {
824                         if (view == displayed) {
825                                 current_view = i;
826                                 report("new current view");
827                                 return view;
828                         }
829                 }
830         }
831
832         if (!view->win)
833                 resize_view(view);
834
835         /* Reload */
836
837         if (view->line) {
838                 for (i = 0; i < view->lines; i++)
839                         if (view->line[i])
840                                 free(view->line[i]);
841
842                 free(view->line);
843                 view->line = NULL;
844         }
845
846         if (prev && prev->pipe)
847                 end_update(prev);
848
849         if (begin_update(view)) {
850                 if (!view->cmd) {
851                         report("%s", HELP);
852                 } else {
853                         /* Clear the old view and let the incremental updating
854                          * refill the screen. */
855                         wclear(view->win);
856                         report("loading...");
857                 }
858         }
859
860         return view;
861 }
862
863
864 /* Process a keystroke */
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_NEXT_LINE:
873         case REQ_PREV_LINE:
874         case REQ_FIRST_LINE:
875         case REQ_LAST_LINE:
876         case REQ_NEXT_PAGE:
877         case REQ_PREV_PAGE:
878                 if (view)
879                         navigate_view(view, request);
880                 break;
881
882         case REQ_SCR_FLINE:
883         case REQ_SCR_BLINE:
884         case REQ_SCR_FPAGE:
885         case REQ_SCR_BPAGE:
886                 if (view)
887                         scroll_view(view, request);
888                 break;
889
890         case REQ_MAIN:
891         case REQ_LOG:
892         case REQ_DIFF:
893                 view = switch_view(view, request);
894                 break;
895
896         case REQ_LINE_NUMBER:
897                 opt_line_number = !opt_line_number;
898                 redraw_view(view);
899                 break;
900
901         case REQ_REDRAW:
902                 redraw_view(view);
903                 break;
904
905         case REQ_STOP:
906                 foreach_view (view, i) {
907                         if (view->pipe) {
908                                 end_update(view);
909                                 scroll_view(view, 0);
910                         }
911                 }
912                 break;
913
914         case REQ_VERSION:
915                 report("version %s", VERSION);
916                 return TRUE;
917
918         case REQ_UPDATE:
919                 doupdate();
920                 return TRUE;
921
922         case REQ_QUIT:
923                 return FALSE;
924
925         default:
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(commit_id, 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 % NUMBER_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                 /* No empty lines makes cursor drawing and clearing implicit. */
994                 if (!*line)
995                         line = " ", linelen = 1;
996                 mvwaddnstr(view->win, lineno, 0, line, linelen);
997         }
998
999         return TRUE;
1000 }
1001
1002 static int
1003 pager_read(struct view *view, char *line)
1004 {
1005         view->line[view->lines] = strdup(line);
1006         if (!view->line[view->lines])
1007                 return FALSE;
1008
1009         view->lines++;
1010         return TRUE;
1011 }
1012
1013 static int
1014 main_draw(struct view *view, unsigned int lineno)
1015 {
1016         char buf[21];
1017         struct commit *commit;
1018         enum line_type type;
1019         int cols = 0;
1020         size_t timelen;
1021
1022         if (view->offset + lineno >= view->lines)
1023                 return FALSE;
1024
1025         commit = view->line[view->offset + lineno];
1026         if (!*commit->author)
1027                 return FALSE;
1028
1029         if (view->offset + lineno == view->lineno) {
1030                 string_copy(commit_id, commit->id);
1031                 type = LINE_CURSOR;
1032         } else {
1033                 type = LINE_MAIN_COMMIT;
1034         }
1035
1036         wmove(view->win, lineno, cols);
1037         wattrset(view->win, get_line_attr(LINE_MAIN_DATE));
1038
1039         timelen = strftime(buf, sizeof(buf), DATE_FORMAT, &commit->time);
1040         waddnstr(view->win, buf, timelen);
1041         waddstr(view->win, " ");
1042
1043         cols += DATE_COLS;
1044         wmove(view->win, lineno, cols);
1045         wattrset(view->win, get_line_attr(LINE_MAIN_AUTHOR));
1046
1047         if (strlen(commit->author) > 19) {
1048                 waddnstr(view->win, commit->author, 18);
1049                 wattrset(view->win, get_line_attr(LINE_MAIN_DELIM));
1050                 waddch(view->win, '~');
1051         } else {
1052                 waddstr(view->win, commit->author);
1053         }
1054
1055         cols += 20;
1056         wattrset(view->win, A_NORMAL);
1057         mvwaddch(view->win, lineno, cols, ACS_LTEE);
1058         wattrset(view->win, get_line_attr(type));
1059         mvwaddstr(view->win, lineno, cols + 2, commit->title);
1060         wattrset(view->win, A_NORMAL);
1061
1062         return TRUE;
1063 }
1064
1065 /* Reads git log --pretty=raw output and parses it into the commit struct. */
1066 static int
1067 main_read(struct view *view, char *line)
1068 {
1069         enum line_type type = get_line_type(line);
1070         struct commit *commit;
1071
1072         switch (type) {
1073         case LINE_COMMIT:
1074                 commit = calloc(1, sizeof(struct commit));
1075                 if (!commit)
1076                         return FALSE;
1077
1078                 line += STRING_SIZE("commit ");
1079
1080                 view->line[view->lines++] = commit;
1081                 string_copy(commit->id, line);
1082                 break;
1083
1084         case LINE_AUTHOR_IDENT:
1085         {
1086                 char *ident = line + STRING_SIZE("author ");
1087                 char *end = strchr(ident, '<');
1088
1089                 if (end) {
1090                         for (; end > ident && isspace(end[-1]); end--) ;
1091                         *end = 0;
1092                 }
1093
1094                 commit = view->line[view->lines - 1];
1095                 string_copy(commit->author, ident);
1096
1097                 /* Parse epoch and timezone */
1098                 if (end) {
1099                         char *secs = strchr(end + 1, '>');
1100                         char *zone;
1101                         time_t time;
1102
1103                         if (!secs || secs[1] != ' ')
1104                                 break;
1105
1106                         secs += 2;
1107                         time = (time_t) atol(secs);
1108                         zone = strchr(secs, ' ');
1109                         if (zone && strlen(zone) == STRING_SIZE(" +0700")) {
1110                                 long tz;
1111
1112                                 zone++;
1113                                 tz  = ('0' - zone[1]) * 60 * 60 * 10;
1114                                 tz += ('0' - zone[2]) * 60 * 60;
1115                                 tz += ('0' - zone[3]) * 60;
1116                                 tz += ('0' - zone[4]) * 60;
1117
1118                                 if (zone[0] == '-')
1119                                         tz = -tz;
1120
1121                                 time -= tz;
1122                         }
1123                         gmtime_r(&time, &commit->time);
1124                 }
1125                 break;
1126         }
1127         default:
1128                 /* Fill in the commit title */
1129                 commit = view->line[view->lines - 1];
1130                 if (commit->title[0] ||
1131                     strncmp(line, "    ", 4) ||
1132                     isspace(line[5]))
1133                         break;
1134
1135                 string_copy(commit->title, line + 4);
1136         }
1137
1138         return TRUE;
1139 }
1140
1141
1142 /*
1143  * Main
1144  */
1145
1146 static void
1147 quit(int sig)
1148 {
1149         if (status_win)
1150                 delwin(status_win);
1151         if (title_win)
1152                 delwin(title_win);
1153         endwin();
1154
1155         /* FIXME: Shutdown gracefully. */
1156
1157         exit(0);
1158 }
1159
1160 static void die(const char *err, ...)
1161 {
1162         va_list args;
1163
1164         endwin();
1165
1166         va_start(args, err);
1167         fputs("tig: ", stderr);
1168         vfprintf(stderr, err, args);
1169         fputs("\n", stderr);
1170         va_end(args);
1171
1172         exit(1);
1173 }
1174
1175 static void
1176 report(const char *msg, ...)
1177 {
1178         struct view *view = display[current_view];
1179         va_list args;
1180
1181         werase(title_win);
1182         wmove(title_win, 0, 0);
1183         if (view) {
1184                 wprintw(title_win, "[%s] ref: %s", view->name, commit_id);
1185
1186                 if (view->lines) {
1187                         wprintw(title_win, " - line %d of %d (%d%%)",
1188                                 view->lineno + 1,
1189                                 view->lines,
1190                                 view->lines ? (view->lineno + 1) * 100 / view->lines : 0);
1191                 }
1192         } else {
1193                 wprintw(title_win, "commit %s", commit_id);
1194         }
1195         wrefresh(title_win);
1196
1197         va_start(args, msg);
1198
1199         werase(status_win);
1200         wmove(status_win, 0, 0);
1201
1202 #if 0
1203         if (display[current_view])
1204                 wprintw(status_win, "%s %4s: ", commit_id, display[current_view]->name);
1205 #endif
1206         vwprintw(status_win, msg, args);
1207         wrefresh(status_win);
1208
1209         va_end(args);
1210 }
1211
1212 int
1213 main(int argc, char *argv[])
1214 {
1215         int x, y;
1216         int request;
1217         int git_cmd;
1218
1219         signal(SIGINT, quit);
1220
1221         git_cmd = parse_options(argc, argv);
1222         if (git_cmd < 0)
1223                 return 0;
1224         if (git_cmd < argc) {
1225                 die("opts");
1226         }
1227
1228         request = opt_request;
1229
1230         initscr();      /* initialize the curses library */
1231         nonl();         /* tell curses not to do NL->CR/NL on output */
1232         cbreak();       /* take input chars one at a time, no wait for \n */
1233         noecho();       /* don't echo input */
1234         leaveok(stdscr, TRUE);
1235         /* curs_set(0); */
1236
1237         if (has_colors())
1238                 init_colors();
1239
1240         getmaxyx(stdscr, y, x);
1241         status_win = newwin(1, 0, y - 1, 0);
1242         if (!status_win)
1243                 die("Failed to create status window");
1244
1245         title_win = newwin(1, 0, y - 2, 0);
1246         if (!title_win)
1247                 die("Failed to create title window");
1248
1249         /* Enable keyboard mapping */
1250         keypad(status_win, TRUE);
1251         wbkgdset(status_win, get_line_attr(LINE_STATUS));
1252         wbkgdset(title_win, get_line_attr(LINE_TITLE));
1253
1254         while (view_driver(display[current_view], request)) {
1255                 struct view *view;
1256                 int i;
1257
1258                 foreach_view (view, i) {
1259                         if (view->pipe) {
1260                                 update_view(view);
1261                         }
1262                 }
1263
1264                 /* Refresh, accept single keystroke of input */
1265                 request = wgetch(status_win);
1266                 if (request == KEY_RESIZE) {
1267                         int lines, cols;
1268
1269                         getmaxyx(stdscr, lines, cols);
1270
1271                         mvwin(status_win, lines - 1, 0);
1272                         wresize(status_win, 1, cols - 1);
1273
1274                         mvwin(title_win, lines - 2, 0);
1275                         wresize(title_win, 1, cols - 1);
1276                 }
1277         }
1278
1279         quit(0);
1280
1281         return 0;
1282 }
1283
1284 /**
1285  * BUGS
1286  * ----
1287  * Known bugs and problems:
1288  *
1289  * Redrawing of the main view while loading::
1290  *      If only part of a commit has been parsed not all fields will be visible
1291  *      or even redrawn when the whole commit have loaded. This can be
1292  *      triggered when continuously moving to the last line. Use 'r' to redraw
1293  *      the whole screen.
1294  *
1295  * TODO
1296  * ----
1297  * Features that should be explored.
1298  *
1299  * - Dynamic scaling of line number indentation.
1300  *
1301  * - Proper command line handling; ability to take the command that should be
1302  *   shown. Example:
1303  *
1304  *      $ tig log -p
1305  *
1306  * - Internal command line (exmode-inspired) which allows to specify what git
1307  *   log or git diff command to run. Example:
1308  *
1309  *      :log -p
1310  *
1311  * - Proper resizing support. I am yet to figure out whether catching SIGWINCH
1312  *   is preferred over using ncurses' built-in support for resizing.
1313  *
1314  * - Locale support.
1315  *
1316  * COPYRIGHT
1317  * ---------
1318  * Copyright (c) Jonas Fonseca, 2006
1319  *
1320  * This program is free software; you can redistribute it and/or modify
1321  * it under the terms of the GNU General Public License as published by
1322  * the Free Software Foundation; either version 2 of the License, or
1323  * (at your option) any later version.
1324  *
1325  * SEE ALSO
1326  * --------
1327  * [verse]
1328  * link:http://www.kernel.org/pub/software/scm/git/docs/[git(7)],
1329  * link:http://www.kernel.org/pub/software/scm/cogito/docs/[cogito(7)]
1330  * gitk(1): git repository browser written using tcl/tk,
1331  * gitview(1): git repository browser written using python/gtk.
1332  **/