882b2fd537b6ac5d9ee78a1a3f9b7cef74051a76
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] [--] [git log options]
16 * tig [options] log [git log options]
17 * tig [options] diff [git diff options]
18 * tig [options] < [git log or git diff output]
19 *
20 * DESCRIPTION
21 * -----------
22 * Browse changes in a git repository.
23 **/
25 #ifndef DEBUG
26 #define NDEBUG
27 #endif
29 #ifndef VERSION
30 #define VERSION "tig-0.1"
31 #endif
33 #include <assert.h>
34 #include <errno.h>
35 #include <ctype.h>
36 #include <signal.h>
37 #include <stdarg.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <unistd.h>
42 #include <time.h>
44 #include <curses.h>
46 static void die(const char *err, ...);
47 static void report(const char *msg, ...);
48 static void set_nonblocking_input(int boolean);
50 #define ABS(x) ((x) >= 0 ? (x) : -(x))
51 #define MIN(x, y) ((x) < (y) ? (x) : (y))
53 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
54 #define STRING_SIZE(x) (sizeof(x) - 1)
56 #define SIZEOF_REF 256 /* Size of symbolic or SHA1 ID. */
57 #define SIZEOF_CMD 1024 /* Size of command buffer. */
59 /* This color name can be used to refer to the default term colors. */
60 #define COLOR_DEFAULT (-1)
62 /* The format and size of the date column in the main view. */
63 #define DATE_FORMAT "%Y-%m-%d %H:%M"
64 #define DATE_COLS STRING_SIZE("2006-04-29 14:21 ")
66 /* The default interval between line numbers. */
67 #define NUMBER_INTERVAL 1
69 #define SCALE_SPLIT_VIEW(height) ((height) * 2 / 3)
71 /* Some ascii-shorthands that fit into the ncurses namespace. */
72 #define KEY_TAB '\t'
73 #define KEY_RETURN '\r'
74 #define KEY_ESC 27
76 /* User action requests. */
77 enum request {
78 /* Offset all requests to avoid conflicts with ncurses getch values. */
79 REQ_OFFSET = KEY_MAX + 1,
81 /* XXX: Keep the view request first and in sync with views[]. */
82 REQ_VIEW_MAIN,
83 REQ_VIEW_DIFF,
84 REQ_VIEW_LOG,
85 REQ_VIEW_HELP,
86 REQ_VIEW_PAGER,
88 REQ_ENTER,
89 REQ_QUIT,
90 REQ_PROMPT,
91 REQ_SCREEN_REDRAW,
92 REQ_SCREEN_UPDATE,
93 REQ_SHOW_VERSION,
94 REQ_STOP_LOADING,
95 REQ_TOGGLE_LINE_NUMBERS,
96 REQ_VIEW_NEXT,
98 REQ_MOVE_UP,
99 REQ_MOVE_DOWN,
100 REQ_MOVE_PAGE_UP,
101 REQ_MOVE_PAGE_DOWN,
102 REQ_MOVE_FIRST_LINE,
103 REQ_MOVE_LAST_LINE,
105 REQ_SCROLL_LINE_UP,
106 REQ_SCROLL_LINE_DOWN,
107 REQ_SCROLL_PAGE_UP,
108 REQ_SCROLL_PAGE_DOWN,
109 };
111 struct commit {
112 char id[41]; /* SHA1 ID. */
113 char title[75]; /* The first line of the commit message. */
114 char author[75]; /* The author of the commit. */
115 struct tm time; /* Date from the author ident. */
116 };
118 /*
119 * String helpers
120 */
122 static inline void
123 string_ncopy(char *dst, char *src, int dstlen)
124 {
125 strncpy(dst, src, dstlen - 1);
126 dst[dstlen - 1] = 0;
128 }
130 /* Shorthand for safely copying into a fixed buffer. */
131 #define string_copy(dst, src) \
132 string_ncopy(dst, src, sizeof(dst))
134 /* Shell quoting
135 *
136 * NOTE: The following is a slightly modified copy of the git project's shell
137 * quoting routines found in the quote.c file.
138 *
139 * Help to copy the thing properly quoted for the shell safety. any single
140 * quote is replaced with '\'', any exclamation point is replaced with '\!',
141 * and the whole thing is enclosed in a
142 *
143 * E.g.
144 * original sq_quote result
145 * name ==> name ==> 'name'
146 * a b ==> a b ==> 'a b'
147 * a'b ==> a'\''b ==> 'a'\''b'
148 * a!b ==> a'\!'b ==> 'a'\!'b'
149 */
151 static size_t
152 sq_quote(char buf[SIZEOF_CMD], size_t bufsize, const char *src)
153 {
154 char c;
156 #define BUFPUT(x) ( (bufsize < SIZEOF_CMD) && (buf[bufsize++] = (x)) )
158 BUFPUT('\'');
159 while ((c = *src++)) {
160 if (c == '\'' || c == '!') {
161 BUFPUT('\'');
162 BUFPUT('\\');
163 BUFPUT(c);
164 BUFPUT('\'');
165 } else {
166 BUFPUT(c);
167 }
168 }
169 BUFPUT('\'');
171 return bufsize;
172 }
175 /**
176 * OPTIONS
177 * -------
178 **/
180 static int opt_line_number = FALSE;
181 static int opt_num_interval = NUMBER_INTERVAL;
182 static enum request opt_request = REQ_VIEW_MAIN;
183 static char opt_cmd[SIZEOF_CMD] = "";
184 static FILE *opt_pipe = NULL;
186 char ref_head[SIZEOF_REF] = "HEAD";
187 char ref_commit[SIZEOF_REF] = "HEAD";
189 /* Returns the index of log or diff command or -1 to exit. */
190 static int
191 parse_options(int argc, char *argv[])
192 {
193 int i;
195 for (i = 1; i < argc; i++) {
196 char *opt = argv[i];
198 /**
199 * log [options]::
200 * git log options.
201 *
202 * diff [options]::
203 * git diff options.
204 **/
205 if (!strcmp(opt, "log") ||
206 !strcmp(opt, "diff")) {
207 opt_request = opt[0] == 'l'
208 ? REQ_VIEW_LOG : REQ_VIEW_DIFF;
209 break;
210 }
212 /**
213 * -l::
214 * Start up in log view.
215 **/
216 if (!strcmp(opt, "-l")) {
217 opt_request = REQ_VIEW_LOG;
218 continue;
219 }
221 /**
222 * -d::
223 * Start up in diff view.
224 **/
225 if (!strcmp(opt, "-d")) {
226 opt_request = REQ_VIEW_DIFF;
227 continue;
228 }
230 /**
231 * -n[INTERVAL], --line-number[=INTERVAL]::
232 * Prefix line numbers in log and diff view.
233 * Optionally, with interval different than each line.
234 **/
235 if (!strncmp(opt, "-n", 2) ||
236 !strncmp(opt, "--line-number", 13)) {
237 char *num = opt;
239 if (opt[1] == 'n') {
240 num = opt + 2;
242 } else if (opt[STRING_SIZE("--line-number")] == '=') {
243 num = opt + STRING_SIZE("--line-number=");
244 }
246 if (isdigit(*num))
247 opt_num_interval = atoi(num);
249 opt_line_number = TRUE;
250 continue;
251 }
253 /**
254 * -v, --version::
255 * Show version and exit.
256 **/
257 if (!strcmp(opt, "-v") ||
258 !strcmp(opt, "--version")) {
259 printf("tig version %s\n", VERSION);
260 return -1;
261 }
263 /**
264 * \--::
265 * End of tig options. Useful when specifying commands
266 * for the main view. Example:
267 *
268 * $ tig -- --pretty=raw tag-1.0..HEAD
269 **/
270 if (!strcmp(opt, "--")) {
271 i++;
272 break;
273 }
275 /* Make stuff like:
276 *
277 * $ tig tag-1.0..HEAD
278 *
279 * work.
280 */
281 if (opt[0] && opt[0] != '-')
282 break;
284 die("unknown command '%s'", opt);
285 }
287 if (!isatty(STDIN_FILENO)) {
288 /* XXX: When pager mode has been requested, silently override
289 * view startup options. */
290 opt_request = REQ_VIEW_PAGER;
291 opt_pipe = stdin;
293 } else if (i < argc) {
294 size_t buf_size;
296 /* XXX: This is vulnerable to the user overriding options
297 * required for the main view parser. */
298 if (opt_request == REQ_VIEW_MAIN)
299 string_copy(opt_cmd, "git log --stat --pretty=raw");
300 else
301 string_copy(opt_cmd, "git");
302 buf_size = strlen(opt_cmd);
304 while (buf_size < sizeof(opt_cmd) && i < argc) {
305 opt_cmd[buf_size++] = ' ';
306 buf_size = sq_quote(opt_cmd, buf_size, argv[i++]);
307 }
309 if (buf_size >= sizeof(opt_cmd))
310 die("command too long");
312 opt_cmd[buf_size] = 0;
314 }
316 return i;
317 }
320 /**
321 * KEYS
322 * ----
323 **/
325 #define HELP "(d)iff, (l)og, (m)ain, (q)uit, (v)ersion, (h)elp"
327 struct keymap {
328 int alias;
329 int request;
330 };
332 struct keymap keymap[] = {
333 /**
334 * View switching
335 * ~~~~~~~~~~~~~~
336 * d::
337 * Switch to diff view.
338 * l::
339 * Switch to log view.
340 * m::
341 * Switch to main view.
342 * h::
343 * Show man page.
344 * Return::
345 * If in main view split the view
346 * and show the diff in the bottom view.
347 * Tab::
348 * Switch to next view.
349 **/
350 { 'm', REQ_VIEW_MAIN },
351 { 'd', REQ_VIEW_DIFF },
352 { 'l', REQ_VIEW_LOG },
353 { 'h', REQ_VIEW_HELP },
355 { KEY_TAB, REQ_VIEW_NEXT },
356 { KEY_RETURN, REQ_ENTER },
358 /**
359 * Cursor navigation
360 * ~~~~~~~~~~~~~~~~~
361 * Up, k::
362 * Move curser one line up.
363 * Down, j::
364 * Move cursor one line down.
365 * Page Up::
366 * Move curser one page up.
367 * Page Down::
368 * Move cursor one page down.
369 * Home::
370 * Jump to first line.
371 * End::
372 * Jump to last line.
373 **/
374 { KEY_UP, REQ_MOVE_UP },
375 { 'k', REQ_MOVE_UP },
376 { KEY_DOWN, REQ_MOVE_DOWN },
377 { 'j', REQ_MOVE_DOWN },
378 { KEY_HOME, REQ_MOVE_FIRST_LINE },
379 { KEY_END, REQ_MOVE_LAST_LINE },
380 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
381 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
383 /**
384 * Scrolling
385 * ~~~~~~~~~
386 * Insert::
387 * Scroll view one line up.
388 * Delete::
389 * Scroll view one line down.
390 * w::
391 * Scroll view one page up.
392 * s::
393 * Scroll view one page down.
394 **/
395 { KEY_IC, REQ_SCROLL_LINE_UP },
396 { KEY_DC, REQ_SCROLL_LINE_DOWN },
397 { 'w', REQ_SCROLL_PAGE_UP },
398 { 's', REQ_SCROLL_PAGE_DOWN },
400 /**
401 * Misc
402 * ~~~~
403 * q, Escape::
404 * Quit
405 * r::
406 * Redraw screen.
407 * z::
408 * Stop all background loading.
409 * v::
410 * Show version.
411 * n::
412 * Toggle line numbers on/off.
413 * ':'::
414 * Open prompt.
415 **/
416 { KEY_ESC, REQ_QUIT },
417 { 'q', REQ_QUIT },
418 { 'z', REQ_STOP_LOADING },
419 { 'v', REQ_SHOW_VERSION },
420 { 'r', REQ_SCREEN_REDRAW },
421 { 'n', REQ_TOGGLE_LINE_NUMBERS },
422 { ':', REQ_PROMPT },
424 /* wgetch() with nodelay() enabled returns ERR when there's no input. */
425 { ERR, REQ_SCREEN_UPDATE },
426 };
428 static enum request
429 get_request(int key)
430 {
431 int i;
433 for (i = 0; i < ARRAY_SIZE(keymap); i++)
434 if (keymap[i].alias == key)
435 return keymap[i].request;
437 return (enum request) key;
438 }
441 /*
442 * Line-oriented content detection.
443 */
445 #define LINE_INFO \
446 /* Line type String to match Foreground Background Attributes
447 * --------- --------------- ---------- ---------- ---------- */ \
448 /* Diff markup */ \
449 LINE(DIFF, "diff --git ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
450 LINE(INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
451 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
452 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
453 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
454 LINE(DIFF_OLDMODE, "old mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
455 LINE(DIFF_NEWMODE, "new mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
456 LINE(DIFF_COPY, "copy ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
457 LINE(DIFF_RENAME, "rename ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
458 LINE(DIFF_SIM, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
459 LINE(DIFF_DISSIM, "dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
460 /* Pretty print commit header */ \
461 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
462 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
463 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
464 LINE(PP_COMMIT, "Commit: ", COLOR_GREEN, COLOR_DEFAULT, 0), \
465 /* Raw commit header */ \
466 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
467 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
468 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
469 LINE(AUTHOR_IDENT, "author ", COLOR_CYAN, COLOR_DEFAULT, 0), \
470 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
471 /* Misc */ \
472 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
473 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
474 /* UI colors */ \
475 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
476 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
477 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
478 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
479 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
480 LINE(MAIN_DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
481 LINE(MAIN_AUTHOR, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
482 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
483 LINE(MAIN_DELIM, "", COLOR_MAGENTA, COLOR_DEFAULT, 0),
485 enum line_type {
486 #define LINE(type, line, fg, bg, attr) \
487 LINE_##type
488 LINE_INFO
489 #undef LINE
490 };
492 struct line_info {
493 char *line; /* The start of line to match. */
494 int linelen; /* Size of string to match. */
495 int fg, bg, attr; /* Color and text attributes for the lines. */
496 };
498 static struct line_info line_info[] = {
499 #define LINE(type, line, fg, bg, attr) \
500 { (line), STRING_SIZE(line), (fg), (bg), (attr) }
501 LINE_INFO
502 #undef LINE
503 };
505 static enum line_type
506 get_line_type(char *line)
507 {
508 int linelen = strlen(line);
509 enum line_type type;
511 for (type = 0; type < ARRAY_SIZE(line_info); type++)
512 /* Case insensitive search matches Signed-off-by lines better. */
513 if (linelen >= line_info[type].linelen &&
514 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
515 return type;
517 return LINE_DEFAULT;
518 }
520 static inline int
521 get_line_attr(enum line_type type)
522 {
523 assert(type < ARRAY_SIZE(line_info));
524 return COLOR_PAIR(type) | line_info[type].attr;
525 }
527 static void
528 init_colors(void)
529 {
530 int default_bg = COLOR_BLACK;
531 int default_fg = COLOR_WHITE;
532 enum line_type type;
534 start_color();
536 if (use_default_colors() != ERR) {
537 default_bg = -1;
538 default_fg = -1;
539 }
541 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
542 struct line_info *info = &line_info[type];
543 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
544 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
546 init_pair(type, fg, bg);
547 }
548 }
551 /*
552 * Viewer
553 */
555 struct view {
556 const char *name; /* View name */
557 const char *defcmd; /* Default command line */
558 char *id; /* Points to either of ref_{head,commit} */
559 size_t objsize; /* Size of objects in the line index */
561 struct view_ops {
562 bool (*draw)(struct view *view, unsigned int lineno);
563 bool (*read)(struct view *view, char *line);
564 bool (*enter)(struct view *view);
565 } *ops;
567 char cmd[SIZEOF_CMD]; /* Command buffer */
568 char ref[SIZEOF_REF]; /* Hovered Commit reference */
569 /* The view reference that describes the content of this view. */
570 char vref[SIZEOF_REF];
572 WINDOW *win;
573 WINDOW *title;
574 int height, width;
576 /* Navigation */
577 unsigned long offset; /* Offset of the window top */
578 unsigned long lineno; /* Current line number */
580 /* Buffering */
581 unsigned long lines; /* Total number of lines */
582 void **line; /* Line index */
584 /* Loading */
585 FILE *pipe;
586 time_t start_time;
587 };
589 static struct view_ops pager_ops;
590 static struct view_ops main_ops;
592 #define DIFF_CMD \
593 "git log --stat -n1 %s ; echo; " \
594 "git diff --find-copies-harder -B -C %s^ %s"
596 #define LOG_CMD \
597 "git log --cc --stat -n100 %s"
599 #define MAIN_CMD \
600 "git log --stat --pretty=raw %s"
602 #define HELP_CMD \
603 "man tig 2> /dev/null"
605 static struct view views[] = {
606 { "main", MAIN_CMD, ref_head, sizeof(struct commit), &main_ops },
607 { "diff", DIFF_CMD, ref_commit, sizeof(char), &pager_ops },
608 { "log", LOG_CMD, ref_head, sizeof(char), &pager_ops },
609 { "help", HELP_CMD, ref_head, sizeof(char), &pager_ops },
610 { "pager", "cat", ref_head, sizeof(char), &pager_ops },
611 };
613 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
615 /* The display array of active views and the index of the current view. */
616 static struct view *display[2];
617 static unsigned int current_view;
619 #define foreach_view(view, i) \
620 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
623 static void
624 redraw_view_from(struct view *view, int lineno)
625 {
626 assert(0 <= lineno && lineno < view->height);
628 for (; lineno < view->height; lineno++) {
629 if (!view->ops->draw(view, lineno))
630 break;
631 }
633 redrawwin(view->win);
634 wrefresh(view->win);
635 }
637 static void
638 redraw_view(struct view *view)
639 {
640 wclear(view->win);
641 redraw_view_from(view, 0);
642 }
644 static void
645 resize_display(void)
646 {
647 int offset, i;
648 struct view *base = display[0];
649 struct view *view = display[1] ? display[1] : display[0];
651 /* Setup window dimensions */
653 getmaxyx(stdscr, base->height, base->width);
655 /* Make room for the status window. */
656 base->height -= 1;
658 if (view != base) {
659 /* Horizontal split. */
660 view->width = base->width;
661 view->height = SCALE_SPLIT_VIEW(base->height);
662 base->height -= view->height;
664 /* Make room for the title bar. */
665 view->height -= 1;
666 }
668 /* Make room for the title bar. */
669 base->height -= 1;
671 offset = 0;
673 foreach_view (view, i) {
674 if (!view->win) {
675 view->win = newwin(view->height, 0, offset, 0);
676 if (!view->win)
677 die("Failed to create %s view", view->name);
679 scrollok(view->win, TRUE);
681 view->title = newwin(1, 0, offset + view->height, 0);
682 if (!view->title)
683 die("Failed to create title window");
685 } else {
686 wresize(view->win, view->height, view->width);
687 mvwin(view->win, offset, 0);
688 mvwin(view->title, offset + view->height, 0);
689 wrefresh(view->win);
690 }
692 offset += view->height + 1;
693 }
694 }
696 static void
697 update_view_title(struct view *view)
698 {
699 if (view == display[current_view])
700 wbkgdset(view->title, get_line_attr(LINE_TITLE_FOCUS));
701 else
702 wbkgdset(view->title, get_line_attr(LINE_TITLE_BLUR));
704 werase(view->title);
705 wmove(view->title, 0, 0);
707 /* [main] ref: 334b506... - commit 6 of 4383 (0%) */
709 if (*view->ref)
710 wprintw(view->title, "[%s] ref: %s", view->name, view->ref);
711 else
712 wprintw(view->title, "[%s]", view->name);
714 if (view->lines) {
715 char *type = view == VIEW(REQ_VIEW_MAIN) ? "commit" : "line";
717 wprintw(view->title, " - %s %d of %d (%d%%)",
718 type,
719 view->lineno + 1,
720 view->lines,
721 (view->lineno + 1) * 100 / view->lines);
722 }
724 wrefresh(view->title);
725 }
727 /*
728 * Navigation
729 */
731 /* Scrolling backend */
732 static void
733 do_scroll_view(struct view *view, int lines)
734 {
735 /* The rendering expects the new offset. */
736 view->offset += lines;
738 assert(0 <= view->offset && view->offset < view->lines);
739 assert(lines);
741 /* Redraw the whole screen if scrolling is pointless. */
742 if (view->height < ABS(lines)) {
743 redraw_view(view);
745 } else {
746 int line = lines > 0 ? view->height - lines : 0;
747 int end = line + ABS(lines);
749 wscrl(view->win, lines);
751 for (; line < end; line++) {
752 if (!view->ops->draw(view, line))
753 break;
754 }
755 }
757 /* Move current line into the view. */
758 if (view->lineno < view->offset) {
759 view->lineno = view->offset;
760 view->ops->draw(view, 0);
762 } else if (view->lineno >= view->offset + view->height) {
763 view->lineno = view->offset + view->height - 1;
764 view->ops->draw(view, view->lineno - view->offset);
765 }
767 assert(view->offset <= view->lineno && view->lineno < view->lines);
769 redrawwin(view->win);
770 wrefresh(view->win);
771 report("");
772 }
774 /* Scroll frontend */
775 static void
776 scroll_view(struct view *view, enum request request)
777 {
778 int lines = 1;
780 switch (request) {
781 case REQ_SCROLL_PAGE_DOWN:
782 lines = view->height;
783 case REQ_SCROLL_LINE_DOWN:
784 if (view->offset + lines > view->lines)
785 lines = view->lines - view->offset;
787 if (lines == 0 || view->offset + view->height >= view->lines) {
788 report("Already on last line");
789 return;
790 }
791 break;
793 case REQ_SCROLL_PAGE_UP:
794 lines = view->height;
795 case REQ_SCROLL_LINE_UP:
796 if (lines > view->offset)
797 lines = view->offset;
799 if (lines == 0) {
800 report("Already on first line");
801 return;
802 }
804 lines = -lines;
805 break;
807 default:
808 die("request %d not handled in switch", request);
809 }
811 do_scroll_view(view, lines);
812 }
814 /* Cursor moving */
815 static void
816 move_view(struct view *view, enum request request)
817 {
818 int steps;
820 switch (request) {
821 case REQ_MOVE_FIRST_LINE:
822 steps = -view->lineno;
823 break;
825 case REQ_MOVE_LAST_LINE:
826 steps = view->lines - view->lineno - 1;
827 break;
829 case REQ_MOVE_PAGE_UP:
830 steps = view->height > view->lineno
831 ? -view->lineno : -view->height;
832 break;
834 case REQ_MOVE_PAGE_DOWN:
835 steps = view->lineno + view->height >= view->lines
836 ? view->lines - view->lineno - 1 : view->height;
837 break;
839 case REQ_MOVE_UP:
840 steps = -1;
841 break;
843 case REQ_MOVE_DOWN:
844 steps = 1;
845 break;
847 default:
848 die("request %d not handled in switch", request);
849 }
851 if (steps <= 0 && view->lineno == 0) {
852 report("Already on first line");
853 return;
855 } else if (steps >= 0 && view->lineno + 1 >= view->lines) {
856 report("Already on last line");
857 return;
858 }
860 /* Move the current line */
861 view->lineno += steps;
862 assert(0 <= view->lineno && view->lineno < view->lines);
864 /* Repaint the old "current" line if we be scrolling */
865 if (ABS(steps) < view->height) {
866 int prev_lineno = view->lineno - steps - view->offset;
868 wmove(view->win, prev_lineno, 0);
869 wclrtoeol(view->win);
870 view->ops->draw(view, prev_lineno);
871 }
873 /* Check whether the view needs to be scrolled */
874 if (view->lineno < view->offset ||
875 view->lineno >= view->offset + view->height) {
876 if (steps < 0 && -steps > view->offset) {
877 steps = -view->offset;
879 } else if (steps > 0) {
880 if (view->lineno == view->lines - 1 &&
881 view->lines > view->height) {
882 steps = view->lines - view->offset - 1;
883 if (steps >= view->height)
884 steps -= view->height - 1;
885 }
886 }
888 do_scroll_view(view, steps);
889 return;
890 }
892 /* Draw the current line */
893 view->ops->draw(view, view->lineno - view->offset);
895 redrawwin(view->win);
896 wrefresh(view->win);
897 report("");
898 }
901 /*
902 * Incremental updating
903 */
905 static bool
906 begin_update(struct view *view)
907 {
908 char *id = view->id;
910 if (opt_cmd[0]) {
911 string_copy(view->cmd, opt_cmd);
912 opt_cmd[0] = 0;
913 } else {
914 if (snprintf(view->cmd, sizeof(view->cmd), view->defcmd,
915 id, id, id) >= sizeof(view->cmd))
916 return FALSE;
917 }
919 /* Special case for the pager view. */
920 if (opt_pipe) {
921 view->pipe = opt_pipe;
922 opt_pipe = NULL;
923 } else {
924 view->pipe = popen(view->cmd, "r");
925 }
927 if (!view->pipe)
928 return FALSE;
930 set_nonblocking_input(TRUE);
932 view->offset = 0;
933 view->lines = 0;
934 view->lineno = 0;
936 if (view->line) {
937 int i;
939 for (i = 0; i < view->lines; i++)
940 if (view->line[i])
941 free(view->line[i]);
943 free(view->line);
944 view->line = NULL;
945 }
947 view->start_time = time(NULL);
949 return TRUE;
950 }
952 static void
953 end_update(struct view *view)
954 {
955 if (!view->pipe)
956 return;
957 set_nonblocking_input(FALSE);
958 pclose(view->pipe);
959 view->pipe = NULL;
960 }
962 static bool
963 update_view(struct view *view)
964 {
965 char buffer[BUFSIZ];
966 char *line;
967 void **tmp;
968 /* The number of lines to read. If too low it will cause too much
969 * redrawing (and possible flickering), if too high responsiveness
970 * will suffer. */
971 int lines = view->height;
972 int redraw_from = -1;
974 if (!view->pipe)
975 return TRUE;
977 /* Only redraw if lines are visible. */
978 if (view->offset + view->height >= view->lines)
979 redraw_from = view->lines - view->offset;
981 tmp = realloc(view->line, sizeof(*view->line) * (view->lines + lines));
982 if (!tmp)
983 goto alloc_error;
985 view->line = tmp;
987 while ((line = fgets(buffer, sizeof(buffer), view->pipe))) {
988 int linelen;
990 linelen = strlen(line);
991 if (linelen)
992 line[linelen - 1] = 0;
994 if (!view->ops->read(view, line))
995 goto alloc_error;
997 if (lines-- == 1)
998 break;
999 }
1001 /* CPU hogilicious! */
1002 update_view_title(view);
1004 if (redraw_from >= 0) {
1005 /* If this is an incremental update, redraw the previous line
1006 * since for commits some members could have changed when
1007 * loading the main view. */
1008 if (redraw_from > 0)
1009 redraw_from--;
1011 /* Incrementally draw avoids flickering. */
1012 redraw_view_from(view, redraw_from);
1013 }
1015 if (ferror(view->pipe)) {
1016 report("Failed to read: %s", strerror(errno));
1017 goto end;
1019 } else if (feof(view->pipe)) {
1020 time_t secs = time(NULL) - view->start_time;
1022 if (view == VIEW(REQ_VIEW_HELP)) {
1023 report("%s", HELP);
1024 goto end;
1025 }
1027 report("Loaded %d lines in %ld second%s", view->lines, secs,
1028 secs == 1 ? "" : "s");
1029 goto end;
1030 }
1032 return TRUE;
1034 alloc_error:
1035 report("Allocation failure");
1037 end:
1038 end_update(view);
1039 return FALSE;
1040 }
1042 static void
1043 switch_view(struct view *prev, enum request request,
1044 bool backgrounded, bool split)
1045 {
1046 struct view *view = VIEW(request);
1047 struct view *displayed;
1048 int nviews;
1050 /* Cycle between displayed views and count the views. */
1051 foreach_view (displayed, nviews) {
1052 if (prev != view &&
1053 view == displayed &&
1054 !strcmp(view->id, prev->id)) {
1055 current_view = nviews;
1056 /* Blur out the title of the previous view. */
1057 update_view_title(prev);
1058 report("Switching to %s view", view->name);
1059 return;
1060 }
1061 }
1063 if (view == prev && nviews == 1) {
1064 report("Already in %s view", view->name);
1065 return;
1066 }
1068 if (strcmp(view->vref, view->id) &&
1069 !begin_update(view)) {
1070 report("Failed to load %s view", view->name);
1071 return;
1072 }
1074 if (split) {
1075 display[current_view + 1] = view;
1076 if (!backgrounded)
1077 current_view++;
1078 } else {
1079 /* Maximize the current view. */
1080 memset(display, 0, sizeof(display));
1081 current_view = 0;
1082 display[current_view] = view;
1083 }
1085 resize_display();
1087 if (split && prev->lineno - prev->offset > prev->height) {
1088 /* Take the title line into account. */
1089 int lines = prev->lineno - prev->height + 1;
1091 /* Scroll the view that was split if the current line is
1092 * outside the new limited view. */
1093 do_scroll_view(prev, lines);
1094 }
1096 if (prev && view != prev) {
1097 /* "Blur" the previous view. */
1098 update_view_title(prev);
1100 /* Continue loading split views in the background. */
1101 if (!split)
1102 end_update(prev);
1103 }
1105 if (view->pipe) {
1106 /* Clear the old view and let the incremental updating refill
1107 * the screen. */
1108 wclear(view->win);
1109 report("Loading...");
1110 } else {
1111 redraw_view(view);
1112 report("");
1113 }
1114 }
1117 /*
1118 * User request switch noodle
1119 */
1121 static int
1122 view_driver(struct view *view, enum request request)
1123 {
1124 int i;
1126 switch (request) {
1127 case REQ_MOVE_UP:
1128 case REQ_MOVE_DOWN:
1129 case REQ_MOVE_PAGE_UP:
1130 case REQ_MOVE_PAGE_DOWN:
1131 case REQ_MOVE_FIRST_LINE:
1132 case REQ_MOVE_LAST_LINE:
1133 move_view(view, request);
1134 break;
1136 case REQ_SCROLL_LINE_DOWN:
1137 case REQ_SCROLL_LINE_UP:
1138 case REQ_SCROLL_PAGE_DOWN:
1139 case REQ_SCROLL_PAGE_UP:
1140 scroll_view(view, request);
1141 break;
1143 case REQ_VIEW_MAIN:
1144 case REQ_VIEW_DIFF:
1145 case REQ_VIEW_LOG:
1146 case REQ_VIEW_HELP:
1147 case REQ_VIEW_PAGER:
1148 switch_view(view, request, FALSE, FALSE);
1149 break;
1151 case REQ_ENTER:
1152 if (!view->lines) {
1153 report("Nothing to enter");
1154 break;
1155 }
1156 return view->ops->enter(view);
1158 case REQ_VIEW_NEXT:
1159 {
1160 int nviews = display[1] ? 2 : 1;
1161 int next_view = (current_view + 1) % nviews;
1163 if (next_view == current_view) {
1164 report("Only one view is displayed");
1165 break;
1166 }
1168 current_view = next_view;
1169 /* Blur out the title of the previous view. */
1170 update_view_title(view);
1171 report("Switching to %s view", display[current_view]->name);
1172 break;
1173 }
1174 case REQ_TOGGLE_LINE_NUMBERS:
1175 opt_line_number = !opt_line_number;
1176 redraw_view(view);
1177 break;
1179 case REQ_PROMPT:
1180 switch_view(view, opt_request, FALSE, FALSE);
1181 break;
1183 case REQ_STOP_LOADING:
1184 foreach_view (view, i) {
1185 if (view->pipe)
1186 report("Stopped loaded of %s view", view->name),
1187 end_update(view);
1188 }
1189 break;
1191 case REQ_SHOW_VERSION:
1192 report("Version: %s", VERSION);
1193 return TRUE;
1195 case REQ_SCREEN_REDRAW:
1196 redraw_view(view);
1197 break;
1199 case REQ_SCREEN_UPDATE:
1200 doupdate();
1201 return TRUE;
1203 case REQ_QUIT:
1204 return FALSE;
1206 default:
1207 /* An unknown key will show most commonly used commands. */
1208 report("%s", HELP);
1209 return TRUE;
1210 }
1212 return TRUE;
1213 }
1216 /*
1217 * View backend handlers
1218 */
1220 static bool
1221 pager_draw(struct view *view, unsigned int lineno)
1222 {
1223 enum line_type type;
1224 char *line;
1225 int linelen;
1226 int attr;
1228 if (view->offset + lineno >= view->lines)
1229 return FALSE;
1231 line = view->line[view->offset + lineno];
1232 type = get_line_type(line);
1234 if (view->offset + lineno == view->lineno) {
1235 switch (type) {
1236 case LINE_COMMIT:
1237 string_copy(view->ref, line + 7);
1238 string_copy(ref_commit, view->ref);
1239 break;
1240 case LINE_PP_COMMIT:
1241 string_copy(view->ref, line + 8);
1242 string_copy(ref_commit, view->ref);
1243 default:
1244 break;
1245 }
1246 type = LINE_CURSOR;
1247 }
1249 attr = get_line_attr(type);
1250 wattrset(view->win, attr);
1252 linelen = strlen(line);
1253 linelen = MIN(linelen, view->width);
1255 if (opt_line_number) {
1256 unsigned int real_lineno = view->offset + lineno + 1;
1257 int col = 0;
1259 if (real_lineno == 1 || (real_lineno % opt_num_interval) == 0)
1260 mvwprintw(view->win, lineno, 0, "%4d: ", real_lineno);
1261 else
1262 mvwaddstr(view->win, lineno, 0, " : ");
1264 while (line) {
1265 if (*line == '\t') {
1266 waddnstr(view->win, " ", 8 - (col % 8));
1267 col += 8 - (col % 8);
1268 line++;
1270 } else {
1271 char *tab = strchr(line, '\t');
1273 if (tab)
1274 waddnstr(view->win, line, tab - line);
1275 else
1276 waddstr(view->win, line);
1277 col += tab - line;
1278 line = tab;
1279 }
1280 }
1281 waddstr(view->win, line);
1283 } else {
1284 #if 0
1285 /* NOTE: Code for only highlighting the text on the cursor line.
1286 * Kept since I've not yet decided whether to highlight the
1287 * entire line or not. --fonseca */
1288 /* No empty lines makes cursor drawing and clearing implicit. */
1289 if (!*line)
1290 line = " ", linelen = 1;
1291 #endif
1292 mvwaddnstr(view->win, lineno, 0, line, linelen);
1293 }
1295 /* Paint the rest of the line if it's the cursor line. */
1296 if (type == LINE_CURSOR)
1297 wchgat(view->win, -1, 0, type, NULL);
1299 return TRUE;
1300 }
1302 static bool
1303 pager_read(struct view *view, char *line)
1304 {
1305 view->line[view->lines] = strdup(line);
1306 if (!view->line[view->lines])
1307 return FALSE;
1309 view->lines++;
1310 return TRUE;
1311 }
1313 static bool
1314 pager_enter(struct view *view)
1315 {
1316 char *line = view->line[view->lineno];
1318 if (get_line_type(line) == LINE_COMMIT) {
1319 switch_view(view, REQ_VIEW_DIFF, FALSE, FALSE);
1320 }
1322 return TRUE;
1323 }
1326 static struct view_ops pager_ops = {
1327 pager_draw,
1328 pager_read,
1329 pager_enter,
1330 };
1332 static bool
1333 main_draw(struct view *view, unsigned int lineno)
1334 {
1335 char buf[DATE_COLS + 1];
1336 struct commit *commit;
1337 enum line_type type;
1338 int cols = 0;
1339 size_t timelen;
1341 if (view->offset + lineno >= view->lines)
1342 return FALSE;
1344 commit = view->line[view->offset + lineno];
1345 if (!*commit->author)
1346 return FALSE;
1348 if (view->offset + lineno == view->lineno) {
1349 string_copy(view->ref, commit->id);
1350 type = LINE_CURSOR;
1351 } else {
1352 type = LINE_MAIN_COMMIT;
1353 }
1355 wmove(view->win, lineno, cols);
1356 wattrset(view->win, get_line_attr(LINE_MAIN_DATE));
1358 timelen = strftime(buf, sizeof(buf), DATE_FORMAT, &commit->time);
1359 waddnstr(view->win, buf, timelen);
1360 waddstr(view->win, " ");
1362 cols += DATE_COLS;
1363 wmove(view->win, lineno, cols);
1364 wattrset(view->win, get_line_attr(LINE_MAIN_AUTHOR));
1366 if (strlen(commit->author) > 19) {
1367 waddnstr(view->win, commit->author, 18);
1368 wattrset(view->win, get_line_attr(LINE_MAIN_DELIM));
1369 waddch(view->win, '~');
1370 } else {
1371 waddstr(view->win, commit->author);
1372 }
1374 cols += 20;
1375 wattrset(view->win, A_NORMAL);
1376 mvwaddch(view->win, lineno, cols, ACS_LTEE);
1377 wattrset(view->win, get_line_attr(type));
1378 mvwaddstr(view->win, lineno, cols + 2, commit->title);
1379 wattrset(view->win, A_NORMAL);
1381 return TRUE;
1382 }
1384 /* Reads git log --pretty=raw output and parses it into the commit struct. */
1385 static bool
1386 main_read(struct view *view, char *line)
1387 {
1388 enum line_type type = get_line_type(line);
1389 struct commit *commit;
1391 switch (type) {
1392 case LINE_COMMIT:
1393 commit = calloc(1, sizeof(struct commit));
1394 if (!commit)
1395 return FALSE;
1397 line += STRING_SIZE("commit ");
1399 view->line[view->lines++] = commit;
1400 string_copy(commit->id, line);
1401 break;
1403 case LINE_AUTHOR_IDENT:
1404 {
1405 char *ident = line + STRING_SIZE("author ");
1406 char *end = strchr(ident, '<');
1408 if (end) {
1409 for (; end > ident && isspace(end[-1]); end--) ;
1410 *end = 0;
1411 }
1413 commit = view->line[view->lines - 1];
1414 string_copy(commit->author, ident);
1416 /* Parse epoch and timezone */
1417 if (end) {
1418 char *secs = strchr(end + 1, '>');
1419 char *zone;
1420 time_t time;
1422 if (!secs || secs[1] != ' ')
1423 break;
1425 secs += 2;
1426 time = (time_t) atol(secs);
1427 zone = strchr(secs, ' ');
1428 if (zone && strlen(zone) == STRING_SIZE(" +0700")) {
1429 long tz;
1431 zone++;
1432 tz = ('0' - zone[1]) * 60 * 60 * 10;
1433 tz += ('0' - zone[2]) * 60 * 60;
1434 tz += ('0' - zone[3]) * 60;
1435 tz += ('0' - zone[4]) * 60;
1437 if (zone[0] == '-')
1438 tz = -tz;
1440 time -= tz;
1441 }
1442 gmtime_r(&time, &commit->time);
1443 }
1444 break;
1445 }
1446 default:
1447 /* We should only ever end up here if there has already been a
1448 * commit line, however, be safe. */
1449 if (view->lines == 0)
1450 break;
1452 /* Fill in the commit title if it has not already been set. */
1453 commit = view->line[view->lines - 1];
1454 if (commit->title[0])
1455 break;
1457 /* Require titles to start with a non-space character at the
1458 * offset used by git log. */
1459 if (strncmp(line, " ", 4) ||
1460 isspace(line[5]))
1461 break;
1463 string_copy(commit->title, line + 4);
1464 }
1466 return TRUE;
1467 }
1469 static bool
1470 main_enter(struct view *view)
1471 {
1472 switch_view(view, REQ_VIEW_DIFF, TRUE, TRUE);
1473 return TRUE;
1474 }
1476 static struct view_ops main_ops = {
1477 main_draw,
1478 main_read,
1479 main_enter,
1480 };
1482 /*
1483 * Status management
1484 */
1486 /* The status window is used for polling keystrokes. */
1487 static WINDOW *status_win;
1489 /* Update status and title window. */
1490 static void
1491 report(const char *msg, ...)
1492 {
1493 va_list args;
1495 va_start(args, msg);
1497 /* Update the title window first, so the cursor ends up in the status
1498 * window. */
1499 update_view_title(display[current_view]);
1501 werase(status_win);
1502 wmove(status_win, 0, 0);
1503 vwprintw(status_win, msg, args);
1504 wrefresh(status_win);
1506 va_end(args);
1507 }
1509 /* Controls when nodelay should be in effect when polling user input. */
1510 static void
1511 set_nonblocking_input(int loading)
1512 {
1513 /* The number of loading views. */
1514 static unsigned int nloading;
1516 if (loading == TRUE) {
1517 if (nloading++ == 0)
1518 nodelay(status_win, TRUE);
1519 return;
1520 }
1522 if (nloading-- == 1)
1523 nodelay(status_win, FALSE);
1524 }
1526 static void
1527 init_display(void)
1528 {
1529 int x, y;
1531 /* Initialize the curses library */
1532 if (isatty(STDIN_FILENO)) {
1533 initscr();
1534 } else {
1535 /* Leave stdin and stdout alone when acting as a pager. */
1536 FILE *io = fopen("/dev/tty", "r+");
1538 newterm(NULL, io, io);
1539 }
1541 nonl(); /* Tell curses not to do NL->CR/NL on output */
1542 cbreak(); /* Take input chars one at a time, no wait for \n */
1543 noecho(); /* Don't echo input */
1544 leaveok(stdscr, TRUE);
1546 if (has_colors())
1547 init_colors();
1549 getmaxyx(stdscr, y, x);
1550 status_win = newwin(1, 0, y - 1, 0);
1551 if (!status_win)
1552 die("Failed to create status window");
1554 /* Enable keyboard mapping */
1555 keypad(status_win, TRUE);
1556 wbkgdset(status_win, get_line_attr(LINE_STATUS));
1557 }
1559 /*
1560 * Main
1561 */
1563 static void
1564 quit(int sig)
1565 {
1566 if (status_win)
1567 delwin(status_win);
1568 endwin();
1570 /* FIXME: Shutdown gracefully. */
1572 exit(0);
1573 }
1575 static void die(const char *err, ...)
1576 {
1577 va_list args;
1579 endwin();
1581 va_start(args, err);
1582 fputs("tig: ", stderr);
1583 vfprintf(stderr, err, args);
1584 fputs("\n", stderr);
1585 va_end(args);
1587 exit(1);
1588 }
1590 int
1591 main(int argc, char *argv[])
1592 {
1593 enum request request;
1594 int git_arg;
1596 signal(SIGINT, quit);
1598 git_arg = parse_options(argc, argv);
1599 if (git_arg < 0)
1600 return 0;
1602 request = opt_request;
1604 init_display();
1606 while (view_driver(display[current_view], request)) {
1607 struct view *view;
1608 int key;
1609 int i;
1611 foreach_view (view, i)
1612 update_view(view);
1614 /* Refresh, accept single keystroke of input */
1615 key = wgetch(status_win);
1616 request = get_request(key);
1618 if (request == REQ_PROMPT) {
1619 report(":");
1620 /* Temporarily switch to line-oriented and echoed
1621 * input. */
1622 nocbreak();
1623 echo();
1624 if (wgetnstr(status_win, opt_cmd, sizeof(opt_cmd)) == OK)
1625 die("%s", opt_cmd);
1626 noecho();
1627 cbreak();
1628 }
1629 }
1631 quit(0);
1633 return 0;
1634 }
1636 /**
1637 * TODO
1638 * ----
1639 * Features that should be explored.
1640 *
1641 * - Dynamic scaling of line number indentation.
1642 *
1643 * - Internal command line (exmode-inspired) which allows to specify what git
1644 * log or git diff command to run. Example:
1645 *
1646 * :log -p
1647 *
1648 * - Terminal resizing support. I am yet to figure out whether catching
1649 * SIGWINCH is preferred over using ncurses' built-in support for resizing.
1650 *
1651 * - Locale support.
1652 *
1653 * COPYRIGHT
1654 * ---------
1655 * Copyright (c) Jonas Fonseca <fonseca@diku.dk>, 2006
1656 *
1657 * This program is free software; you can redistribute it and/or modify
1658 * it under the terms of the GNU General Public License as published by
1659 * the Free Software Foundation; either version 2 of the License, or
1660 * (at your option) any later version.
1661 *
1662 * SEE ALSO
1663 * --------
1664 * [verse]
1665 * link:http://www.kernel.org/pub/software/scm/git/docs/[git(7)],
1666 * link:http://www.kernel.org/pub/software/scm/cogito/docs/[cogito(7)]
1667 * gitk(1): git repository browser written using tcl/tk,
1668 * gitview(1): git repository browser written using python/gtk.
1669 **/