6a94a2af9814a4a8401d3a6258f634033a66cb47
[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] [--] [git log options]
16 * tig [options] log [git log options]
17 * tig [options] diff [git diff options]
18 * tig [options] show [git show options]
19 * tig [options] < [git command output]
20 *
21 * DESCRIPTION
22 * -----------
23 * Browse changes in a git repository. Additionally, tig(1) can also act
24 * as a pager for output of various git commands.
25 *
26 * When browsing repositories, tig(1) uses the underlaying git commands
27 * to present the user with various views, such as summarized commit log
28 * and showing the commit with the log message, diffstat, and the diff.
29 *
30 * Using tig(1) as a pager, it will display input from stdin and try
31 * to colorize it.
32 **/
33
34 #ifndef VERSION
35 #define VERSION "tig-0.1"
36 #endif
37
38 #ifndef DEBUG
39 #define NDEBUG
40 #endif
41
42 #include <assert.h>
43 #include <errno.h>
44 #include <ctype.h>
45 #include <signal.h>
46 #include <stdarg.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <string.h>
50 #include <unistd.h>
51 #include <time.h>
52
53 #include <curses.h>
54
55 static void die(const char *err, ...);
56 static void report(const char *msg, ...);
57 static void set_nonblocking_input(bool loading);
58
59 #define ABS(x) ((x) >= 0 ? (x) : -(x))
60 #define MIN(x, y) ((x) < (y) ? (x) : (y))
61
62 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
63 #define STRING_SIZE(x) (sizeof(x) - 1)
64
65 #define SIZEOF_REF 256 /* Size of symbolic or SHA1 ID. */
66 #define SIZEOF_CMD 1024 /* Size of command buffer. */
67
68 /* This color name can be used to refer to the default term colors. */
69 #define COLOR_DEFAULT (-1)
70
71 #define TIG_HELP "(d)iff, (l)og, (m)ain, (q)uit, (h)elp, (Enter) show diff"
72
73 /* The format and size of the date column in the main view. */
74 #define DATE_FORMAT "%Y-%m-%d %H:%M"
75 #define DATE_COLS STRING_SIZE("2006-04-29 14:21 ")
76
77 /* The default interval between line numbers. */
78 #define NUMBER_INTERVAL 1
79
80 #define TABSIZE 8
81
82 #define SCALE_SPLIT_VIEW(height) ((height) * 2 / 3)
83
84 /* Some ascii-shorthands fitted into the ncurses namespace. */
85 #define KEY_TAB '\t'
86 #define KEY_RETURN '\r'
87 #define KEY_ESC 27
88
89
90 /* User action requests. */
91 enum request {
92 /* Offset all requests to avoid conflicts with ncurses getch values. */
93 REQ_OFFSET = KEY_MAX + 1,
94
95 /* XXX: Keep the view request first and in sync with views[]. */
96 REQ_VIEW_MAIN,
97 REQ_VIEW_DIFF,
98 REQ_VIEW_LOG,
99 REQ_VIEW_HELP,
100 REQ_VIEW_PAGER,
101
102 REQ_ENTER,
103 REQ_QUIT,
104 REQ_PROMPT,
105 REQ_SCREEN_REDRAW,
106 REQ_SCREEN_RESIZE,
107 REQ_SCREEN_UPDATE,
108 REQ_SHOW_VERSION,
109 REQ_STOP_LOADING,
110 REQ_TOGGLE_LINE_NUMBERS,
111 REQ_VIEW_NEXT,
112
113 REQ_MOVE_UP,
114 REQ_MOVE_UP_ENTER,
115 REQ_MOVE_DOWN,
116 REQ_MOVE_DOWN_ENTER,
117 REQ_MOVE_PAGE_UP,
118 REQ_MOVE_PAGE_DOWN,
119 REQ_MOVE_FIRST_LINE,
120 REQ_MOVE_LAST_LINE,
121
122 REQ_SCROLL_LINE_UP,
123 REQ_SCROLL_LINE_DOWN,
124 REQ_SCROLL_PAGE_UP,
125 REQ_SCROLL_PAGE_DOWN,
126 };
127
128 struct ref {
129 char *name; /* Ref name; tag or head names are shortened. */
130 char id[41]; /* Commit SHA1 ID */
131 unsigned int tag:1; /* Is it a tag? */
132 unsigned int next:1; /* For ref lists: are there more refs? */
133 };
134
135 struct commit {
136 char id[41]; /* SHA1 ID. */
137 char title[75]; /* The first line of the commit message. */
138 char author[75]; /* The author of the commit. */
139 struct tm time; /* Date from the author ident. */
140 struct ref **refs; /* Repository references; tags & branch heads. */
141 };
142
143
144 /*
145 * String helpers
146 */
147
148 static inline void
149 string_ncopy(char *dst, char *src, int dstlen)
150 {
151 strncpy(dst, src, dstlen - 1);
152 dst[dstlen - 1] = 0;
153
154 }
155
156 /* Shorthand for safely copying into a fixed buffer. */
157 #define string_copy(dst, src) \
158 string_ncopy(dst, src, sizeof(dst))
159
160
161 /* Shell quoting
162 *
163 * NOTE: The following is a slightly modified copy of the git project's shell
164 * quoting routines found in the quote.c file.
165 *
166 * Help to copy the thing properly quoted for the shell safety. any single
167 * quote is replaced with '\'', any exclamation point is replaced with '\!',
168 * and the whole thing is enclosed in a
169 *
170 * E.g.
171 * original sq_quote result
172 * name ==> name ==> 'name'
173 * a b ==> a b ==> 'a b'
174 * a'b ==> a'\''b ==> 'a'\''b'
175 * a!b ==> a'\!'b ==> 'a'\!'b'
176 */
177
178 static size_t
179 sq_quote(char buf[SIZEOF_CMD], size_t bufsize, const char *src)
180 {
181 char c;
182
183 #define BUFPUT(x) ( (bufsize < SIZEOF_CMD) && (buf[bufsize++] = (x)) )
184
185 BUFPUT('\'');
186 while ((c = *src++)) {
187 if (c == '\'' || c == '!') {
188 BUFPUT('\'');
189 BUFPUT('\\');
190 BUFPUT(c);
191 BUFPUT('\'');
192 } else {
193 BUFPUT(c);
194 }
195 }
196 BUFPUT('\'');
197
198 return bufsize;
199 }
200
201
202 /**
203 * OPTIONS
204 * -------
205 **/
206
207 /* Option and state variables. */
208 static bool opt_line_number = FALSE;
209 static int opt_num_interval = NUMBER_INTERVAL;
210 static int opt_tab_size = TABSIZE;
211 static enum request opt_request = REQ_VIEW_MAIN;
212 static char opt_cmd[SIZEOF_CMD] = "";
213 static FILE *opt_pipe = NULL;
214
215 /* Returns the index of log or diff command or -1 to exit. */
216 static bool
217 parse_options(int argc, char *argv[])
218 {
219 int i;
220
221 for (i = 1; i < argc; i++) {
222 char *opt = argv[i];
223
224 /**
225 * -l::
226 * Start up in log view using the internal log command.
227 **/
228 if (!strcmp(opt, "-l")) {
229 opt_request = REQ_VIEW_LOG;
230 continue;
231 }
232
233 /**
234 * -d::
235 * Start up in diff view using the internal diff command.
236 **/
237 if (!strcmp(opt, "-d")) {
238 opt_request = REQ_VIEW_DIFF;
239 continue;
240 }
241
242 /**
243 * -n[INTERVAL], --line-number[=INTERVAL]::
244 * Prefix line numbers in log and diff view.
245 * Optionally, with interval different than each line.
246 **/
247 if (!strncmp(opt, "-n", 2) ||
248 !strncmp(opt, "--line-number", 13)) {
249 char *num = opt;
250
251 if (opt[1] == 'n') {
252 num = opt + 2;
253
254 } else if (opt[STRING_SIZE("--line-number")] == '=') {
255 num = opt + STRING_SIZE("--line-number=");
256 }
257
258 if (isdigit(*num))
259 opt_num_interval = atoi(num);
260
261 opt_line_number = TRUE;
262 continue;
263 }
264
265 /**
266 * -t[NSPACES], --tab-size[=NSPACES]::
267 * Set the number of spaces tabs should be expanded to.
268 **/
269 if (!strncmp(opt, "-t", 2) ||
270 !strncmp(opt, "--tab-size", 10)) {
271 char *num = opt;
272
273 if (opt[1] == 't') {
274 num = opt + 2;
275
276 } else if (opt[STRING_SIZE("--tab-size")] == '=') {
277 num = opt + STRING_SIZE("--tab-size=");
278 }
279
280 if (isdigit(*num))
281 opt_tab_size = MIN(atoi(num), TABSIZE);
282 continue;
283 }
284
285 /**
286 * -v, --version::
287 * Show version and exit.
288 **/
289 if (!strcmp(opt, "-v") ||
290 !strcmp(opt, "--version")) {
291 printf("tig version %s\n", VERSION);
292 return FALSE;
293 }
294
295 /**
296 * \--::
297 * End of tig(1) options. Useful when specifying commands
298 * options for the main view. Example:
299 *
300 * $ tig -- --since=1.month
301 **/
302 if (!strcmp(opt, "--")) {
303 i++;
304 break;
305 }
306
307 /**
308 * log [git log options]::
309 * Open log view using the given git log options.
310 *
311 * diff [git diff options]::
312 * Open diff view using the given git diff options.
313 *
314 * show [git show options]::
315 * Open diff view using the given git show options.
316 **/
317 if (!strcmp(opt, "log") ||
318 !strcmp(opt, "diff") ||
319 !strcmp(opt, "show")) {
320 opt_request = opt[0] == 'l'
321 ? REQ_VIEW_LOG : REQ_VIEW_DIFF;
322 break;
323 }
324
325 /**
326 * [git options]::
327 * tig(1) will stop the option parsing when the first
328 * command line parameter not starting with "-" is
329 * encountered. This makes the following work:
330 *
331 * $ tig tag-1.0..HEAD
332 **/
333 if (opt[0] && opt[0] != '-')
334 break;
335
336 die("unknown command '%s'", opt);
337 }
338
339 if (!isatty(STDIN_FILENO)) {
340 /**
341 * Pager mode
342 * ~~~~~~~~~~
343 * If stdin is a pipe, any log or diff options will be ignored and the
344 * pager view will be opened loading data from stdin. The pager mode
345 * can be used for colorizing output from various git commands.
346 *
347 * Example on how to colorize the output of git-show(1):
348 *
349 * $ git show | tig
350 **/
351 opt_request = REQ_VIEW_PAGER;
352 opt_pipe = stdin;
353
354 } else if (i < argc) {
355 size_t buf_size;
356
357 /**
358 * Git command options
359 * ~~~~~~~~~~~~~~~~~~~
360 * All git command options specified on the command line will
361 * be passed to the given command and all will be shell quoted
362 * before they are passed to the shell.
363 *
364 * NOTE: If you specify options for the main view, you should
365 * not use the `--pretty` option as this option will be set
366 * automatically to the format expected by the main view.
367 *
368 * Example on how to open the log view and show both author and
369 * committer information:
370 *
371 * $ tig log --pretty=fuller
372 *
373 * See the "Specifying revisions" section below for an introduction
374 * to revision options supported by the git commands. For
375 * details on specific git command options, refer to the man
376 * page of the command in question.
377 **/
378
379 if (opt_request == REQ_VIEW_MAIN)
380 /* XXX: This is vulnerable to the user overriding
381 * options required for the main view parser. */
382 string_copy(opt_cmd, "git log --stat --pretty=raw");
383 else
384 string_copy(opt_cmd, "git");
385 buf_size = strlen(opt_cmd);
386
387 while (buf_size < sizeof(opt_cmd) && i < argc) {
388 opt_cmd[buf_size++] = ' ';
389 buf_size = sq_quote(opt_cmd, buf_size, argv[i++]);
390 }
391
392 if (buf_size >= sizeof(opt_cmd))
393 die("command too long");
394
395 opt_cmd[buf_size] = 0;
396
397 }
398
399 return TRUE;
400 }
401
402
403 /*
404 * Line-oriented content detection.
405 */
406
407 #define LINE_INFO \
408 /* Line type String to match Foreground Background Attributes
409 * --------- --------------- ---------- ---------- ---------- */ \
410 /* Diff markup */ \
411 LINE(DIFF, "diff --git ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
412 LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
413 LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
414 LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
415 LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
416 LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
417 LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
418 LINE(DIFF_COPY, "copy ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
419 LINE(DIFF_RENAME, "rename ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
420 LINE(DIFF_SIM, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
421 LINE(DIFF_DISSIM, "dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
422 /* Pretty print commit header */ \
423 LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
424 LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
425 LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
426 LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
427 LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
428 LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
429 /* Raw commit header */ \
430 LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
431 LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
432 LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
433 LINE(AUTHOR, "author ", COLOR_CYAN, COLOR_DEFAULT, 0), \
434 LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
435 /* Misc */ \
436 LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
437 LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
438 /* UI colors */ \
439 LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
440 LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
441 LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
442 LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
443 LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
444 LINE(MAIN_DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
445 LINE(MAIN_AUTHOR, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
446 LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
447 LINE(MAIN_DELIM, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
448 LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
449 LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD),
450
451 enum line_type {
452 #define LINE(type, line, fg, bg, attr) \
453 LINE_##type
454 LINE_INFO
455 #undef LINE
456 };
457
458 struct line_info {
459 char *line; /* The start of line to match. */
460 int linelen; /* Size of string to match. */
461 int fg, bg, attr; /* Color and text attributes for the lines. */
462 };
463
464 static struct line_info line_info[] = {
465 #define LINE(type, line, fg, bg, attr) \
466 { (line), STRING_SIZE(line), (fg), (bg), (attr) }
467 LINE_INFO
468 #undef LINE
469 };
470
471 static enum line_type
472 get_line_type(char *line)
473 {
474 int linelen = strlen(line);
475 enum line_type type;
476
477 for (type = 0; type < ARRAY_SIZE(line_info); type++)
478 /* Case insensitive search matches Signed-off-by lines better. */
479 if (linelen >= line_info[type].linelen &&
480 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
481 return type;
482
483 return LINE_DEFAULT;
484 }
485
486 static inline int
487 get_line_attr(enum line_type type)
488 {
489 assert(type < ARRAY_SIZE(line_info));
490 return COLOR_PAIR(type) | line_info[type].attr;
491 }
492
493 static void
494 init_colors(void)
495 {
496 int default_bg = COLOR_BLACK;
497 int default_fg = COLOR_WHITE;
498 enum line_type type;
499
500 start_color();
501
502 if (use_default_colors() != ERR) {
503 default_bg = -1;
504 default_fg = -1;
505 }
506
507 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
508 struct line_info *info = &line_info[type];
509 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
510 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
511
512 init_pair(type, fg, bg);
513 }
514 }
515
516
517 /**
518 * ENVIRONMENT VARIABLES
519 * ---------------------
520 * Several options related to the interface with git can be configured
521 * via environment options.
522 *
523 * Repository references
524 * ~~~~~~~~~~~~~~~~~~~~~
525 * Commits that are referenced by tags and branch heads will be marked
526 * by the reference name surrounded by '[' and ']':
527 *
528 * 2006-03-26 19:42 Petr Baudis | [cogito-0.17.1] Cogito 0.17.1
529 *
530 * If you want to filter out certain directories under `.git/refs/`, say
531 * `tmp` you can do it by setting the following variable:
532 *
533 * $ TIG_LS_REMOTE="git ls-remote . | sed /\/tmp\//d" tig
534 *
535 * Or set the variable permanently in your environment.
536 *
537 * TIG_LS_REMOTE::
538 * Set command for retrieving all repository references. The command
539 * should output data in the same format as git-ls-remote(1).
540 **/
541
542 #define TIG_LS_REMOTE \
543 "git ls-remote ."
544
545 /**
546 * View commands
547 * ~~~~~~~~~~~~~
548 * It is possible to alter which commands are used for the different views.
549 * If for example you prefer commits in the main view to be sorted by date
550 * and only show 500 commits, use:
551 *
552 * $ TIG_MAIN_CMD="git log --date-order -n500 --pretty=raw %s" tig
553 *
554 * Or set the variable permanently in your environment.
555 *
556 * Notice, how `%s` is used to specify the commit reference. There can
557 * be a maximum of 5 `%s` ref specifications.
558 *
559 * TIG_DIFF_CMD::
560 * The command used for the diff view. By default, git show is used
561 * as a backend.
562 *
563 * TIG_LOG_CMD::
564 * The command used for the log view. If you prefer to have both
565 * author and committer shown in the log view be sure to pass
566 * `--pretty=fuller` to git log.
567 *
568 * TIG_MAIN_CMD::
569 * The command used for the main view. Note, you must always specify
570 * the option: `--pretty=raw` since the main view parser expects to
571 * read that format.
572 **/
573
574 #define TIG_DIFF_CMD \
575 "git show --patch-with-stat --find-copies-harder -B -C %s"
576
577 #define TIG_LOG_CMD \
578 "git log --cc --stat -n100 %s"
579
580 #define TIG_MAIN_CMD \
581 "git log --topo-order --stat --pretty=raw %s"
582
583 /* We silently ignore that the following are also exported. */
584
585 #define TIG_HELP_CMD \
586 "man tig 2> /dev/null"
587
588 #define TIG_PAGER_CMD \
589 ""
590
591 /**
592 * The viewer
593 * ----------
594 *
595 * tig(1) presents various 'views' of a repository. Each view is based on output
596 * from an external command, most often 'git log', 'git diff', or 'git show'.
597 *
598 * The main view::
599 * Is the default view, and it shows a one line summary of each commit
600 * in the chosen list of revision. The summary includes commit date,
601 * author, and the first line of the log message. Additionally, any
602 * repository references, such as tags, will be shown.
603 *
604 * The log view::
605 * Presents a more rich view of the revision log showing the whole log
606 * message and the diffstat.
607 *
608 * The diff view::
609 * Shows either the diff of the current working tree, that is, what
610 * has changed since the last commit, or the commit diff complete
611 * with log message, diffstat and diff.
612 *
613 * The pager view::
614 * Is used for displaying both input from stdin and output from git
615 * commands entered in the internal prompt.
616 *
617 * The help view::
618 * Displays the information from the tig(1) man page. For the help view
619 * to work you need to have the tig(1) man page installed.
620 **/
621
622 struct view {
623 const char *name; /* View name */
624 char *cmd_fmt; /* Default command line format */
625 char *cmd_env; /* Command line set via environment */
626 char *id; /* Points to either of ref_{head,commit} */
627 size_t objsize; /* Size of objects in the line index */
628
629 struct view_ops {
630 /* What type of content being displayed. Used in the
631 * title bar. */
632 char *type;
633 /* Draw one line; @lineno must be < view->height. */
634 bool (*draw)(struct view *view, unsigned int lineno);
635 /* Read one line; updates view->line. */
636 bool (*read)(struct view *view, char *line);
637 /* Depending on view, change display based on current line. */
638 bool (*enter)(struct view *view);
639 } *ops;
640
641 char cmd[SIZEOF_CMD]; /* Command buffer */
642 char ref[SIZEOF_REF]; /* Hovered commit reference */
643 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
644
645 int height, width; /* The width and height of the main window */
646 WINDOW *win; /* The main window */
647 WINDOW *title; /* The title window living below the main window */
648
649 /* Navigation */
650 unsigned long offset; /* Offset of the window top */
651 unsigned long lineno; /* Current line number */
652
653 /* Buffering */
654 unsigned long lines; /* Total number of lines */
655 void **line; /* Line index; each line contains user data */
656 unsigned int digits; /* Number of digits in the lines member. */
657
658 /* Loading */
659 FILE *pipe;
660 time_t start_time;
661 };
662
663 static struct view_ops pager_ops;
664 static struct view_ops main_ops;
665
666 char ref_head[SIZEOF_REF] = "HEAD";
667 char ref_commit[SIZEOF_REF] = "HEAD";
668
669 #define VIEW_STR(name, cmd, env, ref, objsize, ops) \
670 { name, cmd, #env, ref, objsize, ops }
671
672 #define VIEW_(id, name, ops, ref, objsize) \
673 VIEW_STR(name, TIG_##id##_CMD, TIG_##id##_CMD, ref, objsize, ops)
674
675 static struct view views[] = {
676 VIEW_(MAIN, "main", &main_ops, ref_head, sizeof(struct commit)),
677 VIEW_(DIFF, "diff", &pager_ops, ref_commit, sizeof(char)),
678 VIEW_(LOG, "log", &pager_ops, ref_head, sizeof(char)),
679 VIEW_(HELP, "help", &pager_ops, ref_head, sizeof(char)),
680 VIEW_(PAGER, "pager", &pager_ops, "static", sizeof(char)),
681 };
682
683 #define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
684
685 /* The display array of active views and the index of the current view. */
686 static struct view *display[2];
687 static unsigned int current_view;
688
689 #define foreach_view(view, i) \
690 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
691
692
693 static void
694 redraw_view_from(struct view *view, int lineno)
695 {
696 assert(0 <= lineno && lineno < view->height);
697
698 for (; lineno < view->height; lineno++) {
699 if (!view->ops->draw(view, lineno))
700 break;
701 }
702
703 redrawwin(view->win);
704 wrefresh(view->win);
705 }
706
707 static void
708 redraw_view(struct view *view)
709 {
710 wclear(view->win);
711 redraw_view_from(view, 0);
712 }
713
714 static void
715 resize_display(void)
716 {
717 int offset, i;
718 struct view *base = display[0];
719 struct view *view = display[1] ? display[1] : display[0];
720
721 /* Setup window dimensions */
722
723 getmaxyx(stdscr, base->height, base->width);
724
725 /* Make room for the status window. */
726 base->height -= 1;
727
728 if (view != base) {
729 /* Horizontal split. */
730 view->width = base->width;
731 view->height = SCALE_SPLIT_VIEW(base->height);
732 base->height -= view->height;
733
734 /* Make room for the title bar. */
735 view->height -= 1;
736 }
737
738 /* Make room for the title bar. */
739 base->height -= 1;
740
741 offset = 0;
742
743 foreach_view (view, i) {
744 /* Keep the size of the all view windows one lager than is
745 * required. This makes current line management easier when the
746 * cursor will go outside the window. */
747 if (!view->win) {
748 view->win = newwin(view->height + 1, 0, offset, 0);
749 if (!view->win)
750 die("Failed to create %s view", view->name);
751
752 scrollok(view->win, TRUE);
753
754 view->title = newwin(1, 0, offset + view->height, 0);
755 if (!view->title)
756 die("Failed to create title window");
757
758 } else {
759 wresize(view->win, view->height + 1, view->width);
760 mvwin(view->win, offset, 0);
761 mvwin(view->title, offset + view->height, 0);
762 wrefresh(view->win);
763 }
764
765 offset += view->height + 1;
766 }
767 }
768
769 static void
770 update_view_title(struct view *view)
771 {
772 if (view == display[current_view])
773 wbkgdset(view->title, get_line_attr(LINE_TITLE_FOCUS));
774 else
775 wbkgdset(view->title, get_line_attr(LINE_TITLE_BLUR));
776
777 werase(view->title);
778 wmove(view->title, 0, 0);
779
780 /* [main] ref: 334b506... - commit 6 of 4383 (0%) */
781
782 if (*view->ref)
783 wprintw(view->title, "[%s] %s", view->name, view->ref);
784 else
785 wprintw(view->title, "[%s]", view->name);
786
787 if (view->lines) {
788 wprintw(view->title, " - %s %d of %d (%d%%)",
789 view->ops->type,
790 view->lineno + 1,
791 view->lines,
792 (view->lineno + 1) * 100 / view->lines);
793 }
794
795 wrefresh(view->title);
796 }
797
798 /*
799 * Navigation
800 */
801
802 /* Scrolling backend */
803 static void
804 do_scroll_view(struct view *view, int lines)
805 {
806 /* The rendering expects the new offset. */
807 view->offset += lines;
808
809 assert(0 <= view->offset && view->offset < view->lines);
810 assert(lines);
811
812 /* Redraw the whole screen if scrolling is pointless. */
813 if (view->height < ABS(lines)) {
814 redraw_view(view);
815
816 } else {
817 int line = lines > 0 ? view->height - lines : 0;
818 int end = line + ABS(lines);
819
820 wscrl(view->win, lines);
821
822 for (; line < end; line++) {
823 if (!view->ops->draw(view, line))
824 break;
825 }
826 }
827
828 /* Move current line into the view. */
829 if (view->lineno < view->offset) {
830 view->lineno = view->offset;
831 view->ops->draw(view, 0);
832
833 } else if (view->lineno >= view->offset + view->height) {
834 if (view->lineno == view->offset + view->height) {
835 /* Clear the hidden line so it doesn't show if the view
836 * is scrolled up. */
837 wmove(view->win, view->height, 0);
838 wclrtoeol(view->win);
839 }
840 view->lineno = view->offset + view->height - 1;
841 view->ops->draw(view, view->lineno - view->offset);
842 }
843
844 assert(view->offset <= view->lineno && view->lineno < view->lines);
845
846 redrawwin(view->win);
847 wrefresh(view->win);
848 report("");
849 }
850
851 /* Scroll frontend */
852 static void
853 scroll_view(struct view *view, enum request request)
854 {
855 int lines = 1;
856
857 switch (request) {
858 case REQ_SCROLL_PAGE_DOWN:
859 lines = view->height;
860 case REQ_SCROLL_LINE_DOWN:
861 if (view->offset + lines > view->lines)
862 lines = view->lines - view->offset;
863
864 if (lines == 0 || view->offset + view->height >= view->lines) {
865 report("Cannot scroll beyond the last line");
866 return;
867 }
868 break;
869
870 case REQ_SCROLL_PAGE_UP:
871 lines = view->height;
872 case REQ_SCROLL_LINE_UP:
873 if (lines > view->offset)
874 lines = view->offset;
875
876 if (lines == 0) {
877 report("Cannot scroll beyond the first line");
878 return;
879 }
880
881 lines = -lines;
882 break;
883
884 default:
885 die("request %d not handled in switch", request);
886 }
887
888 do_scroll_view(view, lines);
889 }
890
891 /* Cursor moving */
892 static void
893 move_view(struct view *view, enum request request)
894 {
895 int steps;
896
897 switch (request) {
898 case REQ_MOVE_FIRST_LINE:
899 steps = -view->lineno;
900 break;
901
902 case REQ_MOVE_LAST_LINE:
903 steps = view->lines - view->lineno - 1;
904 break;
905
906 case REQ_MOVE_PAGE_UP:
907 steps = view->height > view->lineno
908 ? -view->lineno : -view->height;
909 break;
910
911 case REQ_MOVE_PAGE_DOWN:
912 steps = view->lineno + view->height >= view->lines
913 ? view->lines - view->lineno - 1 : view->height;
914 break;
915
916 case REQ_MOVE_UP:
917 case REQ_MOVE_UP_ENTER:
918 steps = -1;
919 break;
920
921 case REQ_MOVE_DOWN:
922 case REQ_MOVE_DOWN_ENTER:
923 steps = 1;
924 break;
925
926 default:
927 die("request %d not handled in switch", request);
928 }
929
930 if (steps <= 0 && view->lineno == 0) {
931 report("Cannot move beyond the first line");
932 return;
933
934 } else if (steps >= 0 && view->lineno + 1 >= view->lines) {
935 report("Cannot move beyond the last line");
936 return;
937 }
938
939 /* Move the current line */
940 view->lineno += steps;
941 assert(0 <= view->lineno && view->lineno < view->lines);
942
943 /* Repaint the old "current" line if we be scrolling */
944 if (ABS(steps) < view->height) {
945 int prev_lineno = view->lineno - steps - view->offset;
946
947 wmove(view->win, prev_lineno, 0);
948 wclrtoeol(view->win);
949 view->ops->draw(view, prev_lineno);
950 }
951
952 /* Check whether the view needs to be scrolled */
953 if (view->lineno < view->offset ||
954 view->lineno >= view->offset + view->height) {
955 if (steps < 0 && -steps > view->offset) {
956 steps = -view->offset;
957
958 } else if (steps > 0) {
959 if (view->lineno == view->lines - 1 &&
960 view->lines > view->height) {
961 steps = view->lines - view->offset - 1;
962 if (steps >= view->height)
963 steps -= view->height - 1;
964 }
965 }
966
967 do_scroll_view(view, steps);
968 return;
969 }
970
971 /* Draw the current line */
972 view->ops->draw(view, view->lineno - view->offset);
973
974 redrawwin(view->win);
975 wrefresh(view->win);
976 report("");
977 }
978
979
980 /*
981 * Incremental updating
982 */
983
984 static bool
985 begin_update(struct view *view)
986 {
987 char *id = view->id;
988
989 if (opt_cmd[0]) {
990 string_copy(view->cmd, opt_cmd);
991 opt_cmd[0] = 0;
992 /* When running random commands, the view ref could have become
993 * invalid so clear it. */
994 view->ref[0] = 0;
995 } else {
996 char *format = view->cmd_env ? view->cmd_env : view->cmd_fmt;
997
998 if (snprintf(view->cmd, sizeof(view->cmd), format,
999 id, id, id, id, id) >= sizeof(view->cmd))
1000 return FALSE;
1001 }
1002
1003 /* Special case for the pager view. */
1004 if (opt_pipe) {
1005 view->pipe = opt_pipe;
1006 opt_pipe = NULL;
1007 } else {
1008 view->pipe = popen(view->cmd, "r");
1009 }
1010
1011 if (!view->pipe)
1012 return FALSE;
1013
1014 set_nonblocking_input(TRUE);
1015
1016 view->offset = 0;
1017 view->lines = 0;
1018 view->lineno = 0;
1019 string_copy(view->vid, id);
1020
1021 if (view->line) {
1022 int i;
1023
1024 for (i = 0; i < view->lines; i++)
1025 if (view->line[i])
1026 free(view->line[i]);
1027
1028 free(view->line);
1029 view->line = NULL;
1030 }
1031
1032 view->start_time = time(NULL);
1033
1034 return TRUE;
1035 }
1036
1037 static void
1038 end_update(struct view *view)
1039 {
1040 if (!view->pipe)
1041 return;
1042 set_nonblocking_input(FALSE);
1043 if (view->pipe == stdin)
1044 fclose(view->pipe);
1045 else
1046 pclose(view->pipe);
1047 view->pipe = NULL;
1048 }
1049
1050 static bool
1051 update_view(struct view *view)
1052 {
1053 char buffer[BUFSIZ];
1054 char *line;
1055 void **tmp;
1056 /* The number of lines to read. If too low it will cause too much
1057 * redrawing (and possible flickering), if too high responsiveness
1058 * will suffer. */
1059 unsigned long lines = view->height;
1060 int redraw_from = -1;
1061
1062 if (!view->pipe)
1063 return TRUE;
1064
1065 /* Only redraw if lines are visible. */
1066 if (view->offset + view->height >= view->lines)
1067 redraw_from = view->lines - view->offset;
1068
1069 tmp = realloc(view->line, sizeof(*view->line) * (view->lines + lines));
1070 if (!tmp)
1071 goto alloc_error;
1072
1073 view->line = tmp;
1074
1075 while ((line = fgets(buffer, sizeof(buffer), view->pipe))) {
1076 int linelen = strlen(line);
1077
1078 if (linelen)
1079 line[linelen - 1] = 0;
1080
1081 if (!view->ops->read(view, line))
1082 goto alloc_error;
1083
1084 if (lines-- == 1)
1085 break;
1086 }
1087
1088 {
1089 int digits;
1090
1091 lines = view->lines;
1092 for (digits = 0; lines; digits++)
1093 lines /= 10;
1094
1095 /* Keep the displayed view in sync with line number scaling. */
1096 if (digits != view->digits) {
1097 view->digits = digits;
1098 redraw_from = 0;
1099 }
1100 }
1101
1102 if (redraw_from >= 0) {
1103 /* If this is an incremental update, redraw the previous line
1104 * since for commits some members could have changed when
1105 * loading the main view. */
1106 if (redraw_from > 0)
1107 redraw_from--;
1108
1109 /* Incrementally draw avoids flickering. */
1110 redraw_view_from(view, redraw_from);
1111 }
1112
1113 /* Update the title _after_ the redraw so that if the redraw picks up a
1114 * commit reference in view->ref it'll be available here. */
1115 update_view_title(view);
1116
1117 if (ferror(view->pipe)) {
1118 report("Failed to read: %s", strerror(errno));
1119 goto end;
1120
1121 } else if (feof(view->pipe)) {
1122 time_t secs = time(NULL) - view->start_time;
1123
1124 if (view == VIEW(REQ_VIEW_HELP)) {
1125 char *msg = TIG_HELP;
1126
1127 if (view->lines == 0) {
1128 /* Slightly ugly, but abusing view->ref keeps
1129 * the error message. */
1130 string_copy(view->ref, "No help available");
1131 msg = "The tig(1) manpage is not installed";
1132 }
1133
1134 report("%s", msg);
1135 goto end;
1136 }
1137
1138 report("Loaded %d lines in %ld second%s", view->lines, secs,
1139 secs == 1 ? "" : "s");
1140 goto end;
1141 }
1142
1143 return TRUE;
1144
1145 alloc_error:
1146 report("Allocation failure");
1147
1148 end:
1149 end_update(view);
1150 return FALSE;
1151 }
1152
1153 enum open_flags {
1154 OPEN_DEFAULT = 0, /* Use default view switching. */
1155 OPEN_SPLIT = 1, /* Split current view. */
1156 OPEN_BACKGROUNDED = 2, /* Backgrounded. */
1157 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
1158 };
1159
1160 static void
1161 open_view(struct view *prev, enum request request, enum open_flags flags)
1162 {
1163 bool backgrounded = !!(flags & OPEN_BACKGROUNDED);
1164 bool split = !!(flags & OPEN_SPLIT);
1165 bool reload = !!(flags & OPEN_RELOAD);
1166 struct view *view = VIEW(request);
1167 struct view *displayed;
1168 int nviews;
1169
1170 /* Cycle between displayed views and count the views. */
1171 foreach_view (displayed, nviews) {
1172 if (prev != view &&
1173 view == displayed &&
1174 !strcmp(view->vid, prev->vid)) {
1175 current_view = nviews;
1176 /* Blur out the title of the previous view. */
1177 update_view_title(prev);
1178 report("");
1179 return;
1180 }
1181 }
1182
1183 if (view == prev && nviews == 1 && !reload) {
1184 report("Already in %s view", view->name);
1185 return;
1186 }
1187
1188 if ((reload || strcmp(view->vid, view->id)) &&
1189 !begin_update(view)) {
1190 report("Failed to load %s view", view->name);
1191 return;
1192 }
1193
1194 if (split) {
1195 display[current_view + 1] = view;
1196 if (!backgrounded)
1197 current_view++;
1198 } else {
1199 /* Maximize the current view. */
1200 memset(display, 0, sizeof(display));
1201 current_view = 0;
1202 display[current_view] = view;
1203 }
1204
1205 resize_display();
1206
1207 if (split && prev->lineno - prev->offset >= prev->height) {
1208 /* Take the title line into account. */
1209 int lines = prev->lineno - prev->offset - prev->height + 1;
1210
1211 /* Scroll the view that was split if the current line is
1212 * outside the new limited view. */
1213 do_scroll_view(prev, lines);
1214 }
1215
1216 if (prev && view != prev) {
1217 /* "Blur" the previous view. */
1218 if (!backgrounded)
1219 update_view_title(prev);
1220
1221 /* Continue loading split views in the background. */
1222 if (!split)
1223 end_update(prev);
1224 }
1225
1226 if (view->pipe) {
1227 /* Clear the old view and let the incremental updating refill
1228 * the screen. */
1229 wclear(view->win);
1230 report("Loading...");
1231 } else {
1232 redraw_view(view);
1233 if (view == VIEW(REQ_VIEW_HELP))
1234 report("%s", TIG_HELP);
1235 else
1236 report("");
1237 }
1238
1239 /* If the view is backgrounded the above calls to report()
1240 * won't redraw the view title. */
1241 if (backgrounded)
1242 update_view_title(view);
1243 }
1244
1245
1246 /*
1247 * User request switch noodle
1248 */
1249
1250 static int
1251 view_driver(struct view *view, enum request request)
1252 {
1253 int i;
1254
1255 switch (request) {
1256 case REQ_MOVE_UP:
1257 case REQ_MOVE_DOWN:
1258 case REQ_MOVE_PAGE_UP:
1259 case REQ_MOVE_PAGE_DOWN:
1260 case REQ_MOVE_FIRST_LINE:
1261 case REQ_MOVE_LAST_LINE:
1262 move_view(view, request);
1263 break;
1264
1265 case REQ_SCROLL_LINE_DOWN:
1266 case REQ_SCROLL_LINE_UP:
1267 case REQ_SCROLL_PAGE_DOWN:
1268 case REQ_SCROLL_PAGE_UP:
1269 scroll_view(view, request);
1270 break;
1271
1272 case REQ_VIEW_MAIN:
1273 case REQ_VIEW_DIFF:
1274 case REQ_VIEW_LOG:
1275 case REQ_VIEW_HELP:
1276 case REQ_VIEW_PAGER:
1277 open_view(view, request, OPEN_DEFAULT);
1278 break;
1279
1280 case REQ_MOVE_UP_ENTER:
1281 case REQ_MOVE_DOWN_ENTER:
1282 move_view(view, request);
1283 /* Fall-through */
1284
1285 case REQ_ENTER:
1286 if (!view->lines) {
1287 report("Nothing to enter");
1288 break;
1289 }
1290 return view->ops->enter(view);
1291
1292 case REQ_VIEW_NEXT:
1293 {
1294 int nviews = display[1] ? 2 : 1;
1295 int next_view = (current_view + 1) % nviews;
1296
1297 if (next_view == current_view) {
1298 report("Only one view is displayed");
1299 break;
1300 }
1301
1302 current_view = next_view;
1303 /* Blur out the title of the previous view. */
1304 update_view_title(view);
1305 report("");
1306 break;
1307 }
1308 case REQ_TOGGLE_LINE_NUMBERS:
1309 opt_line_number = !opt_line_number;
1310 redraw_view(view);
1311 update_view_title(view);
1312 break;
1313
1314 case REQ_PROMPT:
1315 /* Always reload^Wrerun commands from the prompt. */
1316 open_view(view, opt_request, OPEN_RELOAD);
1317 break;
1318
1319 case REQ_STOP_LOADING:
1320 foreach_view (view, i) {
1321 if (view->pipe)
1322 report("Stopped loaded the %s view", view->name),
1323 end_update(view);
1324 }
1325 break;
1326
1327 case REQ_SHOW_VERSION:
1328 report("Version: %s", VERSION);
1329 return TRUE;
1330
1331 case REQ_SCREEN_RESIZE:
1332 resize_display();
1333 /* Fall-through */
1334 case REQ_SCREEN_REDRAW:
1335 foreach_view (view, i) {
1336 redraw_view(view);
1337 update_view_title(view);
1338 }
1339 break;
1340
1341 case REQ_SCREEN_UPDATE:
1342 doupdate();
1343 return TRUE;
1344
1345 case REQ_QUIT:
1346 return FALSE;
1347
1348 default:
1349 /* An unknown key will show most commonly used commands. */
1350 report("Unknown key, press 'h' for help");
1351 return TRUE;
1352 }
1353
1354 return TRUE;
1355 }
1356
1357
1358 /*
1359 * View backend handlers
1360 */
1361
1362 static bool
1363 pager_draw(struct view *view, unsigned int lineno)
1364 {
1365 enum line_type type;
1366 char *line;
1367 int linelen;
1368 int attr;
1369
1370 if (view->offset + lineno >= view->lines)
1371 return FALSE;
1372
1373 line = view->line[view->offset + lineno];
1374 type = get_line_type(line);
1375
1376 wmove(view->win, lineno, 0);
1377
1378 if (view->offset + lineno == view->lineno) {
1379 if (type == LINE_COMMIT) {
1380 string_copy(view->ref, line + 7);
1381 string_copy(ref_commit, view->ref);
1382 }
1383
1384 type = LINE_CURSOR;
1385 wchgat(view->win, -1, 0, type, NULL);
1386 }
1387
1388 attr = get_line_attr(type);
1389 wattrset(view->win, attr);
1390
1391 linelen = strlen(line);
1392
1393 if (opt_line_number || opt_tab_size < TABSIZE) {
1394 static char spaces[] = " ";
1395 int col_offset = 0, col = 0;
1396
1397 if (opt_line_number) {
1398 unsigned long real_lineno = view->offset + lineno + 1;
1399
1400 if (real_lineno == 1 ||
1401 (real_lineno % opt_num_interval) == 0) {
1402 wprintw(view->win, "%.*d", view->digits, real_lineno);
1403
1404 } else {
1405 waddnstr(view->win, spaces,
1406 MIN(view->digits, STRING_SIZE(spaces)));
1407 }
1408 waddstr(view->win, ": ");
1409 col_offset = view->digits + 2;
1410 }
1411
1412 while (line && col_offset + col < view->width) {
1413 int cols_max = view->width - col_offset - col;
1414 char *text = line;
1415 int cols;
1416
1417 if (*line == '\t') {
1418 assert(sizeof(spaces) > TABSIZE);
1419 line++;
1420 text = spaces;
1421 cols = opt_tab_size - (col % opt_tab_size);
1422
1423 } else {
1424 line = strchr(line, '\t');
1425 cols = line ? line - text : strlen(text);
1426 }
1427
1428 waddnstr(view->win, text, MIN(cols, cols_max));
1429 col += cols;
1430 }
1431
1432 } else {
1433 int col = 0, pos = 0;
1434
1435 for (; pos < linelen && col < view->width; pos++, col++)
1436 if (line[pos] == '\t')
1437 col += TABSIZE - (col % TABSIZE) - 1;
1438
1439 waddnstr(view->win, line, pos);
1440 }
1441
1442 return TRUE;
1443 }
1444
1445 static bool
1446 pager_read(struct view *view, char *line)
1447 {
1448 /* Compress empty lines in the help view. */
1449 if (view == VIEW(REQ_VIEW_HELP) &&
1450 !*line &&
1451 view->lines &&
1452 !*((char *) view->line[view->lines - 1]))
1453 return TRUE;
1454
1455 view->line[view->lines] = strdup(line);
1456 if (!view->line[view->lines])
1457 return FALSE;
1458
1459 view->lines++;
1460 return TRUE;
1461 }
1462
1463 static bool
1464 pager_enter(struct view *view)
1465 {
1466 char *line = view->line[view->lineno];
1467
1468 if (get_line_type(line) == LINE_COMMIT) {
1469 if (view == VIEW(REQ_VIEW_LOG))
1470 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT | OPEN_BACKGROUNDED);
1471 else
1472 open_view(view, REQ_VIEW_DIFF, OPEN_DEFAULT);
1473 }
1474
1475 return TRUE;
1476 }
1477
1478 static struct view_ops pager_ops = {
1479 "line",
1480 pager_draw,
1481 pager_read,
1482 pager_enter,
1483 };
1484
1485
1486 static struct ref **get_refs(char *id);
1487
1488 static bool
1489 main_draw(struct view *view, unsigned int lineno)
1490 {
1491 char buf[DATE_COLS + 1];
1492 struct commit *commit;
1493 enum line_type type;
1494 int col = 0;
1495 size_t timelen;
1496
1497 if (view->offset + lineno >= view->lines)
1498 return FALSE;
1499
1500 commit = view->line[view->offset + lineno];
1501 if (!*commit->author)
1502 return FALSE;
1503
1504 wmove(view->win, lineno, col);
1505
1506 if (view->offset + lineno == view->lineno) {
1507 string_copy(view->ref, commit->id);
1508 string_copy(ref_commit, view->ref);
1509 type = LINE_CURSOR;
1510 wattrset(view->win, get_line_attr(type));
1511 wchgat(view->win, -1, 0, type, NULL);
1512
1513 } else {
1514 type = LINE_MAIN_COMMIT;
1515 wattrset(view->win, get_line_attr(LINE_MAIN_DATE));
1516 }
1517
1518 timelen = strftime(buf, sizeof(buf), DATE_FORMAT, &commit->time);
1519 waddnstr(view->win, buf, timelen);
1520 waddstr(view->win, " ");
1521
1522 col += DATE_COLS;
1523 wmove(view->win, lineno, col);
1524 if (type != LINE_CURSOR)
1525 wattrset(view->win, get_line_attr(LINE_MAIN_AUTHOR));
1526
1527 if (strlen(commit->author) > 19) {
1528 waddnstr(view->win, commit->author, 18);
1529 if (type != LINE_CURSOR)
1530 wattrset(view->win, get_line_attr(LINE_MAIN_DELIM));
1531 waddch(view->win, '~');
1532 } else {
1533 waddstr(view->win, commit->author);
1534 }
1535
1536 col += 20;
1537 if (type != LINE_CURSOR)
1538 wattrset(view->win, A_NORMAL);
1539
1540 mvwaddch(view->win, lineno, col, ACS_LTEE);
1541 wmove(view->win, lineno, col + 2);
1542 col += 2;
1543
1544 if (commit->refs) {
1545 size_t i = 0;
1546
1547 do {
1548 if (type == LINE_CURSOR)
1549 ;
1550 else if (commit->refs[i]->tag)
1551 wattrset(view->win, get_line_attr(LINE_MAIN_TAG));
1552 else
1553 wattrset(view->win, get_line_attr(LINE_MAIN_REF));
1554 waddstr(view->win, "[");
1555 waddstr(view->win, commit->refs[i]->name);
1556 waddstr(view->win, "]");
1557 if (type != LINE_CURSOR)
1558 wattrset(view->win, A_NORMAL);
1559 waddstr(view->win, " ");
1560 col += strlen(commit->refs[i]->name) + STRING_SIZE("[] ");
1561 } while (commit->refs[i++]->next);
1562 }
1563
1564 if (type != LINE_CURSOR)
1565 wattrset(view->win, get_line_attr(type));
1566
1567 {
1568 int titlelen = strlen(commit->title);
1569
1570 if (col + titlelen > view->width)
1571 titlelen = view->width - col;
1572
1573 waddnstr(view->win, commit->title, titlelen);
1574 }
1575
1576 return TRUE;
1577 }
1578
1579 /* Reads git log --pretty=raw output and parses it into the commit struct. */
1580 static bool
1581 main_read(struct view *view, char *line)
1582 {
1583 enum line_type type = get_line_type(line);
1584 struct commit *commit;
1585
1586 switch (type) {
1587 case LINE_COMMIT:
1588 commit = calloc(1, sizeof(struct commit));
1589 if (!commit)
1590 return FALSE;
1591
1592 line += STRING_SIZE("commit ");
1593
1594 view->line[view->lines++] = commit;
1595 string_copy(commit->id, line);
1596 commit->refs = get_refs(commit->id);
1597 break;
1598
1599 case LINE_AUTHOR:
1600 {
1601 char *ident = line + STRING_SIZE("author ");
1602 char *end = strchr(ident, '<');
1603
1604 if (end) {
1605 for (; end > ident && isspace(end[-1]); end--) ;
1606 *end = 0;
1607 }
1608
1609 commit = view->line[view->lines - 1];
1610 string_copy(commit->author, ident);
1611
1612 /* Parse epoch and timezone */
1613 if (end) {
1614 char *secs = strchr(end + 1, '>');
1615 char *zone;
1616 time_t time;
1617
1618 if (!secs || secs[1] != ' ')
1619 break;
1620
1621 secs += 2;
1622 time = (time_t) atol(secs);
1623 zone = strchr(secs, ' ');
1624 if (zone && strlen(zone) == STRING_SIZE(" +0700")) {
1625 long tz;
1626
1627 zone++;
1628 tz = ('0' - zone[1]) * 60 * 60 * 10;
1629 tz += ('0' - zone[2]) * 60 * 60;
1630 tz += ('0' - zone[3]) * 60;
1631 tz += ('0' - zone[4]) * 60;
1632
1633 if (zone[0] == '-')
1634 tz = -tz;
1635
1636 time -= tz;
1637 }
1638 gmtime_r(&time, &commit->time);
1639 }
1640 break;
1641 }
1642 default:
1643 /* We should only ever end up here if there has already been a
1644 * commit line, however, be safe. */
1645 if (view->lines == 0)
1646 break;
1647
1648 /* Fill in the commit title if it has not already been set. */
1649 commit = view->line[view->lines - 1];
1650 if (commit->title[0])
1651 break;
1652
1653 /* Require titles to start with a non-space character at the
1654 * offset used by git log. */
1655 /* FIXME: More gracefull handling of titles; append "..." to
1656 * shortened titles, etc. */
1657 if (strncmp(line, " ", 4) ||
1658 isspace(line[4]))
1659 break;
1660
1661 string_copy(commit->title, line + 4);
1662 }
1663
1664 return TRUE;
1665 }
1666
1667 static bool
1668 main_enter(struct view *view)
1669 {
1670 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT | OPEN_BACKGROUNDED);
1671 return TRUE;
1672 }
1673
1674 static struct view_ops main_ops = {
1675 "commit",
1676 main_draw,
1677 main_read,
1678 main_enter,
1679 };
1680
1681
1682 /**
1683 * KEYS
1684 * ----
1685 * Below the default key bindings are shown.
1686 **/
1687
1688 struct keymap {
1689 int alias;
1690 int request;
1691 };
1692
1693 struct keymap keymap[] = {
1694 /**
1695 * View switching
1696 * ~~~~~~~~~~~~~~
1697 * m::
1698 * Switch to main view.
1699 * d::
1700 * Switch to diff view.
1701 * l::
1702 * Switch to log view.
1703 * p::
1704 * Switch to pager view.
1705 * h::
1706 * Show man page.
1707 * Return::
1708 * If on a commit line show the commit diff. Addiionally, if in
1709 * main or log view this will split the view. To open the commit
1710 * diff in full size view either use 'd' or press Return twice.
1711 * Tab::
1712 * Switch to next view.
1713 **/
1714 { 'm', REQ_VIEW_MAIN },
1715 { 'd', REQ_VIEW_DIFF },
1716 { 'l', REQ_VIEW_LOG },
1717 { 'p', REQ_VIEW_PAGER },
1718 { 'h', REQ_VIEW_HELP },
1719
1720 { KEY_TAB, REQ_VIEW_NEXT },
1721 { KEY_RETURN, REQ_ENTER },
1722
1723 /**
1724 * Cursor navigation
1725 * ~~~~~~~~~~~~~~~~~
1726 * Up::
1727 * Move curser one line up.
1728 * Down::
1729 * Move cursor one line down.
1730 * k::
1731 * Move curser one line up and enter. When used in the main view
1732 * this will always show the diff of the current commit in the
1733 * split diff view.
1734 * j::
1735 * Move cursor one line down and enter.
1736 * PgUp::
1737 * Move curser one page up.
1738 * PgDown::
1739 * Move cursor one page down.
1740 * Home::
1741 * Jump to first line.
1742 * End::
1743 * Jump to last line.
1744 **/
1745 { KEY_UP, REQ_MOVE_UP },
1746 { KEY_DOWN, REQ_MOVE_DOWN },
1747 { 'k', REQ_MOVE_UP_ENTER },
1748 { 'j', REQ_MOVE_DOWN_ENTER },
1749 { KEY_HOME, REQ_MOVE_FIRST_LINE },
1750 { KEY_END, REQ_MOVE_LAST_LINE },
1751 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
1752 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
1753
1754 /**
1755 * Scrolling
1756 * ~~~~~~~~~
1757 * Insert::
1758 * Scroll view one line up.
1759 * Delete::
1760 * Scroll view one line down.
1761 * w::
1762 * Scroll view one page up.
1763 * s::
1764 * Scroll view one page down.
1765 **/
1766 { KEY_IC, REQ_SCROLL_LINE_UP },
1767 { KEY_DC, REQ_SCROLL_LINE_DOWN },
1768 { 'w', REQ_SCROLL_PAGE_UP },
1769 { 's', REQ_SCROLL_PAGE_DOWN },
1770
1771 /**
1772 * Misc
1773 * ~~~~
1774 * q::
1775 * Quit
1776 * r::
1777 * Redraw screen.
1778 * z::
1779 * Stop all background loading. This can be useful if you use
1780 * tig(1) in a repository with a long history without limiting
1781 * the log output.
1782 * v::
1783 * Show version.
1784 * n::
1785 * Toggle line numbers on/off.
1786 * ':'::
1787 * Open prompt. This allows you to specify what git command
1788 * to run. Example:
1789 *
1790 * :log -p
1791 **/
1792 { 'q', REQ_QUIT },
1793 { 'z', REQ_STOP_LOADING },
1794 { 'v', REQ_SHOW_VERSION },
1795 { 'r', REQ_SCREEN_REDRAW },
1796 { 'n', REQ_TOGGLE_LINE_NUMBERS },
1797 { ':', REQ_PROMPT },
1798
1799 /* wgetch() with nodelay() enabled returns ERR when there's no input. */
1800 { ERR, REQ_SCREEN_UPDATE },
1801
1802 /* Use the ncurses SIGWINCH handler. */
1803 { KEY_RESIZE, REQ_SCREEN_RESIZE },
1804 };
1805
1806 static enum request
1807 get_request(int key)
1808 {
1809 int i;
1810
1811 for (i = 0; i < ARRAY_SIZE(keymap); i++)
1812 if (keymap[i].alias == key)
1813 return keymap[i].request;
1814
1815 return (enum request) key;
1816 }
1817
1818
1819 /*
1820 * Status management
1821 */
1822
1823 /* Whether or not the curses interface has been initialized. */
1824 bool cursed = FALSE;
1825
1826 /* The status window is used for polling keystrokes. */
1827 static WINDOW *status_win;
1828
1829 /* Update status and title window. */
1830 static void
1831 report(const char *msg, ...)
1832 {
1833 static bool empty = TRUE;
1834 struct view *view = display[current_view];
1835
1836 if (!empty || *msg) {
1837 va_list args;
1838
1839 va_start(args, msg);
1840
1841 werase(status_win);
1842 wmove(status_win, 0, 0);
1843 if (*msg) {
1844 vwprintw(status_win, msg, args);
1845 empty = FALSE;
1846 } else {
1847 empty = TRUE;
1848 }
1849 wrefresh(status_win);
1850
1851 va_end(args);
1852 }
1853
1854 update_view_title(view);
1855
1856 /* Move the cursor to the right-most column of the cursor line.
1857 *
1858 * XXX: This could turn out to be a bit expensive, but it ensures that
1859 * the cursor does not jump around. */
1860 if (view->lines) {
1861 wmove(view->win, view->lineno - view->offset, view->width - 1);
1862 wrefresh(view->win);
1863 }
1864 }
1865
1866 /* Controls when nodelay should be in effect when polling user input. */
1867 static void
1868 set_nonblocking_input(bool loading)
1869 {
1870 static unsigned int loading_views;
1871
1872 if ((loading == FALSE && loading_views-- == 1) ||
1873 (loading == TRUE && loading_views++ == 0))
1874 nodelay(status_win, loading);
1875 }
1876
1877 static void
1878 init_display(void)
1879 {
1880 int x, y;
1881
1882 /* Initialize the curses library */
1883 if (isatty(STDIN_FILENO)) {
1884 cursed = !!initscr();
1885 } else {
1886 /* Leave stdin and stdout alone when acting as a pager. */
1887 FILE *io = fopen("/dev/tty", "r+");
1888
1889 cursed = !!newterm(NULL, io, io);
1890 }
1891
1892 if (!cursed)
1893 die("Failed to initialize curses");
1894
1895 nonl(); /* Tell curses not to do NL->CR/NL on output */
1896 cbreak(); /* Take input chars one at a time, no wait for \n */
1897 noecho(); /* Don't echo input */
1898 leaveok(stdscr, TRUE);
1899
1900 if (has_colors())
1901 init_colors();
1902
1903 getmaxyx(stdscr, y, x);
1904 status_win = newwin(1, 0, y - 1, 0);
1905 if (!status_win)
1906 die("Failed to create status window");
1907
1908 /* Enable keyboard mapping */
1909 keypad(status_win, TRUE);
1910 wbkgdset(status_win, get_line_attr(LINE_STATUS));
1911 }
1912
1913
1914 /*
1915 * Repository references
1916 */
1917
1918 static struct ref *refs;
1919 size_t refs_size;
1920
1921 static struct ref **
1922 get_refs(char *id)
1923 {
1924 struct ref **id_refs = NULL;
1925 size_t id_refs_size = 0;
1926 size_t i;
1927
1928 for (i = 0; i < refs_size; i++) {
1929 struct ref **tmp;
1930
1931 if (strcmp(id, refs[i].id))
1932 continue;
1933
1934 tmp = realloc(id_refs, (id_refs_size + 1) * sizeof(*id_refs));
1935 if (!tmp) {
1936 if (id_refs)
1937 free(id_refs);
1938 return NULL;
1939 }
1940
1941 id_refs = tmp;
1942 if (id_refs_size > 0)
1943 id_refs[id_refs_size - 1]->next = 1;
1944 id_refs[id_refs_size] = &refs[i];
1945
1946 /* XXX: The properties of the commit chains ensures that we can
1947 * safely modify the shared ref. The repo references will
1948 * always be similar for the same id. */
1949 id_refs[id_refs_size]->next = 0;
1950 id_refs_size++;
1951 }
1952
1953 return id_refs;
1954 }
1955
1956 static int
1957 load_refs(void)
1958 {
1959 char *cmd_env = getenv("TIG_LS_REMOTE");
1960 char *cmd = cmd_env && *cmd_env ? cmd_env : TIG_LS_REMOTE;
1961 FILE *pipe = popen(cmd, "r");
1962 char buffer[BUFSIZ];
1963 char *line;
1964
1965 if (!pipe)
1966 return ERR;
1967
1968 while ((line = fgets(buffer, sizeof(buffer), pipe))) {
1969 char *name = strchr(line, '\t');
1970 struct ref *ref;
1971 int namelen;
1972 bool tag = FALSE;
1973 bool tag_commit = FALSE;
1974
1975 if (!name)
1976 continue;
1977
1978 *name++ = 0;
1979 namelen = strlen(name) - 1;
1980
1981 /* Commits referenced by tags has "^{}" appended. */
1982 if (name[namelen - 1] == '}') {
1983 while (namelen > 0 && name[namelen] != '^')
1984 namelen--;
1985 if (namelen > 0)
1986 tag_commit = TRUE;
1987 }
1988 name[namelen] = 0;
1989
1990 if (!strncmp(name, "refs/tags/", STRING_SIZE("refs/tags/"))) {
1991 if (!tag_commit)
1992 continue;
1993 name += STRING_SIZE("refs/tags/");
1994 tag = TRUE;
1995
1996 } else if (!strncmp(name, "refs/heads/", STRING_SIZE("refs/heads/"))) {
1997 name += STRING_SIZE("refs/heads/");
1998
1999 } else if (!strcmp(name, "HEAD")) {
2000 continue;
2001 }
2002
2003 refs = realloc(refs, sizeof(*refs) * (refs_size + 1));
2004 if (!refs)
2005 return ERR;
2006
2007 ref = &refs[refs_size++];
2008 ref->tag = tag;
2009 ref->name = strdup(name);
2010 if (!ref->name)
2011 return ERR;
2012
2013 string_copy(ref->id, line);
2014 }
2015
2016 if (ferror(pipe))
2017 return ERR;
2018
2019 pclose(pipe);
2020
2021 return OK;
2022 }
2023
2024 /*
2025 * Main
2026 */
2027
2028 static void
2029 quit(int sig)
2030 {
2031 /* XXX: Restore tty modes and let the OS cleanup the rest! */
2032 if (cursed)
2033 endwin();
2034 exit(0);
2035 }
2036
2037 static void die(const char *err, ...)
2038 {
2039 va_list args;
2040
2041 endwin();
2042
2043 va_start(args, err);
2044 fputs("tig: ", stderr);
2045 vfprintf(stderr, err, args);
2046 fputs("\n", stderr);
2047 va_end(args);
2048
2049 exit(1);
2050 }
2051
2052 int
2053 main(int argc, char *argv[])
2054 {
2055 struct view *view;
2056 enum request request;
2057 size_t i;
2058
2059 signal(SIGINT, quit);
2060
2061 if (!parse_options(argc, argv))
2062 return 0;
2063
2064 if (load_refs() == ERR)
2065 die("Failed to load refs.");
2066
2067 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
2068 view->cmd_env = getenv(view->cmd_env);
2069
2070 request = opt_request;
2071
2072 init_display();
2073
2074 while (view_driver(display[current_view], request)) {
2075 int key;
2076 int i;
2077
2078 foreach_view (view, i)
2079 update_view(view);
2080
2081 /* Refresh, accept single keystroke of input */
2082 key = wgetch(status_win);
2083 request = get_request(key);
2084
2085 /* Some low-level request handling. This keeps access to
2086 * status_win restricted. */
2087 switch (request) {
2088 case REQ_PROMPT:
2089 report(":");
2090 /* Temporarily switch to line-oriented and echoed
2091 * input. */
2092 nocbreak();
2093 echo();
2094
2095 if (wgetnstr(status_win, opt_cmd + 4, sizeof(opt_cmd) - 4) == OK) {
2096 memcpy(opt_cmd, "git ", 4);
2097 opt_request = REQ_VIEW_PAGER;
2098 } else {
2099 request = ERR;
2100 }
2101
2102 noecho();
2103 cbreak();
2104 break;
2105
2106 case REQ_SCREEN_RESIZE:
2107 {
2108 int height, width;
2109
2110 getmaxyx(stdscr, height, width);
2111
2112 /* Resize the status view and let the view driver take
2113 * care of resizing the displayed views. */
2114 wresize(status_win, 1, width);
2115 mvwin(status_win, height - 1, 0);
2116 wrefresh(status_win);
2117 break;
2118 }
2119 default:
2120 break;
2121 }
2122 }
2123
2124 quit(0);
2125
2126 return 0;
2127 }
2128
2129 /**
2130 * Specifying revisions
2131 * --------------------
2132 * This section describes various ways to specify what revisions to
2133 * display or otherwise limit the view to.
2134 *
2135 * Limit by date or number
2136 * ~~~~~~~~~~~~~~~~~~~~~~~
2137 * To speed up interaction with git, you can limit the amount of commits
2138 * to show both for the log and main view. Either limit by date using
2139 * e.g. `--since=1.month` or limit by the number of commits using `-n400`.
2140 *
2141 * NOTE: You can tune the interaction with git by making use of the options
2142 * explained in this section.
2143 *
2144 * NOTE: tig(1) does not itself parse the revision options
2145 * described in this section.
2146 *
2147 * Ranges
2148 * ~~~~~~
2149 * Alternatively, commits can be limited to a specific range, such as
2150 * "all commits between 'tag-1.0' and 'tag-2.0'". For example:
2151 *
2152 * $ tig log tag-1.0..tag-2.0
2153 *
2154 * This way of commit limiting makes it trivial to only browse the commits
2155 * which haven't been pushed to a remote branch. Assuming 'origin' is your
2156 * upstream remote branch, using:
2157 *
2158 * $ tig log origin..HEAD
2159 *
2160 * will list what will be pushed to the remote branch. Optionally, the ending
2161 * 'HEAD' can be left out since it is implied.
2162 *
2163 * Limiting by reachability
2164 * ~~~~~~~~~~~~~~~~~~~~~~~~
2165 * Git interprets the range specifier "tag-1.0..tag-2.0" as
2166 * "all commits reachable from 'tag-2.0' but not from 'tag-1.0'".
2167 * If you prefer to specify which commit to preview in this way use the
2168 * following:
2169 *
2170 * $ tig log tag-2.0 ^tag-1.0
2171 *
2172 * You can think of '^' as a negator. Using this alternate syntax, it is
2173 * possible to furthur prune commits by specifying multiple negators.
2174 *
2175 * BUGS
2176 * ----
2177 * Known bugs and problems:
2178 *
2179 * - If the screen width is very small the main view can draw
2180 * outside the current view causing bad wrapping. Same goes
2181 * for title and status windows.
2182 *
2183 * TODO
2184 * ----
2185 * Features that should be explored.
2186 *
2187 * - Searching.
2188 *
2189 * - Locale support.
2190 *
2191 * COPYRIGHT
2192 * ---------
2193 * Copyright (c) Jonas Fonseca <fonseca@diku.dk>, 2006
2194 *
2195 * This program is free software; you can redistribute it and/or modify
2196 * it under the terms of the GNU General Public License as published by
2197 * the Free Software Foundation; either version 2 of the License, or
2198 * (at your option) any later version.
2199 *
2200 * SEE ALSO
2201 * --------
2202 * [verse]
2203 * link:http://www.kernel.org/pub/software/scm/git/docs/[git(7)],
2204 * link:http://www.kernel.org/pub/software/scm/cogito/docs/[cogito(7)]
2205 * gitk(1): git repository browser written using tcl/tk,
2206 * gitview(1): git repository browser written using python/gtk.
2207 **/