read_prompt: take prompt 'name' as arg
[tig] / tig.c
CommitLineData
4a2909a7 1/* Copyright (c) 2006 Jonas Fonseca <fonseca@diku.dk>
192d9a60 2 *
5cfbde75
JF
3 * This program is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU General Public License as
5 * published by the Free Software Foundation; either version 2 of
6 * the License, or (at your option) any later version.
192d9a60
JF
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 */
b801d8b2 13
b76c2afc 14#ifndef VERSION
0f11e3a9 15#define VERSION "tig-0.4.git"
b76c2afc
JF
16#endif
17
8855ada4
JF
18#ifndef DEBUG
19#define NDEBUG
20#endif
21
22f66b0a 22#include <assert.h>
4c6fabc2 23#include <errno.h>
22f66b0a
JF
24#include <ctype.h>
25#include <signal.h>
b801d8b2 26#include <stdarg.h>
b801d8b2 27#include <stdio.h>
22f66b0a 28#include <stdlib.h>
b801d8b2 29#include <string.h>
6908bdbd 30#include <unistd.h>
b76c2afc 31#include <time.h>
b801d8b2 32
6b68fd24
JF
33#include <locale.h>
34#include <langinfo.h>
35#include <iconv.h>
36
b801d8b2 37#include <curses.h>
b801d8b2 38
e2da526d
JF
39#if __GNUC__ >= 3
40#define __NORETURN __attribute__((__noreturn__))
41#else
42#define __NORETURN
43#endif
44
45static void __NORETURN die(const char *err, ...);
b801d8b2 46static void report(const char *msg, ...);
4a63c884 47static int read_properties(FILE *pipe, const char *separators, int (*read)(char *, int, char *, int));
1ba2ae4b 48static void set_nonblocking_input(bool loading);
10e290ee 49static size_t utf8_length(const char *string, size_t max_width, int *coloffset, int *trimmed);
6b161b31
JF
50
51#define ABS(x) ((x) >= 0 ? (x) : -(x))
52#define MIN(x, y) ((x) < (y) ? (x) : (y))
53
54#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
55#define STRING_SIZE(x) (sizeof(x) - 1)
b76c2afc 56
17482b11 57#define SIZEOF_STR 1024 /* Default string size. */
2e8488b4 58#define SIZEOF_REF 256 /* Size of symbolic or SHA1 ID. */
54efb62b 59#define SIZEOF_REVGRAPH 19 /* Size of revision ancestry graphics. */
b801d8b2 60
82e78006
JF
61/* This color name can be used to refer to the default term colors. */
62#define COLOR_DEFAULT (-1)
78c70acd 63
6b68fd24
JF
64#define ICONV_NONE ((iconv_t) -1)
65
82e78006 66/* The format and size of the date column in the main view. */
4c6fabc2 67#define DATE_FORMAT "%Y-%m-%d %H:%M"
6b161b31 68#define DATE_COLS STRING_SIZE("2006-04-29 14:21 ")
4c6fabc2 69
10e290ee
JF
70#define AUTHOR_COLS 20
71
a28bcc22 72/* The default interval between line numbers. */
4a2909a7 73#define NUMBER_INTERVAL 1
82e78006 74
6706b2ba
JF
75#define TABSIZE 8
76
a28bcc22
JF
77#define SCALE_SPLIT_VIEW(height) ((height) * 2 / 3)
78
8eb62770
JF
79#define TIG_LS_REMOTE \
80 "git ls-remote . 2>/dev/null"
81
82#define TIG_DIFF_CMD \
73fb51d5 83 "git show --root --patch-with-stat --find-copies-harder -B -C %s 2>/dev/null"
8eb62770
JF
84
85#define TIG_LOG_CMD \
8fee6614 86 "git log --cc --stat -n100 %s 2>/dev/null"
8eb62770
JF
87
88#define TIG_MAIN_CMD \
8fee6614 89 "git log --topo-order --pretty=raw %s 2>/dev/null"
8eb62770
JF
90
91/* XXX: Needs to be defined to the empty string. */
92#define TIG_HELP_CMD ""
93#define TIG_PAGER_CMD ""
94
8855ada4 95/* Some ascii-shorthands fitted into the ncurses namespace. */
a28bcc22
JF
96#define KEY_TAB '\t'
97#define KEY_RETURN '\r'
4a2909a7
JF
98#define KEY_ESC 27
99
6706b2ba 100
c34d9c9f 101struct ref {
468876c9
JF
102 char *name; /* Ref name; tag or head names are shortened. */
103 char id[41]; /* Commit SHA1 ID */
104 unsigned int tag:1; /* Is it a tag? */
105 unsigned int next:1; /* For ref lists: are there more refs? */
c34d9c9f
JF
106};
107
ff26aa29 108static struct ref **get_refs(char *id);
4c6fabc2 109
660e09ad
JF
110struct int_map {
111 const char *name;
112 int namelen;
113 int value;
114};
115
116static int
117set_from_int_map(struct int_map *map, size_t map_size,
118 int *value, const char *name, int namelen)
119{
120
121 int i;
122
123 for (i = 0; i < map_size; i++)
124 if (namelen == map[i].namelen &&
125 !strncasecmp(name, map[i].name, namelen)) {
126 *value = map[i].value;
127 return OK;
128 }
129
130 return ERR;
131}
132
6706b2ba 133
03a93dbb
JF
134/*
135 * String helpers
136 */
78c70acd 137
82e78006 138static inline void
4685845e 139string_ncopy(char *dst, const char *src, int dstlen)
82e78006
JF
140{
141 strncpy(dst, src, dstlen - 1);
142 dst[dstlen - 1] = 0;
03a93dbb 143
82e78006
JF
144}
145
146/* Shorthand for safely copying into a fixed buffer. */
147#define string_copy(dst, src) \
148 string_ncopy(dst, src, sizeof(dst))
149
4a63c884
JF
150static char *
151chomp_string(char *name)
152{
153 int namelen;
154
155 while (isspace(*name))
156 name++;
157
158 namelen = strlen(name) - 1;
159 while (namelen > 0 && isspace(name[namelen]))
160 name[namelen--] = 0;
161
162 return name;
163}
164
cc2d1364
JF
165static bool
166string_nformat(char *buf, size_t bufsize, int *bufpos, const char *fmt, ...)
167{
168 va_list args;
169 int pos = bufpos ? *bufpos : 0;
170
171 va_start(args, fmt);
172 pos += vsnprintf(buf + pos, bufsize - pos, fmt, args);
173 va_end(args);
174
175 if (bufpos)
176 *bufpos = pos;
177
178 return pos >= bufsize ? FALSE : TRUE;
179}
180
181#define string_format(buf, fmt, args...) \
182 string_nformat(buf, sizeof(buf), NULL, fmt, args)
183
184#define string_format_from(buf, from, fmt, args...) \
185 string_nformat(buf, sizeof(buf), from, fmt, args)
6706b2ba 186
201f5a18
JF
187static int
188string_enum_compare(const char *str1, const char *str2, int len)
189{
190 size_t i;
191
192#define string_enum_sep(x) ((x) == '-' || (x) == '_' || (x) == '.')
193
194 /* Diff-Header == DIFF_HEADER */
195 for (i = 0; i < len; i++) {
196 if (toupper(str1[i]) == toupper(str2[i]))
197 continue;
198
199 if (string_enum_sep(str1[i]) &&
200 string_enum_sep(str2[i]))
201 continue;
202
203 return str1[i] - str2[i];
204 }
205
206 return 0;
207}
208
03a93dbb
JF
209/* Shell quoting
210 *
211 * NOTE: The following is a slightly modified copy of the git project's shell
212 * quoting routines found in the quote.c file.
213 *
214 * Help to copy the thing properly quoted for the shell safety. any single
215 * quote is replaced with '\'', any exclamation point is replaced with '\!',
216 * and the whole thing is enclosed in a
217 *
218 * E.g.
219 * original sq_quote result
220 * name ==> name ==> 'name'
221 * a b ==> a b ==> 'a b'
222 * a'b ==> a'\''b ==> 'a'\''b'
223 * a!b ==> a'\!'b ==> 'a'\!'b'
224 */
225
226static size_t
17482b11 227sq_quote(char buf[SIZEOF_STR], size_t bufsize, const char *src)
03a93dbb
JF
228{
229 char c;
230
17482b11 231#define BUFPUT(x) do { if (bufsize < SIZEOF_STR) buf[bufsize++] = (x); } while (0)
03a93dbb
JF
232
233 BUFPUT('\'');
234 while ((c = *src++)) {
235 if (c == '\'' || c == '!') {
236 BUFPUT('\'');
237 BUFPUT('\\');
238 BUFPUT(c);
239 BUFPUT('\'');
240 } else {
241 BUFPUT(c);
242 }
243 }
244 BUFPUT('\'');
245
246 return bufsize;
247}
248
82e78006 249
24b5b3e0
JF
250/*
251 * User requests
252 */
253
254#define REQ_INFO \
255 /* XXX: Keep the view request first and in sync with views[]. */ \
256 REQ_GROUP("View switching") \
257 REQ_(VIEW_MAIN, "Show main view"), \
258 REQ_(VIEW_DIFF, "Show diff view"), \
259 REQ_(VIEW_LOG, "Show log view"), \
260 REQ_(VIEW_HELP, "Show help page"), \
261 REQ_(VIEW_PAGER, "Show pager view"), \
262 \
263 REQ_GROUP("View manipulation") \
264 REQ_(ENTER, "Enter current line and scroll"), \
265 REQ_(NEXT, "Move to next"), \
266 REQ_(PREVIOUS, "Move to previous"), \
267 REQ_(VIEW_NEXT, "Move focus to next view"), \
268 REQ_(VIEW_CLOSE, "Close the current view"), \
269 REQ_(QUIT, "Close all views and quit"), \
270 \
271 REQ_GROUP("Cursor navigation") \
272 REQ_(MOVE_UP, "Move cursor one line up"), \
273 REQ_(MOVE_DOWN, "Move cursor one line down"), \
274 REQ_(MOVE_PAGE_DOWN, "Move cursor one page down"), \
275 REQ_(MOVE_PAGE_UP, "Move cursor one page up"), \
276 REQ_(MOVE_FIRST_LINE, "Move cursor to first line"), \
277 REQ_(MOVE_LAST_LINE, "Move cursor to last line"), \
278 \
279 REQ_GROUP("Scrolling") \
280 REQ_(SCROLL_LINE_UP, "Scroll one line up"), \
281 REQ_(SCROLL_LINE_DOWN, "Scroll one line down"), \
282 REQ_(SCROLL_PAGE_UP, "Scroll one page up"), \
283 REQ_(SCROLL_PAGE_DOWN, "Scroll one page down"), \
284 \
285 REQ_GROUP("Misc") \
286 REQ_(PROMPT, "Bring up the prompt"), \
287 REQ_(SCREEN_UPDATE, "Update the screen"), \
288 REQ_(SCREEN_REDRAW, "Redraw the screen"), \
289 REQ_(SCREEN_RESIZE, "Resize the screen"), \
290 REQ_(SHOW_VERSION, "Show version information"), \
291 REQ_(STOP_LOADING, "Stop all loading views"), \
54efb62b 292 REQ_(TOGGLE_LINENO, "Toggle line numbers"), \
04e2b7b2 293 REQ_(TOGGLE_REV_GRAPH, "Toggle revision graph visualization")
24b5b3e0
JF
294
295
296/* User action requests. */
297enum request {
298#define REQ_GROUP(help)
299#define REQ_(req, help) REQ_##req
300
301 /* Offset all requests to avoid conflicts with ncurses getch values. */
302 REQ_OFFSET = KEY_MAX + 1,
04e2b7b2
JF
303 REQ_INFO,
304 REQ_UNKNOWN,
24b5b3e0
JF
305
306#undef REQ_GROUP
307#undef REQ_
308};
309
310struct request_info {
311 enum request request;
04e2b7b2
JF
312 char *name;
313 int namelen;
24b5b3e0
JF
314 char *help;
315};
316
317static struct request_info req_info[] = {
04e2b7b2
JF
318#define REQ_GROUP(help) { 0, NULL, 0, (help) },
319#define REQ_(req, help) { REQ_##req, (#req), STRING_SIZE(#req), (help) }
24b5b3e0
JF
320 REQ_INFO
321#undef REQ_GROUP
322#undef REQ_
323};
324
04e2b7b2
JF
325static enum request
326get_request(const char *name)
327{
328 int namelen = strlen(name);
329 int i;
330
331 for (i = 0; i < ARRAY_SIZE(req_info); i++)
332 if (req_info[i].namelen == namelen &&
333 !string_enum_compare(req_info[i].name, name, namelen))
334 return req_info[i].request;
335
336 return REQ_UNKNOWN;
337}
338
339
8eb62770
JF
340/*
341 * Options
342 */
b76c2afc 343
4b8c01a3
JF
344static const char usage[] =
345VERSION " (" __DATE__ ")\n"
346"\n"
347"Usage: tig [options]\n"
348" or: tig [options] [--] [git log options]\n"
349" or: tig [options] log [git log options]\n"
350" or: tig [options] diff [git diff options]\n"
351" or: tig [options] show [git show options]\n"
352" or: tig [options] < [git command output]\n"
353"\n"
354"Options:\n"
355" -l Start up in log view\n"
356" -d Start up in diff view\n"
357" -n[I], --line-number[=I] Show line numbers with given interval\n"
b3c965c9 358" -b[N], --tab-size[=N] Set number of spaces for tab expansion\n"
4b8c01a3
JF
359" -- Mark end of tig options\n"
360" -v, --version Show version and exit\n"
361" -h, --help Show help message and exit\n";
362
6706b2ba
JF
363/* Option and state variables. */
364static bool opt_line_number = FALSE;
54efb62b 365static bool opt_rev_graph = TRUE;
2e8488b4 366static int opt_num_interval = NUMBER_INTERVAL;
6706b2ba 367static int opt_tab_size = TABSIZE;
6b161b31 368static enum request opt_request = REQ_VIEW_MAIN;
17482b11 369static char opt_cmd[SIZEOF_STR] = "";
6908bdbd 370static FILE *opt_pipe = NULL;
6b68fd24
JF
371static char opt_encoding[20] = "UTF-8";
372static bool opt_utf8 = TRUE;
373static char opt_codeset[20] = "UTF-8";
374static iconv_t opt_iconv = ICONV_NONE;
b76c2afc 375
6dbf6c19
JF
376enum option_type {
377 OPT_NONE,
378 OPT_INT,
379};
380
381static bool
382check_option(char *opt, char short_name, char *name, enum option_type type, ...)
383{
384 va_list args;
385 char *value = "";
386 int *number;
387
388 if (opt[0] != '-')
389 return FALSE;
390
391 if (opt[1] == '-') {
392 int namelen = strlen(name);
393
394 opt += 2;
395
396 if (strncmp(opt, name, namelen))
397 return FALSE;
398
399 if (opt[namelen] == '=')
400 value = opt + namelen + 1;
401
402 } else {
403 if (!short_name || opt[1] != short_name)
404 return FALSE;
405 value = opt + 2;
406 }
407
408 va_start(args, type);
409 if (type == OPT_INT) {
410 number = va_arg(args, int *);
411 if (isdigit(*value))
412 *number = atoi(value);
413 }
414 va_end(args);
415
416 return TRUE;
417}
418
b76c2afc 419/* Returns the index of log or diff command or -1 to exit. */
8855ada4 420static bool
b76c2afc
JF
421parse_options(int argc, char *argv[])
422{
423 int i;
424
425 for (i = 1; i < argc; i++) {
426 char *opt = argv[i];
427
6b161b31 428 if (!strcmp(opt, "-l")) {
4a2909a7 429 opt_request = REQ_VIEW_LOG;
6b161b31
JF
430 continue;
431 }
b76c2afc 432
6b161b31 433 if (!strcmp(opt, "-d")) {
4a2909a7 434 opt_request = REQ_VIEW_DIFF;
6b161b31
JF
435 continue;
436 }
b76c2afc 437
6dbf6c19 438 if (check_option(opt, 'n', "line-number", OPT_INT, &opt_num_interval)) {
6b161b31
JF
439 opt_line_number = TRUE;
440 continue;
441 }
b76c2afc 442
6dbf6c19
JF
443 if (check_option(opt, 'b', "tab-size", OPT_INT, &opt_tab_size)) {
444 opt_tab_size = MIN(opt_tab_size, TABSIZE);
6706b2ba
JF
445 continue;
446 }
447
6dbf6c19 448 if (check_option(opt, 'v', "version", OPT_NONE)) {
b76c2afc 449 printf("tig version %s\n", VERSION);
8855ada4 450 return FALSE;
6b161b31 451 }
b76c2afc 452
6dbf6c19 453 if (check_option(opt, 'h', "help", OPT_NONE)) {
4b8c01a3
JF
454 printf(usage);
455 return FALSE;
456 }
457
6908bdbd
JF
458 if (!strcmp(opt, "--")) {
459 i++;
460 break;
461 }
03a93dbb 462
8855ada4
JF
463 if (!strcmp(opt, "log") ||
464 !strcmp(opt, "diff") ||
465 !strcmp(opt, "show")) {
466 opt_request = opt[0] == 'l'
467 ? REQ_VIEW_LOG : REQ_VIEW_DIFF;
468 break;
469 }
470
03a93dbb 471 if (opt[0] && opt[0] != '-')
6908bdbd 472 break;
6b161b31 473
bf174187 474 die("unknown option '%s'\n\n%s", opt, usage);
b76c2afc
JF
475 }
476
6908bdbd 477 if (!isatty(STDIN_FILENO)) {
6908bdbd
JF
478 opt_request = REQ_VIEW_PAGER;
479 opt_pipe = stdin;
480
481 } else if (i < argc) {
482 size_t buf_size;
483
6908bdbd 484 if (opt_request == REQ_VIEW_MAIN)
8855ada4
JF
485 /* XXX: This is vulnerable to the user overriding
486 * options required for the main view parser. */
6908bdbd
JF
487 string_copy(opt_cmd, "git log --stat --pretty=raw");
488 else
489 string_copy(opt_cmd, "git");
490 buf_size = strlen(opt_cmd);
491
492 while (buf_size < sizeof(opt_cmd) && i < argc) {
493 opt_cmd[buf_size++] = ' ';
494 buf_size = sq_quote(opt_cmd, buf_size, argv[i++]);
495 }
496
497 if (buf_size >= sizeof(opt_cmd))
498 die("command too long");
499
500 opt_cmd[buf_size] = 0;
501
502 }
503
afdc35b3
JF
504 if (*opt_encoding && strcasecmp(opt_encoding, "UTF-8"))
505 opt_utf8 = FALSE;
506
8855ada4 507 return TRUE;
b76c2afc
JF
508}
509
510
54efb62b
JF
511/*
512 * Line-oriented content detection.
513 */
514
2e8488b4 515#define LINE_INFO \
660e09ad 516LINE(DIFF_HEADER, "diff --git ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
a28bcc22
JF
517LINE(DIFF_CHUNK, "@@", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
518LINE(DIFF_ADD, "+", COLOR_GREEN, COLOR_DEFAULT, 0), \
519LINE(DIFF_DEL, "-", COLOR_RED, COLOR_DEFAULT, 0), \
660e09ad
JF
520LINE(DIFF_INDEX, "index ", COLOR_BLUE, COLOR_DEFAULT, 0), \
521LINE(DIFF_OLDMODE, "old file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
522LINE(DIFF_NEWMODE, "new file mode ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
523LINE(DIFF_COPY_FROM, "copy from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
524LINE(DIFF_COPY_TO, "copy to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
525LINE(DIFF_RENAME_FROM, "rename from", COLOR_YELLOW, COLOR_DEFAULT, 0), \
526LINE(DIFF_RENAME_TO, "rename to", COLOR_YELLOW, COLOR_DEFAULT, 0), \
527LINE(DIFF_SIMILARITY, "similarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
528LINE(DIFF_DISSIMILARITY,"dissimilarity ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
529LINE(DIFF_TREE, "diff-tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
6908bdbd 530LINE(PP_AUTHOR, "Author: ", COLOR_CYAN, COLOR_DEFAULT, 0), \
8855ada4 531LINE(PP_COMMIT, "Commit: ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
6908bdbd
JF
532LINE(PP_MERGE, "Merge: ", COLOR_BLUE, COLOR_DEFAULT, 0), \
533LINE(PP_DATE, "Date: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
8855ada4
JF
534LINE(PP_ADATE, "AuthorDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
535LINE(PP_CDATE, "CommitDate: ", COLOR_YELLOW, COLOR_DEFAULT, 0), \
7b99a34c 536LINE(PP_REFS, "Refs: ", COLOR_RED, COLOR_DEFAULT, 0), \
a28bcc22
JF
537LINE(COMMIT, "commit ", COLOR_GREEN, COLOR_DEFAULT, 0), \
538LINE(PARENT, "parent ", COLOR_BLUE, COLOR_DEFAULT, 0), \
539LINE(TREE, "tree ", COLOR_BLUE, COLOR_DEFAULT, 0), \
8855ada4 540LINE(AUTHOR, "author ", COLOR_CYAN, COLOR_DEFAULT, 0), \
a28bcc22 541LINE(COMMITTER, "committer ", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
a28bcc22 542LINE(SIGNOFF, " Signed-off-by", COLOR_YELLOW, COLOR_DEFAULT, 0), \
a28bcc22
JF
543LINE(DEFAULT, "", COLOR_DEFAULT, COLOR_DEFAULT, A_NORMAL), \
544LINE(CURSOR, "", COLOR_WHITE, COLOR_GREEN, A_BOLD), \
545LINE(STATUS, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
6b161b31
JF
546LINE(TITLE_BLUR, "", COLOR_WHITE, COLOR_BLUE, 0), \
547LINE(TITLE_FOCUS, "", COLOR_WHITE, COLOR_BLUE, A_BOLD), \
a28bcc22
JF
548LINE(MAIN_DATE, "", COLOR_BLUE, COLOR_DEFAULT, 0), \
549LINE(MAIN_AUTHOR, "", COLOR_GREEN, COLOR_DEFAULT, 0), \
550LINE(MAIN_COMMIT, "", COLOR_DEFAULT, COLOR_DEFAULT, 0), \
c34d9c9f
JF
551LINE(MAIN_DELIM, "", COLOR_MAGENTA, COLOR_DEFAULT, 0), \
552LINE(MAIN_TAG, "", COLOR_MAGENTA, COLOR_DEFAULT, A_BOLD), \
660e09ad 553LINE(MAIN_REF, "", COLOR_CYAN, COLOR_DEFAULT, A_BOLD), \
660e09ad 554
78c70acd 555enum line_type {
2e8488b4
JF
556#define LINE(type, line, fg, bg, attr) \
557 LINE_##type
558 LINE_INFO
559#undef LINE
78c70acd
JF
560};
561
562struct line_info {
660e09ad
JF
563 const char *name; /* Option name. */
564 int namelen; /* Size of option name. */
4685845e 565 const char *line; /* The start of line to match. */
2e8488b4
JF
566 int linelen; /* Size of string to match. */
567 int fg, bg, attr; /* Color and text attributes for the lines. */
78c70acd
JF
568};
569
2e8488b4 570static struct line_info line_info[] = {
78c70acd 571#define LINE(type, line, fg, bg, attr) \
660e09ad 572 { #type, STRING_SIZE(#type), (line), STRING_SIZE(line), (fg), (bg), (attr) }
2e8488b4
JF
573 LINE_INFO
574#undef LINE
78c70acd
JF
575};
576
2e8488b4
JF
577static enum line_type
578get_line_type(char *line)
78c70acd
JF
579{
580 int linelen = strlen(line);
a28bcc22 581 enum line_type type;
78c70acd 582
a28bcc22 583 for (type = 0; type < ARRAY_SIZE(line_info); type++)
2e8488b4 584 /* Case insensitive search matches Signed-off-by lines better. */
a28bcc22
JF
585 if (linelen >= line_info[type].linelen &&
586 !strncasecmp(line_info[type].line, line, line_info[type].linelen))
587 return type;
78c70acd 588
2e8488b4 589 return LINE_DEFAULT;
78c70acd
JF
590}
591
2e8488b4 592static inline int
78c70acd
JF
593get_line_attr(enum line_type type)
594{
2e8488b4
JF
595 assert(type < ARRAY_SIZE(line_info));
596 return COLOR_PAIR(type) | line_info[type].attr;
78c70acd
JF
597}
598
660e09ad
JF
599static struct line_info *
600get_line_info(char *name, int namelen)
601{
602 enum line_type type;
660e09ad
JF
603
604 for (type = 0; type < ARRAY_SIZE(line_info); type++)
605 if (namelen == line_info[type].namelen &&
201f5a18 606 !string_enum_compare(line_info[type].name, name, namelen))
660e09ad
JF
607 return &line_info[type];
608
609 return NULL;
610}
611
78c70acd
JF
612static void
613init_colors(void)
614{
82e78006
JF
615 int default_bg = COLOR_BLACK;
616 int default_fg = COLOR_WHITE;
a28bcc22 617 enum line_type type;
78c70acd
JF
618
619 start_color();
620
621 if (use_default_colors() != ERR) {
82e78006
JF
622 default_bg = -1;
623 default_fg = -1;
78c70acd
JF
624 }
625
a28bcc22
JF
626 for (type = 0; type < ARRAY_SIZE(line_info); type++) {
627 struct line_info *info = &line_info[type];
82e78006
JF
628 int bg = info->bg == COLOR_DEFAULT ? default_bg : info->bg;
629 int fg = info->fg == COLOR_DEFAULT ? default_fg : info->fg;
78c70acd 630
a28bcc22 631 init_pair(type, fg, bg);
78c70acd
JF
632 }
633}
634
fe7233c3
JF
635struct line {
636 enum line_type type;
637 void *data; /* User data */
638};
639
78c70acd 640
1899507c 641/*
37157fa0
JF
642 * Keys
643 */
644
93a97d86 645struct keybinding {
37157fa0 646 int alias;
93a97d86 647 enum request request;
04e2b7b2 648 struct keybinding *next;
37157fa0
JF
649};
650
93a97d86 651static struct keybinding default_keybindings[] = {
37157fa0
JF
652 /* View switching */
653 { 'm', REQ_VIEW_MAIN },
654 { 'd', REQ_VIEW_DIFF },
655 { 'l', REQ_VIEW_LOG },
656 { 'p', REQ_VIEW_PAGER },
657 { 'h', REQ_VIEW_HELP },
658 { '?', REQ_VIEW_HELP },
659
660 /* View manipulation */
661 { 'q', REQ_VIEW_CLOSE },
662 { KEY_TAB, REQ_VIEW_NEXT },
663 { KEY_RETURN, REQ_ENTER },
664 { KEY_UP, REQ_PREVIOUS },
665 { KEY_DOWN, REQ_NEXT },
666
667 /* Cursor navigation */
668 { 'k', REQ_MOVE_UP },
669 { 'j', REQ_MOVE_DOWN },
670 { KEY_HOME, REQ_MOVE_FIRST_LINE },
671 { KEY_END, REQ_MOVE_LAST_LINE },
672 { KEY_NPAGE, REQ_MOVE_PAGE_DOWN },
673 { ' ', REQ_MOVE_PAGE_DOWN },
674 { KEY_PPAGE, REQ_MOVE_PAGE_UP },
675 { 'b', REQ_MOVE_PAGE_UP },
676 { '-', REQ_MOVE_PAGE_UP },
677
678 /* Scrolling */
679 { KEY_IC, REQ_SCROLL_LINE_UP },
680 { KEY_DC, REQ_SCROLL_LINE_DOWN },
681 { 'w', REQ_SCROLL_PAGE_UP },
682 { 's', REQ_SCROLL_PAGE_DOWN },
683
684 /* Misc */
685 { 'Q', REQ_QUIT },
686 { 'z', REQ_STOP_LOADING },
687 { 'v', REQ_SHOW_VERSION },
688 { 'r', REQ_SCREEN_REDRAW },
689 { 'n', REQ_TOGGLE_LINENO },
73fb51d5 690 { 'g', REQ_TOGGLE_REV_GRAPH },
37157fa0
JF
691 { ':', REQ_PROMPT },
692
693 /* wgetch() with nodelay() enabled returns ERR when there's no input. */
694 { ERR, REQ_SCREEN_UPDATE },
695
696 /* Use the ncurses SIGWINCH handler. */
697 { KEY_RESIZE, REQ_SCREEN_RESIZE },
698};
699
04e2b7b2
JF
700#define KEYMAP_INFO \
701 KEYMAP_(GENERIC), \
702 KEYMAP_(MAIN), \
703 KEYMAP_(DIFF), \
704 KEYMAP_(LOG), \
705 KEYMAP_(PAGER), \
706 KEYMAP_(HELP) \
707
708enum keymap {
709#define KEYMAP_(name) KEYMAP_##name
710 KEYMAP_INFO
711#undef KEYMAP_
712};
713
714static struct int_map keymap_table[] = {
715#define KEYMAP_(name) { #name, STRING_SIZE(#name), KEYMAP_##name }
716 KEYMAP_INFO
717#undef KEYMAP_
718};
719
720#define set_keymap(map, name) \
721 set_from_int_map(keymap_table, ARRAY_SIZE(keymap_table), map, name, strlen(name))
722
723static struct keybinding *keybindings[ARRAY_SIZE(keymap_table)];
724
725static void
726add_keybinding(enum keymap keymap, enum request request, int key)
727{
728 struct keybinding *keybinding;
729
730 keybinding = calloc(1, sizeof(*keybinding));
731 if (!keybinding)
732 die("Failed to allocate keybinding");
733
734 keybinding->alias = key;
735 keybinding->request = request;
736 keybinding->next = keybindings[keymap];
737 keybindings[keymap] = keybinding;
738}
739
740/* Looks for a key binding first in the given map, then in the generic map, and
741 * lastly in the default keybindings. */
37157fa0 742static enum request
04e2b7b2 743get_keybinding(enum keymap keymap, int key)
37157fa0 744{
04e2b7b2 745 struct keybinding *kbd;
37157fa0
JF
746 int i;
747
04e2b7b2
JF
748 for (kbd = keybindings[keymap]; kbd; kbd = kbd->next)
749 if (kbd->alias == key)
750 return kbd->request;
751
752 for (kbd = keybindings[KEYMAP_GENERIC]; kbd; kbd = kbd->next)
753 if (kbd->alias == key)
754 return kbd->request;
755
93a97d86
JF
756 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++)
757 if (default_keybindings[i].alias == key)
758 return default_keybindings[i].request;
37157fa0
JF
759
760 return (enum request) key;
761}
762
93a97d86 763
37157fa0
JF
764struct key {
765 char *name;
766 int value;
767};
768
769static struct key key_table[] = {
770 { "Enter", KEY_RETURN },
771 { "Space", ' ' },
772 { "Backspace", KEY_BACKSPACE },
773 { "Tab", KEY_TAB },
774 { "Escape", KEY_ESC },
775 { "Left", KEY_LEFT },
776 { "Right", KEY_RIGHT },
777 { "Up", KEY_UP },
778 { "Down", KEY_DOWN },
779 { "Insert", KEY_IC },
780 { "Delete", KEY_DC },
74f83ee6 781 { "Hash", '#' },
37157fa0
JF
782 { "Home", KEY_HOME },
783 { "End", KEY_END },
784 { "PageUp", KEY_PPAGE },
785 { "PageDown", KEY_NPAGE },
786 { "F1", KEY_F(1) },
787 { "F2", KEY_F(2) },
788 { "F3", KEY_F(3) },
789 { "F4", KEY_F(4) },
790 { "F5", KEY_F(5) },
791 { "F6", KEY_F(6) },
792 { "F7", KEY_F(7) },
793 { "F8", KEY_F(8) },
794 { "F9", KEY_F(9) },
795 { "F10", KEY_F(10) },
796 { "F11", KEY_F(11) },
797 { "F12", KEY_F(12) },
798};
799
04e2b7b2
JF
800static int
801get_key_value(const char *name)
802{
803 int i;
804
805 for (i = 0; i < ARRAY_SIZE(key_table); i++)
806 if (!strcasecmp(key_table[i].name, name))
807 return key_table[i].value;
808
809 if (strlen(name) == 1 && isprint(*name))
810 return (int) *name;
811
812 return ERR;
813}
814
37157fa0
JF
815static char *
816get_key(enum request request)
817{
818 static char buf[BUFSIZ];
819 static char key_char[] = "'X'";
820 int pos = 0;
821 char *sep = " ";
822 int i;
823
824 buf[pos] = 0;
825
93a97d86
JF
826 for (i = 0; i < ARRAY_SIZE(default_keybindings); i++) {
827 struct keybinding *keybinding = &default_keybindings[i];
37157fa0
JF
828 char *seq = NULL;
829 int key;
830
93a97d86 831 if (keybinding->request != request)
37157fa0
JF
832 continue;
833
834 for (key = 0; key < ARRAY_SIZE(key_table); key++)
93a97d86 835 if (key_table[key].value == keybinding->alias)
37157fa0
JF
836 seq = key_table[key].name;
837
838 if (seq == NULL &&
93a97d86
JF
839 keybinding->alias < 127 &&
840 isprint(keybinding->alias)) {
841 key_char[1] = (char) keybinding->alias;
37157fa0
JF
842 seq = key_char;
843 }
844
845 if (!seq)
846 seq = "'?'";
847
848 if (!string_format_from(buf, &pos, "%s%s", sep, seq))
849 return "Too many keybindings!";
850 sep = ", ";
851 }
852
853 return buf;
854}
855
856
857/*
1899507c
JF
858 * User config file handling.
859 */
860
5dc795f2
JF
861static struct int_map color_map[] = {
862#define COLOR_MAP(name) { #name, STRING_SIZE(#name), COLOR_##name }
863 COLOR_MAP(DEFAULT),
864 COLOR_MAP(BLACK),
865 COLOR_MAP(BLUE),
866 COLOR_MAP(CYAN),
867 COLOR_MAP(GREEN),
868 COLOR_MAP(MAGENTA),
869 COLOR_MAP(RED),
870 COLOR_MAP(WHITE),
871 COLOR_MAP(YELLOW),
872};
873
9256ab05
JF
874#define set_color(color, name) \
875 set_from_int_map(color_map, ARRAY_SIZE(color_map), color, name, strlen(name))
660e09ad 876
5dc795f2
JF
877static struct int_map attr_map[] = {
878#define ATTR_MAP(name) { #name, STRING_SIZE(#name), A_##name }
879 ATTR_MAP(NORMAL),
880 ATTR_MAP(BLINK),
881 ATTR_MAP(BOLD),
882 ATTR_MAP(DIM),
883 ATTR_MAP(REVERSE),
884 ATTR_MAP(STANDOUT),
885 ATTR_MAP(UNDERLINE),
886};
887
9256ab05
JF
888#define set_attribute(attr, name) \
889 set_from_int_map(attr_map, ARRAY_SIZE(attr_map), attr, name, strlen(name))
660e09ad 890
3c3801c2
JF
891static int config_lineno;
892static bool config_errors;
893static char *config_msg;
894
5bfd96c7 895/* Wants: object fgcolor bgcolor [attr] */
660e09ad 896static int
5bfd96c7 897option_color_command(int argc, char *argv[])
660e09ad 898{
bca8fcaa
JF
899 struct line_info *info;
900
9256ab05
JF
901 if (argc != 3 && argc != 4) {
902 config_msg = "Wrong number of arguments given to color command";
903 return ERR;
904 }
905
906 info = get_line_info(argv[0], strlen(argv[0]));
bca8fcaa
JF
907 if (!info) {
908 config_msg = "Unknown color name";
909 return ERR;
910 }
660e09ad 911
a3653368
JF
912 if (set_color(&info->fg, argv[1]) == ERR ||
913 set_color(&info->bg, argv[2]) == ERR) {
bca8fcaa
JF
914 config_msg = "Unknown color";
915 return ERR;
916 }
660e09ad 917
9256ab05 918 if (argc == 4 && set_attribute(&info->attr, argv[3]) == ERR) {
bca8fcaa
JF
919 config_msg = "Unknown attribute";
920 return ERR;
660e09ad
JF
921 }
922
bca8fcaa
JF
923 return OK;
924}
925
5bfd96c7
JF
926/* Wants: name = value */
927static int
928option_set_command(int argc, char *argv[])
929{
930 if (argc != 3) {
931 config_msg = "Wrong number of arguments given to set command";
932 return ERR;
933 }
934
935 if (strcmp(argv[1], "=")) {
936 config_msg = "No value assigned";
937 return ERR;
938 }
939
940 if (!strcmp(argv[0], "show-rev-graph")) {
941 opt_rev_graph = (!strcmp(argv[2], "1") ||
942 !strcmp(argv[2], "true") ||
943 !strcmp(argv[2], "yes"));
944 return OK;
945 }
946
947 if (!strcmp(argv[0], "line-number-interval")) {
948 opt_num_interval = atoi(argv[2]);
949 return OK;
950 }
951
952 if (!strcmp(argv[0], "tab-size")) {
953 opt_tab_size = atoi(argv[2]);
954 return OK;
955 }
956
cb7267ee 957 if (!strcmp(argv[0], "commit-encoding")) {
3cc9a4d4
JF
958 char *arg = argv[2];
959 int delimiter = *arg;
960 int i;
961
962 switch (delimiter) {
963 case '"':
964 case '\'':
965 for (arg++, i = 0; arg[i]; i++)
966 if (arg[i] == delimiter) {
967 arg[i] = 0;
968 break;
969 }
970 default:
971 string_copy(opt_encoding, arg);
972 return OK;
973 }
5bfd96c7
JF
974 }
975
a3653368 976 config_msg = "Unknown variable name";
5bfd96c7
JF
977 return ERR;
978}
979
04e2b7b2
JF
980/* Wants: mode request key */
981static int
982option_bind_command(int argc, char *argv[])
983{
984 enum request request;
985 int keymap;
986 int key;
987
988 if (argc != 3) {
989 config_msg = "Wrong number of arguments given to bind command";
990 return ERR;
991 }
992
993 if (set_keymap(&keymap, argv[0]) == ERR) {
994 config_msg = "Unknown key map";
995 return ERR;
996 }
997
998 key = get_key_value(argv[1]);
999 if (key == ERR) {
1000 config_msg = "Unknown key";
1001 return ERR;
1002 }
1003
1004 request = get_request(argv[2]);
1005 if (request == REQ_UNKNOWN) {
1006 config_msg = "Unknown request name";
1007 return ERR;
1008 }
1009
1010 add_keybinding(keymap, request, key);
1011
1012 return OK;
1013}
1014
bca8fcaa 1015static int
9256ab05 1016set_option(char *opt, char *value)
bca8fcaa 1017{
9256ab05
JF
1018 char *argv[16];
1019 int valuelen;
1020 int argc = 0;
1021
1022 /* Tokenize */
1023 while (argc < ARRAY_SIZE(argv) && (valuelen = strcspn(value, " \t"))) {
1024 argv[argc++] = value;
1025
1026 value += valuelen;
1027 if (!*value)
1028 break;
1029
1030 *value++ = 0;
1031 while (isspace(*value))
1032 value++;
1033 }
1034
1035 if (!strcmp(opt, "color"))
5bfd96c7
JF
1036 return option_color_command(argc, argv);
1037
1038 if (!strcmp(opt, "set"))
1039 return option_set_command(argc, argv);
bca8fcaa 1040
04e2b7b2
JF
1041 if (!strcmp(opt, "bind"))
1042 return option_bind_command(argc, argv);
1043
a3653368 1044 config_msg = "Unknown option command";
660e09ad
JF
1045 return ERR;
1046}
1047
1048static int
3c3801c2
JF
1049read_option(char *opt, int optlen, char *value, int valuelen)
1050{
a3653368
JF
1051 int status = OK;
1052
3c3801c2
JF
1053 config_lineno++;
1054 config_msg = "Internal error";
1055
a3653368
JF
1056 /* Check for comment markers, since read_properties() will
1057 * only ensure opt and value are split at first " \t". */
74f83ee6 1058 optlen = strcspn(opt, "#");
a3653368 1059 if (optlen == 0)
3c3801c2
JF
1060 return OK;
1061
a3653368
JF
1062 if (opt[optlen] != 0) {
1063 config_msg = "No option value";
1064 status = ERR;
1065
1066 } else {
1067 /* Look for comment endings in the value. */
74f83ee6 1068 int len = strcspn(value, "#");
a3653368
JF
1069
1070 if (len < valuelen) {
1071 valuelen = len;
1072 value[valuelen] = 0;
1073 }
1074
1075 status = set_option(opt, value);
3c3801c2
JF
1076 }
1077
a3653368
JF
1078 if (status == ERR) {
1079 fprintf(stderr, "Error on line %d, near '%.*s': %s\n",
3c3801c2
JF
1080 config_lineno, optlen, opt, config_msg);
1081 config_errors = TRUE;
1082 }
1083
1084 /* Always keep going if errors are encountered. */
1085 return OK;
1086}
1087
1088static int
660e09ad
JF
1089load_options(void)
1090{
1091 char *home = getenv("HOME");
17482b11 1092 char buf[SIZEOF_STR];
660e09ad
JF
1093 FILE *file;
1094
3c3801c2
JF
1095 config_lineno = 0;
1096 config_errors = FALSE;
1097
cc2d1364 1098 if (!home || !string_format(buf, "%s/.tigrc", home))
660e09ad
JF
1099 return ERR;
1100
1101 /* It's ok that the file doesn't exist. */
1102 file = fopen(buf, "r");
1103 if (!file)
1104 return OK;
1105
3c3801c2
JF
1106 if (read_properties(file, " \t", read_option) == ERR ||
1107 config_errors == TRUE)
1108 fprintf(stderr, "Errors while loading %s.\n", buf);
1109
1110 return OK;
660e09ad
JF
1111}
1112
1113
d839253b 1114/*
468876c9 1115 * The viewer
d839253b 1116 */
c2124ccd
JF
1117
1118struct view;
fe7233c3 1119struct view_ops;
c2124ccd
JF
1120
1121/* The display array of active views and the index of the current view. */
1122static struct view *display[2];
1123static unsigned int current_view;
1124
1125#define foreach_view(view, i) \
1126 for (i = 0; i < ARRAY_SIZE(display) && (view = display[i]); i++)
1127
9f41488f 1128#define displayed_views() (display[1] != NULL ? 2 : 1)
c2124ccd 1129
d839253b 1130/* Current head and commit ID */
c2124ccd
JF
1131static char ref_commit[SIZEOF_REF] = "HEAD";
1132static char ref_head[SIZEOF_REF] = "HEAD";
1133
b801d8b2 1134struct view {
03a93dbb 1135 const char *name; /* View name */
4685845e
TH
1136 const char *cmd_fmt; /* Default command line format */
1137 const char *cmd_env; /* Command line set via environment */
1138 const char *id; /* Points to either of ref_{head,commit} */
6b161b31 1139
fe7233c3 1140 struct view_ops *ops; /* View operations */
22f66b0a 1141
04e2b7b2
JF
1142 enum keymap keymap; /* What keymap does this view have */
1143
17482b11 1144 char cmd[SIZEOF_STR]; /* Command buffer */
49f2b43f
JF
1145 char ref[SIZEOF_REF]; /* Hovered commit reference */
1146 char vid[SIZEOF_REF]; /* View ID. Set to id member when updating. */
2e8488b4 1147
8855ada4
JF
1148 int height, width; /* The width and height of the main window */
1149 WINDOW *win; /* The main window */
1150 WINDOW *title; /* The title window living below the main window */
b801d8b2
JF
1151
1152 /* Navigation */
1153 unsigned long offset; /* Offset of the window top */
1154 unsigned long lineno; /* Current line number */
1155
f6da0b66
JF
1156 /* If non-NULL, points to the view that opened this view. If this view
1157 * is closed tig will switch back to the parent view. */
1158 struct view *parent;
1159
b801d8b2
JF
1160 /* Buffering */
1161 unsigned long lines; /* Total number of lines */
fe7233c3 1162 struct line *line; /* Line index */
e2c01617 1163 unsigned long line_size;/* Total number of allocated lines */
8855ada4 1164 unsigned int digits; /* Number of digits in the lines member. */
b801d8b2
JF
1165
1166 /* Loading */
1167 FILE *pipe;
2e8488b4 1168 time_t start_time;
b801d8b2
JF
1169};
1170
fe7233c3
JF
1171struct view_ops {
1172 /* What type of content being displayed. Used in the title bar. */
1173 const char *type;
1174 /* Draw one line; @lineno must be < view->height. */
1175 bool (*draw)(struct view *view, struct line *line, unsigned int lineno);
1176 /* Read one line; updates view->line. */
701e4f5d 1177 bool (*read)(struct view *view, char *data);
fe7233c3
JF
1178 /* Depending on view, change display based on current line. */
1179 bool (*enter)(struct view *view, struct line *line);
1180};
1181
6b161b31
JF
1182static struct view_ops pager_ops;
1183static struct view_ops main_ops;
a28bcc22 1184
04e2b7b2
JF
1185#define VIEW_STR(name, cmd, env, ref, ops, map) \
1186 { name, cmd, #env, ref, ops, map}
1ba2ae4b 1187
95d7ddcd 1188#define VIEW_(id, name, ops, ref) \
04e2b7b2 1189 VIEW_STR(name, TIG_##id##_CMD, TIG_##id##_CMD, ref, ops, KEYMAP_##id)
1ba2ae4b 1190
c2124ccd 1191
b801d8b2 1192static struct view views[] = {
95d7ddcd
JF
1193 VIEW_(MAIN, "main", &main_ops, ref_head),
1194 VIEW_(DIFF, "diff", &pager_ops, ref_commit),
1195 VIEW_(LOG, "log", &pager_ops, ref_head),
1196 VIEW_(HELP, "help", &pager_ops, "static"),
1197 VIEW_(PAGER, "pager", &pager_ops, "static"),
b801d8b2
JF
1198};
1199
a28bcc22
JF
1200#define VIEW(req) (&views[(req) - REQ_OFFSET - 1])
1201
4c6fabc2 1202
fe7233c3
JF
1203static bool
1204draw_view_line(struct view *view, unsigned int lineno)
1205{
1206 if (view->offset + lineno >= view->lines)
1207 return FALSE;
1208
1209 return view->ops->draw(view, &view->line[view->offset + lineno], lineno);
1210}
1211
b801d8b2 1212static void
82e78006 1213redraw_view_from(struct view *view, int lineno)
b801d8b2 1214{
82e78006 1215 assert(0 <= lineno && lineno < view->height);
b801d8b2 1216
82e78006 1217 for (; lineno < view->height; lineno++) {
fe7233c3 1218 if (!draw_view_line(view, lineno))
fd85fef1 1219 break;
b801d8b2
JF
1220 }
1221
1222 redrawwin(view->win);
1223 wrefresh(view->win);
1224}
1225
b76c2afc 1226static void
82e78006
JF
1227redraw_view(struct view *view)
1228{
1229 wclear(view->win);
1230 redraw_view_from(view, 0);
1231}
1232
c2124ccd 1233
6b161b31 1234static void
81030ec8
JF
1235update_view_title(struct view *view)
1236{
1237 if (view == display[current_view])
1238 wbkgdset(view->title, get_line_attr(LINE_TITLE_FOCUS));
1239 else
1240 wbkgdset(view->title, get_line_attr(LINE_TITLE_BLUR));
1241
1242 werase(view->title);
1243 wmove(view->title, 0, 0);
1244
81030ec8
JF
1245 if (*view->ref)
1246 wprintw(view->title, "[%s] %s", view->name, view->ref);
1247 else
1248 wprintw(view->title, "[%s]", view->name);
1249
c19f8017 1250 if (view->lines || view->pipe) {
6d9c07af 1251 unsigned int view_lines = view->offset + view->height;
c19f8017 1252 unsigned int lines = view->lines
6d9c07af 1253 ? MIN(view_lines, view->lines) * 100 / view->lines
c19f8017
JF
1254 : 0;
1255
81030ec8
JF
1256 wprintw(view->title, " - %s %d of %d (%d%%)",
1257 view->ops->type,
1258 view->lineno + 1,
1259 view->lines,
c19f8017 1260 lines);
81030ec8
JF
1261 }
1262
f97f4012
JF
1263 if (view->pipe) {
1264 time_t secs = time(NULL) - view->start_time;
1265
1266 /* Three git seconds are a long time ... */
1267 if (secs > 2)
1268 wprintw(view->title, " %lds", secs);
1269 }
1270
976447f8 1271 wmove(view->title, 0, view->width - 1);
81030ec8
JF
1272 wrefresh(view->title);
1273}
1274
1275static void
6b161b31 1276resize_display(void)
b76c2afc 1277{
03a93dbb 1278 int offset, i;
6b161b31
JF
1279 struct view *base = display[0];
1280 struct view *view = display[1] ? display[1] : display[0];
b76c2afc 1281
6b161b31 1282 /* Setup window dimensions */
b76c2afc 1283
03a93dbb 1284 getmaxyx(stdscr, base->height, base->width);
b76c2afc 1285
6b161b31 1286 /* Make room for the status window. */
03a93dbb 1287 base->height -= 1;
6b161b31
JF
1288
1289 if (view != base) {
03a93dbb
JF
1290 /* Horizontal split. */
1291 view->width = base->width;
6b161b31
JF
1292 view->height = SCALE_SPLIT_VIEW(base->height);
1293 base->height -= view->height;
1294
1295 /* Make room for the title bar. */
1296 view->height -= 1;
1297 }
1298
1299 /* Make room for the title bar. */
1300 base->height -= 1;
1301
1302 offset = 0;
1303
1304 foreach_view (view, i) {
b76c2afc 1305 if (!view->win) {
c19f8017 1306 view->win = newwin(view->height, 0, offset, 0);
6b161b31
JF
1307 if (!view->win)
1308 die("Failed to create %s view", view->name);
1309
1310 scrollok(view->win, TRUE);
1311
1312 view->title = newwin(1, 0, offset + view->height, 0);
1313 if (!view->title)
1314 die("Failed to create title window");
1315
1316 } else {
c19f8017 1317 wresize(view->win, view->height, view->width);
6b161b31
JF
1318 mvwin(view->win, offset, 0);
1319 mvwin(view->title, offset + view->height, 0);
a28bcc22 1320 }
a28bcc22 1321
6b161b31 1322 offset += view->height + 1;
b76c2afc 1323 }
6b161b31 1324}
b76c2afc 1325
6b161b31 1326static void
20bb5e18
JF
1327redraw_display(void)
1328{
1329 struct view *view;
1330 int i;
1331
1332 foreach_view (view, i) {
1333 redraw_view(view);
1334 update_view_title(view);
1335 }
1336}
1337
85af6284
JF
1338static void
1339update_display_cursor(void)
1340{
1341 struct view *view = display[current_view];
1342
1343 /* Move the cursor to the right-most column of the cursor line.
1344 *
1345 * XXX: This could turn out to be a bit expensive, but it ensures that
1346 * the cursor does not jump around. */
1347 if (view->lines) {
1348 wmove(view->win, view->lineno - view->offset, view->width - 1);
1349 wrefresh(view->win);
1350 }
1351}
20bb5e18 1352
2e8488b4
JF
1353/*
1354 * Navigation
1355 */
1356
4a2909a7 1357/* Scrolling backend */
b801d8b2 1358static void
b3a54cba 1359do_scroll_view(struct view *view, int lines, bool redraw)
b801d8b2 1360{
fd85fef1
JF
1361 /* The rendering expects the new offset. */
1362 view->offset += lines;
1363
1364 assert(0 <= view->offset && view->offset < view->lines);
1365 assert(lines);
b801d8b2 1366
82e78006 1367 /* Redraw the whole screen if scrolling is pointless. */
4c6fabc2 1368 if (view->height < ABS(lines)) {
b76c2afc
JF
1369 redraw_view(view);
1370
1371 } else {
22f66b0a 1372 int line = lines > 0 ? view->height - lines : 0;
82e78006 1373 int end = line + ABS(lines);
fd85fef1
JF
1374
1375 wscrl(view->win, lines);
1376
22f66b0a 1377 for (; line < end; line++) {
fe7233c3 1378 if (!draw_view_line(view, line))
fd85fef1
JF
1379 break;
1380 }
1381 }
1382
1383 /* Move current line into the view. */
1384 if (view->lineno < view->offset) {
1385 view->lineno = view->offset;
fe7233c3 1386 draw_view_line(view, 0);
fd85fef1
JF
1387
1388 } else if (view->lineno >= view->offset + view->height) {
6706b2ba
JF
1389 if (view->lineno == view->offset + view->height) {
1390 /* Clear the hidden line so it doesn't show if the view
1391 * is scrolled up. */
1392 wmove(view->win, view->height, 0);
1393 wclrtoeol(view->win);
1394 }
fd85fef1 1395 view->lineno = view->offset + view->height - 1;
fe7233c3 1396 draw_view_line(view, view->lineno - view->offset);
fd85fef1
JF
1397 }
1398
4c6fabc2 1399 assert(view->offset <= view->lineno && view->lineno < view->lines);
fd85fef1 1400
b3a54cba
JF
1401 if (!redraw)
1402 return;
1403
fd85fef1
JF
1404 redrawwin(view->win);
1405 wrefresh(view->win);
9d3f5834 1406 report("");
fd85fef1 1407}
78c70acd 1408
4a2909a7 1409/* Scroll frontend */
fd85fef1 1410static void
6b161b31 1411scroll_view(struct view *view, enum request request)
fd85fef1
JF
1412{
1413 int lines = 1;
b801d8b2
JF
1414
1415 switch (request) {
4a2909a7 1416 case REQ_SCROLL_PAGE_DOWN:
fd85fef1 1417 lines = view->height;
4a2909a7 1418 case REQ_SCROLL_LINE_DOWN:
b801d8b2 1419 if (view->offset + lines > view->lines)
bde3653a 1420 lines = view->lines - view->offset;
b801d8b2 1421
fd85fef1 1422 if (lines == 0 || view->offset + view->height >= view->lines) {
eb98559e 1423 report("Cannot scroll beyond the last line");
b801d8b2
JF
1424 return;
1425 }
1426 break;
1427
4a2909a7 1428 case REQ_SCROLL_PAGE_UP:
fd85fef1 1429 lines = view->height;
4a2909a7 1430 case REQ_SCROLL_LINE_UP:
b801d8b2
JF
1431 if (lines > view->offset)
1432 lines = view->offset;
1433
1434 if (lines == 0) {
eb98559e 1435 report("Cannot scroll beyond the first line");
b801d8b2
JF
1436 return;
1437 }
1438
fd85fef1 1439 lines = -lines;
b801d8b2 1440 break;
03a93dbb 1441
6b161b31
JF
1442 default:
1443 die("request %d not handled in switch", request);
b801d8b2
JF
1444 }
1445
b3a54cba 1446 do_scroll_view(view, lines, TRUE);
fd85fef1 1447}
b801d8b2 1448
4a2909a7 1449/* Cursor moving */
fd85fef1 1450static void
b3a54cba 1451move_view(struct view *view, enum request request, bool redraw)
fd85fef1
JF
1452{
1453 int steps;
b801d8b2 1454
fd85fef1 1455 switch (request) {
4a2909a7 1456 case REQ_MOVE_FIRST_LINE:
78c70acd
JF
1457 steps = -view->lineno;
1458 break;
1459
4a2909a7 1460 case REQ_MOVE_LAST_LINE:
78c70acd
JF
1461 steps = view->lines - view->lineno - 1;
1462 break;
1463
4a2909a7 1464 case REQ_MOVE_PAGE_UP:
78c70acd
JF
1465 steps = view->height > view->lineno
1466 ? -view->lineno : -view->height;
1467 break;
1468
4a2909a7 1469 case REQ_MOVE_PAGE_DOWN:
78c70acd
JF
1470 steps = view->lineno + view->height >= view->lines
1471 ? view->lines - view->lineno - 1 : view->height;
1472 break;
1473
4a2909a7 1474 case REQ_MOVE_UP:
fd85fef1
JF
1475 steps = -1;
1476 break;
b801d8b2 1477
4a2909a7 1478 case REQ_MOVE_DOWN:
fd85fef1
JF
1479 steps = 1;
1480 break;
6b161b31
JF
1481
1482 default:
1483 die("request %d not handled in switch", request);
78c70acd 1484 }
b801d8b2 1485
4c6fabc2 1486 if (steps <= 0 && view->lineno == 0) {
eb98559e 1487 report("Cannot move beyond the first line");
78c70acd 1488 return;
b801d8b2 1489
6908bdbd 1490 } else if (steps >= 0 && view->lineno + 1 >= view->lines) {
eb98559e 1491 report("Cannot move beyond the last line");
78c70acd 1492 return;
fd85fef1
JF
1493 }
1494
4c6fabc2 1495 /* Move the current line */
fd85fef1 1496 view->lineno += steps;
4c6fabc2
JF
1497 assert(0 <= view->lineno && view->lineno < view->lines);
1498
1499 /* Repaint the old "current" line if we be scrolling */
2e8488b4
JF
1500 if (ABS(steps) < view->height) {
1501 int prev_lineno = view->lineno - steps - view->offset;
1502
1503 wmove(view->win, prev_lineno, 0);
1504 wclrtoeol(view->win);
fe7233c3 1505 draw_view_line(view, prev_lineno);
2e8488b4 1506 }
fd85fef1 1507
4c6fabc2 1508 /* Check whether the view needs to be scrolled */
fd85fef1
JF
1509 if (view->lineno < view->offset ||
1510 view->lineno >= view->offset + view->height) {
1511 if (steps < 0 && -steps > view->offset) {
1512 steps = -view->offset;
b76c2afc
JF
1513
1514 } else if (steps > 0) {
1515 if (view->lineno == view->lines - 1 &&
1516 view->lines > view->height) {
1517 steps = view->lines - view->offset - 1;
1518 if (steps >= view->height)
1519 steps -= view->height - 1;
1520 }
b801d8b2 1521 }
78c70acd 1522
b3a54cba 1523 do_scroll_view(view, steps, redraw);
fd85fef1 1524 return;
b801d8b2
JF
1525 }
1526
4c6fabc2 1527 /* Draw the current line */
fe7233c3 1528 draw_view_line(view, view->lineno - view->offset);
fd85fef1 1529
b3a54cba
JF
1530 if (!redraw)
1531 return;
1532
b801d8b2
JF
1533 redrawwin(view->win);
1534 wrefresh(view->win);
9d3f5834 1535 report("");
b801d8b2
JF
1536}
1537
b801d8b2 1538
2e8488b4
JF
1539/*
1540 * Incremental updating
1541 */
b801d8b2 1542
199d1288
JF
1543static void
1544end_update(struct view *view)
1545{
1546 if (!view->pipe)
1547 return;
1548 set_nonblocking_input(FALSE);
1549 if (view->pipe == stdin)
1550 fclose(view->pipe);
1551 else
1552 pclose(view->pipe);
1553 view->pipe = NULL;
1554}
1555
03a93dbb 1556static bool
b801d8b2
JF
1557begin_update(struct view *view)
1558{
4685845e 1559 const char *id = view->id;
fd85fef1 1560
199d1288
JF
1561 if (view->pipe)
1562 end_update(view);
1563
03a93dbb
JF
1564 if (opt_cmd[0]) {
1565 string_copy(view->cmd, opt_cmd);
1566 opt_cmd[0] = 0;
8855ada4
JF
1567 /* When running random commands, the view ref could have become
1568 * invalid so clear it. */
1569 view->ref[0] = 0;
03a93dbb 1570 } else {
4685845e 1571 const char *format = view->cmd_env ? view->cmd_env : view->cmd_fmt;
1ba2ae4b 1572
cc2d1364 1573 if (!string_format(view->cmd, format, id, id, id, id, id))
03a93dbb
JF
1574 return FALSE;
1575 }
b801d8b2 1576
6908bdbd
JF
1577 /* Special case for the pager view. */
1578 if (opt_pipe) {
1579 view->pipe = opt_pipe;
1580 opt_pipe = NULL;
1581 } else {
1582 view->pipe = popen(view->cmd, "r");
1583 }
1584
2e8488b4
JF
1585 if (!view->pipe)
1586 return FALSE;
b801d8b2 1587
6b161b31 1588 set_nonblocking_input(TRUE);
b801d8b2
JF
1589
1590 view->offset = 0;
1591 view->lines = 0;
1592 view->lineno = 0;
49f2b43f 1593 string_copy(view->vid, id);
b801d8b2 1594
2e8488b4
JF
1595 if (view->line) {
1596 int i;
1597
1598 for (i = 0; i < view->lines; i++)
fe7233c3
JF
1599 if (view->line[i].data)
1600 free(view->line[i].data);
2e8488b4
JF
1601
1602 free(view->line);
1603 view->line = NULL;
1604 }
1605
1606 view->start_time = time(NULL);
1607
b801d8b2
JF
1608 return TRUE;
1609}
1610
e2c01617
JF
1611static struct line *
1612realloc_lines(struct view *view, size_t line_size)
1613{
1614 struct line *tmp = realloc(view->line, sizeof(*view->line) * line_size);
1615
1616 if (!tmp)
1617 return NULL;
1618
1619 view->line = tmp;
1620 view->line_size = line_size;
1621 return view->line;
1622}
1623
03a93dbb 1624static bool
b801d8b2
JF
1625update_view(struct view *view)
1626{
6b68fd24
JF
1627 char in_buffer[BUFSIZ];
1628 char out_buffer[BUFSIZ * 2];
b801d8b2 1629 char *line;
82e78006
JF
1630 /* The number of lines to read. If too low it will cause too much
1631 * redrawing (and possible flickering), if too high responsiveness
1632 * will suffer. */
8855ada4 1633 unsigned long lines = view->height;
82e78006 1634 int redraw_from = -1;
b801d8b2
JF
1635
1636 if (!view->pipe)
1637 return TRUE;
1638
82e78006
JF
1639 /* Only redraw if lines are visible. */
1640 if (view->offset + view->height >= view->lines)
1641 redraw_from = view->lines - view->offset;
b801d8b2 1642
e2c01617 1643 if (!realloc_lines(view, view->lines + lines))
b801d8b2
JF
1644 goto alloc_error;
1645
6b68fd24
JF
1646 while ((line = fgets(in_buffer, sizeof(in_buffer), view->pipe))) {
1647 size_t linelen = strlen(line);
b801d8b2 1648
b801d8b2
JF
1649 if (linelen)
1650 line[linelen - 1] = 0;
1651
6b68fd24
JF
1652 if (opt_iconv != ICONV_NONE) {
1653 char *inbuf = line;
1654 size_t inlen = linelen;
1655
1656 char *outbuf = out_buffer;
1657 size_t outlen = sizeof(out_buffer);
1658
1659 size_t ret;
1660
1661 ret = iconv(opt_iconv, &inbuf, &inlen, &outbuf, &outlen);
1662 if (ret != (size_t) -1) {
1663 line = out_buffer;
1664 linelen = strlen(out_buffer);
1665 }
1666 }
1667
701e4f5d 1668 if (!view->ops->read(view, line))
b801d8b2 1669 goto alloc_error;
fd85fef1
JF
1670
1671 if (lines-- == 1)
1672 break;
b801d8b2
JF
1673 }
1674
8855ada4
JF
1675 {
1676 int digits;
1677
1678 lines = view->lines;
1679 for (digits = 0; lines; digits++)
1680 lines /= 10;
1681
1682 /* Keep the displayed view in sync with line number scaling. */
1683 if (digits != view->digits) {
1684 view->digits = digits;
1685 redraw_from = 0;
1686 }
1687 }
1688
82e78006
JF
1689 if (redraw_from >= 0) {
1690 /* If this is an incremental update, redraw the previous line
a28bcc22
JF
1691 * since for commits some members could have changed when
1692 * loading the main view. */
82e78006
JF
1693 if (redraw_from > 0)
1694 redraw_from--;
1695
1696 /* Incrementally draw avoids flickering. */
1697 redraw_view_from(view, redraw_from);
4c6fabc2 1698 }
b801d8b2 1699
eb98559e
JF
1700 /* Update the title _after_ the redraw so that if the redraw picks up a
1701 * commit reference in view->ref it'll be available here. */
1702 update_view_title(view);
1703
b801d8b2 1704 if (ferror(view->pipe)) {
03a93dbb 1705 report("Failed to read: %s", strerror(errno));
b801d8b2
JF
1706 goto end;
1707
1708 } else if (feof(view->pipe)) {
f97f4012 1709 report("");
b801d8b2
JF
1710 goto end;
1711 }
1712
1713 return TRUE;
1714
1715alloc_error:
2e8488b4 1716 report("Allocation failure");
b801d8b2
JF
1717
1718end:
1719 end_update(view);
1720 return FALSE;
1721}
1722
79d445ca 1723
e10154d5
JF
1724/*
1725 * View opening
1726 */
1727
79d445ca
JF
1728static void open_help_view(struct view *view)
1729{
1730 char buf[BUFSIZ];
1731 int lines = ARRAY_SIZE(req_info) + 2;
1732 int i;
1733
1734 if (view->lines > 0)
1735 return;
1736
1737 for (i = 0; i < ARRAY_SIZE(req_info); i++)
1738 if (!req_info[i].request)
1739 lines++;
1740
1741 view->line = calloc(lines, sizeof(*view->line));
1742 if (!view->line) {
1743 report("Allocation failure");
1744 return;
1745 }
1746
1747 view->ops->read(view, "Quick reference for tig keybindings:");
1748
1749 for (i = 0; i < ARRAY_SIZE(req_info); i++) {
1750 char *key;
1751
1752 if (!req_info[i].request) {
1753 view->ops->read(view, "");
1754 view->ops->read(view, req_info[i].help);
1755 continue;
1756 }
1757
1758 key = get_key(req_info[i].request);
1759 if (!string_format(buf, "%-25s %s", key, req_info[i].help))
1760 continue;
1761
1762 view->ops->read(view, buf);
1763 }
1764}
1765
49f2b43f
JF
1766enum open_flags {
1767 OPEN_DEFAULT = 0, /* Use default view switching. */
1768 OPEN_SPLIT = 1, /* Split current view. */
1769 OPEN_BACKGROUNDED = 2, /* Backgrounded. */
1770 OPEN_RELOAD = 4, /* Reload view even if it is the current. */
1771};
1772
6b161b31 1773static void
49f2b43f 1774open_view(struct view *prev, enum request request, enum open_flags flags)
b801d8b2 1775{
49f2b43f
JF
1776 bool backgrounded = !!(flags & OPEN_BACKGROUNDED);
1777 bool split = !!(flags & OPEN_SPLIT);
1778 bool reload = !!(flags & OPEN_RELOAD);
a28bcc22 1779 struct view *view = VIEW(request);
9f41488f 1780 int nviews = displayed_views();
6e950a52 1781 struct view *base_view = display[0];
b801d8b2 1782
49f2b43f 1783 if (view == prev && nviews == 1 && !reload) {
6b161b31
JF
1784 report("Already in %s view", view->name);
1785 return;
1786 }
b801d8b2 1787
2509b112 1788 if (view == VIEW(REQ_VIEW_HELP)) {
79d445ca 1789 open_help_view(view);
2509b112
JF
1790
1791 } else if ((reload || strcmp(view->vid, view->id)) &&
1792 !begin_update(view)) {
6b161b31
JF
1793 report("Failed to load %s view", view->name);
1794 return;
1795 }
a28bcc22 1796
6b161b31 1797 if (split) {
8d741c06 1798 display[1] = view;
6b161b31 1799 if (!backgrounded)
8d741c06 1800 current_view = 1;
6b161b31
JF
1801 } else {
1802 /* Maximize the current view. */
1803 memset(display, 0, sizeof(display));
1804 current_view = 0;
1805 display[current_view] = view;
a28bcc22 1806 }
b801d8b2 1807
6e950a52
JF
1808 /* Resize the view when switching between split- and full-screen,
1809 * or when switching between two different full-screen views. */
1810 if (nviews != displayed_views() ||
1811 (nviews == 1 && base_view != display[0]))
a006db63 1812 resize_display();
b801d8b2 1813
a8891802 1814 if (split && prev->lineno - prev->offset >= prev->height) {
03a93dbb 1815 /* Take the title line into account. */
eb98559e 1816 int lines = prev->lineno - prev->offset - prev->height + 1;
03a93dbb
JF
1817
1818 /* Scroll the view that was split if the current line is
1819 * outside the new limited view. */
b3a54cba 1820 do_scroll_view(prev, lines, TRUE);
03a93dbb
JF
1821 }
1822
6b161b31 1823 if (prev && view != prev) {
9b995f0c 1824 if (split && !backgrounded) {
f0b3ab80
JF
1825 /* "Blur" the previous view. */
1826 update_view_title(prev);
9f396969 1827 }
f0b3ab80 1828
f6da0b66 1829 view->parent = prev;
b801d8b2
JF
1830 }
1831
9f396969 1832 if (view->pipe && view->lines == 0) {
03a93dbb
JF
1833 /* Clear the old view and let the incremental updating refill
1834 * the screen. */
1835 wclear(view->win);
f97f4012 1836 report("");
03a93dbb
JF
1837 } else {
1838 redraw_view(view);
24b5b3e0 1839 report("");
03a93dbb 1840 }
6706b2ba
JF
1841
1842 /* If the view is backgrounded the above calls to report()
1843 * won't redraw the view title. */
1844 if (backgrounded)
1845 update_view_title(view);
b801d8b2
JF
1846}
1847
1848
6b161b31
JF
1849/*
1850 * User request switch noodle
1851 */
1852
b801d8b2 1853static int
6b161b31 1854view_driver(struct view *view, enum request request)
b801d8b2 1855{
b801d8b2
JF
1856 int i;
1857
1858 switch (request) {
4a2909a7
JF
1859 case REQ_MOVE_UP:
1860 case REQ_MOVE_DOWN:
1861 case REQ_MOVE_PAGE_UP:
1862 case REQ_MOVE_PAGE_DOWN:
1863 case REQ_MOVE_FIRST_LINE:
1864 case REQ_MOVE_LAST_LINE:
b3a54cba 1865 move_view(view, request, TRUE);
fd85fef1
JF
1866 break;
1867
4a2909a7
JF
1868 case REQ_SCROLL_LINE_DOWN:
1869 case REQ_SCROLL_LINE_UP:
1870 case REQ_SCROLL_PAGE_DOWN:
1871 case REQ_SCROLL_PAGE_UP:
a28bcc22 1872 scroll_view(view, request);
b801d8b2
JF
1873 break;
1874
4a2909a7 1875 case REQ_VIEW_MAIN:
4a2909a7 1876 case REQ_VIEW_DIFF:
2e8488b4
JF
1877 case REQ_VIEW_LOG:
1878 case REQ_VIEW_HELP:
6908bdbd 1879 case REQ_VIEW_PAGER:
49f2b43f 1880 open_view(view, request, OPEN_DEFAULT);
b801d8b2
JF
1881 break;
1882
b3a54cba
JF
1883 case REQ_NEXT:
1884 case REQ_PREVIOUS:
1885 request = request == REQ_NEXT ? REQ_MOVE_DOWN : REQ_MOVE_UP;
1886
1887 if (view == VIEW(REQ_VIEW_DIFF) &&
1888 view->parent == VIEW(REQ_VIEW_MAIN)) {
f0b3ab80 1889 bool redraw = display[1] == view;
b3a54cba
JF
1890
1891 view = view->parent;
1892 move_view(view, request, redraw);
f0b3ab80
JF
1893 if (redraw)
1894 update_view_title(view);
b3a54cba
JF
1895 } else {
1896 move_view(view, request, TRUE);
1897 break;
1898 }
6706b2ba
JF
1899 /* Fall-through */
1900
6b161b31 1901 case REQ_ENTER:
6908bdbd
JF
1902 if (!view->lines) {
1903 report("Nothing to enter");
1904 break;
1905 }
fe7233c3 1906 return view->ops->enter(view, &view->line[view->lineno]);
6b161b31 1907
03a93dbb
JF
1908 case REQ_VIEW_NEXT:
1909 {
9f41488f 1910 int nviews = displayed_views();
03a93dbb
JF
1911 int next_view = (current_view + 1) % nviews;
1912
1913 if (next_view == current_view) {
1914 report("Only one view is displayed");
1915 break;
1916 }
1917
1918 current_view = next_view;
1919 /* Blur out the title of the previous view. */
1920 update_view_title(view);
6734f6b9 1921 report("");
03a93dbb
JF
1922 break;
1923 }
24b5b3e0 1924 case REQ_TOGGLE_LINENO:
b76c2afc 1925 opt_line_number = !opt_line_number;
20bb5e18 1926 redraw_display();
b801d8b2
JF
1927 break;
1928
54efb62b
JF
1929 case REQ_TOGGLE_REV_GRAPH:
1930 opt_rev_graph = !opt_rev_graph;
1931 redraw_display();
1932 break;
1933
03a93dbb 1934 case REQ_PROMPT:
8855ada4 1935 /* Always reload^Wrerun commands from the prompt. */
49f2b43f 1936 open_view(view, opt_request, OPEN_RELOAD);
03a93dbb
JF
1937 break;
1938
4a2909a7 1939 case REQ_STOP_LOADING:
59a45d3a
JF
1940 for (i = 0; i < ARRAY_SIZE(views); i++) {
1941 view = &views[i];
2e8488b4 1942 if (view->pipe)
6a7bb912 1943 report("Stopped loading the %s view", view->name),
03a93dbb
JF
1944 end_update(view);
1945 }
b801d8b2
JF
1946 break;
1947
4a2909a7 1948 case REQ_SHOW_VERSION:
6cb291b7 1949 report("%s (built %s)", VERSION, __DATE__);
b801d8b2
JF
1950 return TRUE;
1951
fac7db6c
JF
1952 case REQ_SCREEN_RESIZE:
1953 resize_display();
1954 /* Fall-through */
4a2909a7 1955 case REQ_SCREEN_REDRAW:
20bb5e18 1956 redraw_display();
4a2909a7
JF
1957 break;
1958
1959 case REQ_SCREEN_UPDATE:
b801d8b2
JF
1960 doupdate();
1961 return TRUE;
1962
4f9b667a 1963 case REQ_VIEW_CLOSE:
2fcf5401
JF
1964 /* XXX: Mark closed views by letting view->parent point to the
1965 * view itself. Parents to closed view should never be
1966 * followed. */
1967 if (view->parent &&
1968 view->parent->parent != view->parent) {
4f9b667a
JF
1969 memset(display, 0, sizeof(display));
1970 current_view = 0;
f6da0b66 1971 display[current_view] = view->parent;
2fcf5401 1972 view->parent = view;
4f9b667a
JF
1973 resize_display();
1974 redraw_display();
1975 break;
1976 }
1977 /* Fall-through */
b801d8b2
JF
1978 case REQ_QUIT:
1979 return FALSE;
1980
1981 default:
2e8488b4 1982 /* An unknown key will show most commonly used commands. */
468876c9 1983 report("Unknown key, press 'h' for help");
b801d8b2
JF
1984 return TRUE;
1985 }
1986
1987 return TRUE;
1988}
1989
1990
1991/*
ff26aa29 1992 * Pager backend
b801d8b2
JF
1993 */
1994
6b161b31 1995static bool
fe7233c3 1996pager_draw(struct view *view, struct line *line, unsigned int lineno)
b801d8b2 1997{
fe7233c3
JF
1998 char *text = line->data;
1999 enum line_type type = line->type;
2000 int textlen = strlen(text);
78c70acd 2001 int attr;
b801d8b2 2002
6706b2ba
JF
2003 wmove(view->win, lineno, 0);
2004
fd85fef1 2005 if (view->offset + lineno == view->lineno) {
8855ada4 2006 if (type == LINE_COMMIT) {
fe7233c3 2007 string_copy(view->ref, text + 7);
03a93dbb
JF
2008 string_copy(ref_commit, view->ref);
2009 }
8855ada4 2010
78c70acd 2011 type = LINE_CURSOR;
6706b2ba 2012 wchgat(view->win, -1, 0, type, NULL);
fd85fef1
JF
2013 }
2014
78c70acd 2015 attr = get_line_attr(type);
b801d8b2 2016 wattrset(view->win, attr);
b76c2afc 2017
6706b2ba
JF
2018 if (opt_line_number || opt_tab_size < TABSIZE) {
2019 static char spaces[] = " ";
2020 int col_offset = 0, col = 0;
2021
2022 if (opt_line_number) {
2023 unsigned long real_lineno = view->offset + lineno + 1;
82e78006 2024
6706b2ba
JF
2025 if (real_lineno == 1 ||
2026 (real_lineno % opt_num_interval) == 0) {
2027 wprintw(view->win, "%.*d", view->digits, real_lineno);
8855ada4 2028
6706b2ba
JF
2029 } else {
2030 waddnstr(view->win, spaces,
2031 MIN(view->digits, STRING_SIZE(spaces)));
2032 }
2033 waddstr(view->win, ": ");
2034 col_offset = view->digits + 2;
2035 }
8855ada4 2036
fe7233c3 2037 while (text && col_offset + col < view->width) {
6706b2ba 2038 int cols_max = view->width - col_offset - col;
fe7233c3 2039 char *pos = text;
6706b2ba 2040 int cols;
4c6fabc2 2041
fe7233c3
JF
2042 if (*text == '\t') {
2043 text++;
6706b2ba 2044 assert(sizeof(spaces) > TABSIZE);
fe7233c3 2045 pos = spaces;
6706b2ba 2046 cols = opt_tab_size - (col % opt_tab_size);
82e78006 2047
b76c2afc 2048 } else {
fe7233c3
JF
2049 text = strchr(text, '\t');
2050 cols = line ? text - pos : strlen(pos);
b76c2afc 2051 }
6706b2ba 2052
fe7233c3 2053 waddnstr(view->win, pos, MIN(cols, cols_max));
6706b2ba 2054 col += cols;
b76c2afc 2055 }
b76c2afc
JF
2056
2057 } else {
6706b2ba 2058 int col = 0, pos = 0;
b801d8b2 2059
fe7233c3
JF
2060 for (; pos < textlen && col < view->width; pos++, col++)
2061 if (text[pos] == '\t')
6706b2ba
JF
2062 col += TABSIZE - (col % TABSIZE) - 1;
2063
fe7233c3 2064 waddnstr(view->win, text, pos);
6706b2ba 2065 }
2e8488b4 2066
b801d8b2
JF
2067 return TRUE;
2068}
2069
dc23c0e3
JF
2070static bool
2071add_describe_ref(char *buf, int *bufpos, char *commit_id, const char *sep)
2072{
17482b11 2073 char refbuf[SIZEOF_STR];
dc23c0e3
JF
2074 char *ref = NULL;
2075 FILE *pipe;
2076
2077 if (!string_format(refbuf, "git describe %s", commit_id))
2078 return TRUE;
2079
2080 pipe = popen(refbuf, "r");
2081 if (!pipe)
2082 return TRUE;
2083
2084 if ((ref = fgets(refbuf, sizeof(refbuf), pipe)))
2085 ref = chomp_string(ref);
2086 pclose(pipe);
2087
2088 if (!ref || !*ref)
2089 return TRUE;
2090
2091 /* This is the only fatal call, since it can "corrupt" the buffer. */
17482b11 2092 if (!string_nformat(buf, SIZEOF_STR, bufpos, "%s%s", sep, ref))
dc23c0e3
JF
2093 return FALSE;
2094
2095 return TRUE;
2096}
2097
7b99a34c
JF
2098static void
2099add_pager_refs(struct view *view, struct line *line)
2100{
17482b11 2101 char buf[SIZEOF_STR];
c9ca1ec3 2102 char *commit_id = line->data + STRING_SIZE("commit ");
7b99a34c
JF
2103 struct ref **refs;
2104 int bufpos = 0, refpos = 0;
2105 const char *sep = "Refs: ";
dc23c0e3 2106 bool is_tag = FALSE;
7b99a34c
JF
2107
2108 assert(line->type == LINE_COMMIT);
2109
c9ca1ec3 2110 refs = get_refs(commit_id);
dc23c0e3
JF
2111 if (!refs) {
2112 if (view == VIEW(REQ_VIEW_DIFF))
2113 goto try_add_describe_ref;
7b99a34c 2114 return;
dc23c0e3 2115 }
7b99a34c
JF
2116
2117 do {
cc2d1364
JF
2118 struct ref *ref = refs[refpos];
2119 char *fmt = ref->tag ? "%s[%s]" : "%s%s";
7b99a34c 2120
cc2d1364
JF
2121 if (!string_format_from(buf, &bufpos, fmt, sep, ref->name))
2122 return;
7b99a34c 2123 sep = ", ";
dc23c0e3
JF
2124 if (ref->tag)
2125 is_tag = TRUE;
7b99a34c
JF
2126 } while (refs[refpos++]->next);
2127
dc23c0e3
JF
2128 if (!is_tag && view == VIEW(REQ_VIEW_DIFF)) {
2129try_add_describe_ref:
2130 if (!add_describe_ref(buf, &bufpos, commit_id, sep))
2131 return;
2132 }
2133
cc2d1364 2134 if (!realloc_lines(view, view->line_size + 1))
7b99a34c
JF
2135 return;
2136
2137 line = &view->line[view->lines];
2138 line->data = strdup(buf);
2139 if (!line->data)
2140 return;
2141
2142 line->type = LINE_PP_REFS;
2143 view->lines++;
2144}
2145
6b161b31 2146static bool
701e4f5d 2147pager_read(struct view *view, char *data)
22f66b0a 2148{
7b99a34c 2149 struct line *line = &view->line[view->lines];
22f66b0a 2150
7b99a34c
JF
2151 line->data = strdup(data);
2152 if (!line->data)
2153 return FALSE;
fe7233c3 2154
7b99a34c 2155 line->type = get_line_type(line->data);
22f66b0a 2156 view->lines++;
7b99a34c
JF
2157
2158 if (line->type == LINE_COMMIT &&
2159 (view == VIEW(REQ_VIEW_DIFF) ||
2160 view == VIEW(REQ_VIEW_LOG)))
2161 add_pager_refs(view, line);
2162
22f66b0a
JF
2163 return TRUE;
2164}
2165
6b161b31 2166static bool
fe7233c3 2167pager_enter(struct view *view, struct line *line)
6b161b31 2168{
91e8e277 2169 int split = 0;
6b161b31 2170
9fbbd28f
JF
2171 if (line->type == LINE_COMMIT &&
2172 (view == VIEW(REQ_VIEW_LOG) ||
2173 view == VIEW(REQ_VIEW_PAGER))) {
91e8e277
JF
2174 open_view(view, REQ_VIEW_DIFF, OPEN_SPLIT);
2175 split = 1;
67e48ac5
JF
2176 }
2177
91e8e277
JF
2178 /* Always scroll the view even if it was split. That way
2179 * you can use Enter to scroll through the log view and
2180 * split open each commit diff. */
2181 scroll_view(view, REQ_SCROLL_LINE_DOWN);
2182
2183 /* FIXME: A minor workaround. Scrolling the view will call report("")
9d82d824
JF
2184 * but if we are scrolling a non-current view this won't properly
2185 * update the view title. */
91e8e277
JF
2186 if (split)
2187 update_view_title(view);
6b161b31
JF
2188
2189 return TRUE;
2190}
2191
6b161b31 2192static struct view_ops pager_ops = {
6734f6b9 2193 "line",
6b161b31
JF
2194 pager_draw,
2195 pager_read,
2196 pager_enter,
2197};
2198
80ce96ea 2199
ff26aa29
JF
2200/*
2201 * Main view backend
2202 */
2203
2204struct commit {
54efb62b
JF
2205 char id[41]; /* SHA1 ID. */
2206 char title[75]; /* First line of the commit message. */
2207 char author[75]; /* Author of the commit. */
2208 struct tm time; /* Date from the author ident. */
2209 struct ref **refs; /* Repository references. */
2210 chtype graph[SIZEOF_REVGRAPH]; /* Ancestry chain graphics. */
2211 size_t graph_size; /* The width of the graph array. */
ff26aa29 2212};
c34d9c9f 2213
6b161b31 2214static bool
fe7233c3 2215main_draw(struct view *view, struct line *line, unsigned int lineno)
22f66b0a 2216{
2e8488b4 2217 char buf[DATE_COLS + 1];
fe7233c3 2218 struct commit *commit = line->data;
78c70acd 2219 enum line_type type;
6706b2ba 2220 int col = 0;
b76c2afc 2221 size_t timelen;
10e290ee 2222 size_t authorlen;
9989bf60 2223 int trimmed = 1;
22f66b0a 2224
4c6fabc2
JF
2225 if (!*commit->author)
2226 return FALSE;
22f66b0a 2227
6706b2ba
JF
2228 wmove(view->win, lineno, col);
2229
22f66b0a 2230 if (view->offset + lineno == view->lineno) {
03a93dbb 2231 string_copy(view->ref, commit->id);
49f2b43f 2232 string_copy(ref_commit, view->ref);
78c70acd 2233 type = LINE_CURSOR;
6706b2ba
JF
2234 wattrset(view->win, get_line_attr(type));
2235 wchgat(view->win, -1, 0, type, NULL);
2236
78c70acd 2237 } else {
b76c2afc 2238 type = LINE_MAIN_COMMIT;
6706b2ba 2239 wattrset(view->win, get_line_attr(LINE_MAIN_DATE));
b76c2afc
JF
2240 }
2241
4c6fabc2 2242 timelen = strftime(buf, sizeof(buf), DATE_FORMAT, &commit->time);
b76c2afc 2243 waddnstr(view->win, buf, timelen);
4c6fabc2 2244 waddstr(view->win, " ");
b76c2afc 2245
6706b2ba
JF
2246 col += DATE_COLS;
2247 wmove(view->win, lineno, col);
2248 if (type != LINE_CURSOR)
2249 wattrset(view->win, get_line_attr(LINE_MAIN_AUTHOR));
b76c2afc 2250
9989bf60
JF
2251 if (opt_utf8) {
2252 authorlen = utf8_length(commit->author, AUTHOR_COLS - 2, &col, &trimmed);
2253 } else {
2254 authorlen = strlen(commit->author);
2255 if (authorlen > AUTHOR_COLS - 2) {
2256 authorlen = AUTHOR_COLS - 2;
2257 trimmed = 1;
2258 }
2259 }
10e290ee
JF
2260
2261 if (trimmed) {
2262 waddnstr(view->win, commit->author, authorlen);
6706b2ba
JF
2263 if (type != LINE_CURSOR)
2264 wattrset(view->win, get_line_attr(LINE_MAIN_DELIM));
b76c2afc
JF
2265 waddch(view->win, '~');
2266 } else {
2267 waddstr(view->win, commit->author);
22f66b0a
JF
2268 }
2269
10e290ee 2270 col += AUTHOR_COLS;
6706b2ba
JF
2271 if (type != LINE_CURSOR)
2272 wattrset(view->win, A_NORMAL);
2273
54efb62b
JF
2274 if (opt_rev_graph && commit->graph_size) {
2275 size_t i;
2276
2277 wmove(view->win, lineno, col);
2278 /* Using waddch() instead of waddnstr() ensures that
2279 * they'll be rendered correctly for the cursor line. */
2280 for (i = 0; i < commit->graph_size; i++)
2281 waddch(view->win, commit->graph[i]);
2282
2283 col += commit->graph_size + 1;
2284 }
2285
2286 wmove(view->win, lineno, col);
c34d9c9f
JF
2287
2288 if (commit->refs) {
2289 size_t i = 0;
2290
2291 do {
6706b2ba
JF
2292 if (type == LINE_CURSOR)
2293 ;
2294 else if (commit->refs[i]->tag)
c34d9c9f
JF
2295 wattrset(view->win, get_line_attr(LINE_MAIN_TAG));
2296 else
2297 wattrset(view->win, get_line_attr(LINE_MAIN_REF));
2298 waddstr(view->win, "[");
2299 waddstr(view->win, commit->refs[i]->name);
2300 waddstr(view->win, "]");
6706b2ba
JF
2301 if (type != LINE_CURSOR)
2302 wattrset(view->win, A_NORMAL);
c34d9c9f 2303 waddstr(view->win, " ");
6706b2ba 2304 col += strlen(commit->refs[i]->name) + STRING_SIZE("[] ");
c34d9c9f
JF
2305 } while (commit->refs[i++]->next);
2306 }
2307
6706b2ba
JF
2308 if (type != LINE_CURSOR)
2309 wattrset(view->win, get_line_attr(type));
2310
2311 {
2312 int titlelen = strlen(commit->title);
2313
2314 if (col + titlelen > view->width)
2315 titlelen = view->width - col;
2316
2317 waddnstr(view->win, commit->title, titlelen);
2318 }
22f66b0a
JF
2319
2320 return TRUE;
2321}
2322
4c6fabc2 2323/* Reads git log --pretty=raw output and parses it into the commit struct. */
6b161b31 2324static bool
701e4f5d 2325main_read(struct view *view, char *line)
22f66b0a 2326{
78c70acd 2327 enum line_type type = get_line_type(line);
701e4f5d
JF
2328 struct commit *commit = view->lines
2329 ? view->line[view->lines - 1].data : NULL;
22f66b0a 2330
78c70acd
JF
2331 switch (type) {
2332 case LINE_COMMIT:
22f66b0a
JF
2333 commit = calloc(1, sizeof(struct commit));
2334 if (!commit)
2335 return FALSE;
2336
4c6fabc2 2337 line += STRING_SIZE("commit ");
b76c2afc 2338
fe7233c3 2339 view->line[view->lines++].data = commit;
82e78006 2340 string_copy(commit->id, line);
c34d9c9f 2341 commit->refs = get_refs(commit->id);
54efb62b 2342 commit->graph[commit->graph_size++] = ACS_LTEE;
78c70acd 2343 break;
22f66b0a 2344
8855ada4 2345 case LINE_AUTHOR:
b76c2afc 2346 {
4c6fabc2 2347 char *ident = line + STRING_SIZE("author ");
b76c2afc
JF
2348 char *end = strchr(ident, '<');
2349
701e4f5d 2350 if (!commit)
fe7233c3
JF
2351 break;
2352
b76c2afc 2353 if (end) {
cbbf2d1b
JF
2354 char *email = end + 1;
2355
b76c2afc 2356 for (; end > ident && isspace(end[-1]); end--) ;
cbbf2d1b
JF
2357
2358 if (end == ident && *email) {
2359 ident = email;
2360 end = strchr(ident, '>');
2361 for (; end > ident && isspace(end[-1]); end--) ;
2362 }
b76c2afc
JF
2363 *end = 0;
2364 }
2365
cbbf2d1b
JF
2366 /* End is NULL or ident meaning there's no author. */
2367 if (end <= ident)
2368 ident = "Unknown";
2369
82e78006 2370 string_copy(commit->author, ident);
b76c2afc 2371
4c6fabc2 2372 /* Parse epoch and timezone */
b76c2afc
JF
2373 if (end) {
2374 char *secs = strchr(end + 1, '>');
2375 char *zone;
2376 time_t time;
2377
2378 if (!secs || secs[1] != ' ')
2379 break;
2380
2381 secs += 2;
2382 time = (time_t) atol(secs);
2383 zone = strchr(secs, ' ');
4c6fabc2 2384 if (zone && strlen(zone) == STRING_SIZE(" +0700")) {
b76c2afc
JF
2385 long tz;
2386
2387 zone++;
2388 tz = ('0' - zone[1]) * 60 * 60 * 10;
2389 tz += ('0' - zone[2]) * 60 * 60;
2390 tz += ('0' - zone[3]) * 60;
2391 tz += ('0' - zone[4]) * 60;
2392
2393 if (zone[0] == '-')
2394 tz = -tz;
2395
2396 time -= tz;
2397 }
2398 gmtime_r(&time, &commit->time);
2399 }
2400 break;
2401 }
78c70acd 2402 default:
701e4f5d 2403 if (!commit)
2e8488b4
JF
2404 break;
2405
2406 /* Fill in the commit title if it has not already been set. */
2e8488b4
JF
2407 if (commit->title[0])
2408 break;
2409
2410 /* Require titles to start with a non-space character at the
2411 * offset used by git log. */
eb98559e
JF
2412 /* FIXME: More gracefull handling of titles; append "..." to
2413 * shortened titles, etc. */
2e8488b4 2414 if (strncmp(line, " ", 4) ||
eb98559e 2415 isspace(line[4]))
82e78006
JF
2416 break;
2417
2418 string_copy(commit->title, line + 4);
22f66b0a
JF
2419 }
2420
2421 return TRUE;
2422}
2423
6b161b31 2424static bool
fe7233c3 2425main_enter(struct view *view, struct line *line)
b801d8b2 2426{
b3a54cba
JF
2427 enum open_flags flags = display[0] == view ? OPEN_SPLIT : OPEN_DEFAULT;
2428
2429 open_view(view, REQ_VIEW_DIFF, flags);
6b161b31 2430 return TRUE;
b801d8b2
JF
2431}
2432
6b161b31 2433static struct view_ops main_ops = {
6734f6b9 2434 "commit",
6b161b31
JF
2435 main_draw,
2436 main_read,
2437 main_enter,
2438};
2e8488b4 2439
c34d9c9f 2440
6b161b31 2441/*
10e290ee
JF
2442 * Unicode / UTF-8 handling
2443 *
2444 * NOTE: Much of the following code for dealing with unicode is derived from
2445 * ELinks' UTF-8 code developed by Scrool <scroolik@gmail.com>. Origin file is
2446 * src/intl/charset.c from the utf8 branch commit elinks-0.11.0-g31f2c28.
2447 */
2448
2449/* I've (over)annotated a lot of code snippets because I am not entirely
2450 * confident that the approach taken by this small UTF-8 interface is correct.
2451 * --jonas */
2452
2453static inline int
2454unicode_width(unsigned long c)
2455{
2456 if (c >= 0x1100 &&
2457 (c <= 0x115f /* Hangul Jamo */
2458 || c == 0x2329
2459 || c == 0x232a
2460 || (c >= 0x2e80 && c <= 0xa4cf && c != 0x303f)
f97f4012 2461 /* CJK ... Yi */
10e290ee
JF
2462 || (c >= 0xac00 && c <= 0xd7a3) /* Hangul Syllables */
2463 || (c >= 0xf900 && c <= 0xfaff) /* CJK Compatibility Ideographs */
2464 || (c >= 0xfe30 && c <= 0xfe6f) /* CJK Compatibility Forms */
2465 || (c >= 0xff00 && c <= 0xff60) /* Fullwidth Forms */
2466 || (c >= 0xffe0 && c <= 0xffe6)
2467 || (c >= 0x20000 && c <= 0x2fffd)
2468 || (c >= 0x30000 && c <= 0x3fffd)))
2469 return 2;
2470
2471 return 1;
2472}
2473
2474/* Number of bytes used for encoding a UTF-8 character indexed by first byte.
2475 * Illegal bytes are set one. */
2476static const unsigned char utf8_bytes[256] = {
2477 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,
2478 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,
2479 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,
2480 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,
2481 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,
2482 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,
2483 2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,
2484 3,3,3,3,3,3,3,3, 3,3,3,3,3,3,3,3, 4,4,4,4,4,4,4,4, 5,5,5,5,6,6,1,1,
2485};
2486
2487/* Decode UTF-8 multi-byte representation into a unicode character. */
2488static inline unsigned long
2489utf8_to_unicode(const char *string, size_t length)
2490{
2491 unsigned long unicode;
2492
2493 switch (length) {
2494 case 1:
2495 unicode = string[0];
2496 break;
2497 case 2:
2498 unicode = (string[0] & 0x1f) << 6;
2499 unicode += (string[1] & 0x3f);
2500 break;
2501 case 3:
2502 unicode = (string[0] & 0x0f) << 12;
2503 unicode += ((string[1] & 0x3f) << 6);
2504 unicode += (string[2] & 0x3f);
2505 break;
2506 case 4:
2507 unicode = (string[0] & 0x0f) << 18;
2508 unicode += ((string[1] & 0x3f) << 12);
2509 unicode += ((string[2] & 0x3f) << 6);
2510 unicode += (string[3] & 0x3f);
2511 break;
2512 case 5:
2513 unicode = (string[0] & 0x0f) << 24;
2514 unicode += ((string[1] & 0x3f) << 18);
2515 unicode += ((string[2] & 0x3f) << 12);
2516 unicode += ((string[3] & 0x3f) << 6);
2517 unicode += (string[4] & 0x3f);
2518 break;
68b6e0eb 2519 case 6:
10e290ee
JF
2520 unicode = (string[0] & 0x01) << 30;
2521 unicode += ((string[1] & 0x3f) << 24);
2522 unicode += ((string[2] & 0x3f) << 18);
2523 unicode += ((string[3] & 0x3f) << 12);
2524 unicode += ((string[4] & 0x3f) << 6);
2525 unicode += (string[5] & 0x3f);
2526 break;
2527 default:
2528 die("Invalid unicode length");
2529 }
2530
2531 /* Invalid characters could return the special 0xfffd value but NUL
2532 * should be just as good. */
2533 return unicode > 0xffff ? 0 : unicode;
2534}
2535
2536/* Calculates how much of string can be shown within the given maximum width
2537 * and sets trimmed parameter to non-zero value if all of string could not be
2538 * shown.
2539 *
2540 * Additionally, adds to coloffset how many many columns to move to align with
2541 * the expected position. Takes into account how multi-byte and double-width
2542 * characters will effect the cursor position.
2543 *
2544 * Returns the number of bytes to output from string to satisfy max_width. */
2545static size_t
2546utf8_length(const char *string, size_t max_width, int *coloffset, int *trimmed)
2547{
2548 const char *start = string;
2549 const char *end = strchr(string, '\0');
2550 size_t mbwidth = 0;
2551 size_t width = 0;
2552
2553 *trimmed = 0;
2554
2555 while (string < end) {
2556 int c = *(unsigned char *) string;
2557 unsigned char bytes = utf8_bytes[c];
2558 size_t ucwidth;
2559 unsigned long unicode;
2560
2561 if (string + bytes > end)
2562 break;
2563
2564 /* Change representation to figure out whether
2565 * it is a single- or double-width character. */
2566
2567 unicode = utf8_to_unicode(string, bytes);
2568 /* FIXME: Graceful handling of invalid unicode character. */
2569 if (!unicode)
2570 break;
2571
2572 ucwidth = unicode_width(unicode);
2573 width += ucwidth;
2574 if (width > max_width) {
2575 *trimmed = 1;
2576 break;
2577 }
2578
2579 /* The column offset collects the differences between the
2580 * number of bytes encoding a character and the number of
2581 * columns will be used for rendering said character.
2582 *
2583 * So if some character A is encoded in 2 bytes, but will be
2584 * represented on the screen using only 1 byte this will and up
2585 * adding 1 to the multi-byte column offset.
2586 *
2587 * Assumes that no double-width character can be encoding in
2588 * less than two bytes. */
2589 if (bytes > ucwidth)
2590 mbwidth += bytes - ucwidth;
2591
2592 string += bytes;
2593 }
2594
2595 *coloffset += mbwidth;
2596
2597 return string - start;
2598}
2599
2600
2601/*
6b161b31
JF
2602 * Status management
2603 */
2e8488b4 2604
8855ada4 2605/* Whether or not the curses interface has been initialized. */
68b6e0eb 2606static bool cursed = FALSE;
8855ada4 2607
6b161b31
JF
2608/* The status window is used for polling keystrokes. */
2609static WINDOW *status_win;
4a2909a7 2610
2e8488b4 2611/* Update status and title window. */
4a2909a7
JF
2612static void
2613report(const char *msg, ...)
2614{
6706b2ba
JF
2615 static bool empty = TRUE;
2616 struct view *view = display[current_view];
b76c2afc 2617
6706b2ba
JF
2618 if (!empty || *msg) {
2619 va_list args;
4a2909a7 2620
6706b2ba 2621 va_start(args, msg);
4b76734f 2622
6706b2ba
JF
2623 werase(status_win);
2624 wmove(status_win, 0, 0);
2625 if (*msg) {
2626 vwprintw(status_win, msg, args);
2627 empty = FALSE;
2628 } else {
2629 empty = TRUE;
2630 }
2631 wrefresh(status_win);
b801d8b2 2632
6706b2ba
JF
2633 va_end(args);
2634 }
2635
2636 update_view_title(view);
85af6284 2637 update_display_cursor();
b801d8b2
JF
2638}
2639
6b161b31
JF
2640/* Controls when nodelay should be in effect when polling user input. */
2641static void
1ba2ae4b 2642set_nonblocking_input(bool loading)
b801d8b2 2643{
6706b2ba 2644 static unsigned int loading_views;
b801d8b2 2645
6706b2ba
JF
2646 if ((loading == FALSE && loading_views-- == 1) ||
2647 (loading == TRUE && loading_views++ == 0))
1ba2ae4b 2648 nodelay(status_win, loading);
6b161b31
JF
2649}
2650
2651static void
2652init_display(void)
2653{
2654 int x, y;
b76c2afc 2655
6908bdbd
JF
2656 /* Initialize the curses library */
2657 if (isatty(STDIN_FILENO)) {
8855ada4 2658 cursed = !!initscr();
6908bdbd
JF
2659 } else {
2660 /* Leave stdin and stdout alone when acting as a pager. */
2661 FILE *io = fopen("/dev/tty", "r+");
2662
e6f60674
JF
2663 if (!io)
2664 die("Failed to open /dev/tty");
8855ada4 2665 cursed = !!newterm(NULL, io, io);
6908bdbd
JF
2666 }
2667
8855ada4
JF
2668 if (!cursed)
2669 die("Failed to initialize curses");
2670
2e8488b4
JF
2671 nonl(); /* Tell curses not to do NL->CR/NL on output */
2672 cbreak(); /* Take input chars one at a time, no wait for \n */
2673 noecho(); /* Don't echo input */
b801d8b2 2674 leaveok(stdscr, TRUE);
b801d8b2
JF
2675
2676 if (has_colors())
2677 init_colors();
2678
2679 getmaxyx(stdscr, y, x);
2680 status_win = newwin(1, 0, y - 1, 0);
2681 if (!status_win)
2682 die("Failed to create status window");
2683
2684 /* Enable keyboard mapping */
2685 keypad(status_win, TRUE);
78c70acd 2686 wbkgdset(status_win, get_line_attr(LINE_STATUS));
6b161b31
JF
2687}
2688
ef5404a4 2689static int
cb9e48c1 2690read_prompt(const char *prompt)
ef5404a4
JF
2691{
2692 enum { READING, STOP, CANCEL } status = READING;
2693 char buf[sizeof(opt_cmd) - STRING_SIZE("git \0")];
2694 int pos = 0;
2695
2696 while (status == READING) {
2697 struct view *view;
2698 int i, key;
2699
2700 foreach_view (view, i)
2701 update_view(view);
2702
cb9e48c1 2703 report("%s%.*s", prompt, pos, buf);
ef5404a4
JF
2704 /* Refresh, accept single keystroke of input */
2705 key = wgetch(status_win);
2706 switch (key) {
2707 case KEY_RETURN:
2708 case KEY_ENTER:
2709 case '\n':
2710 status = pos ? STOP : CANCEL;
2711 break;
2712
2713 case KEY_BACKSPACE:
2714 if (pos > 0)
2715 pos--;
2716 else
2717 status = CANCEL;
2718 break;
2719
2720 case KEY_ESC:
2721 status = CANCEL;
2722 break;
2723
2724 case ERR:
2725 break;
2726
2727 default:
2728 if (pos >= sizeof(buf)) {
2729 report("Input string too long");
2730 return ERR;
2731 }
2732
2733 if (isprint(key))
2734 buf[pos++] = (char) key;
2735 }
2736 }
2737
2738 if (status == CANCEL) {
2739 /* Clear the status window */
2740 report("");
2741 return ERR;
2742 }
2743
2744 buf[pos++] = 0;
2745 if (!string_format(opt_cmd, "git %s", buf))
2746 return ERR;
efa092c4
JF
2747 if (strncmp(buf, "show", 4) && isspace(buf[4]))
2748 opt_request = REQ_VIEW_DIFF;
2749 else
2750 opt_request = REQ_VIEW_PAGER;
ef5404a4
JF
2751
2752 return OK;
2753}
c34d9c9f
JF
2754
2755/*
2756 * Repository references
2757 */
2758
2759static struct ref *refs;
3a91b75e 2760static size_t refs_size;
c34d9c9f 2761
1307df1a
JF
2762/* Id <-> ref store */
2763static struct ref ***id_refs;
2764static size_t id_refs_size;
2765
c34d9c9f
JF
2766static struct ref **
2767get_refs(char *id)
2768{
1307df1a
JF
2769 struct ref ***tmp_id_refs;
2770 struct ref **ref_list = NULL;
2771 size_t ref_list_size = 0;
c34d9c9f
JF
2772 size_t i;
2773
1307df1a
JF
2774 for (i = 0; i < id_refs_size; i++)
2775 if (!strcmp(id, id_refs[i][0]->id))
2776 return id_refs[i];
2777
2778 tmp_id_refs = realloc(id_refs, (id_refs_size + 1) * sizeof(*id_refs));
2779 if (!tmp_id_refs)
2780 return NULL;
2781
2782 id_refs = tmp_id_refs;
2783
c34d9c9f
JF
2784 for (i = 0; i < refs_size; i++) {
2785 struct ref **tmp;
2786
2787 if (strcmp(id, refs[i].id))
2788 continue;
2789
1307df1a 2790 tmp = realloc(ref_list, (ref_list_size + 1) * sizeof(*ref_list));
c34d9c9f 2791 if (!tmp) {
1307df1a
JF
2792 if (ref_list)
2793 free(ref_list);
c34d9c9f
JF
2794 return NULL;
2795 }
2796
1307df1a
JF
2797 ref_list = tmp;
2798 if (ref_list_size > 0)
2799 ref_list[ref_list_size - 1]->next = 1;
2800 ref_list[ref_list_size] = &refs[i];
3af8774e
JF
2801
2802 /* XXX: The properties of the commit chains ensures that we can
2803 * safely modify the shared ref. The repo references will
2804 * always be similar for the same id. */
1307df1a
JF
2805 ref_list[ref_list_size]->next = 0;
2806 ref_list_size++;
c34d9c9f
JF
2807 }
2808
1307df1a
JF
2809 if (ref_list)
2810 id_refs[id_refs_size++] = ref_list;
2811
2812 return ref_list;
c34d9c9f
JF
2813}
2814
2815static int
d0cea5f9 2816read_ref(char *id, int idlen, char *name, int namelen)
c34d9c9f 2817{
d0cea5f9
JF
2818 struct ref *ref;
2819 bool tag = FALSE;
d0cea5f9 2820
8b0297ae
JF
2821 if (!strncmp(name, "refs/tags/", STRING_SIZE("refs/tags/"))) {
2822 /* Commits referenced by tags has "^{}" appended. */
2823 if (name[namelen - 1] != '}')
2824 return OK;
2825
d0cea5f9
JF
2826 while (namelen > 0 && name[namelen] != '^')
2827 namelen--;
c34d9c9f 2828
d0cea5f9 2829 tag = TRUE;
8b0297ae
JF
2830 namelen -= STRING_SIZE("refs/tags/");
2831 name += STRING_SIZE("refs/tags/");
c34d9c9f 2832
d0cea5f9 2833 } else if (!strncmp(name, "refs/heads/", STRING_SIZE("refs/heads/"))) {
8b0297ae
JF
2834 namelen -= STRING_SIZE("refs/heads/");
2835 name += STRING_SIZE("refs/heads/");
c34d9c9f 2836
d0cea5f9
JF
2837 } else if (!strcmp(name, "HEAD")) {
2838 return OK;
2839 }
6706b2ba 2840
d0cea5f9
JF
2841 refs = realloc(refs, sizeof(*refs) * (refs_size + 1));
2842 if (!refs)
2843 return ERR;
c34d9c9f 2844
d0cea5f9 2845 ref = &refs[refs_size++];
8b0297ae 2846 ref->name = malloc(namelen + 1);
d0cea5f9
JF
2847 if (!ref->name)
2848 return ERR;
3af8774e 2849
8b0297ae
JF
2850 strncpy(ref->name, name, namelen);
2851 ref->name[namelen] = 0;
d0cea5f9
JF
2852 ref->tag = tag;
2853 string_copy(ref->id, id);
3af8774e 2854
d0cea5f9
JF
2855 return OK;
2856}
c34d9c9f 2857
d0cea5f9
JF
2858static int
2859load_refs(void)
2860{
2861 const char *cmd_env = getenv("TIG_LS_REMOTE");
2862 const char *cmd = cmd_env && *cmd_env ? cmd_env : TIG_LS_REMOTE;
c34d9c9f 2863
4a63c884 2864 return read_properties(popen(cmd, "r"), "\t", read_ref);
d0cea5f9 2865}
c34d9c9f 2866
d0cea5f9 2867static int
14c778a6 2868read_repo_config_option(char *name, int namelen, char *value, int valuelen)
d0cea5f9 2869{
22913179 2870 if (!strcmp(name, "i18n.commitencoding"))
d0cea5f9 2871 string_copy(opt_encoding, value);
c34d9c9f 2872
c34d9c9f
JF
2873 return OK;
2874}
2875
4670cf89 2876static int
14c778a6 2877load_repo_config(void)
4670cf89 2878{
66749723 2879 return read_properties(popen("git repo-config --list", "r"),
14c778a6 2880 "=", read_repo_config_option);
d0cea5f9
JF
2881}
2882
2883static int
4a63c884 2884read_properties(FILE *pipe, const char *separators,
d0cea5f9
JF
2885 int (*read_property)(char *, int, char *, int))
2886{
4670cf89
JF
2887 char buffer[BUFSIZ];
2888 char *name;
d0cea5f9 2889 int state = OK;
4670cf89
JF
2890
2891 if (!pipe)
2892 return ERR;
2893
d0cea5f9 2894 while (state == OK && (name = fgets(buffer, sizeof(buffer), pipe))) {
4a63c884
JF
2895 char *value;
2896 size_t namelen;
2897 size_t valuelen;
4670cf89 2898
4a63c884
JF
2899 name = chomp_string(name);
2900 namelen = strcspn(name, separators);
2901
2902 if (name[namelen]) {
2903 name[namelen] = 0;
2904 value = chomp_string(name + namelen + 1);
d0cea5f9 2905 valuelen = strlen(value);
4670cf89 2906
d0cea5f9 2907 } else {
d0cea5f9
JF
2908 value = "";
2909 valuelen = 0;
4670cf89 2910 }
d0cea5f9 2911
3c3801c2 2912 state = read_property(name, namelen, value, valuelen);
4670cf89
JF
2913 }
2914
d0cea5f9
JF
2915 if (state != ERR && ferror(pipe))
2916 state = ERR;
4670cf89
JF
2917
2918 pclose(pipe);
2919
d0cea5f9 2920 return state;
4670cf89
JF
2921}
2922
d0cea5f9 2923
6b161b31
JF
2924/*
2925 * Main
2926 */
2927
b5c9e67f 2928static void __NORETURN
6b161b31
JF
2929quit(int sig)
2930{
8855ada4
JF
2931 /* XXX: Restore tty modes and let the OS cleanup the rest! */
2932 if (cursed)
2933 endwin();
6b161b31
JF
2934 exit(0);
2935}
2936
c6704a4e
JF
2937static void __NORETURN
2938die(const char *err, ...)
6b161b31
JF
2939{
2940 va_list args;
2941
2942 endwin();
2943
2944 va_start(args, err);
2945 fputs("tig: ", stderr);
2946 vfprintf(stderr, err, args);
2947 fputs("\n", stderr);
2948 va_end(args);
2949
2950 exit(1);
2951}
2952
2953int
2954main(int argc, char *argv[])
2955{
1ba2ae4b 2956 struct view *view;
6b161b31 2957 enum request request;
1ba2ae4b 2958 size_t i;
6b161b31
JF
2959
2960 signal(SIGINT, quit);
2961
6b68fd24
JF
2962 if (setlocale(LC_ALL, "")) {
2963 string_copy(opt_codeset, nl_langinfo(CODESET));
2964 }
2965
660e09ad
JF
2966 if (load_options() == ERR)
2967 die("Failed to load user config.");
2968
2969 /* Load the repo config file so options can be overwritten from
afdc35b3 2970 * the command line. */
14c778a6 2971 if (load_repo_config() == ERR)
afdc35b3
JF
2972 die("Failed to load repo config.");
2973
8855ada4 2974 if (!parse_options(argc, argv))
6b161b31
JF
2975 return 0;
2976
6b68fd24
JF
2977 if (*opt_codeset && strcmp(opt_codeset, opt_encoding)) {
2978 opt_iconv = iconv_open(opt_codeset, opt_encoding);
2979 if (opt_iconv == (iconv_t) -1)
2980 die("Failed to initialize character set conversion");
2981 }
2982
c34d9c9f
JF
2983 if (load_refs() == ERR)
2984 die("Failed to load refs.");
2985
7bb55251
JF
2986 /* Require a git repository unless when running in pager mode. */
2987 if (refs_size == 0 && opt_request != REQ_VIEW_PAGER)
2988 die("Not a git repository");
2989
1ba2ae4b
JF
2990 for (i = 0; i < ARRAY_SIZE(views) && (view = &views[i]); i++)
2991 view->cmd_env = getenv(view->cmd_env);
2992
6b161b31
JF
2993 request = opt_request;
2994
2995 init_display();
b801d8b2
JF
2996
2997 while (view_driver(display[current_view], request)) {
6b161b31 2998 int key;
b801d8b2
JF
2999 int i;
3000
6b161b31
JF
3001 foreach_view (view, i)
3002 update_view(view);
b801d8b2
JF
3003
3004 /* Refresh, accept single keystroke of input */
6b161b31 3005 key = wgetch(status_win);
04e2b7b2
JF
3006
3007 request = get_keybinding(display[current_view]->keymap, key);
03a93dbb 3008
6706b2ba 3009 /* Some low-level request handling. This keeps access to
fac7db6c
JF
3010 * status_win restricted. */
3011 switch (request) {
3012 case REQ_PROMPT:
cb9e48c1 3013 if (read_prompt(":") == ERR)
6a7bb912 3014 request = REQ_SCREEN_UPDATE;
fac7db6c
JF
3015 break;
3016
3017 case REQ_SCREEN_RESIZE:
3018 {
3019 int height, width;
3020
3021 getmaxyx(stdscr, height, width);
3022
3023 /* Resize the status view and let the view driver take
3024 * care of resizing the displayed views. */
3025 wresize(status_win, 1, width);
3026 mvwin(status_win, height - 1, 0);
3027 wrefresh(status_win);
3028 break;
3029 }
3030 default:
3031 break;
03a93dbb 3032 }
b801d8b2
JF
3033 }
3034
3035 quit(0);
3036
3037 return 0;
3038}