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;
2432 if (tog_io.wait_for_ui && s->thread_args.need_commit_marker) {
2433 int rc;
2435 rc = pthread_cond_wait(&s->thread_args.log_loaded, &tog_mutex);
2436 if (rc)
2437 return got_error_set_errno(rc, "pthread_cond_wait");
2440 committer_time = got_object_commit_get_committer_time(commit);
2441 if (gmtime_r(&committer_time, &tm) == NULL)
2442 return got_error_from_errno("gmtime_r");
2443 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2444 return got_error(GOT_ERR_NO_SPACE);
2446 if (avail <= date_display_cols)
2447 limit = MIN(sizeof(datebuf) - 1, avail);
2448 else
2449 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2450 tc = get_color(&s->colors, TOG_COLOR_DATE);
2451 if (tc)
2452 wattr_on(view->window,
2453 COLOR_PAIR(tc->colorpair), NULL);
2454 waddnstr(view->window, datebuf, limit);
2455 if (tc)
2456 wattr_off(view->window,
2457 COLOR_PAIR(tc->colorpair), NULL);
2458 col = limit;
2459 if (col > avail)
2460 goto done;
2462 if (avail >= 120) {
2463 char *id_str;
2464 err = got_object_id_str(&id_str, id);
2465 if (err)
2466 goto done;
2467 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2468 if (tc)
2469 wattr_on(view->window,
2470 COLOR_PAIR(tc->colorpair), NULL);
2471 wprintw(view->window, "%.8s ", id_str);
2472 if (tc)
2473 wattr_off(view->window,
2474 COLOR_PAIR(tc->colorpair), NULL);
2475 free(id_str);
2476 col += 9;
2477 if (col > avail)
2478 goto done;
2481 if (s->use_committer)
2482 author = strdup(got_object_commit_get_committer(commit));
2483 else
2484 author = strdup(got_object_commit_get_author(commit));
2485 if (author == NULL) {
2486 err = got_error_from_errno("strdup");
2487 goto done;
2489 err = format_author(&wauthor, &author_width, author, avail - col, col);
2490 if (err)
2491 goto done;
2492 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2493 if (tc)
2494 wattr_on(view->window,
2495 COLOR_PAIR(tc->colorpair), NULL);
2496 waddwstr(view->window, wauthor);
2497 col += author_width;
2498 while (col < avail && author_width < author_display_cols + 2) {
2499 if (tog_base_commit.marker != GOT_WORKTREE_STATE_UNKNOWN &&
2500 author_width == marker_column &&
2501 entry->idx == tog_base_commit.idx) {
2502 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2503 if (tc)
2504 wattr_on(view->window,
2505 COLOR_PAIR(tc->colorpair), NULL);
2506 waddch(view->window, tog_base_commit.marker);
2507 if (tc)
2508 wattr_off(view->window,
2509 COLOR_PAIR(tc->colorpair), NULL);
2510 } else
2511 waddch(view->window, ' ');
2512 col++;
2513 author_width++;
2515 if (tc)
2516 wattr_off(view->window,
2517 COLOR_PAIR(tc->colorpair), NULL);
2518 if (col > avail)
2519 goto done;
2521 err = got_object_commit_get_logmsg(&logmsg0, commit);
2522 if (err)
2523 goto done;
2524 logmsg = logmsg0;
2525 while (*logmsg == '\n')
2526 logmsg++;
2527 newline = strchr(logmsg, '\n');
2528 if (newline)
2529 *newline = '\0';
2531 limit = avail - col;
2532 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2533 limit--; /* for the border */
2535 /* Prepend reference labels to log message if possible .*/
2536 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, id);
2537 err = build_refs_str(&refs_str, refs, id, s->repo);
2538 if (err)
2539 goto done;
2540 if (refs_str) {
2541 char *rs;
2543 if (asprintf(&rs, "[%s]", refs_str) == -1) {
2544 err = got_error_from_errno("asprintf");
2545 goto done;
2547 err = format_line(&wrefstr, &refstr_width,
2548 &scrollx, rs, view->x, limit, col, 1);
2549 free(rs);
2550 if (err)
2551 goto done;
2552 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2553 if (tc)
2554 wattr_on(view->window,
2555 COLOR_PAIR(tc->colorpair), NULL);
2556 waddwstr(view->window, &wrefstr[scrollx]);
2557 if (tc)
2558 wattr_off(view->window,
2559 COLOR_PAIR(tc->colorpair), NULL);
2560 col += MAX(refstr_width, 0);
2561 if (col > avail)
2562 goto done;
2564 if (col < avail) {
2565 waddch(view->window, ' ');
2566 col++;
2569 if (refstr_width > 0)
2570 logmsg_x = 0;
2571 else {
2572 int unscrolled_refstr_width;
2573 size_t len = wcslen(wrefstr);
2576 * No need to check for -1 return value here since
2577 * unprintables have been replaced by span_wline().
2579 unscrolled_refstr_width = wcswidth(wrefstr, len);
2580 unscrolled_refstr_width += 1; /* trailing space */
2581 logmsg_x = view->x - unscrolled_refstr_width;
2584 limit = avail - col;
2585 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2586 limit--; /* for the border */
2587 } else
2588 logmsg_x = view->x;
2590 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, logmsg_x,
2591 limit, col, 1);
2592 if (err)
2593 goto done;
2594 waddwstr(view->window, &wlogmsg[scrollx]);
2595 col += MAX(logmsg_width, 0);
2596 while (col < avail) {
2597 waddch(view->window, ' ');
2598 col++;
2600 done:
2601 free(logmsg0);
2602 free(wlogmsg);
2603 free(wrefstr);
2604 free(refs_str);
2605 free(author);
2606 free(wauthor);
2607 free(line);
2608 return err;
2611 static struct commit_queue_entry *
2612 alloc_commit_queue_entry(struct got_commit_object *commit,
2613 struct got_object_id *id)
2615 struct commit_queue_entry *entry;
2616 struct got_object_id *dup;
2618 entry = calloc(1, sizeof(*entry));
2619 if (entry == NULL)
2620 return NULL;
2622 dup = got_object_id_dup(id);
2623 if (dup == NULL) {
2624 free(entry);
2625 return NULL;
2628 entry->id = dup;
2629 entry->commit = commit;
2630 return entry;
2633 static void
2634 pop_commit(struct commit_queue *commits)
2636 struct commit_queue_entry *entry;
2638 entry = TAILQ_FIRST(&commits->head);
2639 TAILQ_REMOVE(&commits->head, entry, entry);
2640 got_object_commit_close(entry->commit);
2641 commits->ncommits--;
2642 free(entry->id);
2643 free(entry);
2646 static void
2647 free_commits(struct commit_queue *commits)
2649 while (!TAILQ_EMPTY(&commits->head))
2650 pop_commit(commits);
2653 static const struct got_error *
2654 match_commit(int *have_match, struct got_object_id *id,
2655 struct got_commit_object *commit, regex_t *regex)
2657 const struct got_error *err = NULL;
2658 regmatch_t regmatch;
2659 char *id_str = NULL, *logmsg = NULL;
2661 *have_match = 0;
2663 err = got_object_id_str(&id_str, id);
2664 if (err)
2665 return err;
2667 err = got_object_commit_get_logmsg(&logmsg, commit);
2668 if (err)
2669 goto done;
2671 if (regexec(regex, got_object_commit_get_author(commit), 1,
2672 &regmatch, 0) == 0 ||
2673 regexec(regex, got_object_commit_get_committer(commit), 1,
2674 &regmatch, 0) == 0 ||
2675 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2676 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2677 *have_match = 1;
2678 done:
2679 free(id_str);
2680 free(logmsg);
2681 return err;
2684 static const struct got_error *
2685 queue_commits(struct tog_log_thread_args *a)
2687 const struct got_error *err = NULL;
2690 * We keep all commits open throughout the lifetime of the log
2691 * view in order to avoid having to re-fetch commits from disk
2692 * while updating the display.
2694 do {
2695 struct got_object_id id;
2696 struct got_commit_object *commit;
2697 struct commit_queue_entry *entry;
2698 int limit_match = 0;
2699 int errcode;
2701 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2702 NULL, NULL);
2703 if (err)
2704 break;
2706 err = got_object_open_as_commit(&commit, a->repo, &id);
2707 if (err)
2708 break;
2709 entry = alloc_commit_queue_entry(commit, &id);
2710 if (entry == NULL) {
2711 err = got_error_from_errno("alloc_commit_queue_entry");
2712 break;
2715 errcode = pthread_mutex_lock(&tog_mutex);
2716 if (errcode) {
2717 err = got_error_set_errno(errcode,
2718 "pthread_mutex_lock");
2719 break;
2722 entry->idx = a->real_commits->ncommits;
2723 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2724 a->real_commits->ncommits++;
2726 if (*a->limiting) {
2727 err = match_commit(&limit_match, &id, commit,
2728 a->limit_regex);
2729 if (err)
2730 break;
2732 if (limit_match) {
2733 struct commit_queue_entry *matched;
2735 matched = alloc_commit_queue_entry(
2736 entry->commit, entry->id);
2737 if (matched == NULL) {
2738 err = got_error_from_errno(
2739 "alloc_commit_queue_entry");
2740 break;
2742 matched->commit = entry->commit;
2743 got_object_commit_retain(entry->commit);
2745 matched->idx = a->limit_commits->ncommits;
2746 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2747 matched, entry);
2748 a->limit_commits->ncommits++;
2752 * This is how we signal log_thread() that we
2753 * have found a match, and that it should be
2754 * counted as a new entry for the view.
2756 a->limit_match = limit_match;
2759 if (*a->searching == TOG_SEARCH_FORWARD &&
2760 !*a->search_next_done) {
2761 int have_match;
2762 err = match_commit(&have_match, &id, commit, a->regex);
2763 if (err)
2764 break;
2766 if (*a->limiting) {
2767 if (limit_match && have_match)
2768 *a->search_next_done =
2769 TOG_SEARCH_HAVE_MORE;
2770 } else if (have_match)
2771 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2774 errcode = pthread_mutex_unlock(&tog_mutex);
2775 if (errcode && err == NULL)
2776 err = got_error_set_errno(errcode,
2777 "pthread_mutex_unlock");
2778 if (err)
2779 break;
2780 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2782 return err;
2785 static void
2786 select_commit(struct tog_log_view_state *s)
2788 struct commit_queue_entry *entry;
2789 int ncommits = 0;
2791 entry = s->first_displayed_entry;
2792 while (entry) {
2793 if (ncommits == s->selected) {
2794 s->selected_entry = entry;
2795 break;
2797 entry = TAILQ_NEXT(entry, entry);
2798 ncommits++;
2802 static const struct got_error *
2803 draw_commits(struct tog_view *view)
2805 const struct got_error *err = NULL;
2806 struct tog_log_view_state *s = &view->state.log;
2807 struct commit_queue_entry *entry = s->selected_entry;
2808 int limit = view->nlines;
2809 int width;
2810 int ncommits, author_cols = 4, refstr_cols;
2811 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2812 char *refs_str = NULL;
2813 wchar_t *wline;
2814 struct tog_color *tc;
2815 static const size_t date_display_cols = 12;
2816 struct got_reflist_head *refs;
2818 if (view_is_hsplit_top(view))
2819 --limit; /* account for border */
2821 if (s->selected_entry &&
2822 !(view->searching && view->search_next_done == 0)) {
2823 err = got_object_id_str(&id_str, s->selected_entry->id);
2824 if (err)
2825 return err;
2826 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2827 s->selected_entry->id);
2828 err = build_refs_str(&refs_str, refs, s->selected_entry->id,
2829 s->repo);
2830 if (err)
2831 goto done;
2834 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2835 halfdelay(10); /* disable fast refresh */
2837 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2838 if (asprintf(&ncommits_str, " [%d/%d] %s",
2839 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2840 (view->searching && !view->search_next_done) ?
2841 "searching..." : "loading...") == -1) {
2842 err = got_error_from_errno("asprintf");
2843 goto done;
2845 } else {
2846 const char *search_str = NULL;
2847 const char *limit_str = NULL;
2849 if (view->searching) {
2850 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2851 search_str = "no more matches";
2852 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2853 search_str = "no matches found";
2854 else if (!view->search_next_done)
2855 search_str = "searching...";
2858 if (s->limit_view && s->commits->ncommits == 0)
2859 limit_str = "no matches found";
2861 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2862 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2863 search_str ? search_str : (refs_str ? refs_str : ""),
2864 limit_str ? limit_str : "") == -1) {
2865 err = got_error_from_errno("asprintf");
2866 goto done;
2870 free(refs_str);
2871 refs_str = NULL;
2873 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2874 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2875 "........................................",
2876 s->in_repo_path, ncommits_str) == -1) {
2877 err = got_error_from_errno("asprintf");
2878 header = NULL;
2879 goto done;
2881 } else if (asprintf(&header, "commit %s%s",
2882 id_str ? id_str : "........................................",
2883 ncommits_str) == -1) {
2884 err = got_error_from_errno("asprintf");
2885 header = NULL;
2886 goto done;
2888 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2889 if (err)
2890 goto done;
2892 werase(view->window);
2894 if (view_needs_focus_indication(view))
2895 wstandout(view->window);
2896 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2897 if (tc)
2898 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2899 waddwstr(view->window, wline);
2900 while (width < view->ncols) {
2901 waddch(view->window, ' ');
2902 width++;
2904 if (tc)
2905 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2906 if (view_needs_focus_indication(view))
2907 wstandend(view->window);
2908 free(wline);
2909 if (limit <= 1)
2910 goto done;
2912 /* Grow author column size if necessary, and set view->maxx. */
2913 entry = s->first_displayed_entry;
2914 ncommits = 0;
2915 view->maxx = 0;
2916 while (entry) {
2917 struct got_commit_object *c = entry->commit;
2918 char *author, *eol, *msg, *msg0;
2919 wchar_t *wauthor, *wmsg;
2920 int width;
2921 if (ncommits >= limit - 1)
2922 break;
2923 if (s->use_committer)
2924 author = strdup(got_object_commit_get_committer(c));
2925 else
2926 author = strdup(got_object_commit_get_author(c));
2927 if (author == NULL) {
2928 err = got_error_from_errno("strdup");
2929 goto done;
2931 err = format_author(&wauthor, &width, author, COLS,
2932 date_display_cols);
2933 if (author_cols < width)
2934 author_cols = width;
2935 free(wauthor);
2936 free(author);
2937 if (err)
2938 goto done;
2939 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2940 entry->id);
2941 err = build_refs_str(&refs_str, refs, entry->id, s->repo);
2942 if (err)
2943 goto done;
2944 if (refs_str) {
2945 wchar_t *ws;
2946 err = format_line(&ws, &width, NULL, refs_str,
2947 0, INT_MAX, date_display_cols + author_cols, 0);
2948 free(ws);
2949 free(refs_str);
2950 refs_str = NULL;
2951 if (err)
2952 goto done;
2953 refstr_cols = width + 3; /* account for [ ] + space */
2954 } else
2955 refstr_cols = 0;
2956 err = got_object_commit_get_logmsg(&msg0, c);
2957 if (err)
2958 goto done;
2959 msg = msg0;
2960 while (*msg == '\n')
2961 ++msg;
2962 if ((eol = strchr(msg, '\n')))
2963 *eol = '\0';
2964 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2965 date_display_cols + author_cols + refstr_cols, 0);
2966 if (err)
2967 goto done;
2968 view->maxx = MAX(view->maxx, width + refstr_cols);
2969 free(msg0);
2970 free(wmsg);
2971 ncommits++;
2972 entry = TAILQ_NEXT(entry, entry);
2975 entry = s->first_displayed_entry;
2976 s->last_displayed_entry = s->first_displayed_entry;
2977 ncommits = 0;
2978 while (entry) {
2979 if (ncommits >= limit - 1)
2980 break;
2981 if (ncommits == s->selected)
2982 wstandout(view->window);
2983 err = draw_commit(view, entry, date_display_cols, author_cols);
2984 if (ncommits == s->selected)
2985 wstandend(view->window);
2986 if (err)
2987 goto done;
2988 ncommits++;
2989 s->last_displayed_entry = entry;
2990 entry = TAILQ_NEXT(entry, entry);
2993 view_border(view);
2994 done:
2995 free(id_str);
2996 free(refs_str);
2997 free(ncommits_str);
2998 free(header);
2999 return err;
3002 static void
3003 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
3005 struct commit_queue_entry *entry;
3006 int nscrolled = 0;
3008 entry = TAILQ_FIRST(&s->commits->head);
3009 if (s->first_displayed_entry == entry)
3010 return;
3012 entry = s->first_displayed_entry;
3013 while (entry && nscrolled < maxscroll) {
3014 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3015 if (entry) {
3016 s->first_displayed_entry = entry;
3017 nscrolled++;
3022 static const struct got_error *
3023 trigger_log_thread(struct tog_view *view, int wait)
3025 struct tog_log_thread_args *ta = &view->state.log.thread_args;
3026 int errcode;
3028 if (!using_mock_io)
3029 halfdelay(1); /* fast refresh while loading commits */
3031 while (!ta->log_complete && !tog_thread_error &&
3032 (ta->commits_needed > 0 || ta->load_all)) {
3033 /* Wake the log thread. */
3034 errcode = pthread_cond_signal(&ta->need_commits);
3035 if (errcode)
3036 return got_error_set_errno(errcode,
3037 "pthread_cond_signal");
3040 * The mutex will be released while the view loop waits
3041 * in wgetch(), at which time the log thread will run.
3043 if (!wait)
3044 break;
3046 /* Display progress update in log view. */
3047 show_log_view(view);
3048 update_panels();
3049 doupdate();
3051 /* Wait right here while next commit is being loaded. */
3052 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
3053 if (errcode)
3054 return got_error_set_errno(errcode,
3055 "pthread_cond_wait");
3057 /* Display progress update in log view. */
3058 show_log_view(view);
3059 update_panels();
3060 doupdate();
3063 return NULL;
3066 static const struct got_error *
3067 request_log_commits(struct tog_view *view)
3069 struct tog_log_view_state *state = &view->state.log;
3070 const struct got_error *err = NULL;
3072 if (state->thread_args.log_complete)
3073 return NULL;
3075 state->thread_args.commits_needed += view->nscrolled;
3076 err = trigger_log_thread(view, 1);
3077 view->nscrolled = 0;
3079 return err;
3082 static const struct got_error *
3083 log_scroll_down(struct tog_view *view, int maxscroll)
3085 struct tog_log_view_state *s = &view->state.log;
3086 const struct got_error *err = NULL;
3087 struct commit_queue_entry *pentry;
3088 int nscrolled = 0, ncommits_needed;
3090 if (s->last_displayed_entry == NULL)
3091 return NULL;
3093 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
3094 if (s->commits->ncommits < ncommits_needed &&
3095 !s->thread_args.log_complete) {
3097 * Ask the log thread for required amount of commits.
3099 s->thread_args.commits_needed +=
3100 ncommits_needed - s->commits->ncommits;
3101 err = trigger_log_thread(view, 1);
3102 if (err)
3103 return err;
3106 do {
3107 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
3108 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
3109 break;
3111 s->last_displayed_entry = pentry ?
3112 pentry : s->last_displayed_entry;
3114 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
3115 if (pentry == NULL)
3116 break;
3117 s->first_displayed_entry = pentry;
3118 } while (++nscrolled < maxscroll);
3120 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
3121 view->nscrolled += nscrolled;
3122 else
3123 view->nscrolled = 0;
3125 return err;
3128 static const struct got_error *
3129 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
3130 struct got_commit_object *commit, struct got_object_id *commit_id,
3131 struct tog_view *log_view, struct got_repository *repo)
3133 const struct got_error *err;
3134 struct got_object_qid *parent_id;
3135 struct tog_view *diff_view;
3137 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3138 if (diff_view == NULL)
3139 return got_error_from_errno("view_open");
3141 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3142 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3143 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3144 if (err == NULL)
3145 *new_view = diff_view;
3146 return err;
3149 static const struct got_error *
3150 tree_view_visit_subtree(struct tog_tree_view_state *s,
3151 struct got_tree_object *subtree)
3153 struct tog_parent_tree *parent;
3155 parent = calloc(1, sizeof(*parent));
3156 if (parent == NULL)
3157 return got_error_from_errno("calloc");
3159 parent->tree = s->tree;
3160 parent->first_displayed_entry = s->first_displayed_entry;
3161 parent->selected_entry = s->selected_entry;
3162 parent->selected = s->selected;
3163 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3164 s->tree = subtree;
3165 s->selected = 0;
3166 s->first_displayed_entry = NULL;
3167 return NULL;
3170 static const struct got_error *
3171 tree_view_walk_path(struct tog_tree_view_state *s,
3172 struct got_commit_object *commit, const char *path)
3174 const struct got_error *err = NULL;
3175 struct got_tree_object *tree = NULL;
3176 const char *p;
3177 char *slash, *subpath = NULL;
3179 /* Walk the path and open corresponding tree objects. */
3180 p = path;
3181 while (*p) {
3182 struct got_tree_entry *te;
3183 struct got_object_id *tree_id;
3184 char *te_name;
3186 while (p[0] == '/')
3187 p++;
3189 /* Ensure the correct subtree entry is selected. */
3190 slash = strchr(p, '/');
3191 if (slash == NULL)
3192 te_name = strdup(p);
3193 else
3194 te_name = strndup(p, slash - p);
3195 if (te_name == NULL) {
3196 err = got_error_from_errno("strndup");
3197 break;
3199 te = got_object_tree_find_entry(s->tree, te_name);
3200 if (te == NULL) {
3201 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3202 free(te_name);
3203 break;
3205 free(te_name);
3206 s->first_displayed_entry = s->selected_entry = te;
3208 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3209 break; /* jump to this file's entry */
3211 slash = strchr(p, '/');
3212 if (slash)
3213 subpath = strndup(path, slash - path);
3214 else
3215 subpath = strdup(path);
3216 if (subpath == NULL) {
3217 err = got_error_from_errno("strdup");
3218 break;
3221 err = got_object_id_by_path(&tree_id, s->repo, commit,
3222 subpath);
3223 if (err)
3224 break;
3226 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3227 free(tree_id);
3228 if (err)
3229 break;
3231 err = tree_view_visit_subtree(s, tree);
3232 if (err) {
3233 got_object_tree_close(tree);
3234 break;
3236 if (slash == NULL)
3237 break;
3238 free(subpath);
3239 subpath = NULL;
3240 p = slash;
3243 free(subpath);
3244 return err;
3247 static const struct got_error *
3248 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3249 struct commit_queue_entry *entry, const char *path,
3250 const char *head_ref_name, struct got_repository *repo)
3252 const struct got_error *err = NULL;
3253 struct tog_tree_view_state *s;
3254 struct tog_view *tree_view;
3256 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3257 if (tree_view == NULL)
3258 return got_error_from_errno("view_open");
3260 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3261 if (err)
3262 return err;
3263 s = &tree_view->state.tree;
3265 *new_view = tree_view;
3267 if (got_path_is_root_dir(path))
3268 return NULL;
3270 return tree_view_walk_path(s, entry->commit, path);
3273 static const struct got_error *
3274 block_signals_used_by_main_thread(void)
3276 sigset_t sigset;
3277 int errcode;
3279 if (sigemptyset(&sigset) == -1)
3280 return got_error_from_errno("sigemptyset");
3282 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3283 if (sigaddset(&sigset, SIGWINCH) == -1)
3284 return got_error_from_errno("sigaddset");
3285 if (sigaddset(&sigset, SIGCONT) == -1)
3286 return got_error_from_errno("sigaddset");
3287 if (sigaddset(&sigset, SIGINT) == -1)
3288 return got_error_from_errno("sigaddset");
3289 if (sigaddset(&sigset, SIGTERM) == -1)
3290 return got_error_from_errno("sigaddset");
3292 /* ncurses handles SIGTSTP */
3293 if (sigaddset(&sigset, SIGTSTP) == -1)
3294 return got_error_from_errno("sigaddset");
3296 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3297 if (errcode)
3298 return got_error_set_errno(errcode, "pthread_sigmask");
3300 return NULL;
3303 static void *
3304 log_thread(void *arg)
3306 const struct got_error *err = NULL;
3307 int errcode = 0;
3308 struct tog_log_thread_args *a = arg;
3309 int done = 0;
3312 * Sync startup with main thread such that we begin our
3313 * work once view_input() has released the mutex.
3315 errcode = pthread_mutex_lock(&tog_mutex);
3316 if (errcode) {
3317 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3318 return (void *)err;
3321 err = block_signals_used_by_main_thread();
3322 if (err) {
3323 pthread_mutex_unlock(&tog_mutex);
3324 goto done;
3327 while (!done && !err && !tog_fatal_signal_received()) {
3328 errcode = pthread_mutex_unlock(&tog_mutex);
3329 if (errcode) {
3330 err = got_error_set_errno(errcode,
3331 "pthread_mutex_unlock");
3332 goto done;
3334 err = queue_commits(a);
3335 if (err) {
3336 if (err->code != GOT_ERR_ITER_COMPLETED)
3337 goto done;
3338 err = NULL;
3339 done = 1;
3340 a->commits_needed = 0;
3341 } else if (a->commits_needed > 0 && !a->load_all) {
3342 if (*a->limiting) {
3343 if (a->limit_match)
3344 a->commits_needed--;
3345 } else
3346 a->commits_needed--;
3349 errcode = pthread_mutex_lock(&tog_mutex);
3350 if (errcode) {
3351 err = got_error_set_errno(errcode,
3352 "pthread_mutex_lock");
3353 goto done;
3354 } else if (*a->quit)
3355 done = 1;
3356 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3357 *a->first_displayed_entry =
3358 TAILQ_FIRST(&a->limit_commits->head);
3359 *a->selected_entry = *a->first_displayed_entry;
3360 } else if (*a->first_displayed_entry == NULL) {
3361 *a->first_displayed_entry =
3362 TAILQ_FIRST(&a->real_commits->head);
3363 *a->selected_entry = *a->first_displayed_entry;
3366 errcode = pthread_cond_signal(&a->commit_loaded);
3367 if (errcode) {
3368 err = got_error_set_errno(errcode,
3369 "pthread_cond_signal");
3370 pthread_mutex_unlock(&tog_mutex);
3371 goto done;
3374 if (a->commits_needed == 0 &&
3375 a->need_commit_marker && a->worktree) {
3376 errcode = pthread_mutex_unlock(&tog_mutex);
3377 if (errcode) {
3378 err = got_error_set_errno(errcode,
3379 "pthread_mutex_unlock");
3380 goto done;
3382 err = got_worktree_get_state(&tog_base_commit.marker,
3383 a->repo, a->worktree, NULL, NULL);
3384 if (err)
3385 goto done;
3386 errcode = pthread_mutex_lock(&tog_mutex);
3387 if (errcode) {
3388 err = got_error_set_errno(errcode,
3389 "pthread_mutex_lock");
3390 goto done;
3392 a->need_commit_marker = 0;
3394 * The main thread did not close this
3395 * work tree yet. Close it now.
3397 got_worktree_close(a->worktree);
3398 a->worktree = NULL;
3400 if (*a->quit)
3401 done = 1;
3404 if (done)
3405 a->commits_needed = 0;
3406 else {
3407 if (a->commits_needed == 0 && !a->load_all) {
3408 if (tog_io.wait_for_ui) {
3409 errcode = pthread_cond_signal(
3410 &a->log_loaded);
3411 if (errcode && err == NULL)
3412 err = got_error_set_errno(
3413 errcode,
3414 "pthread_cond_signal");
3417 errcode = pthread_cond_wait(&a->need_commits,
3418 &tog_mutex);
3419 if (errcode) {
3420 err = got_error_set_errno(errcode,
3421 "pthread_cond_wait");
3422 pthread_mutex_unlock(&tog_mutex);
3423 goto done;
3425 if (*a->quit)
3426 done = 1;
3430 a->log_complete = 1;
3431 if (tog_io.wait_for_ui) {
3432 errcode = pthread_cond_signal(&a->log_loaded);
3433 if (errcode && err == NULL)
3434 err = got_error_set_errno(errcode,
3435 "pthread_cond_signal");
3438 errcode = pthread_mutex_unlock(&tog_mutex);
3439 if (errcode)
3440 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3441 done:
3442 if (err) {
3443 tog_thread_error = 1;
3444 pthread_cond_signal(&a->commit_loaded);
3445 if (a->worktree) {
3446 got_worktree_close(a->worktree);
3447 a->worktree = NULL;
3450 return (void *)err;
3453 static const struct got_error *
3454 stop_log_thread(struct tog_log_view_state *s)
3456 const struct got_error *err = NULL, *thread_err = NULL;
3457 int errcode;
3459 if (s->thread) {
3460 s->quit = 1;
3461 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3462 if (errcode)
3463 return got_error_set_errno(errcode,
3464 "pthread_cond_signal");
3465 errcode = pthread_mutex_unlock(&tog_mutex);
3466 if (errcode)
3467 return got_error_set_errno(errcode,
3468 "pthread_mutex_unlock");
3469 errcode = pthread_join(s->thread, (void **)&thread_err);
3470 if (errcode)
3471 return got_error_set_errno(errcode, "pthread_join");
3472 errcode = pthread_mutex_lock(&tog_mutex);
3473 if (errcode)
3474 return got_error_set_errno(errcode,
3475 "pthread_mutex_lock");
3476 s->thread = NULL;
3479 if (s->thread_args.repo) {
3480 err = got_repo_close(s->thread_args.repo);
3481 s->thread_args.repo = NULL;
3484 if (s->thread_args.pack_fds) {
3485 const struct got_error *pack_err =
3486 got_repo_pack_fds_close(s->thread_args.pack_fds);
3487 if (err == NULL)
3488 err = pack_err;
3489 s->thread_args.pack_fds = NULL;
3492 if (s->thread_args.graph) {
3493 got_commit_graph_close(s->thread_args.graph);
3494 s->thread_args.graph = NULL;
3497 return err ? err : thread_err;
3500 static const struct got_error *
3501 close_log_view(struct tog_view *view)
3503 const struct got_error *err = NULL;
3504 struct tog_log_view_state *s = &view->state.log;
3505 int errcode;
3507 err = stop_log_thread(s);
3509 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3510 if (errcode && err == NULL)
3511 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3513 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3514 if (errcode && err == NULL)
3515 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3517 free_commits(&s->limit_commits);
3518 free_commits(&s->real_commits);
3519 free(s->in_repo_path);
3520 s->in_repo_path = NULL;
3521 free(s->start_id);
3522 s->start_id = NULL;
3523 free(s->head_ref_name);
3524 s->head_ref_name = NULL;
3525 return err;
3529 * We use two queues to implement the limit feature: first consists of
3530 * commits matching the current limit_regex; second is the real queue
3531 * of all known commits (real_commits). When the user starts limiting,
3532 * we swap queues such that all movement and displaying functionality
3533 * works with very slight change.
3535 static const struct got_error *
3536 limit_log_view(struct tog_view *view)
3538 struct tog_log_view_state *s = &view->state.log;
3539 struct commit_queue_entry *entry;
3540 struct tog_view *v = view;
3541 const struct got_error *err = NULL;
3542 char pattern[1024];
3543 int ret;
3545 if (view_is_hsplit_top(view))
3546 v = view->child;
3547 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3548 v = view->parent;
3550 /* Get the pattern */
3551 wmove(v->window, v->nlines - 1, 0);
3552 wclrtoeol(v->window);
3553 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3554 nodelay(v->window, FALSE);
3555 nocbreak();
3556 echo();
3557 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3558 cbreak();
3559 noecho();
3560 nodelay(v->window, TRUE);
3561 if (ret == ERR)
3562 return NULL;
3564 if (*pattern == '\0') {
3566 * Safety measure for the situation where the user
3567 * resets limit without previously limiting anything.
3569 if (!s->limit_view)
3570 return NULL;
3573 * User could have pressed Ctrl+L, which refreshed the
3574 * commit queues, it means we can't save previously
3575 * (before limit took place) displayed entries,
3576 * because they would point to already free'ed memory,
3577 * so we are forced to always select first entry of
3578 * the queue.
3580 s->commits = &s->real_commits;
3581 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3582 s->selected_entry = s->first_displayed_entry;
3583 s->selected = 0;
3584 s->limit_view = 0;
3586 return NULL;
3589 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3590 return NULL;
3592 s->limit_view = 1;
3594 /* Clear the screen while loading limit view */
3595 s->first_displayed_entry = NULL;
3596 s->last_displayed_entry = NULL;
3597 s->selected_entry = NULL;
3598 s->commits = &s->limit_commits;
3600 /* Prepare limit queue for new search */
3601 free_commits(&s->limit_commits);
3602 s->limit_commits.ncommits = 0;
3604 /* First process commits, which are in queue already */
3605 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3606 int have_match = 0;
3608 err = match_commit(&have_match, entry->id,
3609 entry->commit, &s->limit_regex);
3610 if (err)
3611 return err;
3613 if (have_match) {
3614 struct commit_queue_entry *matched;
3616 matched = alloc_commit_queue_entry(entry->commit,
3617 entry->id);
3618 if (matched == NULL) {
3619 err = got_error_from_errno(
3620 "alloc_commit_queue_entry");
3621 break;
3623 matched->commit = entry->commit;
3624 got_object_commit_retain(entry->commit);
3626 matched->idx = s->limit_commits.ncommits;
3627 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3628 matched, entry);
3629 s->limit_commits.ncommits++;
3633 /* Second process all the commits, until we fill the screen */
3634 if (s->limit_commits.ncommits < view->nlines - 1 &&
3635 !s->thread_args.log_complete) {
3636 s->thread_args.commits_needed +=
3637 view->nlines - s->limit_commits.ncommits - 1;
3638 err = trigger_log_thread(view, 1);
3639 if (err)
3640 return err;
3643 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3644 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3645 s->selected = 0;
3647 return NULL;
3650 static const struct got_error *
3651 search_start_log_view(struct tog_view *view)
3653 struct tog_log_view_state *s = &view->state.log;
3655 s->matched_entry = NULL;
3656 s->search_entry = NULL;
3657 return NULL;
3660 static const struct got_error *
3661 search_next_log_view(struct tog_view *view)
3663 const struct got_error *err = NULL;
3664 struct tog_log_view_state *s = &view->state.log;
3665 struct commit_queue_entry *entry;
3667 /* Display progress update in log view. */
3668 show_log_view(view);
3669 update_panels();
3670 doupdate();
3672 if (s->search_entry) {
3673 int errcode, ch;
3674 errcode = pthread_mutex_unlock(&tog_mutex);
3675 if (errcode)
3676 return got_error_set_errno(errcode,
3677 "pthread_mutex_unlock");
3678 ch = wgetch(view->window);
3679 errcode = pthread_mutex_lock(&tog_mutex);
3680 if (errcode)
3681 return got_error_set_errno(errcode,
3682 "pthread_mutex_lock");
3683 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3684 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3685 return NULL;
3687 if (view->searching == TOG_SEARCH_FORWARD)
3688 entry = TAILQ_NEXT(s->search_entry, entry);
3689 else
3690 entry = TAILQ_PREV(s->search_entry,
3691 commit_queue_head, entry);
3692 } else if (s->matched_entry) {
3694 * If the user has moved the cursor after we hit a match,
3695 * the position from where we should continue searching
3696 * might have changed.
3698 if (view->searching == TOG_SEARCH_FORWARD)
3699 entry = TAILQ_NEXT(s->selected_entry, entry);
3700 else
3701 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3702 entry);
3703 } else {
3704 entry = s->selected_entry;
3707 while (1) {
3708 int have_match = 0;
3710 if (entry == NULL) {
3711 if (s->thread_args.log_complete ||
3712 view->searching == TOG_SEARCH_BACKWARD) {
3713 view->search_next_done =
3714 (s->matched_entry == NULL ?
3715 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3716 s->search_entry = NULL;
3717 return NULL;
3720 * Poke the log thread for more commits and return,
3721 * allowing the main loop to make progress. Search
3722 * will resume at s->search_entry once we come back.
3724 s->thread_args.commits_needed++;
3725 return trigger_log_thread(view, 0);
3728 err = match_commit(&have_match, entry->id, entry->commit,
3729 &view->regex);
3730 if (err)
3731 break;
3732 if (have_match) {
3733 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3734 s->matched_entry = entry;
3735 break;
3738 s->search_entry = entry;
3739 if (view->searching == TOG_SEARCH_FORWARD)
3740 entry = TAILQ_NEXT(entry, entry);
3741 else
3742 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3745 if (s->matched_entry) {
3746 int cur = s->selected_entry->idx;
3747 while (cur < s->matched_entry->idx) {
3748 err = input_log_view(NULL, view, KEY_DOWN);
3749 if (err)
3750 return err;
3751 cur++;
3753 while (cur > s->matched_entry->idx) {
3754 err = input_log_view(NULL, view, KEY_UP);
3755 if (err)
3756 return err;
3757 cur--;
3761 s->search_entry = NULL;
3763 return NULL;
3766 static const struct got_error *
3767 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3768 struct got_repository *repo, const char *head_ref_name,
3769 const char *in_repo_path, int log_branches,
3770 struct got_worktree *worktree)
3772 const struct got_error *err = NULL;
3773 struct tog_log_view_state *s = &view->state.log;
3774 struct got_repository *thread_repo = NULL;
3775 struct got_commit_graph *thread_graph = NULL;
3776 int errcode;
3778 if (in_repo_path != s->in_repo_path) {
3779 free(s->in_repo_path);
3780 s->in_repo_path = strdup(in_repo_path);
3781 if (s->in_repo_path == NULL) {
3782 err = got_error_from_errno("strdup");
3783 goto done;
3787 /* The commit queue only contains commits being displayed. */
3788 TAILQ_INIT(&s->real_commits.head);
3789 s->real_commits.ncommits = 0;
3790 s->commits = &s->real_commits;
3792 TAILQ_INIT(&s->limit_commits.head);
3793 s->limit_view = 0;
3794 s->limit_commits.ncommits = 0;
3796 s->repo = repo;
3797 if (head_ref_name) {
3798 s->head_ref_name = strdup(head_ref_name);
3799 if (s->head_ref_name == NULL) {
3800 err = got_error_from_errno("strdup");
3801 goto done;
3804 s->start_id = got_object_id_dup(start_id);
3805 if (s->start_id == NULL) {
3806 err = got_error_from_errno("got_object_id_dup");
3807 goto done;
3809 s->log_branches = log_branches;
3810 s->use_committer = 1;
3812 STAILQ_INIT(&s->colors);
3813 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3814 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3815 get_color_value("TOG_COLOR_COMMIT"));
3816 if (err)
3817 goto done;
3818 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3819 get_color_value("TOG_COLOR_AUTHOR"));
3820 if (err) {
3821 free_colors(&s->colors);
3822 goto done;
3824 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3825 get_color_value("TOG_COLOR_DATE"));
3826 if (err) {
3827 free_colors(&s->colors);
3828 goto done;
3832 view->show = show_log_view;
3833 view->input = input_log_view;
3834 view->resize = resize_log_view;
3835 view->close = close_log_view;
3836 view->search_start = search_start_log_view;
3837 view->search_next = search_next_log_view;
3839 if (s->thread_args.pack_fds == NULL) {
3840 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3841 if (err)
3842 goto done;
3844 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3845 s->thread_args.pack_fds);
3846 if (err)
3847 goto done;
3848 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3849 !s->log_branches);
3850 if (err)
3851 goto done;
3852 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3853 s->repo, NULL, NULL);
3854 if (err)
3855 goto done;
3857 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3858 if (errcode) {
3859 err = got_error_set_errno(errcode, "pthread_cond_init");
3860 goto done;
3862 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3863 if (errcode) {
3864 err = got_error_set_errno(errcode, "pthread_cond_init");
3865 goto done;
3868 if (using_mock_io) {
3869 int rc;
3871 rc = pthread_cond_init(&s->thread_args.log_loaded, NULL);
3872 if (rc)
3873 return got_error_set_errno(rc, "pthread_cond_init");
3876 s->thread_args.commits_needed = view->nlines;
3877 s->thread_args.graph = thread_graph;
3878 s->thread_args.real_commits = &s->real_commits;
3879 s->thread_args.limit_commits = &s->limit_commits;
3880 s->thread_args.in_repo_path = s->in_repo_path;
3881 s->thread_args.start_id = s->start_id;
3882 s->thread_args.repo = thread_repo;
3883 s->thread_args.log_complete = 0;
3884 s->thread_args.quit = &s->quit;
3885 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3886 s->thread_args.selected_entry = &s->selected_entry;
3887 s->thread_args.searching = &view->searching;
3888 s->thread_args.search_next_done = &view->search_next_done;
3889 s->thread_args.regex = &view->regex;
3890 s->thread_args.limiting = &s->limit_view;
3891 s->thread_args.limit_regex = &s->limit_regex;
3892 s->thread_args.limit_commits = &s->limit_commits;
3893 s->thread_args.worktree = worktree;
3894 if (worktree)
3895 s->thread_args.need_commit_marker = 1;
3896 done:
3897 if (err) {
3898 if (view->close == NULL)
3899 close_log_view(view);
3900 view_close(view);
3902 return err;
3905 static const struct got_error *
3906 show_log_view(struct tog_view *view)
3908 const struct got_error *err;
3909 struct tog_log_view_state *s = &view->state.log;
3911 if (s->thread == NULL) {
3912 int errcode = pthread_create(&s->thread, NULL, log_thread,
3913 &s->thread_args);
3914 if (errcode)
3915 return got_error_set_errno(errcode, "pthread_create");
3916 if (s->thread_args.commits_needed > 0) {
3917 err = trigger_log_thread(view, 1);
3918 if (err)
3919 return err;
3923 return draw_commits(view);
3926 static void
3927 log_move_cursor_up(struct tog_view *view, int page, int home)
3929 struct tog_log_view_state *s = &view->state.log;
3931 if (s->first_displayed_entry == NULL)
3932 return;
3933 if (s->selected_entry->idx == 0)
3934 view->count = 0;
3936 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3937 || home)
3938 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3940 if (!page && !home && s->selected > 0)
3941 --s->selected;
3942 else
3943 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3945 select_commit(s);
3946 return;
3949 static const struct got_error *
3950 log_move_cursor_down(struct tog_view *view, int page)
3952 struct tog_log_view_state *s = &view->state.log;
3953 const struct got_error *err = NULL;
3954 int eos = view->nlines - 2;
3956 if (s->first_displayed_entry == NULL)
3957 return NULL;
3959 if (s->thread_args.log_complete &&
3960 s->selected_entry->idx >= s->commits->ncommits - 1)
3961 return NULL;
3963 if (view_is_hsplit_top(view))
3964 --eos; /* border consumes the last line */
3966 if (!page) {
3967 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3968 ++s->selected;
3969 else
3970 err = log_scroll_down(view, 1);
3971 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3972 struct commit_queue_entry *entry;
3973 int n;
3975 s->selected = 0;
3976 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3977 s->last_displayed_entry = entry;
3978 for (n = 0; n <= eos; n++) {
3979 if (entry == NULL)
3980 break;
3981 s->first_displayed_entry = entry;
3982 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3984 if (n > 0)
3985 s->selected = n - 1;
3986 } else {
3987 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3988 s->thread_args.log_complete)
3989 s->selected += MIN(page,
3990 s->commits->ncommits - s->selected_entry->idx - 1);
3991 else
3992 err = log_scroll_down(view, page);
3994 if (err)
3995 return err;
3998 * We might necessarily overshoot in horizontal
3999 * splits; if so, select the last displayed commit.
4001 if (s->first_displayed_entry && s->last_displayed_entry) {
4002 s->selected = MIN(s->selected,
4003 s->last_displayed_entry->idx -
4004 s->first_displayed_entry->idx);
4007 select_commit(s);
4009 if (s->thread_args.log_complete &&
4010 s->selected_entry->idx == s->commits->ncommits - 1)
4011 view->count = 0;
4013 return NULL;
4016 static void
4017 view_get_split(struct tog_view *view, int *y, int *x)
4019 *x = 0;
4020 *y = 0;
4022 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
4023 if (view->child && view->child->resized_y)
4024 *y = view->child->resized_y;
4025 else if (view->resized_y)
4026 *y = view->resized_y;
4027 else
4028 *y = view_split_begin_y(view->lines);
4029 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
4030 if (view->child && view->child->resized_x)
4031 *x = view->child->resized_x;
4032 else if (view->resized_x)
4033 *x = view->resized_x;
4034 else
4035 *x = view_split_begin_x(view->begin_x);
4039 /* Split view horizontally at y and offset view->state->selected line. */
4040 static const struct got_error *
4041 view_init_hsplit(struct tog_view *view, int y)
4043 const struct got_error *err = NULL;
4045 view->nlines = y;
4046 view->ncols = COLS;
4047 err = view_resize(view);
4048 if (err)
4049 return err;
4051 err = offset_selection_down(view);
4053 return err;
4056 static const struct got_error *
4057 log_goto_line(struct tog_view *view, int nlines)
4059 const struct got_error *err = NULL;
4060 struct tog_log_view_state *s = &view->state.log;
4061 int g, idx = s->selected_entry->idx;
4063 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
4064 return NULL;
4066 g = view->gline;
4067 view->gline = 0;
4069 if (g >= s->first_displayed_entry->idx + 1 &&
4070 g <= s->last_displayed_entry->idx + 1 &&
4071 g - s->first_displayed_entry->idx - 1 < nlines) {
4072 s->selected = g - s->first_displayed_entry->idx - 1;
4073 select_commit(s);
4074 return NULL;
4077 if (idx + 1 < g) {
4078 err = log_move_cursor_down(view, g - idx - 1);
4079 if (!err && g > s->selected_entry->idx + 1)
4080 err = log_move_cursor_down(view,
4081 g - s->first_displayed_entry->idx - 1);
4082 if (err)
4083 return err;
4084 } else if (idx + 1 > g)
4085 log_move_cursor_up(view, idx - g + 1, 0);
4087 if (g < nlines && s->first_displayed_entry->idx == 0)
4088 s->selected = g - 1;
4090 select_commit(s);
4091 return NULL;
4095 static void
4096 horizontal_scroll_input(struct tog_view *view, int ch)
4099 switch (ch) {
4100 case KEY_LEFT:
4101 case 'h':
4102 view->x -= MIN(view->x, 2);
4103 if (view->x <= 0)
4104 view->count = 0;
4105 break;
4106 case KEY_RIGHT:
4107 case 'l':
4108 if (view->x + view->ncols / 2 < view->maxx)
4109 view->x += 2;
4110 else
4111 view->count = 0;
4112 break;
4113 case '0':
4114 view->x = 0;
4115 break;
4116 case '$':
4117 view->x = MAX(view->maxx - view->ncols / 2, 0);
4118 view->count = 0;
4119 break;
4120 default:
4121 break;
4125 static const struct got_error *
4126 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
4128 const struct got_error *err = NULL;
4129 struct tog_log_view_state *s = &view->state.log;
4130 int eos, nscroll;
4132 if (s->thread_args.load_all) {
4133 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
4134 s->thread_args.load_all = 0;
4135 else if (s->thread_args.log_complete) {
4136 err = log_move_cursor_down(view, s->commits->ncommits);
4137 s->thread_args.load_all = 0;
4139 if (err)
4140 return err;
4143 eos = nscroll = view->nlines - 1;
4144 if (view_is_hsplit_top(view))
4145 --eos; /* border */
4147 if (view->gline)
4148 return log_goto_line(view, eos);
4150 switch (ch) {
4151 case '&':
4152 err = limit_log_view(view);
4153 break;
4154 case 'q':
4155 s->quit = 1;
4156 break;
4157 case '0':
4158 case '$':
4159 case KEY_RIGHT:
4160 case 'l':
4161 case KEY_LEFT:
4162 case 'h':
4163 horizontal_scroll_input(view, ch);
4164 break;
4165 case 'k':
4166 case KEY_UP:
4167 case '<':
4168 case ',':
4169 case CTRL('p'):
4170 log_move_cursor_up(view, 0, 0);
4171 break;
4172 case 'g':
4173 case '=':
4174 case KEY_HOME:
4175 log_move_cursor_up(view, 0, 1);
4176 view->count = 0;
4177 break;
4178 case CTRL('u'):
4179 case 'u':
4180 nscroll /= 2;
4181 /* FALL THROUGH */
4182 case KEY_PPAGE:
4183 case CTRL('b'):
4184 case 'b':
4185 log_move_cursor_up(view, nscroll, 0);
4186 break;
4187 case 'j':
4188 case KEY_DOWN:
4189 case '>':
4190 case '.':
4191 case CTRL('n'):
4192 err = log_move_cursor_down(view, 0);
4193 break;
4194 case '@':
4195 s->use_committer = !s->use_committer;
4196 view->action = s->use_committer ?
4197 "show committer" : "show commit author";
4198 break;
4199 case 'G':
4200 case '*':
4201 case KEY_END: {
4202 /* We don't know yet how many commits, so we're forced to
4203 * traverse them all. */
4204 view->count = 0;
4205 s->thread_args.load_all = 1;
4206 if (!s->thread_args.log_complete)
4207 return trigger_log_thread(view, 0);
4208 err = log_move_cursor_down(view, s->commits->ncommits);
4209 s->thread_args.load_all = 0;
4210 break;
4212 case CTRL('d'):
4213 case 'd':
4214 nscroll /= 2;
4215 /* FALL THROUGH */
4216 case KEY_NPAGE:
4217 case CTRL('f'):
4218 case 'f':
4219 case ' ':
4220 err = log_move_cursor_down(view, nscroll);
4221 break;
4222 case KEY_RESIZE:
4223 if (s->selected > view->nlines - 2)
4224 s->selected = view->nlines - 2;
4225 if (s->selected > s->commits->ncommits - 1)
4226 s->selected = s->commits->ncommits - 1;
4227 select_commit(s);
4228 if (s->commits->ncommits < view->nlines - 1 &&
4229 !s->thread_args.log_complete) {
4230 s->thread_args.commits_needed += (view->nlines - 1) -
4231 s->commits->ncommits;
4232 err = trigger_log_thread(view, 1);
4234 break;
4235 case KEY_ENTER:
4236 case '\r':
4237 view->count = 0;
4238 if (s->selected_entry == NULL)
4239 break;
4240 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4241 break;
4242 case 'T':
4243 view->count = 0;
4244 if (s->selected_entry == NULL)
4245 break;
4246 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4247 break;
4248 case KEY_BACKSPACE:
4249 case CTRL('l'):
4250 case 'B':
4251 view->count = 0;
4252 if (ch == KEY_BACKSPACE &&
4253 got_path_is_root_dir(s->in_repo_path))
4254 break;
4255 err = stop_log_thread(s);
4256 if (err)
4257 return err;
4258 if (ch == KEY_BACKSPACE) {
4259 char *parent_path;
4260 err = got_path_dirname(&parent_path, s->in_repo_path);
4261 if (err)
4262 return err;
4263 free(s->in_repo_path);
4264 s->in_repo_path = parent_path;
4265 s->thread_args.in_repo_path = s->in_repo_path;
4266 } else if (ch == CTRL('l')) {
4267 struct got_object_id *start_id;
4268 err = got_repo_match_object_id(&start_id, NULL,
4269 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4270 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4271 if (err) {
4272 if (s->head_ref_name == NULL ||
4273 err->code != GOT_ERR_NOT_REF)
4274 return err;
4275 /* Try to cope with deleted references. */
4276 free(s->head_ref_name);
4277 s->head_ref_name = NULL;
4278 err = got_repo_match_object_id(&start_id,
4279 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4280 &tog_refs, s->repo);
4281 if (err)
4282 return err;
4284 free(s->start_id);
4285 s->start_id = start_id;
4286 s->thread_args.start_id = s->start_id;
4287 } else /* 'B' */
4288 s->log_branches = !s->log_branches;
4290 if (s->thread_args.pack_fds == NULL) {
4291 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4292 if (err)
4293 return err;
4295 err = got_repo_open(&s->thread_args.repo,
4296 got_repo_get_path(s->repo), NULL,
4297 s->thread_args.pack_fds);
4298 if (err)
4299 return err;
4300 tog_free_refs();
4301 err = tog_load_refs(s->repo, 0);
4302 if (err)
4303 return err;
4304 err = got_commit_graph_open(&s->thread_args.graph,
4305 s->in_repo_path, !s->log_branches);
4306 if (err)
4307 return err;
4308 err = got_commit_graph_iter_start(s->thread_args.graph,
4309 s->start_id, s->repo, NULL, NULL);
4310 if (err)
4311 return err;
4312 free_commits(&s->real_commits);
4313 free_commits(&s->limit_commits);
4314 s->first_displayed_entry = NULL;
4315 s->last_displayed_entry = NULL;
4316 s->selected_entry = NULL;
4317 s->selected = 0;
4318 s->thread_args.log_complete = 0;
4319 s->quit = 0;
4320 s->thread_args.commits_needed = view->lines;
4321 s->matched_entry = NULL;
4322 s->search_entry = NULL;
4323 view->offset = 0;
4324 break;
4325 case 'R':
4326 view->count = 0;
4327 err = view_request_new(new_view, view, TOG_VIEW_REF);
4328 break;
4329 default:
4330 view->count = 0;
4331 break;
4334 return err;
4337 static const struct got_error *
4338 apply_unveil(const char *repo_path, const char *worktree_path)
4340 const struct got_error *error;
4342 #ifdef PROFILE
4343 if (unveil("gmon.out", "rwc") != 0)
4344 return got_error_from_errno2("unveil", "gmon.out");
4345 #endif
4346 if (repo_path && unveil(repo_path, "r") != 0)
4347 return got_error_from_errno2("unveil", repo_path);
4349 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4350 return got_error_from_errno2("unveil", worktree_path);
4352 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4353 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4355 error = got_privsep_unveil_exec_helpers();
4356 if (error != NULL)
4357 return error;
4359 if (unveil(NULL, NULL) != 0)
4360 return got_error_from_errno("unveil");
4362 return NULL;
4365 static const struct got_error *
4366 init_mock_term(const char *test_script_path)
4368 const struct got_error *err = NULL;
4369 const char *screen_dump_path;
4370 int in;
4372 if (test_script_path == NULL || *test_script_path == '\0')
4373 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4375 tog_io.f = fopen(test_script_path, "re");
4376 if (tog_io.f == NULL) {
4377 err = got_error_from_errno_fmt("fopen: %s",
4378 test_script_path);
4379 goto done;
4382 /* test mode, we don't want any output */
4383 tog_io.cout = fopen("/dev/null", "w+");
4384 if (tog_io.cout == NULL) {
4385 err = got_error_from_errno2("fopen", "/dev/null");
4386 goto done;
4389 in = dup(fileno(tog_io.cout));
4390 if (in == -1) {
4391 err = got_error_from_errno("dup");
4392 goto done;
4394 tog_io.cin = fdopen(in, "r");
4395 if (tog_io.cin == NULL) {
4396 err = got_error_from_errno("fdopen");
4397 close(in);
4398 goto done;
4401 screen_dump_path = getenv("TOG_SCR_DUMP");
4402 if (screen_dump_path == NULL || *screen_dump_path == '\0')
4403 return got_error_msg(GOT_ERR_IO, "TOG_SCR_DUMP not defined");
4404 tog_io.sdump = fopen(screen_dump_path, "we");
4405 if (tog_io.sdump == NULL) {
4406 err = got_error_from_errno2("fopen", screen_dump_path);
4407 goto done;
4410 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4411 err = got_error_from_errno("fseeko");
4412 goto done;
4415 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4416 err = got_error_msg(GOT_ERR_IO,
4417 "newterm: failed to initialise curses");
4419 using_mock_io = 1;
4421 done:
4422 if (err)
4423 tog_io_close();
4424 return err;
4427 static void
4428 init_curses(void)
4430 if (using_mock_io) /* In test mode we use a fake terminal */
4431 return;
4433 initscr();
4435 cbreak();
4436 halfdelay(1); /* Fast refresh while initial view is loading. */
4437 noecho();
4438 nonl();
4439 intrflush(stdscr, FALSE);
4440 keypad(stdscr, TRUE);
4441 curs_set(0);
4442 if (getenv("TOG_COLORS") != NULL) {
4443 start_color();
4444 use_default_colors();
4447 return;
4450 static const struct got_error *
4451 set_tog_base_commit(struct got_repository *repo, struct got_worktree *worktree)
4453 tog_base_commit.id = got_object_id_dup(
4454 got_worktree_get_base_commit_id(worktree));
4455 if (tog_base_commit.id == NULL)
4456 return got_error_from_errno( "got_object_id_dup");
4458 return NULL;
4461 static const struct got_error *
4462 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4463 struct got_repository *repo, struct got_worktree *worktree)
4465 const struct got_error *err = NULL;
4467 if (argc == 0) {
4468 *in_repo_path = strdup("/");
4469 if (*in_repo_path == NULL)
4470 return got_error_from_errno("strdup");
4471 return NULL;
4474 if (worktree) {
4475 const char *prefix = got_worktree_get_path_prefix(worktree);
4476 char *p;
4478 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4479 if (err)
4480 return err;
4481 if (asprintf(in_repo_path, "%s%s%s", prefix,
4482 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4483 p) == -1) {
4484 err = got_error_from_errno("asprintf");
4485 *in_repo_path = NULL;
4487 free(p);
4488 } else
4489 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4491 return err;
4494 static const struct got_error *
4495 cmd_log(int argc, char *argv[])
4497 const struct got_error *error;
4498 struct got_repository *repo = NULL;
4499 struct got_worktree *worktree = NULL;
4500 struct got_object_id *start_id = NULL;
4501 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4502 char *keyword_idstr = NULL, *start_commit = NULL, *label = NULL;
4503 struct got_reference *ref = NULL;
4504 const char *head_ref_name = NULL;
4505 int ch, log_branches = 0;
4506 struct tog_view *view;
4507 int *pack_fds = NULL;
4509 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4510 switch (ch) {
4511 case 'b':
4512 log_branches = 1;
4513 break;
4514 case 'c':
4515 start_commit = optarg;
4516 break;
4517 case 'r':
4518 repo_path = realpath(optarg, NULL);
4519 if (repo_path == NULL)
4520 return got_error_from_errno2("realpath",
4521 optarg);
4522 break;
4523 default:
4524 usage_log();
4525 /* NOTREACHED */
4529 argc -= optind;
4530 argv += optind;
4532 if (argc > 1)
4533 usage_log();
4535 error = got_repo_pack_fds_open(&pack_fds);
4536 if (error != NULL)
4537 goto done;
4539 if (repo_path == NULL) {
4540 cwd = getcwd(NULL, 0);
4541 if (cwd == NULL) {
4542 error = got_error_from_errno("getcwd");
4543 goto done;
4545 error = got_worktree_open(&worktree, cwd, NULL);
4546 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4547 goto done;
4548 if (worktree)
4549 repo_path =
4550 strdup(got_worktree_get_repo_path(worktree));
4551 else
4552 repo_path = strdup(cwd);
4553 if (repo_path == NULL) {
4554 error = got_error_from_errno("strdup");
4555 goto done;
4559 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4560 if (error != NULL)
4561 goto done;
4563 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4564 repo, worktree);
4565 if (error)
4566 goto done;
4568 init_curses();
4570 error = apply_unveil(got_repo_get_path(repo),
4571 worktree ? got_worktree_get_root_path(worktree) : NULL);
4572 if (error)
4573 goto done;
4575 /* already loaded by tog_log_with_path()? */
4576 if (TAILQ_EMPTY(&tog_refs)) {
4577 error = tog_load_refs(repo, 0);
4578 if (error)
4579 goto done;
4582 if (start_commit == NULL) {
4583 error = got_repo_match_object_id(&start_id, &label,
4584 worktree ? got_worktree_get_head_ref_name(worktree) :
4585 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4586 if (error)
4587 goto done;
4588 head_ref_name = label;
4589 } else {
4590 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4591 repo, worktree);
4592 if (error != NULL)
4593 goto done;
4594 if (keyword_idstr != NULL)
4595 start_commit = keyword_idstr;
4597 error = got_ref_open(&ref, repo, start_commit, 0);
4598 if (error == NULL)
4599 head_ref_name = got_ref_get_name(ref);
4600 else if (error->code != GOT_ERR_NOT_REF)
4601 goto done;
4602 error = got_repo_match_object_id(&start_id, NULL,
4603 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4604 if (error)
4605 goto done;
4608 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4609 if (view == NULL) {
4610 error = got_error_from_errno("view_open");
4611 goto done;
4614 if (worktree) {
4615 error = set_tog_base_commit(repo, worktree);
4616 if (error != NULL)
4617 goto done;
4620 error = open_log_view(view, start_id, repo, head_ref_name,
4621 in_repo_path, log_branches, worktree);
4622 if (error)
4623 goto done;
4625 if (worktree) {
4626 /* The work tree will be closed by the log thread. */
4627 worktree = NULL;
4630 error = view_loop(view);
4632 done:
4633 free(tog_base_commit.id);
4634 free(keyword_idstr);
4635 free(in_repo_path);
4636 free(repo_path);
4637 free(cwd);
4638 free(start_id);
4639 free(label);
4640 if (ref)
4641 got_ref_close(ref);
4642 if (repo) {
4643 const struct got_error *close_err = got_repo_close(repo);
4644 if (error == NULL)
4645 error = close_err;
4647 if (worktree)
4648 got_worktree_close(worktree);
4649 if (pack_fds) {
4650 const struct got_error *pack_err =
4651 got_repo_pack_fds_close(pack_fds);
4652 if (error == NULL)
4653 error = pack_err;
4655 tog_free_refs();
4656 return error;
4659 __dead static void
4660 usage_diff(void)
4662 endwin();
4663 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4664 "object1 object2\n", getprogname());
4665 exit(1);
4668 static int
4669 match_line(const char *line, regex_t *regex, size_t nmatch,
4670 regmatch_t *regmatch)
4672 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4675 static struct tog_color *
4676 match_color(struct tog_colors *colors, const char *line)
4678 struct tog_color *tc = NULL;
4680 STAILQ_FOREACH(tc, colors, entry) {
4681 if (match_line(line, &tc->regex, 0, NULL))
4682 return tc;
4685 return NULL;
4688 static const struct got_error *
4689 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4690 WINDOW *window, int skipcol, regmatch_t *regmatch)
4692 const struct got_error *err = NULL;
4693 char *exstr = NULL;
4694 wchar_t *wline = NULL;
4695 int rme, rms, n, width, scrollx;
4696 int width0 = 0, width1 = 0, width2 = 0;
4697 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4699 *wtotal = 0;
4701 rms = regmatch->rm_so;
4702 rme = regmatch->rm_eo;
4704 err = expand_tab(&exstr, line);
4705 if (err)
4706 return err;
4708 /* Split the line into 3 segments, according to match offsets. */
4709 seg0 = strndup(exstr, rms);
4710 if (seg0 == NULL) {
4711 err = got_error_from_errno("strndup");
4712 goto done;
4714 seg1 = strndup(exstr + rms, rme - rms);
4715 if (seg1 == NULL) {
4716 err = got_error_from_errno("strndup");
4717 goto done;
4719 seg2 = strdup(exstr + rme);
4720 if (seg2 == NULL) {
4721 err = got_error_from_errno("strndup");
4722 goto done;
4725 /* draw up to matched token if we haven't scrolled past it */
4726 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4727 col_tab_align, 1);
4728 if (err)
4729 goto done;
4730 n = MAX(width0 - skipcol, 0);
4731 if (n) {
4732 free(wline);
4733 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4734 wlimit, col_tab_align, 1);
4735 if (err)
4736 goto done;
4737 waddwstr(window, &wline[scrollx]);
4738 wlimit -= width;
4739 *wtotal += width;
4742 if (wlimit > 0) {
4743 int i = 0, w = 0;
4744 size_t wlen;
4746 free(wline);
4747 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4748 col_tab_align, 1);
4749 if (err)
4750 goto done;
4751 wlen = wcslen(wline);
4752 while (i < wlen) {
4753 width = wcwidth(wline[i]);
4754 if (width == -1) {
4755 /* should not happen, tabs are expanded */
4756 err = got_error(GOT_ERR_RANGE);
4757 goto done;
4759 if (width0 + w + width > skipcol)
4760 break;
4761 w += width;
4762 i++;
4764 /* draw (visible part of) matched token (if scrolled into it) */
4765 if (width1 - w > 0) {
4766 wattron(window, A_STANDOUT);
4767 waddwstr(window, &wline[i]);
4768 wattroff(window, A_STANDOUT);
4769 wlimit -= (width1 - w);
4770 *wtotal += (width1 - w);
4774 if (wlimit > 0) { /* draw rest of line */
4775 free(wline);
4776 if (skipcol > width0 + width1) {
4777 err = format_line(&wline, &width2, &scrollx, seg2,
4778 skipcol - (width0 + width1), wlimit,
4779 col_tab_align, 1);
4780 if (err)
4781 goto done;
4782 waddwstr(window, &wline[scrollx]);
4783 } else {
4784 err = format_line(&wline, &width2, NULL, seg2, 0,
4785 wlimit, col_tab_align, 1);
4786 if (err)
4787 goto done;
4788 waddwstr(window, wline);
4790 *wtotal += width2;
4792 done:
4793 free(wline);
4794 free(exstr);
4795 free(seg0);
4796 free(seg1);
4797 free(seg2);
4798 return err;
4801 static int
4802 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4804 FILE *f = NULL;
4805 int *eof, *first, *selected;
4807 if (view->type == TOG_VIEW_DIFF) {
4808 struct tog_diff_view_state *s = &view->state.diff;
4810 first = &s->first_displayed_line;
4811 selected = first;
4812 eof = &s->eof;
4813 f = s->f;
4814 } else if (view->type == TOG_VIEW_HELP) {
4815 struct tog_help_view_state *s = &view->state.help;
4817 first = &s->first_displayed_line;
4818 selected = first;
4819 eof = &s->eof;
4820 f = s->f;
4821 } else if (view->type == TOG_VIEW_BLAME) {
4822 struct tog_blame_view_state *s = &view->state.blame;
4824 first = &s->first_displayed_line;
4825 selected = &s->selected_line;
4826 eof = &s->eof;
4827 f = s->blame.f;
4828 } else
4829 return 0;
4831 /* Center gline in the middle of the page like vi(1). */
4832 if (*lineno < view->gline - (view->nlines - 3) / 2)
4833 return 0;
4834 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4835 rewind(f);
4836 *eof = 0;
4837 *first = 1;
4838 *lineno = 0;
4839 *nprinted = 0;
4840 return 0;
4843 *selected = view->gline <= (view->nlines - 3) / 2 ?
4844 view->gline : (view->nlines - 3) / 2 + 1;
4845 view->gline = 0;
4847 return 1;
4850 static const struct got_error *
4851 draw_file(struct tog_view *view, const char *header)
4853 struct tog_diff_view_state *s = &view->state.diff;
4854 regmatch_t *regmatch = &view->regmatch;
4855 const struct got_error *err;
4856 int nprinted = 0;
4857 char *line;
4858 size_t linesize = 0;
4859 ssize_t linelen;
4860 wchar_t *wline;
4861 int width;
4862 int max_lines = view->nlines;
4863 int nlines = s->nlines;
4864 off_t line_offset;
4866 s->lineno = s->first_displayed_line - 1;
4867 line_offset = s->lines[s->first_displayed_line - 1].offset;
4868 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4869 return got_error_from_errno("fseek");
4871 werase(view->window);
4873 if (view->gline > s->nlines - 1)
4874 view->gline = s->nlines - 1;
4876 if (header) {
4877 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4878 1 : view->gline - (view->nlines - 3) / 2 :
4879 s->lineno + s->selected_line;
4881 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4882 return got_error_from_errno("asprintf");
4883 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4884 0, 0);
4885 free(line);
4886 if (err)
4887 return err;
4889 if (view_needs_focus_indication(view))
4890 wstandout(view->window);
4891 waddwstr(view->window, wline);
4892 free(wline);
4893 wline = NULL;
4894 while (width++ < view->ncols)
4895 waddch(view->window, ' ');
4896 if (view_needs_focus_indication(view))
4897 wstandend(view->window);
4899 if (max_lines <= 1)
4900 return NULL;
4901 max_lines--;
4904 s->eof = 0;
4905 view->maxx = 0;
4906 line = NULL;
4907 while (max_lines > 0 && nprinted < max_lines) {
4908 enum got_diff_line_type linetype;
4909 attr_t attr = 0;
4911 linelen = getline(&line, &linesize, s->f);
4912 if (linelen == -1) {
4913 if (feof(s->f)) {
4914 s->eof = 1;
4915 break;
4917 free(line);
4918 return got_ferror(s->f, GOT_ERR_IO);
4921 if (++s->lineno < s->first_displayed_line)
4922 continue;
4923 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4924 continue;
4925 if (s->lineno == view->hiline)
4926 attr = A_STANDOUT;
4928 /* Set view->maxx based on full line length. */
4929 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4930 view->x ? 1 : 0);
4931 if (err) {
4932 free(line);
4933 return err;
4935 view->maxx = MAX(view->maxx, width);
4936 free(wline);
4937 wline = NULL;
4939 linetype = s->lines[s->lineno].type;
4940 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4941 linetype < GOT_DIFF_LINE_CONTEXT)
4942 attr |= COLOR_PAIR(linetype);
4943 if (attr)
4944 wattron(view->window, attr);
4945 if (s->first_displayed_line + nprinted == s->matched_line &&
4946 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4947 err = add_matched_line(&width, line, view->ncols, 0,
4948 view->window, view->x, regmatch);
4949 if (err) {
4950 free(line);
4951 return err;
4953 } else {
4954 int skip;
4955 err = format_line(&wline, &width, &skip, line,
4956 view->x, view->ncols, 0, view->x ? 1 : 0);
4957 if (err) {
4958 free(line);
4959 return err;
4961 waddwstr(view->window, &wline[skip]);
4962 free(wline);
4963 wline = NULL;
4965 if (s->lineno == view->hiline) {
4966 /* highlight full gline length */
4967 while (width++ < view->ncols)
4968 waddch(view->window, ' ');
4969 } else {
4970 if (width <= view->ncols - 1)
4971 waddch(view->window, '\n');
4973 if (attr)
4974 wattroff(view->window, attr);
4975 if (++nprinted == 1)
4976 s->first_displayed_line = s->lineno;
4978 free(line);
4979 if (nprinted >= 1)
4980 s->last_displayed_line = s->first_displayed_line +
4981 (nprinted - 1);
4982 else
4983 s->last_displayed_line = s->first_displayed_line;
4985 view_border(view);
4987 if (s->eof) {
4988 while (nprinted < view->nlines) {
4989 waddch(view->window, '\n');
4990 nprinted++;
4993 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4994 view->ncols, 0, 0);
4995 if (err) {
4996 return err;
4999 wstandout(view->window);
5000 waddwstr(view->window, wline);
5001 free(wline);
5002 wline = NULL;
5003 wstandend(view->window);
5006 return NULL;
5009 static char *
5010 get_datestr(time_t *time, char *datebuf)
5012 struct tm mytm, *tm;
5013 char *p, *s;
5015 tm = gmtime_r(time, &mytm);
5016 if (tm == NULL)
5017 return NULL;
5018 s = asctime_r(tm, datebuf);
5019 if (s == NULL)
5020 return NULL;
5021 p = strchr(s, '\n');
5022 if (p)
5023 *p = '\0';
5024 return s;
5027 static const struct got_error *
5028 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
5029 off_t off, uint8_t type)
5031 struct got_diff_line *p;
5033 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
5034 if (p == NULL)
5035 return got_error_from_errno("reallocarray");
5036 *lines = p;
5037 (*lines)[*nlines].offset = off;
5038 (*lines)[*nlines].type = type;
5039 (*nlines)++;
5041 return NULL;
5044 static const struct got_error *
5045 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
5046 struct got_diff_line *s_lines, size_t s_nlines)
5048 struct got_diff_line *p;
5049 char buf[BUFSIZ];
5050 size_t i, r;
5052 if (fseeko(src, 0L, SEEK_SET) == -1)
5053 return got_error_from_errno("fseeko");
5055 for (;;) {
5056 r = fread(buf, 1, sizeof(buf), src);
5057 if (r == 0) {
5058 if (ferror(src))
5059 return got_error_from_errno("fread");
5060 if (feof(src))
5061 break;
5063 if (fwrite(buf, 1, r, dst) != r)
5064 return got_ferror(dst, GOT_ERR_IO);
5067 if (s_nlines == 0 && *d_nlines == 0)
5068 return NULL;
5071 * If commit info was in dst, increment line offsets
5072 * of the appended diff content, but skip s_lines[0]
5073 * because offset zero is already in *d_lines.
5075 if (*d_nlines > 0) {
5076 for (i = 1; i < s_nlines; ++i)
5077 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
5079 if (s_nlines > 0) {
5080 --s_nlines;
5081 ++s_lines;
5085 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
5086 if (p == NULL) {
5087 /* d_lines is freed in close_diff_view() */
5088 return got_error_from_errno("reallocarray");
5091 *d_lines = p;
5093 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
5094 *d_nlines += s_nlines;
5096 return NULL;
5099 static const struct got_error *
5100 write_commit_info(struct got_diff_line **lines, size_t *nlines,
5101 struct got_object_id *commit_id, struct got_reflist_head *refs,
5102 struct got_repository *repo, int ignore_ws, int force_text_diff,
5103 struct got_diffstat_cb_arg *dsa, FILE *outfile)
5105 const struct got_error *err = NULL;
5106 char datebuf[26], *datestr;
5107 struct got_commit_object *commit;
5108 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
5109 time_t committer_time;
5110 const char *author, *committer;
5111 char *refs_str = NULL;
5112 struct got_pathlist_entry *pe;
5113 off_t outoff = 0;
5114 int n;
5116 err = build_refs_str(&refs_str, refs, commit_id, repo);
5117 if (err)
5118 return err;
5120 err = got_object_open_as_commit(&commit, repo, commit_id);
5121 if (err)
5122 return err;
5124 err = got_object_id_str(&id_str, commit_id);
5125 if (err) {
5126 err = got_error_from_errno("got_object_id_str");
5127 goto done;
5130 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
5131 if (err)
5132 goto done;
5134 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
5135 refs_str ? refs_str : "", refs_str ? ")" : "");
5136 if (n < 0) {
5137 err = got_error_from_errno("fprintf");
5138 goto done;
5140 outoff += n;
5141 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
5142 if (err)
5143 goto done;
5145 n = fprintf(outfile, "from: %s\n",
5146 got_object_commit_get_author(commit));
5147 if (n < 0) {
5148 err = got_error_from_errno("fprintf");
5149 goto done;
5151 outoff += n;
5152 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
5153 if (err)
5154 goto done;
5156 author = got_object_commit_get_author(commit);
5157 committer = got_object_commit_get_committer(commit);
5158 if (strcmp(author, committer) != 0) {
5159 n = fprintf(outfile, "via: %s\n", committer);
5160 if (n < 0) {
5161 err = got_error_from_errno("fprintf");
5162 goto done;
5164 outoff += n;
5165 err = add_line_metadata(lines, nlines, outoff,
5166 GOT_DIFF_LINE_AUTHOR);
5167 if (err)
5168 goto done;
5170 committer_time = got_object_commit_get_committer_time(commit);
5171 datestr = get_datestr(&committer_time, datebuf);
5172 if (datestr) {
5173 n = fprintf(outfile, "date: %s UTC\n", datestr);
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_DATE);
5181 if (err)
5182 goto done;
5184 if (got_object_commit_get_nparents(commit) > 1) {
5185 const struct got_object_id_queue *parent_ids;
5186 struct got_object_qid *qid;
5187 int pn = 1;
5188 parent_ids = got_object_commit_get_parent_ids(commit);
5189 STAILQ_FOREACH(qid, parent_ids, entry) {
5190 err = got_object_id_str(&id_str, &qid->id);
5191 if (err)
5192 goto done;
5193 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
5194 if (n < 0) {
5195 err = got_error_from_errno("fprintf");
5196 goto done;
5198 outoff += n;
5199 err = add_line_metadata(lines, nlines, outoff,
5200 GOT_DIFF_LINE_META);
5201 if (err)
5202 goto done;
5203 free(id_str);
5204 id_str = NULL;
5208 err = got_object_commit_get_logmsg(&logmsg, commit);
5209 if (err)
5210 goto done;
5211 s = logmsg;
5212 while ((line = strsep(&s, "\n")) != NULL) {
5213 n = fprintf(outfile, "%s\n", line);
5214 if (n < 0) {
5215 err = got_error_from_errno("fprintf");
5216 goto done;
5218 outoff += n;
5219 err = add_line_metadata(lines, nlines, outoff,
5220 GOT_DIFF_LINE_LOGMSG);
5221 if (err)
5222 goto done;
5225 TAILQ_FOREACH(pe, dsa->paths, entry) {
5226 struct got_diff_changed_path *cp = pe->data;
5227 int pad = dsa->max_path_len - pe->path_len + 1;
5229 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5230 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5231 dsa->rm_cols + 1, cp->rm);
5232 if (n < 0) {
5233 err = got_error_from_errno("fprintf");
5234 goto done;
5236 outoff += n;
5237 err = add_line_metadata(lines, nlines, outoff,
5238 GOT_DIFF_LINE_CHANGES);
5239 if (err)
5240 goto done;
5243 fputc('\n', outfile);
5244 outoff++;
5245 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5246 if (err)
5247 goto done;
5249 n = fprintf(outfile,
5250 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5251 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5252 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5253 if (n < 0) {
5254 err = got_error_from_errno("fprintf");
5255 goto done;
5257 outoff += n;
5258 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5259 if (err)
5260 goto done;
5262 fputc('\n', outfile);
5263 outoff++;
5264 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5265 done:
5266 free(id_str);
5267 free(logmsg);
5268 free(refs_str);
5269 got_object_commit_close(commit);
5270 if (err) {
5271 free(*lines);
5272 *lines = NULL;
5273 *nlines = 0;
5275 return err;
5278 static const struct got_error *
5279 create_diff(struct tog_diff_view_state *s)
5281 const struct got_error *err = NULL;
5282 FILE *f = NULL, *tmp_diff_file = NULL;
5283 int obj_type;
5284 struct got_diff_line *lines = NULL;
5285 struct got_pathlist_head changed_paths;
5287 TAILQ_INIT(&changed_paths);
5289 free(s->lines);
5290 s->lines = malloc(sizeof(*s->lines));
5291 if (s->lines == NULL)
5292 return got_error_from_errno("malloc");
5293 s->nlines = 0;
5295 f = got_opentemp();
5296 if (f == NULL) {
5297 err = got_error_from_errno("got_opentemp");
5298 goto done;
5300 tmp_diff_file = got_opentemp();
5301 if (tmp_diff_file == NULL) {
5302 err = got_error_from_errno("got_opentemp");
5303 goto done;
5305 if (s->f && fclose(s->f) == EOF) {
5306 err = got_error_from_errno("fclose");
5307 goto done;
5309 s->f = f;
5311 if (s->id1)
5312 err = got_object_get_type(&obj_type, s->repo, s->id1);
5313 else
5314 err = got_object_get_type(&obj_type, s->repo, s->id2);
5315 if (err)
5316 goto done;
5318 switch (obj_type) {
5319 case GOT_OBJ_TYPE_BLOB:
5320 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5321 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5322 s->label1, s->label2, tog_diff_algo, s->diff_context,
5323 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5324 s->f);
5325 break;
5326 case GOT_OBJ_TYPE_TREE:
5327 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5328 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5329 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5330 s->force_text_diff, NULL, s->repo, s->f);
5331 break;
5332 case GOT_OBJ_TYPE_COMMIT: {
5333 const struct got_object_id_queue *parent_ids;
5334 struct got_object_qid *pid;
5335 struct got_commit_object *commit2;
5336 struct got_reflist_head *refs;
5337 size_t nlines = 0;
5338 struct got_diffstat_cb_arg dsa = {
5339 0, 0, 0, 0, 0, 0,
5340 &changed_paths,
5341 s->ignore_whitespace,
5342 s->force_text_diff,
5343 tog_diff_algo
5346 lines = malloc(sizeof(*lines));
5347 if (lines == NULL) {
5348 err = got_error_from_errno("malloc");
5349 goto done;
5352 /* build diff first in tmp file then append to commit info */
5353 err = got_diff_objects_as_commits(&lines, &nlines,
5354 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5355 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5356 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5357 if (err)
5358 break;
5360 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5361 if (err)
5362 goto done;
5363 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5364 /* Show commit info if we're diffing to a parent/root commit. */
5365 if (s->id1 == NULL) {
5366 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5367 refs, s->repo, s->ignore_whitespace,
5368 s->force_text_diff, &dsa, s->f);
5369 if (err)
5370 goto done;
5371 } else {
5372 parent_ids = got_object_commit_get_parent_ids(commit2);
5373 STAILQ_FOREACH(pid, parent_ids, entry) {
5374 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5375 err = write_commit_info(&s->lines,
5376 &s->nlines, s->id2, refs, s->repo,
5377 s->ignore_whitespace,
5378 s->force_text_diff, &dsa, s->f);
5379 if (err)
5380 goto done;
5381 break;
5385 got_object_commit_close(commit2);
5387 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5388 lines, nlines);
5389 break;
5391 default:
5392 err = got_error(GOT_ERR_OBJ_TYPE);
5393 break;
5395 done:
5396 free(lines);
5397 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5398 if (s->f && fflush(s->f) != 0 && err == NULL)
5399 err = got_error_from_errno("fflush");
5400 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5401 err = got_error_from_errno("fclose");
5402 return err;
5405 static void
5406 diff_view_indicate_progress(struct tog_view *view)
5408 mvwaddstr(view->window, 0, 0, "diffing...");
5409 update_panels();
5410 doupdate();
5413 static const struct got_error *
5414 search_start_diff_view(struct tog_view *view)
5416 struct tog_diff_view_state *s = &view->state.diff;
5418 s->matched_line = 0;
5419 return NULL;
5422 static void
5423 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5424 size_t *nlines, int **first, int **last, int **match, int **selected)
5426 struct tog_diff_view_state *s = &view->state.diff;
5428 *f = s->f;
5429 *nlines = s->nlines;
5430 *line_offsets = NULL;
5431 *match = &s->matched_line;
5432 *first = &s->first_displayed_line;
5433 *last = &s->last_displayed_line;
5434 *selected = &s->selected_line;
5437 static const struct got_error *
5438 search_next_view_match(struct tog_view *view)
5440 const struct got_error *err = NULL;
5441 FILE *f;
5442 int lineno;
5443 char *line = NULL;
5444 size_t linesize = 0;
5445 ssize_t linelen;
5446 off_t *line_offsets;
5447 size_t nlines = 0;
5448 int *first, *last, *match, *selected;
5450 if (!view->search_setup)
5451 return got_error_msg(GOT_ERR_NOT_IMPL,
5452 "view search not supported");
5453 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5454 &match, &selected);
5456 if (!view->searching) {
5457 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5458 return NULL;
5461 if (*match) {
5462 if (view->searching == TOG_SEARCH_FORWARD)
5463 lineno = *first + 1;
5464 else
5465 lineno = *first - 1;
5466 } else
5467 lineno = *first - 1 + *selected;
5469 while (1) {
5470 off_t offset;
5472 if (lineno <= 0 || lineno > nlines) {
5473 if (*match == 0) {
5474 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5475 break;
5478 if (view->searching == TOG_SEARCH_FORWARD)
5479 lineno = 1;
5480 else
5481 lineno = nlines;
5484 offset = view->type == TOG_VIEW_DIFF ?
5485 view->state.diff.lines[lineno - 1].offset :
5486 line_offsets[lineno - 1];
5487 if (fseeko(f, offset, SEEK_SET) != 0) {
5488 free(line);
5489 return got_error_from_errno("fseeko");
5491 linelen = getline(&line, &linesize, f);
5492 if (linelen != -1) {
5493 char *exstr;
5494 err = expand_tab(&exstr, line);
5495 if (err)
5496 break;
5497 if (match_line(exstr, &view->regex, 1,
5498 &view->regmatch)) {
5499 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5500 *match = lineno;
5501 free(exstr);
5502 break;
5504 free(exstr);
5506 if (view->searching == TOG_SEARCH_FORWARD)
5507 lineno++;
5508 else
5509 lineno--;
5511 free(line);
5513 if (*match) {
5514 *first = *match;
5515 *selected = 1;
5518 return err;
5521 static const struct got_error *
5522 close_diff_view(struct tog_view *view)
5524 const struct got_error *err = NULL;
5525 struct tog_diff_view_state *s = &view->state.diff;
5527 free(s->id1);
5528 s->id1 = NULL;
5529 free(s->id2);
5530 s->id2 = NULL;
5531 if (s->f && fclose(s->f) == EOF)
5532 err = got_error_from_errno("fclose");
5533 s->f = NULL;
5534 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5535 err = got_error_from_errno("fclose");
5536 s->f1 = NULL;
5537 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5538 err = got_error_from_errno("fclose");
5539 s->f2 = NULL;
5540 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5541 err = got_error_from_errno("close");
5542 s->fd1 = -1;
5543 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5544 err = got_error_from_errno("close");
5545 s->fd2 = -1;
5546 free(s->lines);
5547 s->lines = NULL;
5548 s->nlines = 0;
5549 return err;
5552 static const struct got_error *
5553 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5554 struct got_object_id *id2, const char *label1, const char *label2,
5555 int diff_context, int ignore_whitespace, int force_text_diff,
5556 struct tog_view *parent_view, struct got_repository *repo)
5558 const struct got_error *err;
5559 struct tog_diff_view_state *s = &view->state.diff;
5561 memset(s, 0, sizeof(*s));
5562 s->fd1 = -1;
5563 s->fd2 = -1;
5565 if (id1 != NULL && id2 != NULL) {
5566 int type1, type2;
5568 err = got_object_get_type(&type1, repo, id1);
5569 if (err)
5570 goto done;
5571 err = got_object_get_type(&type2, repo, id2);
5572 if (err)
5573 goto done;
5575 if (type1 != type2) {
5576 err = got_error(GOT_ERR_OBJ_TYPE);
5577 goto done;
5580 s->first_displayed_line = 1;
5581 s->last_displayed_line = view->nlines;
5582 s->selected_line = 1;
5583 s->repo = repo;
5584 s->id1 = id1;
5585 s->id2 = id2;
5586 s->label1 = label1;
5587 s->label2 = label2;
5589 if (id1) {
5590 s->id1 = got_object_id_dup(id1);
5591 if (s->id1 == NULL) {
5592 err = got_error_from_errno("got_object_id_dup");
5593 goto done;
5595 } else
5596 s->id1 = NULL;
5598 s->id2 = got_object_id_dup(id2);
5599 if (s->id2 == NULL) {
5600 err = got_error_from_errno("got_object_id_dup");
5601 goto done;
5604 s->f1 = got_opentemp();
5605 if (s->f1 == NULL) {
5606 err = got_error_from_errno("got_opentemp");
5607 goto done;
5610 s->f2 = got_opentemp();
5611 if (s->f2 == NULL) {
5612 err = got_error_from_errno("got_opentemp");
5613 goto done;
5616 s->fd1 = got_opentempfd();
5617 if (s->fd1 == -1) {
5618 err = got_error_from_errno("got_opentempfd");
5619 goto done;
5622 s->fd2 = got_opentempfd();
5623 if (s->fd2 == -1) {
5624 err = got_error_from_errno("got_opentempfd");
5625 goto done;
5628 s->diff_context = diff_context;
5629 s->ignore_whitespace = ignore_whitespace;
5630 s->force_text_diff = force_text_diff;
5631 s->parent_view = parent_view;
5632 s->repo = repo;
5634 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5635 int rc;
5637 rc = init_pair(GOT_DIFF_LINE_MINUS,
5638 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5639 if (rc != ERR)
5640 rc = init_pair(GOT_DIFF_LINE_PLUS,
5641 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5642 if (rc != ERR)
5643 rc = init_pair(GOT_DIFF_LINE_HUNK,
5644 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5645 if (rc != ERR)
5646 rc = init_pair(GOT_DIFF_LINE_META,
5647 get_color_value("TOG_COLOR_DIFF_META"), -1);
5648 if (rc != ERR)
5649 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5650 get_color_value("TOG_COLOR_DIFF_META"), -1);
5651 if (rc != ERR)
5652 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5653 get_color_value("TOG_COLOR_DIFF_META"), -1);
5654 if (rc != ERR)
5655 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5656 get_color_value("TOG_COLOR_DIFF_META"), -1);
5657 if (rc != ERR)
5658 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5659 get_color_value("TOG_COLOR_AUTHOR"), -1);
5660 if (rc != ERR)
5661 rc = init_pair(GOT_DIFF_LINE_DATE,
5662 get_color_value("TOG_COLOR_DATE"), -1);
5663 if (rc == ERR) {
5664 err = got_error(GOT_ERR_RANGE);
5665 goto done;
5669 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5670 view_is_splitscreen(view))
5671 show_log_view(parent_view); /* draw border */
5672 diff_view_indicate_progress(view);
5674 err = create_diff(s);
5676 view->show = show_diff_view;
5677 view->input = input_diff_view;
5678 view->reset = reset_diff_view;
5679 view->close = close_diff_view;
5680 view->search_start = search_start_diff_view;
5681 view->search_setup = search_setup_diff_view;
5682 view->search_next = search_next_view_match;
5683 done:
5684 if (err) {
5685 if (view->close == NULL)
5686 close_diff_view(view);
5687 view_close(view);
5689 return err;
5692 static const struct got_error *
5693 show_diff_view(struct tog_view *view)
5695 const struct got_error *err;
5696 struct tog_diff_view_state *s = &view->state.diff;
5697 char *id_str1 = NULL, *id_str2, *header;
5698 const char *label1, *label2;
5700 if (s->id1) {
5701 err = got_object_id_str(&id_str1, s->id1);
5702 if (err)
5703 return err;
5704 label1 = s->label1 ? s->label1 : id_str1;
5705 } else
5706 label1 = "/dev/null";
5708 err = got_object_id_str(&id_str2, s->id2);
5709 if (err)
5710 return err;
5711 label2 = s->label2 ? s->label2 : id_str2;
5713 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5714 err = got_error_from_errno("asprintf");
5715 free(id_str1);
5716 free(id_str2);
5717 return err;
5719 free(id_str1);
5720 free(id_str2);
5722 err = draw_file(view, header);
5723 free(header);
5724 return err;
5727 static const struct got_error *
5728 set_selected_commit(struct tog_diff_view_state *s,
5729 struct commit_queue_entry *entry)
5731 const struct got_error *err;
5732 const struct got_object_id_queue *parent_ids;
5733 struct got_commit_object *selected_commit;
5734 struct got_object_qid *pid;
5736 free(s->id2);
5737 s->id2 = got_object_id_dup(entry->id);
5738 if (s->id2 == NULL)
5739 return got_error_from_errno("got_object_id_dup");
5741 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5742 if (err)
5743 return err;
5744 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5745 free(s->id1);
5746 pid = STAILQ_FIRST(parent_ids);
5747 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5748 got_object_commit_close(selected_commit);
5749 return NULL;
5752 static const struct got_error *
5753 reset_diff_view(struct tog_view *view)
5755 struct tog_diff_view_state *s = &view->state.diff;
5757 view->count = 0;
5758 wclear(view->window);
5759 s->first_displayed_line = 1;
5760 s->last_displayed_line = view->nlines;
5761 s->matched_line = 0;
5762 diff_view_indicate_progress(view);
5763 return create_diff(s);
5766 static void
5767 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5769 int start, i;
5771 i = start = s->first_displayed_line - 1;
5773 while (s->lines[i].type != type) {
5774 if (i == 0)
5775 i = s->nlines - 1;
5776 if (--i == start)
5777 return; /* do nothing, requested type not in file */
5780 s->selected_line = 1;
5781 s->first_displayed_line = i;
5784 static void
5785 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5787 int start, i;
5789 i = start = s->first_displayed_line + 1;
5791 while (s->lines[i].type != type) {
5792 if (i == s->nlines - 1)
5793 i = 0;
5794 if (++i == start)
5795 return; /* do nothing, requested type not in file */
5798 s->selected_line = 1;
5799 s->first_displayed_line = i;
5802 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5803 int, int, int);
5804 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5805 int, int);
5807 static const struct got_error *
5808 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5810 const struct got_error *err = NULL;
5811 struct tog_diff_view_state *s = &view->state.diff;
5812 struct tog_log_view_state *ls;
5813 struct commit_queue_entry *old_selected_entry;
5814 char *line = NULL;
5815 size_t linesize = 0;
5816 ssize_t linelen;
5817 int i, nscroll = view->nlines - 1, up = 0;
5819 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5821 switch (ch) {
5822 case '0':
5823 case '$':
5824 case KEY_RIGHT:
5825 case 'l':
5826 case KEY_LEFT:
5827 case 'h':
5828 horizontal_scroll_input(view, ch);
5829 break;
5830 case 'a':
5831 case 'w':
5832 if (ch == 'a') {
5833 s->force_text_diff = !s->force_text_diff;
5834 view->action = s->force_text_diff ?
5835 "force ASCII text enabled" :
5836 "force ASCII text disabled";
5838 else if (ch == 'w') {
5839 s->ignore_whitespace = !s->ignore_whitespace;
5840 view->action = s->ignore_whitespace ?
5841 "ignore whitespace enabled" :
5842 "ignore whitespace disabled";
5844 err = reset_diff_view(view);
5845 break;
5846 case 'g':
5847 case KEY_HOME:
5848 s->first_displayed_line = 1;
5849 view->count = 0;
5850 break;
5851 case 'G':
5852 case KEY_END:
5853 view->count = 0;
5854 if (s->eof)
5855 break;
5857 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5858 s->eof = 1;
5859 break;
5860 case 'k':
5861 case KEY_UP:
5862 case CTRL('p'):
5863 if (s->first_displayed_line > 1)
5864 s->first_displayed_line--;
5865 else
5866 view->count = 0;
5867 break;
5868 case CTRL('u'):
5869 case 'u':
5870 nscroll /= 2;
5871 /* FALL THROUGH */
5872 case KEY_PPAGE:
5873 case CTRL('b'):
5874 case 'b':
5875 if (s->first_displayed_line == 1) {
5876 view->count = 0;
5877 break;
5879 i = 0;
5880 while (i++ < nscroll && s->first_displayed_line > 1)
5881 s->first_displayed_line--;
5882 break;
5883 case 'j':
5884 case KEY_DOWN:
5885 case CTRL('n'):
5886 if (!s->eof)
5887 s->first_displayed_line++;
5888 else
5889 view->count = 0;
5890 break;
5891 case CTRL('d'):
5892 case 'd':
5893 nscroll /= 2;
5894 /* FALL THROUGH */
5895 case KEY_NPAGE:
5896 case CTRL('f'):
5897 case 'f':
5898 case ' ':
5899 if (s->eof) {
5900 view->count = 0;
5901 break;
5903 i = 0;
5904 while (!s->eof && i++ < nscroll) {
5905 linelen = getline(&line, &linesize, s->f);
5906 s->first_displayed_line++;
5907 if (linelen == -1) {
5908 if (feof(s->f)) {
5909 s->eof = 1;
5910 } else
5911 err = got_ferror(s->f, GOT_ERR_IO);
5912 break;
5915 free(line);
5916 break;
5917 case '(':
5918 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5919 break;
5920 case ')':
5921 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5922 break;
5923 case '{':
5924 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5925 break;
5926 case '}':
5927 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5928 break;
5929 case '[':
5930 if (s->diff_context > 0) {
5931 s->diff_context--;
5932 s->matched_line = 0;
5933 diff_view_indicate_progress(view);
5934 err = create_diff(s);
5935 if (s->first_displayed_line + view->nlines - 1 >
5936 s->nlines) {
5937 s->first_displayed_line = 1;
5938 s->last_displayed_line = view->nlines;
5940 } else
5941 view->count = 0;
5942 break;
5943 case ']':
5944 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5945 s->diff_context++;
5946 s->matched_line = 0;
5947 diff_view_indicate_progress(view);
5948 err = create_diff(s);
5949 } else
5950 view->count = 0;
5951 break;
5952 case '<':
5953 case ',':
5954 case 'K':
5955 up = 1;
5956 /* FALL THROUGH */
5957 case '>':
5958 case '.':
5959 case 'J':
5960 if (s->parent_view == NULL) {
5961 view->count = 0;
5962 break;
5964 s->parent_view->count = view->count;
5966 if (s->parent_view->type == TOG_VIEW_LOG) {
5967 ls = &s->parent_view->state.log;
5968 old_selected_entry = ls->selected_entry;
5970 err = input_log_view(NULL, s->parent_view,
5971 up ? KEY_UP : KEY_DOWN);
5972 if (err)
5973 break;
5974 view->count = s->parent_view->count;
5976 if (old_selected_entry == ls->selected_entry)
5977 break;
5979 err = set_selected_commit(s, ls->selected_entry);
5980 if (err)
5981 break;
5982 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5983 struct tog_blame_view_state *bs;
5984 struct got_object_id *id, *prev_id;
5986 bs = &s->parent_view->state.blame;
5987 prev_id = get_annotation_for_line(bs->blame.lines,
5988 bs->blame.nlines, bs->last_diffed_line);
5990 err = input_blame_view(&view, s->parent_view,
5991 up ? KEY_UP : KEY_DOWN);
5992 if (err)
5993 break;
5994 view->count = s->parent_view->count;
5996 if (prev_id == NULL)
5997 break;
5998 id = get_selected_commit_id(bs->blame.lines,
5999 bs->blame.nlines, bs->first_displayed_line,
6000 bs->selected_line);
6001 if (id == NULL)
6002 break;
6004 if (!got_object_id_cmp(prev_id, id))
6005 break;
6007 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
6008 if (err)
6009 break;
6011 s->first_displayed_line = 1;
6012 s->last_displayed_line = view->nlines;
6013 s->matched_line = 0;
6014 view->x = 0;
6016 diff_view_indicate_progress(view);
6017 err = create_diff(s);
6018 break;
6019 default:
6020 view->count = 0;
6021 break;
6024 return err;
6027 static const struct got_error *
6028 cmd_diff(int argc, char *argv[])
6030 const struct got_error *error;
6031 struct got_repository *repo = NULL;
6032 struct got_worktree *worktree = NULL;
6033 struct got_object_id *id1 = NULL, *id2 = NULL;
6034 char *repo_path = NULL, *cwd = NULL;
6035 char *id_str1 = NULL, *id_str2 = NULL;
6036 char *keyword_idstr1 = NULL, *keyword_idstr2 = NULL;
6037 char *label1 = NULL, *label2 = NULL;
6038 int diff_context = 3, ignore_whitespace = 0;
6039 int ch, force_text_diff = 0;
6040 const char *errstr;
6041 struct tog_view *view;
6042 int *pack_fds = NULL;
6044 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
6045 switch (ch) {
6046 case 'a':
6047 force_text_diff = 1;
6048 break;
6049 case 'C':
6050 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
6051 &errstr);
6052 if (errstr != NULL)
6053 errx(1, "number of context lines is %s: %s",
6054 errstr, errstr);
6055 break;
6056 case 'r':
6057 repo_path = realpath(optarg, NULL);
6058 if (repo_path == NULL)
6059 return got_error_from_errno2("realpath",
6060 optarg);
6061 got_path_strip_trailing_slashes(repo_path);
6062 break;
6063 case 'w':
6064 ignore_whitespace = 1;
6065 break;
6066 default:
6067 usage_diff();
6068 /* NOTREACHED */
6072 argc -= optind;
6073 argv += optind;
6075 if (argc == 0) {
6076 usage_diff(); /* TODO show local worktree changes */
6077 } else if (argc == 2) {
6078 id_str1 = argv[0];
6079 id_str2 = argv[1];
6080 } else
6081 usage_diff();
6083 error = got_repo_pack_fds_open(&pack_fds);
6084 if (error)
6085 goto done;
6087 if (repo_path == NULL) {
6088 cwd = getcwd(NULL, 0);
6089 if (cwd == NULL)
6090 return got_error_from_errno("getcwd");
6091 error = got_worktree_open(&worktree, cwd, NULL);
6092 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6093 goto done;
6094 if (worktree)
6095 repo_path =
6096 strdup(got_worktree_get_repo_path(worktree));
6097 else
6098 repo_path = strdup(cwd);
6099 if (repo_path == NULL) {
6100 error = got_error_from_errno("strdup");
6101 goto done;
6105 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6106 if (error)
6107 goto done;
6109 init_curses();
6111 error = apply_unveil(got_repo_get_path(repo), NULL);
6112 if (error)
6113 goto done;
6115 error = tog_load_refs(repo, 0);
6116 if (error)
6117 goto done;
6119 if (id_str1 != NULL) {
6120 error = got_keyword_to_idstr(&keyword_idstr1, id_str1,
6121 repo, worktree);
6122 if (error != NULL)
6123 goto done;
6124 if (keyword_idstr1 != NULL)
6125 id_str1 = keyword_idstr1;
6127 if (id_str2 != NULL) {
6128 error = got_keyword_to_idstr(&keyword_idstr2, id_str2,
6129 repo, worktree);
6130 if (error != NULL)
6131 goto done;
6132 if (keyword_idstr2 != NULL)
6133 id_str2 = keyword_idstr2;
6136 error = got_repo_match_object_id(&id1, &label1, id_str1,
6137 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6138 if (error)
6139 goto done;
6141 error = got_repo_match_object_id(&id2, &label2, id_str2,
6142 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6143 if (error)
6144 goto done;
6146 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
6147 if (view == NULL) {
6148 error = got_error_from_errno("view_open");
6149 goto done;
6151 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
6152 ignore_whitespace, force_text_diff, NULL, repo);
6153 if (error)
6154 goto done;
6156 if (worktree) {
6157 error = set_tog_base_commit(repo, worktree);
6158 if (error != NULL)
6159 goto done;
6162 error = view_loop(view);
6164 done:
6165 free(tog_base_commit.id);
6166 free(keyword_idstr1);
6167 free(keyword_idstr2);
6168 free(label1);
6169 free(label2);
6170 free(repo_path);
6171 free(cwd);
6172 if (repo) {
6173 const struct got_error *close_err = got_repo_close(repo);
6174 if (error == NULL)
6175 error = close_err;
6177 if (worktree)
6178 got_worktree_close(worktree);
6179 if (pack_fds) {
6180 const struct got_error *pack_err =
6181 got_repo_pack_fds_close(pack_fds);
6182 if (error == NULL)
6183 error = pack_err;
6185 tog_free_refs();
6186 return error;
6189 __dead static void
6190 usage_blame(void)
6192 endwin();
6193 fprintf(stderr,
6194 "usage: %s blame [-c commit] [-r repository-path] path\n",
6195 getprogname());
6196 exit(1);
6199 struct tog_blame_line {
6200 int annotated;
6201 struct got_object_id *id;
6204 static const struct got_error *
6205 draw_blame(struct tog_view *view)
6207 struct tog_blame_view_state *s = &view->state.blame;
6208 struct tog_blame *blame = &s->blame;
6209 regmatch_t *regmatch = &view->regmatch;
6210 const struct got_error *err;
6211 int lineno = 0, nprinted = 0;
6212 char *line = NULL;
6213 size_t linesize = 0;
6214 ssize_t linelen;
6215 wchar_t *wline;
6216 int width;
6217 struct tog_blame_line *blame_line;
6218 struct got_object_id *prev_id = NULL;
6219 char *id_str;
6220 struct tog_color *tc;
6222 err = got_object_id_str(&id_str, &s->blamed_commit->id);
6223 if (err)
6224 return err;
6226 rewind(blame->f);
6227 werase(view->window);
6229 if (asprintf(&line, "commit %s", id_str) == -1) {
6230 err = got_error_from_errno("asprintf");
6231 free(id_str);
6232 return err;
6235 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6236 free(line);
6237 line = NULL;
6238 if (err)
6239 return err;
6240 if (view_needs_focus_indication(view))
6241 wstandout(view->window);
6242 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6243 if (tc)
6244 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6245 waddwstr(view->window, wline);
6246 while (width++ < view->ncols)
6247 waddch(view->window, ' ');
6248 if (tc)
6249 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6250 if (view_needs_focus_indication(view))
6251 wstandend(view->window);
6252 free(wline);
6253 wline = NULL;
6255 if (view->gline > blame->nlines)
6256 view->gline = blame->nlines;
6258 if (tog_io.wait_for_ui) {
6259 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6260 int rc;
6262 rc = pthread_cond_wait(&bta->blame_complete, &tog_mutex);
6263 if (rc)
6264 return got_error_set_errno(rc, "pthread_cond_wait");
6265 tog_io.wait_for_ui = 0;
6268 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6269 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6270 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6271 free(id_str);
6272 return got_error_from_errno("asprintf");
6274 free(id_str);
6275 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6276 free(line);
6277 line = NULL;
6278 if (err)
6279 return err;
6280 waddwstr(view->window, wline);
6281 free(wline);
6282 wline = NULL;
6283 if (width < view->ncols - 1)
6284 waddch(view->window, '\n');
6286 s->eof = 0;
6287 view->maxx = 0;
6288 while (nprinted < view->nlines - 2) {
6289 linelen = getline(&line, &linesize, blame->f);
6290 if (linelen == -1) {
6291 if (feof(blame->f)) {
6292 s->eof = 1;
6293 break;
6295 free(line);
6296 return got_ferror(blame->f, GOT_ERR_IO);
6298 if (++lineno < s->first_displayed_line)
6299 continue;
6300 if (view->gline && !gotoline(view, &lineno, &nprinted))
6301 continue;
6303 /* Set view->maxx based on full line length. */
6304 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6305 if (err) {
6306 free(line);
6307 return err;
6309 free(wline);
6310 wline = NULL;
6311 view->maxx = MAX(view->maxx, width);
6313 if (nprinted == s->selected_line - 1)
6314 wstandout(view->window);
6316 if (blame->nlines > 0) {
6317 blame_line = &blame->lines[lineno - 1];
6318 if (blame_line->annotated && prev_id &&
6319 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6320 !(nprinted == s->selected_line - 1)) {
6321 waddstr(view->window, " ");
6322 } else if (blame_line->annotated) {
6323 char *id_str;
6324 err = got_object_id_str(&id_str,
6325 blame_line->id);
6326 if (err) {
6327 free(line);
6328 return err;
6330 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6331 if (tc)
6332 wattr_on(view->window,
6333 COLOR_PAIR(tc->colorpair), NULL);
6334 wprintw(view->window, "%.8s", id_str);
6335 if (tc)
6336 wattr_off(view->window,
6337 COLOR_PAIR(tc->colorpair), NULL);
6338 free(id_str);
6339 prev_id = blame_line->id;
6340 } else {
6341 waddstr(view->window, "........");
6342 prev_id = NULL;
6344 } else {
6345 waddstr(view->window, "........");
6346 prev_id = NULL;
6349 if (nprinted == s->selected_line - 1)
6350 wstandend(view->window);
6351 waddstr(view->window, " ");
6353 if (view->ncols <= 9) {
6354 width = 9;
6355 } else if (s->first_displayed_line + nprinted ==
6356 s->matched_line &&
6357 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6358 err = add_matched_line(&width, line, view->ncols - 9, 9,
6359 view->window, view->x, regmatch);
6360 if (err) {
6361 free(line);
6362 return err;
6364 width += 9;
6365 } else {
6366 int skip;
6367 err = format_line(&wline, &width, &skip, line,
6368 view->x, view->ncols - 9, 9, 1);
6369 if (err) {
6370 free(line);
6371 return err;
6373 waddwstr(view->window, &wline[skip]);
6374 width += 9;
6375 free(wline);
6376 wline = NULL;
6379 if (width <= view->ncols - 1)
6380 waddch(view->window, '\n');
6381 if (++nprinted == 1)
6382 s->first_displayed_line = lineno;
6384 free(line);
6385 s->last_displayed_line = lineno;
6387 view_border(view);
6389 return NULL;
6392 static const struct got_error *
6393 blame_cb(void *arg, int nlines, int lineno,
6394 struct got_commit_object *commit, struct got_object_id *id)
6396 const struct got_error *err = NULL;
6397 struct tog_blame_cb_args *a = arg;
6398 struct tog_blame_line *line;
6399 int errcode;
6401 if (nlines != a->nlines ||
6402 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6403 return got_error(GOT_ERR_RANGE);
6405 errcode = pthread_mutex_lock(&tog_mutex);
6406 if (errcode)
6407 return got_error_set_errno(errcode, "pthread_mutex_lock");
6409 if (*a->quit) { /* user has quit the blame view */
6410 err = got_error(GOT_ERR_ITER_COMPLETED);
6411 goto done;
6414 if (lineno == -1)
6415 goto done; /* no change in this commit */
6417 line = &a->lines[lineno - 1];
6418 if (line->annotated)
6419 goto done;
6421 line->id = got_object_id_dup(id);
6422 if (line->id == NULL) {
6423 err = got_error_from_errno("got_object_id_dup");
6424 goto done;
6426 line->annotated = 1;
6427 done:
6428 errcode = pthread_mutex_unlock(&tog_mutex);
6429 if (errcode)
6430 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6431 return err;
6434 static void *
6435 blame_thread(void *arg)
6437 const struct got_error *err, *close_err;
6438 struct tog_blame_thread_args *ta = arg;
6439 struct tog_blame_cb_args *a = ta->cb_args;
6440 int errcode, fd1 = -1, fd2 = -1;
6441 FILE *f1 = NULL, *f2 = NULL;
6443 fd1 = got_opentempfd();
6444 if (fd1 == -1)
6445 return (void *)got_error_from_errno("got_opentempfd");
6447 fd2 = got_opentempfd();
6448 if (fd2 == -1) {
6449 err = got_error_from_errno("got_opentempfd");
6450 goto done;
6453 f1 = got_opentemp();
6454 if (f1 == NULL) {
6455 err = (void *)got_error_from_errno("got_opentemp");
6456 goto done;
6458 f2 = got_opentemp();
6459 if (f2 == NULL) {
6460 err = (void *)got_error_from_errno("got_opentemp");
6461 goto done;
6464 err = block_signals_used_by_main_thread();
6465 if (err)
6466 goto done;
6468 err = got_blame(ta->path, a->commit_id, ta->repo,
6469 tog_diff_algo, blame_cb, ta->cb_args,
6470 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6471 if (err && err->code == GOT_ERR_CANCELLED)
6472 err = NULL;
6474 errcode = pthread_mutex_lock(&tog_mutex);
6475 if (errcode) {
6476 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6477 goto done;
6480 close_err = got_repo_close(ta->repo);
6481 if (err == NULL)
6482 err = close_err;
6483 ta->repo = NULL;
6484 *ta->complete = 1;
6486 if (tog_io.wait_for_ui) {
6487 errcode = pthread_cond_signal(&ta->blame_complete);
6488 if (errcode && err == NULL)
6489 err = got_error_set_errno(errcode,
6490 "pthread_cond_signal");
6493 errcode = pthread_mutex_unlock(&tog_mutex);
6494 if (errcode && err == NULL)
6495 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6497 done:
6498 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6499 err = got_error_from_errno("close");
6500 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6501 err = got_error_from_errno("close");
6502 if (f1 && fclose(f1) == EOF && err == NULL)
6503 err = got_error_from_errno("fclose");
6504 if (f2 && fclose(f2) == EOF && err == NULL)
6505 err = got_error_from_errno("fclose");
6507 return (void *)err;
6510 static struct got_object_id *
6511 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6512 int first_displayed_line, int selected_line)
6514 struct tog_blame_line *line;
6516 if (nlines <= 0)
6517 return NULL;
6519 line = &lines[first_displayed_line - 1 + selected_line - 1];
6520 if (!line->annotated)
6521 return NULL;
6523 return line->id;
6526 static struct got_object_id *
6527 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6528 int lineno)
6530 struct tog_blame_line *line;
6532 if (nlines <= 0 || lineno >= nlines)
6533 return NULL;
6535 line = &lines[lineno - 1];
6536 if (!line->annotated)
6537 return NULL;
6539 return line->id;
6542 static const struct got_error *
6543 stop_blame(struct tog_blame *blame)
6545 const struct got_error *err = NULL;
6546 int i;
6548 if (blame->thread) {
6549 int errcode;
6550 errcode = pthread_mutex_unlock(&tog_mutex);
6551 if (errcode)
6552 return got_error_set_errno(errcode,
6553 "pthread_mutex_unlock");
6554 errcode = pthread_join(blame->thread, (void **)&err);
6555 if (errcode)
6556 return got_error_set_errno(errcode, "pthread_join");
6557 errcode = pthread_mutex_lock(&tog_mutex);
6558 if (errcode)
6559 return got_error_set_errno(errcode,
6560 "pthread_mutex_lock");
6561 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6562 err = NULL;
6563 blame->thread = NULL;
6565 if (blame->thread_args.repo) {
6566 const struct got_error *close_err;
6567 close_err = got_repo_close(blame->thread_args.repo);
6568 if (err == NULL)
6569 err = close_err;
6570 blame->thread_args.repo = NULL;
6572 if (blame->f) {
6573 if (fclose(blame->f) == EOF && err == NULL)
6574 err = got_error_from_errno("fclose");
6575 blame->f = NULL;
6577 if (blame->lines) {
6578 for (i = 0; i < blame->nlines; i++)
6579 free(blame->lines[i].id);
6580 free(blame->lines);
6581 blame->lines = NULL;
6583 free(blame->cb_args.commit_id);
6584 blame->cb_args.commit_id = NULL;
6585 if (blame->pack_fds) {
6586 const struct got_error *pack_err =
6587 got_repo_pack_fds_close(blame->pack_fds);
6588 if (err == NULL)
6589 err = pack_err;
6590 blame->pack_fds = NULL;
6592 return err;
6595 static const struct got_error *
6596 cancel_blame_view(void *arg)
6598 const struct got_error *err = NULL;
6599 int *done = arg;
6600 int errcode;
6602 errcode = pthread_mutex_lock(&tog_mutex);
6603 if (errcode)
6604 return got_error_set_errno(errcode,
6605 "pthread_mutex_unlock");
6607 if (*done)
6608 err = got_error(GOT_ERR_CANCELLED);
6610 errcode = pthread_mutex_unlock(&tog_mutex);
6611 if (errcode)
6612 return got_error_set_errno(errcode,
6613 "pthread_mutex_lock");
6615 return err;
6618 static const struct got_error *
6619 run_blame(struct tog_view *view)
6621 struct tog_blame_view_state *s = &view->state.blame;
6622 struct tog_blame *blame = &s->blame;
6623 const struct got_error *err = NULL;
6624 struct got_commit_object *commit = NULL;
6625 struct got_blob_object *blob = NULL;
6626 struct got_repository *thread_repo = NULL;
6627 struct got_object_id *obj_id = NULL;
6628 int obj_type, fd = -1;
6629 int *pack_fds = NULL;
6631 err = got_object_open_as_commit(&commit, s->repo,
6632 &s->blamed_commit->id);
6633 if (err)
6634 return err;
6636 fd = got_opentempfd();
6637 if (fd == -1) {
6638 err = got_error_from_errno("got_opentempfd");
6639 goto done;
6642 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6643 if (err)
6644 goto done;
6646 err = got_object_get_type(&obj_type, s->repo, obj_id);
6647 if (err)
6648 goto done;
6650 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6651 err = got_error(GOT_ERR_OBJ_TYPE);
6652 goto done;
6655 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6656 if (err)
6657 goto done;
6658 blame->f = got_opentemp();
6659 if (blame->f == NULL) {
6660 err = got_error_from_errno("got_opentemp");
6661 goto done;
6663 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6664 &blame->line_offsets, blame->f, blob);
6665 if (err)
6666 goto done;
6667 if (blame->nlines == 0) {
6668 s->blame_complete = 1;
6669 goto done;
6672 /* Don't include \n at EOF in the blame line count. */
6673 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6674 blame->nlines--;
6676 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6677 if (blame->lines == NULL) {
6678 err = got_error_from_errno("calloc");
6679 goto done;
6682 err = got_repo_pack_fds_open(&pack_fds);
6683 if (err)
6684 goto done;
6685 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6686 pack_fds);
6687 if (err)
6688 goto done;
6690 blame->pack_fds = pack_fds;
6691 blame->cb_args.view = view;
6692 blame->cb_args.lines = blame->lines;
6693 blame->cb_args.nlines = blame->nlines;
6694 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6695 if (blame->cb_args.commit_id == NULL) {
6696 err = got_error_from_errno("got_object_id_dup");
6697 goto done;
6699 blame->cb_args.quit = &s->done;
6701 blame->thread_args.path = s->path;
6702 blame->thread_args.repo = thread_repo;
6703 blame->thread_args.cb_args = &blame->cb_args;
6704 blame->thread_args.complete = &s->blame_complete;
6705 blame->thread_args.cancel_cb = cancel_blame_view;
6706 blame->thread_args.cancel_arg = &s->done;
6707 s->blame_complete = 0;
6709 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6710 s->first_displayed_line = 1;
6711 s->last_displayed_line = view->nlines;
6712 s->selected_line = 1;
6714 s->matched_line = 0;
6716 done:
6717 if (commit)
6718 got_object_commit_close(commit);
6719 if (fd != -1 && close(fd) == -1 && err == NULL)
6720 err = got_error_from_errno("close");
6721 if (blob)
6722 got_object_blob_close(blob);
6723 free(obj_id);
6724 if (err)
6725 stop_blame(blame);
6726 return err;
6729 static const struct got_error *
6730 open_blame_view(struct tog_view *view, char *path,
6731 struct got_object_id *commit_id, struct got_repository *repo)
6733 const struct got_error *err = NULL;
6734 struct tog_blame_view_state *s = &view->state.blame;
6736 STAILQ_INIT(&s->blamed_commits);
6738 s->path = strdup(path);
6739 if (s->path == NULL)
6740 return got_error_from_errno("strdup");
6742 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6743 if (err) {
6744 free(s->path);
6745 return err;
6748 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6749 s->first_displayed_line = 1;
6750 s->last_displayed_line = view->nlines;
6751 s->selected_line = 1;
6752 s->blame_complete = 0;
6753 s->repo = repo;
6754 s->commit_id = commit_id;
6755 memset(&s->blame, 0, sizeof(s->blame));
6757 STAILQ_INIT(&s->colors);
6758 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6759 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6760 get_color_value("TOG_COLOR_COMMIT"));
6761 if (err)
6762 return err;
6765 view->show = show_blame_view;
6766 view->input = input_blame_view;
6767 view->reset = reset_blame_view;
6768 view->close = close_blame_view;
6769 view->search_start = search_start_blame_view;
6770 view->search_setup = search_setup_blame_view;
6771 view->search_next = search_next_view_match;
6773 if (using_mock_io) {
6774 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6775 int rc;
6777 rc = pthread_cond_init(&bta->blame_complete, NULL);
6778 if (rc)
6779 return got_error_set_errno(rc, "pthread_cond_init");
6782 return run_blame(view);
6785 static const struct got_error *
6786 close_blame_view(struct tog_view *view)
6788 const struct got_error *err = NULL;
6789 struct tog_blame_view_state *s = &view->state.blame;
6791 if (s->blame.thread)
6792 err = stop_blame(&s->blame);
6794 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6795 struct got_object_qid *blamed_commit;
6796 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6797 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6798 got_object_qid_free(blamed_commit);
6801 if (using_mock_io) {
6802 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6803 int rc;
6805 rc = pthread_cond_destroy(&bta->blame_complete);
6806 if (rc && err == NULL)
6807 err = got_error_set_errno(rc, "pthread_cond_destroy");
6810 free(s->path);
6811 free_colors(&s->colors);
6812 return err;
6815 static const struct got_error *
6816 search_start_blame_view(struct tog_view *view)
6818 struct tog_blame_view_state *s = &view->state.blame;
6820 s->matched_line = 0;
6821 return NULL;
6824 static void
6825 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6826 size_t *nlines, int **first, int **last, int **match, int **selected)
6828 struct tog_blame_view_state *s = &view->state.blame;
6830 *f = s->blame.f;
6831 *nlines = s->blame.nlines;
6832 *line_offsets = s->blame.line_offsets;
6833 *match = &s->matched_line;
6834 *first = &s->first_displayed_line;
6835 *last = &s->last_displayed_line;
6836 *selected = &s->selected_line;
6839 static const struct got_error *
6840 show_blame_view(struct tog_view *view)
6842 const struct got_error *err = NULL;
6843 struct tog_blame_view_state *s = &view->state.blame;
6844 int errcode;
6846 if (s->blame.thread == NULL && !s->blame_complete) {
6847 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6848 &s->blame.thread_args);
6849 if (errcode)
6850 return got_error_set_errno(errcode, "pthread_create");
6852 if (!using_mock_io)
6853 halfdelay(1); /* fast refresh while annotating */
6856 if (s->blame_complete && !using_mock_io)
6857 halfdelay(10); /* disable fast refresh */
6859 err = draw_blame(view);
6861 view_border(view);
6862 return err;
6865 static const struct got_error *
6866 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6867 struct got_repository *repo, struct got_object_id *id)
6869 struct tog_view *log_view;
6870 const struct got_error *err = NULL;
6872 *new_view = NULL;
6874 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6875 if (log_view == NULL)
6876 return got_error_from_errno("view_open");
6878 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0, NULL);
6879 if (err)
6880 view_close(log_view);
6881 else
6882 *new_view = log_view;
6884 return err;
6887 static const struct got_error *
6888 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6890 const struct got_error *err = NULL, *thread_err = NULL;
6891 struct tog_view *diff_view;
6892 struct tog_blame_view_state *s = &view->state.blame;
6893 int eos, nscroll, begin_y = 0, begin_x = 0;
6895 eos = nscroll = view->nlines - 2;
6896 if (view_is_hsplit_top(view))
6897 --eos; /* border */
6899 switch (ch) {
6900 case '0':
6901 case '$':
6902 case KEY_RIGHT:
6903 case 'l':
6904 case KEY_LEFT:
6905 case 'h':
6906 horizontal_scroll_input(view, ch);
6907 break;
6908 case 'q':
6909 s->done = 1;
6910 break;
6911 case 'g':
6912 case KEY_HOME:
6913 s->selected_line = 1;
6914 s->first_displayed_line = 1;
6915 view->count = 0;
6916 break;
6917 case 'G':
6918 case KEY_END:
6919 if (s->blame.nlines < eos) {
6920 s->selected_line = s->blame.nlines;
6921 s->first_displayed_line = 1;
6922 } else {
6923 s->selected_line = eos;
6924 s->first_displayed_line = s->blame.nlines - (eos - 1);
6926 view->count = 0;
6927 break;
6928 case 'k':
6929 case KEY_UP:
6930 case CTRL('p'):
6931 if (s->selected_line > 1)
6932 s->selected_line--;
6933 else if (s->selected_line == 1 &&
6934 s->first_displayed_line > 1)
6935 s->first_displayed_line--;
6936 else
6937 view->count = 0;
6938 break;
6939 case CTRL('u'):
6940 case 'u':
6941 nscroll /= 2;
6942 /* FALL THROUGH */
6943 case KEY_PPAGE:
6944 case CTRL('b'):
6945 case 'b':
6946 if (s->first_displayed_line == 1) {
6947 if (view->count > 1)
6948 nscroll += nscroll;
6949 s->selected_line = MAX(1, s->selected_line - nscroll);
6950 view->count = 0;
6951 break;
6953 if (s->first_displayed_line > nscroll)
6954 s->first_displayed_line -= nscroll;
6955 else
6956 s->first_displayed_line = 1;
6957 break;
6958 case 'j':
6959 case KEY_DOWN:
6960 case CTRL('n'):
6961 if (s->selected_line < eos && s->first_displayed_line +
6962 s->selected_line <= s->blame.nlines)
6963 s->selected_line++;
6964 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6965 s->first_displayed_line++;
6966 else
6967 view->count = 0;
6968 break;
6969 case 'c':
6970 case 'p': {
6971 struct got_object_id *id = NULL;
6973 view->count = 0;
6974 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6975 s->first_displayed_line, s->selected_line);
6976 if (id == NULL)
6977 break;
6978 if (ch == 'p') {
6979 struct got_commit_object *commit, *pcommit;
6980 struct got_object_qid *pid;
6981 struct got_object_id *blob_id = NULL;
6982 int obj_type;
6983 err = got_object_open_as_commit(&commit,
6984 s->repo, id);
6985 if (err)
6986 break;
6987 pid = STAILQ_FIRST(
6988 got_object_commit_get_parent_ids(commit));
6989 if (pid == NULL) {
6990 got_object_commit_close(commit);
6991 break;
6993 /* Check if path history ends here. */
6994 err = got_object_open_as_commit(&pcommit,
6995 s->repo, &pid->id);
6996 if (err)
6997 break;
6998 err = got_object_id_by_path(&blob_id, s->repo,
6999 pcommit, s->path);
7000 got_object_commit_close(pcommit);
7001 if (err) {
7002 if (err->code == GOT_ERR_NO_TREE_ENTRY)
7003 err = NULL;
7004 got_object_commit_close(commit);
7005 break;
7007 err = got_object_get_type(&obj_type, s->repo,
7008 blob_id);
7009 free(blob_id);
7010 /* Can't blame non-blob type objects. */
7011 if (obj_type != GOT_OBJ_TYPE_BLOB) {
7012 got_object_commit_close(commit);
7013 break;
7015 err = got_object_qid_alloc(&s->blamed_commit,
7016 &pid->id);
7017 got_object_commit_close(commit);
7018 } else {
7019 if (got_object_id_cmp(id,
7020 &s->blamed_commit->id) == 0)
7021 break;
7022 err = got_object_qid_alloc(&s->blamed_commit,
7023 id);
7025 if (err)
7026 break;
7027 s->done = 1;
7028 thread_err = stop_blame(&s->blame);
7029 s->done = 0;
7030 if (thread_err)
7031 break;
7032 STAILQ_INSERT_HEAD(&s->blamed_commits,
7033 s->blamed_commit, entry);
7034 err = run_blame(view);
7035 if (err)
7036 break;
7037 break;
7039 case 'C': {
7040 struct got_object_qid *first;
7042 view->count = 0;
7043 first = STAILQ_FIRST(&s->blamed_commits);
7044 if (!got_object_id_cmp(&first->id, s->commit_id))
7045 break;
7046 s->done = 1;
7047 thread_err = stop_blame(&s->blame);
7048 s->done = 0;
7049 if (thread_err)
7050 break;
7051 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
7052 got_object_qid_free(s->blamed_commit);
7053 s->blamed_commit =
7054 STAILQ_FIRST(&s->blamed_commits);
7055 err = run_blame(view);
7056 if (err)
7057 break;
7058 break;
7060 case 'L':
7061 view->count = 0;
7062 s->id_to_log = get_selected_commit_id(s->blame.lines,
7063 s->blame.nlines, s->first_displayed_line, s->selected_line);
7064 if (s->id_to_log)
7065 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7066 break;
7067 case KEY_ENTER:
7068 case '\r': {
7069 struct got_object_id *id = NULL;
7070 struct got_object_qid *pid;
7071 struct got_commit_object *commit = NULL;
7073 view->count = 0;
7074 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
7075 s->first_displayed_line, s->selected_line);
7076 if (id == NULL)
7077 break;
7078 err = got_object_open_as_commit(&commit, s->repo, id);
7079 if (err)
7080 break;
7081 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
7082 if (*new_view) {
7083 /* traversed from diff view, release diff resources */
7084 err = close_diff_view(*new_view);
7085 if (err)
7086 break;
7087 diff_view = *new_view;
7088 } else {
7089 if (view_is_parent_view(view))
7090 view_get_split(view, &begin_y, &begin_x);
7092 diff_view = view_open(0, 0, begin_y, begin_x,
7093 TOG_VIEW_DIFF);
7094 if (diff_view == NULL) {
7095 got_object_commit_close(commit);
7096 err = got_error_from_errno("view_open");
7097 break;
7100 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
7101 id, NULL, NULL, 3, 0, 0, view, s->repo);
7102 got_object_commit_close(commit);
7103 if (err)
7104 break;
7105 s->last_diffed_line = s->first_displayed_line - 1 +
7106 s->selected_line;
7107 if (*new_view)
7108 break; /* still open from active diff view */
7109 if (view_is_parent_view(view) &&
7110 view->mode == TOG_VIEW_SPLIT_HRZN) {
7111 err = view_init_hsplit(view, begin_y);
7112 if (err)
7113 break;
7116 view->focussed = 0;
7117 diff_view->focussed = 1;
7118 diff_view->mode = view->mode;
7119 diff_view->nlines = view->lines - begin_y;
7120 if (view_is_parent_view(view)) {
7121 view_transfer_size(diff_view, view);
7122 err = view_close_child(view);
7123 if (err)
7124 break;
7125 err = view_set_child(view, diff_view);
7126 if (err)
7127 break;
7128 view->focus_child = 1;
7129 } else
7130 *new_view = diff_view;
7131 if (err)
7132 break;
7133 break;
7135 case CTRL('d'):
7136 case 'd':
7137 nscroll /= 2;
7138 /* FALL THROUGH */
7139 case KEY_NPAGE:
7140 case CTRL('f'):
7141 case 'f':
7142 case ' ':
7143 if (s->last_displayed_line >= s->blame.nlines &&
7144 s->selected_line >= MIN(s->blame.nlines,
7145 view->nlines - 2)) {
7146 view->count = 0;
7147 break;
7149 if (s->last_displayed_line >= s->blame.nlines &&
7150 s->selected_line < view->nlines - 2) {
7151 s->selected_line +=
7152 MIN(nscroll, s->last_displayed_line -
7153 s->first_displayed_line - s->selected_line + 1);
7155 if (s->last_displayed_line + nscroll <= s->blame.nlines)
7156 s->first_displayed_line += nscroll;
7157 else
7158 s->first_displayed_line =
7159 s->blame.nlines - (view->nlines - 3);
7160 break;
7161 case KEY_RESIZE:
7162 if (s->selected_line > view->nlines - 2) {
7163 s->selected_line = MIN(s->blame.nlines,
7164 view->nlines - 2);
7166 break;
7167 default:
7168 view->count = 0;
7169 break;
7171 return thread_err ? thread_err : err;
7174 static const struct got_error *
7175 reset_blame_view(struct tog_view *view)
7177 const struct got_error *err;
7178 struct tog_blame_view_state *s = &view->state.blame;
7180 view->count = 0;
7181 s->done = 1;
7182 err = stop_blame(&s->blame);
7183 s->done = 0;
7184 if (err)
7185 return err;
7186 return run_blame(view);
7189 static const struct got_error *
7190 cmd_blame(int argc, char *argv[])
7192 const struct got_error *error;
7193 struct got_repository *repo = NULL;
7194 struct got_worktree *worktree = NULL;
7195 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7196 char *link_target = NULL;
7197 struct got_object_id *commit_id = NULL;
7198 struct got_commit_object *commit = NULL;
7199 char *keyword_idstr = NULL, *commit_id_str = NULL;
7200 int ch;
7201 struct tog_view *view = NULL;
7202 int *pack_fds = NULL;
7204 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7205 switch (ch) {
7206 case 'c':
7207 commit_id_str = optarg;
7208 break;
7209 case 'r':
7210 repo_path = realpath(optarg, NULL);
7211 if (repo_path == NULL)
7212 return got_error_from_errno2("realpath",
7213 optarg);
7214 break;
7215 default:
7216 usage_blame();
7217 /* NOTREACHED */
7221 argc -= optind;
7222 argv += optind;
7224 if (argc != 1)
7225 usage_blame();
7227 error = got_repo_pack_fds_open(&pack_fds);
7228 if (error != NULL)
7229 goto done;
7231 if (repo_path == NULL) {
7232 cwd = getcwd(NULL, 0);
7233 if (cwd == NULL)
7234 return got_error_from_errno("getcwd");
7235 error = got_worktree_open(&worktree, cwd, NULL);
7236 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7237 goto done;
7238 if (worktree)
7239 repo_path =
7240 strdup(got_worktree_get_repo_path(worktree));
7241 else
7242 repo_path = strdup(cwd);
7243 if (repo_path == NULL) {
7244 error = got_error_from_errno("strdup");
7245 goto done;
7249 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7250 if (error != NULL)
7251 goto done;
7253 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
7254 worktree);
7255 if (error)
7256 goto done;
7258 init_curses();
7260 error = apply_unveil(got_repo_get_path(repo), NULL);
7261 if (error)
7262 goto done;
7264 error = tog_load_refs(repo, 0);
7265 if (error)
7266 goto done;
7268 if (commit_id_str == NULL) {
7269 struct got_reference *head_ref;
7270 error = got_ref_open(&head_ref, repo, worktree ?
7271 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7272 if (error != NULL)
7273 goto done;
7274 error = got_ref_resolve(&commit_id, repo, head_ref);
7275 got_ref_close(head_ref);
7276 } else {
7277 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
7278 repo, worktree);
7279 if (error != NULL)
7280 goto done;
7281 if (keyword_idstr != NULL)
7282 commit_id_str = keyword_idstr;
7284 error = got_repo_match_object_id(&commit_id, NULL,
7285 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7287 if (error != NULL)
7288 goto done;
7290 error = got_object_open_as_commit(&commit, repo, commit_id);
7291 if (error)
7292 goto done;
7294 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7295 commit, repo);
7296 if (error)
7297 goto done;
7299 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7300 if (view == NULL) {
7301 error = got_error_from_errno("view_open");
7302 goto done;
7304 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7305 commit_id, repo);
7306 if (error != NULL) {
7307 if (view->close == NULL)
7308 close_blame_view(view);
7309 view_close(view);
7310 goto done;
7313 if (worktree) {
7314 error = set_tog_base_commit(repo, worktree);
7315 if (error != NULL)
7316 goto done;
7318 /* Release work tree lock. */
7319 got_worktree_close(worktree);
7320 worktree = NULL;
7323 error = view_loop(view);
7325 done:
7326 free(tog_base_commit.id);
7327 free(repo_path);
7328 free(in_repo_path);
7329 free(link_target);
7330 free(cwd);
7331 free(commit_id);
7332 free(keyword_idstr);
7333 if (commit)
7334 got_object_commit_close(commit);
7335 if (worktree)
7336 got_worktree_close(worktree);
7337 if (repo) {
7338 const struct got_error *close_err = got_repo_close(repo);
7339 if (error == NULL)
7340 error = close_err;
7342 if (pack_fds) {
7343 const struct got_error *pack_err =
7344 got_repo_pack_fds_close(pack_fds);
7345 if (error == NULL)
7346 error = pack_err;
7348 tog_free_refs();
7349 return error;
7352 static const struct got_error *
7353 draw_tree_entries(struct tog_view *view, const char *parent_path)
7355 struct tog_tree_view_state *s = &view->state.tree;
7356 const struct got_error *err = NULL;
7357 struct got_tree_entry *te;
7358 wchar_t *wline;
7359 char *index = NULL;
7360 struct tog_color *tc;
7361 int width, n, nentries, scrollx, i = 1;
7362 int limit = view->nlines;
7364 s->ndisplayed = 0;
7365 if (view_is_hsplit_top(view))
7366 --limit; /* border */
7368 werase(view->window);
7370 if (limit == 0)
7371 return NULL;
7373 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7374 0, 0);
7375 if (err)
7376 return err;
7377 if (view_needs_focus_indication(view))
7378 wstandout(view->window);
7379 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7380 if (tc)
7381 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7382 waddwstr(view->window, wline);
7383 free(wline);
7384 wline = NULL;
7385 while (width++ < view->ncols)
7386 waddch(view->window, ' ');
7387 if (tc)
7388 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7389 if (view_needs_focus_indication(view))
7390 wstandend(view->window);
7391 if (--limit <= 0)
7392 return NULL;
7394 i += s->selected;
7395 if (s->first_displayed_entry) {
7396 i += got_tree_entry_get_index(s->first_displayed_entry);
7397 if (s->tree != s->root)
7398 ++i; /* account for ".." entry */
7400 nentries = got_object_tree_get_nentries(s->tree);
7401 if (asprintf(&index, "[%d/%d] %s",
7402 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7403 return got_error_from_errno("asprintf");
7404 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7405 free(index);
7406 if (err)
7407 return err;
7408 waddwstr(view->window, wline);
7409 free(wline);
7410 wline = NULL;
7411 if (width < view->ncols - 1)
7412 waddch(view->window, '\n');
7413 if (--limit <= 0)
7414 return NULL;
7415 waddch(view->window, '\n');
7416 if (--limit <= 0)
7417 return NULL;
7419 if (s->first_displayed_entry == NULL) {
7420 te = got_object_tree_get_first_entry(s->tree);
7421 if (s->selected == 0) {
7422 if (view->focussed)
7423 wstandout(view->window);
7424 s->selected_entry = NULL;
7426 waddstr(view->window, " ..\n"); /* parent directory */
7427 if (s->selected == 0 && view->focussed)
7428 wstandend(view->window);
7429 s->ndisplayed++;
7430 if (--limit <= 0)
7431 return NULL;
7432 n = 1;
7433 } else {
7434 n = 0;
7435 te = s->first_displayed_entry;
7438 view->maxx = 0;
7439 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7440 char *line = NULL, *id_str = NULL, *link_target = NULL;
7441 const char *modestr = "";
7442 mode_t mode;
7444 te = got_object_tree_get_entry(s->tree, i);
7445 mode = got_tree_entry_get_mode(te);
7447 if (s->show_ids) {
7448 err = got_object_id_str(&id_str,
7449 got_tree_entry_get_id(te));
7450 if (err)
7451 return got_error_from_errno(
7452 "got_object_id_str");
7454 if (got_object_tree_entry_is_submodule(te))
7455 modestr = "$";
7456 else if (S_ISLNK(mode)) {
7457 int i;
7459 err = got_tree_entry_get_symlink_target(&link_target,
7460 te, s->repo);
7461 if (err) {
7462 free(id_str);
7463 return err;
7465 for (i = 0; link_target[i] != '\0'; i++) {
7466 if (!isprint((unsigned char)link_target[i]))
7467 link_target[i] = '?';
7469 modestr = "@";
7471 else if (S_ISDIR(mode))
7472 modestr = "/";
7473 else if (mode & S_IXUSR)
7474 modestr = "*";
7475 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7476 got_tree_entry_get_name(te), modestr,
7477 link_target ? " -> ": "",
7478 link_target ? link_target : "") == -1) {
7479 free(id_str);
7480 free(link_target);
7481 return got_error_from_errno("asprintf");
7483 free(id_str);
7484 free(link_target);
7486 /* use full line width to determine view->maxx */
7487 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7488 if (err) {
7489 free(line);
7490 break;
7492 view->maxx = MAX(view->maxx, width);
7493 free(wline);
7494 wline = NULL;
7496 err = format_line(&wline, &width, &scrollx, line, view->x,
7497 view->ncols, 0, 0);
7498 if (err) {
7499 free(line);
7500 break;
7502 if (n == s->selected) {
7503 if (view->focussed)
7504 wstandout(view->window);
7505 s->selected_entry = te;
7507 tc = match_color(&s->colors, line);
7508 if (tc)
7509 wattr_on(view->window,
7510 COLOR_PAIR(tc->colorpair), NULL);
7511 waddwstr(view->window, &wline[scrollx]);
7512 if (tc)
7513 wattr_off(view->window,
7514 COLOR_PAIR(tc->colorpair), NULL);
7515 if (width < view->ncols)
7516 waddch(view->window, '\n');
7517 if (n == s->selected && view->focussed)
7518 wstandend(view->window);
7519 free(line);
7520 free(wline);
7521 wline = NULL;
7522 n++;
7523 s->ndisplayed++;
7524 s->last_displayed_entry = te;
7525 if (--limit <= 0)
7526 break;
7529 return err;
7532 static void
7533 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7535 struct got_tree_entry *te;
7536 int isroot = s->tree == s->root;
7537 int i = 0;
7539 if (s->first_displayed_entry == NULL)
7540 return;
7542 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7543 while (i++ < maxscroll) {
7544 if (te == NULL) {
7545 if (!isroot)
7546 s->first_displayed_entry = NULL;
7547 break;
7549 s->first_displayed_entry = te;
7550 te = got_tree_entry_get_prev(s->tree, te);
7554 static const struct got_error *
7555 tree_scroll_down(struct tog_view *view, int maxscroll)
7557 struct tog_tree_view_state *s = &view->state.tree;
7558 struct got_tree_entry *next, *last;
7559 int n = 0;
7561 if (s->first_displayed_entry)
7562 next = got_tree_entry_get_next(s->tree,
7563 s->first_displayed_entry);
7564 else
7565 next = got_object_tree_get_first_entry(s->tree);
7567 last = s->last_displayed_entry;
7568 while (next && n++ < maxscroll) {
7569 if (last) {
7570 s->last_displayed_entry = last;
7571 last = got_tree_entry_get_next(s->tree, last);
7573 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7574 s->first_displayed_entry = next;
7575 next = got_tree_entry_get_next(s->tree, next);
7579 return NULL;
7582 static const struct got_error *
7583 tree_entry_path(char **path, struct tog_parent_trees *parents,
7584 struct got_tree_entry *te)
7586 const struct got_error *err = NULL;
7587 struct tog_parent_tree *pt;
7588 size_t len = 2; /* for leading slash and NUL */
7590 TAILQ_FOREACH(pt, parents, entry)
7591 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7592 + 1 /* slash */;
7593 if (te)
7594 len += strlen(got_tree_entry_get_name(te));
7596 *path = calloc(1, len);
7597 if (path == NULL)
7598 return got_error_from_errno("calloc");
7600 (*path)[0] = '/';
7601 pt = TAILQ_LAST(parents, tog_parent_trees);
7602 while (pt) {
7603 const char *name = got_tree_entry_get_name(pt->selected_entry);
7604 if (strlcat(*path, name, len) >= len) {
7605 err = got_error(GOT_ERR_NO_SPACE);
7606 goto done;
7608 if (strlcat(*path, "/", len) >= len) {
7609 err = got_error(GOT_ERR_NO_SPACE);
7610 goto done;
7612 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7614 if (te) {
7615 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7616 err = got_error(GOT_ERR_NO_SPACE);
7617 goto done;
7620 done:
7621 if (err) {
7622 free(*path);
7623 *path = NULL;
7625 return err;
7628 static const struct got_error *
7629 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7630 struct got_tree_entry *te, struct tog_parent_trees *parents,
7631 struct got_object_id *commit_id, struct got_repository *repo)
7633 const struct got_error *err = NULL;
7634 char *path;
7635 struct tog_view *blame_view;
7637 *new_view = NULL;
7639 err = tree_entry_path(&path, parents, te);
7640 if (err)
7641 return err;
7643 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7644 if (blame_view == NULL) {
7645 err = got_error_from_errno("view_open");
7646 goto done;
7649 err = open_blame_view(blame_view, path, commit_id, repo);
7650 if (err) {
7651 if (err->code == GOT_ERR_CANCELLED)
7652 err = NULL;
7653 view_close(blame_view);
7654 } else
7655 *new_view = blame_view;
7656 done:
7657 free(path);
7658 return err;
7661 static const struct got_error *
7662 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7663 struct tog_tree_view_state *s)
7665 struct tog_view *log_view;
7666 const struct got_error *err = NULL;
7667 char *path;
7669 *new_view = NULL;
7671 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7672 if (log_view == NULL)
7673 return got_error_from_errno("view_open");
7675 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7676 if (err)
7677 return err;
7679 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7680 path, 0, NULL);
7681 if (err)
7682 view_close(log_view);
7683 else
7684 *new_view = log_view;
7685 free(path);
7686 return err;
7689 static const struct got_error *
7690 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7691 const char *head_ref_name, struct got_repository *repo)
7693 const struct got_error *err = NULL;
7694 char *commit_id_str = NULL;
7695 struct tog_tree_view_state *s = &view->state.tree;
7696 struct got_commit_object *commit = NULL;
7698 TAILQ_INIT(&s->parents);
7699 STAILQ_INIT(&s->colors);
7701 s->commit_id = got_object_id_dup(commit_id);
7702 if (s->commit_id == NULL) {
7703 err = got_error_from_errno("got_object_id_dup");
7704 goto done;
7707 err = got_object_open_as_commit(&commit, repo, commit_id);
7708 if (err)
7709 goto done;
7712 * The root is opened here and will be closed when the view is closed.
7713 * Any visited subtrees and their path-wise parents are opened and
7714 * closed on demand.
7716 err = got_object_open_as_tree(&s->root, repo,
7717 got_object_commit_get_tree_id(commit));
7718 if (err)
7719 goto done;
7720 s->tree = s->root;
7722 err = got_object_id_str(&commit_id_str, commit_id);
7723 if (err != NULL)
7724 goto done;
7726 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7727 err = got_error_from_errno("asprintf");
7728 goto done;
7731 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7732 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7733 if (head_ref_name) {
7734 s->head_ref_name = strdup(head_ref_name);
7735 if (s->head_ref_name == NULL) {
7736 err = got_error_from_errno("strdup");
7737 goto done;
7740 s->repo = repo;
7742 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7743 err = add_color(&s->colors, "\\$$",
7744 TOG_COLOR_TREE_SUBMODULE,
7745 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7746 if (err)
7747 goto done;
7748 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7749 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7750 if (err)
7751 goto done;
7752 err = add_color(&s->colors, "/$",
7753 TOG_COLOR_TREE_DIRECTORY,
7754 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7755 if (err)
7756 goto done;
7758 err = add_color(&s->colors, "\\*$",
7759 TOG_COLOR_TREE_EXECUTABLE,
7760 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7761 if (err)
7762 goto done;
7764 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7765 get_color_value("TOG_COLOR_COMMIT"));
7766 if (err)
7767 goto done;
7770 view->show = show_tree_view;
7771 view->input = input_tree_view;
7772 view->close = close_tree_view;
7773 view->search_start = search_start_tree_view;
7774 view->search_next = search_next_tree_view;
7775 done:
7776 free(commit_id_str);
7777 if (commit)
7778 got_object_commit_close(commit);
7779 if (err) {
7780 if (view->close == NULL)
7781 close_tree_view(view);
7782 view_close(view);
7784 return err;
7787 static const struct got_error *
7788 close_tree_view(struct tog_view *view)
7790 struct tog_tree_view_state *s = &view->state.tree;
7792 free_colors(&s->colors);
7793 free(s->tree_label);
7794 s->tree_label = NULL;
7795 free(s->commit_id);
7796 s->commit_id = NULL;
7797 free(s->head_ref_name);
7798 s->head_ref_name = NULL;
7799 while (!TAILQ_EMPTY(&s->parents)) {
7800 struct tog_parent_tree *parent;
7801 parent = TAILQ_FIRST(&s->parents);
7802 TAILQ_REMOVE(&s->parents, parent, entry);
7803 if (parent->tree != s->root)
7804 got_object_tree_close(parent->tree);
7805 free(parent);
7808 if (s->tree != NULL && s->tree != s->root)
7809 got_object_tree_close(s->tree);
7810 if (s->root)
7811 got_object_tree_close(s->root);
7812 return NULL;
7815 static const struct got_error *
7816 search_start_tree_view(struct tog_view *view)
7818 struct tog_tree_view_state *s = &view->state.tree;
7820 s->matched_entry = NULL;
7821 return NULL;
7824 static int
7825 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7827 regmatch_t regmatch;
7829 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7830 0) == 0;
7833 static const struct got_error *
7834 search_next_tree_view(struct tog_view *view)
7836 struct tog_tree_view_state *s = &view->state.tree;
7837 struct got_tree_entry *te = NULL;
7839 if (!view->searching) {
7840 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7841 return NULL;
7844 if (s->matched_entry) {
7845 if (view->searching == TOG_SEARCH_FORWARD) {
7846 if (s->selected_entry)
7847 te = got_tree_entry_get_next(s->tree,
7848 s->selected_entry);
7849 else
7850 te = got_object_tree_get_first_entry(s->tree);
7851 } else {
7852 if (s->selected_entry == NULL)
7853 te = got_object_tree_get_last_entry(s->tree);
7854 else
7855 te = got_tree_entry_get_prev(s->tree,
7856 s->selected_entry);
7858 } else {
7859 if (s->selected_entry)
7860 te = s->selected_entry;
7861 else if (view->searching == TOG_SEARCH_FORWARD)
7862 te = got_object_tree_get_first_entry(s->tree);
7863 else
7864 te = got_object_tree_get_last_entry(s->tree);
7867 while (1) {
7868 if (te == NULL) {
7869 if (s->matched_entry == NULL) {
7870 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7871 return NULL;
7873 if (view->searching == TOG_SEARCH_FORWARD)
7874 te = got_object_tree_get_first_entry(s->tree);
7875 else
7876 te = got_object_tree_get_last_entry(s->tree);
7879 if (match_tree_entry(te, &view->regex)) {
7880 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7881 s->matched_entry = te;
7882 break;
7885 if (view->searching == TOG_SEARCH_FORWARD)
7886 te = got_tree_entry_get_next(s->tree, te);
7887 else
7888 te = got_tree_entry_get_prev(s->tree, te);
7891 if (s->matched_entry) {
7892 s->first_displayed_entry = s->matched_entry;
7893 s->selected = 0;
7896 return NULL;
7899 static const struct got_error *
7900 show_tree_view(struct tog_view *view)
7902 const struct got_error *err = NULL;
7903 struct tog_tree_view_state *s = &view->state.tree;
7904 char *parent_path;
7906 err = tree_entry_path(&parent_path, &s->parents, NULL);
7907 if (err)
7908 return err;
7910 err = draw_tree_entries(view, parent_path);
7911 free(parent_path);
7913 view_border(view);
7914 return err;
7917 static const struct got_error *
7918 tree_goto_line(struct tog_view *view, int nlines)
7920 const struct got_error *err = NULL;
7921 struct tog_tree_view_state *s = &view->state.tree;
7922 struct got_tree_entry **fte, **lte, **ste;
7923 int g, last, first = 1, i = 1;
7924 int root = s->tree == s->root;
7925 int off = root ? 1 : 2;
7927 g = view->gline;
7928 view->gline = 0;
7930 if (g == 0)
7931 g = 1;
7932 else if (g > got_object_tree_get_nentries(s->tree))
7933 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7935 fte = &s->first_displayed_entry;
7936 lte = &s->last_displayed_entry;
7937 ste = &s->selected_entry;
7939 if (*fte != NULL) {
7940 first = got_tree_entry_get_index(*fte);
7941 first += off; /* account for ".." */
7943 last = got_tree_entry_get_index(*lte);
7944 last += off;
7946 if (g >= first && g <= last && g - first < nlines) {
7947 s->selected = g - first;
7948 return NULL; /* gline is on the current page */
7951 if (*ste != NULL) {
7952 i = got_tree_entry_get_index(*ste);
7953 i += off;
7956 if (i < g) {
7957 err = tree_scroll_down(view, g - i);
7958 if (err)
7959 return err;
7960 if (got_tree_entry_get_index(*lte) >=
7961 got_object_tree_get_nentries(s->tree) - 1 &&
7962 first + s->selected < g &&
7963 s->selected < s->ndisplayed - 1) {
7964 first = got_tree_entry_get_index(*fte);
7965 first += off;
7966 s->selected = g - first;
7968 } else if (i > g)
7969 tree_scroll_up(s, i - g);
7971 if (g < nlines &&
7972 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7973 s->selected = g - 1;
7975 return NULL;
7978 static const struct got_error *
7979 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7981 const struct got_error *err = NULL;
7982 struct tog_tree_view_state *s = &view->state.tree;
7983 struct got_tree_entry *te;
7984 int n, nscroll = view->nlines - 3;
7986 if (view->gline)
7987 return tree_goto_line(view, nscroll);
7989 switch (ch) {
7990 case '0':
7991 case '$':
7992 case KEY_RIGHT:
7993 case 'l':
7994 case KEY_LEFT:
7995 case 'h':
7996 horizontal_scroll_input(view, ch);
7997 break;
7998 case 'i':
7999 s->show_ids = !s->show_ids;
8000 view->count = 0;
8001 break;
8002 case 'L':
8003 view->count = 0;
8004 if (!s->selected_entry)
8005 break;
8006 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8007 break;
8008 case 'R':
8009 view->count = 0;
8010 err = view_request_new(new_view, view, TOG_VIEW_REF);
8011 break;
8012 case 'g':
8013 case '=':
8014 case KEY_HOME:
8015 s->selected = 0;
8016 view->count = 0;
8017 if (s->tree == s->root)
8018 s->first_displayed_entry =
8019 got_object_tree_get_first_entry(s->tree);
8020 else
8021 s->first_displayed_entry = NULL;
8022 break;
8023 case 'G':
8024 case '*':
8025 case KEY_END: {
8026 int eos = view->nlines - 3;
8028 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8029 --eos; /* border */
8030 s->selected = 0;
8031 view->count = 0;
8032 te = got_object_tree_get_last_entry(s->tree);
8033 for (n = 0; n < eos; n++) {
8034 if (te == NULL) {
8035 if (s->tree != s->root) {
8036 s->first_displayed_entry = NULL;
8037 n++;
8039 break;
8041 s->first_displayed_entry = te;
8042 te = got_tree_entry_get_prev(s->tree, te);
8044 if (n > 0)
8045 s->selected = n - 1;
8046 break;
8048 case 'k':
8049 case KEY_UP:
8050 case CTRL('p'):
8051 if (s->selected > 0) {
8052 s->selected--;
8053 break;
8055 tree_scroll_up(s, 1);
8056 if (s->selected_entry == NULL ||
8057 (s->tree == s->root && s->selected_entry ==
8058 got_object_tree_get_first_entry(s->tree)))
8059 view->count = 0;
8060 break;
8061 case CTRL('u'):
8062 case 'u':
8063 nscroll /= 2;
8064 /* FALL THROUGH */
8065 case KEY_PPAGE:
8066 case CTRL('b'):
8067 case 'b':
8068 if (s->tree == s->root) {
8069 if (got_object_tree_get_first_entry(s->tree) ==
8070 s->first_displayed_entry)
8071 s->selected -= MIN(s->selected, nscroll);
8072 } else {
8073 if (s->first_displayed_entry == NULL)
8074 s->selected -= MIN(s->selected, nscroll);
8076 tree_scroll_up(s, MAX(0, nscroll));
8077 if (s->selected_entry == NULL ||
8078 (s->tree == s->root && s->selected_entry ==
8079 got_object_tree_get_first_entry(s->tree)))
8080 view->count = 0;
8081 break;
8082 case 'j':
8083 case KEY_DOWN:
8084 case CTRL('n'):
8085 if (s->selected < s->ndisplayed - 1) {
8086 s->selected++;
8087 break;
8089 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
8090 == NULL) {
8091 /* can't scroll any further */
8092 view->count = 0;
8093 break;
8095 tree_scroll_down(view, 1);
8096 break;
8097 case CTRL('d'):
8098 case 'd':
8099 nscroll /= 2;
8100 /* FALL THROUGH */
8101 case KEY_NPAGE:
8102 case CTRL('f'):
8103 case 'f':
8104 case ' ':
8105 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
8106 == NULL) {
8107 /* can't scroll any further; move cursor down */
8108 if (s->selected < s->ndisplayed - 1)
8109 s->selected += MIN(nscroll,
8110 s->ndisplayed - s->selected - 1);
8111 else
8112 view->count = 0;
8113 break;
8115 tree_scroll_down(view, nscroll);
8116 break;
8117 case KEY_ENTER:
8118 case '\r':
8119 case KEY_BACKSPACE:
8120 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
8121 struct tog_parent_tree *parent;
8122 /* user selected '..' */
8123 if (s->tree == s->root) {
8124 view->count = 0;
8125 break;
8127 parent = TAILQ_FIRST(&s->parents);
8128 TAILQ_REMOVE(&s->parents, parent,
8129 entry);
8130 got_object_tree_close(s->tree);
8131 s->tree = parent->tree;
8132 s->first_displayed_entry =
8133 parent->first_displayed_entry;
8134 s->selected_entry =
8135 parent->selected_entry;
8136 s->selected = parent->selected;
8137 if (s->selected > view->nlines - 3) {
8138 err = offset_selection_down(view);
8139 if (err)
8140 break;
8142 free(parent);
8143 } else if (S_ISDIR(got_tree_entry_get_mode(
8144 s->selected_entry))) {
8145 struct got_tree_object *subtree;
8146 view->count = 0;
8147 err = got_object_open_as_tree(&subtree, s->repo,
8148 got_tree_entry_get_id(s->selected_entry));
8149 if (err)
8150 break;
8151 err = tree_view_visit_subtree(s, subtree);
8152 if (err) {
8153 got_object_tree_close(subtree);
8154 break;
8156 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
8157 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
8158 break;
8159 case KEY_RESIZE:
8160 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
8161 s->selected = view->nlines - 4;
8162 view->count = 0;
8163 break;
8164 default:
8165 view->count = 0;
8166 break;
8169 return err;
8172 __dead static void
8173 usage_tree(void)
8175 endwin();
8176 fprintf(stderr,
8177 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
8178 getprogname());
8179 exit(1);
8182 static const struct got_error *
8183 cmd_tree(int argc, char *argv[])
8185 const struct got_error *error;
8186 struct got_repository *repo = NULL;
8187 struct got_worktree *worktree = NULL;
8188 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8189 struct got_object_id *commit_id = NULL;
8190 struct got_commit_object *commit = NULL;
8191 const char *commit_id_arg = NULL;
8192 char *keyword_idstr = NULL, *label = NULL;
8193 struct got_reference *ref = NULL;
8194 const char *head_ref_name = NULL;
8195 int ch;
8196 struct tog_view *view;
8197 int *pack_fds = NULL;
8199 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
8200 switch (ch) {
8201 case 'c':
8202 commit_id_arg = optarg;
8203 break;
8204 case 'r':
8205 repo_path = realpath(optarg, NULL);
8206 if (repo_path == NULL)
8207 return got_error_from_errno2("realpath",
8208 optarg);
8209 break;
8210 default:
8211 usage_tree();
8212 /* NOTREACHED */
8216 argc -= optind;
8217 argv += optind;
8219 if (argc > 1)
8220 usage_tree();
8222 error = got_repo_pack_fds_open(&pack_fds);
8223 if (error != NULL)
8224 goto done;
8226 if (repo_path == NULL) {
8227 cwd = getcwd(NULL, 0);
8228 if (cwd == NULL)
8229 return got_error_from_errno("getcwd");
8230 error = got_worktree_open(&worktree, cwd, NULL);
8231 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8232 goto done;
8233 if (worktree)
8234 repo_path =
8235 strdup(got_worktree_get_repo_path(worktree));
8236 else
8237 repo_path = strdup(cwd);
8238 if (repo_path == NULL) {
8239 error = got_error_from_errno("strdup");
8240 goto done;
8244 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8245 if (error != NULL)
8246 goto done;
8248 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8249 repo, worktree);
8250 if (error)
8251 goto done;
8253 init_curses();
8255 error = apply_unveil(got_repo_get_path(repo), NULL);
8256 if (error)
8257 goto done;
8259 error = tog_load_refs(repo, 0);
8260 if (error)
8261 goto done;
8263 if (commit_id_arg == NULL) {
8264 error = got_repo_match_object_id(&commit_id, &label,
8265 worktree ? got_worktree_get_head_ref_name(worktree) :
8266 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8267 if (error)
8268 goto done;
8269 head_ref_name = label;
8270 } else {
8271 error = got_keyword_to_idstr(&keyword_idstr, commit_id_arg,
8272 repo, worktree);
8273 if (error != NULL)
8274 goto done;
8275 if (keyword_idstr != NULL)
8276 commit_id_arg = keyword_idstr;
8278 error = got_ref_open(&ref, repo, commit_id_arg, 0);
8279 if (error == NULL)
8280 head_ref_name = got_ref_get_name(ref);
8281 else if (error->code != GOT_ERR_NOT_REF)
8282 goto done;
8283 error = got_repo_match_object_id(&commit_id, NULL,
8284 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8285 if (error)
8286 goto done;
8289 error = got_object_open_as_commit(&commit, repo, commit_id);
8290 if (error)
8291 goto done;
8293 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
8294 if (view == NULL) {
8295 error = got_error_from_errno("view_open");
8296 goto done;
8298 error = open_tree_view(view, commit_id, head_ref_name, repo);
8299 if (error)
8300 goto done;
8301 if (!got_path_is_root_dir(in_repo_path)) {
8302 error = tree_view_walk_path(&view->state.tree, commit,
8303 in_repo_path);
8304 if (error)
8305 goto done;
8308 if (worktree) {
8309 error = set_tog_base_commit(repo, worktree);
8310 if (error != NULL)
8311 goto done;
8313 /* Release work tree lock. */
8314 got_worktree_close(worktree);
8315 worktree = NULL;
8318 error = view_loop(view);
8320 done:
8321 free(tog_base_commit.id);
8322 free(keyword_idstr);
8323 free(repo_path);
8324 free(cwd);
8325 free(commit_id);
8326 free(label);
8327 if (ref)
8328 got_ref_close(ref);
8329 if (worktree != NULL)
8330 got_worktree_close(worktree);
8331 if (repo) {
8332 const struct got_error *close_err = got_repo_close(repo);
8333 if (error == NULL)
8334 error = close_err;
8336 if (pack_fds) {
8337 const struct got_error *pack_err =
8338 got_repo_pack_fds_close(pack_fds);
8339 if (error == NULL)
8340 error = pack_err;
8342 tog_free_refs();
8343 return error;
8346 static const struct got_error *
8347 ref_view_load_refs(struct tog_ref_view_state *s)
8349 struct got_reflist_entry *sre;
8350 struct tog_reflist_entry *re;
8352 s->nrefs = 0;
8353 TAILQ_FOREACH(sre, &tog_refs, entry) {
8354 if (strncmp(got_ref_get_name(sre->ref),
8355 "refs/got/", 9) == 0 &&
8356 strncmp(got_ref_get_name(sre->ref),
8357 "refs/got/backup/", 16) != 0)
8358 continue;
8360 re = malloc(sizeof(*re));
8361 if (re == NULL)
8362 return got_error_from_errno("malloc");
8364 re->ref = got_ref_dup(sre->ref);
8365 if (re->ref == NULL)
8366 return got_error_from_errno("got_ref_dup");
8367 re->idx = s->nrefs++;
8368 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8371 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8372 return NULL;
8375 static void
8376 ref_view_free_refs(struct tog_ref_view_state *s)
8378 struct tog_reflist_entry *re;
8380 while (!TAILQ_EMPTY(&s->refs)) {
8381 re = TAILQ_FIRST(&s->refs);
8382 TAILQ_REMOVE(&s->refs, re, entry);
8383 got_ref_close(re->ref);
8384 free(re);
8388 static const struct got_error *
8389 open_ref_view(struct tog_view *view, struct got_repository *repo)
8391 const struct got_error *err = NULL;
8392 struct tog_ref_view_state *s = &view->state.ref;
8394 s->selected_entry = 0;
8395 s->repo = repo;
8397 TAILQ_INIT(&s->refs);
8398 STAILQ_INIT(&s->colors);
8400 err = ref_view_load_refs(s);
8401 if (err)
8402 goto done;
8404 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8405 err = add_color(&s->colors, "^refs/heads/",
8406 TOG_COLOR_REFS_HEADS,
8407 get_color_value("TOG_COLOR_REFS_HEADS"));
8408 if (err)
8409 goto done;
8411 err = add_color(&s->colors, "^refs/tags/",
8412 TOG_COLOR_REFS_TAGS,
8413 get_color_value("TOG_COLOR_REFS_TAGS"));
8414 if (err)
8415 goto done;
8417 err = add_color(&s->colors, "^refs/remotes/",
8418 TOG_COLOR_REFS_REMOTES,
8419 get_color_value("TOG_COLOR_REFS_REMOTES"));
8420 if (err)
8421 goto done;
8423 err = add_color(&s->colors, "^refs/got/backup/",
8424 TOG_COLOR_REFS_BACKUP,
8425 get_color_value("TOG_COLOR_REFS_BACKUP"));
8426 if (err)
8427 goto done;
8430 view->show = show_ref_view;
8431 view->input = input_ref_view;
8432 view->close = close_ref_view;
8433 view->search_start = search_start_ref_view;
8434 view->search_next = search_next_ref_view;
8435 done:
8436 if (err) {
8437 if (view->close == NULL)
8438 close_ref_view(view);
8439 view_close(view);
8441 return err;
8444 static const struct got_error *
8445 close_ref_view(struct tog_view *view)
8447 struct tog_ref_view_state *s = &view->state.ref;
8449 ref_view_free_refs(s);
8450 free_colors(&s->colors);
8452 return NULL;
8455 static const struct got_error *
8456 resolve_reflist_entry(struct got_object_id **commit_id,
8457 struct tog_reflist_entry *re, struct got_repository *repo)
8459 const struct got_error *err = NULL;
8460 struct got_object_id *obj_id;
8461 struct got_tag_object *tag = NULL;
8462 int obj_type;
8464 *commit_id = NULL;
8466 err = got_ref_resolve(&obj_id, repo, re->ref);
8467 if (err)
8468 return err;
8470 err = got_object_get_type(&obj_type, repo, obj_id);
8471 if (err)
8472 goto done;
8474 switch (obj_type) {
8475 case GOT_OBJ_TYPE_COMMIT:
8476 *commit_id = obj_id;
8477 break;
8478 case GOT_OBJ_TYPE_TAG:
8479 err = got_object_open_as_tag(&tag, repo, obj_id);
8480 if (err)
8481 goto done;
8482 free(obj_id);
8483 err = got_object_get_type(&obj_type, repo,
8484 got_object_tag_get_object_id(tag));
8485 if (err)
8486 goto done;
8487 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8488 err = got_error(GOT_ERR_OBJ_TYPE);
8489 goto done;
8491 *commit_id = got_object_id_dup(
8492 got_object_tag_get_object_id(tag));
8493 if (*commit_id == NULL) {
8494 err = got_error_from_errno("got_object_id_dup");
8495 goto done;
8497 break;
8498 default:
8499 err = got_error(GOT_ERR_OBJ_TYPE);
8500 break;
8503 done:
8504 if (tag)
8505 got_object_tag_close(tag);
8506 if (err) {
8507 free(*commit_id);
8508 *commit_id = NULL;
8510 return err;
8513 static const struct got_error *
8514 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8515 struct tog_reflist_entry *re, struct got_repository *repo)
8517 struct tog_view *log_view;
8518 const struct got_error *err = NULL;
8519 struct got_object_id *commit_id = NULL;
8521 *new_view = NULL;
8523 err = resolve_reflist_entry(&commit_id, re, repo);
8524 if (err) {
8525 if (err->code != GOT_ERR_OBJ_TYPE)
8526 return err;
8527 else
8528 return NULL;
8531 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8532 if (log_view == NULL) {
8533 err = got_error_from_errno("view_open");
8534 goto done;
8537 err = open_log_view(log_view, commit_id, repo,
8538 got_ref_get_name(re->ref), "", 0, NULL);
8539 done:
8540 if (err)
8541 view_close(log_view);
8542 else
8543 *new_view = log_view;
8544 free(commit_id);
8545 return err;
8548 static void
8549 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8551 struct tog_reflist_entry *re;
8552 int i = 0;
8554 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8555 return;
8557 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8558 while (i++ < maxscroll) {
8559 if (re == NULL)
8560 break;
8561 s->first_displayed_entry = re;
8562 re = TAILQ_PREV(re, tog_reflist_head, entry);
8566 static const struct got_error *
8567 ref_scroll_down(struct tog_view *view, int maxscroll)
8569 struct tog_ref_view_state *s = &view->state.ref;
8570 struct tog_reflist_entry *next, *last;
8571 int n = 0;
8573 if (s->first_displayed_entry)
8574 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8575 else
8576 next = TAILQ_FIRST(&s->refs);
8578 last = s->last_displayed_entry;
8579 while (next && n++ < maxscroll) {
8580 if (last) {
8581 s->last_displayed_entry = last;
8582 last = TAILQ_NEXT(last, entry);
8584 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8585 s->first_displayed_entry = next;
8586 next = TAILQ_NEXT(next, entry);
8590 return NULL;
8593 static const struct got_error *
8594 search_start_ref_view(struct tog_view *view)
8596 struct tog_ref_view_state *s = &view->state.ref;
8598 s->matched_entry = NULL;
8599 return NULL;
8602 static int
8603 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8605 regmatch_t regmatch;
8607 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8608 0) == 0;
8611 static const struct got_error *
8612 search_next_ref_view(struct tog_view *view)
8614 struct tog_ref_view_state *s = &view->state.ref;
8615 struct tog_reflist_entry *re = NULL;
8617 if (!view->searching) {
8618 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8619 return NULL;
8622 if (s->matched_entry) {
8623 if (view->searching == TOG_SEARCH_FORWARD) {
8624 if (s->selected_entry)
8625 re = TAILQ_NEXT(s->selected_entry, entry);
8626 else
8627 re = TAILQ_PREV(s->selected_entry,
8628 tog_reflist_head, entry);
8629 } else {
8630 if (s->selected_entry == NULL)
8631 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8632 else
8633 re = TAILQ_PREV(s->selected_entry,
8634 tog_reflist_head, entry);
8636 } else {
8637 if (s->selected_entry)
8638 re = s->selected_entry;
8639 else if (view->searching == TOG_SEARCH_FORWARD)
8640 re = TAILQ_FIRST(&s->refs);
8641 else
8642 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8645 while (1) {
8646 if (re == NULL) {
8647 if (s->matched_entry == NULL) {
8648 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8649 return NULL;
8651 if (view->searching == TOG_SEARCH_FORWARD)
8652 re = TAILQ_FIRST(&s->refs);
8653 else
8654 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8657 if (match_reflist_entry(re, &view->regex)) {
8658 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8659 s->matched_entry = re;
8660 break;
8663 if (view->searching == TOG_SEARCH_FORWARD)
8664 re = TAILQ_NEXT(re, entry);
8665 else
8666 re = TAILQ_PREV(re, tog_reflist_head, entry);
8669 if (s->matched_entry) {
8670 s->first_displayed_entry = s->matched_entry;
8671 s->selected = 0;
8674 return NULL;
8677 static const struct got_error *
8678 show_ref_view(struct tog_view *view)
8680 const struct got_error *err = NULL;
8681 struct tog_ref_view_state *s = &view->state.ref;
8682 struct tog_reflist_entry *re;
8683 char *line = NULL;
8684 wchar_t *wline;
8685 struct tog_color *tc;
8686 int width, n, scrollx;
8687 int limit = view->nlines;
8689 werase(view->window);
8691 s->ndisplayed = 0;
8692 if (view_is_hsplit_top(view))
8693 --limit; /* border */
8695 if (limit == 0)
8696 return NULL;
8698 re = s->first_displayed_entry;
8700 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8701 s->nrefs) == -1)
8702 return got_error_from_errno("asprintf");
8704 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8705 if (err) {
8706 free(line);
8707 return err;
8709 if (view_needs_focus_indication(view))
8710 wstandout(view->window);
8711 waddwstr(view->window, wline);
8712 while (width++ < view->ncols)
8713 waddch(view->window, ' ');
8714 if (view_needs_focus_indication(view))
8715 wstandend(view->window);
8716 free(wline);
8717 wline = NULL;
8718 free(line);
8719 line = NULL;
8720 if (--limit <= 0)
8721 return NULL;
8723 n = 0;
8724 view->maxx = 0;
8725 while (re && limit > 0) {
8726 char *line = NULL;
8727 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8729 if (s->show_date) {
8730 struct got_commit_object *ci;
8731 struct got_tag_object *tag;
8732 struct got_object_id *id;
8733 struct tm tm;
8734 time_t t;
8736 err = got_ref_resolve(&id, s->repo, re->ref);
8737 if (err)
8738 return err;
8739 err = got_object_open_as_tag(&tag, s->repo, id);
8740 if (err) {
8741 if (err->code != GOT_ERR_OBJ_TYPE) {
8742 free(id);
8743 return err;
8745 err = got_object_open_as_commit(&ci, s->repo,
8746 id);
8747 if (err) {
8748 free(id);
8749 return err;
8751 t = got_object_commit_get_committer_time(ci);
8752 got_object_commit_close(ci);
8753 } else {
8754 t = got_object_tag_get_tagger_time(tag);
8755 got_object_tag_close(tag);
8757 free(id);
8758 if (gmtime_r(&t, &tm) == NULL)
8759 return got_error_from_errno("gmtime_r");
8760 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8761 return got_error(GOT_ERR_NO_SPACE);
8763 if (got_ref_is_symbolic(re->ref)) {
8764 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8765 ymd : "", got_ref_get_name(re->ref),
8766 got_ref_get_symref_target(re->ref)) == -1)
8767 return got_error_from_errno("asprintf");
8768 } else if (s->show_ids) {
8769 struct got_object_id *id;
8770 char *id_str;
8771 err = got_ref_resolve(&id, s->repo, re->ref);
8772 if (err)
8773 return err;
8774 err = got_object_id_str(&id_str, id);
8775 if (err) {
8776 free(id);
8777 return err;
8779 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8780 got_ref_get_name(re->ref), id_str) == -1) {
8781 err = got_error_from_errno("asprintf");
8782 free(id);
8783 free(id_str);
8784 return err;
8786 free(id);
8787 free(id_str);
8788 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8789 got_ref_get_name(re->ref)) == -1)
8790 return got_error_from_errno("asprintf");
8792 /* use full line width to determine view->maxx */
8793 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8794 if (err) {
8795 free(line);
8796 return err;
8798 view->maxx = MAX(view->maxx, width);
8799 free(wline);
8800 wline = NULL;
8802 err = format_line(&wline, &width, &scrollx, line, view->x,
8803 view->ncols, 0, 0);
8804 if (err) {
8805 free(line);
8806 return err;
8808 if (n == s->selected) {
8809 if (view->focussed)
8810 wstandout(view->window);
8811 s->selected_entry = re;
8813 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8814 if (tc)
8815 wattr_on(view->window,
8816 COLOR_PAIR(tc->colorpair), NULL);
8817 waddwstr(view->window, &wline[scrollx]);
8818 if (tc)
8819 wattr_off(view->window,
8820 COLOR_PAIR(tc->colorpair), NULL);
8821 if (width < view->ncols)
8822 waddch(view->window, '\n');
8823 if (n == s->selected && view->focussed)
8824 wstandend(view->window);
8825 free(line);
8826 free(wline);
8827 wline = NULL;
8828 n++;
8829 s->ndisplayed++;
8830 s->last_displayed_entry = re;
8832 limit--;
8833 re = TAILQ_NEXT(re, entry);
8836 view_border(view);
8837 return err;
8840 static const struct got_error *
8841 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8842 struct tog_reflist_entry *re, struct got_repository *repo)
8844 const struct got_error *err = NULL;
8845 struct got_object_id *commit_id = NULL;
8846 struct tog_view *tree_view;
8848 *new_view = NULL;
8850 err = resolve_reflist_entry(&commit_id, re, repo);
8851 if (err) {
8852 if (err->code != GOT_ERR_OBJ_TYPE)
8853 return err;
8854 else
8855 return NULL;
8859 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8860 if (tree_view == NULL) {
8861 err = got_error_from_errno("view_open");
8862 goto done;
8865 err = open_tree_view(tree_view, commit_id,
8866 got_ref_get_name(re->ref), repo);
8867 if (err)
8868 goto done;
8870 *new_view = tree_view;
8871 done:
8872 free(commit_id);
8873 return err;
8876 static const struct got_error *
8877 ref_goto_line(struct tog_view *view, int nlines)
8879 const struct got_error *err = NULL;
8880 struct tog_ref_view_state *s = &view->state.ref;
8881 int g, idx = s->selected_entry->idx;
8883 g = view->gline;
8884 view->gline = 0;
8886 if (g == 0)
8887 g = 1;
8888 else if (g > s->nrefs)
8889 g = s->nrefs;
8891 if (g >= s->first_displayed_entry->idx + 1 &&
8892 g <= s->last_displayed_entry->idx + 1 &&
8893 g - s->first_displayed_entry->idx - 1 < nlines) {
8894 s->selected = g - s->first_displayed_entry->idx - 1;
8895 return NULL;
8898 if (idx + 1 < g) {
8899 err = ref_scroll_down(view, g - idx - 1);
8900 if (err)
8901 return err;
8902 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8903 s->first_displayed_entry->idx + s->selected < g &&
8904 s->selected < s->ndisplayed - 1)
8905 s->selected = g - s->first_displayed_entry->idx - 1;
8906 } else if (idx + 1 > g)
8907 ref_scroll_up(s, idx - g + 1);
8909 if (g < nlines && s->first_displayed_entry->idx == 0)
8910 s->selected = g - 1;
8912 return NULL;
8916 static const struct got_error *
8917 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8919 const struct got_error *err = NULL;
8920 struct tog_ref_view_state *s = &view->state.ref;
8921 struct tog_reflist_entry *re;
8922 int n, nscroll = view->nlines - 1;
8924 if (view->gline)
8925 return ref_goto_line(view, nscroll);
8927 switch (ch) {
8928 case '0':
8929 case '$':
8930 case KEY_RIGHT:
8931 case 'l':
8932 case KEY_LEFT:
8933 case 'h':
8934 horizontal_scroll_input(view, ch);
8935 break;
8936 case 'i':
8937 s->show_ids = !s->show_ids;
8938 view->count = 0;
8939 break;
8940 case 'm':
8941 s->show_date = !s->show_date;
8942 view->count = 0;
8943 break;
8944 case 'o':
8945 s->sort_by_date = !s->sort_by_date;
8946 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8947 view->count = 0;
8948 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8949 got_ref_cmp_by_commit_timestamp_descending :
8950 tog_ref_cmp_by_name, s->repo);
8951 if (err)
8952 break;
8953 got_reflist_object_id_map_free(tog_refs_idmap);
8954 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8955 &tog_refs, s->repo);
8956 if (err)
8957 break;
8958 ref_view_free_refs(s);
8959 err = ref_view_load_refs(s);
8960 break;
8961 case KEY_ENTER:
8962 case '\r':
8963 view->count = 0;
8964 if (!s->selected_entry)
8965 break;
8966 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8967 break;
8968 case 'T':
8969 view->count = 0;
8970 if (!s->selected_entry)
8971 break;
8972 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8973 break;
8974 case 'g':
8975 case '=':
8976 case KEY_HOME:
8977 s->selected = 0;
8978 view->count = 0;
8979 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8980 break;
8981 case 'G':
8982 case '*':
8983 case KEY_END: {
8984 int eos = view->nlines - 1;
8986 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8987 --eos; /* border */
8988 s->selected = 0;
8989 view->count = 0;
8990 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8991 for (n = 0; n < eos; n++) {
8992 if (re == NULL)
8993 break;
8994 s->first_displayed_entry = re;
8995 re = TAILQ_PREV(re, tog_reflist_head, entry);
8997 if (n > 0)
8998 s->selected = n - 1;
8999 break;
9001 case 'k':
9002 case KEY_UP:
9003 case CTRL('p'):
9004 if (s->selected > 0) {
9005 s->selected--;
9006 break;
9008 ref_scroll_up(s, 1);
9009 if (s->selected_entry == TAILQ_FIRST(&s->refs))
9010 view->count = 0;
9011 break;
9012 case CTRL('u'):
9013 case 'u':
9014 nscroll /= 2;
9015 /* FALL THROUGH */
9016 case KEY_PPAGE:
9017 case CTRL('b'):
9018 case 'b':
9019 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
9020 s->selected -= MIN(nscroll, s->selected);
9021 ref_scroll_up(s, MAX(0, nscroll));
9022 if (s->selected_entry == TAILQ_FIRST(&s->refs))
9023 view->count = 0;
9024 break;
9025 case 'j':
9026 case KEY_DOWN:
9027 case CTRL('n'):
9028 if (s->selected < s->ndisplayed - 1) {
9029 s->selected++;
9030 break;
9032 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
9033 /* can't scroll any further */
9034 view->count = 0;
9035 break;
9037 ref_scroll_down(view, 1);
9038 break;
9039 case CTRL('d'):
9040 case 'd':
9041 nscroll /= 2;
9042 /* FALL THROUGH */
9043 case KEY_NPAGE:
9044 case CTRL('f'):
9045 case 'f':
9046 case ' ':
9047 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
9048 /* can't scroll any further; move cursor down */
9049 if (s->selected < s->ndisplayed - 1)
9050 s->selected += MIN(nscroll,
9051 s->ndisplayed - s->selected - 1);
9052 if (view->count > 1 && s->selected < s->ndisplayed - 1)
9053 s->selected += s->ndisplayed - s->selected - 1;
9054 view->count = 0;
9055 break;
9057 ref_scroll_down(view, nscroll);
9058 break;
9059 case CTRL('l'):
9060 view->count = 0;
9061 tog_free_refs();
9062 err = tog_load_refs(s->repo, s->sort_by_date);
9063 if (err)
9064 break;
9065 ref_view_free_refs(s);
9066 err = ref_view_load_refs(s);
9067 break;
9068 case KEY_RESIZE:
9069 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
9070 s->selected = view->nlines - 2;
9071 break;
9072 default:
9073 view->count = 0;
9074 break;
9077 return err;
9080 __dead static void
9081 usage_ref(void)
9083 endwin();
9084 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
9085 getprogname());
9086 exit(1);
9089 static const struct got_error *
9090 cmd_ref(int argc, char *argv[])
9092 const struct got_error *error;
9093 struct got_repository *repo = NULL;
9094 struct got_worktree *worktree = NULL;
9095 char *cwd = NULL, *repo_path = NULL;
9096 int ch;
9097 struct tog_view *view;
9098 int *pack_fds = NULL;
9100 while ((ch = getopt(argc, argv, "r:")) != -1) {
9101 switch (ch) {
9102 case 'r':
9103 repo_path = realpath(optarg, NULL);
9104 if (repo_path == NULL)
9105 return got_error_from_errno2("realpath",
9106 optarg);
9107 break;
9108 default:
9109 usage_ref();
9110 /* NOTREACHED */
9114 argc -= optind;
9115 argv += optind;
9117 if (argc > 1)
9118 usage_ref();
9120 error = got_repo_pack_fds_open(&pack_fds);
9121 if (error != NULL)
9122 goto done;
9124 if (repo_path == NULL) {
9125 cwd = getcwd(NULL, 0);
9126 if (cwd == NULL)
9127 return got_error_from_errno("getcwd");
9128 error = got_worktree_open(&worktree, cwd, NULL);
9129 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9130 goto done;
9131 if (worktree)
9132 repo_path =
9133 strdup(got_worktree_get_repo_path(worktree));
9134 else
9135 repo_path = strdup(cwd);
9136 if (repo_path == NULL) {
9137 error = got_error_from_errno("strdup");
9138 goto done;
9142 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9143 if (error != NULL)
9144 goto done;
9146 init_curses();
9148 error = apply_unveil(got_repo_get_path(repo), NULL);
9149 if (error)
9150 goto done;
9152 error = tog_load_refs(repo, 0);
9153 if (error)
9154 goto done;
9156 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
9157 if (view == NULL) {
9158 error = got_error_from_errno("view_open");
9159 goto done;
9162 error = open_ref_view(view, repo);
9163 if (error)
9164 goto done;
9166 if (worktree) {
9167 error = set_tog_base_commit(repo, worktree);
9168 if (error != NULL)
9169 goto done;
9171 /* Release work tree lock. */
9172 got_worktree_close(worktree);
9173 worktree = NULL;
9176 error = view_loop(view);
9178 done:
9179 free(tog_base_commit.id);
9180 free(repo_path);
9181 free(cwd);
9182 if (worktree != NULL)
9183 got_worktree_close(worktree);
9184 if (repo) {
9185 const struct got_error *close_err = got_repo_close(repo);
9186 if (close_err)
9187 error = close_err;
9189 if (pack_fds) {
9190 const struct got_error *pack_err =
9191 got_repo_pack_fds_close(pack_fds);
9192 if (error == NULL)
9193 error = pack_err;
9195 tog_free_refs();
9196 return error;
9199 static const struct got_error*
9200 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
9201 const char *str)
9203 size_t len;
9205 if (win == NULL)
9206 win = stdscr;
9208 len = strlen(str);
9209 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
9211 if (focus)
9212 wstandout(win);
9213 if (mvwprintw(win, y, x, "%s", str) == ERR)
9214 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
9215 if (focus)
9216 wstandend(win);
9218 return NULL;
9221 static const struct got_error *
9222 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
9224 off_t *p;
9226 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
9227 if (p == NULL) {
9228 free(*line_offsets);
9229 *line_offsets = NULL;
9230 return got_error_from_errno("reallocarray");
9233 *line_offsets = p;
9234 (*line_offsets)[*nlines] = off;
9235 ++(*nlines);
9236 return NULL;
9239 static const struct got_error *
9240 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
9242 *ret = 0;
9244 for (;n > 0; --n, ++km) {
9245 char *t0, *t, *k;
9246 size_t len = 1;
9248 if (km->keys == NULL)
9249 continue;
9251 t = t0 = strdup(km->keys);
9252 if (t0 == NULL)
9253 return got_error_from_errno("strdup");
9255 len += strlen(t);
9256 while ((k = strsep(&t, " ")) != NULL)
9257 len += strlen(k) > 1 ? 2 : 0;
9258 free(t0);
9259 *ret = MAX(*ret, len);
9262 return NULL;
9266 * Write keymap section headers, keys, and key info in km to f.
9267 * Save line offset to *off. If terminal has UTF8 encoding enabled,
9268 * wrap control and symbolic keys in guillemets, else use <>.
9270 static const struct got_error *
9271 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
9273 int n, len = width;
9275 if (km->keys) {
9276 static const char *u8_glyph[] = {
9277 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
9278 "\xe2\x80\xba" /* U+203A (utf8 >) */
9280 char *t0, *t, *k;
9281 int cs, s, first = 1;
9283 cs = got_locale_is_utf8();
9285 t = t0 = strdup(km->keys);
9286 if (t0 == NULL)
9287 return got_error_from_errno("strdup");
9289 len = strlen(km->keys);
9290 while ((k = strsep(&t, " ")) != NULL) {
9291 s = strlen(k) > 1; /* control or symbolic key */
9292 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
9293 cs && s ? u8_glyph[0] : s ? "<" : "", k,
9294 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
9295 if (n < 0) {
9296 free(t0);
9297 return got_error_from_errno("fprintf");
9299 first = 0;
9300 len += s ? 2 : 0;
9301 *off += n;
9303 free(t0);
9305 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
9306 if (n < 0)
9307 return got_error_from_errno("fprintf");
9308 *off += n;
9310 return NULL;
9313 static const struct got_error *
9314 format_help(struct tog_help_view_state *s)
9316 const struct got_error *err = NULL;
9317 off_t off = 0;
9318 int i, max, n, show = s->all;
9319 static const struct tog_key_map km[] = {
9320 #define KEYMAP_(info, type) { NULL, (info), type }
9321 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
9322 GENERATE_HELP
9323 #undef KEYMAP_
9324 #undef KEY_
9327 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
9328 if (err)
9329 return err;
9331 n = nitems(km);
9332 err = max_key_str(&max, km, n);
9333 if (err)
9334 return err;
9336 for (i = 0; i < n; ++i) {
9337 if (km[i].keys == NULL) {
9338 show = s->all;
9339 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9340 km[i].type == s->type || s->all)
9341 show = 1;
9343 if (show) {
9344 err = format_help_line(&off, s->f, &km[i], max);
9345 if (err)
9346 return err;
9347 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9348 if (err)
9349 return err;
9352 fputc('\n', s->f);
9353 ++off;
9354 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9355 return err;
9358 static const struct got_error *
9359 create_help(struct tog_help_view_state *s)
9361 FILE *f;
9362 const struct got_error *err;
9364 free(s->line_offsets);
9365 s->line_offsets = NULL;
9366 s->nlines = 0;
9368 f = got_opentemp();
9369 if (f == NULL)
9370 return got_error_from_errno("got_opentemp");
9371 s->f = f;
9373 err = format_help(s);
9374 if (err)
9375 return err;
9377 if (s->f && fflush(s->f) != 0)
9378 return got_error_from_errno("fflush");
9380 return NULL;
9383 static const struct got_error *
9384 search_start_help_view(struct tog_view *view)
9386 view->state.help.matched_line = 0;
9387 return NULL;
9390 static void
9391 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9392 size_t *nlines, int **first, int **last, int **match, int **selected)
9394 struct tog_help_view_state *s = &view->state.help;
9396 *f = s->f;
9397 *nlines = s->nlines;
9398 *line_offsets = s->line_offsets;
9399 *match = &s->matched_line;
9400 *first = &s->first_displayed_line;
9401 *last = &s->last_displayed_line;
9402 *selected = &s->selected_line;
9405 static const struct got_error *
9406 show_help_view(struct tog_view *view)
9408 struct tog_help_view_state *s = &view->state.help;
9409 const struct got_error *err;
9410 regmatch_t *regmatch = &view->regmatch;
9411 wchar_t *wline;
9412 char *line;
9413 ssize_t linelen;
9414 size_t linesz = 0;
9415 int width, nprinted = 0, rc = 0;
9416 int eos = view->nlines;
9418 if (view_is_hsplit_top(view))
9419 --eos; /* account for border */
9421 s->lineno = 0;
9422 rewind(s->f);
9423 werase(view->window);
9425 if (view->gline > s->nlines - 1)
9426 view->gline = s->nlines - 1;
9428 err = win_draw_center(view->window, 0, 0, view->ncols,
9429 view_needs_focus_indication(view),
9430 "tog help (press q to return to tog)");
9431 if (err)
9432 return err;
9433 if (eos <= 1)
9434 return NULL;
9435 waddstr(view->window, "\n\n");
9436 eos -= 2;
9438 s->eof = 0;
9439 view->maxx = 0;
9440 line = NULL;
9441 while (eos > 0 && nprinted < eos) {
9442 attr_t attr = 0;
9444 linelen = getline(&line, &linesz, s->f);
9445 if (linelen == -1) {
9446 if (!feof(s->f)) {
9447 free(line);
9448 return got_ferror(s->f, GOT_ERR_IO);
9450 s->eof = 1;
9451 break;
9453 if (++s->lineno < s->first_displayed_line)
9454 continue;
9455 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9456 continue;
9457 if (s->lineno == view->hiline)
9458 attr = A_STANDOUT;
9460 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9461 view->x ? 1 : 0);
9462 if (err) {
9463 free(line);
9464 return err;
9466 view->maxx = MAX(view->maxx, width);
9467 free(wline);
9468 wline = NULL;
9470 if (attr)
9471 wattron(view->window, attr);
9472 if (s->first_displayed_line + nprinted == s->matched_line &&
9473 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9474 err = add_matched_line(&width, line, view->ncols - 1, 0,
9475 view->window, view->x, regmatch);
9476 if (err) {
9477 free(line);
9478 return err;
9480 } else {
9481 int skip;
9483 err = format_line(&wline, &width, &skip, line,
9484 view->x, view->ncols, 0, view->x ? 1 : 0);
9485 if (err) {
9486 free(line);
9487 return err;
9489 waddwstr(view->window, &wline[skip]);
9490 free(wline);
9491 wline = NULL;
9493 if (s->lineno == view->hiline) {
9494 while (width++ < view->ncols)
9495 waddch(view->window, ' ');
9496 } else {
9497 if (width < view->ncols)
9498 waddch(view->window, '\n');
9500 if (attr)
9501 wattroff(view->window, attr);
9502 if (++nprinted == 1)
9503 s->first_displayed_line = s->lineno;
9505 free(line);
9506 if (nprinted > 0)
9507 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9508 else
9509 s->last_displayed_line = s->first_displayed_line;
9511 view_border(view);
9513 if (s->eof) {
9514 rc = waddnstr(view->window,
9515 "See the tog(1) manual page for full documentation",
9516 view->ncols - 1);
9517 if (rc == ERR)
9518 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9519 } else {
9520 wmove(view->window, view->nlines - 1, 0);
9521 wclrtoeol(view->window);
9522 wstandout(view->window);
9523 rc = waddnstr(view->window, "scroll down for more...",
9524 view->ncols - 1);
9525 if (rc == ERR)
9526 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9527 if (getcurx(view->window) < view->ncols - 6) {
9528 rc = wprintw(view->window, "[%.0f%%]",
9529 100.00 * s->last_displayed_line / s->nlines);
9530 if (rc == ERR)
9531 return got_error_msg(GOT_ERR_IO, "wprintw");
9533 wstandend(view->window);
9536 return NULL;
9539 static const struct got_error *
9540 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9542 struct tog_help_view_state *s = &view->state.help;
9543 const struct got_error *err = NULL;
9544 char *line = NULL;
9545 ssize_t linelen;
9546 size_t linesz = 0;
9547 int eos, nscroll;
9549 eos = nscroll = view->nlines;
9550 if (view_is_hsplit_top(view))
9551 --eos; /* border */
9553 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9555 switch (ch) {
9556 case '0':
9557 case '$':
9558 case KEY_RIGHT:
9559 case 'l':
9560 case KEY_LEFT:
9561 case 'h':
9562 horizontal_scroll_input(view, ch);
9563 break;
9564 case 'g':
9565 case KEY_HOME:
9566 s->first_displayed_line = 1;
9567 view->count = 0;
9568 break;
9569 case 'G':
9570 case KEY_END:
9571 view->count = 0;
9572 if (s->eof)
9573 break;
9574 s->first_displayed_line = (s->nlines - eos) + 3;
9575 s->eof = 1;
9576 break;
9577 case 'k':
9578 case KEY_UP:
9579 if (s->first_displayed_line > 1)
9580 --s->first_displayed_line;
9581 else
9582 view->count = 0;
9583 break;
9584 case CTRL('u'):
9585 case 'u':
9586 nscroll /= 2;
9587 /* FALL THROUGH */
9588 case KEY_PPAGE:
9589 case CTRL('b'):
9590 case 'b':
9591 if (s->first_displayed_line == 1) {
9592 view->count = 0;
9593 break;
9595 while (--nscroll > 0 && s->first_displayed_line > 1)
9596 s->first_displayed_line--;
9597 break;
9598 case 'j':
9599 case KEY_DOWN:
9600 case CTRL('n'):
9601 if (!s->eof)
9602 ++s->first_displayed_line;
9603 else
9604 view->count = 0;
9605 break;
9606 case CTRL('d'):
9607 case 'd':
9608 nscroll /= 2;
9609 /* FALL THROUGH */
9610 case KEY_NPAGE:
9611 case CTRL('f'):
9612 case 'f':
9613 case ' ':
9614 if (s->eof) {
9615 view->count = 0;
9616 break;
9618 while (!s->eof && --nscroll > 0) {
9619 linelen = getline(&line, &linesz, s->f);
9620 s->first_displayed_line++;
9621 if (linelen == -1) {
9622 if (feof(s->f))
9623 s->eof = 1;
9624 else
9625 err = got_ferror(s->f, GOT_ERR_IO);
9626 break;
9629 free(line);
9630 break;
9631 default:
9632 view->count = 0;
9633 break;
9636 return err;
9639 static const struct got_error *
9640 close_help_view(struct tog_view *view)
9642 struct tog_help_view_state *s = &view->state.help;
9644 free(s->line_offsets);
9645 s->line_offsets = NULL;
9646 if (fclose(s->f) == EOF)
9647 return got_error_from_errno("fclose");
9649 return NULL;
9652 static const struct got_error *
9653 reset_help_view(struct tog_view *view)
9655 struct tog_help_view_state *s = &view->state.help;
9658 if (s->f && fclose(s->f) == EOF)
9659 return got_error_from_errno("fclose");
9661 wclear(view->window);
9662 view->count = 0;
9663 view->x = 0;
9664 s->all = !s->all;
9665 s->first_displayed_line = 1;
9666 s->last_displayed_line = view->nlines;
9667 s->matched_line = 0;
9669 return create_help(s);
9672 static const struct got_error *
9673 open_help_view(struct tog_view *view, struct tog_view *parent)
9675 const struct got_error *err = NULL;
9676 struct tog_help_view_state *s = &view->state.help;
9678 s->type = (enum tog_keymap_type)parent->type;
9679 s->first_displayed_line = 1;
9680 s->last_displayed_line = view->nlines;
9681 s->selected_line = 1;
9683 view->show = show_help_view;
9684 view->input = input_help_view;
9685 view->reset = reset_help_view;
9686 view->close = close_help_view;
9687 view->search_start = search_start_help_view;
9688 view->search_setup = search_setup_help_view;
9689 view->search_next = search_next_view_match;
9691 err = create_help(s);
9692 return err;
9695 static const struct got_error *
9696 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9697 enum tog_view_type request, int y, int x)
9699 const struct got_error *err = NULL;
9701 *new_view = NULL;
9703 switch (request) {
9704 case TOG_VIEW_DIFF:
9705 if (view->type == TOG_VIEW_LOG) {
9706 struct tog_log_view_state *s = &view->state.log;
9708 err = open_diff_view_for_commit(new_view, y, x,
9709 s->selected_entry->commit, s->selected_entry->id,
9710 view, s->repo);
9711 } else
9712 return got_error_msg(GOT_ERR_NOT_IMPL,
9713 "parent/child view pair not supported");
9714 break;
9715 case TOG_VIEW_BLAME:
9716 if (view->type == TOG_VIEW_TREE) {
9717 struct tog_tree_view_state *s = &view->state.tree;
9719 err = blame_tree_entry(new_view, y, x,
9720 s->selected_entry, &s->parents, s->commit_id,
9721 s->repo);
9722 } else
9723 return got_error_msg(GOT_ERR_NOT_IMPL,
9724 "parent/child view pair not supported");
9725 break;
9726 case TOG_VIEW_LOG:
9727 if (view->type == TOG_VIEW_BLAME)
9728 err = log_annotated_line(new_view, y, x,
9729 view->state.blame.repo, view->state.blame.id_to_log);
9730 else if (view->type == TOG_VIEW_TREE)
9731 err = log_selected_tree_entry(new_view, y, x,
9732 &view->state.tree);
9733 else if (view->type == TOG_VIEW_REF)
9734 err = log_ref_entry(new_view, y, x,
9735 view->state.ref.selected_entry,
9736 view->state.ref.repo);
9737 else
9738 return got_error_msg(GOT_ERR_NOT_IMPL,
9739 "parent/child view pair not supported");
9740 break;
9741 case TOG_VIEW_TREE:
9742 if (view->type == TOG_VIEW_LOG)
9743 err = browse_commit_tree(new_view, y, x,
9744 view->state.log.selected_entry,
9745 view->state.log.in_repo_path,
9746 view->state.log.head_ref_name,
9747 view->state.log.repo);
9748 else if (view->type == TOG_VIEW_REF)
9749 err = browse_ref_tree(new_view, y, x,
9750 view->state.ref.selected_entry,
9751 view->state.ref.repo);
9752 else
9753 return got_error_msg(GOT_ERR_NOT_IMPL,
9754 "parent/child view pair not supported");
9755 break;
9756 case TOG_VIEW_REF:
9757 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9758 if (*new_view == NULL)
9759 return got_error_from_errno("view_open");
9760 if (view->type == TOG_VIEW_LOG)
9761 err = open_ref_view(*new_view, view->state.log.repo);
9762 else if (view->type == TOG_VIEW_TREE)
9763 err = open_ref_view(*new_view, view->state.tree.repo);
9764 else
9765 err = got_error_msg(GOT_ERR_NOT_IMPL,
9766 "parent/child view pair not supported");
9767 if (err)
9768 view_close(*new_view);
9769 break;
9770 case TOG_VIEW_HELP:
9771 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9772 if (*new_view == NULL)
9773 return got_error_from_errno("view_open");
9774 err = open_help_view(*new_view, view);
9775 if (err)
9776 view_close(*new_view);
9777 break;
9778 default:
9779 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9782 return err;
9786 * If view was scrolled down to move the selected line into view when opening a
9787 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9789 static void
9790 offset_selection_up(struct tog_view *view)
9792 switch (view->type) {
9793 case TOG_VIEW_BLAME: {
9794 struct tog_blame_view_state *s = &view->state.blame;
9795 if (s->first_displayed_line == 1) {
9796 s->selected_line = MAX(s->selected_line - view->offset,
9797 1);
9798 break;
9800 if (s->first_displayed_line > view->offset)
9801 s->first_displayed_line -= view->offset;
9802 else
9803 s->first_displayed_line = 1;
9804 s->selected_line += view->offset;
9805 break;
9807 case TOG_VIEW_LOG:
9808 log_scroll_up(&view->state.log, view->offset);
9809 view->state.log.selected += view->offset;
9810 break;
9811 case TOG_VIEW_REF:
9812 ref_scroll_up(&view->state.ref, view->offset);
9813 view->state.ref.selected += view->offset;
9814 break;
9815 case TOG_VIEW_TREE:
9816 tree_scroll_up(&view->state.tree, view->offset);
9817 view->state.tree.selected += view->offset;
9818 break;
9819 default:
9820 break;
9823 view->offset = 0;
9827 * If the selected line is in the section of screen covered by the bottom split,
9828 * scroll down offset lines to move it into view and index its new position.
9830 static const struct got_error *
9831 offset_selection_down(struct tog_view *view)
9833 const struct got_error *err = NULL;
9834 const struct got_error *(*scrolld)(struct tog_view *, int);
9835 int *selected = NULL;
9836 int header, offset;
9838 switch (view->type) {
9839 case TOG_VIEW_BLAME: {
9840 struct tog_blame_view_state *s = &view->state.blame;
9841 header = 3;
9842 scrolld = NULL;
9843 if (s->selected_line > view->nlines - header) {
9844 offset = abs(view->nlines - s->selected_line - header);
9845 s->first_displayed_line += offset;
9846 s->selected_line -= offset;
9847 view->offset = offset;
9849 break;
9851 case TOG_VIEW_LOG: {
9852 struct tog_log_view_state *s = &view->state.log;
9853 scrolld = &log_scroll_down;
9854 header = view_is_parent_view(view) ? 3 : 2;
9855 selected = &s->selected;
9856 break;
9858 case TOG_VIEW_REF: {
9859 struct tog_ref_view_state *s = &view->state.ref;
9860 scrolld = &ref_scroll_down;
9861 header = 3;
9862 selected = &s->selected;
9863 break;
9865 case TOG_VIEW_TREE: {
9866 struct tog_tree_view_state *s = &view->state.tree;
9867 scrolld = &tree_scroll_down;
9868 header = 5;
9869 selected = &s->selected;
9870 break;
9872 default:
9873 selected = NULL;
9874 scrolld = NULL;
9875 header = 0;
9876 break;
9879 if (selected && *selected > view->nlines - header) {
9880 offset = abs(view->nlines - *selected - header);
9881 view->offset = offset;
9882 if (scrolld && offset) {
9883 err = scrolld(view, offset);
9884 *selected -= offset;
9888 return err;
9891 static void
9892 list_commands(FILE *fp)
9894 size_t i;
9896 fprintf(fp, "commands:");
9897 for (i = 0; i < nitems(tog_commands); i++) {
9898 const struct tog_cmd *cmd = &tog_commands[i];
9899 fprintf(fp, " %s", cmd->name);
9901 fputc('\n', fp);
9904 __dead static void
9905 usage(int hflag, int status)
9907 FILE *fp = (status == 0) ? stdout : stderr;
9909 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9910 getprogname());
9911 if (hflag) {
9912 fprintf(fp, "lazy usage: %s path\n", getprogname());
9913 list_commands(fp);
9915 exit(status);
9918 static char **
9919 make_argv(int argc, ...)
9921 va_list ap;
9922 char **argv;
9923 int i;
9925 va_start(ap, argc);
9927 argv = calloc(argc, sizeof(char *));
9928 if (argv == NULL)
9929 err(1, "calloc");
9930 for (i = 0; i < argc; i++) {
9931 argv[i] = strdup(va_arg(ap, char *));
9932 if (argv[i] == NULL)
9933 err(1, "strdup");
9936 va_end(ap);
9937 return argv;
9941 * Try to convert 'tog path' into a 'tog log path' command.
9942 * The user could simply have mistyped the command rather than knowingly
9943 * provided a path. So check whether argv[0] can in fact be resolved
9944 * to a path in the HEAD commit and print a special error if not.
9945 * This hack is for mpi@ <3
9947 static const struct got_error *
9948 tog_log_with_path(int argc, char *argv[])
9950 const struct got_error *error = NULL, *close_err;
9951 const struct tog_cmd *cmd = NULL;
9952 struct got_repository *repo = NULL;
9953 struct got_worktree *worktree = NULL;
9954 struct got_object_id *commit_id = NULL, *id = NULL;
9955 struct got_commit_object *commit = NULL;
9956 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9957 char *commit_id_str = NULL, **cmd_argv = NULL;
9958 int *pack_fds = NULL;
9960 cwd = getcwd(NULL, 0);
9961 if (cwd == NULL)
9962 return got_error_from_errno("getcwd");
9964 error = got_repo_pack_fds_open(&pack_fds);
9965 if (error != NULL)
9966 goto done;
9968 error = got_worktree_open(&worktree, cwd, NULL);
9969 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9970 goto done;
9972 if (worktree)
9973 repo_path = strdup(got_worktree_get_repo_path(worktree));
9974 else
9975 repo_path = strdup(cwd);
9976 if (repo_path == NULL) {
9977 error = got_error_from_errno("strdup");
9978 goto done;
9981 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9982 if (error != NULL)
9983 goto done;
9985 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9986 repo, worktree);
9987 if (error)
9988 goto done;
9990 error = tog_load_refs(repo, 0);
9991 if (error)
9992 goto done;
9993 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9994 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9995 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9996 if (error)
9997 goto done;
9999 if (worktree) {
10000 got_worktree_close(worktree);
10001 worktree = NULL;
10004 error = got_object_open_as_commit(&commit, repo, commit_id);
10005 if (error)
10006 goto done;
10008 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
10009 if (error) {
10010 if (error->code != GOT_ERR_NO_TREE_ENTRY)
10011 goto done;
10012 fprintf(stderr, "%s: '%s' is no known command or path\n",
10013 getprogname(), argv[0]);
10014 usage(1, 1);
10015 /* not reached */
10018 error = got_object_id_str(&commit_id_str, commit_id);
10019 if (error)
10020 goto done;
10022 cmd = &tog_commands[0]; /* log */
10023 argc = 4;
10024 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
10025 error = cmd->cmd_main(argc, cmd_argv);
10026 done:
10027 if (repo) {
10028 close_err = got_repo_close(repo);
10029 if (error == NULL)
10030 error = close_err;
10032 if (commit)
10033 got_object_commit_close(commit);
10034 if (worktree)
10035 got_worktree_close(worktree);
10036 if (pack_fds) {
10037 const struct got_error *pack_err =
10038 got_repo_pack_fds_close(pack_fds);
10039 if (error == NULL)
10040 error = pack_err;
10042 free(id);
10043 free(commit_id_str);
10044 free(commit_id);
10045 free(cwd);
10046 free(repo_path);
10047 free(in_repo_path);
10048 if (cmd_argv) {
10049 int i;
10050 for (i = 0; i < argc; i++)
10051 free(cmd_argv[i]);
10052 free(cmd_argv);
10054 tog_free_refs();
10055 return error;
10058 int
10059 main(int argc, char *argv[])
10061 const struct got_error *io_err, *error = NULL;
10062 const struct tog_cmd *cmd = NULL;
10063 int ch, hflag = 0, Vflag = 0;
10064 char **cmd_argv = NULL;
10065 static const struct option longopts[] = {
10066 { "version", no_argument, NULL, 'V' },
10067 { NULL, 0, NULL, 0}
10069 char *diff_algo_str = NULL;
10070 const char *test_script_path;
10072 setlocale(LC_CTYPE, "");
10075 * Override default signal handlers before starting ncurses.
10076 * This should prevent ncurses from installing its own
10077 * broken cleanup() signal handler.
10079 signal(SIGWINCH, tog_sigwinch);
10080 signal(SIGPIPE, tog_sigpipe);
10081 signal(SIGCONT, tog_sigcont);
10082 signal(SIGINT, tog_sigint);
10083 signal(SIGTERM, tog_sigterm);
10086 * Test mode init must happen before pledge() because "tty" will
10087 * not allow TTY-related ioctls to occur via regular files.
10089 test_script_path = getenv("TOG_TEST_SCRIPT");
10090 if (test_script_path != NULL) {
10091 error = init_mock_term(test_script_path);
10092 if (error) {
10093 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
10094 return 1;
10096 } else if (!isatty(STDIN_FILENO))
10097 errx(1, "standard input is not a tty");
10099 #if !defined(PROFILE)
10100 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
10101 NULL) == -1)
10102 err(1, "pledge");
10103 #endif
10105 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
10106 switch (ch) {
10107 case 'h':
10108 hflag = 1;
10109 break;
10110 case 'V':
10111 Vflag = 1;
10112 break;
10113 default:
10114 usage(hflag, 1);
10115 /* NOTREACHED */
10119 argc -= optind;
10120 argv += optind;
10121 optind = 1;
10122 optreset = 1;
10124 if (Vflag) {
10125 got_version_print_str();
10126 return 0;
10129 if (argc == 0) {
10130 if (hflag)
10131 usage(hflag, 0);
10132 /* Build an argument vector which runs a default command. */
10133 cmd = &tog_commands[0];
10134 argc = 1;
10135 cmd_argv = make_argv(argc, cmd->name);
10136 } else {
10137 size_t i;
10139 /* Did the user specify a command? */
10140 for (i = 0; i < nitems(tog_commands); i++) {
10141 if (strncmp(tog_commands[i].name, argv[0],
10142 strlen(argv[0])) == 0) {
10143 cmd = &tog_commands[i];
10144 break;
10149 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
10150 if (diff_algo_str) {
10151 if (strcasecmp(diff_algo_str, "patience") == 0)
10152 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
10153 if (strcasecmp(diff_algo_str, "myers") == 0)
10154 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
10157 tog_base_commit.idx = -1;
10158 tog_base_commit.marker = GOT_WORKTREE_STATE_UNKNOWN;
10160 if (cmd == NULL) {
10161 if (argc != 1)
10162 usage(0, 1);
10163 /* No command specified; try log with a path */
10164 error = tog_log_with_path(argc, argv);
10165 } else {
10166 if (hflag)
10167 cmd->cmd_usage();
10168 else
10169 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
10172 if (using_mock_io) {
10173 io_err = tog_io_close();
10174 if (error == NULL)
10175 error = io_err;
10177 endwin();
10178 if (cmd_argv) {
10179 int i;
10180 for (i = 0; i < argc; i++)
10181 free(cmd_argv[i]);
10182 free(cmd_argv);
10185 if (error && error->code != GOT_ERR_CANCELLED &&
10186 error->code != GOT_ERR_EOF &&
10187 error->code != GOT_ERR_PRIVSEP_EXIT &&
10188 error->code != GOT_ERR_PRIVSEP_PIPE &&
10189 !(error->code == GOT_ERR_ERRNO && errno == EINTR)) {
10190 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
10191 return 1;
10193 return 0;