Blob


1 /*
2 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/queue.h>
18 #include <sys/stat.h>
19 #include <sys/ioctl.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
24 #include <curses.h>
25 #include <panel.h>
26 #include <locale.h>
27 #include <sha1.h>
28 #include <sha2.h>
29 #include <signal.h>
30 #include <stdlib.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <getopt.h>
34 #include <string.h>
35 #include <err.h>
36 #include <unistd.h>
37 #include <limits.h>
38 #include <wchar.h>
39 #include <time.h>
40 #include <pthread.h>
41 #include <libgen.h>
42 #include <regex.h>
43 #include <sched.h>
45 #include "got_version.h"
46 #include "got_error.h"
47 #include "got_object.h"
48 #include "got_reference.h"
49 #include "got_repository.h"
50 #include "got_diff.h"
51 #include "got_opentemp.h"
52 #include "got_utf8.h"
53 #include "got_cancel.h"
54 #include "got_commit_graph.h"
55 #include "got_blame.h"
56 #include "got_privsep.h"
57 #include "got_path.h"
58 #include "got_worktree.h"
59 #include "got_keyword.h"
61 #ifndef MIN
62 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
63 #endif
65 #ifndef MAX
66 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
67 #endif
69 #define CTRL(x) ((x) & 0x1f)
71 #ifndef nitems
72 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
73 #endif
75 struct tog_cmd {
76 const char *name;
77 const struct got_error *(*cmd_main)(int, char *[]);
78 void (*cmd_usage)(void);
79 };
81 __dead static void usage(int, int);
82 __dead static void usage_log(void);
83 __dead static void usage_diff(void);
84 __dead static void usage_blame(void);
85 __dead static void usage_tree(void);
86 __dead static void usage_ref(void);
88 static const struct got_error* cmd_log(int, char *[]);
89 static const struct got_error* cmd_diff(int, char *[]);
90 static const struct got_error* cmd_blame(int, char *[]);
91 static const struct got_error* cmd_tree(int, char *[]);
92 static const struct got_error* cmd_ref(int, char *[]);
94 static const struct tog_cmd tog_commands[] = {
95 { "log", cmd_log, usage_log },
96 { "diff", cmd_diff, usage_diff },
97 { "blame", cmd_blame, usage_blame },
98 { "tree", cmd_tree, usage_tree },
99 { "ref", cmd_ref, usage_ref },
100 };
102 enum tog_view_type {
103 TOG_VIEW_DIFF,
104 TOG_VIEW_LOG,
105 TOG_VIEW_BLAME,
106 TOG_VIEW_TREE,
107 TOG_VIEW_REF,
108 TOG_VIEW_HELP
109 };
111 /* Match _DIFF to _HELP with enum tog_view_type TOG_VIEW_* counterparts. */
112 enum tog_keymap_type {
113 TOG_KEYMAP_KEYS = -2,
114 TOG_KEYMAP_GLOBAL,
115 TOG_KEYMAP_DIFF,
116 TOG_KEYMAP_LOG,
117 TOG_KEYMAP_BLAME,
118 TOG_KEYMAP_TREE,
119 TOG_KEYMAP_REF,
120 TOG_KEYMAP_HELP
121 };
123 enum tog_view_mode {
124 TOG_VIEW_SPLIT_NONE,
125 TOG_VIEW_SPLIT_VERT,
126 TOG_VIEW_SPLIT_HRZN
127 };
129 #define HSPLIT_SCALE 0.3f /* default horizontal split scale */
131 #define TOG_EOF_STRING "(END)"
133 struct commit_queue_entry {
134 TAILQ_ENTRY(commit_queue_entry) entry;
135 struct got_object_id *id;
136 struct got_commit_object *commit;
137 int idx;
138 };
139 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
140 struct commit_queue {
141 int ncommits;
142 struct commit_queue_head head;
143 };
145 struct tog_color {
146 STAILQ_ENTRY(tog_color) entry;
147 regex_t regex;
148 short colorpair;
149 };
150 STAILQ_HEAD(tog_colors, tog_color);
152 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
153 static struct got_reflist_object_id_map *tog_refs_idmap;
154 static struct {
155 struct got_object_id *id;
156 int idx;
157 char marker;
158 } tog_base_commit;
159 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
161 static const struct got_error *
162 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
163 struct got_reference* re2)
165 const char *name1 = got_ref_get_name(re1);
166 const char *name2 = got_ref_get_name(re2);
167 int isbackup1, isbackup2;
169 /* Sort backup refs towards the bottom of the list. */
170 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
171 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
172 if (!isbackup1 && isbackup2) {
173 *cmp = -1;
174 return NULL;
175 } else if (isbackup1 && !isbackup2) {
176 *cmp = 1;
177 return NULL;
180 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
181 return NULL;
184 static const struct got_error *
185 tog_load_refs(struct got_repository *repo, int sort_by_date)
187 const struct got_error *err;
189 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
190 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
191 repo);
192 if (err)
193 return err;
195 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
196 repo);
199 static void
200 tog_free_refs(void)
202 if (tog_refs_idmap) {
203 got_reflist_object_id_map_free(tog_refs_idmap);
204 tog_refs_idmap = NULL;
206 got_ref_list_free(&tog_refs);
209 static const struct got_error *
210 add_color(struct tog_colors *colors, const char *pattern,
211 int idx, short color)
213 const struct got_error *err = NULL;
214 struct tog_color *tc;
215 int regerr = 0;
217 if (idx < 1 || idx > COLOR_PAIRS - 1)
218 return NULL;
220 init_pair(idx, color, -1);
222 tc = calloc(1, sizeof(*tc));
223 if (tc == NULL)
224 return got_error_from_errno("calloc");
225 regerr = regcomp(&tc->regex, pattern,
226 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
227 if (regerr) {
228 static char regerr_msg[512];
229 static char err_msg[512];
230 regerror(regerr, &tc->regex, regerr_msg,
231 sizeof(regerr_msg));
232 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
233 regerr_msg);
234 err = got_error_msg(GOT_ERR_REGEX, err_msg);
235 free(tc);
236 return err;
238 tc->colorpair = idx;
239 STAILQ_INSERT_HEAD(colors, tc, entry);
240 return NULL;
243 static void
244 free_colors(struct tog_colors *colors)
246 struct tog_color *tc;
248 while (!STAILQ_EMPTY(colors)) {
249 tc = STAILQ_FIRST(colors);
250 STAILQ_REMOVE_HEAD(colors, entry);
251 regfree(&tc->regex);
252 free(tc);
256 static struct tog_color *
257 get_color(struct tog_colors *colors, int colorpair)
259 struct tog_color *tc = NULL;
261 STAILQ_FOREACH(tc, colors, entry) {
262 if (tc->colorpair == colorpair)
263 return tc;
266 return NULL;
269 static int
270 default_color_value(const char *envvar)
272 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
273 return COLOR_MAGENTA;
274 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
275 return COLOR_CYAN;
276 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
277 return COLOR_YELLOW;
278 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
279 return COLOR_GREEN;
280 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
281 return COLOR_MAGENTA;
282 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
283 return COLOR_MAGENTA;
284 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
285 return COLOR_CYAN;
286 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
287 return COLOR_GREEN;
288 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
289 return COLOR_GREEN;
290 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
291 return COLOR_CYAN;
292 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
293 return COLOR_YELLOW;
294 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
295 return COLOR_GREEN;
296 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
297 return COLOR_MAGENTA;
298 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
299 return COLOR_YELLOW;
300 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
301 return COLOR_CYAN;
303 return -1;
306 static int
307 get_color_value(const char *envvar)
309 const char *val = getenv(envvar);
311 if (val == NULL)
312 return default_color_value(envvar);
314 if (strcasecmp(val, "black") == 0)
315 return COLOR_BLACK;
316 if (strcasecmp(val, "red") == 0)
317 return COLOR_RED;
318 if (strcasecmp(val, "green") == 0)
319 return COLOR_GREEN;
320 if (strcasecmp(val, "yellow") == 0)
321 return COLOR_YELLOW;
322 if (strcasecmp(val, "blue") == 0)
323 return COLOR_BLUE;
324 if (strcasecmp(val, "magenta") == 0)
325 return COLOR_MAGENTA;
326 if (strcasecmp(val, "cyan") == 0)
327 return COLOR_CYAN;
328 if (strcasecmp(val, "white") == 0)
329 return COLOR_WHITE;
330 if (strcasecmp(val, "default") == 0)
331 return -1;
333 return default_color_value(envvar);
336 struct tog_diff_view_state {
337 struct got_object_id *id1, *id2;
338 const char *label1, *label2;
339 FILE *f, *f1, *f2;
340 int fd1, fd2;
341 int lineno;
342 int first_displayed_line;
343 int last_displayed_line;
344 int eof;
345 int diff_context;
346 int ignore_whitespace;
347 int force_text_diff;
348 struct got_repository *repo;
349 struct got_diff_line *lines;
350 size_t nlines;
351 int matched_line;
352 int selected_line;
354 /* passed from log or blame view; may be NULL */
355 struct tog_view *parent_view;
356 };
358 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
359 static volatile sig_atomic_t tog_thread_error;
361 struct tog_log_thread_args {
362 pthread_cond_t need_commits;
363 pthread_cond_t commit_loaded;
364 int commits_needed;
365 int load_all;
366 struct got_commit_graph *graph;
367 struct commit_queue *real_commits;
368 const char *in_repo_path;
369 struct got_object_id *start_id;
370 struct got_repository *repo;
371 int *pack_fds;
372 int log_complete;
373 pthread_cond_t log_loaded;
374 sig_atomic_t *quit;
375 struct commit_queue_entry **first_displayed_entry;
376 struct commit_queue_entry **selected_entry;
377 int *searching;
378 int *search_next_done;
379 regex_t *regex;
380 int *limiting;
381 int limit_match;
382 regex_t *limit_regex;
383 struct commit_queue *limit_commits;
384 struct got_worktree *worktree;
385 int need_commit_marker;
386 };
388 struct tog_log_view_state {
389 struct commit_queue *commits;
390 struct commit_queue_entry *first_displayed_entry;
391 struct commit_queue_entry *last_displayed_entry;
392 struct commit_queue_entry *selected_entry;
393 struct commit_queue real_commits;
394 int selected;
395 char *in_repo_path;
396 char *head_ref_name;
397 int log_branches;
398 struct got_repository *repo;
399 struct got_object_id *start_id;
400 sig_atomic_t quit;
401 pthread_t thread;
402 struct tog_log_thread_args thread_args;
403 struct commit_queue_entry *matched_entry;
404 struct commit_queue_entry *search_entry;
405 struct tog_colors colors;
406 int use_committer;
407 int limit_view;
408 regex_t limit_regex;
409 struct commit_queue limit_commits;
410 };
412 #define TOG_COLOR_DIFF_MINUS 1
413 #define TOG_COLOR_DIFF_PLUS 2
414 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
415 #define TOG_COLOR_DIFF_META 4
416 #define TOG_COLOR_TREE_SUBMODULE 5
417 #define TOG_COLOR_TREE_SYMLINK 6
418 #define TOG_COLOR_TREE_DIRECTORY 7
419 #define TOG_COLOR_TREE_EXECUTABLE 8
420 #define TOG_COLOR_COMMIT 9
421 #define TOG_COLOR_AUTHOR 10
422 #define TOG_COLOR_DATE 11
423 #define TOG_COLOR_REFS_HEADS 12
424 #define TOG_COLOR_REFS_TAGS 13
425 #define TOG_COLOR_REFS_REMOTES 14
426 #define TOG_COLOR_REFS_BACKUP 15
428 struct tog_blame_cb_args {
429 struct tog_blame_line *lines; /* one per line */
430 int nlines;
432 struct tog_view *view;
433 struct got_object_id *commit_id;
434 int *quit;
435 };
437 struct tog_blame_thread_args {
438 const char *path;
439 struct got_repository *repo;
440 struct tog_blame_cb_args *cb_args;
441 int *complete;
442 got_cancel_cb cancel_cb;
443 void *cancel_arg;
444 pthread_cond_t blame_complete;
445 };
447 struct tog_blame {
448 FILE *f;
449 off_t filesize;
450 struct tog_blame_line *lines;
451 int nlines;
452 off_t *line_offsets;
453 pthread_t thread;
454 struct tog_blame_thread_args thread_args;
455 struct tog_blame_cb_args cb_args;
456 const char *path;
457 int *pack_fds;
458 };
460 struct tog_blame_view_state {
461 int first_displayed_line;
462 int last_displayed_line;
463 int selected_line;
464 int last_diffed_line;
465 int blame_complete;
466 int eof;
467 int done;
468 struct got_object_id_queue blamed_commits;
469 struct got_object_qid *blamed_commit;
470 char *path;
471 struct got_repository *repo;
472 struct got_object_id *commit_id;
473 struct got_object_id *id_to_log;
474 struct tog_blame blame;
475 int matched_line;
476 struct tog_colors colors;
477 };
479 struct tog_parent_tree {
480 TAILQ_ENTRY(tog_parent_tree) entry;
481 struct got_tree_object *tree;
482 struct got_tree_entry *first_displayed_entry;
483 struct got_tree_entry *selected_entry;
484 int selected;
485 };
487 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
489 struct tog_tree_view_state {
490 char *tree_label;
491 struct got_object_id *commit_id;/* commit which this tree belongs to */
492 struct got_tree_object *root; /* the commit's root tree entry */
493 struct got_tree_object *tree; /* currently displayed (sub-)tree */
494 struct got_tree_entry *first_displayed_entry;
495 struct got_tree_entry *last_displayed_entry;
496 struct got_tree_entry *selected_entry;
497 int ndisplayed, selected, show_ids;
498 struct tog_parent_trees parents; /* parent trees of current sub-tree */
499 char *head_ref_name;
500 struct got_repository *repo;
501 struct got_tree_entry *matched_entry;
502 struct tog_colors colors;
503 };
505 struct tog_reflist_entry {
506 TAILQ_ENTRY(tog_reflist_entry) entry;
507 struct got_reference *ref;
508 int idx;
509 };
511 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
513 struct tog_ref_view_state {
514 struct tog_reflist_head refs;
515 struct tog_reflist_entry *first_displayed_entry;
516 struct tog_reflist_entry *last_displayed_entry;
517 struct tog_reflist_entry *selected_entry;
518 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
519 struct got_repository *repo;
520 struct tog_reflist_entry *matched_entry;
521 struct tog_colors colors;
522 };
524 struct tog_help_view_state {
525 FILE *f;
526 off_t *line_offsets;
527 size_t nlines;
528 int lineno;
529 int first_displayed_line;
530 int last_displayed_line;
531 int eof;
532 int matched_line;
533 int selected_line;
534 int all;
535 enum tog_keymap_type type;
536 };
538 #define GENERATE_HELP \
539 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
540 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
541 KEY_("k C-p Up", "Move cursor or page up one line"), \
542 KEY_("j C-n Down", "Move cursor or page down one line"), \
543 KEY_("C-b b PgUp", "Scroll the view up one page"), \
544 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
545 KEY_("C-u u", "Scroll the view up one half page"), \
546 KEY_("C-d d", "Scroll the view down one half page"), \
547 KEY_("g", "Go to line N (default: first line)"), \
548 KEY_("Home =", "Go to the first line"), \
549 KEY_("G", "Go to line N (default: last line)"), \
550 KEY_("End *", "Go to the last line"), \
551 KEY_("l Right", "Scroll the view right"), \
552 KEY_("h Left", "Scroll the view left"), \
553 KEY_("$", "Scroll view to the rightmost position"), \
554 KEY_("0", "Scroll view to the leftmost position"), \
555 KEY_("-", "Decrease size of the focussed split"), \
556 KEY_("+", "Increase size of the focussed split"), \
557 KEY_("Tab", "Switch focus between views"), \
558 KEY_("F", "Toggle fullscreen mode"), \
559 KEY_("S", "Switch split-screen layout"), \
560 KEY_("/", "Open prompt to enter search term"), \
561 KEY_("n", "Find next line/token matching the current search term"), \
562 KEY_("N", "Find previous line/token matching the current search term"),\
563 KEY_("q", "Quit the focussed view; Quit help screen"), \
564 KEY_("Q", "Quit tog"), \
566 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
567 KEY_("< ,", "Move cursor up one commit"), \
568 KEY_("> .", "Move cursor down one commit"), \
569 KEY_("Enter", "Open diff view of the selected commit"), \
570 KEY_("B", "Reload the log view and toggle display of merged commits"), \
571 KEY_("R", "Open ref view of all repository references"), \
572 KEY_("T", "Display tree view of the repository from the selected" \
573 " commit"), \
574 KEY_("@", "Toggle between displaying author and committer name"), \
575 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
576 KEY_("C-g Backspace", "Cancel current search or log operation"), \
577 KEY_("C-l", "Reload the log view with new commits in the repository"), \
579 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
580 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
581 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
582 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
583 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
584 " data"), \
585 KEY_("(", "Go to the previous file in the diff"), \
586 KEY_(")", "Go to the next file in the diff"), \
587 KEY_("{", "Go to the previous hunk in the diff"), \
588 KEY_("}", "Go to the next hunk in the diff"), \
589 KEY_("[", "Decrease the number of context lines"), \
590 KEY_("]", "Increase the number of context lines"), \
591 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
593 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
594 KEY_("Enter", "Display diff view of the selected line's commit"), \
595 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
596 KEY_("L", "Open log view for the currently selected annotated line"), \
597 KEY_("C", "Reload view with the previously blamed commit"), \
598 KEY_("c", "Reload view with the version of the file found in the" \
599 " selected line's commit"), \
600 KEY_("p", "Reload view with the version of the file found in the" \
601 " selected line's parent commit"), \
603 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
604 KEY_("Enter", "Enter selected directory or open blame view of the" \
605 " selected file"), \
606 KEY_("L", "Open log view for the selected entry"), \
607 KEY_("R", "Open ref view of all repository references"), \
608 KEY_("i", "Show object IDs for all tree entries"), \
609 KEY_("Backspace", "Return to the parent directory"), \
611 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
612 KEY_("Enter", "Display log view of the selected reference"), \
613 KEY_("T", "Display tree view of the selected reference"), \
614 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
615 KEY_("m", "Toggle display of last modified date for each reference"), \
616 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
617 KEY_("C-l", "Reload view with all repository references")
619 struct tog_key_map {
620 const char *keys;
621 const char *info;
622 enum tog_keymap_type type;
623 };
625 /* curses io for tog regress */
626 struct tog_io {
627 FILE *cin;
628 FILE *cout;
629 FILE *f;
630 FILE *sdump;
631 int wait_for_ui;
632 } tog_io;
633 static int using_mock_io;
635 #define TOG_KEY_SCRDUMP SHRT_MIN
637 /*
638 * We implement two types of views: parent views and child views.
640 * The 'Tab' key switches focus between a parent view and its child view.
641 * Child views are shown side-by-side to their parent view, provided
642 * there is enough screen estate.
644 * When a new view is opened from within a parent view, this new view
645 * becomes a child view of the parent view, replacing any existing child.
647 * When a new view is opened from within a child view, this new view
648 * becomes a parent view which will obscure the views below until the
649 * user quits the new parent view by typing 'q'.
651 * This list of views contains parent views only.
652 * Child views are only pointed to by their parent view.
653 */
654 TAILQ_HEAD(tog_view_list_head, tog_view);
656 struct tog_view {
657 TAILQ_ENTRY(tog_view) entry;
658 WINDOW *window;
659 PANEL *panel;
660 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
661 int resized_y, resized_x; /* begin_y/x based on user resizing */
662 int maxx, x; /* max column and current start column */
663 int lines, cols; /* copies of LINES and COLS */
664 int nscrolled, offset; /* lines scrolled and hsplit line offset */
665 int gline, hiline; /* navigate to and highlight this nG line */
666 int ch, count; /* current keymap and count prefix */
667 int resized; /* set when in a resize event */
668 int focussed; /* Only set on one parent or child view at a time. */
669 int dying;
670 struct tog_view *parent;
671 struct tog_view *child;
673 /*
674 * This flag is initially set on parent views when a new child view
675 * is created. It gets toggled when the 'Tab' key switches focus
676 * between parent and child.
677 * The flag indicates whether focus should be passed on to our child
678 * view if this parent view gets picked for focus after another parent
679 * view was closed. This prevents child views from losing focus in such
680 * situations.
681 */
682 int focus_child;
684 enum tog_view_mode mode;
685 /* type-specific state */
686 enum tog_view_type type;
687 union {
688 struct tog_diff_view_state diff;
689 struct tog_log_view_state log;
690 struct tog_blame_view_state blame;
691 struct tog_tree_view_state tree;
692 struct tog_ref_view_state ref;
693 struct tog_help_view_state help;
694 } state;
696 const struct got_error *(*show)(struct tog_view *);
697 const struct got_error *(*input)(struct tog_view **,
698 struct tog_view *, int);
699 const struct got_error *(*reset)(struct tog_view *);
700 const struct got_error *(*resize)(struct tog_view *, int);
701 const struct got_error *(*close)(struct tog_view *);
703 const struct got_error *(*search_start)(struct tog_view *);
704 const struct got_error *(*search_next)(struct tog_view *);
705 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
706 int **, int **, int **, int **);
707 int search_started;
708 int searching;
709 #define TOG_SEARCH_FORWARD 1
710 #define TOG_SEARCH_BACKWARD 2
711 int search_next_done;
712 #define TOG_SEARCH_HAVE_MORE 1
713 #define TOG_SEARCH_NO_MORE 2
714 #define TOG_SEARCH_HAVE_NONE 3
715 regex_t regex;
716 regmatch_t regmatch;
717 const char *action;
718 };
720 static const struct got_error *open_diff_view(struct tog_view *,
721 struct got_object_id *, struct got_object_id *,
722 const char *, const char *, int, int, int, struct tog_view *,
723 struct got_repository *);
724 static const struct got_error *show_diff_view(struct tog_view *);
725 static const struct got_error *input_diff_view(struct tog_view **,
726 struct tog_view *, int);
727 static const struct got_error *reset_diff_view(struct tog_view *);
728 static const struct got_error* close_diff_view(struct tog_view *);
729 static const struct got_error *search_start_diff_view(struct tog_view *);
730 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
731 size_t *, int **, int **, int **, int **);
732 static const struct got_error *search_next_view_match(struct tog_view *);
734 static const struct got_error *open_log_view(struct tog_view *,
735 struct got_object_id *, struct got_repository *,
736 const char *, const char *, int, struct got_worktree *);
737 static const struct got_error * show_log_view(struct tog_view *);
738 static const struct got_error *input_log_view(struct tog_view **,
739 struct tog_view *, int);
740 static const struct got_error *resize_log_view(struct tog_view *, int);
741 static const struct got_error *close_log_view(struct tog_view *);
742 static const struct got_error *search_start_log_view(struct tog_view *);
743 static const struct got_error *search_next_log_view(struct tog_view *);
745 static const struct got_error *open_blame_view(struct tog_view *, char *,
746 struct got_object_id *, struct got_repository *);
747 static const struct got_error *show_blame_view(struct tog_view *);
748 static const struct got_error *input_blame_view(struct tog_view **,
749 struct tog_view *, int);
750 static const struct got_error *reset_blame_view(struct tog_view *);
751 static const struct got_error *close_blame_view(struct tog_view *);
752 static const struct got_error *search_start_blame_view(struct tog_view *);
753 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
754 size_t *, int **, int **, int **, int **);
756 static const struct got_error *open_tree_view(struct tog_view *,
757 struct got_object_id *, const char *, struct got_repository *);
758 static const struct got_error *show_tree_view(struct tog_view *);
759 static const struct got_error *input_tree_view(struct tog_view **,
760 struct tog_view *, int);
761 static const struct got_error *close_tree_view(struct tog_view *);
762 static const struct got_error *search_start_tree_view(struct tog_view *);
763 static const struct got_error *search_next_tree_view(struct tog_view *);
765 static const struct got_error *open_ref_view(struct tog_view *,
766 struct got_repository *);
767 static const struct got_error *show_ref_view(struct tog_view *);
768 static const struct got_error *input_ref_view(struct tog_view **,
769 struct tog_view *, int);
770 static const struct got_error *close_ref_view(struct tog_view *);
771 static const struct got_error *search_start_ref_view(struct tog_view *);
772 static const struct got_error *search_next_ref_view(struct tog_view *);
774 static const struct got_error *open_help_view(struct tog_view *,
775 struct tog_view *);
776 static const struct got_error *show_help_view(struct tog_view *);
777 static const struct got_error *input_help_view(struct tog_view **,
778 struct tog_view *, int);
779 static const struct got_error *reset_help_view(struct tog_view *);
780 static const struct got_error* close_help_view(struct tog_view *);
781 static const struct got_error *search_start_help_view(struct tog_view *);
782 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
783 size_t *, int **, int **, int **, int **);
785 static volatile sig_atomic_t tog_sigwinch_received;
786 static volatile sig_atomic_t tog_sigpipe_received;
787 static volatile sig_atomic_t tog_sigcont_received;
788 static volatile sig_atomic_t tog_sigint_received;
789 static volatile sig_atomic_t tog_sigterm_received;
791 static void
792 tog_sigwinch(int signo)
794 tog_sigwinch_received = 1;
797 static void
798 tog_sigpipe(int signo)
800 tog_sigpipe_received = 1;
803 static void
804 tog_sigcont(int signo)
806 tog_sigcont_received = 1;
809 static void
810 tog_sigint(int signo)
812 tog_sigint_received = 1;
815 static void
816 tog_sigterm(int signo)
818 tog_sigterm_received = 1;
821 static int
822 tog_fatal_signal_received(void)
824 return (tog_sigpipe_received ||
825 tog_sigint_received || tog_sigterm_received);
828 static const struct got_error *
829 view_close(struct tog_view *view)
831 const struct got_error *err = NULL, *child_err = NULL;
833 if (view->child) {
834 child_err = view_close(view->child);
835 view->child = NULL;
837 if (view->close)
838 err = view->close(view);
839 if (view->panel)
840 del_panel(view->panel);
841 if (view->window)
842 delwin(view->window);
843 free(view);
844 return err ? err : child_err;
847 static struct tog_view *
848 view_open(int nlines, int ncols, int begin_y, int begin_x,
849 enum tog_view_type type)
851 struct tog_view *view = calloc(1, sizeof(*view));
853 if (view == NULL)
854 return NULL;
856 view->type = type;
857 view->lines = LINES;
858 view->cols = COLS;
859 view->nlines = nlines ? nlines : LINES - begin_y;
860 view->ncols = ncols ? ncols : COLS - begin_x;
861 view->begin_y = begin_y;
862 view->begin_x = begin_x;
863 view->window = newwin(nlines, ncols, begin_y, begin_x);
864 if (view->window == NULL) {
865 view_close(view);
866 return NULL;
868 view->panel = new_panel(view->window);
869 if (view->panel == NULL ||
870 set_panel_userptr(view->panel, view) != OK) {
871 view_close(view);
872 return NULL;
875 keypad(view->window, TRUE);
876 return view;
879 static int
880 view_split_begin_x(int begin_x)
882 if (begin_x > 0 || COLS < 120)
883 return 0;
884 return (COLS - MAX(COLS / 2, 80));
887 /* XXX Stub till we decide what to do. */
888 static int
889 view_split_begin_y(int lines)
891 return lines * HSPLIT_SCALE;
894 static const struct got_error *view_resize(struct tog_view *);
896 static const struct got_error *
897 view_splitscreen(struct tog_view *view)
899 const struct got_error *err = NULL;
901 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
902 if (view->resized_y && view->resized_y < view->lines)
903 view->begin_y = view->resized_y;
904 else
905 view->begin_y = view_split_begin_y(view->nlines);
906 view->begin_x = 0;
907 } else if (!view->resized) {
908 if (view->resized_x && view->resized_x < view->cols - 1 &&
909 view->cols > 119)
910 view->begin_x = view->resized_x;
911 else
912 view->begin_x = view_split_begin_x(0);
913 view->begin_y = 0;
915 view->nlines = LINES - view->begin_y;
916 view->ncols = COLS - view->begin_x;
917 view->lines = LINES;
918 view->cols = COLS;
919 err = view_resize(view);
920 if (err)
921 return err;
923 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
924 view->parent->nlines = view->begin_y;
926 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
927 return got_error_from_errno("mvwin");
929 return NULL;
932 static const struct got_error *
933 view_fullscreen(struct tog_view *view)
935 const struct got_error *err = NULL;
937 view->begin_x = 0;
938 view->begin_y = view->resized ? view->begin_y : 0;
939 view->nlines = view->resized ? view->nlines : LINES;
940 view->ncols = COLS;
941 view->lines = LINES;
942 view->cols = COLS;
943 err = view_resize(view);
944 if (err)
945 return err;
947 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
948 return got_error_from_errno("mvwin");
950 return NULL;
953 static int
954 view_is_parent_view(struct tog_view *view)
956 return view->parent == NULL;
959 static int
960 view_is_splitscreen(struct tog_view *view)
962 return view->begin_x > 0 || view->begin_y > 0;
965 static int
966 view_is_fullscreen(struct tog_view *view)
968 return view->nlines == LINES && view->ncols == COLS;
971 static int
972 view_is_hsplit_top(struct tog_view *view)
974 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
975 view_is_splitscreen(view->child);
978 static void
979 view_border(struct tog_view *view)
981 PANEL *panel;
982 const struct tog_view *view_above;
984 if (view->parent)
985 return view_border(view->parent);
987 panel = panel_above(view->panel);
988 if (panel == NULL)
989 return;
991 view_above = panel_userptr(panel);
992 if (view->mode == TOG_VIEW_SPLIT_HRZN)
993 mvwhline(view->window, view_above->begin_y - 1,
994 view->begin_x, ACS_HLINE, view->ncols);
995 else
996 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
997 ACS_VLINE, view->nlines);
1000 static const struct got_error *view_init_hsplit(struct tog_view *, int);
1001 static const struct got_error *request_log_commits(struct tog_view *);
1002 static const struct got_error *offset_selection_down(struct tog_view *);
1003 static void offset_selection_up(struct tog_view *);
1004 static void view_get_split(struct tog_view *, int *, int *);
1006 static const struct got_error *
1007 view_resize(struct tog_view *view)
1009 const struct got_error *err = NULL;
1010 int dif, nlines, ncols;
1012 dif = LINES - view->lines; /* line difference */
1014 if (view->lines > LINES)
1015 nlines = view->nlines - (view->lines - LINES);
1016 else
1017 nlines = view->nlines + (LINES - view->lines);
1018 if (view->cols > COLS)
1019 ncols = view->ncols - (view->cols - COLS);
1020 else
1021 ncols = view->ncols + (COLS - view->cols);
1023 if (view->child) {
1024 int hs = view->child->begin_y;
1026 if (!view_is_fullscreen(view))
1027 view->child->begin_x = view_split_begin_x(view->begin_x);
1028 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1029 view->child->begin_x == 0) {
1030 ncols = COLS;
1032 view_fullscreen(view->child);
1033 if (view->child->focussed)
1034 show_panel(view->child->panel);
1035 else
1036 show_panel(view->panel);
1037 } else {
1038 ncols = view->child->begin_x;
1040 view_splitscreen(view->child);
1041 show_panel(view->child->panel);
1044 * XXX This is ugly and needs to be moved into the above
1045 * logic but "works" for now and my attempts at moving it
1046 * break either 'tab' or 'F' key maps in horizontal splits.
1048 if (hs) {
1049 err = view_splitscreen(view->child);
1050 if (err)
1051 return err;
1052 if (dif < 0) { /* top split decreased */
1053 err = offset_selection_down(view);
1054 if (err)
1055 return err;
1057 view_border(view);
1058 update_panels();
1059 doupdate();
1060 show_panel(view->child->panel);
1061 nlines = view->nlines;
1063 } else if (view->parent == NULL)
1064 ncols = COLS;
1066 if (view->resize && dif > 0) {
1067 err = view->resize(view, dif);
1068 if (err)
1069 return err;
1072 if (wresize(view->window, nlines, ncols) == ERR)
1073 return got_error_from_errno("wresize");
1074 if (replace_panel(view->panel, view->window) == ERR)
1075 return got_error_from_errno("replace_panel");
1076 wclear(view->window);
1078 view->nlines = nlines;
1079 view->ncols = ncols;
1080 view->lines = LINES;
1081 view->cols = COLS;
1083 return NULL;
1086 static const struct got_error *
1087 resize_log_view(struct tog_view *view, int increase)
1089 struct tog_log_view_state *s = &view->state.log;
1090 const struct got_error *err = NULL;
1091 int n = 0;
1093 if (s->selected_entry)
1094 n = s->selected_entry->idx + view->lines - s->selected;
1097 * Request commits to account for the increased
1098 * height so we have enough to populate the view.
1100 if (s->commits->ncommits < n) {
1101 view->nscrolled = n - s->commits->ncommits + increase + 1;
1102 err = request_log_commits(view);
1105 return err;
1108 static void
1109 view_adjust_offset(struct tog_view *view, int n)
1111 if (n == 0)
1112 return;
1114 if (view->parent && view->parent->offset) {
1115 if (view->parent->offset + n >= 0)
1116 view->parent->offset += n;
1117 else
1118 view->parent->offset = 0;
1119 } else if (view->offset) {
1120 if (view->offset - n >= 0)
1121 view->offset -= n;
1122 else
1123 view->offset = 0;
1127 static const struct got_error *
1128 view_resize_split(struct tog_view *view, int resize)
1130 const struct got_error *err = NULL;
1131 struct tog_view *v = NULL;
1133 if (view->parent)
1134 v = view->parent;
1135 else
1136 v = view;
1138 if (!v->child || !view_is_splitscreen(v->child))
1139 return NULL;
1141 v->resized = v->child->resized = resize; /* lock for resize event */
1143 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1144 if (v->child->resized_y)
1145 v->child->begin_y = v->child->resized_y;
1146 if (view->parent)
1147 v->child->begin_y -= resize;
1148 else
1149 v->child->begin_y += resize;
1150 if (v->child->begin_y < 3) {
1151 view->count = 0;
1152 v->child->begin_y = 3;
1153 } else if (v->child->begin_y > LINES - 1) {
1154 view->count = 0;
1155 v->child->begin_y = LINES - 1;
1157 v->ncols = COLS;
1158 v->child->ncols = COLS;
1159 view_adjust_offset(view, resize);
1160 err = view_init_hsplit(v, v->child->begin_y);
1161 if (err)
1162 return err;
1163 v->child->resized_y = v->child->begin_y;
1164 } else {
1165 if (v->child->resized_x)
1166 v->child->begin_x = v->child->resized_x;
1167 if (view->parent)
1168 v->child->begin_x -= resize;
1169 else
1170 v->child->begin_x += resize;
1171 if (v->child->begin_x < 11) {
1172 view->count = 0;
1173 v->child->begin_x = 11;
1174 } else if (v->child->begin_x > COLS - 1) {
1175 view->count = 0;
1176 v->child->begin_x = COLS - 1;
1178 v->child->resized_x = v->child->begin_x;
1181 v->child->mode = v->mode;
1182 v->child->nlines = v->lines - v->child->begin_y;
1183 v->child->ncols = v->cols - v->child->begin_x;
1184 v->focus_child = 1;
1186 err = view_fullscreen(v);
1187 if (err)
1188 return err;
1189 err = view_splitscreen(v->child);
1190 if (err)
1191 return err;
1193 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1194 err = offset_selection_down(v->child);
1195 if (err)
1196 return err;
1199 if (v->resize)
1200 err = v->resize(v, 0);
1201 else if (v->child->resize)
1202 err = v->child->resize(v->child, 0);
1204 v->resized = v->child->resized = 0;
1206 return err;
1209 static void
1210 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1212 struct tog_view *v = src->child ? src->child : src;
1214 dst->resized_x = v->resized_x;
1215 dst->resized_y = v->resized_y;
1218 static const struct got_error *
1219 view_close_child(struct tog_view *view)
1221 const struct got_error *err = NULL;
1223 if (view->child == NULL)
1224 return NULL;
1226 err = view_close(view->child);
1227 view->child = NULL;
1228 return err;
1231 static const struct got_error *
1232 view_set_child(struct tog_view *view, struct tog_view *child)
1234 const struct got_error *err = NULL;
1236 view->child = child;
1237 child->parent = view;
1239 err = view_resize(view);
1240 if (err)
1241 return err;
1243 if (view->child->resized_x || view->child->resized_y)
1244 err = view_resize_split(view, 0);
1246 return err;
1249 static const struct got_error *view_dispatch_request(struct tog_view **,
1250 struct tog_view *, enum tog_view_type, int, int);
1252 static const struct got_error *
1253 view_request_new(struct tog_view **requested, struct tog_view *view,
1254 enum tog_view_type request)
1256 struct tog_view *new_view = NULL;
1257 const struct got_error *err;
1258 int y = 0, x = 0;
1260 *requested = NULL;
1262 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1263 view_get_split(view, &y, &x);
1265 err = view_dispatch_request(&new_view, view, request, y, x);
1266 if (err)
1267 return err;
1269 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1270 request != TOG_VIEW_HELP) {
1271 err = view_init_hsplit(view, y);
1272 if (err)
1273 return err;
1276 view->focussed = 0;
1277 new_view->focussed = 1;
1278 new_view->mode = view->mode;
1279 new_view->nlines = request == TOG_VIEW_HELP ?
1280 view->lines : view->lines - y;
1282 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1283 view_transfer_size(new_view, view);
1284 err = view_close_child(view);
1285 if (err)
1286 return err;
1287 err = view_set_child(view, new_view);
1288 if (err)
1289 return err;
1290 view->focus_child = 1;
1291 } else
1292 *requested = new_view;
1294 return NULL;
1297 static void
1298 tog_resizeterm(void)
1300 int cols, lines;
1301 struct winsize size;
1303 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1304 cols = 80; /* Default */
1305 lines = 24;
1306 } else {
1307 cols = size.ws_col;
1308 lines = size.ws_row;
1310 resize_term(lines, cols);
1313 static const struct got_error *
1314 view_search_start(struct tog_view *view, int fast_refresh)
1316 const struct got_error *err = NULL;
1317 struct tog_view *v = view;
1318 char pattern[1024];
1319 int ret;
1321 if (view->search_started) {
1322 regfree(&view->regex);
1323 view->searching = 0;
1324 memset(&view->regmatch, 0, sizeof(view->regmatch));
1326 view->search_started = 0;
1328 if (view->nlines < 1)
1329 return NULL;
1331 if (view_is_hsplit_top(view))
1332 v = view->child;
1333 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1334 v = view->parent;
1336 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1337 wclrtoeol(v->window);
1339 nodelay(v->window, FALSE); /* block for search term input */
1340 nocbreak();
1341 echo();
1342 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1343 wrefresh(v->window);
1344 cbreak();
1345 noecho();
1346 nodelay(v->window, TRUE);
1347 if (!fast_refresh && !using_mock_io)
1348 halfdelay(10);
1349 if (ret == ERR)
1350 return NULL;
1352 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1353 err = view->search_start(view);
1354 if (err) {
1355 regfree(&view->regex);
1356 return err;
1358 view->search_started = 1;
1359 view->searching = TOG_SEARCH_FORWARD;
1360 view->search_next_done = 0;
1361 view->search_next(view);
1364 return NULL;
1367 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1368 static const struct got_error *
1369 switch_split(struct tog_view *view)
1371 const struct got_error *err = NULL;
1372 struct tog_view *v = NULL;
1374 if (view->parent)
1375 v = view->parent;
1376 else
1377 v = view;
1379 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1380 v->mode = TOG_VIEW_SPLIT_VERT;
1381 else
1382 v->mode = TOG_VIEW_SPLIT_HRZN;
1384 if (!v->child)
1385 return NULL;
1386 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1387 v->mode = TOG_VIEW_SPLIT_NONE;
1389 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1390 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1391 v->child->begin_y = v->child->resized_y;
1392 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1393 v->child->begin_x = v->child->resized_x;
1396 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1397 v->ncols = COLS;
1398 v->child->ncols = COLS;
1399 v->child->nscrolled = LINES - v->child->nlines;
1401 err = view_init_hsplit(v, v->child->begin_y);
1402 if (err)
1403 return err;
1405 v->child->mode = v->mode;
1406 v->child->nlines = v->lines - v->child->begin_y;
1407 v->focus_child = 1;
1409 err = view_fullscreen(v);
1410 if (err)
1411 return err;
1412 err = view_splitscreen(v->child);
1413 if (err)
1414 return err;
1416 if (v->mode == TOG_VIEW_SPLIT_NONE)
1417 v->mode = TOG_VIEW_SPLIT_VERT;
1418 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1419 err = offset_selection_down(v);
1420 if (err)
1421 return err;
1422 err = offset_selection_down(v->child);
1423 if (err)
1424 return err;
1425 } else {
1426 offset_selection_up(v);
1427 offset_selection_up(v->child);
1429 if (v->resize)
1430 err = v->resize(v, 0);
1431 else if (v->child->resize)
1432 err = v->child->resize(v->child, 0);
1434 return err;
1438 * Strip trailing whitespace from str starting at byte *n;
1439 * if *n < 0, use strlen(str). Return new str length in *n.
1441 static void
1442 strip_trailing_ws(char *str, int *n)
1444 size_t x = *n;
1446 if (str == NULL || *str == '\0')
1447 return;
1449 if (x < 0)
1450 x = strlen(str);
1452 while (x-- > 0 && isspace((unsigned char)str[x]))
1453 str[x] = '\0';
1455 *n = x + 1;
1459 * Extract visible substring of line y from the curses screen
1460 * and strip trailing whitespace. If vline is set, overwrite
1461 * line[vline] with '|' because the ACS_VLINE character is
1462 * written out as 'x'. Write the line to file f.
1464 static const struct got_error *
1465 view_write_line(FILE *f, int y, int vline)
1467 char line[COLS * MB_LEN_MAX]; /* allow for multibyte chars */
1468 int r, w;
1470 r = mvwinnstr(curscr, y, 0, line, sizeof(line));
1471 if (r == ERR)
1472 return got_error_fmt(GOT_ERR_RANGE,
1473 "failed to extract line %d", y);
1476 * In some views, lines are padded with blanks to COLS width.
1477 * Strip them so we can diff without the -b flag when testing.
1479 strip_trailing_ws(line, &r);
1481 if (vline > 0)
1482 line[vline] = '|';
1484 w = fprintf(f, "%s\n", line);
1485 if (w != r + 1) /* \n */
1486 return got_ferror(f, GOT_ERR_IO);
1488 return NULL;
1492 * Capture the visible curses screen by writing each line to the
1493 * file at the path set via the TOG_SCR_DUMP environment variable.
1495 static const struct got_error *
1496 screendump(struct tog_view *view)
1498 const struct got_error *err;
1499 int i;
1501 err = got_opentemp_truncate(tog_io.sdump);
1502 if (err)
1503 return err;
1505 if ((view->child && view->child->begin_x) ||
1506 (view->parent && view->begin_x)) {
1507 int ncols = view->child ? view->ncols : view->parent->ncols;
1509 /* vertical splitscreen */
1510 for (i = 0; i < view->nlines; ++i) {
1511 err = view_write_line(tog_io.sdump, i, ncols - 1);
1512 if (err)
1513 goto done;
1515 } else {
1516 int hline = 0;
1518 /* fullscreen or horizontal splitscreen */
1519 if ((view->child && view->child->begin_y) ||
1520 (view->parent && view->begin_y)) /* hsplit */
1521 hline = view->child ?
1522 view->child->begin_y : view->begin_y;
1524 for (i = 0; i < view->lines; i++) {
1525 if (hline && i == hline - 1) {
1526 int c;
1528 /* ACS_HLINE writes out as 'q', overwrite it */
1529 for (c = 0; c < view->cols; ++c)
1530 fputc('-', tog_io.sdump);
1531 fputc('\n', tog_io.sdump);
1532 continue;
1535 err = view_write_line(tog_io.sdump, i, 0);
1536 if (err)
1537 goto done;
1541 done:
1542 return err;
1546 * Compute view->count from numeric input. Assign total to view->count and
1547 * return first non-numeric key entered.
1549 static int
1550 get_compound_key(struct tog_view *view, int c)
1552 struct tog_view *v = view;
1553 int x, n = 0;
1555 if (view_is_hsplit_top(view))
1556 v = view->child;
1557 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1558 v = view->parent;
1560 view->count = 0;
1561 cbreak(); /* block for input */
1562 nodelay(view->window, FALSE);
1563 wmove(v->window, v->nlines - 1, 0);
1564 wclrtoeol(v->window);
1565 waddch(v->window, ':');
1567 do {
1568 x = getcurx(v->window);
1569 if (x != ERR && x < view->ncols) {
1570 waddch(v->window, c);
1571 wrefresh(v->window);
1575 * Don't overflow. Max valid request should be the greatest
1576 * between the longest and total lines; cap at 10 million.
1578 if (n >= 9999999)
1579 n = 9999999;
1580 else
1581 n = n * 10 + (c - '0');
1582 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1584 if (c == 'G' || c == 'g') { /* nG key map */
1585 view->gline = view->hiline = n;
1586 n = 0;
1587 c = 0;
1590 /* Massage excessive or inapplicable values at the input handler. */
1591 view->count = n;
1593 return c;
1596 static void
1597 action_report(struct tog_view *view)
1599 struct tog_view *v = view;
1601 if (view_is_hsplit_top(view))
1602 v = view->child;
1603 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1604 v = view->parent;
1606 wmove(v->window, v->nlines - 1, 0);
1607 wclrtoeol(v->window);
1608 wprintw(v->window, ":%s", view->action);
1609 wrefresh(v->window);
1612 * Clear action status report. Only clear in blame view
1613 * once annotating is complete, otherwise it's too fast.
1615 if (view->type == TOG_VIEW_BLAME) {
1616 if (view->state.blame.blame_complete)
1617 view->action = NULL;
1618 } else
1619 view->action = NULL;
1623 * Read the next line from the test script and assign
1624 * key instruction to *ch. If at EOF, set the *done flag.
1626 static const struct got_error *
1627 tog_read_script_key(FILE *script, struct tog_view *view, int *ch, int *done)
1629 const struct got_error *err = NULL;
1630 char *line = NULL;
1631 size_t linesz = 0;
1633 if (view->count && --view->count) {
1634 *ch = view->ch;
1635 return NULL;
1636 } else
1637 *ch = -1;
1639 if (getline(&line, &linesz, script) == -1) {
1640 if (feof(script)) {
1641 *done = 1;
1642 goto done;
1643 } else {
1644 err = got_ferror(script, GOT_ERR_IO);
1645 goto done;
1649 if (strncasecmp(line, "WAIT_FOR_UI", 11) == 0)
1650 tog_io.wait_for_ui = 1;
1651 else if (strncasecmp(line, "KEY_ENTER", 9) == 0)
1652 *ch = KEY_ENTER;
1653 else if (strncasecmp(line, "KEY_RIGHT", 9) == 0)
1654 *ch = KEY_RIGHT;
1655 else if (strncasecmp(line, "KEY_LEFT", 8) == 0)
1656 *ch = KEY_LEFT;
1657 else if (strncasecmp(line, "KEY_DOWN", 8) == 0)
1658 *ch = KEY_DOWN;
1659 else if (strncasecmp(line, "KEY_UP", 6) == 0)
1660 *ch = KEY_UP;
1661 else if (strncasecmp(line, "TAB", 3) == 0)
1662 *ch = '\t';
1663 else if (strncasecmp(line, "SCREENDUMP", 10) == 0)
1664 *ch = TOG_KEY_SCRDUMP;
1665 else if (isdigit((unsigned char)*line)) {
1666 char *t = line;
1668 while (isdigit((unsigned char)*t))
1669 ++t;
1670 view->ch = *ch = *t;
1671 *t = '\0';
1672 /* ignore error, view->count is 0 if instruction is invalid */
1673 view->count = strtonum(line, 0, INT_MAX, NULL);
1674 } else
1675 *ch = *line;
1677 done:
1678 free(line);
1679 return err;
1682 static const struct got_error *
1683 view_input(struct tog_view **new, int *done, struct tog_view *view,
1684 struct tog_view_list_head *views, int fast_refresh)
1686 const struct got_error *err = NULL;
1687 struct tog_view *v;
1688 int ch, errcode;
1690 *new = NULL;
1692 if (view->action)
1693 action_report(view);
1695 /* Clear "no matches" indicator. */
1696 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1697 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1698 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1699 view->count = 0;
1702 if (view->searching && !view->search_next_done) {
1703 errcode = pthread_mutex_unlock(&tog_mutex);
1704 if (errcode)
1705 return got_error_set_errno(errcode,
1706 "pthread_mutex_unlock");
1707 sched_yield();
1708 errcode = pthread_mutex_lock(&tog_mutex);
1709 if (errcode)
1710 return got_error_set_errno(errcode,
1711 "pthread_mutex_lock");
1712 view->search_next(view);
1713 return NULL;
1716 /* Allow threads to make progress while we are waiting for input. */
1717 errcode = pthread_mutex_unlock(&tog_mutex);
1718 if (errcode)
1719 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1721 if (using_mock_io) {
1722 err = tog_read_script_key(tog_io.f, view, &ch, done);
1723 if (err) {
1724 errcode = pthread_mutex_lock(&tog_mutex);
1725 return err;
1727 } else if (view->count && --view->count) {
1728 cbreak();
1729 nodelay(view->window, TRUE);
1730 ch = wgetch(view->window);
1731 /* let C-g or backspace abort unfinished count */
1732 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1733 view->count = 0;
1734 else
1735 ch = view->ch;
1736 } else {
1737 ch = wgetch(view->window);
1738 if (ch >= '1' && ch <= '9')
1739 view->ch = ch = get_compound_key(view, ch);
1741 if (view->hiline && ch != ERR && ch != 0)
1742 view->hiline = 0; /* key pressed, clear line highlight */
1743 nodelay(view->window, TRUE);
1744 errcode = pthread_mutex_lock(&tog_mutex);
1745 if (errcode)
1746 return got_error_set_errno(errcode, "pthread_mutex_lock");
1748 if (tog_sigwinch_received || tog_sigcont_received) {
1749 tog_resizeterm();
1750 tog_sigwinch_received = 0;
1751 tog_sigcont_received = 0;
1752 TAILQ_FOREACH(v, views, entry) {
1753 err = view_resize(v);
1754 if (err)
1755 return err;
1756 err = v->input(new, v, KEY_RESIZE);
1757 if (err)
1758 return err;
1759 if (v->child) {
1760 err = view_resize(v->child);
1761 if (err)
1762 return err;
1763 err = v->child->input(new, v->child,
1764 KEY_RESIZE);
1765 if (err)
1766 return err;
1767 if (v->child->resized_x || v->child->resized_y) {
1768 err = view_resize_split(v, 0);
1769 if (err)
1770 return err;
1776 switch (ch) {
1777 case '?':
1778 case 'H':
1779 case KEY_F(1):
1780 if (view->type == TOG_VIEW_HELP)
1781 err = view->reset(view);
1782 else
1783 err = view_request_new(new, view, TOG_VIEW_HELP);
1784 break;
1785 case '\t':
1786 view->count = 0;
1787 if (view->child) {
1788 view->focussed = 0;
1789 view->child->focussed = 1;
1790 view->focus_child = 1;
1791 } else if (view->parent) {
1792 view->focussed = 0;
1793 view->parent->focussed = 1;
1794 view->parent->focus_child = 0;
1795 if (!view_is_splitscreen(view)) {
1796 if (view->parent->resize) {
1797 err = view->parent->resize(view->parent,
1798 0);
1799 if (err)
1800 return err;
1802 offset_selection_up(view->parent);
1803 err = view_fullscreen(view->parent);
1804 if (err)
1805 return err;
1808 break;
1809 case 'q':
1810 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1811 if (view->parent->resize) {
1812 /* might need more commits to fill fullscreen */
1813 err = view->parent->resize(view->parent, 0);
1814 if (err)
1815 break;
1817 offset_selection_up(view->parent);
1819 err = view->input(new, view, ch);
1820 view->dying = 1;
1821 break;
1822 case 'Q':
1823 *done = 1;
1824 break;
1825 case 'F':
1826 view->count = 0;
1827 if (view_is_parent_view(view)) {
1828 if (view->child == NULL)
1829 break;
1830 if (view_is_splitscreen(view->child)) {
1831 view->focussed = 0;
1832 view->child->focussed = 1;
1833 err = view_fullscreen(view->child);
1834 } else {
1835 err = view_splitscreen(view->child);
1836 if (!err)
1837 err = view_resize_split(view, 0);
1839 if (err)
1840 break;
1841 err = view->child->input(new, view->child,
1842 KEY_RESIZE);
1843 } else {
1844 if (view_is_splitscreen(view)) {
1845 view->parent->focussed = 0;
1846 view->focussed = 1;
1847 err = view_fullscreen(view);
1848 } else {
1849 err = view_splitscreen(view);
1850 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1851 err = view_resize(view->parent);
1852 if (!err)
1853 err = view_resize_split(view, 0);
1855 if (err)
1856 break;
1857 err = view->input(new, view, KEY_RESIZE);
1859 if (err)
1860 break;
1861 if (view->resize) {
1862 err = view->resize(view, 0);
1863 if (err)
1864 break;
1866 if (view->parent) {
1867 if (view->parent->resize) {
1868 err = view->parent->resize(view->parent, 0);
1869 if (err != NULL)
1870 break;
1872 err = offset_selection_down(view->parent);
1873 if (err != NULL)
1874 break;
1876 err = offset_selection_down(view);
1877 break;
1878 case 'S':
1879 view->count = 0;
1880 err = switch_split(view);
1881 break;
1882 case '-':
1883 err = view_resize_split(view, -1);
1884 break;
1885 case '+':
1886 err = view_resize_split(view, 1);
1887 break;
1888 case KEY_RESIZE:
1889 break;
1890 case '/':
1891 view->count = 0;
1892 if (view->search_start)
1893 view_search_start(view, fast_refresh);
1894 else
1895 err = view->input(new, view, ch);
1896 break;
1897 case 'N':
1898 case 'n':
1899 if (view->search_started && view->search_next) {
1900 view->searching = (ch == 'n' ?
1901 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1902 view->search_next_done = 0;
1903 view->search_next(view);
1904 } else
1905 err = view->input(new, view, ch);
1906 break;
1907 case 'A':
1908 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1909 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1910 view->action = "Patience diff algorithm";
1911 } else {
1912 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1913 view->action = "Myers diff algorithm";
1915 TAILQ_FOREACH(v, views, entry) {
1916 if (v->reset) {
1917 err = v->reset(v);
1918 if (err)
1919 return err;
1921 if (v->child && v->child->reset) {
1922 err = v->child->reset(v->child);
1923 if (err)
1924 return err;
1927 break;
1928 case TOG_KEY_SCRDUMP:
1929 err = screendump(view);
1930 break;
1931 default:
1932 err = view->input(new, view, ch);
1933 break;
1936 return err;
1939 static int
1940 view_needs_focus_indication(struct tog_view *view)
1942 if (view_is_parent_view(view)) {
1943 if (view->child == NULL || view->child->focussed)
1944 return 0;
1945 if (!view_is_splitscreen(view->child))
1946 return 0;
1947 } else if (!view_is_splitscreen(view))
1948 return 0;
1950 return view->focussed;
1953 static const struct got_error *
1954 tog_io_close(void)
1956 const struct got_error *err = NULL;
1958 if (tog_io.cin && fclose(tog_io.cin) == EOF)
1959 err = got_ferror(tog_io.cin, GOT_ERR_IO);
1960 if (tog_io.cout && fclose(tog_io.cout) == EOF && err == NULL)
1961 err = got_ferror(tog_io.cout, GOT_ERR_IO);
1962 if (tog_io.f && fclose(tog_io.f) == EOF && err == NULL)
1963 err = got_ferror(tog_io.f, GOT_ERR_IO);
1964 if (tog_io.sdump && fclose(tog_io.sdump) == EOF && err == NULL)
1965 err = got_ferror(tog_io.sdump, GOT_ERR_IO);
1967 return err;
1970 static const struct got_error *
1971 view_loop(struct tog_view *view)
1973 const struct got_error *err = NULL;
1974 struct tog_view_list_head views;
1975 struct tog_view *new_view;
1976 char *mode;
1977 int fast_refresh = 10;
1978 int done = 0, errcode;
1980 mode = getenv("TOG_VIEW_SPLIT_MODE");
1981 if (!mode || !(*mode == 'h' || *mode == 'H'))
1982 view->mode = TOG_VIEW_SPLIT_VERT;
1983 else
1984 view->mode = TOG_VIEW_SPLIT_HRZN;
1986 errcode = pthread_mutex_lock(&tog_mutex);
1987 if (errcode)
1988 return got_error_set_errno(errcode, "pthread_mutex_lock");
1990 TAILQ_INIT(&views);
1991 TAILQ_INSERT_HEAD(&views, view, entry);
1993 view->focussed = 1;
1994 err = view->show(view);
1995 if (err)
1996 return err;
1997 update_panels();
1998 doupdate();
1999 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
2000 !tog_fatal_signal_received()) {
2001 /* Refresh fast during initialization, then become slower. */
2002 if (fast_refresh && --fast_refresh == 0 && !using_mock_io)
2003 halfdelay(10); /* switch to once per second */
2005 err = view_input(&new_view, &done, view, &views, fast_refresh);
2006 if (err)
2007 break;
2009 if (view->dying && view == TAILQ_FIRST(&views) &&
2010 TAILQ_NEXT(view, entry) == NULL)
2011 done = 1;
2012 if (done) {
2013 struct tog_view *v;
2016 * When we quit, scroll the screen up a single line
2017 * so we don't lose any information.
2019 TAILQ_FOREACH(v, &views, entry) {
2020 wmove(v->window, 0, 0);
2021 wdeleteln(v->window);
2022 wnoutrefresh(v->window);
2023 if (v->child && !view_is_fullscreen(v)) {
2024 wmove(v->child->window, 0, 0);
2025 wdeleteln(v->child->window);
2026 wnoutrefresh(v->child->window);
2029 doupdate();
2032 if (view->dying) {
2033 struct tog_view *v, *prev = NULL;
2035 if (view_is_parent_view(view))
2036 prev = TAILQ_PREV(view, tog_view_list_head,
2037 entry);
2038 else if (view->parent)
2039 prev = view->parent;
2041 if (view->parent) {
2042 view->parent->child = NULL;
2043 view->parent->focus_child = 0;
2044 /* Restore fullscreen line height. */
2045 view->parent->nlines = view->parent->lines;
2046 err = view_resize(view->parent);
2047 if (err)
2048 break;
2049 /* Make resized splits persist. */
2050 view_transfer_size(view->parent, view);
2051 } else
2052 TAILQ_REMOVE(&views, view, entry);
2054 err = view_close(view);
2055 if (err)
2056 goto done;
2058 view = NULL;
2059 TAILQ_FOREACH(v, &views, entry) {
2060 if (v->focussed)
2061 break;
2063 if (view == NULL && new_view == NULL) {
2064 /* No view has focus. Try to pick one. */
2065 if (prev)
2066 view = prev;
2067 else if (!TAILQ_EMPTY(&views)) {
2068 view = TAILQ_LAST(&views,
2069 tog_view_list_head);
2071 if (view) {
2072 if (view->focus_child) {
2073 view->child->focussed = 1;
2074 view = view->child;
2075 } else
2076 view->focussed = 1;
2080 if (new_view) {
2081 struct tog_view *v, *t;
2082 /* Only allow one parent view per type. */
2083 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2084 if (v->type != new_view->type)
2085 continue;
2086 TAILQ_REMOVE(&views, v, entry);
2087 err = view_close(v);
2088 if (err)
2089 goto done;
2090 break;
2092 TAILQ_INSERT_TAIL(&views, new_view, entry);
2093 view = new_view;
2095 if (view && !done) {
2096 if (view_is_parent_view(view)) {
2097 if (view->child && view->child->focussed)
2098 view = view->child;
2099 } else {
2100 if (view->parent && view->parent->focussed)
2101 view = view->parent;
2103 show_panel(view->panel);
2104 if (view->child && view_is_splitscreen(view->child))
2105 show_panel(view->child->panel);
2106 if (view->parent && view_is_splitscreen(view)) {
2107 err = view->parent->show(view->parent);
2108 if (err)
2109 goto done;
2111 err = view->show(view);
2112 if (err)
2113 goto done;
2114 if (view->child) {
2115 err = view->child->show(view->child);
2116 if (err)
2117 goto done;
2119 update_panels();
2120 doupdate();
2123 done:
2124 while (!TAILQ_EMPTY(&views)) {
2125 const struct got_error *close_err;
2126 view = TAILQ_FIRST(&views);
2127 TAILQ_REMOVE(&views, view, entry);
2128 close_err = view_close(view);
2129 if (close_err && err == NULL)
2130 err = close_err;
2133 errcode = pthread_mutex_unlock(&tog_mutex);
2134 if (errcode && err == NULL)
2135 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2137 return err;
2140 __dead static void
2141 usage_log(void)
2143 endwin();
2144 fprintf(stderr,
2145 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2146 getprogname());
2147 exit(1);
2150 /* Create newly allocated wide-character string equivalent to a byte string. */
2151 static const struct got_error *
2152 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2154 char *vis = NULL;
2155 const struct got_error *err = NULL;
2157 *ws = NULL;
2158 *wlen = mbstowcs(NULL, s, 0);
2159 if (*wlen == (size_t)-1) {
2160 int vislen;
2161 if (errno != EILSEQ)
2162 return got_error_from_errno("mbstowcs");
2164 /* byte string invalid in current encoding; try to "fix" it */
2165 err = got_mbsavis(&vis, &vislen, s);
2166 if (err)
2167 return err;
2168 *wlen = mbstowcs(NULL, vis, 0);
2169 if (*wlen == (size_t)-1) {
2170 err = got_error_from_errno("mbstowcs"); /* give up */
2171 goto done;
2175 *ws = calloc(*wlen + 1, sizeof(**ws));
2176 if (*ws == NULL) {
2177 err = got_error_from_errno("calloc");
2178 goto done;
2181 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2182 err = got_error_from_errno("mbstowcs");
2183 done:
2184 free(vis);
2185 if (err) {
2186 free(*ws);
2187 *ws = NULL;
2188 *wlen = 0;
2190 return err;
2193 static const struct got_error *
2194 expand_tab(char **ptr, const char *src)
2196 char *dst;
2197 size_t len, n, idx = 0, sz = 0;
2199 *ptr = NULL;
2200 n = len = strlen(src);
2201 dst = malloc(n + 1);
2202 if (dst == NULL)
2203 return got_error_from_errno("malloc");
2205 while (idx < len && src[idx]) {
2206 const char c = src[idx];
2208 if (c == '\t') {
2209 size_t nb = TABSIZE - sz % TABSIZE;
2210 char *p;
2212 p = realloc(dst, n + nb);
2213 if (p == NULL) {
2214 free(dst);
2215 return got_error_from_errno("realloc");
2218 dst = p;
2219 n += nb;
2220 memset(dst + sz, ' ', nb);
2221 sz += nb;
2222 } else
2223 dst[sz++] = src[idx];
2224 ++idx;
2227 dst[sz] = '\0';
2228 *ptr = dst;
2229 return NULL;
2233 * Advance at most n columns from wline starting at offset off.
2234 * Return the index to the first character after the span operation.
2235 * Return the combined column width of all spanned wide characters in
2236 * *rcol.
2238 static int
2239 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2241 int width, i, cols = 0;
2243 if (n == 0) {
2244 *rcol = cols;
2245 return off;
2248 for (i = off; wline[i] != L'\0'; ++i) {
2249 if (wline[i] == L'\t')
2250 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2251 else
2252 width = wcwidth(wline[i]);
2254 if (width == -1) {
2255 width = 1;
2256 wline[i] = L'.';
2259 if (cols + width > n)
2260 break;
2261 cols += width;
2264 *rcol = cols;
2265 return i;
2269 * Format a line for display, ensuring that it won't overflow a width limit.
2270 * With scrolling, the width returned refers to the scrolled version of the
2271 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2273 static const struct got_error *
2274 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2275 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2277 const struct got_error *err = NULL;
2278 int cols;
2279 wchar_t *wline = NULL;
2280 char *exstr = NULL;
2281 size_t wlen;
2282 int i, scrollx;
2284 *wlinep = NULL;
2285 *widthp = 0;
2287 if (expand) {
2288 err = expand_tab(&exstr, line);
2289 if (err)
2290 return err;
2293 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2294 free(exstr);
2295 if (err)
2296 return err;
2298 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2300 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2301 wline[wlen - 1] = L'\0';
2302 wlen--;
2304 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2305 wline[wlen - 1] = L'\0';
2306 wlen--;
2309 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2310 wline[i] = L'\0';
2312 if (widthp)
2313 *widthp = cols;
2314 if (scrollxp)
2315 *scrollxp = scrollx;
2316 if (err)
2317 free(wline);
2318 else
2319 *wlinep = wline;
2320 return err;
2323 static const struct got_error*
2324 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2325 struct got_object_id *id, struct got_repository *repo)
2327 static const struct got_error *err = NULL;
2328 struct got_reflist_entry *re;
2329 char *s;
2330 const char *name;
2332 *refs_str = NULL;
2334 if (refs == NULL)
2335 return NULL;
2337 TAILQ_FOREACH(re, refs, entry) {
2338 struct got_tag_object *tag = NULL;
2339 struct got_object_id *ref_id;
2340 int cmp;
2342 name = got_ref_get_name(re->ref);
2343 if (strcmp(name, GOT_REF_HEAD) == 0)
2344 continue;
2345 if (strncmp(name, "refs/", 5) == 0)
2346 name += 5;
2347 if (strncmp(name, "got/", 4) == 0)
2348 continue;
2349 if (strncmp(name, "heads/", 6) == 0)
2350 name += 6;
2351 if (strncmp(name, "remotes/", 8) == 0) {
2352 name += 8;
2353 s = strstr(name, "/" GOT_REF_HEAD);
2354 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
2355 continue;
2357 err = got_ref_resolve(&ref_id, repo, re->ref);
2358 if (err)
2359 break;
2360 if (strncmp(name, "tags/", 5) == 0) {
2361 err = got_object_open_as_tag(&tag, repo, ref_id);
2362 if (err) {
2363 if (err->code != GOT_ERR_OBJ_TYPE) {
2364 free(ref_id);
2365 break;
2367 /* Ref points at something other than a tag. */
2368 err = NULL;
2369 tag = NULL;
2372 cmp = got_object_id_cmp(tag ?
2373 got_object_tag_get_object_id(tag) : ref_id, id);
2374 free(ref_id);
2375 if (tag)
2376 got_object_tag_close(tag);
2377 if (cmp != 0)
2378 continue;
2379 s = *refs_str;
2380 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2381 s ? ", " : "", name) == -1) {
2382 err = got_error_from_errno("asprintf");
2383 free(s);
2384 *refs_str = NULL;
2385 break;
2387 free(s);
2390 return err;
2393 static const struct got_error *
2394 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2395 int col_tab_align)
2397 char *smallerthan;
2399 smallerthan = strchr(author, '<');
2400 if (smallerthan && smallerthan[1] != '\0')
2401 author = smallerthan + 1;
2402 author[strcspn(author, "@>")] = '\0';
2403 return format_line(wauthor, author_width, NULL, author, 0, limit,
2404 col_tab_align, 0);
2407 static const struct got_error *
2408 draw_commit(struct tog_view *view, struct commit_queue_entry *entry,
2409 const size_t date_display_cols, int author_display_cols)
2411 struct tog_log_view_state *s = &view->state.log;
2412 const struct got_error *err = NULL;
2413 struct got_commit_object *commit = entry->commit;
2414 struct got_object_id *id = entry->id;
2415 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2416 char *refs_str = NULL;
2417 char *logmsg0 = NULL, *logmsg = NULL;
2418 char *author = NULL;
2419 wchar_t *wrefstr = NULL, *wlogmsg = NULL, *wauthor = NULL;
2420 int author_width, refstr_width, logmsg_width;
2421 char *newline, *line = NULL;
2422 int col, limit, scrollx, logmsg_x;
2423 const int avail = view->ncols, marker_column = author_display_cols + 1;
2424 struct tm tm;
2425 time_t committer_time;
2426 struct tog_color *tc;
2427 struct got_reflist_head *refs;
2429 if (tog_base_commit.id != NULL && tog_base_commit.idx == -1 &&
2430 got_object_id_cmp(id, tog_base_commit.id) == 0)
2431 tog_base_commit.idx = entry->idx;
2433 committer_time = got_object_commit_get_committer_time(commit);
2434 if (gmtime_r(&committer_time, &tm) == NULL)
2435 return got_error_from_errno("gmtime_r");
2436 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2437 return got_error(GOT_ERR_NO_SPACE);
2439 if (avail <= date_display_cols)
2440 limit = MIN(sizeof(datebuf) - 1, avail);
2441 else
2442 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2443 tc = get_color(&s->colors, TOG_COLOR_DATE);
2444 if (tc)
2445 wattr_on(view->window,
2446 COLOR_PAIR(tc->colorpair), NULL);
2447 waddnstr(view->window, datebuf, limit);
2448 if (tc)
2449 wattr_off(view->window,
2450 COLOR_PAIR(tc->colorpair), NULL);
2451 col = limit;
2452 if (col > avail)
2453 goto done;
2455 if (avail >= 120) {
2456 char *id_str;
2457 err = got_object_id_str(&id_str, id);
2458 if (err)
2459 goto done;
2460 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2461 if (tc)
2462 wattr_on(view->window,
2463 COLOR_PAIR(tc->colorpair), NULL);
2464 wprintw(view->window, "%.8s ", id_str);
2465 if (tc)
2466 wattr_off(view->window,
2467 COLOR_PAIR(tc->colorpair), NULL);
2468 free(id_str);
2469 col += 9;
2470 if (col > avail)
2471 goto done;
2474 if (s->use_committer)
2475 author = strdup(got_object_commit_get_committer(commit));
2476 else
2477 author = strdup(got_object_commit_get_author(commit));
2478 if (author == NULL) {
2479 err = got_error_from_errno("strdup");
2480 goto done;
2482 err = format_author(&wauthor, &author_width, author, avail - col, col);
2483 if (err)
2484 goto done;
2485 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2486 if (tc)
2487 wattr_on(view->window,
2488 COLOR_PAIR(tc->colorpair), NULL);
2489 waddwstr(view->window, wauthor);
2490 col += author_width;
2491 while (col < avail && author_width < author_display_cols + 2) {
2492 if (tog_base_commit.marker != GOT_WORKTREE_STATE_UNKNOWN &&
2493 author_width == marker_column &&
2494 entry->idx == tog_base_commit.idx) {
2495 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2496 if (tc)
2497 wattr_on(view->window,
2498 COLOR_PAIR(tc->colorpair), NULL);
2499 waddch(view->window, tog_base_commit.marker);
2500 if (tc)
2501 wattr_off(view->window,
2502 COLOR_PAIR(tc->colorpair), NULL);
2503 } else
2504 waddch(view->window, ' ');
2505 col++;
2506 author_width++;
2508 if (tc)
2509 wattr_off(view->window,
2510 COLOR_PAIR(tc->colorpair), NULL);
2511 if (col > avail)
2512 goto done;
2514 err = got_object_commit_get_logmsg(&logmsg0, commit);
2515 if (err)
2516 goto done;
2517 logmsg = logmsg0;
2518 while (*logmsg == '\n')
2519 logmsg++;
2520 newline = strchr(logmsg, '\n');
2521 if (newline)
2522 *newline = '\0';
2524 limit = avail - col;
2525 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2526 limit--; /* for the border */
2528 /* Prepend reference labels to log message if possible .*/
2529 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, id);
2530 err = build_refs_str(&refs_str, refs, id, s->repo);
2531 if (err)
2532 goto done;
2533 if (refs_str) {
2534 char *rs;
2536 if (asprintf(&rs, "[%s]", refs_str) == -1) {
2537 err = got_error_from_errno("asprintf");
2538 goto done;
2540 err = format_line(&wrefstr, &refstr_width,
2541 &scrollx, rs, view->x, limit, col, 1);
2542 free(rs);
2543 if (err)
2544 goto done;
2545 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2546 if (tc)
2547 wattr_on(view->window,
2548 COLOR_PAIR(tc->colorpair), NULL);
2549 waddwstr(view->window, &wrefstr[scrollx]);
2550 if (tc)
2551 wattr_off(view->window,
2552 COLOR_PAIR(tc->colorpair), NULL);
2553 col += MAX(refstr_width, 0);
2554 if (col > avail)
2555 goto done;
2557 if (col < avail) {
2558 waddch(view->window, ' ');
2559 col++;
2562 if (refstr_width > 0)
2563 logmsg_x = 0;
2564 else {
2565 int unscrolled_refstr_width;
2566 size_t len = wcslen(wrefstr);
2569 * No need to check for -1 return value here since
2570 * unprintables have been replaced by span_wline().
2572 unscrolled_refstr_width = wcswidth(wrefstr, len);
2573 unscrolled_refstr_width += 1; /* trailing space */
2574 logmsg_x = view->x - unscrolled_refstr_width;
2577 limit = avail - col;
2578 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2579 limit--; /* for the border */
2580 } else
2581 logmsg_x = view->x;
2583 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, logmsg_x,
2584 limit, col, 1);
2585 if (err)
2586 goto done;
2587 waddwstr(view->window, &wlogmsg[scrollx]);
2588 col += MAX(logmsg_width, 0);
2589 while (col < avail) {
2590 waddch(view->window, ' ');
2591 col++;
2593 done:
2594 free(logmsg0);
2595 free(wlogmsg);
2596 free(wrefstr);
2597 free(refs_str);
2598 free(author);
2599 free(wauthor);
2600 free(line);
2601 return err;
2604 static struct commit_queue_entry *
2605 alloc_commit_queue_entry(struct got_commit_object *commit,
2606 struct got_object_id *id)
2608 struct commit_queue_entry *entry;
2609 struct got_object_id *dup;
2611 entry = calloc(1, sizeof(*entry));
2612 if (entry == NULL)
2613 return NULL;
2615 dup = got_object_id_dup(id);
2616 if (dup == NULL) {
2617 free(entry);
2618 return NULL;
2621 entry->id = dup;
2622 entry->commit = commit;
2623 return entry;
2626 static void
2627 pop_commit(struct commit_queue *commits)
2629 struct commit_queue_entry *entry;
2631 entry = TAILQ_FIRST(&commits->head);
2632 TAILQ_REMOVE(&commits->head, entry, entry);
2633 got_object_commit_close(entry->commit);
2634 commits->ncommits--;
2635 free(entry->id);
2636 free(entry);
2639 static void
2640 free_commits(struct commit_queue *commits)
2642 while (!TAILQ_EMPTY(&commits->head))
2643 pop_commit(commits);
2646 static const struct got_error *
2647 match_commit(int *have_match, struct got_object_id *id,
2648 struct got_commit_object *commit, regex_t *regex)
2650 const struct got_error *err = NULL;
2651 regmatch_t regmatch;
2652 char *id_str = NULL, *logmsg = NULL;
2654 *have_match = 0;
2656 err = got_object_id_str(&id_str, id);
2657 if (err)
2658 return err;
2660 err = got_object_commit_get_logmsg(&logmsg, commit);
2661 if (err)
2662 goto done;
2664 if (regexec(regex, got_object_commit_get_author(commit), 1,
2665 &regmatch, 0) == 0 ||
2666 regexec(regex, got_object_commit_get_committer(commit), 1,
2667 &regmatch, 0) == 0 ||
2668 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2669 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2670 *have_match = 1;
2671 done:
2672 free(id_str);
2673 free(logmsg);
2674 return err;
2677 static const struct got_error *
2678 queue_commits(struct tog_log_thread_args *a)
2680 const struct got_error *err = NULL;
2683 * We keep all commits open throughout the lifetime of the log
2684 * view in order to avoid having to re-fetch commits from disk
2685 * while updating the display.
2687 do {
2688 struct got_object_id id;
2689 struct got_commit_object *commit;
2690 struct commit_queue_entry *entry;
2691 int limit_match = 0;
2692 int errcode;
2694 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2695 NULL, NULL);
2696 if (err)
2697 break;
2699 err = got_object_open_as_commit(&commit, a->repo, &id);
2700 if (err)
2701 break;
2702 entry = alloc_commit_queue_entry(commit, &id);
2703 if (entry == NULL) {
2704 err = got_error_from_errno("alloc_commit_queue_entry");
2705 break;
2708 errcode = pthread_mutex_lock(&tog_mutex);
2709 if (errcode) {
2710 err = got_error_set_errno(errcode,
2711 "pthread_mutex_lock");
2712 break;
2715 entry->idx = a->real_commits->ncommits;
2716 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2717 a->real_commits->ncommits++;
2719 if (*a->limiting) {
2720 err = match_commit(&limit_match, &id, commit,
2721 a->limit_regex);
2722 if (err)
2723 break;
2725 if (limit_match) {
2726 struct commit_queue_entry *matched;
2728 matched = alloc_commit_queue_entry(
2729 entry->commit, entry->id);
2730 if (matched == NULL) {
2731 err = got_error_from_errno(
2732 "alloc_commit_queue_entry");
2733 break;
2735 matched->commit = entry->commit;
2736 got_object_commit_retain(entry->commit);
2738 matched->idx = a->limit_commits->ncommits;
2739 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2740 matched, entry);
2741 a->limit_commits->ncommits++;
2745 * This is how we signal log_thread() that we
2746 * have found a match, and that it should be
2747 * counted as a new entry for the view.
2749 a->limit_match = limit_match;
2752 if (*a->searching == TOG_SEARCH_FORWARD &&
2753 !*a->search_next_done) {
2754 int have_match;
2755 err = match_commit(&have_match, &id, commit, a->regex);
2756 if (err)
2757 break;
2759 if (*a->limiting) {
2760 if (limit_match && have_match)
2761 *a->search_next_done =
2762 TOG_SEARCH_HAVE_MORE;
2763 } else if (have_match)
2764 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2767 errcode = pthread_mutex_unlock(&tog_mutex);
2768 if (errcode && err == NULL)
2769 err = got_error_set_errno(errcode,
2770 "pthread_mutex_unlock");
2771 if (err)
2772 break;
2773 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2775 return err;
2778 static void
2779 select_commit(struct tog_log_view_state *s)
2781 struct commit_queue_entry *entry;
2782 int ncommits = 0;
2784 entry = s->first_displayed_entry;
2785 while (entry) {
2786 if (ncommits == s->selected) {
2787 s->selected_entry = entry;
2788 break;
2790 entry = TAILQ_NEXT(entry, entry);
2791 ncommits++;
2795 static const struct got_error *
2796 draw_commits(struct tog_view *view)
2798 const struct got_error *err = NULL;
2799 struct tog_log_view_state *s = &view->state.log;
2800 struct commit_queue_entry *entry = s->selected_entry;
2801 int limit = view->nlines;
2802 int width;
2803 int ncommits, author_cols = 4, refstr_cols;
2804 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2805 char *refs_str = NULL;
2806 wchar_t *wline;
2807 struct tog_color *tc;
2808 static const size_t date_display_cols = 12;
2809 struct got_reflist_head *refs;
2811 if (view_is_hsplit_top(view))
2812 --limit; /* account for border */
2814 if (s->selected_entry &&
2815 !(view->searching && view->search_next_done == 0)) {
2816 err = got_object_id_str(&id_str, s->selected_entry->id);
2817 if (err)
2818 return err;
2819 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2820 s->selected_entry->id);
2821 err = build_refs_str(&refs_str, refs, s->selected_entry->id,
2822 s->repo);
2823 if (err)
2824 goto done;
2827 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2828 halfdelay(10); /* disable fast refresh */
2830 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2831 if (asprintf(&ncommits_str, " [%d/%d] %s",
2832 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2833 (view->searching && !view->search_next_done) ?
2834 "searching..." : "loading...") == -1) {
2835 err = got_error_from_errno("asprintf");
2836 goto done;
2838 } else {
2839 const char *search_str = NULL;
2840 const char *limit_str = NULL;
2842 if (view->searching) {
2843 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2844 search_str = "no more matches";
2845 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2846 search_str = "no matches found";
2847 else if (!view->search_next_done)
2848 search_str = "searching...";
2851 if (s->limit_view && s->commits->ncommits == 0)
2852 limit_str = "no matches found";
2854 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2855 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2856 search_str ? search_str : (refs_str ? refs_str : ""),
2857 limit_str ? limit_str : "") == -1) {
2858 err = got_error_from_errno("asprintf");
2859 goto done;
2863 free(refs_str);
2864 refs_str = NULL;
2866 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2867 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2868 "........................................",
2869 s->in_repo_path, ncommits_str) == -1) {
2870 err = got_error_from_errno("asprintf");
2871 header = NULL;
2872 goto done;
2874 } else if (asprintf(&header, "commit %s%s",
2875 id_str ? id_str : "........................................",
2876 ncommits_str) == -1) {
2877 err = got_error_from_errno("asprintf");
2878 header = NULL;
2879 goto done;
2881 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2882 if (err)
2883 goto done;
2885 werase(view->window);
2887 if (view_needs_focus_indication(view))
2888 wstandout(view->window);
2889 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2890 if (tc)
2891 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2892 waddwstr(view->window, wline);
2893 while (width < view->ncols) {
2894 waddch(view->window, ' ');
2895 width++;
2897 if (tc)
2898 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2899 if (view_needs_focus_indication(view))
2900 wstandend(view->window);
2901 free(wline);
2902 if (limit <= 1)
2903 goto done;
2905 /* Grow author column size if necessary, and set view->maxx. */
2906 entry = s->first_displayed_entry;
2907 ncommits = 0;
2908 view->maxx = 0;
2909 while (entry) {
2910 struct got_commit_object *c = entry->commit;
2911 char *author, *eol, *msg, *msg0;
2912 wchar_t *wauthor, *wmsg;
2913 int width;
2914 if (ncommits >= limit - 1)
2915 break;
2916 if (s->use_committer)
2917 author = strdup(got_object_commit_get_committer(c));
2918 else
2919 author = strdup(got_object_commit_get_author(c));
2920 if (author == NULL) {
2921 err = got_error_from_errno("strdup");
2922 goto done;
2924 err = format_author(&wauthor, &width, author, COLS,
2925 date_display_cols);
2926 if (author_cols < width)
2927 author_cols = width;
2928 free(wauthor);
2929 free(author);
2930 if (err)
2931 goto done;
2932 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2933 entry->id);
2934 err = build_refs_str(&refs_str, refs, entry->id, s->repo);
2935 if (err)
2936 goto done;
2937 if (refs_str) {
2938 wchar_t *ws;
2939 err = format_line(&ws, &width, NULL, refs_str,
2940 0, INT_MAX, date_display_cols + author_cols, 0);
2941 free(ws);
2942 free(refs_str);
2943 refs_str = NULL;
2944 if (err)
2945 goto done;
2946 refstr_cols = width + 3; /* account for [ ] + space */
2947 } else
2948 refstr_cols = 0;
2949 err = got_object_commit_get_logmsg(&msg0, c);
2950 if (err)
2951 goto done;
2952 msg = msg0;
2953 while (*msg == '\n')
2954 ++msg;
2955 if ((eol = strchr(msg, '\n')))
2956 *eol = '\0';
2957 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2958 date_display_cols + author_cols + refstr_cols, 0);
2959 if (err)
2960 goto done;
2961 view->maxx = MAX(view->maxx, width + refstr_cols);
2962 free(msg0);
2963 free(wmsg);
2964 ncommits++;
2965 entry = TAILQ_NEXT(entry, entry);
2968 entry = s->first_displayed_entry;
2969 s->last_displayed_entry = s->first_displayed_entry;
2970 ncommits = 0;
2971 while (entry) {
2972 if (ncommits >= limit - 1)
2973 break;
2974 if (ncommits == s->selected)
2975 wstandout(view->window);
2976 err = draw_commit(view, entry, date_display_cols, author_cols);
2977 if (ncommits == s->selected)
2978 wstandend(view->window);
2979 if (err)
2980 goto done;
2981 ncommits++;
2982 s->last_displayed_entry = entry;
2983 entry = TAILQ_NEXT(entry, entry);
2986 view_border(view);
2987 done:
2988 free(id_str);
2989 free(refs_str);
2990 free(ncommits_str);
2991 free(header);
2992 return err;
2995 static void
2996 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2998 struct commit_queue_entry *entry;
2999 int nscrolled = 0;
3001 entry = TAILQ_FIRST(&s->commits->head);
3002 if (s->first_displayed_entry == entry)
3003 return;
3005 entry = s->first_displayed_entry;
3006 while (entry && nscrolled < maxscroll) {
3007 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3008 if (entry) {
3009 s->first_displayed_entry = entry;
3010 nscrolled++;
3015 static const struct got_error *
3016 trigger_log_thread(struct tog_view *view, int wait)
3018 struct tog_log_thread_args *ta = &view->state.log.thread_args;
3019 int errcode;
3021 if (!using_mock_io)
3022 halfdelay(1); /* fast refresh while loading commits */
3024 while (!ta->log_complete && !tog_thread_error &&
3025 (ta->commits_needed > 0 || ta->load_all)) {
3026 /* Wake the log thread. */
3027 errcode = pthread_cond_signal(&ta->need_commits);
3028 if (errcode)
3029 return got_error_set_errno(errcode,
3030 "pthread_cond_signal");
3033 * The mutex will be released while the view loop waits
3034 * in wgetch(), at which time the log thread will run.
3036 if (!wait)
3037 break;
3039 /* Display progress update in log view. */
3040 show_log_view(view);
3041 update_panels();
3042 doupdate();
3044 /* Wait right here while next commit is being loaded. */
3045 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
3046 if (errcode)
3047 return got_error_set_errno(errcode,
3048 "pthread_cond_wait");
3050 /* Display progress update in log view. */
3051 show_log_view(view);
3052 update_panels();
3053 doupdate();
3056 return NULL;
3059 static const struct got_error *
3060 request_log_commits(struct tog_view *view)
3062 struct tog_log_view_state *state = &view->state.log;
3063 const struct got_error *err = NULL;
3065 if (state->thread_args.log_complete)
3066 return NULL;
3068 state->thread_args.commits_needed += view->nscrolled;
3069 err = trigger_log_thread(view, 1);
3070 view->nscrolled = 0;
3072 return err;
3075 static const struct got_error *
3076 log_scroll_down(struct tog_view *view, int maxscroll)
3078 struct tog_log_view_state *s = &view->state.log;
3079 const struct got_error *err = NULL;
3080 struct commit_queue_entry *pentry;
3081 int nscrolled = 0, ncommits_needed;
3083 if (s->last_displayed_entry == NULL)
3084 return NULL;
3086 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
3087 if (s->commits->ncommits < ncommits_needed &&
3088 !s->thread_args.log_complete) {
3090 * Ask the log thread for required amount of commits.
3092 s->thread_args.commits_needed +=
3093 ncommits_needed - s->commits->ncommits;
3094 err = trigger_log_thread(view, 1);
3095 if (err)
3096 return err;
3099 do {
3100 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
3101 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
3102 break;
3104 s->last_displayed_entry = pentry ?
3105 pentry : s->last_displayed_entry;
3107 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
3108 if (pentry == NULL)
3109 break;
3110 s->first_displayed_entry = pentry;
3111 } while (++nscrolled < maxscroll);
3113 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
3114 view->nscrolled += nscrolled;
3115 else
3116 view->nscrolled = 0;
3118 return err;
3121 static const struct got_error *
3122 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
3123 struct got_commit_object *commit, struct got_object_id *commit_id,
3124 struct tog_view *log_view, struct got_repository *repo)
3126 const struct got_error *err;
3127 struct got_object_qid *parent_id;
3128 struct tog_view *diff_view;
3130 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3131 if (diff_view == NULL)
3132 return got_error_from_errno("view_open");
3134 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3135 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3136 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3137 if (err == NULL)
3138 *new_view = diff_view;
3139 return err;
3142 static const struct got_error *
3143 tree_view_visit_subtree(struct tog_tree_view_state *s,
3144 struct got_tree_object *subtree)
3146 struct tog_parent_tree *parent;
3148 parent = calloc(1, sizeof(*parent));
3149 if (parent == NULL)
3150 return got_error_from_errno("calloc");
3152 parent->tree = s->tree;
3153 parent->first_displayed_entry = s->first_displayed_entry;
3154 parent->selected_entry = s->selected_entry;
3155 parent->selected = s->selected;
3156 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3157 s->tree = subtree;
3158 s->selected = 0;
3159 s->first_displayed_entry = NULL;
3160 return NULL;
3163 static const struct got_error *
3164 tree_view_walk_path(struct tog_tree_view_state *s,
3165 struct got_commit_object *commit, const char *path)
3167 const struct got_error *err = NULL;
3168 struct got_tree_object *tree = NULL;
3169 const char *p;
3170 char *slash, *subpath = NULL;
3172 /* Walk the path and open corresponding tree objects. */
3173 p = path;
3174 while (*p) {
3175 struct got_tree_entry *te;
3176 struct got_object_id *tree_id;
3177 char *te_name;
3179 while (p[0] == '/')
3180 p++;
3182 /* Ensure the correct subtree entry is selected. */
3183 slash = strchr(p, '/');
3184 if (slash == NULL)
3185 te_name = strdup(p);
3186 else
3187 te_name = strndup(p, slash - p);
3188 if (te_name == NULL) {
3189 err = got_error_from_errno("strndup");
3190 break;
3192 te = got_object_tree_find_entry(s->tree, te_name);
3193 if (te == NULL) {
3194 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3195 free(te_name);
3196 break;
3198 free(te_name);
3199 s->first_displayed_entry = s->selected_entry = te;
3201 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3202 break; /* jump to this file's entry */
3204 slash = strchr(p, '/');
3205 if (slash)
3206 subpath = strndup(path, slash - path);
3207 else
3208 subpath = strdup(path);
3209 if (subpath == NULL) {
3210 err = got_error_from_errno("strdup");
3211 break;
3214 err = got_object_id_by_path(&tree_id, s->repo, commit,
3215 subpath);
3216 if (err)
3217 break;
3219 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3220 free(tree_id);
3221 if (err)
3222 break;
3224 err = tree_view_visit_subtree(s, tree);
3225 if (err) {
3226 got_object_tree_close(tree);
3227 break;
3229 if (slash == NULL)
3230 break;
3231 free(subpath);
3232 subpath = NULL;
3233 p = slash;
3236 free(subpath);
3237 return err;
3240 static const struct got_error *
3241 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3242 struct commit_queue_entry *entry, const char *path,
3243 const char *head_ref_name, struct got_repository *repo)
3245 const struct got_error *err = NULL;
3246 struct tog_tree_view_state *s;
3247 struct tog_view *tree_view;
3249 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3250 if (tree_view == NULL)
3251 return got_error_from_errno("view_open");
3253 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3254 if (err)
3255 return err;
3256 s = &tree_view->state.tree;
3258 *new_view = tree_view;
3260 if (got_path_is_root_dir(path))
3261 return NULL;
3263 return tree_view_walk_path(s, entry->commit, path);
3266 static const struct got_error *
3267 block_signals_used_by_main_thread(void)
3269 sigset_t sigset;
3270 int errcode;
3272 if (sigemptyset(&sigset) == -1)
3273 return got_error_from_errno("sigemptyset");
3275 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3276 if (sigaddset(&sigset, SIGWINCH) == -1)
3277 return got_error_from_errno("sigaddset");
3278 if (sigaddset(&sigset, SIGCONT) == -1)
3279 return got_error_from_errno("sigaddset");
3280 if (sigaddset(&sigset, SIGINT) == -1)
3281 return got_error_from_errno("sigaddset");
3282 if (sigaddset(&sigset, SIGTERM) == -1)
3283 return got_error_from_errno("sigaddset");
3285 /* ncurses handles SIGTSTP */
3286 if (sigaddset(&sigset, SIGTSTP) == -1)
3287 return got_error_from_errno("sigaddset");
3289 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3290 if (errcode)
3291 return got_error_set_errno(errcode, "pthread_sigmask");
3293 return NULL;
3296 static void *
3297 log_thread(void *arg)
3299 const struct got_error *err = NULL;
3300 int errcode = 0;
3301 struct tog_log_thread_args *a = arg;
3302 int done = 0;
3305 * Sync startup with main thread such that we begin our
3306 * work once view_input() has released the mutex.
3308 errcode = pthread_mutex_lock(&tog_mutex);
3309 if (errcode) {
3310 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3311 return (void *)err;
3314 err = block_signals_used_by_main_thread();
3315 if (err) {
3316 pthread_mutex_unlock(&tog_mutex);
3317 goto done;
3320 while (!done && !err && !tog_fatal_signal_received()) {
3321 errcode = pthread_mutex_unlock(&tog_mutex);
3322 if (errcode) {
3323 err = got_error_set_errno(errcode,
3324 "pthread_mutex_unlock");
3325 goto done;
3327 err = queue_commits(a);
3328 if (err) {
3329 if (err->code != GOT_ERR_ITER_COMPLETED)
3330 goto done;
3331 err = NULL;
3332 done = 1;
3333 a->commits_needed = 0;
3334 } else if (a->commits_needed > 0 && !a->load_all) {
3335 if (*a->limiting) {
3336 if (a->limit_match)
3337 a->commits_needed--;
3338 } else
3339 a->commits_needed--;
3342 errcode = pthread_mutex_lock(&tog_mutex);
3343 if (errcode) {
3344 err = got_error_set_errno(errcode,
3345 "pthread_mutex_lock");
3346 goto done;
3347 } else if (*a->quit)
3348 done = 1;
3349 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3350 *a->first_displayed_entry =
3351 TAILQ_FIRST(&a->limit_commits->head);
3352 *a->selected_entry = *a->first_displayed_entry;
3353 } else if (*a->first_displayed_entry == NULL) {
3354 *a->first_displayed_entry =
3355 TAILQ_FIRST(&a->real_commits->head);
3356 *a->selected_entry = *a->first_displayed_entry;
3359 errcode = pthread_cond_signal(&a->commit_loaded);
3360 if (errcode) {
3361 err = got_error_set_errno(errcode,
3362 "pthread_cond_signal");
3363 pthread_mutex_unlock(&tog_mutex);
3364 goto done;
3367 if (a->commits_needed == 0 &&
3368 a->need_commit_marker && a->worktree) {
3369 errcode = pthread_mutex_unlock(&tog_mutex);
3370 if (errcode) {
3371 err = got_error_set_errno(errcode,
3372 "pthread_mutex_unlock");
3373 goto done;
3375 err = got_worktree_get_state(&tog_base_commit.marker,
3376 a->repo, a->worktree, NULL, NULL);
3377 if (err)
3378 goto done;
3379 errcode = pthread_mutex_lock(&tog_mutex);
3380 if (errcode) {
3381 err = got_error_set_errno(errcode,
3382 "pthread_mutex_lock");
3383 goto done;
3385 a->need_commit_marker = 0;
3387 * The main thread did not close this
3388 * work tree yet. Close it now.
3390 got_worktree_close(a->worktree);
3391 a->worktree = NULL;
3393 if (*a->quit)
3394 done = 1;
3397 if (done)
3398 a->commits_needed = 0;
3399 else {
3400 if (a->commits_needed == 0 && !a->load_all) {
3401 if (tog_io.wait_for_ui) {
3402 errcode = pthread_cond_signal(
3403 &a->log_loaded);
3404 if (errcode && err == NULL)
3405 err = got_error_set_errno(
3406 errcode,
3407 "pthread_cond_signal");
3410 errcode = pthread_cond_wait(&a->need_commits,
3411 &tog_mutex);
3412 if (errcode) {
3413 err = got_error_set_errno(errcode,
3414 "pthread_cond_wait");
3415 pthread_mutex_unlock(&tog_mutex);
3416 goto done;
3418 if (*a->quit)
3419 done = 1;
3423 a->log_complete = 1;
3424 if (tog_io.wait_for_ui) {
3425 errcode = pthread_cond_signal(&a->log_loaded);
3426 if (errcode && err == NULL)
3427 err = got_error_set_errno(errcode,
3428 "pthread_cond_signal");
3431 errcode = pthread_mutex_unlock(&tog_mutex);
3432 if (errcode)
3433 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3434 done:
3435 if (err) {
3436 tog_thread_error = 1;
3437 pthread_cond_signal(&a->commit_loaded);
3438 if (a->worktree) {
3439 got_worktree_close(a->worktree);
3440 a->worktree = NULL;
3443 return (void *)err;
3446 static const struct got_error *
3447 stop_log_thread(struct tog_log_view_state *s)
3449 const struct got_error *err = NULL, *thread_err = NULL;
3450 int errcode;
3452 if (s->thread) {
3453 s->quit = 1;
3454 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3455 if (errcode)
3456 return got_error_set_errno(errcode,
3457 "pthread_cond_signal");
3458 errcode = pthread_mutex_unlock(&tog_mutex);
3459 if (errcode)
3460 return got_error_set_errno(errcode,
3461 "pthread_mutex_unlock");
3462 errcode = pthread_join(s->thread, (void **)&thread_err);
3463 if (errcode)
3464 return got_error_set_errno(errcode, "pthread_join");
3465 errcode = pthread_mutex_lock(&tog_mutex);
3466 if (errcode)
3467 return got_error_set_errno(errcode,
3468 "pthread_mutex_lock");
3469 s->thread = NULL;
3472 if (s->thread_args.repo) {
3473 err = got_repo_close(s->thread_args.repo);
3474 s->thread_args.repo = NULL;
3477 if (s->thread_args.pack_fds) {
3478 const struct got_error *pack_err =
3479 got_repo_pack_fds_close(s->thread_args.pack_fds);
3480 if (err == NULL)
3481 err = pack_err;
3482 s->thread_args.pack_fds = NULL;
3485 if (s->thread_args.graph) {
3486 got_commit_graph_close(s->thread_args.graph);
3487 s->thread_args.graph = NULL;
3490 return err ? err : thread_err;
3493 static const struct got_error *
3494 close_log_view(struct tog_view *view)
3496 const struct got_error *err = NULL;
3497 struct tog_log_view_state *s = &view->state.log;
3498 int errcode;
3500 err = stop_log_thread(s);
3502 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3503 if (errcode && err == NULL)
3504 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3506 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3507 if (errcode && err == NULL)
3508 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3510 free_commits(&s->limit_commits);
3511 free_commits(&s->real_commits);
3512 free(s->in_repo_path);
3513 s->in_repo_path = NULL;
3514 free(s->start_id);
3515 s->start_id = NULL;
3516 free(s->head_ref_name);
3517 s->head_ref_name = NULL;
3518 return err;
3522 * We use two queues to implement the limit feature: first consists of
3523 * commits matching the current limit_regex; second is the real queue
3524 * of all known commits (real_commits). When the user starts limiting,
3525 * we swap queues such that all movement and displaying functionality
3526 * works with very slight change.
3528 static const struct got_error *
3529 limit_log_view(struct tog_view *view)
3531 struct tog_log_view_state *s = &view->state.log;
3532 struct commit_queue_entry *entry;
3533 struct tog_view *v = view;
3534 const struct got_error *err = NULL;
3535 char pattern[1024];
3536 int ret;
3538 if (view_is_hsplit_top(view))
3539 v = view->child;
3540 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3541 v = view->parent;
3543 /* Get the pattern */
3544 wmove(v->window, v->nlines - 1, 0);
3545 wclrtoeol(v->window);
3546 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3547 nodelay(v->window, FALSE);
3548 nocbreak();
3549 echo();
3550 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3551 cbreak();
3552 noecho();
3553 nodelay(v->window, TRUE);
3554 if (ret == ERR)
3555 return NULL;
3557 if (*pattern == '\0') {
3559 * Safety measure for the situation where the user
3560 * resets limit without previously limiting anything.
3562 if (!s->limit_view)
3563 return NULL;
3566 * User could have pressed Ctrl+L, which refreshed the
3567 * commit queues, it means we can't save previously
3568 * (before limit took place) displayed entries,
3569 * because they would point to already free'ed memory,
3570 * so we are forced to always select first entry of
3571 * the queue.
3573 s->commits = &s->real_commits;
3574 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3575 s->selected_entry = s->first_displayed_entry;
3576 s->selected = 0;
3577 s->limit_view = 0;
3579 return NULL;
3582 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3583 return NULL;
3585 s->limit_view = 1;
3587 /* Clear the screen while loading limit view */
3588 s->first_displayed_entry = NULL;
3589 s->last_displayed_entry = NULL;
3590 s->selected_entry = NULL;
3591 s->commits = &s->limit_commits;
3593 /* Prepare limit queue for new search */
3594 free_commits(&s->limit_commits);
3595 s->limit_commits.ncommits = 0;
3597 /* First process commits, which are in queue already */
3598 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3599 int have_match = 0;
3601 err = match_commit(&have_match, entry->id,
3602 entry->commit, &s->limit_regex);
3603 if (err)
3604 return err;
3606 if (have_match) {
3607 struct commit_queue_entry *matched;
3609 matched = alloc_commit_queue_entry(entry->commit,
3610 entry->id);
3611 if (matched == NULL) {
3612 err = got_error_from_errno(
3613 "alloc_commit_queue_entry");
3614 break;
3616 matched->commit = entry->commit;
3617 got_object_commit_retain(entry->commit);
3619 matched->idx = s->limit_commits.ncommits;
3620 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3621 matched, entry);
3622 s->limit_commits.ncommits++;
3626 /* Second process all the commits, until we fill the screen */
3627 if (s->limit_commits.ncommits < view->nlines - 1 &&
3628 !s->thread_args.log_complete) {
3629 s->thread_args.commits_needed +=
3630 view->nlines - s->limit_commits.ncommits - 1;
3631 err = trigger_log_thread(view, 1);
3632 if (err)
3633 return err;
3636 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3637 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3638 s->selected = 0;
3640 return NULL;
3643 static const struct got_error *
3644 search_start_log_view(struct tog_view *view)
3646 struct tog_log_view_state *s = &view->state.log;
3648 s->matched_entry = NULL;
3649 s->search_entry = NULL;
3650 return NULL;
3653 static const struct got_error *
3654 search_next_log_view(struct tog_view *view)
3656 const struct got_error *err = NULL;
3657 struct tog_log_view_state *s = &view->state.log;
3658 struct commit_queue_entry *entry;
3660 /* Display progress update in log view. */
3661 show_log_view(view);
3662 update_panels();
3663 doupdate();
3665 if (s->search_entry) {
3666 int errcode, ch;
3667 errcode = pthread_mutex_unlock(&tog_mutex);
3668 if (errcode)
3669 return got_error_set_errno(errcode,
3670 "pthread_mutex_unlock");
3671 ch = wgetch(view->window);
3672 errcode = pthread_mutex_lock(&tog_mutex);
3673 if (errcode)
3674 return got_error_set_errno(errcode,
3675 "pthread_mutex_lock");
3676 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3677 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3678 return NULL;
3680 if (view->searching == TOG_SEARCH_FORWARD)
3681 entry = TAILQ_NEXT(s->search_entry, entry);
3682 else
3683 entry = TAILQ_PREV(s->search_entry,
3684 commit_queue_head, entry);
3685 } else if (s->matched_entry) {
3687 * If the user has moved the cursor after we hit a match,
3688 * the position from where we should continue searching
3689 * might have changed.
3691 if (view->searching == TOG_SEARCH_FORWARD)
3692 entry = TAILQ_NEXT(s->selected_entry, entry);
3693 else
3694 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3695 entry);
3696 } else {
3697 entry = s->selected_entry;
3700 while (1) {
3701 int have_match = 0;
3703 if (entry == NULL) {
3704 if (s->thread_args.log_complete ||
3705 view->searching == TOG_SEARCH_BACKWARD) {
3706 view->search_next_done =
3707 (s->matched_entry == NULL ?
3708 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3709 s->search_entry = NULL;
3710 return NULL;
3713 * Poke the log thread for more commits and return,
3714 * allowing the main loop to make progress. Search
3715 * will resume at s->search_entry once we come back.
3717 s->thread_args.commits_needed++;
3718 return trigger_log_thread(view, 0);
3721 err = match_commit(&have_match, entry->id, entry->commit,
3722 &view->regex);
3723 if (err)
3724 break;
3725 if (have_match) {
3726 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3727 s->matched_entry = entry;
3728 break;
3731 s->search_entry = entry;
3732 if (view->searching == TOG_SEARCH_FORWARD)
3733 entry = TAILQ_NEXT(entry, entry);
3734 else
3735 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3738 if (s->matched_entry) {
3739 int cur = s->selected_entry->idx;
3740 while (cur < s->matched_entry->idx) {
3741 err = input_log_view(NULL, view, KEY_DOWN);
3742 if (err)
3743 return err;
3744 cur++;
3746 while (cur > s->matched_entry->idx) {
3747 err = input_log_view(NULL, view, KEY_UP);
3748 if (err)
3749 return err;
3750 cur--;
3754 s->search_entry = NULL;
3756 return NULL;
3759 static const struct got_error *
3760 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3761 struct got_repository *repo, const char *head_ref_name,
3762 const char *in_repo_path, int log_branches,
3763 struct got_worktree *worktree)
3765 const struct got_error *err = NULL;
3766 struct tog_log_view_state *s = &view->state.log;
3767 struct got_repository *thread_repo = NULL;
3768 struct got_commit_graph *thread_graph = NULL;
3769 int errcode;
3771 if (in_repo_path != s->in_repo_path) {
3772 free(s->in_repo_path);
3773 s->in_repo_path = strdup(in_repo_path);
3774 if (s->in_repo_path == NULL) {
3775 err = got_error_from_errno("strdup");
3776 goto done;
3780 /* The commit queue only contains commits being displayed. */
3781 TAILQ_INIT(&s->real_commits.head);
3782 s->real_commits.ncommits = 0;
3783 s->commits = &s->real_commits;
3785 TAILQ_INIT(&s->limit_commits.head);
3786 s->limit_view = 0;
3787 s->limit_commits.ncommits = 0;
3789 s->repo = repo;
3790 if (head_ref_name) {
3791 s->head_ref_name = strdup(head_ref_name);
3792 if (s->head_ref_name == NULL) {
3793 err = got_error_from_errno("strdup");
3794 goto done;
3797 s->start_id = got_object_id_dup(start_id);
3798 if (s->start_id == NULL) {
3799 err = got_error_from_errno("got_object_id_dup");
3800 goto done;
3802 s->log_branches = log_branches;
3803 s->use_committer = 1;
3805 STAILQ_INIT(&s->colors);
3806 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3807 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3808 get_color_value("TOG_COLOR_COMMIT"));
3809 if (err)
3810 goto done;
3811 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3812 get_color_value("TOG_COLOR_AUTHOR"));
3813 if (err) {
3814 free_colors(&s->colors);
3815 goto done;
3817 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3818 get_color_value("TOG_COLOR_DATE"));
3819 if (err) {
3820 free_colors(&s->colors);
3821 goto done;
3825 view->show = show_log_view;
3826 view->input = input_log_view;
3827 view->resize = resize_log_view;
3828 view->close = close_log_view;
3829 view->search_start = search_start_log_view;
3830 view->search_next = search_next_log_view;
3832 if (s->thread_args.pack_fds == NULL) {
3833 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3834 if (err)
3835 goto done;
3837 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3838 s->thread_args.pack_fds);
3839 if (err)
3840 goto done;
3841 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3842 !s->log_branches);
3843 if (err)
3844 goto done;
3845 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3846 s->repo, NULL, NULL);
3847 if (err)
3848 goto done;
3850 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3851 if (errcode) {
3852 err = got_error_set_errno(errcode, "pthread_cond_init");
3853 goto done;
3855 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3856 if (errcode) {
3857 err = got_error_set_errno(errcode, "pthread_cond_init");
3858 goto done;
3861 if (using_mock_io) {
3862 int rc;
3864 rc = pthread_cond_init(&s->thread_args.log_loaded, NULL);
3865 if (rc)
3866 return got_error_set_errno(rc, "pthread_cond_init");
3869 s->thread_args.commits_needed = view->nlines;
3870 s->thread_args.graph = thread_graph;
3871 s->thread_args.real_commits = &s->real_commits;
3872 s->thread_args.limit_commits = &s->limit_commits;
3873 s->thread_args.in_repo_path = s->in_repo_path;
3874 s->thread_args.start_id = s->start_id;
3875 s->thread_args.repo = thread_repo;
3876 s->thread_args.log_complete = 0;
3877 s->thread_args.quit = &s->quit;
3878 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3879 s->thread_args.selected_entry = &s->selected_entry;
3880 s->thread_args.searching = &view->searching;
3881 s->thread_args.search_next_done = &view->search_next_done;
3882 s->thread_args.regex = &view->regex;
3883 s->thread_args.limiting = &s->limit_view;
3884 s->thread_args.limit_regex = &s->limit_regex;
3885 s->thread_args.limit_commits = &s->limit_commits;
3886 s->thread_args.worktree = worktree;
3887 if (worktree)
3888 s->thread_args.need_commit_marker = 1;
3889 done:
3890 if (err) {
3891 if (view->close == NULL)
3892 close_log_view(view);
3893 view_close(view);
3895 return err;
3898 static const struct got_error *
3899 show_log_view(struct tog_view *view)
3901 const struct got_error *err;
3902 struct tog_log_view_state *s = &view->state.log;
3904 if (s->thread == NULL) {
3905 int errcode = pthread_create(&s->thread, NULL, log_thread,
3906 &s->thread_args);
3907 if (errcode)
3908 return got_error_set_errno(errcode, "pthread_create");
3909 if (s->thread_args.commits_needed > 0) {
3910 err = trigger_log_thread(view, 1);
3911 if (err)
3912 return err;
3913 if (tog_io.wait_for_ui) {
3914 int rc;
3916 rc = pthread_cond_wait(&s->thread_args.log_loaded,
3917 &tog_mutex);
3918 if (rc)
3919 return got_error_set_errno(rc,
3920 "pthread_cond_wait");
3921 tog_io.wait_for_ui = 0;
3926 return draw_commits(view);
3929 static void
3930 log_move_cursor_up(struct tog_view *view, int page, int home)
3932 struct tog_log_view_state *s = &view->state.log;
3934 if (s->first_displayed_entry == NULL)
3935 return;
3936 if (s->selected_entry->idx == 0)
3937 view->count = 0;
3939 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3940 || home)
3941 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3943 if (!page && !home && s->selected > 0)
3944 --s->selected;
3945 else
3946 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3948 select_commit(s);
3949 return;
3952 static const struct got_error *
3953 log_move_cursor_down(struct tog_view *view, int page)
3955 struct tog_log_view_state *s = &view->state.log;
3956 const struct got_error *err = NULL;
3957 int eos = view->nlines - 2;
3959 if (s->first_displayed_entry == NULL)
3960 return NULL;
3962 if (s->thread_args.log_complete &&
3963 s->selected_entry->idx >= s->commits->ncommits - 1)
3964 return NULL;
3966 if (view_is_hsplit_top(view))
3967 --eos; /* border consumes the last line */
3969 if (!page) {
3970 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3971 ++s->selected;
3972 else
3973 err = log_scroll_down(view, 1);
3974 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3975 struct commit_queue_entry *entry;
3976 int n;
3978 s->selected = 0;
3979 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3980 s->last_displayed_entry = entry;
3981 for (n = 0; n <= eos; n++) {
3982 if (entry == NULL)
3983 break;
3984 s->first_displayed_entry = entry;
3985 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3987 if (n > 0)
3988 s->selected = n - 1;
3989 } else {
3990 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3991 s->thread_args.log_complete)
3992 s->selected += MIN(page,
3993 s->commits->ncommits - s->selected_entry->idx - 1);
3994 else
3995 err = log_scroll_down(view, page);
3997 if (err)
3998 return err;
4001 * We might necessarily overshoot in horizontal
4002 * splits; if so, select the last displayed commit.
4004 if (s->first_displayed_entry && s->last_displayed_entry) {
4005 s->selected = MIN(s->selected,
4006 s->last_displayed_entry->idx -
4007 s->first_displayed_entry->idx);
4010 select_commit(s);
4012 if (s->thread_args.log_complete &&
4013 s->selected_entry->idx == s->commits->ncommits - 1)
4014 view->count = 0;
4016 return NULL;
4019 static void
4020 view_get_split(struct tog_view *view, int *y, int *x)
4022 *x = 0;
4023 *y = 0;
4025 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
4026 if (view->child && view->child->resized_y)
4027 *y = view->child->resized_y;
4028 else if (view->resized_y)
4029 *y = view->resized_y;
4030 else
4031 *y = view_split_begin_y(view->lines);
4032 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
4033 if (view->child && view->child->resized_x)
4034 *x = view->child->resized_x;
4035 else if (view->resized_x)
4036 *x = view->resized_x;
4037 else
4038 *x = view_split_begin_x(view->begin_x);
4042 /* Split view horizontally at y and offset view->state->selected line. */
4043 static const struct got_error *
4044 view_init_hsplit(struct tog_view *view, int y)
4046 const struct got_error *err = NULL;
4048 view->nlines = y;
4049 view->ncols = COLS;
4050 err = view_resize(view);
4051 if (err)
4052 return err;
4054 err = offset_selection_down(view);
4056 return err;
4059 static const struct got_error *
4060 log_goto_line(struct tog_view *view, int nlines)
4062 const struct got_error *err = NULL;
4063 struct tog_log_view_state *s = &view->state.log;
4064 int g, idx = s->selected_entry->idx;
4066 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
4067 return NULL;
4069 g = view->gline;
4070 view->gline = 0;
4072 if (g >= s->first_displayed_entry->idx + 1 &&
4073 g <= s->last_displayed_entry->idx + 1 &&
4074 g - s->first_displayed_entry->idx - 1 < nlines) {
4075 s->selected = g - s->first_displayed_entry->idx - 1;
4076 select_commit(s);
4077 return NULL;
4080 if (idx + 1 < g) {
4081 err = log_move_cursor_down(view, g - idx - 1);
4082 if (!err && g > s->selected_entry->idx + 1)
4083 err = log_move_cursor_down(view,
4084 g - s->first_displayed_entry->idx - 1);
4085 if (err)
4086 return err;
4087 } else if (idx + 1 > g)
4088 log_move_cursor_up(view, idx - g + 1, 0);
4090 if (g < nlines && s->first_displayed_entry->idx == 0)
4091 s->selected = g - 1;
4093 select_commit(s);
4094 return NULL;
4098 static void
4099 horizontal_scroll_input(struct tog_view *view, int ch)
4102 switch (ch) {
4103 case KEY_LEFT:
4104 case 'h':
4105 view->x -= MIN(view->x, 2);
4106 if (view->x <= 0)
4107 view->count = 0;
4108 break;
4109 case KEY_RIGHT:
4110 case 'l':
4111 if (view->x + view->ncols / 2 < view->maxx)
4112 view->x += 2;
4113 else
4114 view->count = 0;
4115 break;
4116 case '0':
4117 view->x = 0;
4118 break;
4119 case '$':
4120 view->x = MAX(view->maxx - view->ncols / 2, 0);
4121 view->count = 0;
4122 break;
4123 default:
4124 break;
4128 static const struct got_error *
4129 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
4131 const struct got_error *err = NULL;
4132 struct tog_log_view_state *s = &view->state.log;
4133 int eos, nscroll;
4135 if (s->thread_args.load_all) {
4136 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
4137 s->thread_args.load_all = 0;
4138 else if (s->thread_args.log_complete) {
4139 err = log_move_cursor_down(view, s->commits->ncommits);
4140 s->thread_args.load_all = 0;
4142 if (err)
4143 return err;
4146 eos = nscroll = view->nlines - 1;
4147 if (view_is_hsplit_top(view))
4148 --eos; /* border */
4150 if (view->gline)
4151 return log_goto_line(view, eos);
4153 switch (ch) {
4154 case '&':
4155 err = limit_log_view(view);
4156 break;
4157 case 'q':
4158 s->quit = 1;
4159 break;
4160 case '0':
4161 case '$':
4162 case KEY_RIGHT:
4163 case 'l':
4164 case KEY_LEFT:
4165 case 'h':
4166 horizontal_scroll_input(view, ch);
4167 break;
4168 case 'k':
4169 case KEY_UP:
4170 case '<':
4171 case ',':
4172 case CTRL('p'):
4173 log_move_cursor_up(view, 0, 0);
4174 break;
4175 case 'g':
4176 case '=':
4177 case KEY_HOME:
4178 log_move_cursor_up(view, 0, 1);
4179 view->count = 0;
4180 break;
4181 case CTRL('u'):
4182 case 'u':
4183 nscroll /= 2;
4184 /* FALL THROUGH */
4185 case KEY_PPAGE:
4186 case CTRL('b'):
4187 case 'b':
4188 log_move_cursor_up(view, nscroll, 0);
4189 break;
4190 case 'j':
4191 case KEY_DOWN:
4192 case '>':
4193 case '.':
4194 case CTRL('n'):
4195 err = log_move_cursor_down(view, 0);
4196 break;
4197 case '@':
4198 s->use_committer = !s->use_committer;
4199 view->action = s->use_committer ?
4200 "show committer" : "show commit author";
4201 break;
4202 case 'G':
4203 case '*':
4204 case KEY_END: {
4205 /* We don't know yet how many commits, so we're forced to
4206 * traverse them all. */
4207 view->count = 0;
4208 s->thread_args.load_all = 1;
4209 if (!s->thread_args.log_complete)
4210 return trigger_log_thread(view, 0);
4211 err = log_move_cursor_down(view, s->commits->ncommits);
4212 s->thread_args.load_all = 0;
4213 break;
4215 case CTRL('d'):
4216 case 'd':
4217 nscroll /= 2;
4218 /* FALL THROUGH */
4219 case KEY_NPAGE:
4220 case CTRL('f'):
4221 case 'f':
4222 case ' ':
4223 err = log_move_cursor_down(view, nscroll);
4224 break;
4225 case KEY_RESIZE:
4226 if (s->selected > view->nlines - 2)
4227 s->selected = view->nlines - 2;
4228 if (s->selected > s->commits->ncommits - 1)
4229 s->selected = s->commits->ncommits - 1;
4230 select_commit(s);
4231 if (s->commits->ncommits < view->nlines - 1 &&
4232 !s->thread_args.log_complete) {
4233 s->thread_args.commits_needed += (view->nlines - 1) -
4234 s->commits->ncommits;
4235 err = trigger_log_thread(view, 1);
4237 break;
4238 case KEY_ENTER:
4239 case '\r':
4240 view->count = 0;
4241 if (s->selected_entry == NULL)
4242 break;
4243 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4244 break;
4245 case 'T':
4246 view->count = 0;
4247 if (s->selected_entry == NULL)
4248 break;
4249 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4250 break;
4251 case KEY_BACKSPACE:
4252 case CTRL('l'):
4253 case 'B':
4254 view->count = 0;
4255 if (ch == KEY_BACKSPACE &&
4256 got_path_is_root_dir(s->in_repo_path))
4257 break;
4258 err = stop_log_thread(s);
4259 if (err)
4260 return err;
4261 if (ch == KEY_BACKSPACE) {
4262 char *parent_path;
4263 err = got_path_dirname(&parent_path, s->in_repo_path);
4264 if (err)
4265 return err;
4266 free(s->in_repo_path);
4267 s->in_repo_path = parent_path;
4268 s->thread_args.in_repo_path = s->in_repo_path;
4269 } else if (ch == CTRL('l')) {
4270 struct got_object_id *start_id;
4271 err = got_repo_match_object_id(&start_id, NULL,
4272 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4273 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4274 if (err) {
4275 if (s->head_ref_name == NULL ||
4276 err->code != GOT_ERR_NOT_REF)
4277 return err;
4278 /* Try to cope with deleted references. */
4279 free(s->head_ref_name);
4280 s->head_ref_name = NULL;
4281 err = got_repo_match_object_id(&start_id,
4282 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4283 &tog_refs, s->repo);
4284 if (err)
4285 return err;
4287 free(s->start_id);
4288 s->start_id = start_id;
4289 s->thread_args.start_id = s->start_id;
4290 } else /* 'B' */
4291 s->log_branches = !s->log_branches;
4293 if (s->thread_args.pack_fds == NULL) {
4294 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4295 if (err)
4296 return err;
4298 err = got_repo_open(&s->thread_args.repo,
4299 got_repo_get_path(s->repo), NULL,
4300 s->thread_args.pack_fds);
4301 if (err)
4302 return err;
4303 tog_free_refs();
4304 err = tog_load_refs(s->repo, 0);
4305 if (err)
4306 return err;
4307 err = got_commit_graph_open(&s->thread_args.graph,
4308 s->in_repo_path, !s->log_branches);
4309 if (err)
4310 return err;
4311 err = got_commit_graph_iter_start(s->thread_args.graph,
4312 s->start_id, s->repo, NULL, NULL);
4313 if (err)
4314 return err;
4315 free_commits(&s->real_commits);
4316 free_commits(&s->limit_commits);
4317 s->first_displayed_entry = NULL;
4318 s->last_displayed_entry = NULL;
4319 s->selected_entry = NULL;
4320 s->selected = 0;
4321 s->thread_args.log_complete = 0;
4322 s->quit = 0;
4323 s->thread_args.commits_needed = view->lines;
4324 s->matched_entry = NULL;
4325 s->search_entry = NULL;
4326 view->offset = 0;
4327 break;
4328 case 'R':
4329 view->count = 0;
4330 err = view_request_new(new_view, view, TOG_VIEW_REF);
4331 break;
4332 default:
4333 view->count = 0;
4334 break;
4337 return err;
4340 static const struct got_error *
4341 apply_unveil(const char *repo_path, const char *worktree_path)
4343 const struct got_error *error;
4345 #ifdef PROFILE
4346 if (unveil("gmon.out", "rwc") != 0)
4347 return got_error_from_errno2("unveil", "gmon.out");
4348 #endif
4349 if (repo_path && unveil(repo_path, "r") != 0)
4350 return got_error_from_errno2("unveil", repo_path);
4352 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4353 return got_error_from_errno2("unveil", worktree_path);
4355 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4356 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4358 error = got_privsep_unveil_exec_helpers();
4359 if (error != NULL)
4360 return error;
4362 if (unveil(NULL, NULL) != 0)
4363 return got_error_from_errno("unveil");
4365 return NULL;
4368 static const struct got_error *
4369 init_mock_term(const char *test_script_path)
4371 const struct got_error *err = NULL;
4372 const char *screen_dump_path;
4373 int in;
4375 if (test_script_path == NULL || *test_script_path == '\0')
4376 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4378 tog_io.f = fopen(test_script_path, "re");
4379 if (tog_io.f == NULL) {
4380 err = got_error_from_errno_fmt("fopen: %s",
4381 test_script_path);
4382 goto done;
4385 /* test mode, we don't want any output */
4386 tog_io.cout = fopen("/dev/null", "w+");
4387 if (tog_io.cout == NULL) {
4388 err = got_error_from_errno2("fopen", "/dev/null");
4389 goto done;
4392 in = dup(fileno(tog_io.cout));
4393 if (in == -1) {
4394 err = got_error_from_errno("dup");
4395 goto done;
4397 tog_io.cin = fdopen(in, "r");
4398 if (tog_io.cin == NULL) {
4399 err = got_error_from_errno("fdopen");
4400 close(in);
4401 goto done;
4404 screen_dump_path = getenv("TOG_SCR_DUMP");
4405 if (screen_dump_path == NULL || *screen_dump_path == '\0')
4406 return got_error_msg(GOT_ERR_IO, "TOG_SCR_DUMP not defined");
4407 tog_io.sdump = fopen(screen_dump_path, "we");
4408 if (tog_io.sdump == NULL) {
4409 err = got_error_from_errno2("fopen", screen_dump_path);
4410 goto done;
4413 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4414 err = got_error_from_errno("fseeko");
4415 goto done;
4418 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4419 err = got_error_msg(GOT_ERR_IO,
4420 "newterm: failed to initialise curses");
4422 using_mock_io = 1;
4424 done:
4425 if (err)
4426 tog_io_close();
4427 return err;
4430 static void
4431 init_curses(void)
4434 * Override default signal handlers before starting ncurses.
4435 * This should prevent ncurses from installing its own
4436 * broken cleanup() signal handler.
4438 signal(SIGWINCH, tog_sigwinch);
4439 signal(SIGPIPE, tog_sigpipe);
4440 signal(SIGCONT, tog_sigcont);
4441 signal(SIGINT, tog_sigint);
4442 signal(SIGTERM, tog_sigterm);
4444 if (using_mock_io) /* In test mode we use a fake terminal */
4445 return;
4447 initscr();
4449 cbreak();
4450 halfdelay(1); /* Fast refresh while initial view is loading. */
4451 noecho();
4452 nonl();
4453 intrflush(stdscr, FALSE);
4454 keypad(stdscr, TRUE);
4455 curs_set(0);
4456 if (getenv("TOG_COLORS") != NULL) {
4457 start_color();
4458 use_default_colors();
4461 return;
4464 static const struct got_error *
4465 set_tog_base_commit(struct got_repository *repo, struct got_worktree *worktree)
4467 tog_base_commit.id = got_object_id_dup(
4468 got_worktree_get_base_commit_id(worktree));
4469 if (tog_base_commit.id == NULL)
4470 return got_error_from_errno( "got_object_id_dup");
4472 return NULL;
4475 static const struct got_error *
4476 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4477 struct got_repository *repo, struct got_worktree *worktree)
4479 const struct got_error *err = NULL;
4481 if (argc == 0) {
4482 *in_repo_path = strdup("/");
4483 if (*in_repo_path == NULL)
4484 return got_error_from_errno("strdup");
4485 return NULL;
4488 if (worktree) {
4489 const char *prefix = got_worktree_get_path_prefix(worktree);
4490 char *p;
4492 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4493 if (err)
4494 return err;
4495 if (asprintf(in_repo_path, "%s%s%s", prefix,
4496 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4497 p) == -1) {
4498 err = got_error_from_errno("asprintf");
4499 *in_repo_path = NULL;
4501 free(p);
4502 } else
4503 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4505 return err;
4508 static const struct got_error *
4509 cmd_log(int argc, char *argv[])
4511 const struct got_error *error;
4512 struct got_repository *repo = NULL;
4513 struct got_worktree *worktree = NULL;
4514 struct got_object_id *start_id = NULL;
4515 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4516 char *keyword_idstr = NULL, *start_commit = NULL, *label = NULL;
4517 struct got_reference *ref = NULL;
4518 const char *head_ref_name = NULL;
4519 int ch, log_branches = 0;
4520 struct tog_view *view;
4521 int *pack_fds = NULL;
4523 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4524 switch (ch) {
4525 case 'b':
4526 log_branches = 1;
4527 break;
4528 case 'c':
4529 start_commit = optarg;
4530 break;
4531 case 'r':
4532 repo_path = realpath(optarg, NULL);
4533 if (repo_path == NULL)
4534 return got_error_from_errno2("realpath",
4535 optarg);
4536 break;
4537 default:
4538 usage_log();
4539 /* NOTREACHED */
4543 argc -= optind;
4544 argv += optind;
4546 if (argc > 1)
4547 usage_log();
4549 error = got_repo_pack_fds_open(&pack_fds);
4550 if (error != NULL)
4551 goto done;
4553 if (repo_path == NULL) {
4554 cwd = getcwd(NULL, 0);
4555 if (cwd == NULL) {
4556 error = got_error_from_errno("getcwd");
4557 goto done;
4559 error = got_worktree_open(&worktree, cwd, NULL);
4560 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4561 goto done;
4562 if (worktree)
4563 repo_path =
4564 strdup(got_worktree_get_repo_path(worktree));
4565 else
4566 repo_path = strdup(cwd);
4567 if (repo_path == NULL) {
4568 error = got_error_from_errno("strdup");
4569 goto done;
4573 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4574 if (error != NULL)
4575 goto done;
4577 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4578 repo, worktree);
4579 if (error)
4580 goto done;
4582 init_curses();
4584 error = apply_unveil(got_repo_get_path(repo),
4585 worktree ? got_worktree_get_root_path(worktree) : NULL);
4586 if (error)
4587 goto done;
4589 /* already loaded by tog_log_with_path()? */
4590 if (TAILQ_EMPTY(&tog_refs)) {
4591 error = tog_load_refs(repo, 0);
4592 if (error)
4593 goto done;
4596 if (start_commit == NULL) {
4597 error = got_repo_match_object_id(&start_id, &label,
4598 worktree ? got_worktree_get_head_ref_name(worktree) :
4599 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4600 if (error)
4601 goto done;
4602 head_ref_name = label;
4603 } else {
4604 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4605 repo, worktree);
4606 if (error != NULL)
4607 goto done;
4608 if (keyword_idstr != NULL)
4609 start_commit = keyword_idstr;
4611 error = got_ref_open(&ref, repo, start_commit, 0);
4612 if (error == NULL)
4613 head_ref_name = got_ref_get_name(ref);
4614 else if (error->code != GOT_ERR_NOT_REF)
4615 goto done;
4616 error = got_repo_match_object_id(&start_id, NULL,
4617 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4618 if (error)
4619 goto done;
4622 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4623 if (view == NULL) {
4624 error = got_error_from_errno("view_open");
4625 goto done;
4628 if (worktree) {
4629 error = set_tog_base_commit(repo, worktree);
4630 if (error != NULL)
4631 goto done;
4634 error = open_log_view(view, start_id, repo, head_ref_name,
4635 in_repo_path, log_branches, worktree);
4636 if (error)
4637 goto done;
4639 if (worktree) {
4640 /* The work tree will be closed by the log thread. */
4641 worktree = NULL;
4644 error = view_loop(view);
4646 done:
4647 free(tog_base_commit.id);
4648 free(keyword_idstr);
4649 free(in_repo_path);
4650 free(repo_path);
4651 free(cwd);
4652 free(start_id);
4653 free(label);
4654 if (ref)
4655 got_ref_close(ref);
4656 if (repo) {
4657 const struct got_error *close_err = got_repo_close(repo);
4658 if (error == NULL)
4659 error = close_err;
4661 if (worktree)
4662 got_worktree_close(worktree);
4663 if (pack_fds) {
4664 const struct got_error *pack_err =
4665 got_repo_pack_fds_close(pack_fds);
4666 if (error == NULL)
4667 error = pack_err;
4669 tog_free_refs();
4670 return error;
4673 __dead static void
4674 usage_diff(void)
4676 endwin();
4677 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4678 "object1 object2\n", getprogname());
4679 exit(1);
4682 static int
4683 match_line(const char *line, regex_t *regex, size_t nmatch,
4684 regmatch_t *regmatch)
4686 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4689 static struct tog_color *
4690 match_color(struct tog_colors *colors, const char *line)
4692 struct tog_color *tc = NULL;
4694 STAILQ_FOREACH(tc, colors, entry) {
4695 if (match_line(line, &tc->regex, 0, NULL))
4696 return tc;
4699 return NULL;
4702 static const struct got_error *
4703 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4704 WINDOW *window, int skipcol, regmatch_t *regmatch)
4706 const struct got_error *err = NULL;
4707 char *exstr = NULL;
4708 wchar_t *wline = NULL;
4709 int rme, rms, n, width, scrollx;
4710 int width0 = 0, width1 = 0, width2 = 0;
4711 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4713 *wtotal = 0;
4715 rms = regmatch->rm_so;
4716 rme = regmatch->rm_eo;
4718 err = expand_tab(&exstr, line);
4719 if (err)
4720 return err;
4722 /* Split the line into 3 segments, according to match offsets. */
4723 seg0 = strndup(exstr, rms);
4724 if (seg0 == NULL) {
4725 err = got_error_from_errno("strndup");
4726 goto done;
4728 seg1 = strndup(exstr + rms, rme - rms);
4729 if (seg1 == NULL) {
4730 err = got_error_from_errno("strndup");
4731 goto done;
4733 seg2 = strdup(exstr + rme);
4734 if (seg2 == NULL) {
4735 err = got_error_from_errno("strndup");
4736 goto done;
4739 /* draw up to matched token if we haven't scrolled past it */
4740 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4741 col_tab_align, 1);
4742 if (err)
4743 goto done;
4744 n = MAX(width0 - skipcol, 0);
4745 if (n) {
4746 free(wline);
4747 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4748 wlimit, col_tab_align, 1);
4749 if (err)
4750 goto done;
4751 waddwstr(window, &wline[scrollx]);
4752 wlimit -= width;
4753 *wtotal += width;
4756 if (wlimit > 0) {
4757 int i = 0, w = 0;
4758 size_t wlen;
4760 free(wline);
4761 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4762 col_tab_align, 1);
4763 if (err)
4764 goto done;
4765 wlen = wcslen(wline);
4766 while (i < wlen) {
4767 width = wcwidth(wline[i]);
4768 if (width == -1) {
4769 /* should not happen, tabs are expanded */
4770 err = got_error(GOT_ERR_RANGE);
4771 goto done;
4773 if (width0 + w + width > skipcol)
4774 break;
4775 w += width;
4776 i++;
4778 /* draw (visible part of) matched token (if scrolled into it) */
4779 if (width1 - w > 0) {
4780 wattron(window, A_STANDOUT);
4781 waddwstr(window, &wline[i]);
4782 wattroff(window, A_STANDOUT);
4783 wlimit -= (width1 - w);
4784 *wtotal += (width1 - w);
4788 if (wlimit > 0) { /* draw rest of line */
4789 free(wline);
4790 if (skipcol > width0 + width1) {
4791 err = format_line(&wline, &width2, &scrollx, seg2,
4792 skipcol - (width0 + width1), wlimit,
4793 col_tab_align, 1);
4794 if (err)
4795 goto done;
4796 waddwstr(window, &wline[scrollx]);
4797 } else {
4798 err = format_line(&wline, &width2, NULL, seg2, 0,
4799 wlimit, col_tab_align, 1);
4800 if (err)
4801 goto done;
4802 waddwstr(window, wline);
4804 *wtotal += width2;
4806 done:
4807 free(wline);
4808 free(exstr);
4809 free(seg0);
4810 free(seg1);
4811 free(seg2);
4812 return err;
4815 static int
4816 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4818 FILE *f = NULL;
4819 int *eof, *first, *selected;
4821 if (view->type == TOG_VIEW_DIFF) {
4822 struct tog_diff_view_state *s = &view->state.diff;
4824 first = &s->first_displayed_line;
4825 selected = first;
4826 eof = &s->eof;
4827 f = s->f;
4828 } else if (view->type == TOG_VIEW_HELP) {
4829 struct tog_help_view_state *s = &view->state.help;
4831 first = &s->first_displayed_line;
4832 selected = first;
4833 eof = &s->eof;
4834 f = s->f;
4835 } else if (view->type == TOG_VIEW_BLAME) {
4836 struct tog_blame_view_state *s = &view->state.blame;
4838 first = &s->first_displayed_line;
4839 selected = &s->selected_line;
4840 eof = &s->eof;
4841 f = s->blame.f;
4842 } else
4843 return 0;
4845 /* Center gline in the middle of the page like vi(1). */
4846 if (*lineno < view->gline - (view->nlines - 3) / 2)
4847 return 0;
4848 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4849 rewind(f);
4850 *eof = 0;
4851 *first = 1;
4852 *lineno = 0;
4853 *nprinted = 0;
4854 return 0;
4857 *selected = view->gline <= (view->nlines - 3) / 2 ?
4858 view->gline : (view->nlines - 3) / 2 + 1;
4859 view->gline = 0;
4861 return 1;
4864 static const struct got_error *
4865 draw_file(struct tog_view *view, const char *header)
4867 struct tog_diff_view_state *s = &view->state.diff;
4868 regmatch_t *regmatch = &view->regmatch;
4869 const struct got_error *err;
4870 int nprinted = 0;
4871 char *line;
4872 size_t linesize = 0;
4873 ssize_t linelen;
4874 wchar_t *wline;
4875 int width;
4876 int max_lines = view->nlines;
4877 int nlines = s->nlines;
4878 off_t line_offset;
4880 s->lineno = s->first_displayed_line - 1;
4881 line_offset = s->lines[s->first_displayed_line - 1].offset;
4882 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4883 return got_error_from_errno("fseek");
4885 werase(view->window);
4887 if (view->gline > s->nlines - 1)
4888 view->gline = s->nlines - 1;
4890 if (header) {
4891 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4892 1 : view->gline - (view->nlines - 3) / 2 :
4893 s->lineno + s->selected_line;
4895 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4896 return got_error_from_errno("asprintf");
4897 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4898 0, 0);
4899 free(line);
4900 if (err)
4901 return err;
4903 if (view_needs_focus_indication(view))
4904 wstandout(view->window);
4905 waddwstr(view->window, wline);
4906 free(wline);
4907 wline = NULL;
4908 while (width++ < view->ncols)
4909 waddch(view->window, ' ');
4910 if (view_needs_focus_indication(view))
4911 wstandend(view->window);
4913 if (max_lines <= 1)
4914 return NULL;
4915 max_lines--;
4918 s->eof = 0;
4919 view->maxx = 0;
4920 line = NULL;
4921 while (max_lines > 0 && nprinted < max_lines) {
4922 enum got_diff_line_type linetype;
4923 attr_t attr = 0;
4925 linelen = getline(&line, &linesize, s->f);
4926 if (linelen == -1) {
4927 if (feof(s->f)) {
4928 s->eof = 1;
4929 break;
4931 free(line);
4932 return got_ferror(s->f, GOT_ERR_IO);
4935 if (++s->lineno < s->first_displayed_line)
4936 continue;
4937 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4938 continue;
4939 if (s->lineno == view->hiline)
4940 attr = A_STANDOUT;
4942 /* Set view->maxx based on full line length. */
4943 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4944 view->x ? 1 : 0);
4945 if (err) {
4946 free(line);
4947 return err;
4949 view->maxx = MAX(view->maxx, width);
4950 free(wline);
4951 wline = NULL;
4953 linetype = s->lines[s->lineno].type;
4954 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4955 linetype < GOT_DIFF_LINE_CONTEXT)
4956 attr |= COLOR_PAIR(linetype);
4957 if (attr)
4958 wattron(view->window, attr);
4959 if (s->first_displayed_line + nprinted == s->matched_line &&
4960 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4961 err = add_matched_line(&width, line, view->ncols, 0,
4962 view->window, view->x, regmatch);
4963 if (err) {
4964 free(line);
4965 return err;
4967 } else {
4968 int skip;
4969 err = format_line(&wline, &width, &skip, line,
4970 view->x, view->ncols, 0, view->x ? 1 : 0);
4971 if (err) {
4972 free(line);
4973 return err;
4975 waddwstr(view->window, &wline[skip]);
4976 free(wline);
4977 wline = NULL;
4979 if (s->lineno == view->hiline) {
4980 /* highlight full gline length */
4981 while (width++ < view->ncols)
4982 waddch(view->window, ' ');
4983 } else {
4984 if (width <= view->ncols - 1)
4985 waddch(view->window, '\n');
4987 if (attr)
4988 wattroff(view->window, attr);
4989 if (++nprinted == 1)
4990 s->first_displayed_line = s->lineno;
4992 free(line);
4993 if (nprinted >= 1)
4994 s->last_displayed_line = s->first_displayed_line +
4995 (nprinted - 1);
4996 else
4997 s->last_displayed_line = s->first_displayed_line;
4999 view_border(view);
5001 if (s->eof) {
5002 while (nprinted < view->nlines) {
5003 waddch(view->window, '\n');
5004 nprinted++;
5007 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
5008 view->ncols, 0, 0);
5009 if (err) {
5010 return err;
5013 wstandout(view->window);
5014 waddwstr(view->window, wline);
5015 free(wline);
5016 wline = NULL;
5017 wstandend(view->window);
5020 return NULL;
5023 static char *
5024 get_datestr(time_t *time, char *datebuf)
5026 struct tm mytm, *tm;
5027 char *p, *s;
5029 tm = gmtime_r(time, &mytm);
5030 if (tm == NULL)
5031 return NULL;
5032 s = asctime_r(tm, datebuf);
5033 if (s == NULL)
5034 return NULL;
5035 p = strchr(s, '\n');
5036 if (p)
5037 *p = '\0';
5038 return s;
5041 static const struct got_error *
5042 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
5043 off_t off, uint8_t type)
5045 struct got_diff_line *p;
5047 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
5048 if (p == NULL)
5049 return got_error_from_errno("reallocarray");
5050 *lines = p;
5051 (*lines)[*nlines].offset = off;
5052 (*lines)[*nlines].type = type;
5053 (*nlines)++;
5055 return NULL;
5058 static const struct got_error *
5059 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
5060 struct got_diff_line *s_lines, size_t s_nlines)
5062 struct got_diff_line *p;
5063 char buf[BUFSIZ];
5064 size_t i, r;
5066 if (fseeko(src, 0L, SEEK_SET) == -1)
5067 return got_error_from_errno("fseeko");
5069 for (;;) {
5070 r = fread(buf, 1, sizeof(buf), src);
5071 if (r == 0) {
5072 if (ferror(src))
5073 return got_error_from_errno("fread");
5074 if (feof(src))
5075 break;
5077 if (fwrite(buf, 1, r, dst) != r)
5078 return got_ferror(dst, GOT_ERR_IO);
5081 if (s_nlines == 0 && *d_nlines == 0)
5082 return NULL;
5085 * If commit info was in dst, increment line offsets
5086 * of the appended diff content, but skip s_lines[0]
5087 * because offset zero is already in *d_lines.
5089 if (*d_nlines > 0) {
5090 for (i = 1; i < s_nlines; ++i)
5091 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
5093 if (s_nlines > 0) {
5094 --s_nlines;
5095 ++s_lines;
5099 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
5100 if (p == NULL) {
5101 /* d_lines is freed in close_diff_view() */
5102 return got_error_from_errno("reallocarray");
5105 *d_lines = p;
5107 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
5108 *d_nlines += s_nlines;
5110 return NULL;
5113 static const struct got_error *
5114 write_commit_info(struct got_diff_line **lines, size_t *nlines,
5115 struct got_object_id *commit_id, struct got_reflist_head *refs,
5116 struct got_repository *repo, int ignore_ws, int force_text_diff,
5117 struct got_diffstat_cb_arg *dsa, FILE *outfile)
5119 const struct got_error *err = NULL;
5120 char datebuf[26], *datestr;
5121 struct got_commit_object *commit;
5122 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
5123 time_t committer_time;
5124 const char *author, *committer;
5125 char *refs_str = NULL;
5126 struct got_pathlist_entry *pe;
5127 off_t outoff = 0;
5128 int n;
5130 err = build_refs_str(&refs_str, refs, commit_id, repo);
5131 if (err)
5132 return err;
5134 err = got_object_open_as_commit(&commit, repo, commit_id);
5135 if (err)
5136 return err;
5138 err = got_object_id_str(&id_str, commit_id);
5139 if (err) {
5140 err = got_error_from_errno("got_object_id_str");
5141 goto done;
5144 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
5145 if (err)
5146 goto done;
5148 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
5149 refs_str ? refs_str : "", refs_str ? ")" : "");
5150 if (n < 0) {
5151 err = got_error_from_errno("fprintf");
5152 goto done;
5154 outoff += n;
5155 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
5156 if (err)
5157 goto done;
5159 n = fprintf(outfile, "from: %s\n",
5160 got_object_commit_get_author(commit));
5161 if (n < 0) {
5162 err = got_error_from_errno("fprintf");
5163 goto done;
5165 outoff += n;
5166 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
5167 if (err)
5168 goto done;
5170 author = got_object_commit_get_author(commit);
5171 committer = got_object_commit_get_committer(commit);
5172 if (strcmp(author, committer) != 0) {
5173 n = fprintf(outfile, "via: %s\n", committer);
5174 if (n < 0) {
5175 err = got_error_from_errno("fprintf");
5176 goto done;
5178 outoff += n;
5179 err = add_line_metadata(lines, nlines, outoff,
5180 GOT_DIFF_LINE_AUTHOR);
5181 if (err)
5182 goto done;
5184 committer_time = got_object_commit_get_committer_time(commit);
5185 datestr = get_datestr(&committer_time, datebuf);
5186 if (datestr) {
5187 n = fprintf(outfile, "date: %s UTC\n", datestr);
5188 if (n < 0) {
5189 err = got_error_from_errno("fprintf");
5190 goto done;
5192 outoff += n;
5193 err = add_line_metadata(lines, nlines, outoff,
5194 GOT_DIFF_LINE_DATE);
5195 if (err)
5196 goto done;
5198 if (got_object_commit_get_nparents(commit) > 1) {
5199 const struct got_object_id_queue *parent_ids;
5200 struct got_object_qid *qid;
5201 int pn = 1;
5202 parent_ids = got_object_commit_get_parent_ids(commit);
5203 STAILQ_FOREACH(qid, parent_ids, entry) {
5204 err = got_object_id_str(&id_str, &qid->id);
5205 if (err)
5206 goto done;
5207 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
5208 if (n < 0) {
5209 err = got_error_from_errno("fprintf");
5210 goto done;
5212 outoff += n;
5213 err = add_line_metadata(lines, nlines, outoff,
5214 GOT_DIFF_LINE_META);
5215 if (err)
5216 goto done;
5217 free(id_str);
5218 id_str = NULL;
5222 err = got_object_commit_get_logmsg(&logmsg, commit);
5223 if (err)
5224 goto done;
5225 s = logmsg;
5226 while ((line = strsep(&s, "\n")) != NULL) {
5227 n = fprintf(outfile, "%s\n", line);
5228 if (n < 0) {
5229 err = got_error_from_errno("fprintf");
5230 goto done;
5232 outoff += n;
5233 err = add_line_metadata(lines, nlines, outoff,
5234 GOT_DIFF_LINE_LOGMSG);
5235 if (err)
5236 goto done;
5239 TAILQ_FOREACH(pe, dsa->paths, entry) {
5240 struct got_diff_changed_path *cp = pe->data;
5241 int pad = dsa->max_path_len - pe->path_len + 1;
5243 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5244 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5245 dsa->rm_cols + 1, cp->rm);
5246 if (n < 0) {
5247 err = got_error_from_errno("fprintf");
5248 goto done;
5250 outoff += n;
5251 err = add_line_metadata(lines, nlines, outoff,
5252 GOT_DIFF_LINE_CHANGES);
5253 if (err)
5254 goto done;
5257 fputc('\n', outfile);
5258 outoff++;
5259 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5260 if (err)
5261 goto done;
5263 n = fprintf(outfile,
5264 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5265 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5266 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5267 if (n < 0) {
5268 err = got_error_from_errno("fprintf");
5269 goto done;
5271 outoff += n;
5272 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5273 if (err)
5274 goto done;
5276 fputc('\n', outfile);
5277 outoff++;
5278 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5279 done:
5280 free(id_str);
5281 free(logmsg);
5282 free(refs_str);
5283 got_object_commit_close(commit);
5284 if (err) {
5285 free(*lines);
5286 *lines = NULL;
5287 *nlines = 0;
5289 return err;
5292 static const struct got_error *
5293 create_diff(struct tog_diff_view_state *s)
5295 const struct got_error *err = NULL;
5296 FILE *f = NULL, *tmp_diff_file = NULL;
5297 int obj_type;
5298 struct got_diff_line *lines = NULL;
5299 struct got_pathlist_head changed_paths;
5301 TAILQ_INIT(&changed_paths);
5303 free(s->lines);
5304 s->lines = malloc(sizeof(*s->lines));
5305 if (s->lines == NULL)
5306 return got_error_from_errno("malloc");
5307 s->nlines = 0;
5309 f = got_opentemp();
5310 if (f == NULL) {
5311 err = got_error_from_errno("got_opentemp");
5312 goto done;
5314 tmp_diff_file = got_opentemp();
5315 if (tmp_diff_file == NULL) {
5316 err = got_error_from_errno("got_opentemp");
5317 goto done;
5319 if (s->f && fclose(s->f) == EOF) {
5320 err = got_error_from_errno("fclose");
5321 goto done;
5323 s->f = f;
5325 if (s->id1)
5326 err = got_object_get_type(&obj_type, s->repo, s->id1);
5327 else
5328 err = got_object_get_type(&obj_type, s->repo, s->id2);
5329 if (err)
5330 goto done;
5332 switch (obj_type) {
5333 case GOT_OBJ_TYPE_BLOB:
5334 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5335 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5336 s->label1, s->label2, tog_diff_algo, s->diff_context,
5337 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5338 s->f);
5339 break;
5340 case GOT_OBJ_TYPE_TREE:
5341 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5342 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5343 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5344 s->force_text_diff, NULL, s->repo, s->f);
5345 break;
5346 case GOT_OBJ_TYPE_COMMIT: {
5347 const struct got_object_id_queue *parent_ids;
5348 struct got_object_qid *pid;
5349 struct got_commit_object *commit2;
5350 struct got_reflist_head *refs;
5351 size_t nlines = 0;
5352 struct got_diffstat_cb_arg dsa = {
5353 0, 0, 0, 0, 0, 0,
5354 &changed_paths,
5355 s->ignore_whitespace,
5356 s->force_text_diff,
5357 tog_diff_algo
5360 lines = malloc(sizeof(*lines));
5361 if (lines == NULL) {
5362 err = got_error_from_errno("malloc");
5363 goto done;
5366 /* build diff first in tmp file then append to commit info */
5367 err = got_diff_objects_as_commits(&lines, &nlines,
5368 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5369 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5370 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5371 if (err)
5372 break;
5374 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5375 if (err)
5376 goto done;
5377 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5378 /* Show commit info if we're diffing to a parent/root commit. */
5379 if (s->id1 == NULL) {
5380 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5381 refs, s->repo, s->ignore_whitespace,
5382 s->force_text_diff, &dsa, s->f);
5383 if (err)
5384 goto done;
5385 } else {
5386 parent_ids = got_object_commit_get_parent_ids(commit2);
5387 STAILQ_FOREACH(pid, parent_ids, entry) {
5388 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5389 err = write_commit_info(&s->lines,
5390 &s->nlines, s->id2, refs, s->repo,
5391 s->ignore_whitespace,
5392 s->force_text_diff, &dsa, s->f);
5393 if (err)
5394 goto done;
5395 break;
5399 got_object_commit_close(commit2);
5401 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5402 lines, nlines);
5403 break;
5405 default:
5406 err = got_error(GOT_ERR_OBJ_TYPE);
5407 break;
5409 done:
5410 free(lines);
5411 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5412 if (s->f && fflush(s->f) != 0 && err == NULL)
5413 err = got_error_from_errno("fflush");
5414 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5415 err = got_error_from_errno("fclose");
5416 return err;
5419 static void
5420 diff_view_indicate_progress(struct tog_view *view)
5422 mvwaddstr(view->window, 0, 0, "diffing...");
5423 update_panels();
5424 doupdate();
5427 static const struct got_error *
5428 search_start_diff_view(struct tog_view *view)
5430 struct tog_diff_view_state *s = &view->state.diff;
5432 s->matched_line = 0;
5433 return NULL;
5436 static void
5437 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5438 size_t *nlines, int **first, int **last, int **match, int **selected)
5440 struct tog_diff_view_state *s = &view->state.diff;
5442 *f = s->f;
5443 *nlines = s->nlines;
5444 *line_offsets = NULL;
5445 *match = &s->matched_line;
5446 *first = &s->first_displayed_line;
5447 *last = &s->last_displayed_line;
5448 *selected = &s->selected_line;
5451 static const struct got_error *
5452 search_next_view_match(struct tog_view *view)
5454 const struct got_error *err = NULL;
5455 FILE *f;
5456 int lineno;
5457 char *line = NULL;
5458 size_t linesize = 0;
5459 ssize_t linelen;
5460 off_t *line_offsets;
5461 size_t nlines = 0;
5462 int *first, *last, *match, *selected;
5464 if (!view->search_setup)
5465 return got_error_msg(GOT_ERR_NOT_IMPL,
5466 "view search not supported");
5467 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5468 &match, &selected);
5470 if (!view->searching) {
5471 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5472 return NULL;
5475 if (*match) {
5476 if (view->searching == TOG_SEARCH_FORWARD)
5477 lineno = *first + 1;
5478 else
5479 lineno = *first - 1;
5480 } else
5481 lineno = *first - 1 + *selected;
5483 while (1) {
5484 off_t offset;
5486 if (lineno <= 0 || lineno > nlines) {
5487 if (*match == 0) {
5488 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5489 break;
5492 if (view->searching == TOG_SEARCH_FORWARD)
5493 lineno = 1;
5494 else
5495 lineno = nlines;
5498 offset = view->type == TOG_VIEW_DIFF ?
5499 view->state.diff.lines[lineno - 1].offset :
5500 line_offsets[lineno - 1];
5501 if (fseeko(f, offset, SEEK_SET) != 0) {
5502 free(line);
5503 return got_error_from_errno("fseeko");
5505 linelen = getline(&line, &linesize, f);
5506 if (linelen != -1) {
5507 char *exstr;
5508 err = expand_tab(&exstr, line);
5509 if (err)
5510 break;
5511 if (match_line(exstr, &view->regex, 1,
5512 &view->regmatch)) {
5513 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5514 *match = lineno;
5515 free(exstr);
5516 break;
5518 free(exstr);
5520 if (view->searching == TOG_SEARCH_FORWARD)
5521 lineno++;
5522 else
5523 lineno--;
5525 free(line);
5527 if (*match) {
5528 *first = *match;
5529 *selected = 1;
5532 return err;
5535 static const struct got_error *
5536 close_diff_view(struct tog_view *view)
5538 const struct got_error *err = NULL;
5539 struct tog_diff_view_state *s = &view->state.diff;
5541 free(s->id1);
5542 s->id1 = NULL;
5543 free(s->id2);
5544 s->id2 = NULL;
5545 if (s->f && fclose(s->f) == EOF)
5546 err = got_error_from_errno("fclose");
5547 s->f = NULL;
5548 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5549 err = got_error_from_errno("fclose");
5550 s->f1 = NULL;
5551 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5552 err = got_error_from_errno("fclose");
5553 s->f2 = NULL;
5554 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5555 err = got_error_from_errno("close");
5556 s->fd1 = -1;
5557 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5558 err = got_error_from_errno("close");
5559 s->fd2 = -1;
5560 free(s->lines);
5561 s->lines = NULL;
5562 s->nlines = 0;
5563 return err;
5566 static const struct got_error *
5567 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5568 struct got_object_id *id2, const char *label1, const char *label2,
5569 int diff_context, int ignore_whitespace, int force_text_diff,
5570 struct tog_view *parent_view, struct got_repository *repo)
5572 const struct got_error *err;
5573 struct tog_diff_view_state *s = &view->state.diff;
5575 memset(s, 0, sizeof(*s));
5576 s->fd1 = -1;
5577 s->fd2 = -1;
5579 if (id1 != NULL && id2 != NULL) {
5580 int type1, type2;
5582 err = got_object_get_type(&type1, repo, id1);
5583 if (err)
5584 goto done;
5585 err = got_object_get_type(&type2, repo, id2);
5586 if (err)
5587 goto done;
5589 if (type1 != type2) {
5590 err = got_error(GOT_ERR_OBJ_TYPE);
5591 goto done;
5594 s->first_displayed_line = 1;
5595 s->last_displayed_line = view->nlines;
5596 s->selected_line = 1;
5597 s->repo = repo;
5598 s->id1 = id1;
5599 s->id2 = id2;
5600 s->label1 = label1;
5601 s->label2 = label2;
5603 if (id1) {
5604 s->id1 = got_object_id_dup(id1);
5605 if (s->id1 == NULL) {
5606 err = got_error_from_errno("got_object_id_dup");
5607 goto done;
5609 } else
5610 s->id1 = NULL;
5612 s->id2 = got_object_id_dup(id2);
5613 if (s->id2 == NULL) {
5614 err = got_error_from_errno("got_object_id_dup");
5615 goto done;
5618 s->f1 = got_opentemp();
5619 if (s->f1 == NULL) {
5620 err = got_error_from_errno("got_opentemp");
5621 goto done;
5624 s->f2 = got_opentemp();
5625 if (s->f2 == NULL) {
5626 err = got_error_from_errno("got_opentemp");
5627 goto done;
5630 s->fd1 = got_opentempfd();
5631 if (s->fd1 == -1) {
5632 err = got_error_from_errno("got_opentempfd");
5633 goto done;
5636 s->fd2 = got_opentempfd();
5637 if (s->fd2 == -1) {
5638 err = got_error_from_errno("got_opentempfd");
5639 goto done;
5642 s->diff_context = diff_context;
5643 s->ignore_whitespace = ignore_whitespace;
5644 s->force_text_diff = force_text_diff;
5645 s->parent_view = parent_view;
5646 s->repo = repo;
5648 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5649 int rc;
5651 rc = init_pair(GOT_DIFF_LINE_MINUS,
5652 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5653 if (rc != ERR)
5654 rc = init_pair(GOT_DIFF_LINE_PLUS,
5655 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5656 if (rc != ERR)
5657 rc = init_pair(GOT_DIFF_LINE_HUNK,
5658 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5659 if (rc != ERR)
5660 rc = init_pair(GOT_DIFF_LINE_META,
5661 get_color_value("TOG_COLOR_DIFF_META"), -1);
5662 if (rc != ERR)
5663 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5664 get_color_value("TOG_COLOR_DIFF_META"), -1);
5665 if (rc != ERR)
5666 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5667 get_color_value("TOG_COLOR_DIFF_META"), -1);
5668 if (rc != ERR)
5669 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5670 get_color_value("TOG_COLOR_DIFF_META"), -1);
5671 if (rc != ERR)
5672 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5673 get_color_value("TOG_COLOR_AUTHOR"), -1);
5674 if (rc != ERR)
5675 rc = init_pair(GOT_DIFF_LINE_DATE,
5676 get_color_value("TOG_COLOR_DATE"), -1);
5677 if (rc == ERR) {
5678 err = got_error(GOT_ERR_RANGE);
5679 goto done;
5683 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5684 view_is_splitscreen(view))
5685 show_log_view(parent_view); /* draw border */
5686 diff_view_indicate_progress(view);
5688 err = create_diff(s);
5690 view->show = show_diff_view;
5691 view->input = input_diff_view;
5692 view->reset = reset_diff_view;
5693 view->close = close_diff_view;
5694 view->search_start = search_start_diff_view;
5695 view->search_setup = search_setup_diff_view;
5696 view->search_next = search_next_view_match;
5697 done:
5698 if (err) {
5699 if (view->close == NULL)
5700 close_diff_view(view);
5701 view_close(view);
5703 return err;
5706 static const struct got_error *
5707 show_diff_view(struct tog_view *view)
5709 const struct got_error *err;
5710 struct tog_diff_view_state *s = &view->state.diff;
5711 char *id_str1 = NULL, *id_str2, *header;
5712 const char *label1, *label2;
5714 if (s->id1) {
5715 err = got_object_id_str(&id_str1, s->id1);
5716 if (err)
5717 return err;
5718 label1 = s->label1 ? s->label1 : id_str1;
5719 } else
5720 label1 = "/dev/null";
5722 err = got_object_id_str(&id_str2, s->id2);
5723 if (err)
5724 return err;
5725 label2 = s->label2 ? s->label2 : id_str2;
5727 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5728 err = got_error_from_errno("asprintf");
5729 free(id_str1);
5730 free(id_str2);
5731 return err;
5733 free(id_str1);
5734 free(id_str2);
5736 err = draw_file(view, header);
5737 free(header);
5738 return err;
5741 static const struct got_error *
5742 set_selected_commit(struct tog_diff_view_state *s,
5743 struct commit_queue_entry *entry)
5745 const struct got_error *err;
5746 const struct got_object_id_queue *parent_ids;
5747 struct got_commit_object *selected_commit;
5748 struct got_object_qid *pid;
5750 free(s->id2);
5751 s->id2 = got_object_id_dup(entry->id);
5752 if (s->id2 == NULL)
5753 return got_error_from_errno("got_object_id_dup");
5755 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5756 if (err)
5757 return err;
5758 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5759 free(s->id1);
5760 pid = STAILQ_FIRST(parent_ids);
5761 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5762 got_object_commit_close(selected_commit);
5763 return NULL;
5766 static const struct got_error *
5767 reset_diff_view(struct tog_view *view)
5769 struct tog_diff_view_state *s = &view->state.diff;
5771 view->count = 0;
5772 wclear(view->window);
5773 s->first_displayed_line = 1;
5774 s->last_displayed_line = view->nlines;
5775 s->matched_line = 0;
5776 diff_view_indicate_progress(view);
5777 return create_diff(s);
5780 static void
5781 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5783 int start, i;
5785 i = start = s->first_displayed_line - 1;
5787 while (s->lines[i].type != type) {
5788 if (i == 0)
5789 i = s->nlines - 1;
5790 if (--i == start)
5791 return; /* do nothing, requested type not in file */
5794 s->selected_line = 1;
5795 s->first_displayed_line = i;
5798 static void
5799 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5801 int start, i;
5803 i = start = s->first_displayed_line + 1;
5805 while (s->lines[i].type != type) {
5806 if (i == s->nlines - 1)
5807 i = 0;
5808 if (++i == start)
5809 return; /* do nothing, requested type not in file */
5812 s->selected_line = 1;
5813 s->first_displayed_line = i;
5816 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5817 int, int, int);
5818 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5819 int, int);
5821 static const struct got_error *
5822 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5824 const struct got_error *err = NULL;
5825 struct tog_diff_view_state *s = &view->state.diff;
5826 struct tog_log_view_state *ls;
5827 struct commit_queue_entry *old_selected_entry;
5828 char *line = NULL;
5829 size_t linesize = 0;
5830 ssize_t linelen;
5831 int i, nscroll = view->nlines - 1, up = 0;
5833 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5835 switch (ch) {
5836 case '0':
5837 case '$':
5838 case KEY_RIGHT:
5839 case 'l':
5840 case KEY_LEFT:
5841 case 'h':
5842 horizontal_scroll_input(view, ch);
5843 break;
5844 case 'a':
5845 case 'w':
5846 if (ch == 'a') {
5847 s->force_text_diff = !s->force_text_diff;
5848 view->action = s->force_text_diff ?
5849 "force ASCII text enabled" :
5850 "force ASCII text disabled";
5852 else if (ch == 'w') {
5853 s->ignore_whitespace = !s->ignore_whitespace;
5854 view->action = s->ignore_whitespace ?
5855 "ignore whitespace enabled" :
5856 "ignore whitespace disabled";
5858 err = reset_diff_view(view);
5859 break;
5860 case 'g':
5861 case KEY_HOME:
5862 s->first_displayed_line = 1;
5863 view->count = 0;
5864 break;
5865 case 'G':
5866 case KEY_END:
5867 view->count = 0;
5868 if (s->eof)
5869 break;
5871 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5872 s->eof = 1;
5873 break;
5874 case 'k':
5875 case KEY_UP:
5876 case CTRL('p'):
5877 if (s->first_displayed_line > 1)
5878 s->first_displayed_line--;
5879 else
5880 view->count = 0;
5881 break;
5882 case CTRL('u'):
5883 case 'u':
5884 nscroll /= 2;
5885 /* FALL THROUGH */
5886 case KEY_PPAGE:
5887 case CTRL('b'):
5888 case 'b':
5889 if (s->first_displayed_line == 1) {
5890 view->count = 0;
5891 break;
5893 i = 0;
5894 while (i++ < nscroll && s->first_displayed_line > 1)
5895 s->first_displayed_line--;
5896 break;
5897 case 'j':
5898 case KEY_DOWN:
5899 case CTRL('n'):
5900 if (!s->eof)
5901 s->first_displayed_line++;
5902 else
5903 view->count = 0;
5904 break;
5905 case CTRL('d'):
5906 case 'd':
5907 nscroll /= 2;
5908 /* FALL THROUGH */
5909 case KEY_NPAGE:
5910 case CTRL('f'):
5911 case 'f':
5912 case ' ':
5913 if (s->eof) {
5914 view->count = 0;
5915 break;
5917 i = 0;
5918 while (!s->eof && i++ < nscroll) {
5919 linelen = getline(&line, &linesize, s->f);
5920 s->first_displayed_line++;
5921 if (linelen == -1) {
5922 if (feof(s->f)) {
5923 s->eof = 1;
5924 } else
5925 err = got_ferror(s->f, GOT_ERR_IO);
5926 break;
5929 free(line);
5930 break;
5931 case '(':
5932 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5933 break;
5934 case ')':
5935 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5936 break;
5937 case '{':
5938 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5939 break;
5940 case '}':
5941 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5942 break;
5943 case '[':
5944 if (s->diff_context > 0) {
5945 s->diff_context--;
5946 s->matched_line = 0;
5947 diff_view_indicate_progress(view);
5948 err = create_diff(s);
5949 if (s->first_displayed_line + view->nlines - 1 >
5950 s->nlines) {
5951 s->first_displayed_line = 1;
5952 s->last_displayed_line = view->nlines;
5954 } else
5955 view->count = 0;
5956 break;
5957 case ']':
5958 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5959 s->diff_context++;
5960 s->matched_line = 0;
5961 diff_view_indicate_progress(view);
5962 err = create_diff(s);
5963 } else
5964 view->count = 0;
5965 break;
5966 case '<':
5967 case ',':
5968 case 'K':
5969 up = 1;
5970 /* FALL THROUGH */
5971 case '>':
5972 case '.':
5973 case 'J':
5974 if (s->parent_view == NULL) {
5975 view->count = 0;
5976 break;
5978 s->parent_view->count = view->count;
5980 if (s->parent_view->type == TOG_VIEW_LOG) {
5981 ls = &s->parent_view->state.log;
5982 old_selected_entry = ls->selected_entry;
5984 err = input_log_view(NULL, s->parent_view,
5985 up ? KEY_UP : KEY_DOWN);
5986 if (err)
5987 break;
5988 view->count = s->parent_view->count;
5990 if (old_selected_entry == ls->selected_entry)
5991 break;
5993 err = set_selected_commit(s, ls->selected_entry);
5994 if (err)
5995 break;
5996 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5997 struct tog_blame_view_state *bs;
5998 struct got_object_id *id, *prev_id;
6000 bs = &s->parent_view->state.blame;
6001 prev_id = get_annotation_for_line(bs->blame.lines,
6002 bs->blame.nlines, bs->last_diffed_line);
6004 err = input_blame_view(&view, s->parent_view,
6005 up ? KEY_UP : KEY_DOWN);
6006 if (err)
6007 break;
6008 view->count = s->parent_view->count;
6010 if (prev_id == NULL)
6011 break;
6012 id = get_selected_commit_id(bs->blame.lines,
6013 bs->blame.nlines, bs->first_displayed_line,
6014 bs->selected_line);
6015 if (id == NULL)
6016 break;
6018 if (!got_object_id_cmp(prev_id, id))
6019 break;
6021 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
6022 if (err)
6023 break;
6025 s->first_displayed_line = 1;
6026 s->last_displayed_line = view->nlines;
6027 s->matched_line = 0;
6028 view->x = 0;
6030 diff_view_indicate_progress(view);
6031 err = create_diff(s);
6032 break;
6033 default:
6034 view->count = 0;
6035 break;
6038 return err;
6041 static const struct got_error *
6042 cmd_diff(int argc, char *argv[])
6044 const struct got_error *error;
6045 struct got_repository *repo = NULL;
6046 struct got_worktree *worktree = NULL;
6047 struct got_object_id *id1 = NULL, *id2 = NULL;
6048 char *repo_path = NULL, *cwd = NULL;
6049 char *id_str1 = NULL, *id_str2 = NULL;
6050 char *keyword_idstr1 = NULL, *keyword_idstr2 = NULL;
6051 char *label1 = NULL, *label2 = NULL;
6052 int diff_context = 3, ignore_whitespace = 0;
6053 int ch, force_text_diff = 0;
6054 const char *errstr;
6055 struct tog_view *view;
6056 int *pack_fds = NULL;
6058 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
6059 switch (ch) {
6060 case 'a':
6061 force_text_diff = 1;
6062 break;
6063 case 'C':
6064 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
6065 &errstr);
6066 if (errstr != NULL)
6067 errx(1, "number of context lines is %s: %s",
6068 errstr, errstr);
6069 break;
6070 case 'r':
6071 repo_path = realpath(optarg, NULL);
6072 if (repo_path == NULL)
6073 return got_error_from_errno2("realpath",
6074 optarg);
6075 got_path_strip_trailing_slashes(repo_path);
6076 break;
6077 case 'w':
6078 ignore_whitespace = 1;
6079 break;
6080 default:
6081 usage_diff();
6082 /* NOTREACHED */
6086 argc -= optind;
6087 argv += optind;
6089 if (argc == 0) {
6090 usage_diff(); /* TODO show local worktree changes */
6091 } else if (argc == 2) {
6092 id_str1 = argv[0];
6093 id_str2 = argv[1];
6094 } else
6095 usage_diff();
6097 error = got_repo_pack_fds_open(&pack_fds);
6098 if (error)
6099 goto done;
6101 if (repo_path == NULL) {
6102 cwd = getcwd(NULL, 0);
6103 if (cwd == NULL)
6104 return got_error_from_errno("getcwd");
6105 error = got_worktree_open(&worktree, cwd, NULL);
6106 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6107 goto done;
6108 if (worktree)
6109 repo_path =
6110 strdup(got_worktree_get_repo_path(worktree));
6111 else
6112 repo_path = strdup(cwd);
6113 if (repo_path == NULL) {
6114 error = got_error_from_errno("strdup");
6115 goto done;
6119 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6120 if (error)
6121 goto done;
6123 init_curses();
6125 error = apply_unveil(got_repo_get_path(repo), NULL);
6126 if (error)
6127 goto done;
6129 error = tog_load_refs(repo, 0);
6130 if (error)
6131 goto done;
6133 if (id_str1 != NULL) {
6134 error = got_keyword_to_idstr(&keyword_idstr1, id_str1,
6135 repo, worktree);
6136 if (error != NULL)
6137 goto done;
6138 if (keyword_idstr1 != NULL)
6139 id_str1 = keyword_idstr1;
6141 if (id_str2 != NULL) {
6142 error = got_keyword_to_idstr(&keyword_idstr2, id_str2,
6143 repo, worktree);
6144 if (error != NULL)
6145 goto done;
6146 if (keyword_idstr2 != NULL)
6147 id_str2 = keyword_idstr2;
6150 error = got_repo_match_object_id(&id1, &label1, id_str1,
6151 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6152 if (error)
6153 goto done;
6155 error = got_repo_match_object_id(&id2, &label2, id_str2,
6156 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6157 if (error)
6158 goto done;
6160 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
6161 if (view == NULL) {
6162 error = got_error_from_errno("view_open");
6163 goto done;
6165 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
6166 ignore_whitespace, force_text_diff, NULL, repo);
6167 if (error)
6168 goto done;
6170 if (worktree) {
6171 error = set_tog_base_commit(repo, worktree);
6172 if (error != NULL)
6173 goto done;
6176 error = view_loop(view);
6178 done:
6179 free(tog_base_commit.id);
6180 free(keyword_idstr1);
6181 free(keyword_idstr2);
6182 free(label1);
6183 free(label2);
6184 free(repo_path);
6185 free(cwd);
6186 if (repo) {
6187 const struct got_error *close_err = got_repo_close(repo);
6188 if (error == NULL)
6189 error = close_err;
6191 if (worktree)
6192 got_worktree_close(worktree);
6193 if (pack_fds) {
6194 const struct got_error *pack_err =
6195 got_repo_pack_fds_close(pack_fds);
6196 if (error == NULL)
6197 error = pack_err;
6199 tog_free_refs();
6200 return error;
6203 __dead static void
6204 usage_blame(void)
6206 endwin();
6207 fprintf(stderr,
6208 "usage: %s blame [-c commit] [-r repository-path] path\n",
6209 getprogname());
6210 exit(1);
6213 struct tog_blame_line {
6214 int annotated;
6215 struct got_object_id *id;
6218 static const struct got_error *
6219 draw_blame(struct tog_view *view)
6221 struct tog_blame_view_state *s = &view->state.blame;
6222 struct tog_blame *blame = &s->blame;
6223 regmatch_t *regmatch = &view->regmatch;
6224 const struct got_error *err;
6225 int lineno = 0, nprinted = 0;
6226 char *line = NULL;
6227 size_t linesize = 0;
6228 ssize_t linelen;
6229 wchar_t *wline;
6230 int width;
6231 struct tog_blame_line *blame_line;
6232 struct got_object_id *prev_id = NULL;
6233 char *id_str;
6234 struct tog_color *tc;
6236 err = got_object_id_str(&id_str, &s->blamed_commit->id);
6237 if (err)
6238 return err;
6240 rewind(blame->f);
6241 werase(view->window);
6243 if (asprintf(&line, "commit %s", id_str) == -1) {
6244 err = got_error_from_errno("asprintf");
6245 free(id_str);
6246 return err;
6249 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6250 free(line);
6251 line = NULL;
6252 if (err)
6253 return err;
6254 if (view_needs_focus_indication(view))
6255 wstandout(view->window);
6256 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6257 if (tc)
6258 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6259 waddwstr(view->window, wline);
6260 while (width++ < view->ncols)
6261 waddch(view->window, ' ');
6262 if (tc)
6263 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6264 if (view_needs_focus_indication(view))
6265 wstandend(view->window);
6266 free(wline);
6267 wline = NULL;
6269 if (view->gline > blame->nlines)
6270 view->gline = blame->nlines;
6272 if (tog_io.wait_for_ui) {
6273 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6274 int rc;
6276 rc = pthread_cond_wait(&bta->blame_complete, &tog_mutex);
6277 if (rc)
6278 return got_error_set_errno(rc, "pthread_cond_wait");
6279 tog_io.wait_for_ui = 0;
6282 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6283 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6284 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6285 free(id_str);
6286 return got_error_from_errno("asprintf");
6288 free(id_str);
6289 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6290 free(line);
6291 line = NULL;
6292 if (err)
6293 return err;
6294 waddwstr(view->window, wline);
6295 free(wline);
6296 wline = NULL;
6297 if (width < view->ncols - 1)
6298 waddch(view->window, '\n');
6300 s->eof = 0;
6301 view->maxx = 0;
6302 while (nprinted < view->nlines - 2) {
6303 linelen = getline(&line, &linesize, blame->f);
6304 if (linelen == -1) {
6305 if (feof(blame->f)) {
6306 s->eof = 1;
6307 break;
6309 free(line);
6310 return got_ferror(blame->f, GOT_ERR_IO);
6312 if (++lineno < s->first_displayed_line)
6313 continue;
6314 if (view->gline && !gotoline(view, &lineno, &nprinted))
6315 continue;
6317 /* Set view->maxx based on full line length. */
6318 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6319 if (err) {
6320 free(line);
6321 return err;
6323 free(wline);
6324 wline = NULL;
6325 view->maxx = MAX(view->maxx, width);
6327 if (nprinted == s->selected_line - 1)
6328 wstandout(view->window);
6330 if (blame->nlines > 0) {
6331 blame_line = &blame->lines[lineno - 1];
6332 if (blame_line->annotated && prev_id &&
6333 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6334 !(nprinted == s->selected_line - 1)) {
6335 waddstr(view->window, " ");
6336 } else if (blame_line->annotated) {
6337 char *id_str;
6338 err = got_object_id_str(&id_str,
6339 blame_line->id);
6340 if (err) {
6341 free(line);
6342 return err;
6344 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6345 if (tc)
6346 wattr_on(view->window,
6347 COLOR_PAIR(tc->colorpair), NULL);
6348 wprintw(view->window, "%.8s", id_str);
6349 if (tc)
6350 wattr_off(view->window,
6351 COLOR_PAIR(tc->colorpair), NULL);
6352 free(id_str);
6353 prev_id = blame_line->id;
6354 } else {
6355 waddstr(view->window, "........");
6356 prev_id = NULL;
6358 } else {
6359 waddstr(view->window, "........");
6360 prev_id = NULL;
6363 if (nprinted == s->selected_line - 1)
6364 wstandend(view->window);
6365 waddstr(view->window, " ");
6367 if (view->ncols <= 9) {
6368 width = 9;
6369 } else if (s->first_displayed_line + nprinted ==
6370 s->matched_line &&
6371 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6372 err = add_matched_line(&width, line, view->ncols - 9, 9,
6373 view->window, view->x, regmatch);
6374 if (err) {
6375 free(line);
6376 return err;
6378 width += 9;
6379 } else {
6380 int skip;
6381 err = format_line(&wline, &width, &skip, line,
6382 view->x, view->ncols - 9, 9, 1);
6383 if (err) {
6384 free(line);
6385 return err;
6387 waddwstr(view->window, &wline[skip]);
6388 width += 9;
6389 free(wline);
6390 wline = NULL;
6393 if (width <= view->ncols - 1)
6394 waddch(view->window, '\n');
6395 if (++nprinted == 1)
6396 s->first_displayed_line = lineno;
6398 free(line);
6399 s->last_displayed_line = lineno;
6401 view_border(view);
6403 return NULL;
6406 static const struct got_error *
6407 blame_cb(void *arg, int nlines, int lineno,
6408 struct got_commit_object *commit, struct got_object_id *id)
6410 const struct got_error *err = NULL;
6411 struct tog_blame_cb_args *a = arg;
6412 struct tog_blame_line *line;
6413 int errcode;
6415 if (nlines != a->nlines ||
6416 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6417 return got_error(GOT_ERR_RANGE);
6419 errcode = pthread_mutex_lock(&tog_mutex);
6420 if (errcode)
6421 return got_error_set_errno(errcode, "pthread_mutex_lock");
6423 if (*a->quit) { /* user has quit the blame view */
6424 err = got_error(GOT_ERR_ITER_COMPLETED);
6425 goto done;
6428 if (lineno == -1)
6429 goto done; /* no change in this commit */
6431 line = &a->lines[lineno - 1];
6432 if (line->annotated)
6433 goto done;
6435 line->id = got_object_id_dup(id);
6436 if (line->id == NULL) {
6437 err = got_error_from_errno("got_object_id_dup");
6438 goto done;
6440 line->annotated = 1;
6441 done:
6442 errcode = pthread_mutex_unlock(&tog_mutex);
6443 if (errcode)
6444 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6445 return err;
6448 static void *
6449 blame_thread(void *arg)
6451 const struct got_error *err, *close_err;
6452 struct tog_blame_thread_args *ta = arg;
6453 struct tog_blame_cb_args *a = ta->cb_args;
6454 int errcode, fd1 = -1, fd2 = -1;
6455 FILE *f1 = NULL, *f2 = NULL;
6457 fd1 = got_opentempfd();
6458 if (fd1 == -1)
6459 return (void *)got_error_from_errno("got_opentempfd");
6461 fd2 = got_opentempfd();
6462 if (fd2 == -1) {
6463 err = got_error_from_errno("got_opentempfd");
6464 goto done;
6467 f1 = got_opentemp();
6468 if (f1 == NULL) {
6469 err = (void *)got_error_from_errno("got_opentemp");
6470 goto done;
6472 f2 = got_opentemp();
6473 if (f2 == NULL) {
6474 err = (void *)got_error_from_errno("got_opentemp");
6475 goto done;
6478 err = block_signals_used_by_main_thread();
6479 if (err)
6480 goto done;
6482 err = got_blame(ta->path, a->commit_id, ta->repo,
6483 tog_diff_algo, blame_cb, ta->cb_args,
6484 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6485 if (err && err->code == GOT_ERR_CANCELLED)
6486 err = NULL;
6488 errcode = pthread_mutex_lock(&tog_mutex);
6489 if (errcode) {
6490 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6491 goto done;
6494 close_err = got_repo_close(ta->repo);
6495 if (err == NULL)
6496 err = close_err;
6497 ta->repo = NULL;
6498 *ta->complete = 1;
6500 if (tog_io.wait_for_ui) {
6501 errcode = pthread_cond_signal(&ta->blame_complete);
6502 if (errcode && err == NULL)
6503 err = got_error_set_errno(errcode,
6504 "pthread_cond_signal");
6507 errcode = pthread_mutex_unlock(&tog_mutex);
6508 if (errcode && err == NULL)
6509 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6511 done:
6512 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6513 err = got_error_from_errno("close");
6514 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6515 err = got_error_from_errno("close");
6516 if (f1 && fclose(f1) == EOF && err == NULL)
6517 err = got_error_from_errno("fclose");
6518 if (f2 && fclose(f2) == EOF && err == NULL)
6519 err = got_error_from_errno("fclose");
6521 return (void *)err;
6524 static struct got_object_id *
6525 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6526 int first_displayed_line, int selected_line)
6528 struct tog_blame_line *line;
6530 if (nlines <= 0)
6531 return NULL;
6533 line = &lines[first_displayed_line - 1 + selected_line - 1];
6534 if (!line->annotated)
6535 return NULL;
6537 return line->id;
6540 static struct got_object_id *
6541 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6542 int lineno)
6544 struct tog_blame_line *line;
6546 if (nlines <= 0 || lineno >= nlines)
6547 return NULL;
6549 line = &lines[lineno - 1];
6550 if (!line->annotated)
6551 return NULL;
6553 return line->id;
6556 static const struct got_error *
6557 stop_blame(struct tog_blame *blame)
6559 const struct got_error *err = NULL;
6560 int i;
6562 if (blame->thread) {
6563 int errcode;
6564 errcode = pthread_mutex_unlock(&tog_mutex);
6565 if (errcode)
6566 return got_error_set_errno(errcode,
6567 "pthread_mutex_unlock");
6568 errcode = pthread_join(blame->thread, (void **)&err);
6569 if (errcode)
6570 return got_error_set_errno(errcode, "pthread_join");
6571 errcode = pthread_mutex_lock(&tog_mutex);
6572 if (errcode)
6573 return got_error_set_errno(errcode,
6574 "pthread_mutex_lock");
6575 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6576 err = NULL;
6577 blame->thread = NULL;
6579 if (blame->thread_args.repo) {
6580 const struct got_error *close_err;
6581 close_err = got_repo_close(blame->thread_args.repo);
6582 if (err == NULL)
6583 err = close_err;
6584 blame->thread_args.repo = NULL;
6586 if (blame->f) {
6587 if (fclose(blame->f) == EOF && err == NULL)
6588 err = got_error_from_errno("fclose");
6589 blame->f = NULL;
6591 if (blame->lines) {
6592 for (i = 0; i < blame->nlines; i++)
6593 free(blame->lines[i].id);
6594 free(blame->lines);
6595 blame->lines = NULL;
6597 free(blame->cb_args.commit_id);
6598 blame->cb_args.commit_id = NULL;
6599 if (blame->pack_fds) {
6600 const struct got_error *pack_err =
6601 got_repo_pack_fds_close(blame->pack_fds);
6602 if (err == NULL)
6603 err = pack_err;
6604 blame->pack_fds = NULL;
6606 return err;
6609 static const struct got_error *
6610 cancel_blame_view(void *arg)
6612 const struct got_error *err = NULL;
6613 int *done = arg;
6614 int errcode;
6616 errcode = pthread_mutex_lock(&tog_mutex);
6617 if (errcode)
6618 return got_error_set_errno(errcode,
6619 "pthread_mutex_unlock");
6621 if (*done)
6622 err = got_error(GOT_ERR_CANCELLED);
6624 errcode = pthread_mutex_unlock(&tog_mutex);
6625 if (errcode)
6626 return got_error_set_errno(errcode,
6627 "pthread_mutex_lock");
6629 return err;
6632 static const struct got_error *
6633 run_blame(struct tog_view *view)
6635 struct tog_blame_view_state *s = &view->state.blame;
6636 struct tog_blame *blame = &s->blame;
6637 const struct got_error *err = NULL;
6638 struct got_commit_object *commit = NULL;
6639 struct got_blob_object *blob = NULL;
6640 struct got_repository *thread_repo = NULL;
6641 struct got_object_id *obj_id = NULL;
6642 int obj_type, fd = -1;
6643 int *pack_fds = NULL;
6645 err = got_object_open_as_commit(&commit, s->repo,
6646 &s->blamed_commit->id);
6647 if (err)
6648 return err;
6650 fd = got_opentempfd();
6651 if (fd == -1) {
6652 err = got_error_from_errno("got_opentempfd");
6653 goto done;
6656 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6657 if (err)
6658 goto done;
6660 err = got_object_get_type(&obj_type, s->repo, obj_id);
6661 if (err)
6662 goto done;
6664 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6665 err = got_error(GOT_ERR_OBJ_TYPE);
6666 goto done;
6669 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6670 if (err)
6671 goto done;
6672 blame->f = got_opentemp();
6673 if (blame->f == NULL) {
6674 err = got_error_from_errno("got_opentemp");
6675 goto done;
6677 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6678 &blame->line_offsets, blame->f, blob);
6679 if (err)
6680 goto done;
6681 if (blame->nlines == 0) {
6682 s->blame_complete = 1;
6683 goto done;
6686 /* Don't include \n at EOF in the blame line count. */
6687 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6688 blame->nlines--;
6690 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6691 if (blame->lines == NULL) {
6692 err = got_error_from_errno("calloc");
6693 goto done;
6696 err = got_repo_pack_fds_open(&pack_fds);
6697 if (err)
6698 goto done;
6699 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6700 pack_fds);
6701 if (err)
6702 goto done;
6704 blame->pack_fds = pack_fds;
6705 blame->cb_args.view = view;
6706 blame->cb_args.lines = blame->lines;
6707 blame->cb_args.nlines = blame->nlines;
6708 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6709 if (blame->cb_args.commit_id == NULL) {
6710 err = got_error_from_errno("got_object_id_dup");
6711 goto done;
6713 blame->cb_args.quit = &s->done;
6715 blame->thread_args.path = s->path;
6716 blame->thread_args.repo = thread_repo;
6717 blame->thread_args.cb_args = &blame->cb_args;
6718 blame->thread_args.complete = &s->blame_complete;
6719 blame->thread_args.cancel_cb = cancel_blame_view;
6720 blame->thread_args.cancel_arg = &s->done;
6721 s->blame_complete = 0;
6723 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6724 s->first_displayed_line = 1;
6725 s->last_displayed_line = view->nlines;
6726 s->selected_line = 1;
6728 s->matched_line = 0;
6730 done:
6731 if (commit)
6732 got_object_commit_close(commit);
6733 if (fd != -1 && close(fd) == -1 && err == NULL)
6734 err = got_error_from_errno("close");
6735 if (blob)
6736 got_object_blob_close(blob);
6737 free(obj_id);
6738 if (err)
6739 stop_blame(blame);
6740 return err;
6743 static const struct got_error *
6744 open_blame_view(struct tog_view *view, char *path,
6745 struct got_object_id *commit_id, struct got_repository *repo)
6747 const struct got_error *err = NULL;
6748 struct tog_blame_view_state *s = &view->state.blame;
6750 STAILQ_INIT(&s->blamed_commits);
6752 s->path = strdup(path);
6753 if (s->path == NULL)
6754 return got_error_from_errno("strdup");
6756 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6757 if (err) {
6758 free(s->path);
6759 return err;
6762 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6763 s->first_displayed_line = 1;
6764 s->last_displayed_line = view->nlines;
6765 s->selected_line = 1;
6766 s->blame_complete = 0;
6767 s->repo = repo;
6768 s->commit_id = commit_id;
6769 memset(&s->blame, 0, sizeof(s->blame));
6771 STAILQ_INIT(&s->colors);
6772 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6773 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6774 get_color_value("TOG_COLOR_COMMIT"));
6775 if (err)
6776 return err;
6779 view->show = show_blame_view;
6780 view->input = input_blame_view;
6781 view->reset = reset_blame_view;
6782 view->close = close_blame_view;
6783 view->search_start = search_start_blame_view;
6784 view->search_setup = search_setup_blame_view;
6785 view->search_next = search_next_view_match;
6787 if (using_mock_io) {
6788 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6789 int rc;
6791 rc = pthread_cond_init(&bta->blame_complete, NULL);
6792 if (rc)
6793 return got_error_set_errno(rc, "pthread_cond_init");
6796 return run_blame(view);
6799 static const struct got_error *
6800 close_blame_view(struct tog_view *view)
6802 const struct got_error *err = NULL;
6803 struct tog_blame_view_state *s = &view->state.blame;
6805 if (s->blame.thread)
6806 err = stop_blame(&s->blame);
6808 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6809 struct got_object_qid *blamed_commit;
6810 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6811 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6812 got_object_qid_free(blamed_commit);
6815 if (using_mock_io) {
6816 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6817 int rc;
6819 rc = pthread_cond_destroy(&bta->blame_complete);
6820 if (rc && err == NULL)
6821 err = got_error_set_errno(rc, "pthread_cond_destroy");
6824 free(s->path);
6825 free_colors(&s->colors);
6826 return err;
6829 static const struct got_error *
6830 search_start_blame_view(struct tog_view *view)
6832 struct tog_blame_view_state *s = &view->state.blame;
6834 s->matched_line = 0;
6835 return NULL;
6838 static void
6839 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6840 size_t *nlines, int **first, int **last, int **match, int **selected)
6842 struct tog_blame_view_state *s = &view->state.blame;
6844 *f = s->blame.f;
6845 *nlines = s->blame.nlines;
6846 *line_offsets = s->blame.line_offsets;
6847 *match = &s->matched_line;
6848 *first = &s->first_displayed_line;
6849 *last = &s->last_displayed_line;
6850 *selected = &s->selected_line;
6853 static const struct got_error *
6854 show_blame_view(struct tog_view *view)
6856 const struct got_error *err = NULL;
6857 struct tog_blame_view_state *s = &view->state.blame;
6858 int errcode;
6860 if (s->blame.thread == NULL && !s->blame_complete) {
6861 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6862 &s->blame.thread_args);
6863 if (errcode)
6864 return got_error_set_errno(errcode, "pthread_create");
6866 if (!using_mock_io)
6867 halfdelay(1); /* fast refresh while annotating */
6870 if (s->blame_complete && !using_mock_io)
6871 halfdelay(10); /* disable fast refresh */
6873 err = draw_blame(view);
6875 view_border(view);
6876 return err;
6879 static const struct got_error *
6880 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6881 struct got_repository *repo, struct got_object_id *id)
6883 struct tog_view *log_view;
6884 const struct got_error *err = NULL;
6886 *new_view = NULL;
6888 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6889 if (log_view == NULL)
6890 return got_error_from_errno("view_open");
6892 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0, NULL);
6893 if (err)
6894 view_close(log_view);
6895 else
6896 *new_view = log_view;
6898 return err;
6901 static const struct got_error *
6902 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6904 const struct got_error *err = NULL, *thread_err = NULL;
6905 struct tog_view *diff_view;
6906 struct tog_blame_view_state *s = &view->state.blame;
6907 int eos, nscroll, begin_y = 0, begin_x = 0;
6909 eos = nscroll = view->nlines - 2;
6910 if (view_is_hsplit_top(view))
6911 --eos; /* border */
6913 switch (ch) {
6914 case '0':
6915 case '$':
6916 case KEY_RIGHT:
6917 case 'l':
6918 case KEY_LEFT:
6919 case 'h':
6920 horizontal_scroll_input(view, ch);
6921 break;
6922 case 'q':
6923 s->done = 1;
6924 break;
6925 case 'g':
6926 case KEY_HOME:
6927 s->selected_line = 1;
6928 s->first_displayed_line = 1;
6929 view->count = 0;
6930 break;
6931 case 'G':
6932 case KEY_END:
6933 if (s->blame.nlines < eos) {
6934 s->selected_line = s->blame.nlines;
6935 s->first_displayed_line = 1;
6936 } else {
6937 s->selected_line = eos;
6938 s->first_displayed_line = s->blame.nlines - (eos - 1);
6940 view->count = 0;
6941 break;
6942 case 'k':
6943 case KEY_UP:
6944 case CTRL('p'):
6945 if (s->selected_line > 1)
6946 s->selected_line--;
6947 else if (s->selected_line == 1 &&
6948 s->first_displayed_line > 1)
6949 s->first_displayed_line--;
6950 else
6951 view->count = 0;
6952 break;
6953 case CTRL('u'):
6954 case 'u':
6955 nscroll /= 2;
6956 /* FALL THROUGH */
6957 case KEY_PPAGE:
6958 case CTRL('b'):
6959 case 'b':
6960 if (s->first_displayed_line == 1) {
6961 if (view->count > 1)
6962 nscroll += nscroll;
6963 s->selected_line = MAX(1, s->selected_line - nscroll);
6964 view->count = 0;
6965 break;
6967 if (s->first_displayed_line > nscroll)
6968 s->first_displayed_line -= nscroll;
6969 else
6970 s->first_displayed_line = 1;
6971 break;
6972 case 'j':
6973 case KEY_DOWN:
6974 case CTRL('n'):
6975 if (s->selected_line < eos && s->first_displayed_line +
6976 s->selected_line <= s->blame.nlines)
6977 s->selected_line++;
6978 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6979 s->first_displayed_line++;
6980 else
6981 view->count = 0;
6982 break;
6983 case 'c':
6984 case 'p': {
6985 struct got_object_id *id = NULL;
6987 view->count = 0;
6988 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6989 s->first_displayed_line, s->selected_line);
6990 if (id == NULL)
6991 break;
6992 if (ch == 'p') {
6993 struct got_commit_object *commit, *pcommit;
6994 struct got_object_qid *pid;
6995 struct got_object_id *blob_id = NULL;
6996 int obj_type;
6997 err = got_object_open_as_commit(&commit,
6998 s->repo, id);
6999 if (err)
7000 break;
7001 pid = STAILQ_FIRST(
7002 got_object_commit_get_parent_ids(commit));
7003 if (pid == NULL) {
7004 got_object_commit_close(commit);
7005 break;
7007 /* Check if path history ends here. */
7008 err = got_object_open_as_commit(&pcommit,
7009 s->repo, &pid->id);
7010 if (err)
7011 break;
7012 err = got_object_id_by_path(&blob_id, s->repo,
7013 pcommit, s->path);
7014 got_object_commit_close(pcommit);
7015 if (err) {
7016 if (err->code == GOT_ERR_NO_TREE_ENTRY)
7017 err = NULL;
7018 got_object_commit_close(commit);
7019 break;
7021 err = got_object_get_type(&obj_type, s->repo,
7022 blob_id);
7023 free(blob_id);
7024 /* Can't blame non-blob type objects. */
7025 if (obj_type != GOT_OBJ_TYPE_BLOB) {
7026 got_object_commit_close(commit);
7027 break;
7029 err = got_object_qid_alloc(&s->blamed_commit,
7030 &pid->id);
7031 got_object_commit_close(commit);
7032 } else {
7033 if (got_object_id_cmp(id,
7034 &s->blamed_commit->id) == 0)
7035 break;
7036 err = got_object_qid_alloc(&s->blamed_commit,
7037 id);
7039 if (err)
7040 break;
7041 s->done = 1;
7042 thread_err = stop_blame(&s->blame);
7043 s->done = 0;
7044 if (thread_err)
7045 break;
7046 STAILQ_INSERT_HEAD(&s->blamed_commits,
7047 s->blamed_commit, entry);
7048 err = run_blame(view);
7049 if (err)
7050 break;
7051 break;
7053 case 'C': {
7054 struct got_object_qid *first;
7056 view->count = 0;
7057 first = STAILQ_FIRST(&s->blamed_commits);
7058 if (!got_object_id_cmp(&first->id, s->commit_id))
7059 break;
7060 s->done = 1;
7061 thread_err = stop_blame(&s->blame);
7062 s->done = 0;
7063 if (thread_err)
7064 break;
7065 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
7066 got_object_qid_free(s->blamed_commit);
7067 s->blamed_commit =
7068 STAILQ_FIRST(&s->blamed_commits);
7069 err = run_blame(view);
7070 if (err)
7071 break;
7072 break;
7074 case 'L':
7075 view->count = 0;
7076 s->id_to_log = get_selected_commit_id(s->blame.lines,
7077 s->blame.nlines, s->first_displayed_line, s->selected_line);
7078 if (s->id_to_log)
7079 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7080 break;
7081 case KEY_ENTER:
7082 case '\r': {
7083 struct got_object_id *id = NULL;
7084 struct got_object_qid *pid;
7085 struct got_commit_object *commit = NULL;
7087 view->count = 0;
7088 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
7089 s->first_displayed_line, s->selected_line);
7090 if (id == NULL)
7091 break;
7092 err = got_object_open_as_commit(&commit, s->repo, id);
7093 if (err)
7094 break;
7095 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
7096 if (*new_view) {
7097 /* traversed from diff view, release diff resources */
7098 err = close_diff_view(*new_view);
7099 if (err)
7100 break;
7101 diff_view = *new_view;
7102 } else {
7103 if (view_is_parent_view(view))
7104 view_get_split(view, &begin_y, &begin_x);
7106 diff_view = view_open(0, 0, begin_y, begin_x,
7107 TOG_VIEW_DIFF);
7108 if (diff_view == NULL) {
7109 got_object_commit_close(commit);
7110 err = got_error_from_errno("view_open");
7111 break;
7114 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
7115 id, NULL, NULL, 3, 0, 0, view, s->repo);
7116 got_object_commit_close(commit);
7117 if (err)
7118 break;
7119 s->last_diffed_line = s->first_displayed_line - 1 +
7120 s->selected_line;
7121 if (*new_view)
7122 break; /* still open from active diff view */
7123 if (view_is_parent_view(view) &&
7124 view->mode == TOG_VIEW_SPLIT_HRZN) {
7125 err = view_init_hsplit(view, begin_y);
7126 if (err)
7127 break;
7130 view->focussed = 0;
7131 diff_view->focussed = 1;
7132 diff_view->mode = view->mode;
7133 diff_view->nlines = view->lines - begin_y;
7134 if (view_is_parent_view(view)) {
7135 view_transfer_size(diff_view, view);
7136 err = view_close_child(view);
7137 if (err)
7138 break;
7139 err = view_set_child(view, diff_view);
7140 if (err)
7141 break;
7142 view->focus_child = 1;
7143 } else
7144 *new_view = diff_view;
7145 if (err)
7146 break;
7147 break;
7149 case CTRL('d'):
7150 case 'd':
7151 nscroll /= 2;
7152 /* FALL THROUGH */
7153 case KEY_NPAGE:
7154 case CTRL('f'):
7155 case 'f':
7156 case ' ':
7157 if (s->last_displayed_line >= s->blame.nlines &&
7158 s->selected_line >= MIN(s->blame.nlines,
7159 view->nlines - 2)) {
7160 view->count = 0;
7161 break;
7163 if (s->last_displayed_line >= s->blame.nlines &&
7164 s->selected_line < view->nlines - 2) {
7165 s->selected_line +=
7166 MIN(nscroll, s->last_displayed_line -
7167 s->first_displayed_line - s->selected_line + 1);
7169 if (s->last_displayed_line + nscroll <= s->blame.nlines)
7170 s->first_displayed_line += nscroll;
7171 else
7172 s->first_displayed_line =
7173 s->blame.nlines - (view->nlines - 3);
7174 break;
7175 case KEY_RESIZE:
7176 if (s->selected_line > view->nlines - 2) {
7177 s->selected_line = MIN(s->blame.nlines,
7178 view->nlines - 2);
7180 break;
7181 default:
7182 view->count = 0;
7183 break;
7185 return thread_err ? thread_err : err;
7188 static const struct got_error *
7189 reset_blame_view(struct tog_view *view)
7191 const struct got_error *err;
7192 struct tog_blame_view_state *s = &view->state.blame;
7194 view->count = 0;
7195 s->done = 1;
7196 err = stop_blame(&s->blame);
7197 s->done = 0;
7198 if (err)
7199 return err;
7200 return run_blame(view);
7203 static const struct got_error *
7204 cmd_blame(int argc, char *argv[])
7206 const struct got_error *error;
7207 struct got_repository *repo = NULL;
7208 struct got_worktree *worktree = NULL;
7209 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7210 char *link_target = NULL;
7211 struct got_object_id *commit_id = NULL;
7212 struct got_commit_object *commit = NULL;
7213 char *keyword_idstr = NULL, *commit_id_str = NULL;
7214 int ch;
7215 struct tog_view *view = NULL;
7216 int *pack_fds = NULL;
7218 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7219 switch (ch) {
7220 case 'c':
7221 commit_id_str = optarg;
7222 break;
7223 case 'r':
7224 repo_path = realpath(optarg, NULL);
7225 if (repo_path == NULL)
7226 return got_error_from_errno2("realpath",
7227 optarg);
7228 break;
7229 default:
7230 usage_blame();
7231 /* NOTREACHED */
7235 argc -= optind;
7236 argv += optind;
7238 if (argc != 1)
7239 usage_blame();
7241 error = got_repo_pack_fds_open(&pack_fds);
7242 if (error != NULL)
7243 goto done;
7245 if (repo_path == NULL) {
7246 cwd = getcwd(NULL, 0);
7247 if (cwd == NULL)
7248 return got_error_from_errno("getcwd");
7249 error = got_worktree_open(&worktree, cwd, NULL);
7250 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7251 goto done;
7252 if (worktree)
7253 repo_path =
7254 strdup(got_worktree_get_repo_path(worktree));
7255 else
7256 repo_path = strdup(cwd);
7257 if (repo_path == NULL) {
7258 error = got_error_from_errno("strdup");
7259 goto done;
7263 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7264 if (error != NULL)
7265 goto done;
7267 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
7268 worktree);
7269 if (error)
7270 goto done;
7272 init_curses();
7274 error = apply_unveil(got_repo_get_path(repo), NULL);
7275 if (error)
7276 goto done;
7278 error = tog_load_refs(repo, 0);
7279 if (error)
7280 goto done;
7282 if (commit_id_str == NULL) {
7283 struct got_reference *head_ref;
7284 error = got_ref_open(&head_ref, repo, worktree ?
7285 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7286 if (error != NULL)
7287 goto done;
7288 error = got_ref_resolve(&commit_id, repo, head_ref);
7289 got_ref_close(head_ref);
7290 } else {
7291 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
7292 repo, worktree);
7293 if (error != NULL)
7294 goto done;
7295 if (keyword_idstr != NULL)
7296 commit_id_str = keyword_idstr;
7298 error = got_repo_match_object_id(&commit_id, NULL,
7299 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7301 if (error != NULL)
7302 goto done;
7304 error = got_object_open_as_commit(&commit, repo, commit_id);
7305 if (error)
7306 goto done;
7308 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7309 commit, repo);
7310 if (error)
7311 goto done;
7313 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7314 if (view == NULL) {
7315 error = got_error_from_errno("view_open");
7316 goto done;
7318 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7319 commit_id, repo);
7320 if (error != NULL) {
7321 if (view->close == NULL)
7322 close_blame_view(view);
7323 view_close(view);
7324 goto done;
7327 if (worktree) {
7328 error = set_tog_base_commit(repo, worktree);
7329 if (error != NULL)
7330 goto done;
7332 /* Release work tree lock. */
7333 got_worktree_close(worktree);
7334 worktree = NULL;
7337 error = view_loop(view);
7339 done:
7340 free(tog_base_commit.id);
7341 free(repo_path);
7342 free(in_repo_path);
7343 free(link_target);
7344 free(cwd);
7345 free(commit_id);
7346 free(keyword_idstr);
7347 if (commit)
7348 got_object_commit_close(commit);
7349 if (worktree)
7350 got_worktree_close(worktree);
7351 if (repo) {
7352 const struct got_error *close_err = got_repo_close(repo);
7353 if (error == NULL)
7354 error = close_err;
7356 if (pack_fds) {
7357 const struct got_error *pack_err =
7358 got_repo_pack_fds_close(pack_fds);
7359 if (error == NULL)
7360 error = pack_err;
7362 tog_free_refs();
7363 return error;
7366 static const struct got_error *
7367 draw_tree_entries(struct tog_view *view, const char *parent_path)
7369 struct tog_tree_view_state *s = &view->state.tree;
7370 const struct got_error *err = NULL;
7371 struct got_tree_entry *te;
7372 wchar_t *wline;
7373 char *index = NULL;
7374 struct tog_color *tc;
7375 int width, n, nentries, scrollx, i = 1;
7376 int limit = view->nlines;
7378 s->ndisplayed = 0;
7379 if (view_is_hsplit_top(view))
7380 --limit; /* border */
7382 werase(view->window);
7384 if (limit == 0)
7385 return NULL;
7387 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7388 0, 0);
7389 if (err)
7390 return err;
7391 if (view_needs_focus_indication(view))
7392 wstandout(view->window);
7393 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7394 if (tc)
7395 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7396 waddwstr(view->window, wline);
7397 free(wline);
7398 wline = NULL;
7399 while (width++ < view->ncols)
7400 waddch(view->window, ' ');
7401 if (tc)
7402 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7403 if (view_needs_focus_indication(view))
7404 wstandend(view->window);
7405 if (--limit <= 0)
7406 return NULL;
7408 i += s->selected;
7409 if (s->first_displayed_entry) {
7410 i += got_tree_entry_get_index(s->first_displayed_entry);
7411 if (s->tree != s->root)
7412 ++i; /* account for ".." entry */
7414 nentries = got_object_tree_get_nentries(s->tree);
7415 if (asprintf(&index, "[%d/%d] %s",
7416 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7417 return got_error_from_errno("asprintf");
7418 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7419 free(index);
7420 if (err)
7421 return err;
7422 waddwstr(view->window, wline);
7423 free(wline);
7424 wline = NULL;
7425 if (width < view->ncols - 1)
7426 waddch(view->window, '\n');
7427 if (--limit <= 0)
7428 return NULL;
7429 waddch(view->window, '\n');
7430 if (--limit <= 0)
7431 return NULL;
7433 if (s->first_displayed_entry == NULL) {
7434 te = got_object_tree_get_first_entry(s->tree);
7435 if (s->selected == 0) {
7436 if (view->focussed)
7437 wstandout(view->window);
7438 s->selected_entry = NULL;
7440 waddstr(view->window, " ..\n"); /* parent directory */
7441 if (s->selected == 0 && view->focussed)
7442 wstandend(view->window);
7443 s->ndisplayed++;
7444 if (--limit <= 0)
7445 return NULL;
7446 n = 1;
7447 } else {
7448 n = 0;
7449 te = s->first_displayed_entry;
7452 view->maxx = 0;
7453 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7454 char *line = NULL, *id_str = NULL, *link_target = NULL;
7455 const char *modestr = "";
7456 mode_t mode;
7458 te = got_object_tree_get_entry(s->tree, i);
7459 mode = got_tree_entry_get_mode(te);
7461 if (s->show_ids) {
7462 err = got_object_id_str(&id_str,
7463 got_tree_entry_get_id(te));
7464 if (err)
7465 return got_error_from_errno(
7466 "got_object_id_str");
7468 if (got_object_tree_entry_is_submodule(te))
7469 modestr = "$";
7470 else if (S_ISLNK(mode)) {
7471 int i;
7473 err = got_tree_entry_get_symlink_target(&link_target,
7474 te, s->repo);
7475 if (err) {
7476 free(id_str);
7477 return err;
7479 for (i = 0; link_target[i] != '\0'; i++) {
7480 if (!isprint((unsigned char)link_target[i]))
7481 link_target[i] = '?';
7483 modestr = "@";
7485 else if (S_ISDIR(mode))
7486 modestr = "/";
7487 else if (mode & S_IXUSR)
7488 modestr = "*";
7489 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7490 got_tree_entry_get_name(te), modestr,
7491 link_target ? " -> ": "",
7492 link_target ? link_target : "") == -1) {
7493 free(id_str);
7494 free(link_target);
7495 return got_error_from_errno("asprintf");
7497 free(id_str);
7498 free(link_target);
7500 /* use full line width to determine view->maxx */
7501 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7502 if (err) {
7503 free(line);
7504 break;
7506 view->maxx = MAX(view->maxx, width);
7507 free(wline);
7508 wline = NULL;
7510 err = format_line(&wline, &width, &scrollx, line, view->x,
7511 view->ncols, 0, 0);
7512 if (err) {
7513 free(line);
7514 break;
7516 if (n == s->selected) {
7517 if (view->focussed)
7518 wstandout(view->window);
7519 s->selected_entry = te;
7521 tc = match_color(&s->colors, line);
7522 if (tc)
7523 wattr_on(view->window,
7524 COLOR_PAIR(tc->colorpair), NULL);
7525 waddwstr(view->window, &wline[scrollx]);
7526 if (tc)
7527 wattr_off(view->window,
7528 COLOR_PAIR(tc->colorpair), NULL);
7529 if (width < view->ncols)
7530 waddch(view->window, '\n');
7531 if (n == s->selected && view->focussed)
7532 wstandend(view->window);
7533 free(line);
7534 free(wline);
7535 wline = NULL;
7536 n++;
7537 s->ndisplayed++;
7538 s->last_displayed_entry = te;
7539 if (--limit <= 0)
7540 break;
7543 return err;
7546 static void
7547 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7549 struct got_tree_entry *te;
7550 int isroot = s->tree == s->root;
7551 int i = 0;
7553 if (s->first_displayed_entry == NULL)
7554 return;
7556 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7557 while (i++ < maxscroll) {
7558 if (te == NULL) {
7559 if (!isroot)
7560 s->first_displayed_entry = NULL;
7561 break;
7563 s->first_displayed_entry = te;
7564 te = got_tree_entry_get_prev(s->tree, te);
7568 static const struct got_error *
7569 tree_scroll_down(struct tog_view *view, int maxscroll)
7571 struct tog_tree_view_state *s = &view->state.tree;
7572 struct got_tree_entry *next, *last;
7573 int n = 0;
7575 if (s->first_displayed_entry)
7576 next = got_tree_entry_get_next(s->tree,
7577 s->first_displayed_entry);
7578 else
7579 next = got_object_tree_get_first_entry(s->tree);
7581 last = s->last_displayed_entry;
7582 while (next && n++ < maxscroll) {
7583 if (last) {
7584 s->last_displayed_entry = last;
7585 last = got_tree_entry_get_next(s->tree, last);
7587 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7588 s->first_displayed_entry = next;
7589 next = got_tree_entry_get_next(s->tree, next);
7593 return NULL;
7596 static const struct got_error *
7597 tree_entry_path(char **path, struct tog_parent_trees *parents,
7598 struct got_tree_entry *te)
7600 const struct got_error *err = NULL;
7601 struct tog_parent_tree *pt;
7602 size_t len = 2; /* for leading slash and NUL */
7604 TAILQ_FOREACH(pt, parents, entry)
7605 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7606 + 1 /* slash */;
7607 if (te)
7608 len += strlen(got_tree_entry_get_name(te));
7610 *path = calloc(1, len);
7611 if (path == NULL)
7612 return got_error_from_errno("calloc");
7614 (*path)[0] = '/';
7615 pt = TAILQ_LAST(parents, tog_parent_trees);
7616 while (pt) {
7617 const char *name = got_tree_entry_get_name(pt->selected_entry);
7618 if (strlcat(*path, name, len) >= len) {
7619 err = got_error(GOT_ERR_NO_SPACE);
7620 goto done;
7622 if (strlcat(*path, "/", len) >= len) {
7623 err = got_error(GOT_ERR_NO_SPACE);
7624 goto done;
7626 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7628 if (te) {
7629 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7630 err = got_error(GOT_ERR_NO_SPACE);
7631 goto done;
7634 done:
7635 if (err) {
7636 free(*path);
7637 *path = NULL;
7639 return err;
7642 static const struct got_error *
7643 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7644 struct got_tree_entry *te, struct tog_parent_trees *parents,
7645 struct got_object_id *commit_id, struct got_repository *repo)
7647 const struct got_error *err = NULL;
7648 char *path;
7649 struct tog_view *blame_view;
7651 *new_view = NULL;
7653 err = tree_entry_path(&path, parents, te);
7654 if (err)
7655 return err;
7657 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7658 if (blame_view == NULL) {
7659 err = got_error_from_errno("view_open");
7660 goto done;
7663 err = open_blame_view(blame_view, path, commit_id, repo);
7664 if (err) {
7665 if (err->code == GOT_ERR_CANCELLED)
7666 err = NULL;
7667 view_close(blame_view);
7668 } else
7669 *new_view = blame_view;
7670 done:
7671 free(path);
7672 return err;
7675 static const struct got_error *
7676 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7677 struct tog_tree_view_state *s)
7679 struct tog_view *log_view;
7680 const struct got_error *err = NULL;
7681 char *path;
7683 *new_view = NULL;
7685 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7686 if (log_view == NULL)
7687 return got_error_from_errno("view_open");
7689 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7690 if (err)
7691 return err;
7693 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7694 path, 0, NULL);
7695 if (err)
7696 view_close(log_view);
7697 else
7698 *new_view = log_view;
7699 free(path);
7700 return err;
7703 static const struct got_error *
7704 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7705 const char *head_ref_name, struct got_repository *repo)
7707 const struct got_error *err = NULL;
7708 char *commit_id_str = NULL;
7709 struct tog_tree_view_state *s = &view->state.tree;
7710 struct got_commit_object *commit = NULL;
7712 TAILQ_INIT(&s->parents);
7713 STAILQ_INIT(&s->colors);
7715 s->commit_id = got_object_id_dup(commit_id);
7716 if (s->commit_id == NULL) {
7717 err = got_error_from_errno("got_object_id_dup");
7718 goto done;
7721 err = got_object_open_as_commit(&commit, repo, commit_id);
7722 if (err)
7723 goto done;
7726 * The root is opened here and will be closed when the view is closed.
7727 * Any visited subtrees and their path-wise parents are opened and
7728 * closed on demand.
7730 err = got_object_open_as_tree(&s->root, repo,
7731 got_object_commit_get_tree_id(commit));
7732 if (err)
7733 goto done;
7734 s->tree = s->root;
7736 err = got_object_id_str(&commit_id_str, commit_id);
7737 if (err != NULL)
7738 goto done;
7740 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7741 err = got_error_from_errno("asprintf");
7742 goto done;
7745 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7746 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7747 if (head_ref_name) {
7748 s->head_ref_name = strdup(head_ref_name);
7749 if (s->head_ref_name == NULL) {
7750 err = got_error_from_errno("strdup");
7751 goto done;
7754 s->repo = repo;
7756 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7757 err = add_color(&s->colors, "\\$$",
7758 TOG_COLOR_TREE_SUBMODULE,
7759 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7760 if (err)
7761 goto done;
7762 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7763 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7764 if (err)
7765 goto done;
7766 err = add_color(&s->colors, "/$",
7767 TOG_COLOR_TREE_DIRECTORY,
7768 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7769 if (err)
7770 goto done;
7772 err = add_color(&s->colors, "\\*$",
7773 TOG_COLOR_TREE_EXECUTABLE,
7774 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7775 if (err)
7776 goto done;
7778 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7779 get_color_value("TOG_COLOR_COMMIT"));
7780 if (err)
7781 goto done;
7784 view->show = show_tree_view;
7785 view->input = input_tree_view;
7786 view->close = close_tree_view;
7787 view->search_start = search_start_tree_view;
7788 view->search_next = search_next_tree_view;
7789 done:
7790 free(commit_id_str);
7791 if (commit)
7792 got_object_commit_close(commit);
7793 if (err) {
7794 if (view->close == NULL)
7795 close_tree_view(view);
7796 view_close(view);
7798 return err;
7801 static const struct got_error *
7802 close_tree_view(struct tog_view *view)
7804 struct tog_tree_view_state *s = &view->state.tree;
7806 free_colors(&s->colors);
7807 free(s->tree_label);
7808 s->tree_label = NULL;
7809 free(s->commit_id);
7810 s->commit_id = NULL;
7811 free(s->head_ref_name);
7812 s->head_ref_name = NULL;
7813 while (!TAILQ_EMPTY(&s->parents)) {
7814 struct tog_parent_tree *parent;
7815 parent = TAILQ_FIRST(&s->parents);
7816 TAILQ_REMOVE(&s->parents, parent, entry);
7817 if (parent->tree != s->root)
7818 got_object_tree_close(parent->tree);
7819 free(parent);
7822 if (s->tree != NULL && s->tree != s->root)
7823 got_object_tree_close(s->tree);
7824 if (s->root)
7825 got_object_tree_close(s->root);
7826 return NULL;
7829 static const struct got_error *
7830 search_start_tree_view(struct tog_view *view)
7832 struct tog_tree_view_state *s = &view->state.tree;
7834 s->matched_entry = NULL;
7835 return NULL;
7838 static int
7839 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7841 regmatch_t regmatch;
7843 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7844 0) == 0;
7847 static const struct got_error *
7848 search_next_tree_view(struct tog_view *view)
7850 struct tog_tree_view_state *s = &view->state.tree;
7851 struct got_tree_entry *te = NULL;
7853 if (!view->searching) {
7854 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7855 return NULL;
7858 if (s->matched_entry) {
7859 if (view->searching == TOG_SEARCH_FORWARD) {
7860 if (s->selected_entry)
7861 te = got_tree_entry_get_next(s->tree,
7862 s->selected_entry);
7863 else
7864 te = got_object_tree_get_first_entry(s->tree);
7865 } else {
7866 if (s->selected_entry == NULL)
7867 te = got_object_tree_get_last_entry(s->tree);
7868 else
7869 te = got_tree_entry_get_prev(s->tree,
7870 s->selected_entry);
7872 } else {
7873 if (s->selected_entry)
7874 te = s->selected_entry;
7875 else if (view->searching == TOG_SEARCH_FORWARD)
7876 te = got_object_tree_get_first_entry(s->tree);
7877 else
7878 te = got_object_tree_get_last_entry(s->tree);
7881 while (1) {
7882 if (te == NULL) {
7883 if (s->matched_entry == NULL) {
7884 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7885 return NULL;
7887 if (view->searching == TOG_SEARCH_FORWARD)
7888 te = got_object_tree_get_first_entry(s->tree);
7889 else
7890 te = got_object_tree_get_last_entry(s->tree);
7893 if (match_tree_entry(te, &view->regex)) {
7894 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7895 s->matched_entry = te;
7896 break;
7899 if (view->searching == TOG_SEARCH_FORWARD)
7900 te = got_tree_entry_get_next(s->tree, te);
7901 else
7902 te = got_tree_entry_get_prev(s->tree, te);
7905 if (s->matched_entry) {
7906 s->first_displayed_entry = s->matched_entry;
7907 s->selected = 0;
7910 return NULL;
7913 static const struct got_error *
7914 show_tree_view(struct tog_view *view)
7916 const struct got_error *err = NULL;
7917 struct tog_tree_view_state *s = &view->state.tree;
7918 char *parent_path;
7920 err = tree_entry_path(&parent_path, &s->parents, NULL);
7921 if (err)
7922 return err;
7924 err = draw_tree_entries(view, parent_path);
7925 free(parent_path);
7927 view_border(view);
7928 return err;
7931 static const struct got_error *
7932 tree_goto_line(struct tog_view *view, int nlines)
7934 const struct got_error *err = NULL;
7935 struct tog_tree_view_state *s = &view->state.tree;
7936 struct got_tree_entry **fte, **lte, **ste;
7937 int g, last, first = 1, i = 1;
7938 int root = s->tree == s->root;
7939 int off = root ? 1 : 2;
7941 g = view->gline;
7942 view->gline = 0;
7944 if (g == 0)
7945 g = 1;
7946 else if (g > got_object_tree_get_nentries(s->tree))
7947 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7949 fte = &s->first_displayed_entry;
7950 lte = &s->last_displayed_entry;
7951 ste = &s->selected_entry;
7953 if (*fte != NULL) {
7954 first = got_tree_entry_get_index(*fte);
7955 first += off; /* account for ".." */
7957 last = got_tree_entry_get_index(*lte);
7958 last += off;
7960 if (g >= first && g <= last && g - first < nlines) {
7961 s->selected = g - first;
7962 return NULL; /* gline is on the current page */
7965 if (*ste != NULL) {
7966 i = got_tree_entry_get_index(*ste);
7967 i += off;
7970 if (i < g) {
7971 err = tree_scroll_down(view, g - i);
7972 if (err)
7973 return err;
7974 if (got_tree_entry_get_index(*lte) >=
7975 got_object_tree_get_nentries(s->tree) - 1 &&
7976 first + s->selected < g &&
7977 s->selected < s->ndisplayed - 1) {
7978 first = got_tree_entry_get_index(*fte);
7979 first += off;
7980 s->selected = g - first;
7982 } else if (i > g)
7983 tree_scroll_up(s, i - g);
7985 if (g < nlines &&
7986 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7987 s->selected = g - 1;
7989 return NULL;
7992 static const struct got_error *
7993 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7995 const struct got_error *err = NULL;
7996 struct tog_tree_view_state *s = &view->state.tree;
7997 struct got_tree_entry *te;
7998 int n, nscroll = view->nlines - 3;
8000 if (view->gline)
8001 return tree_goto_line(view, nscroll);
8003 switch (ch) {
8004 case '0':
8005 case '$':
8006 case KEY_RIGHT:
8007 case 'l':
8008 case KEY_LEFT:
8009 case 'h':
8010 horizontal_scroll_input(view, ch);
8011 break;
8012 case 'i':
8013 s->show_ids = !s->show_ids;
8014 view->count = 0;
8015 break;
8016 case 'L':
8017 view->count = 0;
8018 if (!s->selected_entry)
8019 break;
8020 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8021 break;
8022 case 'R':
8023 view->count = 0;
8024 err = view_request_new(new_view, view, TOG_VIEW_REF);
8025 break;
8026 case 'g':
8027 case '=':
8028 case KEY_HOME:
8029 s->selected = 0;
8030 view->count = 0;
8031 if (s->tree == s->root)
8032 s->first_displayed_entry =
8033 got_object_tree_get_first_entry(s->tree);
8034 else
8035 s->first_displayed_entry = NULL;
8036 break;
8037 case 'G':
8038 case '*':
8039 case KEY_END: {
8040 int eos = view->nlines - 3;
8042 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8043 --eos; /* border */
8044 s->selected = 0;
8045 view->count = 0;
8046 te = got_object_tree_get_last_entry(s->tree);
8047 for (n = 0; n < eos; n++) {
8048 if (te == NULL) {
8049 if (s->tree != s->root) {
8050 s->first_displayed_entry = NULL;
8051 n++;
8053 break;
8055 s->first_displayed_entry = te;
8056 te = got_tree_entry_get_prev(s->tree, te);
8058 if (n > 0)
8059 s->selected = n - 1;
8060 break;
8062 case 'k':
8063 case KEY_UP:
8064 case CTRL('p'):
8065 if (s->selected > 0) {
8066 s->selected--;
8067 break;
8069 tree_scroll_up(s, 1);
8070 if (s->selected_entry == NULL ||
8071 (s->tree == s->root && s->selected_entry ==
8072 got_object_tree_get_first_entry(s->tree)))
8073 view->count = 0;
8074 break;
8075 case CTRL('u'):
8076 case 'u':
8077 nscroll /= 2;
8078 /* FALL THROUGH */
8079 case KEY_PPAGE:
8080 case CTRL('b'):
8081 case 'b':
8082 if (s->tree == s->root) {
8083 if (got_object_tree_get_first_entry(s->tree) ==
8084 s->first_displayed_entry)
8085 s->selected -= MIN(s->selected, nscroll);
8086 } else {
8087 if (s->first_displayed_entry == NULL)
8088 s->selected -= MIN(s->selected, nscroll);
8090 tree_scroll_up(s, MAX(0, nscroll));
8091 if (s->selected_entry == NULL ||
8092 (s->tree == s->root && s->selected_entry ==
8093 got_object_tree_get_first_entry(s->tree)))
8094 view->count = 0;
8095 break;
8096 case 'j':
8097 case KEY_DOWN:
8098 case CTRL('n'):
8099 if (s->selected < s->ndisplayed - 1) {
8100 s->selected++;
8101 break;
8103 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
8104 == NULL) {
8105 /* can't scroll any further */
8106 view->count = 0;
8107 break;
8109 tree_scroll_down(view, 1);
8110 break;
8111 case CTRL('d'):
8112 case 'd':
8113 nscroll /= 2;
8114 /* FALL THROUGH */
8115 case KEY_NPAGE:
8116 case CTRL('f'):
8117 case 'f':
8118 case ' ':
8119 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
8120 == NULL) {
8121 /* can't scroll any further; move cursor down */
8122 if (s->selected < s->ndisplayed - 1)
8123 s->selected += MIN(nscroll,
8124 s->ndisplayed - s->selected - 1);
8125 else
8126 view->count = 0;
8127 break;
8129 tree_scroll_down(view, nscroll);
8130 break;
8131 case KEY_ENTER:
8132 case '\r':
8133 case KEY_BACKSPACE:
8134 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
8135 struct tog_parent_tree *parent;
8136 /* user selected '..' */
8137 if (s->tree == s->root) {
8138 view->count = 0;
8139 break;
8141 parent = TAILQ_FIRST(&s->parents);
8142 TAILQ_REMOVE(&s->parents, parent,
8143 entry);
8144 got_object_tree_close(s->tree);
8145 s->tree = parent->tree;
8146 s->first_displayed_entry =
8147 parent->first_displayed_entry;
8148 s->selected_entry =
8149 parent->selected_entry;
8150 s->selected = parent->selected;
8151 if (s->selected > view->nlines - 3) {
8152 err = offset_selection_down(view);
8153 if (err)
8154 break;
8156 free(parent);
8157 } else if (S_ISDIR(got_tree_entry_get_mode(
8158 s->selected_entry))) {
8159 struct got_tree_object *subtree;
8160 view->count = 0;
8161 err = got_object_open_as_tree(&subtree, s->repo,
8162 got_tree_entry_get_id(s->selected_entry));
8163 if (err)
8164 break;
8165 err = tree_view_visit_subtree(s, subtree);
8166 if (err) {
8167 got_object_tree_close(subtree);
8168 break;
8170 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
8171 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
8172 break;
8173 case KEY_RESIZE:
8174 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
8175 s->selected = view->nlines - 4;
8176 view->count = 0;
8177 break;
8178 default:
8179 view->count = 0;
8180 break;
8183 return err;
8186 __dead static void
8187 usage_tree(void)
8189 endwin();
8190 fprintf(stderr,
8191 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
8192 getprogname());
8193 exit(1);
8196 static const struct got_error *
8197 cmd_tree(int argc, char *argv[])
8199 const struct got_error *error;
8200 struct got_repository *repo = NULL;
8201 struct got_worktree *worktree = NULL;
8202 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8203 struct got_object_id *commit_id = NULL;
8204 struct got_commit_object *commit = NULL;
8205 const char *commit_id_arg = NULL;
8206 char *keyword_idstr = NULL, *label = NULL;
8207 struct got_reference *ref = NULL;
8208 const char *head_ref_name = NULL;
8209 int ch;
8210 struct tog_view *view;
8211 int *pack_fds = NULL;
8213 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
8214 switch (ch) {
8215 case 'c':
8216 commit_id_arg = optarg;
8217 break;
8218 case 'r':
8219 repo_path = realpath(optarg, NULL);
8220 if (repo_path == NULL)
8221 return got_error_from_errno2("realpath",
8222 optarg);
8223 break;
8224 default:
8225 usage_tree();
8226 /* NOTREACHED */
8230 argc -= optind;
8231 argv += optind;
8233 if (argc > 1)
8234 usage_tree();
8236 error = got_repo_pack_fds_open(&pack_fds);
8237 if (error != NULL)
8238 goto done;
8240 if (repo_path == NULL) {
8241 cwd = getcwd(NULL, 0);
8242 if (cwd == NULL)
8243 return got_error_from_errno("getcwd");
8244 error = got_worktree_open(&worktree, cwd, NULL);
8245 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8246 goto done;
8247 if (worktree)
8248 repo_path =
8249 strdup(got_worktree_get_repo_path(worktree));
8250 else
8251 repo_path = strdup(cwd);
8252 if (repo_path == NULL) {
8253 error = got_error_from_errno("strdup");
8254 goto done;
8258 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8259 if (error != NULL)
8260 goto done;
8262 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8263 repo, worktree);
8264 if (error)
8265 goto done;
8267 init_curses();
8269 error = apply_unveil(got_repo_get_path(repo), NULL);
8270 if (error)
8271 goto done;
8273 error = tog_load_refs(repo, 0);
8274 if (error)
8275 goto done;
8277 if (commit_id_arg == NULL) {
8278 error = got_repo_match_object_id(&commit_id, &label,
8279 worktree ? got_worktree_get_head_ref_name(worktree) :
8280 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8281 if (error)
8282 goto done;
8283 head_ref_name = label;
8284 } else {
8285 error = got_keyword_to_idstr(&keyword_idstr, commit_id_arg,
8286 repo, worktree);
8287 if (error != NULL)
8288 goto done;
8289 if (keyword_idstr != NULL)
8290 commit_id_arg = keyword_idstr;
8292 error = got_ref_open(&ref, repo, commit_id_arg, 0);
8293 if (error == NULL)
8294 head_ref_name = got_ref_get_name(ref);
8295 else if (error->code != GOT_ERR_NOT_REF)
8296 goto done;
8297 error = got_repo_match_object_id(&commit_id, NULL,
8298 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8299 if (error)
8300 goto done;
8303 error = got_object_open_as_commit(&commit, repo, commit_id);
8304 if (error)
8305 goto done;
8307 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
8308 if (view == NULL) {
8309 error = got_error_from_errno("view_open");
8310 goto done;
8312 error = open_tree_view(view, commit_id, head_ref_name, repo);
8313 if (error)
8314 goto done;
8315 if (!got_path_is_root_dir(in_repo_path)) {
8316 error = tree_view_walk_path(&view->state.tree, commit,
8317 in_repo_path);
8318 if (error)
8319 goto done;
8322 if (worktree) {
8323 error = set_tog_base_commit(repo, worktree);
8324 if (error != NULL)
8325 goto done;
8327 /* Release work tree lock. */
8328 got_worktree_close(worktree);
8329 worktree = NULL;
8332 error = view_loop(view);
8334 done:
8335 free(tog_base_commit.id);
8336 free(keyword_idstr);
8337 free(repo_path);
8338 free(cwd);
8339 free(commit_id);
8340 free(label);
8341 if (ref)
8342 got_ref_close(ref);
8343 if (worktree != NULL)
8344 got_worktree_close(worktree);
8345 if (repo) {
8346 const struct got_error *close_err = got_repo_close(repo);
8347 if (error == NULL)
8348 error = close_err;
8350 if (pack_fds) {
8351 const struct got_error *pack_err =
8352 got_repo_pack_fds_close(pack_fds);
8353 if (error == NULL)
8354 error = pack_err;
8356 tog_free_refs();
8357 return error;
8360 static const struct got_error *
8361 ref_view_load_refs(struct tog_ref_view_state *s)
8363 struct got_reflist_entry *sre;
8364 struct tog_reflist_entry *re;
8366 s->nrefs = 0;
8367 TAILQ_FOREACH(sre, &tog_refs, entry) {
8368 if (strncmp(got_ref_get_name(sre->ref),
8369 "refs/got/", 9) == 0 &&
8370 strncmp(got_ref_get_name(sre->ref),
8371 "refs/got/backup/", 16) != 0)
8372 continue;
8374 re = malloc(sizeof(*re));
8375 if (re == NULL)
8376 return got_error_from_errno("malloc");
8378 re->ref = got_ref_dup(sre->ref);
8379 if (re->ref == NULL)
8380 return got_error_from_errno("got_ref_dup");
8381 re->idx = s->nrefs++;
8382 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8385 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8386 return NULL;
8389 static void
8390 ref_view_free_refs(struct tog_ref_view_state *s)
8392 struct tog_reflist_entry *re;
8394 while (!TAILQ_EMPTY(&s->refs)) {
8395 re = TAILQ_FIRST(&s->refs);
8396 TAILQ_REMOVE(&s->refs, re, entry);
8397 got_ref_close(re->ref);
8398 free(re);
8402 static const struct got_error *
8403 open_ref_view(struct tog_view *view, struct got_repository *repo)
8405 const struct got_error *err = NULL;
8406 struct tog_ref_view_state *s = &view->state.ref;
8408 s->selected_entry = 0;
8409 s->repo = repo;
8411 TAILQ_INIT(&s->refs);
8412 STAILQ_INIT(&s->colors);
8414 err = ref_view_load_refs(s);
8415 if (err)
8416 goto done;
8418 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8419 err = add_color(&s->colors, "^refs/heads/",
8420 TOG_COLOR_REFS_HEADS,
8421 get_color_value("TOG_COLOR_REFS_HEADS"));
8422 if (err)
8423 goto done;
8425 err = add_color(&s->colors, "^refs/tags/",
8426 TOG_COLOR_REFS_TAGS,
8427 get_color_value("TOG_COLOR_REFS_TAGS"));
8428 if (err)
8429 goto done;
8431 err = add_color(&s->colors, "^refs/remotes/",
8432 TOG_COLOR_REFS_REMOTES,
8433 get_color_value("TOG_COLOR_REFS_REMOTES"));
8434 if (err)
8435 goto done;
8437 err = add_color(&s->colors, "^refs/got/backup/",
8438 TOG_COLOR_REFS_BACKUP,
8439 get_color_value("TOG_COLOR_REFS_BACKUP"));
8440 if (err)
8441 goto done;
8444 view->show = show_ref_view;
8445 view->input = input_ref_view;
8446 view->close = close_ref_view;
8447 view->search_start = search_start_ref_view;
8448 view->search_next = search_next_ref_view;
8449 done:
8450 if (err) {
8451 if (view->close == NULL)
8452 close_ref_view(view);
8453 view_close(view);
8455 return err;
8458 static const struct got_error *
8459 close_ref_view(struct tog_view *view)
8461 struct tog_ref_view_state *s = &view->state.ref;
8463 ref_view_free_refs(s);
8464 free_colors(&s->colors);
8466 return NULL;
8469 static const struct got_error *
8470 resolve_reflist_entry(struct got_object_id **commit_id,
8471 struct tog_reflist_entry *re, struct got_repository *repo)
8473 const struct got_error *err = NULL;
8474 struct got_object_id *obj_id;
8475 struct got_tag_object *tag = NULL;
8476 int obj_type;
8478 *commit_id = NULL;
8480 err = got_ref_resolve(&obj_id, repo, re->ref);
8481 if (err)
8482 return err;
8484 err = got_object_get_type(&obj_type, repo, obj_id);
8485 if (err)
8486 goto done;
8488 switch (obj_type) {
8489 case GOT_OBJ_TYPE_COMMIT:
8490 *commit_id = obj_id;
8491 break;
8492 case GOT_OBJ_TYPE_TAG:
8493 err = got_object_open_as_tag(&tag, repo, obj_id);
8494 if (err)
8495 goto done;
8496 free(obj_id);
8497 err = got_object_get_type(&obj_type, repo,
8498 got_object_tag_get_object_id(tag));
8499 if (err)
8500 goto done;
8501 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8502 err = got_error(GOT_ERR_OBJ_TYPE);
8503 goto done;
8505 *commit_id = got_object_id_dup(
8506 got_object_tag_get_object_id(tag));
8507 if (*commit_id == NULL) {
8508 err = got_error_from_errno("got_object_id_dup");
8509 goto done;
8511 break;
8512 default:
8513 err = got_error(GOT_ERR_OBJ_TYPE);
8514 break;
8517 done:
8518 if (tag)
8519 got_object_tag_close(tag);
8520 if (err) {
8521 free(*commit_id);
8522 *commit_id = NULL;
8524 return err;
8527 static const struct got_error *
8528 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8529 struct tog_reflist_entry *re, struct got_repository *repo)
8531 struct tog_view *log_view;
8532 const struct got_error *err = NULL;
8533 struct got_object_id *commit_id = NULL;
8535 *new_view = NULL;
8537 err = resolve_reflist_entry(&commit_id, re, repo);
8538 if (err) {
8539 if (err->code != GOT_ERR_OBJ_TYPE)
8540 return err;
8541 else
8542 return NULL;
8545 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8546 if (log_view == NULL) {
8547 err = got_error_from_errno("view_open");
8548 goto done;
8551 err = open_log_view(log_view, commit_id, repo,
8552 got_ref_get_name(re->ref), "", 0, NULL);
8553 done:
8554 if (err)
8555 view_close(log_view);
8556 else
8557 *new_view = log_view;
8558 free(commit_id);
8559 return err;
8562 static void
8563 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8565 struct tog_reflist_entry *re;
8566 int i = 0;
8568 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8569 return;
8571 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8572 while (i++ < maxscroll) {
8573 if (re == NULL)
8574 break;
8575 s->first_displayed_entry = re;
8576 re = TAILQ_PREV(re, tog_reflist_head, entry);
8580 static const struct got_error *
8581 ref_scroll_down(struct tog_view *view, int maxscroll)
8583 struct tog_ref_view_state *s = &view->state.ref;
8584 struct tog_reflist_entry *next, *last;
8585 int n = 0;
8587 if (s->first_displayed_entry)
8588 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8589 else
8590 next = TAILQ_FIRST(&s->refs);
8592 last = s->last_displayed_entry;
8593 while (next && n++ < maxscroll) {
8594 if (last) {
8595 s->last_displayed_entry = last;
8596 last = TAILQ_NEXT(last, entry);
8598 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8599 s->first_displayed_entry = next;
8600 next = TAILQ_NEXT(next, entry);
8604 return NULL;
8607 static const struct got_error *
8608 search_start_ref_view(struct tog_view *view)
8610 struct tog_ref_view_state *s = &view->state.ref;
8612 s->matched_entry = NULL;
8613 return NULL;
8616 static int
8617 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8619 regmatch_t regmatch;
8621 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8622 0) == 0;
8625 static const struct got_error *
8626 search_next_ref_view(struct tog_view *view)
8628 struct tog_ref_view_state *s = &view->state.ref;
8629 struct tog_reflist_entry *re = NULL;
8631 if (!view->searching) {
8632 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8633 return NULL;
8636 if (s->matched_entry) {
8637 if (view->searching == TOG_SEARCH_FORWARD) {
8638 if (s->selected_entry)
8639 re = TAILQ_NEXT(s->selected_entry, entry);
8640 else
8641 re = TAILQ_PREV(s->selected_entry,
8642 tog_reflist_head, entry);
8643 } else {
8644 if (s->selected_entry == NULL)
8645 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8646 else
8647 re = TAILQ_PREV(s->selected_entry,
8648 tog_reflist_head, entry);
8650 } else {
8651 if (s->selected_entry)
8652 re = s->selected_entry;
8653 else if (view->searching == TOG_SEARCH_FORWARD)
8654 re = TAILQ_FIRST(&s->refs);
8655 else
8656 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8659 while (1) {
8660 if (re == NULL) {
8661 if (s->matched_entry == NULL) {
8662 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8663 return NULL;
8665 if (view->searching == TOG_SEARCH_FORWARD)
8666 re = TAILQ_FIRST(&s->refs);
8667 else
8668 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8671 if (match_reflist_entry(re, &view->regex)) {
8672 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8673 s->matched_entry = re;
8674 break;
8677 if (view->searching == TOG_SEARCH_FORWARD)
8678 re = TAILQ_NEXT(re, entry);
8679 else
8680 re = TAILQ_PREV(re, tog_reflist_head, entry);
8683 if (s->matched_entry) {
8684 s->first_displayed_entry = s->matched_entry;
8685 s->selected = 0;
8688 return NULL;
8691 static const struct got_error *
8692 show_ref_view(struct tog_view *view)
8694 const struct got_error *err = NULL;
8695 struct tog_ref_view_state *s = &view->state.ref;
8696 struct tog_reflist_entry *re;
8697 char *line = NULL;
8698 wchar_t *wline;
8699 struct tog_color *tc;
8700 int width, n, scrollx;
8701 int limit = view->nlines;
8703 werase(view->window);
8705 s->ndisplayed = 0;
8706 if (view_is_hsplit_top(view))
8707 --limit; /* border */
8709 if (limit == 0)
8710 return NULL;
8712 re = s->first_displayed_entry;
8714 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8715 s->nrefs) == -1)
8716 return got_error_from_errno("asprintf");
8718 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8719 if (err) {
8720 free(line);
8721 return err;
8723 if (view_needs_focus_indication(view))
8724 wstandout(view->window);
8725 waddwstr(view->window, wline);
8726 while (width++ < view->ncols)
8727 waddch(view->window, ' ');
8728 if (view_needs_focus_indication(view))
8729 wstandend(view->window);
8730 free(wline);
8731 wline = NULL;
8732 free(line);
8733 line = NULL;
8734 if (--limit <= 0)
8735 return NULL;
8737 n = 0;
8738 view->maxx = 0;
8739 while (re && limit > 0) {
8740 char *line = NULL;
8741 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8743 if (s->show_date) {
8744 struct got_commit_object *ci;
8745 struct got_tag_object *tag;
8746 struct got_object_id *id;
8747 struct tm tm;
8748 time_t t;
8750 err = got_ref_resolve(&id, s->repo, re->ref);
8751 if (err)
8752 return err;
8753 err = got_object_open_as_tag(&tag, s->repo, id);
8754 if (err) {
8755 if (err->code != GOT_ERR_OBJ_TYPE) {
8756 free(id);
8757 return err;
8759 err = got_object_open_as_commit(&ci, s->repo,
8760 id);
8761 if (err) {
8762 free(id);
8763 return err;
8765 t = got_object_commit_get_committer_time(ci);
8766 got_object_commit_close(ci);
8767 } else {
8768 t = got_object_tag_get_tagger_time(tag);
8769 got_object_tag_close(tag);
8771 free(id);
8772 if (gmtime_r(&t, &tm) == NULL)
8773 return got_error_from_errno("gmtime_r");
8774 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8775 return got_error(GOT_ERR_NO_SPACE);
8777 if (got_ref_is_symbolic(re->ref)) {
8778 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8779 ymd : "", got_ref_get_name(re->ref),
8780 got_ref_get_symref_target(re->ref)) == -1)
8781 return got_error_from_errno("asprintf");
8782 } else if (s->show_ids) {
8783 struct got_object_id *id;
8784 char *id_str;
8785 err = got_ref_resolve(&id, s->repo, re->ref);
8786 if (err)
8787 return err;
8788 err = got_object_id_str(&id_str, id);
8789 if (err) {
8790 free(id);
8791 return err;
8793 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8794 got_ref_get_name(re->ref), id_str) == -1) {
8795 err = got_error_from_errno("asprintf");
8796 free(id);
8797 free(id_str);
8798 return err;
8800 free(id);
8801 free(id_str);
8802 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8803 got_ref_get_name(re->ref)) == -1)
8804 return got_error_from_errno("asprintf");
8806 /* use full line width to determine view->maxx */
8807 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8808 if (err) {
8809 free(line);
8810 return err;
8812 view->maxx = MAX(view->maxx, width);
8813 free(wline);
8814 wline = NULL;
8816 err = format_line(&wline, &width, &scrollx, line, view->x,
8817 view->ncols, 0, 0);
8818 if (err) {
8819 free(line);
8820 return err;
8822 if (n == s->selected) {
8823 if (view->focussed)
8824 wstandout(view->window);
8825 s->selected_entry = re;
8827 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8828 if (tc)
8829 wattr_on(view->window,
8830 COLOR_PAIR(tc->colorpair), NULL);
8831 waddwstr(view->window, &wline[scrollx]);
8832 if (tc)
8833 wattr_off(view->window,
8834 COLOR_PAIR(tc->colorpair), NULL);
8835 if (width < view->ncols)
8836 waddch(view->window, '\n');
8837 if (n == s->selected && view->focussed)
8838 wstandend(view->window);
8839 free(line);
8840 free(wline);
8841 wline = NULL;
8842 n++;
8843 s->ndisplayed++;
8844 s->last_displayed_entry = re;
8846 limit--;
8847 re = TAILQ_NEXT(re, entry);
8850 view_border(view);
8851 return err;
8854 static const struct got_error *
8855 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8856 struct tog_reflist_entry *re, struct got_repository *repo)
8858 const struct got_error *err = NULL;
8859 struct got_object_id *commit_id = NULL;
8860 struct tog_view *tree_view;
8862 *new_view = NULL;
8864 err = resolve_reflist_entry(&commit_id, re, repo);
8865 if (err) {
8866 if (err->code != GOT_ERR_OBJ_TYPE)
8867 return err;
8868 else
8869 return NULL;
8873 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8874 if (tree_view == NULL) {
8875 err = got_error_from_errno("view_open");
8876 goto done;
8879 err = open_tree_view(tree_view, commit_id,
8880 got_ref_get_name(re->ref), repo);
8881 if (err)
8882 goto done;
8884 *new_view = tree_view;
8885 done:
8886 free(commit_id);
8887 return err;
8890 static const struct got_error *
8891 ref_goto_line(struct tog_view *view, int nlines)
8893 const struct got_error *err = NULL;
8894 struct tog_ref_view_state *s = &view->state.ref;
8895 int g, idx = s->selected_entry->idx;
8897 g = view->gline;
8898 view->gline = 0;
8900 if (g == 0)
8901 g = 1;
8902 else if (g > s->nrefs)
8903 g = s->nrefs;
8905 if (g >= s->first_displayed_entry->idx + 1 &&
8906 g <= s->last_displayed_entry->idx + 1 &&
8907 g - s->first_displayed_entry->idx - 1 < nlines) {
8908 s->selected = g - s->first_displayed_entry->idx - 1;
8909 return NULL;
8912 if (idx + 1 < g) {
8913 err = ref_scroll_down(view, g - idx - 1);
8914 if (err)
8915 return err;
8916 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8917 s->first_displayed_entry->idx + s->selected < g &&
8918 s->selected < s->ndisplayed - 1)
8919 s->selected = g - s->first_displayed_entry->idx - 1;
8920 } else if (idx + 1 > g)
8921 ref_scroll_up(s, idx - g + 1);
8923 if (g < nlines && s->first_displayed_entry->idx == 0)
8924 s->selected = g - 1;
8926 return NULL;
8930 static const struct got_error *
8931 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8933 const struct got_error *err = NULL;
8934 struct tog_ref_view_state *s = &view->state.ref;
8935 struct tog_reflist_entry *re;
8936 int n, nscroll = view->nlines - 1;
8938 if (view->gline)
8939 return ref_goto_line(view, nscroll);
8941 switch (ch) {
8942 case '0':
8943 case '$':
8944 case KEY_RIGHT:
8945 case 'l':
8946 case KEY_LEFT:
8947 case 'h':
8948 horizontal_scroll_input(view, ch);
8949 break;
8950 case 'i':
8951 s->show_ids = !s->show_ids;
8952 view->count = 0;
8953 break;
8954 case 'm':
8955 s->show_date = !s->show_date;
8956 view->count = 0;
8957 break;
8958 case 'o':
8959 s->sort_by_date = !s->sort_by_date;
8960 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8961 view->count = 0;
8962 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8963 got_ref_cmp_by_commit_timestamp_descending :
8964 tog_ref_cmp_by_name, s->repo);
8965 if (err)
8966 break;
8967 got_reflist_object_id_map_free(tog_refs_idmap);
8968 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8969 &tog_refs, s->repo);
8970 if (err)
8971 break;
8972 ref_view_free_refs(s);
8973 err = ref_view_load_refs(s);
8974 break;
8975 case KEY_ENTER:
8976 case '\r':
8977 view->count = 0;
8978 if (!s->selected_entry)
8979 break;
8980 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8981 break;
8982 case 'T':
8983 view->count = 0;
8984 if (!s->selected_entry)
8985 break;
8986 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8987 break;
8988 case 'g':
8989 case '=':
8990 case KEY_HOME:
8991 s->selected = 0;
8992 view->count = 0;
8993 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8994 break;
8995 case 'G':
8996 case '*':
8997 case KEY_END: {
8998 int eos = view->nlines - 1;
9000 if (view->mode == TOG_VIEW_SPLIT_HRZN)
9001 --eos; /* border */
9002 s->selected = 0;
9003 view->count = 0;
9004 re = TAILQ_LAST(&s->refs, tog_reflist_head);
9005 for (n = 0; n < eos; n++) {
9006 if (re == NULL)
9007 break;
9008 s->first_displayed_entry = re;
9009 re = TAILQ_PREV(re, tog_reflist_head, entry);
9011 if (n > 0)
9012 s->selected = n - 1;
9013 break;
9015 case 'k':
9016 case KEY_UP:
9017 case CTRL('p'):
9018 if (s->selected > 0) {
9019 s->selected--;
9020 break;
9022 ref_scroll_up(s, 1);
9023 if (s->selected_entry == TAILQ_FIRST(&s->refs))
9024 view->count = 0;
9025 break;
9026 case CTRL('u'):
9027 case 'u':
9028 nscroll /= 2;
9029 /* FALL THROUGH */
9030 case KEY_PPAGE:
9031 case CTRL('b'):
9032 case 'b':
9033 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
9034 s->selected -= MIN(nscroll, s->selected);
9035 ref_scroll_up(s, MAX(0, nscroll));
9036 if (s->selected_entry == TAILQ_FIRST(&s->refs))
9037 view->count = 0;
9038 break;
9039 case 'j':
9040 case KEY_DOWN:
9041 case CTRL('n'):
9042 if (s->selected < s->ndisplayed - 1) {
9043 s->selected++;
9044 break;
9046 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
9047 /* can't scroll any further */
9048 view->count = 0;
9049 break;
9051 ref_scroll_down(view, 1);
9052 break;
9053 case CTRL('d'):
9054 case 'd':
9055 nscroll /= 2;
9056 /* FALL THROUGH */
9057 case KEY_NPAGE:
9058 case CTRL('f'):
9059 case 'f':
9060 case ' ':
9061 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
9062 /* can't scroll any further; move cursor down */
9063 if (s->selected < s->ndisplayed - 1)
9064 s->selected += MIN(nscroll,
9065 s->ndisplayed - s->selected - 1);
9066 if (view->count > 1 && s->selected < s->ndisplayed - 1)
9067 s->selected += s->ndisplayed - s->selected - 1;
9068 view->count = 0;
9069 break;
9071 ref_scroll_down(view, nscroll);
9072 break;
9073 case CTRL('l'):
9074 view->count = 0;
9075 tog_free_refs();
9076 err = tog_load_refs(s->repo, s->sort_by_date);
9077 if (err)
9078 break;
9079 ref_view_free_refs(s);
9080 err = ref_view_load_refs(s);
9081 break;
9082 case KEY_RESIZE:
9083 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
9084 s->selected = view->nlines - 2;
9085 break;
9086 default:
9087 view->count = 0;
9088 break;
9091 return err;
9094 __dead static void
9095 usage_ref(void)
9097 endwin();
9098 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
9099 getprogname());
9100 exit(1);
9103 static const struct got_error *
9104 cmd_ref(int argc, char *argv[])
9106 const struct got_error *error;
9107 struct got_repository *repo = NULL;
9108 struct got_worktree *worktree = NULL;
9109 char *cwd = NULL, *repo_path = NULL;
9110 int ch;
9111 struct tog_view *view;
9112 int *pack_fds = NULL;
9114 while ((ch = getopt(argc, argv, "r:")) != -1) {
9115 switch (ch) {
9116 case 'r':
9117 repo_path = realpath(optarg, NULL);
9118 if (repo_path == NULL)
9119 return got_error_from_errno2("realpath",
9120 optarg);
9121 break;
9122 default:
9123 usage_ref();
9124 /* NOTREACHED */
9128 argc -= optind;
9129 argv += optind;
9131 if (argc > 1)
9132 usage_ref();
9134 error = got_repo_pack_fds_open(&pack_fds);
9135 if (error != NULL)
9136 goto done;
9138 if (repo_path == NULL) {
9139 cwd = getcwd(NULL, 0);
9140 if (cwd == NULL)
9141 return got_error_from_errno("getcwd");
9142 error = got_worktree_open(&worktree, cwd, NULL);
9143 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9144 goto done;
9145 if (worktree)
9146 repo_path =
9147 strdup(got_worktree_get_repo_path(worktree));
9148 else
9149 repo_path = strdup(cwd);
9150 if (repo_path == NULL) {
9151 error = got_error_from_errno("strdup");
9152 goto done;
9156 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9157 if (error != NULL)
9158 goto done;
9160 init_curses();
9162 error = apply_unveil(got_repo_get_path(repo), NULL);
9163 if (error)
9164 goto done;
9166 error = tog_load_refs(repo, 0);
9167 if (error)
9168 goto done;
9170 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
9171 if (view == NULL) {
9172 error = got_error_from_errno("view_open");
9173 goto done;
9176 error = open_ref_view(view, repo);
9177 if (error)
9178 goto done;
9180 if (worktree) {
9181 error = set_tog_base_commit(repo, worktree);
9182 if (error != NULL)
9183 goto done;
9185 /* Release work tree lock. */
9186 got_worktree_close(worktree);
9187 worktree = NULL;
9190 error = view_loop(view);
9192 done:
9193 free(tog_base_commit.id);
9194 free(repo_path);
9195 free(cwd);
9196 if (worktree != NULL)
9197 got_worktree_close(worktree);
9198 if (repo) {
9199 const struct got_error *close_err = got_repo_close(repo);
9200 if (close_err)
9201 error = close_err;
9203 if (pack_fds) {
9204 const struct got_error *pack_err =
9205 got_repo_pack_fds_close(pack_fds);
9206 if (error == NULL)
9207 error = pack_err;
9209 tog_free_refs();
9210 return error;
9213 static const struct got_error*
9214 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
9215 const char *str)
9217 size_t len;
9219 if (win == NULL)
9220 win = stdscr;
9222 len = strlen(str);
9223 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
9225 if (focus)
9226 wstandout(win);
9227 if (mvwprintw(win, y, x, "%s", str) == ERR)
9228 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
9229 if (focus)
9230 wstandend(win);
9232 return NULL;
9235 static const struct got_error *
9236 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
9238 off_t *p;
9240 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
9241 if (p == NULL) {
9242 free(*line_offsets);
9243 *line_offsets = NULL;
9244 return got_error_from_errno("reallocarray");
9247 *line_offsets = p;
9248 (*line_offsets)[*nlines] = off;
9249 ++(*nlines);
9250 return NULL;
9253 static const struct got_error *
9254 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
9256 *ret = 0;
9258 for (;n > 0; --n, ++km) {
9259 char *t0, *t, *k;
9260 size_t len = 1;
9262 if (km->keys == NULL)
9263 continue;
9265 t = t0 = strdup(km->keys);
9266 if (t0 == NULL)
9267 return got_error_from_errno("strdup");
9269 len += strlen(t);
9270 while ((k = strsep(&t, " ")) != NULL)
9271 len += strlen(k) > 1 ? 2 : 0;
9272 free(t0);
9273 *ret = MAX(*ret, len);
9276 return NULL;
9280 * Write keymap section headers, keys, and key info in km to f.
9281 * Save line offset to *off. If terminal has UTF8 encoding enabled,
9282 * wrap control and symbolic keys in guillemets, else use <>.
9284 static const struct got_error *
9285 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
9287 int n, len = width;
9289 if (km->keys) {
9290 static const char *u8_glyph[] = {
9291 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
9292 "\xe2\x80\xba" /* U+203A (utf8 >) */
9294 char *t0, *t, *k;
9295 int cs, s, first = 1;
9297 cs = got_locale_is_utf8();
9299 t = t0 = strdup(km->keys);
9300 if (t0 == NULL)
9301 return got_error_from_errno("strdup");
9303 len = strlen(km->keys);
9304 while ((k = strsep(&t, " ")) != NULL) {
9305 s = strlen(k) > 1; /* control or symbolic key */
9306 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
9307 cs && s ? u8_glyph[0] : s ? "<" : "", k,
9308 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
9309 if (n < 0) {
9310 free(t0);
9311 return got_error_from_errno("fprintf");
9313 first = 0;
9314 len += s ? 2 : 0;
9315 *off += n;
9317 free(t0);
9319 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
9320 if (n < 0)
9321 return got_error_from_errno("fprintf");
9322 *off += n;
9324 return NULL;
9327 static const struct got_error *
9328 format_help(struct tog_help_view_state *s)
9330 const struct got_error *err = NULL;
9331 off_t off = 0;
9332 int i, max, n, show = s->all;
9333 static const struct tog_key_map km[] = {
9334 #define KEYMAP_(info, type) { NULL, (info), type }
9335 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
9336 GENERATE_HELP
9337 #undef KEYMAP_
9338 #undef KEY_
9341 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
9342 if (err)
9343 return err;
9345 n = nitems(km);
9346 err = max_key_str(&max, km, n);
9347 if (err)
9348 return err;
9350 for (i = 0; i < n; ++i) {
9351 if (km[i].keys == NULL) {
9352 show = s->all;
9353 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9354 km[i].type == s->type || s->all)
9355 show = 1;
9357 if (show) {
9358 err = format_help_line(&off, s->f, &km[i], max);
9359 if (err)
9360 return err;
9361 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9362 if (err)
9363 return err;
9366 fputc('\n', s->f);
9367 ++off;
9368 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9369 return err;
9372 static const struct got_error *
9373 create_help(struct tog_help_view_state *s)
9375 FILE *f;
9376 const struct got_error *err;
9378 free(s->line_offsets);
9379 s->line_offsets = NULL;
9380 s->nlines = 0;
9382 f = got_opentemp();
9383 if (f == NULL)
9384 return got_error_from_errno("got_opentemp");
9385 s->f = f;
9387 err = format_help(s);
9388 if (err)
9389 return err;
9391 if (s->f && fflush(s->f) != 0)
9392 return got_error_from_errno("fflush");
9394 return NULL;
9397 static const struct got_error *
9398 search_start_help_view(struct tog_view *view)
9400 view->state.help.matched_line = 0;
9401 return NULL;
9404 static void
9405 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9406 size_t *nlines, int **first, int **last, int **match, int **selected)
9408 struct tog_help_view_state *s = &view->state.help;
9410 *f = s->f;
9411 *nlines = s->nlines;
9412 *line_offsets = s->line_offsets;
9413 *match = &s->matched_line;
9414 *first = &s->first_displayed_line;
9415 *last = &s->last_displayed_line;
9416 *selected = &s->selected_line;
9419 static const struct got_error *
9420 show_help_view(struct tog_view *view)
9422 struct tog_help_view_state *s = &view->state.help;
9423 const struct got_error *err;
9424 regmatch_t *regmatch = &view->regmatch;
9425 wchar_t *wline;
9426 char *line;
9427 ssize_t linelen;
9428 size_t linesz = 0;
9429 int width, nprinted = 0, rc = 0;
9430 int eos = view->nlines;
9432 if (view_is_hsplit_top(view))
9433 --eos; /* account for border */
9435 s->lineno = 0;
9436 rewind(s->f);
9437 werase(view->window);
9439 if (view->gline > s->nlines - 1)
9440 view->gline = s->nlines - 1;
9442 err = win_draw_center(view->window, 0, 0, view->ncols,
9443 view_needs_focus_indication(view),
9444 "tog help (press q to return to tog)");
9445 if (err)
9446 return err;
9447 if (eos <= 1)
9448 return NULL;
9449 waddstr(view->window, "\n\n");
9450 eos -= 2;
9452 s->eof = 0;
9453 view->maxx = 0;
9454 line = NULL;
9455 while (eos > 0 && nprinted < eos) {
9456 attr_t attr = 0;
9458 linelen = getline(&line, &linesz, s->f);
9459 if (linelen == -1) {
9460 if (!feof(s->f)) {
9461 free(line);
9462 return got_ferror(s->f, GOT_ERR_IO);
9464 s->eof = 1;
9465 break;
9467 if (++s->lineno < s->first_displayed_line)
9468 continue;
9469 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9470 continue;
9471 if (s->lineno == view->hiline)
9472 attr = A_STANDOUT;
9474 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9475 view->x ? 1 : 0);
9476 if (err) {
9477 free(line);
9478 return err;
9480 view->maxx = MAX(view->maxx, width);
9481 free(wline);
9482 wline = NULL;
9484 if (attr)
9485 wattron(view->window, attr);
9486 if (s->first_displayed_line + nprinted == s->matched_line &&
9487 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9488 err = add_matched_line(&width, line, view->ncols - 1, 0,
9489 view->window, view->x, regmatch);
9490 if (err) {
9491 free(line);
9492 return err;
9494 } else {
9495 int skip;
9497 err = format_line(&wline, &width, &skip, line,
9498 view->x, view->ncols, 0, view->x ? 1 : 0);
9499 if (err) {
9500 free(line);
9501 return err;
9503 waddwstr(view->window, &wline[skip]);
9504 free(wline);
9505 wline = NULL;
9507 if (s->lineno == view->hiline) {
9508 while (width++ < view->ncols)
9509 waddch(view->window, ' ');
9510 } else {
9511 if (width < view->ncols)
9512 waddch(view->window, '\n');
9514 if (attr)
9515 wattroff(view->window, attr);
9516 if (++nprinted == 1)
9517 s->first_displayed_line = s->lineno;
9519 free(line);
9520 if (nprinted > 0)
9521 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9522 else
9523 s->last_displayed_line = s->first_displayed_line;
9525 view_border(view);
9527 if (s->eof) {
9528 rc = waddnstr(view->window,
9529 "See the tog(1) manual page for full documentation",
9530 view->ncols - 1);
9531 if (rc == ERR)
9532 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9533 } else {
9534 wmove(view->window, view->nlines - 1, 0);
9535 wclrtoeol(view->window);
9536 wstandout(view->window);
9537 rc = waddnstr(view->window, "scroll down for more...",
9538 view->ncols - 1);
9539 if (rc == ERR)
9540 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9541 if (getcurx(view->window) < view->ncols - 6) {
9542 rc = wprintw(view->window, "[%.0f%%]",
9543 100.00 * s->last_displayed_line / s->nlines);
9544 if (rc == ERR)
9545 return got_error_msg(GOT_ERR_IO, "wprintw");
9547 wstandend(view->window);
9550 return NULL;
9553 static const struct got_error *
9554 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9556 struct tog_help_view_state *s = &view->state.help;
9557 const struct got_error *err = NULL;
9558 char *line = NULL;
9559 ssize_t linelen;
9560 size_t linesz = 0;
9561 int eos, nscroll;
9563 eos = nscroll = view->nlines;
9564 if (view_is_hsplit_top(view))
9565 --eos; /* border */
9567 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9569 switch (ch) {
9570 case '0':
9571 case '$':
9572 case KEY_RIGHT:
9573 case 'l':
9574 case KEY_LEFT:
9575 case 'h':
9576 horizontal_scroll_input(view, ch);
9577 break;
9578 case 'g':
9579 case KEY_HOME:
9580 s->first_displayed_line = 1;
9581 view->count = 0;
9582 break;
9583 case 'G':
9584 case KEY_END:
9585 view->count = 0;
9586 if (s->eof)
9587 break;
9588 s->first_displayed_line = (s->nlines - eos) + 3;
9589 s->eof = 1;
9590 break;
9591 case 'k':
9592 case KEY_UP:
9593 if (s->first_displayed_line > 1)
9594 --s->first_displayed_line;
9595 else
9596 view->count = 0;
9597 break;
9598 case CTRL('u'):
9599 case 'u':
9600 nscroll /= 2;
9601 /* FALL THROUGH */
9602 case KEY_PPAGE:
9603 case CTRL('b'):
9604 case 'b':
9605 if (s->first_displayed_line == 1) {
9606 view->count = 0;
9607 break;
9609 while (--nscroll > 0 && s->first_displayed_line > 1)
9610 s->first_displayed_line--;
9611 break;
9612 case 'j':
9613 case KEY_DOWN:
9614 case CTRL('n'):
9615 if (!s->eof)
9616 ++s->first_displayed_line;
9617 else
9618 view->count = 0;
9619 break;
9620 case CTRL('d'):
9621 case 'd':
9622 nscroll /= 2;
9623 /* FALL THROUGH */
9624 case KEY_NPAGE:
9625 case CTRL('f'):
9626 case 'f':
9627 case ' ':
9628 if (s->eof) {
9629 view->count = 0;
9630 break;
9632 while (!s->eof && --nscroll > 0) {
9633 linelen = getline(&line, &linesz, s->f);
9634 s->first_displayed_line++;
9635 if (linelen == -1) {
9636 if (feof(s->f))
9637 s->eof = 1;
9638 else
9639 err = got_ferror(s->f, GOT_ERR_IO);
9640 break;
9643 free(line);
9644 break;
9645 default:
9646 view->count = 0;
9647 break;
9650 return err;
9653 static const struct got_error *
9654 close_help_view(struct tog_view *view)
9656 struct tog_help_view_state *s = &view->state.help;
9658 free(s->line_offsets);
9659 s->line_offsets = NULL;
9660 if (fclose(s->f) == EOF)
9661 return got_error_from_errno("fclose");
9663 return NULL;
9666 static const struct got_error *
9667 reset_help_view(struct tog_view *view)
9669 struct tog_help_view_state *s = &view->state.help;
9672 if (s->f && fclose(s->f) == EOF)
9673 return got_error_from_errno("fclose");
9675 wclear(view->window);
9676 view->count = 0;
9677 view->x = 0;
9678 s->all = !s->all;
9679 s->first_displayed_line = 1;
9680 s->last_displayed_line = view->nlines;
9681 s->matched_line = 0;
9683 return create_help(s);
9686 static const struct got_error *
9687 open_help_view(struct tog_view *view, struct tog_view *parent)
9689 const struct got_error *err = NULL;
9690 struct tog_help_view_state *s = &view->state.help;
9692 s->type = (enum tog_keymap_type)parent->type;
9693 s->first_displayed_line = 1;
9694 s->last_displayed_line = view->nlines;
9695 s->selected_line = 1;
9697 view->show = show_help_view;
9698 view->input = input_help_view;
9699 view->reset = reset_help_view;
9700 view->close = close_help_view;
9701 view->search_start = search_start_help_view;
9702 view->search_setup = search_setup_help_view;
9703 view->search_next = search_next_view_match;
9705 err = create_help(s);
9706 return err;
9709 static const struct got_error *
9710 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9711 enum tog_view_type request, int y, int x)
9713 const struct got_error *err = NULL;
9715 *new_view = NULL;
9717 switch (request) {
9718 case TOG_VIEW_DIFF:
9719 if (view->type == TOG_VIEW_LOG) {
9720 struct tog_log_view_state *s = &view->state.log;
9722 err = open_diff_view_for_commit(new_view, y, x,
9723 s->selected_entry->commit, s->selected_entry->id,
9724 view, s->repo);
9725 } else
9726 return got_error_msg(GOT_ERR_NOT_IMPL,
9727 "parent/child view pair not supported");
9728 break;
9729 case TOG_VIEW_BLAME:
9730 if (view->type == TOG_VIEW_TREE) {
9731 struct tog_tree_view_state *s = &view->state.tree;
9733 err = blame_tree_entry(new_view, y, x,
9734 s->selected_entry, &s->parents, s->commit_id,
9735 s->repo);
9736 } else
9737 return got_error_msg(GOT_ERR_NOT_IMPL,
9738 "parent/child view pair not supported");
9739 break;
9740 case TOG_VIEW_LOG:
9741 if (view->type == TOG_VIEW_BLAME)
9742 err = log_annotated_line(new_view, y, x,
9743 view->state.blame.repo, view->state.blame.id_to_log);
9744 else if (view->type == TOG_VIEW_TREE)
9745 err = log_selected_tree_entry(new_view, y, x,
9746 &view->state.tree);
9747 else if (view->type == TOG_VIEW_REF)
9748 err = log_ref_entry(new_view, y, x,
9749 view->state.ref.selected_entry,
9750 view->state.ref.repo);
9751 else
9752 return got_error_msg(GOT_ERR_NOT_IMPL,
9753 "parent/child view pair not supported");
9754 break;
9755 case TOG_VIEW_TREE:
9756 if (view->type == TOG_VIEW_LOG)
9757 err = browse_commit_tree(new_view, y, x,
9758 view->state.log.selected_entry,
9759 view->state.log.in_repo_path,
9760 view->state.log.head_ref_name,
9761 view->state.log.repo);
9762 else if (view->type == TOG_VIEW_REF)
9763 err = browse_ref_tree(new_view, y, x,
9764 view->state.ref.selected_entry,
9765 view->state.ref.repo);
9766 else
9767 return got_error_msg(GOT_ERR_NOT_IMPL,
9768 "parent/child view pair not supported");
9769 break;
9770 case TOG_VIEW_REF:
9771 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9772 if (*new_view == NULL)
9773 return got_error_from_errno("view_open");
9774 if (view->type == TOG_VIEW_LOG)
9775 err = open_ref_view(*new_view, view->state.log.repo);
9776 else if (view->type == TOG_VIEW_TREE)
9777 err = open_ref_view(*new_view, view->state.tree.repo);
9778 else
9779 err = got_error_msg(GOT_ERR_NOT_IMPL,
9780 "parent/child view pair not supported");
9781 if (err)
9782 view_close(*new_view);
9783 break;
9784 case TOG_VIEW_HELP:
9785 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9786 if (*new_view == NULL)
9787 return got_error_from_errno("view_open");
9788 err = open_help_view(*new_view, view);
9789 if (err)
9790 view_close(*new_view);
9791 break;
9792 default:
9793 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9796 return err;
9800 * If view was scrolled down to move the selected line into view when opening a
9801 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9803 static void
9804 offset_selection_up(struct tog_view *view)
9806 switch (view->type) {
9807 case TOG_VIEW_BLAME: {
9808 struct tog_blame_view_state *s = &view->state.blame;
9809 if (s->first_displayed_line == 1) {
9810 s->selected_line = MAX(s->selected_line - view->offset,
9811 1);
9812 break;
9814 if (s->first_displayed_line > view->offset)
9815 s->first_displayed_line -= view->offset;
9816 else
9817 s->first_displayed_line = 1;
9818 s->selected_line += view->offset;
9819 break;
9821 case TOG_VIEW_LOG:
9822 log_scroll_up(&view->state.log, view->offset);
9823 view->state.log.selected += view->offset;
9824 break;
9825 case TOG_VIEW_REF:
9826 ref_scroll_up(&view->state.ref, view->offset);
9827 view->state.ref.selected += view->offset;
9828 break;
9829 case TOG_VIEW_TREE:
9830 tree_scroll_up(&view->state.tree, view->offset);
9831 view->state.tree.selected += view->offset;
9832 break;
9833 default:
9834 break;
9837 view->offset = 0;
9841 * If the selected line is in the section of screen covered by the bottom split,
9842 * scroll down offset lines to move it into view and index its new position.
9844 static const struct got_error *
9845 offset_selection_down(struct tog_view *view)
9847 const struct got_error *err = NULL;
9848 const struct got_error *(*scrolld)(struct tog_view *, int);
9849 int *selected = NULL;
9850 int header, offset;
9852 switch (view->type) {
9853 case TOG_VIEW_BLAME: {
9854 struct tog_blame_view_state *s = &view->state.blame;
9855 header = 3;
9856 scrolld = NULL;
9857 if (s->selected_line > view->nlines - header) {
9858 offset = abs(view->nlines - s->selected_line - header);
9859 s->first_displayed_line += offset;
9860 s->selected_line -= offset;
9861 view->offset = offset;
9863 break;
9865 case TOG_VIEW_LOG: {
9866 struct tog_log_view_state *s = &view->state.log;
9867 scrolld = &log_scroll_down;
9868 header = view_is_parent_view(view) ? 3 : 2;
9869 selected = &s->selected;
9870 break;
9872 case TOG_VIEW_REF: {
9873 struct tog_ref_view_state *s = &view->state.ref;
9874 scrolld = &ref_scroll_down;
9875 header = 3;
9876 selected = &s->selected;
9877 break;
9879 case TOG_VIEW_TREE: {
9880 struct tog_tree_view_state *s = &view->state.tree;
9881 scrolld = &tree_scroll_down;
9882 header = 5;
9883 selected = &s->selected;
9884 break;
9886 default:
9887 selected = NULL;
9888 scrolld = NULL;
9889 header = 0;
9890 break;
9893 if (selected && *selected > view->nlines - header) {
9894 offset = abs(view->nlines - *selected - header);
9895 view->offset = offset;
9896 if (scrolld && offset) {
9897 err = scrolld(view, offset);
9898 *selected -= offset;
9902 return err;
9905 static void
9906 list_commands(FILE *fp)
9908 size_t i;
9910 fprintf(fp, "commands:");
9911 for (i = 0; i < nitems(tog_commands); i++) {
9912 const struct tog_cmd *cmd = &tog_commands[i];
9913 fprintf(fp, " %s", cmd->name);
9915 fputc('\n', fp);
9918 __dead static void
9919 usage(int hflag, int status)
9921 FILE *fp = (status == 0) ? stdout : stderr;
9923 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9924 getprogname());
9925 if (hflag) {
9926 fprintf(fp, "lazy usage: %s path\n", getprogname());
9927 list_commands(fp);
9929 exit(status);
9932 static char **
9933 make_argv(int argc, ...)
9935 va_list ap;
9936 char **argv;
9937 int i;
9939 va_start(ap, argc);
9941 argv = calloc(argc, sizeof(char *));
9942 if (argv == NULL)
9943 err(1, "calloc");
9944 for (i = 0; i < argc; i++) {
9945 argv[i] = strdup(va_arg(ap, char *));
9946 if (argv[i] == NULL)
9947 err(1, "strdup");
9950 va_end(ap);
9951 return argv;
9955 * Try to convert 'tog path' into a 'tog log path' command.
9956 * The user could simply have mistyped the command rather than knowingly
9957 * provided a path. So check whether argv[0] can in fact be resolved
9958 * to a path in the HEAD commit and print a special error if not.
9959 * This hack is for mpi@ <3
9961 static const struct got_error *
9962 tog_log_with_path(int argc, char *argv[])
9964 const struct got_error *error = NULL, *close_err;
9965 const struct tog_cmd *cmd = NULL;
9966 struct got_repository *repo = NULL;
9967 struct got_worktree *worktree = NULL;
9968 struct got_object_id *commit_id = NULL, *id = NULL;
9969 struct got_commit_object *commit = NULL;
9970 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9971 char *commit_id_str = NULL, **cmd_argv = NULL;
9972 int *pack_fds = NULL;
9974 cwd = getcwd(NULL, 0);
9975 if (cwd == NULL)
9976 return got_error_from_errno("getcwd");
9978 error = got_repo_pack_fds_open(&pack_fds);
9979 if (error != NULL)
9980 goto done;
9982 error = got_worktree_open(&worktree, cwd, NULL);
9983 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9984 goto done;
9986 if (worktree)
9987 repo_path = strdup(got_worktree_get_repo_path(worktree));
9988 else
9989 repo_path = strdup(cwd);
9990 if (repo_path == NULL) {
9991 error = got_error_from_errno("strdup");
9992 goto done;
9995 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9996 if (error != NULL)
9997 goto done;
9999 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
10000 repo, worktree);
10001 if (error)
10002 goto done;
10004 error = tog_load_refs(repo, 0);
10005 if (error)
10006 goto done;
10007 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
10008 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
10009 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
10010 if (error)
10011 goto done;
10013 if (worktree) {
10014 got_worktree_close(worktree);
10015 worktree = NULL;
10018 error = got_object_open_as_commit(&commit, repo, commit_id);
10019 if (error)
10020 goto done;
10022 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
10023 if (error) {
10024 if (error->code != GOT_ERR_NO_TREE_ENTRY)
10025 goto done;
10026 fprintf(stderr, "%s: '%s' is no known command or path\n",
10027 getprogname(), argv[0]);
10028 usage(1, 1);
10029 /* not reached */
10032 error = got_object_id_str(&commit_id_str, commit_id);
10033 if (error)
10034 goto done;
10036 cmd = &tog_commands[0]; /* log */
10037 argc = 4;
10038 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
10039 error = cmd->cmd_main(argc, cmd_argv);
10040 done:
10041 if (repo) {
10042 close_err = got_repo_close(repo);
10043 if (error == NULL)
10044 error = close_err;
10046 if (commit)
10047 got_object_commit_close(commit);
10048 if (worktree)
10049 got_worktree_close(worktree);
10050 if (pack_fds) {
10051 const struct got_error *pack_err =
10052 got_repo_pack_fds_close(pack_fds);
10053 if (error == NULL)
10054 error = pack_err;
10056 free(id);
10057 free(commit_id_str);
10058 free(commit_id);
10059 free(cwd);
10060 free(repo_path);
10061 free(in_repo_path);
10062 if (cmd_argv) {
10063 int i;
10064 for (i = 0; i < argc; i++)
10065 free(cmd_argv[i]);
10066 free(cmd_argv);
10068 tog_free_refs();
10069 return error;
10072 int
10073 main(int argc, char *argv[])
10075 const struct got_error *io_err, *error = NULL;
10076 const struct tog_cmd *cmd = NULL;
10077 int ch, hflag = 0, Vflag = 0;
10078 char **cmd_argv = NULL;
10079 static const struct option longopts[] = {
10080 { "version", no_argument, NULL, 'V' },
10081 { NULL, 0, NULL, 0}
10083 char *diff_algo_str = NULL;
10084 const char *test_script_path;
10086 setlocale(LC_CTYPE, "");
10089 * Test mode init must happen before pledge() because "tty" will
10090 * not allow TTY-related ioctls to occur via regular files.
10092 test_script_path = getenv("TOG_TEST_SCRIPT");
10093 if (test_script_path != NULL) {
10094 error = init_mock_term(test_script_path);
10095 if (error) {
10096 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
10097 return 1;
10099 } else if (!isatty(STDIN_FILENO))
10100 errx(1, "standard input is not a tty");
10102 #if !defined(PROFILE)
10103 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
10104 NULL) == -1)
10105 err(1, "pledge");
10106 #endif
10108 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
10109 switch (ch) {
10110 case 'h':
10111 hflag = 1;
10112 break;
10113 case 'V':
10114 Vflag = 1;
10115 break;
10116 default:
10117 usage(hflag, 1);
10118 /* NOTREACHED */
10122 argc -= optind;
10123 argv += optind;
10124 optind = 1;
10125 optreset = 1;
10127 if (Vflag) {
10128 got_version_print_str();
10129 return 0;
10132 if (argc == 0) {
10133 if (hflag)
10134 usage(hflag, 0);
10135 /* Build an argument vector which runs a default command. */
10136 cmd = &tog_commands[0];
10137 argc = 1;
10138 cmd_argv = make_argv(argc, cmd->name);
10139 } else {
10140 size_t i;
10142 /* Did the user specify a command? */
10143 for (i = 0; i < nitems(tog_commands); i++) {
10144 if (strncmp(tog_commands[i].name, argv[0],
10145 strlen(argv[0])) == 0) {
10146 cmd = &tog_commands[i];
10147 break;
10152 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
10153 if (diff_algo_str) {
10154 if (strcasecmp(diff_algo_str, "patience") == 0)
10155 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
10156 if (strcasecmp(diff_algo_str, "myers") == 0)
10157 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
10160 tog_base_commit.idx = -1;
10161 tog_base_commit.marker = GOT_WORKTREE_STATE_UNKNOWN;
10163 if (cmd == NULL) {
10164 if (argc != 1)
10165 usage(0, 1);
10166 /* No command specified; try log with a path */
10167 error = tog_log_with_path(argc, argv);
10168 } else {
10169 if (hflag)
10170 cmd->cmd_usage();
10171 else
10172 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
10175 if (using_mock_io) {
10176 io_err = tog_io_close();
10177 if (error == NULL)
10178 error = io_err;
10180 endwin();
10181 if (cmd_argv) {
10182 int i;
10183 for (i = 0; i < argc; i++)
10184 free(cmd_argv[i]);
10185 free(cmd_argv);
10188 if (error && error->code != GOT_ERR_CANCELLED &&
10189 error->code != GOT_ERR_EOF &&
10190 error->code != GOT_ERR_PRIVSEP_EXIT &&
10191 error->code != GOT_ERR_PRIVSEP_PIPE &&
10192 !(error->code == GOT_ERR_ERRNO && errno == EINTR)) {
10193 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
10194 return 1;
10196 return 0;