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