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