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 "got_compat.h"
19 #include <sys/queue.h>
20 #include <sys/stat.h>
21 #include <sys/ioctl.h>
23 #include <ctype.h>
24 #include <errno.h>
25 #if defined(__FreeBSD__) || defined(__APPLE__)
26 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
27 #endif
28 #include <curses.h>
29 #include <panel.h>
30 #include <locale.h>
31 #include <signal.h>
32 #include <stdlib.h>
33 #include <stdarg.h>
34 #include <stdio.h>
35 #include <getopt.h>
36 #include <string.h>
37 #include <err.h>
38 #include <unistd.h>
39 #include <limits.h>
40 #include <wchar.h>
41 #include <time.h>
42 #include <pthread.h>
43 #include <libgen.h>
44 #include <regex.h>
45 #include <sched.h>
47 #include "got_version.h"
48 #include "got_error.h"
49 #include "got_object.h"
50 #include "got_reference.h"
51 #include "got_repository.h"
52 #include "got_diff.h"
53 #include "got_opentemp.h"
54 #include "got_utf8.h"
55 #include "got_cancel.h"
56 #include "got_commit_graph.h"
57 #include "got_blame.h"
58 #include "got_privsep.h"
59 #include "got_path.h"
60 #include "got_worktree.h"
61 #include "got_keyword.h"
63 #ifndef MIN
64 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
65 #endif
67 #ifndef MAX
68 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
69 #endif
71 #ifndef CTRL
72 #define CTRL(x) ((x) & 0x1f)
73 #endif
75 #ifndef nitems
76 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
77 #endif
79 struct tog_cmd {
80 const char *name;
81 const struct got_error *(*cmd_main)(int, char *[]);
82 void (*cmd_usage)(void);
83 };
85 __dead static void usage(int, int);
86 __dead static void usage_log(void);
87 __dead static void usage_diff(void);
88 __dead static void usage_blame(void);
89 __dead static void usage_tree(void);
90 __dead static void usage_ref(void);
92 static const struct got_error* cmd_log(int, char *[]);
93 static const struct got_error* cmd_diff(int, char *[]);
94 static const struct got_error* cmd_blame(int, char *[]);
95 static const struct got_error* cmd_tree(int, char *[]);
96 static const struct got_error* cmd_ref(int, char *[]);
98 static const struct tog_cmd tog_commands[] = {
99 { "log", cmd_log, usage_log },
100 { "diff", cmd_diff, usage_diff },
101 { "blame", cmd_blame, usage_blame },
102 { "tree", cmd_tree, usage_tree },
103 { "ref", cmd_ref, usage_ref },
104 };
106 enum tog_view_type {
107 TOG_VIEW_DIFF,
108 TOG_VIEW_LOG,
109 TOG_VIEW_BLAME,
110 TOG_VIEW_TREE,
111 TOG_VIEW_REF,
112 TOG_VIEW_HELP
113 };
115 /* Match _DIFF to _HELP with enum tog_view_type TOG_VIEW_* counterparts. */
116 enum tog_keymap_type {
117 TOG_KEYMAP_KEYS = -2,
118 TOG_KEYMAP_GLOBAL,
119 TOG_KEYMAP_DIFF,
120 TOG_KEYMAP_LOG,
121 TOG_KEYMAP_BLAME,
122 TOG_KEYMAP_TREE,
123 TOG_KEYMAP_REF,
124 TOG_KEYMAP_HELP
125 };
127 enum tog_view_mode {
128 TOG_VIEW_SPLIT_NONE,
129 TOG_VIEW_SPLIT_VERT,
130 TOG_VIEW_SPLIT_HRZN
131 };
133 #define HSPLIT_SCALE 0.3f /* default horizontal split scale */
135 #define TOG_EOF_STRING "(END)"
137 struct commit_queue_entry {
138 TAILQ_ENTRY(commit_queue_entry) entry;
139 struct got_object_id *id;
140 struct got_commit_object *commit;
141 int idx;
142 };
143 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
144 struct commit_queue {
145 int ncommits;
146 struct commit_queue_head head;
147 };
149 struct tog_color {
150 STAILQ_ENTRY(tog_color) entry;
151 regex_t regex;
152 short colorpair;
153 };
154 STAILQ_HEAD(tog_colors, tog_color);
156 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
157 static struct got_reflist_object_id_map *tog_refs_idmap;
158 static struct {
159 struct got_object_id *id;
160 int idx;
161 char marker;
162 } tog_base_commit;
163 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
165 static const struct got_error *
166 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
167 struct got_reference* re2)
169 const char *name1 = got_ref_get_name(re1);
170 const char *name2 = got_ref_get_name(re2);
171 int isbackup1, isbackup2;
173 /* Sort backup refs towards the bottom of the list. */
174 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
175 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
176 if (!isbackup1 && isbackup2) {
177 *cmp = -1;
178 return NULL;
179 } else if (isbackup1 && !isbackup2) {
180 *cmp = 1;
181 return NULL;
184 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
185 return NULL;
188 static const struct got_error *
189 tog_load_refs(struct got_repository *repo, int sort_by_date)
191 const struct got_error *err;
193 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
194 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
195 repo);
196 if (err)
197 return err;
199 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
200 repo);
203 static void
204 tog_free_refs(void)
206 if (tog_refs_idmap) {
207 got_reflist_object_id_map_free(tog_refs_idmap);
208 tog_refs_idmap = NULL;
210 got_ref_list_free(&tog_refs);
213 static const struct got_error *
214 add_color(struct tog_colors *colors, const char *pattern,
215 int idx, short color)
217 const struct got_error *err = NULL;
218 struct tog_color *tc;
219 int regerr = 0;
221 if (idx < 1 || idx > COLOR_PAIRS - 1)
222 return NULL;
224 init_pair(idx, color, -1);
226 tc = calloc(1, sizeof(*tc));
227 if (tc == NULL)
228 return got_error_from_errno("calloc");
229 regerr = regcomp(&tc->regex, pattern,
230 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
231 if (regerr) {
232 static char regerr_msg[512];
233 static char err_msg[512];
234 regerror(regerr, &tc->regex, regerr_msg,
235 sizeof(regerr_msg));
236 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
237 regerr_msg);
238 err = got_error_msg(GOT_ERR_REGEX, err_msg);
239 free(tc);
240 return err;
242 tc->colorpair = idx;
243 STAILQ_INSERT_HEAD(colors, tc, entry);
244 return NULL;
247 static void
248 free_colors(struct tog_colors *colors)
250 struct tog_color *tc;
252 while (!STAILQ_EMPTY(colors)) {
253 tc = STAILQ_FIRST(colors);
254 STAILQ_REMOVE_HEAD(colors, entry);
255 regfree(&tc->regex);
256 free(tc);
260 static struct tog_color *
261 get_color(struct tog_colors *colors, int colorpair)
263 struct tog_color *tc = NULL;
265 STAILQ_FOREACH(tc, colors, entry) {
266 if (tc->colorpair == colorpair)
267 return tc;
270 return NULL;
273 static int
274 default_color_value(const char *envvar)
276 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
277 return COLOR_MAGENTA;
278 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
279 return COLOR_CYAN;
280 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
281 return COLOR_YELLOW;
282 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
283 return COLOR_GREEN;
284 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
285 return COLOR_MAGENTA;
286 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
287 return COLOR_MAGENTA;
288 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
289 return COLOR_CYAN;
290 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
291 return COLOR_GREEN;
292 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
293 return COLOR_GREEN;
294 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
295 return COLOR_CYAN;
296 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
297 return COLOR_YELLOW;
298 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
299 return COLOR_GREEN;
300 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
301 return COLOR_MAGENTA;
302 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
303 return COLOR_YELLOW;
304 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
305 return COLOR_CYAN;
307 return -1;
310 static int
311 get_color_value(const char *envvar)
313 const char *val = getenv(envvar);
315 if (val == NULL)
316 return default_color_value(envvar);
318 if (strcasecmp(val, "black") == 0)
319 return COLOR_BLACK;
320 if (strcasecmp(val, "red") == 0)
321 return COLOR_RED;
322 if (strcasecmp(val, "green") == 0)
323 return COLOR_GREEN;
324 if (strcasecmp(val, "yellow") == 0)
325 return COLOR_YELLOW;
326 if (strcasecmp(val, "blue") == 0)
327 return COLOR_BLUE;
328 if (strcasecmp(val, "magenta") == 0)
329 return COLOR_MAGENTA;
330 if (strcasecmp(val, "cyan") == 0)
331 return COLOR_CYAN;
332 if (strcasecmp(val, "white") == 0)
333 return COLOR_WHITE;
334 if (strcasecmp(val, "default") == 0)
335 return -1;
337 return default_color_value(envvar);
340 struct tog_diff_view_state {
341 struct got_object_id *id1, *id2;
342 const char *label1, *label2;
343 FILE *f, *f1, *f2;
344 int fd1, fd2;
345 int lineno;
346 int first_displayed_line;
347 int last_displayed_line;
348 int eof;
349 int diff_context;
350 int ignore_whitespace;
351 int force_text_diff;
352 struct got_repository *repo;
353 struct got_diff_line *lines;
354 size_t nlines;
355 int matched_line;
356 int selected_line;
358 /* passed from log or blame view; may be NULL */
359 struct tog_view *parent_view;
360 };
362 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
363 static volatile sig_atomic_t tog_thread_error;
365 struct tog_log_thread_args {
366 pthread_cond_t need_commits;
367 pthread_cond_t commit_loaded;
368 int commits_needed;
369 int load_all;
370 struct got_commit_graph *graph;
371 struct commit_queue *real_commits;
372 const char *in_repo_path;
373 struct got_object_id *start_id;
374 struct got_repository *repo;
375 int *pack_fds;
376 int log_complete;
377 pthread_cond_t log_loaded;
378 sig_atomic_t *quit;
379 struct commit_queue_entry **first_displayed_entry;
380 struct commit_queue_entry **selected_entry;
381 int *searching;
382 int *search_next_done;
383 regex_t *regex;
384 int *limiting;
385 int limit_match;
386 regex_t *limit_regex;
387 struct commit_queue *limit_commits;
388 struct got_worktree *worktree;
389 int need_commit_marker;
390 };
392 struct tog_log_view_state {
393 struct commit_queue *commits;
394 struct commit_queue_entry *first_displayed_entry;
395 struct commit_queue_entry *last_displayed_entry;
396 struct commit_queue_entry *selected_entry;
397 struct commit_queue real_commits;
398 int selected;
399 char *in_repo_path;
400 char *head_ref_name;
401 int log_branches;
402 struct got_repository *repo;
403 struct got_object_id *start_id;
404 sig_atomic_t quit;
405 pthread_t thread;
406 struct tog_log_thread_args thread_args;
407 struct commit_queue_entry *matched_entry;
408 struct commit_queue_entry *search_entry;
409 struct tog_colors colors;
410 int use_committer;
411 int limit_view;
412 regex_t limit_regex;
413 struct commit_queue limit_commits;
414 };
416 #define TOG_COLOR_DIFF_MINUS 1
417 #define TOG_COLOR_DIFF_PLUS 2
418 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
419 #define TOG_COLOR_DIFF_META 4
420 #define TOG_COLOR_TREE_SUBMODULE 5
421 #define TOG_COLOR_TREE_SYMLINK 6
422 #define TOG_COLOR_TREE_DIRECTORY 7
423 #define TOG_COLOR_TREE_EXECUTABLE 8
424 #define TOG_COLOR_COMMIT 9
425 #define TOG_COLOR_AUTHOR 10
426 #define TOG_COLOR_DATE 11
427 #define TOG_COLOR_REFS_HEADS 12
428 #define TOG_COLOR_REFS_TAGS 13
429 #define TOG_COLOR_REFS_REMOTES 14
430 #define TOG_COLOR_REFS_BACKUP 15
432 struct tog_blame_cb_args {
433 struct tog_blame_line *lines; /* one per line */
434 int nlines;
436 struct tog_view *view;
437 struct got_object_id *commit_id;
438 int *quit;
439 };
441 struct tog_blame_thread_args {
442 const char *path;
443 struct got_repository *repo;
444 struct tog_blame_cb_args *cb_args;
445 int *complete;
446 got_cancel_cb cancel_cb;
447 void *cancel_arg;
448 pthread_cond_t blame_complete;
449 };
451 struct tog_blame {
452 FILE *f;
453 off_t filesize;
454 struct tog_blame_line *lines;
455 int nlines;
456 off_t *line_offsets;
457 pthread_t thread;
458 struct tog_blame_thread_args thread_args;
459 struct tog_blame_cb_args cb_args;
460 const char *path;
461 int *pack_fds;
462 };
464 struct tog_blame_view_state {
465 int first_displayed_line;
466 int last_displayed_line;
467 int selected_line;
468 int last_diffed_line;
469 int blame_complete;
470 int eof;
471 int done;
472 struct got_object_id_queue blamed_commits;
473 struct got_object_qid *blamed_commit;
474 char *path;
475 struct got_repository *repo;
476 struct got_object_id *commit_id;
477 struct got_object_id *id_to_log;
478 struct tog_blame blame;
479 int matched_line;
480 struct tog_colors colors;
481 };
483 struct tog_parent_tree {
484 TAILQ_ENTRY(tog_parent_tree) entry;
485 struct got_tree_object *tree;
486 struct got_tree_entry *first_displayed_entry;
487 struct got_tree_entry *selected_entry;
488 int selected;
489 };
491 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
493 struct tog_tree_view_state {
494 char *tree_label;
495 struct got_object_id *commit_id;/* commit which this tree belongs to */
496 struct got_tree_object *root; /* the commit's root tree entry */
497 struct got_tree_object *tree; /* currently displayed (sub-)tree */
498 struct got_tree_entry *first_displayed_entry;
499 struct got_tree_entry *last_displayed_entry;
500 struct got_tree_entry *selected_entry;
501 int ndisplayed, selected, show_ids;
502 struct tog_parent_trees parents; /* parent trees of current sub-tree */
503 char *head_ref_name;
504 struct got_repository *repo;
505 struct got_tree_entry *matched_entry;
506 struct tog_colors colors;
507 };
509 struct tog_reflist_entry {
510 TAILQ_ENTRY(tog_reflist_entry) entry;
511 struct got_reference *ref;
512 int idx;
513 };
515 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
517 struct tog_ref_view_state {
518 struct tog_reflist_head refs;
519 struct tog_reflist_entry *first_displayed_entry;
520 struct tog_reflist_entry *last_displayed_entry;
521 struct tog_reflist_entry *selected_entry;
522 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
523 struct got_repository *repo;
524 struct tog_reflist_entry *matched_entry;
525 struct tog_colors colors;
526 };
528 struct tog_help_view_state {
529 FILE *f;
530 off_t *line_offsets;
531 size_t nlines;
532 int lineno;
533 int first_displayed_line;
534 int last_displayed_line;
535 int eof;
536 int matched_line;
537 int selected_line;
538 int all;
539 enum tog_keymap_type type;
540 };
542 #define GENERATE_HELP \
543 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
544 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
545 KEY_("k C-p Up", "Move cursor or page up one line"), \
546 KEY_("j C-n Down", "Move cursor or page down one line"), \
547 KEY_("C-b b PgUp", "Scroll the view up one page"), \
548 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
549 KEY_("C-u u", "Scroll the view up one half page"), \
550 KEY_("C-d d", "Scroll the view down one half page"), \
551 KEY_("g", "Go to line N (default: first line)"), \
552 KEY_("Home =", "Go to the first line"), \
553 KEY_("G", "Go to line N (default: last line)"), \
554 KEY_("End *", "Go to the last line"), \
555 KEY_("l Right", "Scroll the view right"), \
556 KEY_("h Left", "Scroll the view left"), \
557 KEY_("$", "Scroll view to the rightmost position"), \
558 KEY_("0", "Scroll view to the leftmost position"), \
559 KEY_("-", "Decrease size of the focussed split"), \
560 KEY_("+", "Increase size of the focussed split"), \
561 KEY_("Tab", "Switch focus between views"), \
562 KEY_("F", "Toggle fullscreen mode"), \
563 KEY_("S", "Switch split-screen layout"), \
564 KEY_("/", "Open prompt to enter search term"), \
565 KEY_("n", "Find next line/token matching the current search term"), \
566 KEY_("N", "Find previous line/token matching the current search term"),\
567 KEY_("q", "Quit the focussed view; Quit help screen"), \
568 KEY_("Q", "Quit tog"), \
570 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
571 KEY_("< ,", "Move cursor up one commit"), \
572 KEY_("> .", "Move cursor down one commit"), \
573 KEY_("Enter", "Open diff view of the selected commit"), \
574 KEY_("B", "Reload the log view and toggle display of merged commits"), \
575 KEY_("R", "Open ref view of all repository references"), \
576 KEY_("T", "Display tree view of the repository from the selected" \
577 " commit"), \
578 KEY_("@", "Toggle between displaying author and committer name"), \
579 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
580 KEY_("C-g Backspace", "Cancel current search or log operation"), \
581 KEY_("C-l", "Reload the log view with new commits in the repository"), \
583 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
584 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
585 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
586 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
587 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
588 " data"), \
589 KEY_("(", "Go to the previous file in the diff"), \
590 KEY_(")", "Go to the next file in the diff"), \
591 KEY_("{", "Go to the previous hunk in the diff"), \
592 KEY_("}", "Go to the next hunk in the diff"), \
593 KEY_("[", "Decrease the number of context lines"), \
594 KEY_("]", "Increase the number of context lines"), \
595 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
597 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
598 KEY_("Enter", "Display diff view of the selected line's commit"), \
599 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
600 KEY_("L", "Open log view for the currently selected annotated line"), \
601 KEY_("C", "Reload view with the previously blamed commit"), \
602 KEY_("c", "Reload view with the version of the file found in the" \
603 " selected line's commit"), \
604 KEY_("p", "Reload view with the version of the file found in the" \
605 " selected line's parent commit"), \
607 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
608 KEY_("Enter", "Enter selected directory or open blame view of the" \
609 " selected file"), \
610 KEY_("L", "Open log view for the selected entry"), \
611 KEY_("R", "Open ref view of all repository references"), \
612 KEY_("i", "Show object IDs for all tree entries"), \
613 KEY_("Backspace", "Return to the parent directory"), \
615 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
616 KEY_("Enter", "Display log view of the selected reference"), \
617 KEY_("T", "Display tree view of the selected reference"), \
618 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
619 KEY_("m", "Toggle display of last modified date for each reference"), \
620 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
621 KEY_("C-l", "Reload view with all repository references")
623 struct tog_key_map {
624 const char *keys;
625 const char *info;
626 enum tog_keymap_type type;
627 };
629 /* curses io for tog regress */
630 struct tog_io {
631 FILE *cin;
632 FILE *cout;
633 FILE *f;
634 FILE *sdump;
635 int wait_for_ui;
636 } tog_io;
637 static int using_mock_io;
639 #define TOG_KEY_SCRDUMP SHRT_MIN
641 /*
642 * We implement two types of views: parent views and child views.
644 * The 'Tab' key switches focus between a parent view and its child view.
645 * Child views are shown side-by-side to their parent view, provided
646 * there is enough screen estate.
648 * When a new view is opened from within a parent view, this new view
649 * becomes a child view of the parent view, replacing any existing child.
651 * When a new view is opened from within a child view, this new view
652 * becomes a parent view which will obscure the views below until the
653 * user quits the new parent view by typing 'q'.
655 * This list of views contains parent views only.
656 * Child views are only pointed to by their parent view.
657 */
658 TAILQ_HEAD(tog_view_list_head, tog_view);
660 struct tog_view {
661 TAILQ_ENTRY(tog_view) entry;
662 WINDOW *window;
663 PANEL *panel;
664 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
665 int resized_y, resized_x; /* begin_y/x based on user resizing */
666 int maxx, x; /* max column and current start column */
667 int lines, cols; /* copies of LINES and COLS */
668 int nscrolled, offset; /* lines scrolled and hsplit line offset */
669 int gline, hiline; /* navigate to and highlight this nG line */
670 int ch, count; /* current keymap and count prefix */
671 int resized; /* set when in a resize event */
672 int focussed; /* Only set on one parent or child view at a time. */
673 int dying;
674 struct tog_view *parent;
675 struct tog_view *child;
677 /*
678 * This flag is initially set on parent views when a new child view
679 * is created. It gets toggled when the 'Tab' key switches focus
680 * between parent and child.
681 * The flag indicates whether focus should be passed on to our child
682 * view if this parent view gets picked for focus after another parent
683 * view was closed. This prevents child views from losing focus in such
684 * situations.
685 */
686 int focus_child;
688 enum tog_view_mode mode;
689 /* type-specific state */
690 enum tog_view_type type;
691 union {
692 struct tog_diff_view_state diff;
693 struct tog_log_view_state log;
694 struct tog_blame_view_state blame;
695 struct tog_tree_view_state tree;
696 struct tog_ref_view_state ref;
697 struct tog_help_view_state help;
698 } state;
700 const struct got_error *(*show)(struct tog_view *);
701 const struct got_error *(*input)(struct tog_view **,
702 struct tog_view *, int);
703 const struct got_error *(*reset)(struct tog_view *);
704 const struct got_error *(*resize)(struct tog_view *, int);
705 const struct got_error *(*close)(struct tog_view *);
707 const struct got_error *(*search_start)(struct tog_view *);
708 const struct got_error *(*search_next)(struct tog_view *);
709 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
710 int **, int **, int **, int **);
711 int search_started;
712 int searching;
713 #define TOG_SEARCH_FORWARD 1
714 #define TOG_SEARCH_BACKWARD 2
715 int search_next_done;
716 #define TOG_SEARCH_HAVE_MORE 1
717 #define TOG_SEARCH_NO_MORE 2
718 #define TOG_SEARCH_HAVE_NONE 3
719 regex_t regex;
720 regmatch_t regmatch;
721 const char *action;
722 };
724 static const struct got_error *open_diff_view(struct tog_view *,
725 struct got_object_id *, struct got_object_id *,
726 const char *, const char *, int, int, int, struct tog_view *,
727 struct got_repository *);
728 static const struct got_error *show_diff_view(struct tog_view *);
729 static const struct got_error *input_diff_view(struct tog_view **,
730 struct tog_view *, int);
731 static const struct got_error *reset_diff_view(struct tog_view *);
732 static const struct got_error* close_diff_view(struct tog_view *);
733 static const struct got_error *search_start_diff_view(struct tog_view *);
734 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
735 size_t *, int **, int **, int **, int **);
736 static const struct got_error *search_next_view_match(struct tog_view *);
738 static const struct got_error *open_log_view(struct tog_view *,
739 struct got_object_id *, struct got_repository *,
740 const char *, const char *, int, struct got_worktree *);
741 static const struct got_error * show_log_view(struct tog_view *);
742 static const struct got_error *input_log_view(struct tog_view **,
743 struct tog_view *, int);
744 static const struct got_error *resize_log_view(struct tog_view *, int);
745 static const struct got_error *close_log_view(struct tog_view *);
746 static const struct got_error *search_start_log_view(struct tog_view *);
747 static const struct got_error *search_next_log_view(struct tog_view *);
749 static const struct got_error *open_blame_view(struct tog_view *, char *,
750 struct got_object_id *, struct got_repository *);
751 static const struct got_error *show_blame_view(struct tog_view *);
752 static const struct got_error *input_blame_view(struct tog_view **,
753 struct tog_view *, int);
754 static const struct got_error *reset_blame_view(struct tog_view *);
755 static const struct got_error *close_blame_view(struct tog_view *);
756 static const struct got_error *search_start_blame_view(struct tog_view *);
757 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
758 size_t *, int **, int **, int **, int **);
760 static const struct got_error *open_tree_view(struct tog_view *,
761 struct got_object_id *, const char *, struct got_repository *);
762 static const struct got_error *show_tree_view(struct tog_view *);
763 static const struct got_error *input_tree_view(struct tog_view **,
764 struct tog_view *, int);
765 static const struct got_error *close_tree_view(struct tog_view *);
766 static const struct got_error *search_start_tree_view(struct tog_view *);
767 static const struct got_error *search_next_tree_view(struct tog_view *);
769 static const struct got_error *open_ref_view(struct tog_view *,
770 struct got_repository *);
771 static const struct got_error *show_ref_view(struct tog_view *);
772 static const struct got_error *input_ref_view(struct tog_view **,
773 struct tog_view *, int);
774 static const struct got_error *close_ref_view(struct tog_view *);
775 static const struct got_error *search_start_ref_view(struct tog_view *);
776 static const struct got_error *search_next_ref_view(struct tog_view *);
778 static const struct got_error *open_help_view(struct tog_view *,
779 struct tog_view *);
780 static const struct got_error *show_help_view(struct tog_view *);
781 static const struct got_error *input_help_view(struct tog_view **,
782 struct tog_view *, int);
783 static const struct got_error *reset_help_view(struct tog_view *);
784 static const struct got_error* close_help_view(struct tog_view *);
785 static const struct got_error *search_start_help_view(struct tog_view *);
786 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
787 size_t *, int **, int **, int **, int **);
789 static volatile sig_atomic_t tog_sigwinch_received;
790 static volatile sig_atomic_t tog_sigpipe_received;
791 static volatile sig_atomic_t tog_sigcont_received;
792 static volatile sig_atomic_t tog_sigint_received;
793 static volatile sig_atomic_t tog_sigterm_received;
795 static void
796 tog_sigwinch(int signo)
798 tog_sigwinch_received = 1;
801 static void
802 tog_sigpipe(int signo)
804 tog_sigpipe_received = 1;
807 static void
808 tog_sigcont(int signo)
810 tog_sigcont_received = 1;
813 static void
814 tog_sigint(int signo)
816 tog_sigint_received = 1;
819 static void
820 tog_sigterm(int signo)
822 tog_sigterm_received = 1;
825 static int
826 tog_fatal_signal_received(void)
828 return (tog_sigpipe_received ||
829 tog_sigint_received || tog_sigterm_received);
832 static const struct got_error *
833 view_close(struct tog_view *view)
835 const struct got_error *err = NULL, *child_err = NULL;
837 if (view->child) {
838 child_err = view_close(view->child);
839 view->child = NULL;
841 if (view->close)
842 err = view->close(view);
843 if (view->panel)
844 del_panel(view->panel);
845 if (view->window)
846 delwin(view->window);
847 free(view);
848 return err ? err : child_err;
851 static struct tog_view *
852 view_open(int nlines, int ncols, int begin_y, int begin_x,
853 enum tog_view_type type)
855 struct tog_view *view = calloc(1, sizeof(*view));
857 if (view == NULL)
858 return NULL;
860 view->type = type;
861 view->lines = LINES;
862 view->cols = COLS;
863 view->nlines = nlines ? nlines : LINES - begin_y;
864 view->ncols = ncols ? ncols : COLS - begin_x;
865 view->begin_y = begin_y;
866 view->begin_x = begin_x;
867 view->window = newwin(nlines, ncols, begin_y, begin_x);
868 if (view->window == NULL) {
869 view_close(view);
870 return NULL;
872 view->panel = new_panel(view->window);
873 if (view->panel == NULL ||
874 set_panel_userptr(view->panel, view) != OK) {
875 view_close(view);
876 return NULL;
879 keypad(view->window, TRUE);
880 return view;
883 static int
884 view_split_begin_x(int begin_x)
886 if (begin_x > 0 || COLS < 120)
887 return 0;
888 return (COLS - MAX(COLS / 2, 80));
891 /* XXX Stub till we decide what to do. */
892 static int
893 view_split_begin_y(int lines)
895 return lines * HSPLIT_SCALE;
898 static const struct got_error *view_resize(struct tog_view *);
900 static const struct got_error *
901 view_splitscreen(struct tog_view *view)
903 const struct got_error *err = NULL;
905 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
906 if (view->resized_y && view->resized_y < view->lines)
907 view->begin_y = view->resized_y;
908 else
909 view->begin_y = view_split_begin_y(view->nlines);
910 view->begin_x = 0;
911 } else if (!view->resized) {
912 if (view->resized_x && view->resized_x < view->cols - 1 &&
913 view->cols > 119)
914 view->begin_x = view->resized_x;
915 else
916 view->begin_x = view_split_begin_x(0);
917 view->begin_y = 0;
919 view->nlines = LINES - view->begin_y;
920 view->ncols = COLS - view->begin_x;
921 view->lines = LINES;
922 view->cols = COLS;
923 err = view_resize(view);
924 if (err)
925 return err;
927 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
928 view->parent->nlines = view->begin_y;
930 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
931 return got_error_from_errno("mvwin");
933 return NULL;
936 static const struct got_error *
937 view_fullscreen(struct tog_view *view)
939 const struct got_error *err = NULL;
941 view->begin_x = 0;
942 view->begin_y = view->resized ? view->begin_y : 0;
943 view->nlines = view->resized ? view->nlines : LINES;
944 view->ncols = COLS;
945 view->lines = LINES;
946 view->cols = COLS;
947 err = view_resize(view);
948 if (err)
949 return err;
951 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
952 return got_error_from_errno("mvwin");
954 return NULL;
957 static int
958 view_is_parent_view(struct tog_view *view)
960 return view->parent == NULL;
963 static int
964 view_is_splitscreen(struct tog_view *view)
966 return view->begin_x > 0 || view->begin_y > 0;
969 static int
970 view_is_fullscreen(struct tog_view *view)
972 return view->nlines == LINES && view->ncols == COLS;
975 static int
976 view_is_hsplit_top(struct tog_view *view)
978 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
979 view_is_splitscreen(view->child);
982 static void
983 view_border(struct tog_view *view)
985 PANEL *panel;
986 const struct tog_view *view_above;
988 if (view->parent)
989 return view_border(view->parent);
991 panel = panel_above(view->panel);
992 if (panel == NULL)
993 return;
995 view_above = panel_userptr(panel);
996 if (view->mode == TOG_VIEW_SPLIT_HRZN)
997 mvwhline(view->window, view_above->begin_y - 1,
998 view->begin_x, ACS_HLINE, view->ncols);
999 else
1000 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
1001 ACS_VLINE, view->nlines);
1004 static const struct got_error *view_init_hsplit(struct tog_view *, int);
1005 static const struct got_error *request_log_commits(struct tog_view *);
1006 static const struct got_error *offset_selection_down(struct tog_view *);
1007 static void offset_selection_up(struct tog_view *);
1008 static void view_get_split(struct tog_view *, int *, int *);
1010 static const struct got_error *
1011 view_resize(struct tog_view *view)
1013 const struct got_error *err = NULL;
1014 int dif, nlines, ncols;
1016 dif = LINES - view->lines; /* line difference */
1018 if (view->lines > LINES)
1019 nlines = view->nlines - (view->lines - LINES);
1020 else
1021 nlines = view->nlines + (LINES - view->lines);
1022 if (view->cols > COLS)
1023 ncols = view->ncols - (view->cols - COLS);
1024 else
1025 ncols = view->ncols + (COLS - view->cols);
1027 if (view->child) {
1028 int hs = view->child->begin_y;
1030 if (!view_is_fullscreen(view))
1031 view->child->begin_x = view_split_begin_x(view->begin_x);
1032 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1033 view->child->begin_x == 0) {
1034 ncols = COLS;
1036 view_fullscreen(view->child);
1037 if (view->child->focussed)
1038 show_panel(view->child->panel);
1039 else
1040 show_panel(view->panel);
1041 } else {
1042 ncols = view->child->begin_x;
1044 view_splitscreen(view->child);
1045 show_panel(view->child->panel);
1048 * XXX This is ugly and needs to be moved into the above
1049 * logic but "works" for now and my attempts at moving it
1050 * break either 'tab' or 'F' key maps in horizontal splits.
1052 if (hs) {
1053 err = view_splitscreen(view->child);
1054 if (err)
1055 return err;
1056 if (dif < 0) { /* top split decreased */
1057 err = offset_selection_down(view);
1058 if (err)
1059 return err;
1061 view_border(view);
1062 update_panels();
1063 doupdate();
1064 show_panel(view->child->panel);
1065 nlines = view->nlines;
1067 } else if (view->parent == NULL)
1068 ncols = COLS;
1070 if (view->resize && dif > 0) {
1071 err = view->resize(view, dif);
1072 if (err)
1073 return err;
1076 if (wresize(view->window, nlines, ncols) == ERR)
1077 return got_error_from_errno("wresize");
1078 if (replace_panel(view->panel, view->window) == ERR)
1079 return got_error_from_errno("replace_panel");
1080 wclear(view->window);
1082 view->nlines = nlines;
1083 view->ncols = ncols;
1084 view->lines = LINES;
1085 view->cols = COLS;
1087 return NULL;
1090 static const struct got_error *
1091 resize_log_view(struct tog_view *view, int increase)
1093 struct tog_log_view_state *s = &view->state.log;
1094 const struct got_error *err = NULL;
1095 int n = 0;
1097 if (s->selected_entry)
1098 n = s->selected_entry->idx + view->lines - s->selected;
1101 * Request commits to account for the increased
1102 * height so we have enough to populate the view.
1104 if (s->commits->ncommits < n) {
1105 view->nscrolled = n - s->commits->ncommits + increase + 1;
1106 err = request_log_commits(view);
1109 return err;
1112 static void
1113 view_adjust_offset(struct tog_view *view, int n)
1115 if (n == 0)
1116 return;
1118 if (view->parent && view->parent->offset) {
1119 if (view->parent->offset + n >= 0)
1120 view->parent->offset += n;
1121 else
1122 view->parent->offset = 0;
1123 } else if (view->offset) {
1124 if (view->offset - n >= 0)
1125 view->offset -= n;
1126 else
1127 view->offset = 0;
1131 static const struct got_error *
1132 view_resize_split(struct tog_view *view, int resize)
1134 const struct got_error *err = NULL;
1135 struct tog_view *v = NULL;
1137 if (view->parent)
1138 v = view->parent;
1139 else
1140 v = view;
1142 if (!v->child || !view_is_splitscreen(v->child))
1143 return NULL;
1145 v->resized = v->child->resized = resize; /* lock for resize event */
1147 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1148 if (v->child->resized_y)
1149 v->child->begin_y = v->child->resized_y;
1150 if (view->parent)
1151 v->child->begin_y -= resize;
1152 else
1153 v->child->begin_y += resize;
1154 if (v->child->begin_y < 3) {
1155 view->count = 0;
1156 v->child->begin_y = 3;
1157 } else if (v->child->begin_y > LINES - 1) {
1158 view->count = 0;
1159 v->child->begin_y = LINES - 1;
1161 v->ncols = COLS;
1162 v->child->ncols = COLS;
1163 view_adjust_offset(view, resize);
1164 err = view_init_hsplit(v, v->child->begin_y);
1165 if (err)
1166 return err;
1167 v->child->resized_y = v->child->begin_y;
1168 } else {
1169 if (v->child->resized_x)
1170 v->child->begin_x = v->child->resized_x;
1171 if (view->parent)
1172 v->child->begin_x -= resize;
1173 else
1174 v->child->begin_x += resize;
1175 if (v->child->begin_x < 11) {
1176 view->count = 0;
1177 v->child->begin_x = 11;
1178 } else if (v->child->begin_x > COLS - 1) {
1179 view->count = 0;
1180 v->child->begin_x = COLS - 1;
1182 v->child->resized_x = v->child->begin_x;
1185 v->child->mode = v->mode;
1186 v->child->nlines = v->lines - v->child->begin_y;
1187 v->child->ncols = v->cols - v->child->begin_x;
1188 v->focus_child = 1;
1190 err = view_fullscreen(v);
1191 if (err)
1192 return err;
1193 err = view_splitscreen(v->child);
1194 if (err)
1195 return err;
1197 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1198 err = offset_selection_down(v->child);
1199 if (err)
1200 return err;
1203 if (v->resize)
1204 err = v->resize(v, 0);
1205 else if (v->child->resize)
1206 err = v->child->resize(v->child, 0);
1208 v->resized = v->child->resized = 0;
1210 return err;
1213 static void
1214 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1216 struct tog_view *v = src->child ? src->child : src;
1218 dst->resized_x = v->resized_x;
1219 dst->resized_y = v->resized_y;
1222 static const struct got_error *
1223 view_close_child(struct tog_view *view)
1225 const struct got_error *err = NULL;
1227 if (view->child == NULL)
1228 return NULL;
1230 err = view_close(view->child);
1231 view->child = NULL;
1232 return err;
1235 static const struct got_error *
1236 view_set_child(struct tog_view *view, struct tog_view *child)
1238 const struct got_error *err = NULL;
1240 view->child = child;
1241 child->parent = view;
1243 err = view_resize(view);
1244 if (err)
1245 return err;
1247 if (view->child->resized_x || view->child->resized_y)
1248 err = view_resize_split(view, 0);
1250 return err;
1253 static const struct got_error *view_dispatch_request(struct tog_view **,
1254 struct tog_view *, enum tog_view_type, int, int);
1256 static const struct got_error *
1257 view_request_new(struct tog_view **requested, struct tog_view *view,
1258 enum tog_view_type request)
1260 struct tog_view *new_view = NULL;
1261 const struct got_error *err;
1262 int y = 0, x = 0;
1264 *requested = NULL;
1266 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1267 view_get_split(view, &y, &x);
1269 err = view_dispatch_request(&new_view, view, request, y, x);
1270 if (err)
1271 return err;
1273 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1274 request != TOG_VIEW_HELP) {
1275 err = view_init_hsplit(view, y);
1276 if (err)
1277 return err;
1280 view->focussed = 0;
1281 new_view->focussed = 1;
1282 new_view->mode = view->mode;
1283 new_view->nlines = request == TOG_VIEW_HELP ?
1284 view->lines : view->lines - y;
1286 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1287 view_transfer_size(new_view, view);
1288 err = view_close_child(view);
1289 if (err)
1290 return err;
1291 err = view_set_child(view, new_view);
1292 if (err)
1293 return err;
1294 view->focus_child = 1;
1295 } else
1296 *requested = new_view;
1298 return NULL;
1301 static void
1302 tog_resizeterm(void)
1304 int cols, lines;
1305 struct winsize size;
1307 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1308 cols = 80; /* Default */
1309 lines = 24;
1310 } else {
1311 cols = size.ws_col;
1312 lines = size.ws_row;
1314 resize_term(lines, cols);
1317 static const struct got_error *
1318 view_search_start(struct tog_view *view, int fast_refresh)
1320 const struct got_error *err = NULL;
1321 struct tog_view *v = view;
1322 char pattern[1024];
1323 int ret;
1325 if (view->search_started) {
1326 regfree(&view->regex);
1327 view->searching = 0;
1328 memset(&view->regmatch, 0, sizeof(view->regmatch));
1330 view->search_started = 0;
1332 if (view->nlines < 1)
1333 return NULL;
1335 if (view_is_hsplit_top(view))
1336 v = view->child;
1337 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1338 v = view->parent;
1340 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1341 wclrtoeol(v->window);
1343 nodelay(v->window, FALSE); /* block for search term input */
1344 nocbreak();
1345 echo();
1346 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1347 wrefresh(v->window);
1348 cbreak();
1349 noecho();
1350 nodelay(v->window, TRUE);
1351 if (!fast_refresh && !using_mock_io)
1352 halfdelay(10);
1353 if (ret == ERR)
1354 return NULL;
1356 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1357 err = view->search_start(view);
1358 if (err) {
1359 regfree(&view->regex);
1360 return err;
1362 view->search_started = 1;
1363 view->searching = TOG_SEARCH_FORWARD;
1364 view->search_next_done = 0;
1365 view->search_next(view);
1368 return NULL;
1371 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1372 static const struct got_error *
1373 switch_split(struct tog_view *view)
1375 const struct got_error *err = NULL;
1376 struct tog_view *v = NULL;
1378 if (view->parent)
1379 v = view->parent;
1380 else
1381 v = view;
1383 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1384 v->mode = TOG_VIEW_SPLIT_VERT;
1385 else
1386 v->mode = TOG_VIEW_SPLIT_HRZN;
1388 if (!v->child)
1389 return NULL;
1390 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1391 v->mode = TOG_VIEW_SPLIT_NONE;
1393 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1394 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1395 v->child->begin_y = v->child->resized_y;
1396 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1397 v->child->begin_x = v->child->resized_x;
1400 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1401 v->ncols = COLS;
1402 v->child->ncols = COLS;
1403 v->child->nscrolled = LINES - v->child->nlines;
1405 err = view_init_hsplit(v, v->child->begin_y);
1406 if (err)
1407 return err;
1409 v->child->mode = v->mode;
1410 v->child->nlines = v->lines - v->child->begin_y;
1411 v->focus_child = 1;
1413 err = view_fullscreen(v);
1414 if (err)
1415 return err;
1416 err = view_splitscreen(v->child);
1417 if (err)
1418 return err;
1420 if (v->mode == TOG_VIEW_SPLIT_NONE)
1421 v->mode = TOG_VIEW_SPLIT_VERT;
1422 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1423 err = offset_selection_down(v);
1424 if (err)
1425 return err;
1426 err = offset_selection_down(v->child);
1427 if (err)
1428 return err;
1429 } else {
1430 offset_selection_up(v);
1431 offset_selection_up(v->child);
1433 if (v->resize)
1434 err = v->resize(v, 0);
1435 else if (v->child->resize)
1436 err = v->child->resize(v->child, 0);
1438 return err;
1442 * Strip trailing whitespace from str starting at byte *n;
1443 * if *n < 0, use strlen(str). Return new str length in *n.
1445 static void
1446 strip_trailing_ws(char *str, int *n)
1448 size_t x = *n;
1450 if (str == NULL || *str == '\0')
1451 return;
1453 if (x < 0)
1454 x = strlen(str);
1456 while (x-- > 0 && isspace((unsigned char)str[x]))
1457 str[x] = '\0';
1459 *n = x + 1;
1463 * Extract visible substring of line y from the curses screen
1464 * and strip trailing whitespace. If vline is set, overwrite
1465 * line[vline] with '|' because the ACS_VLINE character is
1466 * written out as 'x'. Write the line to file f.
1468 static const struct got_error *
1469 view_write_line(FILE *f, int y, int vline)
1471 char line[COLS * MB_LEN_MAX]; /* allow for multibyte chars */
1472 int r, w;
1474 r = mvwinnstr(curscr, y, 0, line, sizeof(line));
1475 if (r == ERR)
1476 return got_error_fmt(GOT_ERR_RANGE,
1477 "failed to extract line %d", y);
1480 * In some views, lines are padded with blanks to COLS width.
1481 * Strip them so we can diff without the -b flag when testing.
1483 strip_trailing_ws(line, &r);
1485 if (vline > 0)
1486 line[vline] = '|';
1488 w = fprintf(f, "%s\n", line);
1489 if (w != r + 1) /* \n */
1490 return got_ferror(f, GOT_ERR_IO);
1492 return NULL;
1496 * Capture the visible curses screen by writing each line to the
1497 * file at the path set via the TOG_SCR_DUMP environment variable.
1499 static const struct got_error *
1500 screendump(struct tog_view *view)
1502 const struct got_error *err;
1503 int i;
1505 err = got_opentemp_truncate(tog_io.sdump);
1506 if (err)
1507 return err;
1509 if ((view->child && view->child->begin_x) ||
1510 (view->parent && view->begin_x)) {
1511 int ncols = view->child ? view->ncols : view->parent->ncols;
1513 /* vertical splitscreen */
1514 for (i = 0; i < view->nlines; ++i) {
1515 err = view_write_line(tog_io.sdump, i, ncols - 1);
1516 if (err)
1517 goto done;
1519 } else {
1520 int hline = 0;
1522 /* fullscreen or horizontal splitscreen */
1523 if ((view->child && view->child->begin_y) ||
1524 (view->parent && view->begin_y)) /* hsplit */
1525 hline = view->child ?
1526 view->child->begin_y : view->begin_y;
1528 for (i = 0; i < view->lines; i++) {
1529 if (hline && i == hline - 1) {
1530 int c;
1532 /* ACS_HLINE writes out as 'q', overwrite it */
1533 for (c = 0; c < view->cols; ++c)
1534 fputc('-', tog_io.sdump);
1535 fputc('\n', tog_io.sdump);
1536 continue;
1539 err = view_write_line(tog_io.sdump, i, 0);
1540 if (err)
1541 goto done;
1545 done:
1546 return err;
1550 * Compute view->count from numeric input. Assign total to view->count and
1551 * return first non-numeric key entered.
1553 static int
1554 get_compound_key(struct tog_view *view, int c)
1556 struct tog_view *v = view;
1557 int x, n = 0;
1559 if (view_is_hsplit_top(view))
1560 v = view->child;
1561 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1562 v = view->parent;
1564 view->count = 0;
1565 cbreak(); /* block for input */
1566 nodelay(view->window, FALSE);
1567 wmove(v->window, v->nlines - 1, 0);
1568 wclrtoeol(v->window);
1569 waddch(v->window, ':');
1571 do {
1572 x = getcurx(v->window);
1573 if (x != ERR && x < view->ncols) {
1574 waddch(v->window, c);
1575 wrefresh(v->window);
1579 * Don't overflow. Max valid request should be the greatest
1580 * between the longest and total lines; cap at 10 million.
1582 if (n >= 9999999)
1583 n = 9999999;
1584 else
1585 n = n * 10 + (c - '0');
1586 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1588 if (c == 'G' || c == 'g') { /* nG key map */
1589 view->gline = view->hiline = n;
1590 n = 0;
1591 c = 0;
1594 /* Massage excessive or inapplicable values at the input handler. */
1595 view->count = n;
1597 return c;
1600 static void
1601 action_report(struct tog_view *view)
1603 struct tog_view *v = view;
1605 if (view_is_hsplit_top(view))
1606 v = view->child;
1607 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1608 v = view->parent;
1610 wmove(v->window, v->nlines - 1, 0);
1611 wclrtoeol(v->window);
1612 wprintw(v->window, ":%s", view->action);
1613 wrefresh(v->window);
1616 * Clear action status report. Only clear in blame view
1617 * once annotating is complete, otherwise it's too fast.
1619 if (view->type == TOG_VIEW_BLAME) {
1620 if (view->state.blame.blame_complete)
1621 view->action = NULL;
1622 } else
1623 view->action = NULL;
1627 * Read the next line from the test script and assign
1628 * key instruction to *ch. If at EOF, set the *done flag.
1630 static const struct got_error *
1631 tog_read_script_key(FILE *script, struct tog_view *view, int *ch, int *done)
1633 const struct got_error *err = NULL;
1634 char *line = NULL;
1635 size_t linesz = 0;
1637 if (view->count && --view->count) {
1638 *ch = view->ch;
1639 return NULL;
1640 } else
1641 *ch = -1;
1643 if (getline(&line, &linesz, script) == -1) {
1644 if (feof(script)) {
1645 *done = 1;
1646 goto done;
1647 } else {
1648 err = got_ferror(script, GOT_ERR_IO);
1649 goto done;
1653 if (strncasecmp(line, "WAIT_FOR_UI", 11) == 0)
1654 tog_io.wait_for_ui = 1;
1655 else if (strncasecmp(line, "KEY_ENTER", 9) == 0)
1656 *ch = KEY_ENTER;
1657 else if (strncasecmp(line, "KEY_RIGHT", 9) == 0)
1658 *ch = KEY_RIGHT;
1659 else if (strncasecmp(line, "KEY_LEFT", 8) == 0)
1660 *ch = KEY_LEFT;
1661 else if (strncasecmp(line, "KEY_DOWN", 8) == 0)
1662 *ch = KEY_DOWN;
1663 else if (strncasecmp(line, "KEY_UP", 6) == 0)
1664 *ch = KEY_UP;
1665 else if (strncasecmp(line, "TAB", 3) == 0)
1666 *ch = '\t';
1667 else if (strncasecmp(line, "SCREENDUMP", 10) == 0)
1668 *ch = TOG_KEY_SCRDUMP;
1669 else if (isdigit((unsigned char)*line)) {
1670 char *t = line;
1672 while (isdigit((unsigned char)*t))
1673 ++t;
1674 view->ch = *ch = *t;
1675 *t = '\0';
1676 /* ignore error, view->count is 0 if instruction is invalid */
1677 view->count = strtonum(line, 0, INT_MAX, NULL);
1678 } else
1679 *ch = *line;
1681 done:
1682 free(line);
1683 return err;
1686 static const struct got_error *
1687 view_input(struct tog_view **new, int *done, struct tog_view *view,
1688 struct tog_view_list_head *views, int fast_refresh)
1690 const struct got_error *err = NULL;
1691 struct tog_view *v;
1692 int ch, errcode;
1694 *new = NULL;
1696 if (view->action)
1697 action_report(view);
1699 /* Clear "no matches" indicator. */
1700 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1701 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1702 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1703 view->count = 0;
1706 if (view->searching && !view->search_next_done) {
1707 errcode = pthread_mutex_unlock(&tog_mutex);
1708 if (errcode)
1709 return got_error_set_errno(errcode,
1710 "pthread_mutex_unlock");
1711 sched_yield();
1712 errcode = pthread_mutex_lock(&tog_mutex);
1713 if (errcode)
1714 return got_error_set_errno(errcode,
1715 "pthread_mutex_lock");
1716 view->search_next(view);
1717 return NULL;
1720 /* Allow threads to make progress while we are waiting for input. */
1721 errcode = pthread_mutex_unlock(&tog_mutex);
1722 if (errcode)
1723 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1725 if (using_mock_io) {
1726 err = tog_read_script_key(tog_io.f, view, &ch, done);
1727 if (err) {
1728 errcode = pthread_mutex_lock(&tog_mutex);
1729 return err;
1731 } else if (view->count && --view->count) {
1732 cbreak();
1733 nodelay(view->window, TRUE);
1734 ch = wgetch(view->window);
1735 /* let C-g or backspace abort unfinished count */
1736 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1737 view->count = 0;
1738 else
1739 ch = view->ch;
1740 } else {
1741 ch = wgetch(view->window);
1742 if (ch >= '1' && ch <= '9')
1743 view->ch = ch = get_compound_key(view, ch);
1745 if (view->hiline && ch != ERR && ch != 0)
1746 view->hiline = 0; /* key pressed, clear line highlight */
1747 nodelay(view->window, TRUE);
1748 errcode = pthread_mutex_lock(&tog_mutex);
1749 if (errcode)
1750 return got_error_set_errno(errcode, "pthread_mutex_lock");
1752 if (tog_sigwinch_received || tog_sigcont_received) {
1753 tog_resizeterm();
1754 tog_sigwinch_received = 0;
1755 tog_sigcont_received = 0;
1756 TAILQ_FOREACH(v, views, entry) {
1757 err = view_resize(v);
1758 if (err)
1759 return err;
1760 err = v->input(new, v, KEY_RESIZE);
1761 if (err)
1762 return err;
1763 if (v->child) {
1764 err = view_resize(v->child);
1765 if (err)
1766 return err;
1767 err = v->child->input(new, v->child,
1768 KEY_RESIZE);
1769 if (err)
1770 return err;
1771 if (v->child->resized_x || v->child->resized_y) {
1772 err = view_resize_split(v, 0);
1773 if (err)
1774 return err;
1780 switch (ch) {
1781 case '?':
1782 case 'H':
1783 case KEY_F(1):
1784 if (view->type == TOG_VIEW_HELP)
1785 err = view->reset(view);
1786 else
1787 err = view_request_new(new, view, TOG_VIEW_HELP);
1788 break;
1789 case '\t':
1790 view->count = 0;
1791 if (view->child) {
1792 view->focussed = 0;
1793 view->child->focussed = 1;
1794 view->focus_child = 1;
1795 } else if (view->parent) {
1796 view->focussed = 0;
1797 view->parent->focussed = 1;
1798 view->parent->focus_child = 0;
1799 if (!view_is_splitscreen(view)) {
1800 if (view->parent->resize) {
1801 err = view->parent->resize(view->parent,
1802 0);
1803 if (err)
1804 return err;
1806 offset_selection_up(view->parent);
1807 err = view_fullscreen(view->parent);
1808 if (err)
1809 return err;
1812 break;
1813 case 'q':
1814 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1815 if (view->parent->resize) {
1816 /* might need more commits to fill fullscreen */
1817 err = view->parent->resize(view->parent, 0);
1818 if (err)
1819 break;
1821 offset_selection_up(view->parent);
1823 err = view->input(new, view, ch);
1824 view->dying = 1;
1825 break;
1826 case 'Q':
1827 *done = 1;
1828 break;
1829 case 'F':
1830 view->count = 0;
1831 if (view_is_parent_view(view)) {
1832 if (view->child == NULL)
1833 break;
1834 if (view_is_splitscreen(view->child)) {
1835 view->focussed = 0;
1836 view->child->focussed = 1;
1837 err = view_fullscreen(view->child);
1838 } else {
1839 err = view_splitscreen(view->child);
1840 if (!err)
1841 err = view_resize_split(view, 0);
1843 if (err)
1844 break;
1845 err = view->child->input(new, view->child,
1846 KEY_RESIZE);
1847 } else {
1848 if (view_is_splitscreen(view)) {
1849 view->parent->focussed = 0;
1850 view->focussed = 1;
1851 err = view_fullscreen(view);
1852 } else {
1853 err = view_splitscreen(view);
1854 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1855 err = view_resize(view->parent);
1856 if (!err)
1857 err = view_resize_split(view, 0);
1859 if (err)
1860 break;
1861 err = view->input(new, view, KEY_RESIZE);
1863 if (err)
1864 break;
1865 if (view->resize) {
1866 err = view->resize(view, 0);
1867 if (err)
1868 break;
1870 if (view->parent) {
1871 if (view->parent->resize) {
1872 err = view->parent->resize(view->parent, 0);
1873 if (err != NULL)
1874 break;
1876 err = offset_selection_down(view->parent);
1877 if (err != NULL)
1878 break;
1880 err = offset_selection_down(view);
1881 break;
1882 case 'S':
1883 view->count = 0;
1884 err = switch_split(view);
1885 break;
1886 case '-':
1887 err = view_resize_split(view, -1);
1888 break;
1889 case '+':
1890 err = view_resize_split(view, 1);
1891 break;
1892 case KEY_RESIZE:
1893 break;
1894 case '/':
1895 view->count = 0;
1896 if (view->search_start)
1897 view_search_start(view, fast_refresh);
1898 else
1899 err = view->input(new, view, ch);
1900 break;
1901 case 'N':
1902 case 'n':
1903 if (view->search_started && view->search_next) {
1904 view->searching = (ch == 'n' ?
1905 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1906 view->search_next_done = 0;
1907 view->search_next(view);
1908 } else
1909 err = view->input(new, view, ch);
1910 break;
1911 case 'A':
1912 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1913 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1914 view->action = "Patience diff algorithm";
1915 } else {
1916 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1917 view->action = "Myers diff algorithm";
1919 TAILQ_FOREACH(v, views, entry) {
1920 if (v->reset) {
1921 err = v->reset(v);
1922 if (err)
1923 return err;
1925 if (v->child && v->child->reset) {
1926 err = v->child->reset(v->child);
1927 if (err)
1928 return err;
1931 break;
1932 case TOG_KEY_SCRDUMP:
1933 err = screendump(view);
1934 break;
1935 default:
1936 err = view->input(new, view, ch);
1937 break;
1940 return err;
1943 static int
1944 view_needs_focus_indication(struct tog_view *view)
1946 if (view_is_parent_view(view)) {
1947 if (view->child == NULL || view->child->focussed)
1948 return 0;
1949 if (!view_is_splitscreen(view->child))
1950 return 0;
1951 } else if (!view_is_splitscreen(view))
1952 return 0;
1954 return view->focussed;
1957 static const struct got_error *
1958 tog_io_close(void)
1960 const struct got_error *err = NULL;
1962 if (tog_io.cin && fclose(tog_io.cin) == EOF)
1963 err = got_ferror(tog_io.cin, GOT_ERR_IO);
1964 if (tog_io.cout && fclose(tog_io.cout) == EOF && err == NULL)
1965 err = got_ferror(tog_io.cout, GOT_ERR_IO);
1966 if (tog_io.f && fclose(tog_io.f) == EOF && err == NULL)
1967 err = got_ferror(tog_io.f, GOT_ERR_IO);
1968 if (tog_io.sdump && fclose(tog_io.sdump) == EOF && err == NULL)
1969 err = got_ferror(tog_io.sdump, GOT_ERR_IO);
1971 return err;
1974 static const struct got_error *
1975 view_loop(struct tog_view *view)
1977 const struct got_error *err = NULL;
1978 struct tog_view_list_head views;
1979 struct tog_view *new_view;
1980 char *mode;
1981 int fast_refresh = 10;
1982 int done = 0, errcode;
1984 mode = getenv("TOG_VIEW_SPLIT_MODE");
1985 if (!mode || !(*mode == 'h' || *mode == 'H'))
1986 view->mode = TOG_VIEW_SPLIT_VERT;
1987 else
1988 view->mode = TOG_VIEW_SPLIT_HRZN;
1990 errcode = pthread_mutex_lock(&tog_mutex);
1991 if (errcode)
1992 return got_error_set_errno(errcode, "pthread_mutex_lock");
1994 TAILQ_INIT(&views);
1995 TAILQ_INSERT_HEAD(&views, view, entry);
1997 view->focussed = 1;
1998 err = view->show(view);
1999 if (err)
2000 return err;
2001 update_panels();
2002 doupdate();
2003 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
2004 !tog_fatal_signal_received()) {
2005 /* Refresh fast during initialization, then become slower. */
2006 if (fast_refresh && --fast_refresh == 0 && !using_mock_io)
2007 halfdelay(10); /* switch to once per second */
2009 err = view_input(&new_view, &done, view, &views, fast_refresh);
2010 if (err)
2011 break;
2013 if (view->dying && view == TAILQ_FIRST(&views) &&
2014 TAILQ_NEXT(view, entry) == NULL)
2015 done = 1;
2016 if (done) {
2017 struct tog_view *v;
2020 * When we quit, scroll the screen up a single line
2021 * so we don't lose any information.
2023 TAILQ_FOREACH(v, &views, entry) {
2024 wmove(v->window, 0, 0);
2025 wdeleteln(v->window);
2026 wnoutrefresh(v->window);
2027 if (v->child && !view_is_fullscreen(v)) {
2028 wmove(v->child->window, 0, 0);
2029 wdeleteln(v->child->window);
2030 wnoutrefresh(v->child->window);
2033 doupdate();
2036 if (view->dying) {
2037 struct tog_view *v, *prev = NULL;
2039 if (view_is_parent_view(view))
2040 prev = TAILQ_PREV(view, tog_view_list_head,
2041 entry);
2042 else if (view->parent)
2043 prev = view->parent;
2045 if (view->parent) {
2046 view->parent->child = NULL;
2047 view->parent->focus_child = 0;
2048 /* Restore fullscreen line height. */
2049 view->parent->nlines = view->parent->lines;
2050 err = view_resize(view->parent);
2051 if (err)
2052 break;
2053 /* Make resized splits persist. */
2054 view_transfer_size(view->parent, view);
2055 } else
2056 TAILQ_REMOVE(&views, view, entry);
2058 err = view_close(view);
2059 if (err)
2060 goto done;
2062 view = NULL;
2063 TAILQ_FOREACH(v, &views, entry) {
2064 if (v->focussed)
2065 break;
2067 if (view == NULL && new_view == NULL) {
2068 /* No view has focus. Try to pick one. */
2069 if (prev)
2070 view = prev;
2071 else if (!TAILQ_EMPTY(&views)) {
2072 view = TAILQ_LAST(&views,
2073 tog_view_list_head);
2075 if (view) {
2076 if (view->focus_child) {
2077 view->child->focussed = 1;
2078 view = view->child;
2079 } else
2080 view->focussed = 1;
2084 if (new_view) {
2085 struct tog_view *v, *t;
2086 /* Only allow one parent view per type. */
2087 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2088 if (v->type != new_view->type)
2089 continue;
2090 TAILQ_REMOVE(&views, v, entry);
2091 err = view_close(v);
2092 if (err)
2093 goto done;
2094 break;
2096 TAILQ_INSERT_TAIL(&views, new_view, entry);
2097 view = new_view;
2099 if (view && !done) {
2100 if (view_is_parent_view(view)) {
2101 if (view->child && view->child->focussed)
2102 view = view->child;
2103 } else {
2104 if (view->parent && view->parent->focussed)
2105 view = view->parent;
2107 show_panel(view->panel);
2108 if (view->child && view_is_splitscreen(view->child))
2109 show_panel(view->child->panel);
2110 if (view->parent && view_is_splitscreen(view)) {
2111 err = view->parent->show(view->parent);
2112 if (err)
2113 goto done;
2115 err = view->show(view);
2116 if (err)
2117 goto done;
2118 if (view->child) {
2119 err = view->child->show(view->child);
2120 if (err)
2121 goto done;
2123 update_panels();
2124 doupdate();
2127 done:
2128 while (!TAILQ_EMPTY(&views)) {
2129 const struct got_error *close_err;
2130 view = TAILQ_FIRST(&views);
2131 TAILQ_REMOVE(&views, view, entry);
2132 close_err = view_close(view);
2133 if (close_err && err == NULL)
2134 err = close_err;
2137 errcode = pthread_mutex_unlock(&tog_mutex);
2138 if (errcode && err == NULL)
2139 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2141 return err;
2144 __dead static void
2145 usage_log(void)
2147 endwin();
2148 fprintf(stderr,
2149 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2150 getprogname());
2151 exit(1);
2154 /* Create newly allocated wide-character string equivalent to a byte string. */
2155 static const struct got_error *
2156 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2158 char *vis = NULL;
2159 const struct got_error *err = NULL;
2161 *ws = NULL;
2162 *wlen = mbstowcs(NULL, s, 0);
2163 if (*wlen == (size_t)-1) {
2164 int vislen;
2165 if (errno != EILSEQ)
2166 return got_error_from_errno("mbstowcs");
2168 /* byte string invalid in current encoding; try to "fix" it */
2169 err = got_mbsavis(&vis, &vislen, s);
2170 if (err)
2171 return err;
2172 *wlen = mbstowcs(NULL, vis, 0);
2173 if (*wlen == (size_t)-1) {
2174 err = got_error_from_errno("mbstowcs"); /* give up */
2175 goto done;
2179 *ws = calloc(*wlen + 1, sizeof(**ws));
2180 if (*ws == NULL) {
2181 err = got_error_from_errno("calloc");
2182 goto done;
2185 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2186 err = got_error_from_errno("mbstowcs");
2187 done:
2188 free(vis);
2189 if (err) {
2190 free(*ws);
2191 *ws = NULL;
2192 *wlen = 0;
2194 return err;
2197 static const struct got_error *
2198 expand_tab(char **ptr, const char *src)
2200 char *dst;
2201 size_t len, n, idx = 0, sz = 0;
2203 *ptr = NULL;
2204 n = len = strlen(src);
2205 dst = malloc(n + 1);
2206 if (dst == NULL)
2207 return got_error_from_errno("malloc");
2209 while (idx < len && src[idx]) {
2210 const char c = src[idx];
2212 if (c == '\t') {
2213 size_t nb = TABSIZE - sz % TABSIZE;
2214 char *p;
2216 p = realloc(dst, n + nb);
2217 if (p == NULL) {
2218 free(dst);
2219 return got_error_from_errno("realloc");
2222 dst = p;
2223 n += nb;
2224 memset(dst + sz, ' ', nb);
2225 sz += nb;
2226 } else
2227 dst[sz++] = src[idx];
2228 ++idx;
2231 dst[sz] = '\0';
2232 *ptr = dst;
2233 return NULL;
2237 * Advance at most n columns from wline starting at offset off.
2238 * Return the index to the first character after the span operation.
2239 * Return the combined column width of all spanned wide characters in
2240 * *rcol.
2242 static int
2243 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2245 int width, i, cols = 0;
2247 if (n == 0) {
2248 *rcol = cols;
2249 return off;
2252 for (i = off; wline[i] != L'\0'; ++i) {
2253 if (wline[i] == L'\t')
2254 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2255 else
2256 width = wcwidth(wline[i]);
2258 if (width == -1) {
2259 width = 1;
2260 wline[i] = L'.';
2263 if (cols + width > n)
2264 break;
2265 cols += width;
2268 *rcol = cols;
2269 return i;
2273 * Format a line for display, ensuring that it won't overflow a width limit.
2274 * With scrolling, the width returned refers to the scrolled version of the
2275 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2277 static const struct got_error *
2278 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2279 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2281 const struct got_error *err = NULL;
2282 int cols;
2283 wchar_t *wline = NULL;
2284 char *exstr = NULL;
2285 size_t wlen;
2286 int i, scrollx;
2288 *wlinep = NULL;
2289 *widthp = 0;
2291 if (expand) {
2292 err = expand_tab(&exstr, line);
2293 if (err)
2294 return err;
2297 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2298 free(exstr);
2299 if (err)
2300 return err;
2302 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2304 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2305 wline[wlen - 1] = L'\0';
2306 wlen--;
2308 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2309 wline[wlen - 1] = L'\0';
2310 wlen--;
2313 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2314 wline[i] = L'\0';
2316 if (widthp)
2317 *widthp = cols;
2318 if (scrollxp)
2319 *scrollxp = scrollx;
2320 if (err)
2321 free(wline);
2322 else
2323 *wlinep = wline;
2324 return err;
2327 static const struct got_error*
2328 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2329 struct got_object_id *id, struct got_repository *repo)
2331 static const struct got_error *err = NULL;
2332 struct got_reflist_entry *re;
2333 char *s;
2334 const char *name;
2336 *refs_str = NULL;
2338 if (refs == NULL)
2339 return NULL;
2341 TAILQ_FOREACH(re, refs, entry) {
2342 struct got_tag_object *tag = NULL;
2343 struct got_object_id *ref_id;
2344 int cmp;
2346 name = got_ref_get_name(re->ref);
2347 if (strcmp(name, GOT_REF_HEAD) == 0)
2348 continue;
2349 if (strncmp(name, "refs/", 5) == 0)
2350 name += 5;
2351 if (strncmp(name, "got/", 4) == 0)
2352 continue;
2353 if (strncmp(name, "heads/", 6) == 0)
2354 name += 6;
2355 if (strncmp(name, "remotes/", 8) == 0) {
2356 name += 8;
2357 s = strstr(name, "/" GOT_REF_HEAD);
2358 if (s != NULL && strcmp(s, "/" GOT_REF_HEAD) == 0)
2359 continue;
2361 err = got_ref_resolve(&ref_id, repo, re->ref);
2362 if (err)
2363 break;
2364 if (strncmp(name, "tags/", 5) == 0) {
2365 err = got_object_open_as_tag(&tag, repo, ref_id);
2366 if (err) {
2367 if (err->code != GOT_ERR_OBJ_TYPE) {
2368 free(ref_id);
2369 break;
2371 /* Ref points at something other than a tag. */
2372 err = NULL;
2373 tag = NULL;
2376 cmp = got_object_id_cmp(tag ?
2377 got_object_tag_get_object_id(tag) : ref_id, id);
2378 free(ref_id);
2379 if (tag)
2380 got_object_tag_close(tag);
2381 if (cmp != 0)
2382 continue;
2383 s = *refs_str;
2384 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2385 s ? ", " : "", name) == -1) {
2386 err = got_error_from_errno("asprintf");
2387 free(s);
2388 *refs_str = NULL;
2389 break;
2391 free(s);
2394 return err;
2397 static const struct got_error *
2398 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2399 int col_tab_align)
2401 char *smallerthan;
2403 smallerthan = strchr(author, '<');
2404 if (smallerthan && smallerthan[1] != '\0')
2405 author = smallerthan + 1;
2406 author[strcspn(author, "@>")] = '\0';
2407 return format_line(wauthor, author_width, NULL, author, 0, limit,
2408 col_tab_align, 0);
2411 static const struct got_error *
2412 draw_commit(struct tog_view *view, struct commit_queue_entry *entry,
2413 const size_t date_display_cols, int author_display_cols)
2415 struct tog_log_view_state *s = &view->state.log;
2416 const struct got_error *err = NULL;
2417 struct got_commit_object *commit = entry->commit;
2418 struct got_object_id *id = entry->id;
2419 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2420 char *refs_str = NULL;
2421 char *logmsg0 = NULL, *logmsg = NULL;
2422 char *author = NULL;
2423 wchar_t *wrefstr = NULL, *wlogmsg = NULL, *wauthor = NULL;
2424 int author_width, refstr_width, logmsg_width;
2425 char *newline, *line = NULL;
2426 int col, limit, scrollx, logmsg_x;
2427 const int avail = view->ncols, marker_column = author_display_cols + 1;
2428 struct tm tm;
2429 time_t committer_time;
2430 struct tog_color *tc;
2431 struct got_reflist_head *refs;
2433 if (tog_base_commit.id != NULL && tog_base_commit.idx == -1 &&
2434 got_object_id_cmp(id, tog_base_commit.id) == 0)
2435 tog_base_commit.idx = entry->idx;
2436 if (tog_io.wait_for_ui && s->thread_args.need_commit_marker) {
2437 int rc;
2439 rc = pthread_cond_wait(&s->thread_args.log_loaded, &tog_mutex);
2440 if (rc)
2441 return got_error_set_errno(rc, "pthread_cond_wait");
2444 committer_time = got_object_commit_get_committer_time(commit);
2445 if (gmtime_r(&committer_time, &tm) == NULL)
2446 return got_error_from_errno("gmtime_r");
2447 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2448 return got_error(GOT_ERR_NO_SPACE);
2450 if (avail <= date_display_cols)
2451 limit = MIN(sizeof(datebuf) - 1, avail);
2452 else
2453 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2454 tc = get_color(&s->colors, TOG_COLOR_DATE);
2455 if (tc)
2456 wattr_on(view->window,
2457 COLOR_PAIR(tc->colorpair), NULL);
2458 waddnstr(view->window, datebuf, limit);
2459 if (tc)
2460 wattr_off(view->window,
2461 COLOR_PAIR(tc->colorpair), NULL);
2462 col = limit;
2463 if (col > avail)
2464 goto done;
2466 if (avail >= 120) {
2467 char *id_str;
2468 err = got_object_id_str(&id_str, id);
2469 if (err)
2470 goto done;
2471 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2472 if (tc)
2473 wattr_on(view->window,
2474 COLOR_PAIR(tc->colorpair), NULL);
2475 wprintw(view->window, "%.8s ", id_str);
2476 if (tc)
2477 wattr_off(view->window,
2478 COLOR_PAIR(tc->colorpair), NULL);
2479 free(id_str);
2480 col += 9;
2481 if (col > avail)
2482 goto done;
2485 if (s->use_committer)
2486 author = strdup(got_object_commit_get_committer(commit));
2487 else
2488 author = strdup(got_object_commit_get_author(commit));
2489 if (author == NULL) {
2490 err = got_error_from_errno("strdup");
2491 goto done;
2493 err = format_author(&wauthor, &author_width, author, avail - col, col);
2494 if (err)
2495 goto done;
2496 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2497 if (tc)
2498 wattr_on(view->window,
2499 COLOR_PAIR(tc->colorpair), NULL);
2500 waddwstr(view->window, wauthor);
2501 col += author_width;
2502 while (col < avail && author_width < author_display_cols + 2) {
2503 if (tog_base_commit.marker != GOT_WORKTREE_STATE_UNKNOWN &&
2504 author_width == marker_column &&
2505 entry->idx == tog_base_commit.idx) {
2506 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2507 if (tc)
2508 wattr_on(view->window,
2509 COLOR_PAIR(tc->colorpair), NULL);
2510 waddch(view->window, tog_base_commit.marker);
2511 if (tc)
2512 wattr_off(view->window,
2513 COLOR_PAIR(tc->colorpair), NULL);
2514 } else
2515 waddch(view->window, ' ');
2516 col++;
2517 author_width++;
2519 if (tc)
2520 wattr_off(view->window,
2521 COLOR_PAIR(tc->colorpair), NULL);
2522 if (col > avail)
2523 goto done;
2525 err = got_object_commit_get_logmsg(&logmsg0, commit);
2526 if (err)
2527 goto done;
2528 logmsg = logmsg0;
2529 while (*logmsg == '\n')
2530 logmsg++;
2531 newline = strchr(logmsg, '\n');
2532 if (newline)
2533 *newline = '\0';
2535 limit = avail - col;
2536 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2537 limit--; /* for the border */
2539 /* Prepend reference labels to log message if possible .*/
2540 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, id);
2541 err = build_refs_str(&refs_str, refs, id, s->repo);
2542 if (err)
2543 goto done;
2544 if (refs_str) {
2545 char *rs;
2547 if (asprintf(&rs, "[%s]", refs_str) == -1) {
2548 err = got_error_from_errno("asprintf");
2549 goto done;
2551 err = format_line(&wrefstr, &refstr_width,
2552 &scrollx, rs, view->x, limit, col, 1);
2553 free(rs);
2554 if (err)
2555 goto done;
2556 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2557 if (tc)
2558 wattr_on(view->window,
2559 COLOR_PAIR(tc->colorpair), NULL);
2560 waddwstr(view->window, &wrefstr[scrollx]);
2561 if (tc)
2562 wattr_off(view->window,
2563 COLOR_PAIR(tc->colorpair), NULL);
2564 col += MAX(refstr_width, 0);
2565 if (col > avail)
2566 goto done;
2568 if (col < avail) {
2569 waddch(view->window, ' ');
2570 col++;
2573 if (refstr_width > 0)
2574 logmsg_x = 0;
2575 else {
2576 int unscrolled_refstr_width;
2577 size_t len = wcslen(wrefstr);
2580 * No need to check for -1 return value here since
2581 * unprintables have been replaced by span_wline().
2583 unscrolled_refstr_width = wcswidth(wrefstr, len);
2584 unscrolled_refstr_width += 1; /* trailing space */
2585 logmsg_x = view->x - unscrolled_refstr_width;
2588 limit = avail - col;
2589 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2590 limit--; /* for the border */
2591 } else
2592 logmsg_x = view->x;
2594 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, logmsg_x,
2595 limit, col, 1);
2596 if (err)
2597 goto done;
2598 waddwstr(view->window, &wlogmsg[scrollx]);
2599 col += MAX(logmsg_width, 0);
2600 while (col < avail) {
2601 waddch(view->window, ' ');
2602 col++;
2604 done:
2605 free(logmsg0);
2606 free(wlogmsg);
2607 free(wrefstr);
2608 free(refs_str);
2609 free(author);
2610 free(wauthor);
2611 free(line);
2612 return err;
2615 static struct commit_queue_entry *
2616 alloc_commit_queue_entry(struct got_commit_object *commit,
2617 struct got_object_id *id)
2619 struct commit_queue_entry *entry;
2620 struct got_object_id *dup;
2622 entry = calloc(1, sizeof(*entry));
2623 if (entry == NULL)
2624 return NULL;
2626 dup = got_object_id_dup(id);
2627 if (dup == NULL) {
2628 free(entry);
2629 return NULL;
2632 entry->id = dup;
2633 entry->commit = commit;
2634 return entry;
2637 static void
2638 pop_commit(struct commit_queue *commits)
2640 struct commit_queue_entry *entry;
2642 entry = TAILQ_FIRST(&commits->head);
2643 TAILQ_REMOVE(&commits->head, entry, entry);
2644 got_object_commit_close(entry->commit);
2645 commits->ncommits--;
2646 free(entry->id);
2647 free(entry);
2650 static void
2651 free_commits(struct commit_queue *commits)
2653 while (!TAILQ_EMPTY(&commits->head))
2654 pop_commit(commits);
2657 static const struct got_error *
2658 match_commit(int *have_match, struct got_object_id *id,
2659 struct got_commit_object *commit, regex_t *regex)
2661 const struct got_error *err = NULL;
2662 regmatch_t regmatch;
2663 char *id_str = NULL, *logmsg = NULL;
2665 *have_match = 0;
2667 err = got_object_id_str(&id_str, id);
2668 if (err)
2669 return err;
2671 err = got_object_commit_get_logmsg(&logmsg, commit);
2672 if (err)
2673 goto done;
2675 if (regexec(regex, got_object_commit_get_author(commit), 1,
2676 &regmatch, 0) == 0 ||
2677 regexec(regex, got_object_commit_get_committer(commit), 1,
2678 &regmatch, 0) == 0 ||
2679 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2680 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2681 *have_match = 1;
2682 done:
2683 free(id_str);
2684 free(logmsg);
2685 return err;
2688 static const struct got_error *
2689 queue_commits(struct tog_log_thread_args *a)
2691 const struct got_error *err = NULL;
2694 * We keep all commits open throughout the lifetime of the log
2695 * view in order to avoid having to re-fetch commits from disk
2696 * while updating the display.
2698 do {
2699 struct got_object_id id;
2700 struct got_commit_object *commit;
2701 struct commit_queue_entry *entry;
2702 int limit_match = 0;
2703 int errcode;
2705 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2706 NULL, NULL);
2707 if (err)
2708 break;
2710 err = got_object_open_as_commit(&commit, a->repo, &id);
2711 if (err)
2712 break;
2713 entry = alloc_commit_queue_entry(commit, &id);
2714 if (entry == NULL) {
2715 err = got_error_from_errno("alloc_commit_queue_entry");
2716 break;
2719 errcode = pthread_mutex_lock(&tog_mutex);
2720 if (errcode) {
2721 err = got_error_set_errno(errcode,
2722 "pthread_mutex_lock");
2723 break;
2726 entry->idx = a->real_commits->ncommits;
2727 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2728 a->real_commits->ncommits++;
2730 if (*a->limiting) {
2731 err = match_commit(&limit_match, &id, commit,
2732 a->limit_regex);
2733 if (err)
2734 break;
2736 if (limit_match) {
2737 struct commit_queue_entry *matched;
2739 matched = alloc_commit_queue_entry(
2740 entry->commit, entry->id);
2741 if (matched == NULL) {
2742 err = got_error_from_errno(
2743 "alloc_commit_queue_entry");
2744 break;
2746 matched->commit = entry->commit;
2747 got_object_commit_retain(entry->commit);
2749 matched->idx = a->limit_commits->ncommits;
2750 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2751 matched, entry);
2752 a->limit_commits->ncommits++;
2756 * This is how we signal log_thread() that we
2757 * have found a match, and that it should be
2758 * counted as a new entry for the view.
2760 a->limit_match = limit_match;
2763 if (*a->searching == TOG_SEARCH_FORWARD &&
2764 !*a->search_next_done) {
2765 int have_match;
2766 err = match_commit(&have_match, &id, commit, a->regex);
2767 if (err)
2768 break;
2770 if (*a->limiting) {
2771 if (limit_match && have_match)
2772 *a->search_next_done =
2773 TOG_SEARCH_HAVE_MORE;
2774 } else if (have_match)
2775 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2778 errcode = pthread_mutex_unlock(&tog_mutex);
2779 if (errcode && err == NULL)
2780 err = got_error_set_errno(errcode,
2781 "pthread_mutex_unlock");
2782 if (err)
2783 break;
2784 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2786 return err;
2789 static void
2790 select_commit(struct tog_log_view_state *s)
2792 struct commit_queue_entry *entry;
2793 int ncommits = 0;
2795 entry = s->first_displayed_entry;
2796 while (entry) {
2797 if (ncommits == s->selected) {
2798 s->selected_entry = entry;
2799 break;
2801 entry = TAILQ_NEXT(entry, entry);
2802 ncommits++;
2806 static const struct got_error *
2807 draw_commits(struct tog_view *view)
2809 const struct got_error *err = NULL;
2810 struct tog_log_view_state *s = &view->state.log;
2811 struct commit_queue_entry *entry = s->selected_entry;
2812 int limit = view->nlines;
2813 int width;
2814 int ncommits, author_cols = 4, refstr_cols;
2815 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2816 char *refs_str = NULL;
2817 wchar_t *wline;
2818 struct tog_color *tc;
2819 static const size_t date_display_cols = 12;
2820 struct got_reflist_head *refs;
2822 if (view_is_hsplit_top(view))
2823 --limit; /* account for border */
2825 if (s->selected_entry &&
2826 !(view->searching && view->search_next_done == 0)) {
2827 err = got_object_id_str(&id_str, s->selected_entry->id);
2828 if (err)
2829 return err;
2830 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2831 s->selected_entry->id);
2832 err = build_refs_str(&refs_str, refs, s->selected_entry->id,
2833 s->repo);
2834 if (err)
2835 goto done;
2838 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2839 halfdelay(10); /* disable fast refresh */
2841 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2842 if (asprintf(&ncommits_str, " [%d/%d] %s",
2843 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2844 (view->searching && !view->search_next_done) ?
2845 "searching..." : "loading...") == -1) {
2846 err = got_error_from_errno("asprintf");
2847 goto done;
2849 } else {
2850 const char *search_str = NULL;
2851 const char *limit_str = NULL;
2853 if (view->searching) {
2854 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2855 search_str = "no more matches";
2856 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2857 search_str = "no matches found";
2858 else if (!view->search_next_done)
2859 search_str = "searching...";
2862 if (s->limit_view && s->commits->ncommits == 0)
2863 limit_str = "no matches found";
2865 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2866 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2867 search_str ? search_str : (refs_str ? refs_str : ""),
2868 limit_str ? limit_str : "") == -1) {
2869 err = got_error_from_errno("asprintf");
2870 goto done;
2874 free(refs_str);
2875 refs_str = NULL;
2877 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2878 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2879 "........................................",
2880 s->in_repo_path, ncommits_str) == -1) {
2881 err = got_error_from_errno("asprintf");
2882 header = NULL;
2883 goto done;
2885 } else if (asprintf(&header, "commit %s%s",
2886 id_str ? id_str : "........................................",
2887 ncommits_str) == -1) {
2888 err = got_error_from_errno("asprintf");
2889 header = NULL;
2890 goto done;
2892 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2893 if (err)
2894 goto done;
2896 werase(view->window);
2898 if (view_needs_focus_indication(view))
2899 wstandout(view->window);
2900 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2901 if (tc)
2902 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2903 waddwstr(view->window, wline);
2904 while (width < view->ncols) {
2905 waddch(view->window, ' ');
2906 width++;
2908 if (tc)
2909 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2910 if (view_needs_focus_indication(view))
2911 wstandend(view->window);
2912 free(wline);
2913 if (limit <= 1)
2914 goto done;
2916 /* Grow author column size if necessary, and set view->maxx. */
2917 entry = s->first_displayed_entry;
2918 ncommits = 0;
2919 view->maxx = 0;
2920 while (entry) {
2921 struct got_commit_object *c = entry->commit;
2922 char *author, *eol, *msg, *msg0;
2923 wchar_t *wauthor, *wmsg;
2924 int width;
2925 if (ncommits >= limit - 1)
2926 break;
2927 if (s->use_committer)
2928 author = strdup(got_object_commit_get_committer(c));
2929 else
2930 author = strdup(got_object_commit_get_author(c));
2931 if (author == NULL) {
2932 err = got_error_from_errno("strdup");
2933 goto done;
2935 err = format_author(&wauthor, &width, author, COLS,
2936 date_display_cols);
2937 if (author_cols < width)
2938 author_cols = width;
2939 free(wauthor);
2940 free(author);
2941 if (err)
2942 goto done;
2943 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2944 entry->id);
2945 err = build_refs_str(&refs_str, refs, entry->id, s->repo);
2946 if (err)
2947 goto done;
2948 if (refs_str) {
2949 wchar_t *ws;
2950 err = format_line(&ws, &width, NULL, refs_str,
2951 0, INT_MAX, date_display_cols + author_cols, 0);
2952 free(ws);
2953 free(refs_str);
2954 refs_str = NULL;
2955 if (err)
2956 goto done;
2957 refstr_cols = width + 3; /* account for [ ] + space */
2958 } else
2959 refstr_cols = 0;
2960 err = got_object_commit_get_logmsg(&msg0, c);
2961 if (err)
2962 goto done;
2963 msg = msg0;
2964 while (*msg == '\n')
2965 ++msg;
2966 if ((eol = strchr(msg, '\n')))
2967 *eol = '\0';
2968 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2969 date_display_cols + author_cols + refstr_cols, 0);
2970 if (err)
2971 goto done;
2972 view->maxx = MAX(view->maxx, width + refstr_cols);
2973 free(msg0);
2974 free(wmsg);
2975 ncommits++;
2976 entry = TAILQ_NEXT(entry, entry);
2979 entry = s->first_displayed_entry;
2980 s->last_displayed_entry = s->first_displayed_entry;
2981 ncommits = 0;
2982 while (entry) {
2983 if (ncommits >= limit - 1)
2984 break;
2985 if (ncommits == s->selected)
2986 wstandout(view->window);
2987 err = draw_commit(view, entry, date_display_cols, author_cols);
2988 if (ncommits == s->selected)
2989 wstandend(view->window);
2990 if (err)
2991 goto done;
2992 ncommits++;
2993 s->last_displayed_entry = entry;
2994 entry = TAILQ_NEXT(entry, entry);
2997 view_border(view);
2998 done:
2999 free(id_str);
3000 free(refs_str);
3001 free(ncommits_str);
3002 free(header);
3003 return err;
3006 static void
3007 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
3009 struct commit_queue_entry *entry;
3010 int nscrolled = 0;
3012 entry = TAILQ_FIRST(&s->commits->head);
3013 if (s->first_displayed_entry == entry)
3014 return;
3016 entry = s->first_displayed_entry;
3017 while (entry && nscrolled < maxscroll) {
3018 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3019 if (entry) {
3020 s->first_displayed_entry = entry;
3021 nscrolled++;
3026 static const struct got_error *
3027 trigger_log_thread(struct tog_view *view, int wait)
3029 struct tog_log_thread_args *ta = &view->state.log.thread_args;
3030 int errcode;
3032 if (!using_mock_io)
3033 halfdelay(1); /* fast refresh while loading commits */
3035 while (!ta->log_complete && !tog_thread_error &&
3036 (ta->commits_needed > 0 || ta->load_all)) {
3037 /* Wake the log thread. */
3038 errcode = pthread_cond_signal(&ta->need_commits);
3039 if (errcode)
3040 return got_error_set_errno(errcode,
3041 "pthread_cond_signal");
3044 * The mutex will be released while the view loop waits
3045 * in wgetch(), at which time the log thread will run.
3047 if (!wait)
3048 break;
3050 /* Display progress update in log view. */
3051 show_log_view(view);
3052 update_panels();
3053 doupdate();
3055 /* Wait right here while next commit is being loaded. */
3056 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
3057 if (errcode)
3058 return got_error_set_errno(errcode,
3059 "pthread_cond_wait");
3061 /* Display progress update in log view. */
3062 show_log_view(view);
3063 update_panels();
3064 doupdate();
3067 return NULL;
3070 static const struct got_error *
3071 request_log_commits(struct tog_view *view)
3073 struct tog_log_view_state *state = &view->state.log;
3074 const struct got_error *err = NULL;
3076 if (state->thread_args.log_complete)
3077 return NULL;
3079 state->thread_args.commits_needed += view->nscrolled;
3080 err = trigger_log_thread(view, 1);
3081 view->nscrolled = 0;
3083 return err;
3086 static const struct got_error *
3087 log_scroll_down(struct tog_view *view, int maxscroll)
3089 struct tog_log_view_state *s = &view->state.log;
3090 const struct got_error *err = NULL;
3091 struct commit_queue_entry *pentry;
3092 int nscrolled = 0, ncommits_needed;
3094 if (s->last_displayed_entry == NULL)
3095 return NULL;
3097 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
3098 if (s->commits->ncommits < ncommits_needed &&
3099 !s->thread_args.log_complete) {
3101 * Ask the log thread for required amount of commits.
3103 s->thread_args.commits_needed +=
3104 ncommits_needed - s->commits->ncommits;
3105 err = trigger_log_thread(view, 1);
3106 if (err)
3107 return err;
3110 do {
3111 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
3112 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
3113 break;
3115 s->last_displayed_entry = pentry ?
3116 pentry : s->last_displayed_entry;
3118 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
3119 if (pentry == NULL)
3120 break;
3121 s->first_displayed_entry = pentry;
3122 } while (++nscrolled < maxscroll);
3124 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
3125 view->nscrolled += nscrolled;
3126 else
3127 view->nscrolled = 0;
3129 return err;
3132 static const struct got_error *
3133 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
3134 struct got_commit_object *commit, struct got_object_id *commit_id,
3135 struct tog_view *log_view, struct got_repository *repo)
3137 const struct got_error *err;
3138 struct got_object_qid *parent_id;
3139 struct tog_view *diff_view;
3141 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3142 if (diff_view == NULL)
3143 return got_error_from_errno("view_open");
3145 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3146 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3147 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3148 if (err == NULL)
3149 *new_view = diff_view;
3150 return err;
3153 static const struct got_error *
3154 tree_view_visit_subtree(struct tog_tree_view_state *s,
3155 struct got_tree_object *subtree)
3157 struct tog_parent_tree *parent;
3159 parent = calloc(1, sizeof(*parent));
3160 if (parent == NULL)
3161 return got_error_from_errno("calloc");
3163 parent->tree = s->tree;
3164 parent->first_displayed_entry = s->first_displayed_entry;
3165 parent->selected_entry = s->selected_entry;
3166 parent->selected = s->selected;
3167 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3168 s->tree = subtree;
3169 s->selected = 0;
3170 s->first_displayed_entry = NULL;
3171 return NULL;
3174 static const struct got_error *
3175 tree_view_walk_path(struct tog_tree_view_state *s,
3176 struct got_commit_object *commit, const char *path)
3178 const struct got_error *err = NULL;
3179 struct got_tree_object *tree = NULL;
3180 const char *p;
3181 char *slash, *subpath = NULL;
3183 /* Walk the path and open corresponding tree objects. */
3184 p = path;
3185 while (*p) {
3186 struct got_tree_entry *te;
3187 struct got_object_id *tree_id;
3188 char *te_name;
3190 while (p[0] == '/')
3191 p++;
3193 /* Ensure the correct subtree entry is selected. */
3194 slash = strchr(p, '/');
3195 if (slash == NULL)
3196 te_name = strdup(p);
3197 else
3198 te_name = strndup(p, slash - p);
3199 if (te_name == NULL) {
3200 err = got_error_from_errno("strndup");
3201 break;
3203 te = got_object_tree_find_entry(s->tree, te_name);
3204 if (te == NULL) {
3205 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3206 free(te_name);
3207 break;
3209 free(te_name);
3210 s->first_displayed_entry = s->selected_entry = te;
3212 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3213 break; /* jump to this file's entry */
3215 slash = strchr(p, '/');
3216 if (slash)
3217 subpath = strndup(path, slash - path);
3218 else
3219 subpath = strdup(path);
3220 if (subpath == NULL) {
3221 err = got_error_from_errno("strdup");
3222 break;
3225 err = got_object_id_by_path(&tree_id, s->repo, commit,
3226 subpath);
3227 if (err)
3228 break;
3230 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3231 free(tree_id);
3232 if (err)
3233 break;
3235 err = tree_view_visit_subtree(s, tree);
3236 if (err) {
3237 got_object_tree_close(tree);
3238 break;
3240 if (slash == NULL)
3241 break;
3242 free(subpath);
3243 subpath = NULL;
3244 p = slash;
3247 free(subpath);
3248 return err;
3251 static const struct got_error *
3252 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3253 struct commit_queue_entry *entry, const char *path,
3254 const char *head_ref_name, struct got_repository *repo)
3256 const struct got_error *err = NULL;
3257 struct tog_tree_view_state *s;
3258 struct tog_view *tree_view;
3260 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3261 if (tree_view == NULL)
3262 return got_error_from_errno("view_open");
3264 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3265 if (err)
3266 return err;
3267 s = &tree_view->state.tree;
3269 *new_view = tree_view;
3271 if (got_path_is_root_dir(path))
3272 return NULL;
3274 return tree_view_walk_path(s, entry->commit, path);
3277 static const struct got_error *
3278 block_signals_used_by_main_thread(void)
3280 sigset_t sigset;
3281 int errcode;
3283 if (sigemptyset(&sigset) == -1)
3284 return got_error_from_errno("sigemptyset");
3286 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3287 if (sigaddset(&sigset, SIGWINCH) == -1)
3288 return got_error_from_errno("sigaddset");
3289 if (sigaddset(&sigset, SIGCONT) == -1)
3290 return got_error_from_errno("sigaddset");
3291 if (sigaddset(&sigset, SIGINT) == -1)
3292 return got_error_from_errno("sigaddset");
3293 if (sigaddset(&sigset, SIGTERM) == -1)
3294 return got_error_from_errno("sigaddset");
3296 /* ncurses handles SIGTSTP */
3297 if (sigaddset(&sigset, SIGTSTP) == -1)
3298 return got_error_from_errno("sigaddset");
3300 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3301 if (errcode)
3302 return got_error_set_errno(errcode, "pthread_sigmask");
3304 return NULL;
3307 static void *
3308 log_thread(void *arg)
3310 const struct got_error *err = NULL;
3311 int errcode = 0;
3312 struct tog_log_thread_args *a = arg;
3313 int done = 0;
3316 * Sync startup with main thread such that we begin our
3317 * work once view_input() has released the mutex.
3319 errcode = pthread_mutex_lock(&tog_mutex);
3320 if (errcode) {
3321 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3322 return (void *)err;
3325 err = block_signals_used_by_main_thread();
3326 if (err) {
3327 pthread_mutex_unlock(&tog_mutex);
3328 goto done;
3331 while (!done && !err && !tog_fatal_signal_received()) {
3332 errcode = pthread_mutex_unlock(&tog_mutex);
3333 if (errcode) {
3334 err = got_error_set_errno(errcode,
3335 "pthread_mutex_unlock");
3336 goto done;
3338 err = queue_commits(a);
3339 if (err) {
3340 if (err->code != GOT_ERR_ITER_COMPLETED)
3341 goto done;
3342 err = NULL;
3343 done = 1;
3344 a->commits_needed = 0;
3345 } else if (a->commits_needed > 0 && !a->load_all) {
3346 if (*a->limiting) {
3347 if (a->limit_match)
3348 a->commits_needed--;
3349 } else
3350 a->commits_needed--;
3353 errcode = pthread_mutex_lock(&tog_mutex);
3354 if (errcode) {
3355 err = got_error_set_errno(errcode,
3356 "pthread_mutex_lock");
3357 goto done;
3358 } else if (*a->quit)
3359 done = 1;
3360 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3361 *a->first_displayed_entry =
3362 TAILQ_FIRST(&a->limit_commits->head);
3363 *a->selected_entry = *a->first_displayed_entry;
3364 } else if (*a->first_displayed_entry == NULL) {
3365 *a->first_displayed_entry =
3366 TAILQ_FIRST(&a->real_commits->head);
3367 *a->selected_entry = *a->first_displayed_entry;
3370 errcode = pthread_cond_signal(&a->commit_loaded);
3371 if (errcode) {
3372 err = got_error_set_errno(errcode,
3373 "pthread_cond_signal");
3374 pthread_mutex_unlock(&tog_mutex);
3375 goto done;
3378 if (a->commits_needed == 0 &&
3379 a->need_commit_marker && a->worktree) {
3380 errcode = pthread_mutex_unlock(&tog_mutex);
3381 if (errcode) {
3382 err = got_error_set_errno(errcode,
3383 "pthread_mutex_unlock");
3384 goto done;
3386 err = got_worktree_get_state(&tog_base_commit.marker,
3387 a->repo, a->worktree, NULL, NULL);
3388 if (err)
3389 goto done;
3390 errcode = pthread_mutex_lock(&tog_mutex);
3391 if (errcode) {
3392 err = got_error_set_errno(errcode,
3393 "pthread_mutex_lock");
3394 goto done;
3396 a->need_commit_marker = 0;
3398 * The main thread did not close this
3399 * work tree yet. Close it now.
3401 got_worktree_close(a->worktree);
3402 a->worktree = NULL;
3404 if (*a->quit)
3405 done = 1;
3408 if (done)
3409 a->commits_needed = 0;
3410 else {
3411 if (a->commits_needed == 0 && !a->load_all) {
3412 if (tog_io.wait_for_ui) {
3413 errcode = pthread_cond_signal(
3414 &a->log_loaded);
3415 if (errcode && err == NULL)
3416 err = got_error_set_errno(
3417 errcode,
3418 "pthread_cond_signal");
3421 errcode = pthread_cond_wait(&a->need_commits,
3422 &tog_mutex);
3423 if (errcode) {
3424 err = got_error_set_errno(errcode,
3425 "pthread_cond_wait");
3426 pthread_mutex_unlock(&tog_mutex);
3427 goto done;
3429 if (*a->quit)
3430 done = 1;
3434 a->log_complete = 1;
3435 if (tog_io.wait_for_ui) {
3436 errcode = pthread_cond_signal(&a->log_loaded);
3437 if (errcode && err == NULL)
3438 err = got_error_set_errno(errcode,
3439 "pthread_cond_signal");
3442 errcode = pthread_mutex_unlock(&tog_mutex);
3443 if (errcode)
3444 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3445 done:
3446 if (err) {
3447 tog_thread_error = 1;
3448 pthread_cond_signal(&a->commit_loaded);
3449 if (a->worktree) {
3450 got_worktree_close(a->worktree);
3451 a->worktree = NULL;
3454 return (void *)err;
3457 static const struct got_error *
3458 stop_log_thread(struct tog_log_view_state *s)
3460 const struct got_error *err = NULL, *thread_err = NULL;
3461 int errcode;
3463 if (s->thread) {
3464 s->quit = 1;
3465 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3466 if (errcode)
3467 return got_error_set_errno(errcode,
3468 "pthread_cond_signal");
3469 errcode = pthread_mutex_unlock(&tog_mutex);
3470 if (errcode)
3471 return got_error_set_errno(errcode,
3472 "pthread_mutex_unlock");
3473 errcode = pthread_join(s->thread, (void **)&thread_err);
3474 if (errcode)
3475 return got_error_set_errno(errcode, "pthread_join");
3476 errcode = pthread_mutex_lock(&tog_mutex);
3477 if (errcode)
3478 return got_error_set_errno(errcode,
3479 "pthread_mutex_lock");
3480 s->thread = 0; //NULL;
3483 if (s->thread_args.repo) {
3484 err = got_repo_close(s->thread_args.repo);
3485 s->thread_args.repo = NULL;
3488 if (s->thread_args.pack_fds) {
3489 const struct got_error *pack_err =
3490 got_repo_pack_fds_close(s->thread_args.pack_fds);
3491 if (err == NULL)
3492 err = pack_err;
3493 s->thread_args.pack_fds = NULL;
3496 if (s->thread_args.graph) {
3497 got_commit_graph_close(s->thread_args.graph);
3498 s->thread_args.graph = NULL;
3501 return err ? err : thread_err;
3504 static const struct got_error *
3505 close_log_view(struct tog_view *view)
3507 const struct got_error *err = NULL;
3508 struct tog_log_view_state *s = &view->state.log;
3509 int errcode;
3511 err = stop_log_thread(s);
3513 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3514 if (errcode && err == NULL)
3515 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3517 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3518 if (errcode && err == NULL)
3519 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3521 free_commits(&s->limit_commits);
3522 free_commits(&s->real_commits);
3523 free(s->in_repo_path);
3524 s->in_repo_path = NULL;
3525 free(s->start_id);
3526 s->start_id = NULL;
3527 free(s->head_ref_name);
3528 s->head_ref_name = NULL;
3529 return err;
3533 * We use two queues to implement the limit feature: first consists of
3534 * commits matching the current limit_regex; second is the real queue
3535 * of all known commits (real_commits). When the user starts limiting,
3536 * we swap queues such that all movement and displaying functionality
3537 * works with very slight change.
3539 static const struct got_error *
3540 limit_log_view(struct tog_view *view)
3542 struct tog_log_view_state *s = &view->state.log;
3543 struct commit_queue_entry *entry;
3544 struct tog_view *v = view;
3545 const struct got_error *err = NULL;
3546 char pattern[1024];
3547 int ret;
3549 if (view_is_hsplit_top(view))
3550 v = view->child;
3551 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3552 v = view->parent;
3554 /* Get the pattern */
3555 wmove(v->window, v->nlines - 1, 0);
3556 wclrtoeol(v->window);
3557 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3558 nodelay(v->window, FALSE);
3559 nocbreak();
3560 echo();
3561 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3562 cbreak();
3563 noecho();
3564 nodelay(v->window, TRUE);
3565 if (ret == ERR)
3566 return NULL;
3568 if (*pattern == '\0') {
3570 * Safety measure for the situation where the user
3571 * resets limit without previously limiting anything.
3573 if (!s->limit_view)
3574 return NULL;
3577 * User could have pressed Ctrl+L, which refreshed the
3578 * commit queues, it means we can't save previously
3579 * (before limit took place) displayed entries,
3580 * because they would point to already free'ed memory,
3581 * so we are forced to always select first entry of
3582 * the queue.
3584 s->commits = &s->real_commits;
3585 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3586 s->selected_entry = s->first_displayed_entry;
3587 s->selected = 0;
3588 s->limit_view = 0;
3590 return NULL;
3593 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3594 return NULL;
3596 s->limit_view = 1;
3598 /* Clear the screen while loading limit view */
3599 s->first_displayed_entry = NULL;
3600 s->last_displayed_entry = NULL;
3601 s->selected_entry = NULL;
3602 s->commits = &s->limit_commits;
3604 /* Prepare limit queue for new search */
3605 free_commits(&s->limit_commits);
3606 s->limit_commits.ncommits = 0;
3608 /* First process commits, which are in queue already */
3609 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3610 int have_match = 0;
3612 err = match_commit(&have_match, entry->id,
3613 entry->commit, &s->limit_regex);
3614 if (err)
3615 return err;
3617 if (have_match) {
3618 struct commit_queue_entry *matched;
3620 matched = alloc_commit_queue_entry(entry->commit,
3621 entry->id);
3622 if (matched == NULL) {
3623 err = got_error_from_errno(
3624 "alloc_commit_queue_entry");
3625 break;
3627 matched->commit = entry->commit;
3628 got_object_commit_retain(entry->commit);
3630 matched->idx = s->limit_commits.ncommits;
3631 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3632 matched, entry);
3633 s->limit_commits.ncommits++;
3637 /* Second process all the commits, until we fill the screen */
3638 if (s->limit_commits.ncommits < view->nlines - 1 &&
3639 !s->thread_args.log_complete) {
3640 s->thread_args.commits_needed +=
3641 view->nlines - s->limit_commits.ncommits - 1;
3642 err = trigger_log_thread(view, 1);
3643 if (err)
3644 return err;
3647 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3648 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3649 s->selected = 0;
3651 return NULL;
3654 static const struct got_error *
3655 search_start_log_view(struct tog_view *view)
3657 struct tog_log_view_state *s = &view->state.log;
3659 s->matched_entry = NULL;
3660 s->search_entry = NULL;
3661 return NULL;
3664 static const struct got_error *
3665 search_next_log_view(struct tog_view *view)
3667 const struct got_error *err = NULL;
3668 struct tog_log_view_state *s = &view->state.log;
3669 struct commit_queue_entry *entry;
3671 /* Display progress update in log view. */
3672 show_log_view(view);
3673 update_panels();
3674 doupdate();
3676 if (s->search_entry) {
3677 int errcode, ch;
3678 errcode = pthread_mutex_unlock(&tog_mutex);
3679 if (errcode)
3680 return got_error_set_errno(errcode,
3681 "pthread_mutex_unlock");
3682 ch = wgetch(view->window);
3683 errcode = pthread_mutex_lock(&tog_mutex);
3684 if (errcode)
3685 return got_error_set_errno(errcode,
3686 "pthread_mutex_lock");
3687 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3688 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3689 return NULL;
3691 if (view->searching == TOG_SEARCH_FORWARD)
3692 entry = TAILQ_NEXT(s->search_entry, entry);
3693 else
3694 entry = TAILQ_PREV(s->search_entry,
3695 commit_queue_head, entry);
3696 } else if (s->matched_entry) {
3698 * If the user has moved the cursor after we hit a match,
3699 * the position from where we should continue searching
3700 * might have changed.
3702 if (view->searching == TOG_SEARCH_FORWARD)
3703 entry = TAILQ_NEXT(s->selected_entry, entry);
3704 else
3705 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3706 entry);
3707 } else {
3708 entry = s->selected_entry;
3711 while (1) {
3712 int have_match = 0;
3714 if (entry == NULL) {
3715 if (s->thread_args.log_complete ||
3716 view->searching == TOG_SEARCH_BACKWARD) {
3717 view->search_next_done =
3718 (s->matched_entry == NULL ?
3719 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3720 s->search_entry = NULL;
3721 return NULL;
3724 * Poke the log thread for more commits and return,
3725 * allowing the main loop to make progress. Search
3726 * will resume at s->search_entry once we come back.
3728 s->thread_args.commits_needed++;
3729 return trigger_log_thread(view, 0);
3732 err = match_commit(&have_match, entry->id, entry->commit,
3733 &view->regex);
3734 if (err)
3735 break;
3736 if (have_match) {
3737 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3738 s->matched_entry = entry;
3739 break;
3742 s->search_entry = entry;
3743 if (view->searching == TOG_SEARCH_FORWARD)
3744 entry = TAILQ_NEXT(entry, entry);
3745 else
3746 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3749 if (s->matched_entry) {
3750 int cur = s->selected_entry->idx;
3751 while (cur < s->matched_entry->idx) {
3752 err = input_log_view(NULL, view, KEY_DOWN);
3753 if (err)
3754 return err;
3755 cur++;
3757 while (cur > s->matched_entry->idx) {
3758 err = input_log_view(NULL, view, KEY_UP);
3759 if (err)
3760 return err;
3761 cur--;
3765 s->search_entry = NULL;
3767 return NULL;
3770 static const struct got_error *
3771 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3772 struct got_repository *repo, const char *head_ref_name,
3773 const char *in_repo_path, int log_branches,
3774 struct got_worktree *worktree)
3776 const struct got_error *err = NULL;
3777 struct tog_log_view_state *s = &view->state.log;
3778 struct got_repository *thread_repo = NULL;
3779 struct got_commit_graph *thread_graph = NULL;
3780 int errcode;
3782 if (in_repo_path != s->in_repo_path) {
3783 free(s->in_repo_path);
3784 s->in_repo_path = strdup(in_repo_path);
3785 if (s->in_repo_path == NULL) {
3786 err = got_error_from_errno("strdup");
3787 goto done;
3791 /* The commit queue only contains commits being displayed. */
3792 TAILQ_INIT(&s->real_commits.head);
3793 s->real_commits.ncommits = 0;
3794 s->commits = &s->real_commits;
3796 TAILQ_INIT(&s->limit_commits.head);
3797 s->limit_view = 0;
3798 s->limit_commits.ncommits = 0;
3800 s->repo = repo;
3801 if (head_ref_name) {
3802 s->head_ref_name = strdup(head_ref_name);
3803 if (s->head_ref_name == NULL) {
3804 err = got_error_from_errno("strdup");
3805 goto done;
3808 s->start_id = got_object_id_dup(start_id);
3809 if (s->start_id == NULL) {
3810 err = got_error_from_errno("got_object_id_dup");
3811 goto done;
3813 s->log_branches = log_branches;
3814 s->use_committer = 1;
3816 STAILQ_INIT(&s->colors);
3817 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3818 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3819 get_color_value("TOG_COLOR_COMMIT"));
3820 if (err)
3821 goto done;
3822 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3823 get_color_value("TOG_COLOR_AUTHOR"));
3824 if (err) {
3825 free_colors(&s->colors);
3826 goto done;
3828 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3829 get_color_value("TOG_COLOR_DATE"));
3830 if (err) {
3831 free_colors(&s->colors);
3832 goto done;
3836 view->show = show_log_view;
3837 view->input = input_log_view;
3838 view->resize = resize_log_view;
3839 view->close = close_log_view;
3840 view->search_start = search_start_log_view;
3841 view->search_next = search_next_log_view;
3843 if (s->thread_args.pack_fds == NULL) {
3844 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3845 if (err)
3846 goto done;
3848 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3849 s->thread_args.pack_fds);
3850 if (err)
3851 goto done;
3852 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3853 !s->log_branches);
3854 if (err)
3855 goto done;
3856 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3857 s->repo, NULL, NULL);
3858 if (err)
3859 goto done;
3861 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3862 if (errcode) {
3863 err = got_error_set_errno(errcode, "pthread_cond_init");
3864 goto done;
3866 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3867 if (errcode) {
3868 err = got_error_set_errno(errcode, "pthread_cond_init");
3869 goto done;
3872 if (using_mock_io) {
3873 int rc;
3875 rc = pthread_cond_init(&s->thread_args.log_loaded, NULL);
3876 if (rc)
3877 return got_error_set_errno(rc, "pthread_cond_init");
3880 s->thread_args.commits_needed = view->nlines;
3881 s->thread_args.graph = thread_graph;
3882 s->thread_args.real_commits = &s->real_commits;
3883 s->thread_args.limit_commits = &s->limit_commits;
3884 s->thread_args.in_repo_path = s->in_repo_path;
3885 s->thread_args.start_id = s->start_id;
3886 s->thread_args.repo = thread_repo;
3887 s->thread_args.log_complete = 0;
3888 s->thread_args.quit = &s->quit;
3889 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3890 s->thread_args.selected_entry = &s->selected_entry;
3891 s->thread_args.searching = &view->searching;
3892 s->thread_args.search_next_done = &view->search_next_done;
3893 s->thread_args.regex = &view->regex;
3894 s->thread_args.limiting = &s->limit_view;
3895 s->thread_args.limit_regex = &s->limit_regex;
3896 s->thread_args.limit_commits = &s->limit_commits;
3897 s->thread_args.worktree = worktree;
3898 if (worktree)
3899 s->thread_args.need_commit_marker = 1;
3900 done:
3901 if (err) {
3902 if (view->close == NULL)
3903 close_log_view(view);
3904 view_close(view);
3906 return err;
3909 static const struct got_error *
3910 show_log_view(struct tog_view *view)
3912 const struct got_error *err;
3913 struct tog_log_view_state *s = &view->state.log;
3915 if (s->thread == 0) { //NULL) {
3916 int errcode = pthread_create(&s->thread, NULL, log_thread,
3917 &s->thread_args);
3918 if (errcode)
3919 return got_error_set_errno(errcode, "pthread_create");
3920 if (s->thread_args.commits_needed > 0) {
3921 err = trigger_log_thread(view, 1);
3922 if (err)
3923 return err;
3927 return draw_commits(view);
3930 static void
3931 log_move_cursor_up(struct tog_view *view, int page, int home)
3933 struct tog_log_view_state *s = &view->state.log;
3935 if (s->first_displayed_entry == NULL)
3936 return;
3937 if (s->selected_entry->idx == 0)
3938 view->count = 0;
3940 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3941 || home)
3942 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3944 if (!page && !home && s->selected > 0)
3945 --s->selected;
3946 else
3947 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3949 select_commit(s);
3950 return;
3953 static const struct got_error *
3954 log_move_cursor_down(struct tog_view *view, int page)
3956 struct tog_log_view_state *s = &view->state.log;
3957 const struct got_error *err = NULL;
3958 int eos = view->nlines - 2;
3960 if (s->first_displayed_entry == NULL)
3961 return NULL;
3963 if (s->thread_args.log_complete &&
3964 s->selected_entry->idx >= s->commits->ncommits - 1)
3965 return NULL;
3967 if (view_is_hsplit_top(view))
3968 --eos; /* border consumes the last line */
3970 if (!page) {
3971 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3972 ++s->selected;
3973 else
3974 err = log_scroll_down(view, 1);
3975 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3976 struct commit_queue_entry *entry;
3977 int n;
3979 s->selected = 0;
3980 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3981 s->last_displayed_entry = entry;
3982 for (n = 0; n <= eos; n++) {
3983 if (entry == NULL)
3984 break;
3985 s->first_displayed_entry = entry;
3986 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3988 if (n > 0)
3989 s->selected = n - 1;
3990 } else {
3991 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3992 s->thread_args.log_complete)
3993 s->selected += MIN(page,
3994 s->commits->ncommits - s->selected_entry->idx - 1);
3995 else
3996 err = log_scroll_down(view, page);
3998 if (err)
3999 return err;
4002 * We might necessarily overshoot in horizontal
4003 * splits; if so, select the last displayed commit.
4005 if (s->first_displayed_entry && s->last_displayed_entry) {
4006 s->selected = MIN(s->selected,
4007 s->last_displayed_entry->idx -
4008 s->first_displayed_entry->idx);
4011 select_commit(s);
4013 if (s->thread_args.log_complete &&
4014 s->selected_entry->idx == s->commits->ncommits - 1)
4015 view->count = 0;
4017 return NULL;
4020 static void
4021 view_get_split(struct tog_view *view, int *y, int *x)
4023 *x = 0;
4024 *y = 0;
4026 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
4027 if (view->child && view->child->resized_y)
4028 *y = view->child->resized_y;
4029 else if (view->resized_y)
4030 *y = view->resized_y;
4031 else
4032 *y = view_split_begin_y(view->lines);
4033 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
4034 if (view->child && view->child->resized_x)
4035 *x = view->child->resized_x;
4036 else if (view->resized_x)
4037 *x = view->resized_x;
4038 else
4039 *x = view_split_begin_x(view->begin_x);
4043 /* Split view horizontally at y and offset view->state->selected line. */
4044 static const struct got_error *
4045 view_init_hsplit(struct tog_view *view, int y)
4047 const struct got_error *err = NULL;
4049 view->nlines = y;
4050 view->ncols = COLS;
4051 err = view_resize(view);
4052 if (err)
4053 return err;
4055 err = offset_selection_down(view);
4057 return err;
4060 static const struct got_error *
4061 log_goto_line(struct tog_view *view, int nlines)
4063 const struct got_error *err = NULL;
4064 struct tog_log_view_state *s = &view->state.log;
4065 int g, idx = s->selected_entry->idx;
4067 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
4068 return NULL;
4070 g = view->gline;
4071 view->gline = 0;
4073 if (g >= s->first_displayed_entry->idx + 1 &&
4074 g <= s->last_displayed_entry->idx + 1 &&
4075 g - s->first_displayed_entry->idx - 1 < nlines) {
4076 s->selected = g - s->first_displayed_entry->idx - 1;
4077 select_commit(s);
4078 return NULL;
4081 if (idx + 1 < g) {
4082 err = log_move_cursor_down(view, g - idx - 1);
4083 if (!err && g > s->selected_entry->idx + 1)
4084 err = log_move_cursor_down(view,
4085 g - s->first_displayed_entry->idx - 1);
4086 if (err)
4087 return err;
4088 } else if (idx + 1 > g)
4089 log_move_cursor_up(view, idx - g + 1, 0);
4091 if (g < nlines && s->first_displayed_entry->idx == 0)
4092 s->selected = g - 1;
4094 select_commit(s);
4095 return NULL;
4099 static void
4100 horizontal_scroll_input(struct tog_view *view, int ch)
4103 switch (ch) {
4104 case KEY_LEFT:
4105 case 'h':
4106 view->x -= MIN(view->x, 2);
4107 if (view->x <= 0)
4108 view->count = 0;
4109 break;
4110 case KEY_RIGHT:
4111 case 'l':
4112 if (view->x + view->ncols / 2 < view->maxx)
4113 view->x += 2;
4114 else
4115 view->count = 0;
4116 break;
4117 case '0':
4118 view->x = 0;
4119 break;
4120 case '$':
4121 view->x = MAX(view->maxx - view->ncols / 2, 0);
4122 view->count = 0;
4123 break;
4124 default:
4125 break;
4129 static const struct got_error *
4130 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
4132 const struct got_error *err = NULL;
4133 struct tog_log_view_state *s = &view->state.log;
4134 int eos, nscroll;
4136 if (s->thread_args.load_all) {
4137 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
4138 s->thread_args.load_all = 0;
4139 else if (s->thread_args.log_complete) {
4140 err = log_move_cursor_down(view, s->commits->ncommits);
4141 s->thread_args.load_all = 0;
4143 if (err)
4144 return err;
4147 eos = nscroll = view->nlines - 1;
4148 if (view_is_hsplit_top(view))
4149 --eos; /* border */
4151 if (view->gline)
4152 return log_goto_line(view, eos);
4154 switch (ch) {
4155 case '&':
4156 err = limit_log_view(view);
4157 break;
4158 case 'q':
4159 s->quit = 1;
4160 break;
4161 case '0':
4162 case '$':
4163 case KEY_RIGHT:
4164 case 'l':
4165 case KEY_LEFT:
4166 case 'h':
4167 horizontal_scroll_input(view, ch);
4168 break;
4169 case 'k':
4170 case KEY_UP:
4171 case '<':
4172 case ',':
4173 case CTRL('p'):
4174 log_move_cursor_up(view, 0, 0);
4175 break;
4176 case 'g':
4177 case '=':
4178 case KEY_HOME:
4179 log_move_cursor_up(view, 0, 1);
4180 view->count = 0;
4181 break;
4182 case CTRL('u'):
4183 case 'u':
4184 nscroll /= 2;
4185 /* FALL THROUGH */
4186 case KEY_PPAGE:
4187 case CTRL('b'):
4188 case 'b':
4189 log_move_cursor_up(view, nscroll, 0);
4190 break;
4191 case 'j':
4192 case KEY_DOWN:
4193 case '>':
4194 case '.':
4195 case CTRL('n'):
4196 err = log_move_cursor_down(view, 0);
4197 break;
4198 case '@':
4199 s->use_committer = !s->use_committer;
4200 view->action = s->use_committer ?
4201 "show committer" : "show commit author";
4202 break;
4203 case 'G':
4204 case '*':
4205 case KEY_END: {
4206 /* We don't know yet how many commits, so we're forced to
4207 * traverse them all. */
4208 view->count = 0;
4209 s->thread_args.load_all = 1;
4210 if (!s->thread_args.log_complete)
4211 return trigger_log_thread(view, 0);
4212 err = log_move_cursor_down(view, s->commits->ncommits);
4213 s->thread_args.load_all = 0;
4214 break;
4216 case CTRL('d'):
4217 case 'd':
4218 nscroll /= 2;
4219 /* FALL THROUGH */
4220 case KEY_NPAGE:
4221 case CTRL('f'):
4222 case 'f':
4223 case ' ':
4224 err = log_move_cursor_down(view, nscroll);
4225 break;
4226 case KEY_RESIZE:
4227 if (s->selected > view->nlines - 2)
4228 s->selected = view->nlines - 2;
4229 if (s->selected > s->commits->ncommits - 1)
4230 s->selected = s->commits->ncommits - 1;
4231 select_commit(s);
4232 if (s->commits->ncommits < view->nlines - 1 &&
4233 !s->thread_args.log_complete) {
4234 s->thread_args.commits_needed += (view->nlines - 1) -
4235 s->commits->ncommits;
4236 err = trigger_log_thread(view, 1);
4238 break;
4239 case KEY_ENTER:
4240 case '\r':
4241 view->count = 0;
4242 if (s->selected_entry == NULL)
4243 break;
4244 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4245 break;
4246 case 'T':
4247 view->count = 0;
4248 if (s->selected_entry == NULL)
4249 break;
4250 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4251 break;
4252 case KEY_BACKSPACE:
4253 case CTRL('l'):
4254 case 'B':
4255 view->count = 0;
4256 if (ch == KEY_BACKSPACE &&
4257 got_path_is_root_dir(s->in_repo_path))
4258 break;
4259 err = stop_log_thread(s);
4260 if (err)
4261 return err;
4262 if (ch == KEY_BACKSPACE) {
4263 char *parent_path;
4264 err = got_path_dirname(&parent_path, s->in_repo_path);
4265 if (err)
4266 return err;
4267 free(s->in_repo_path);
4268 s->in_repo_path = parent_path;
4269 s->thread_args.in_repo_path = s->in_repo_path;
4270 } else if (ch == CTRL('l')) {
4271 struct got_object_id *start_id;
4272 err = got_repo_match_object_id(&start_id, NULL,
4273 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4274 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4275 if (err) {
4276 if (s->head_ref_name == NULL ||
4277 err->code != GOT_ERR_NOT_REF)
4278 return err;
4279 /* Try to cope with deleted references. */
4280 free(s->head_ref_name);
4281 s->head_ref_name = NULL;
4282 err = got_repo_match_object_id(&start_id,
4283 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4284 &tog_refs, s->repo);
4285 if (err)
4286 return err;
4288 free(s->start_id);
4289 s->start_id = start_id;
4290 s->thread_args.start_id = s->start_id;
4291 } else /* 'B' */
4292 s->log_branches = !s->log_branches;
4294 if (s->thread_args.pack_fds == NULL) {
4295 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4296 if (err)
4297 return err;
4299 err = got_repo_open(&s->thread_args.repo,
4300 got_repo_get_path(s->repo), NULL,
4301 s->thread_args.pack_fds);
4302 if (err)
4303 return err;
4304 tog_free_refs();
4305 err = tog_load_refs(s->repo, 0);
4306 if (err)
4307 return err;
4308 err = got_commit_graph_open(&s->thread_args.graph,
4309 s->in_repo_path, !s->log_branches);
4310 if (err)
4311 return err;
4312 err = got_commit_graph_iter_start(s->thread_args.graph,
4313 s->start_id, s->repo, NULL, NULL);
4314 if (err)
4315 return err;
4316 free_commits(&s->real_commits);
4317 free_commits(&s->limit_commits);
4318 s->first_displayed_entry = NULL;
4319 s->last_displayed_entry = NULL;
4320 s->selected_entry = NULL;
4321 s->selected = 0;
4322 s->thread_args.log_complete = 0;
4323 s->quit = 0;
4324 s->thread_args.commits_needed = view->lines;
4325 s->matched_entry = NULL;
4326 s->search_entry = NULL;
4327 view->offset = 0;
4328 break;
4329 case 'R':
4330 view->count = 0;
4331 err = view_request_new(new_view, view, TOG_VIEW_REF);
4332 break;
4333 default:
4334 view->count = 0;
4335 break;
4338 return err;
4341 static const struct got_error *
4342 apply_unveil(const char *repo_path, const char *worktree_path)
4344 const struct got_error *error;
4346 #ifdef PROFILE
4347 if (unveil("gmon.out", "rwc") != 0)
4348 return got_error_from_errno2("unveil", "gmon.out");
4349 #endif
4350 if (repo_path && unveil(repo_path, "r") != 0)
4351 return got_error_from_errno2("unveil", repo_path);
4353 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4354 return got_error_from_errno2("unveil", worktree_path);
4356 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4357 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4359 error = got_privsep_unveil_exec_helpers();
4360 if (error != NULL)
4361 return error;
4363 if (unveil(NULL, NULL) != 0)
4364 return got_error_from_errno("unveil");
4366 return NULL;
4369 static const struct got_error *
4370 init_mock_term(const char *test_script_path)
4372 const struct got_error *err = NULL;
4373 const char *screen_dump_path;
4374 int in;
4376 if (test_script_path == NULL || *test_script_path == '\0')
4377 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4379 tog_io.f = fopen(test_script_path, "re");
4380 if (tog_io.f == NULL) {
4381 err = got_error_from_errno_fmt("fopen: %s",
4382 test_script_path);
4383 goto done;
4386 /* test mode, we don't want any output */
4387 tog_io.cout = fopen("/dev/null", "w+");
4388 if (tog_io.cout == NULL) {
4389 err = got_error_from_errno2("fopen", "/dev/null");
4390 goto done;
4393 in = dup(fileno(tog_io.cout));
4394 if (in == -1) {
4395 err = got_error_from_errno("dup");
4396 goto done;
4398 tog_io.cin = fdopen(in, "r");
4399 if (tog_io.cin == NULL) {
4400 err = got_error_from_errno("fdopen");
4401 close(in);
4402 goto done;
4405 screen_dump_path = getenv("TOG_SCR_DUMP");
4406 if (screen_dump_path == NULL || *screen_dump_path == '\0')
4407 return got_error_msg(GOT_ERR_IO, "TOG_SCR_DUMP not defined");
4408 tog_io.sdump = fopen(screen_dump_path, "we");
4409 if (tog_io.sdump == NULL) {
4410 err = got_error_from_errno2("fopen", screen_dump_path);
4411 goto done;
4414 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4415 err = got_error_from_errno("fseeko");
4416 goto done;
4419 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4420 err = got_error_msg(GOT_ERR_IO,
4421 "newterm: failed to initialise curses");
4423 using_mock_io = 1;
4425 done:
4426 if (err)
4427 tog_io_close();
4428 return err;
4431 static void
4432 init_curses(void)
4434 if (using_mock_io) /* In test mode we use a fake terminal */
4435 return;
4437 initscr();
4439 cbreak();
4440 halfdelay(1); /* Fast refresh while initial view is loading. */
4441 noecho();
4442 nonl();
4443 intrflush(stdscr, FALSE);
4444 keypad(stdscr, TRUE);
4445 curs_set(0);
4446 if (getenv("TOG_COLORS") != NULL) {
4447 start_color();
4448 use_default_colors();
4451 return;
4454 static const struct got_error *
4455 set_tog_base_commit(struct got_repository *repo, struct got_worktree *worktree)
4457 tog_base_commit.id = got_object_id_dup(
4458 got_worktree_get_base_commit_id(worktree));
4459 if (tog_base_commit.id == NULL)
4460 return got_error_from_errno( "got_object_id_dup");
4462 return NULL;
4465 static const struct got_error *
4466 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4467 struct got_repository *repo, struct got_worktree *worktree)
4469 const struct got_error *err = NULL;
4471 if (argc == 0) {
4472 *in_repo_path = strdup("/");
4473 if (*in_repo_path == NULL)
4474 return got_error_from_errno("strdup");
4475 return NULL;
4478 if (worktree) {
4479 const char *prefix = got_worktree_get_path_prefix(worktree);
4480 char *p;
4482 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4483 if (err)
4484 return err;
4485 if (asprintf(in_repo_path, "%s%s%s", prefix,
4486 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4487 p) == -1) {
4488 err = got_error_from_errno("asprintf");
4489 *in_repo_path = NULL;
4491 free(p);
4492 } else
4493 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4495 return err;
4498 static const struct got_error *
4499 cmd_log(int argc, char *argv[])
4501 const struct got_error *error;
4502 struct got_repository *repo = NULL;
4503 struct got_worktree *worktree = NULL;
4504 struct got_object_id *start_id = NULL;
4505 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4506 char *keyword_idstr = NULL, *start_commit = NULL, *label = NULL;
4507 struct got_reference *ref = NULL;
4508 const char *head_ref_name = NULL;
4509 int ch, log_branches = 0;
4510 struct tog_view *view;
4511 int *pack_fds = NULL;
4513 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4514 switch (ch) {
4515 case 'b':
4516 log_branches = 1;
4517 break;
4518 case 'c':
4519 start_commit = optarg;
4520 break;
4521 case 'r':
4522 repo_path = realpath(optarg, NULL);
4523 if (repo_path == NULL)
4524 return got_error_from_errno2("realpath",
4525 optarg);
4526 break;
4527 default:
4528 usage_log();
4529 /* NOTREACHED */
4533 argc -= optind;
4534 argv += optind;
4536 if (argc > 1)
4537 usage_log();
4539 error = got_repo_pack_fds_open(&pack_fds);
4540 if (error != NULL)
4541 goto done;
4543 if (repo_path == NULL) {
4544 cwd = getcwd(NULL, 0);
4545 if (cwd == NULL) {
4546 error = got_error_from_errno("getcwd");
4547 goto done;
4549 error = got_worktree_open(&worktree, cwd, NULL);
4550 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4551 goto done;
4552 if (worktree)
4553 repo_path =
4554 strdup(got_worktree_get_repo_path(worktree));
4555 else
4556 repo_path = strdup(cwd);
4557 if (repo_path == NULL) {
4558 error = got_error_from_errno("strdup");
4559 goto done;
4563 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4564 if (error != NULL)
4565 goto done;
4567 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4568 repo, worktree);
4569 if (error)
4570 goto done;
4572 init_curses();
4574 error = apply_unveil(got_repo_get_path(repo),
4575 worktree ? got_worktree_get_root_path(worktree) : NULL);
4576 if (error)
4577 goto done;
4579 /* already loaded by tog_log_with_path()? */
4580 if (TAILQ_EMPTY(&tog_refs)) {
4581 error = tog_load_refs(repo, 0);
4582 if (error)
4583 goto done;
4586 if (start_commit == NULL) {
4587 error = got_repo_match_object_id(&start_id, &label,
4588 worktree ? got_worktree_get_head_ref_name(worktree) :
4589 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4590 if (error)
4591 goto done;
4592 head_ref_name = label;
4593 } else {
4594 error = got_keyword_to_idstr(&keyword_idstr, start_commit,
4595 repo, worktree);
4596 if (error != NULL)
4597 goto done;
4598 if (keyword_idstr != NULL)
4599 start_commit = keyword_idstr;
4601 error = got_ref_open(&ref, repo, start_commit, 0);
4602 if (error == NULL)
4603 head_ref_name = got_ref_get_name(ref);
4604 else if (error->code != GOT_ERR_NOT_REF)
4605 goto done;
4606 error = got_repo_match_object_id(&start_id, NULL,
4607 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4608 if (error)
4609 goto done;
4612 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4613 if (view == NULL) {
4614 error = got_error_from_errno("view_open");
4615 goto done;
4618 if (worktree) {
4619 error = set_tog_base_commit(repo, worktree);
4620 if (error != NULL)
4621 goto done;
4624 error = open_log_view(view, start_id, repo, head_ref_name,
4625 in_repo_path, log_branches, worktree);
4626 if (error)
4627 goto done;
4629 if (worktree) {
4630 /* The work tree will be closed by the log thread. */
4631 worktree = NULL;
4634 error = view_loop(view);
4636 done:
4637 free(tog_base_commit.id);
4638 free(keyword_idstr);
4639 free(in_repo_path);
4640 free(repo_path);
4641 free(cwd);
4642 free(start_id);
4643 free(label);
4644 if (ref)
4645 got_ref_close(ref);
4646 if (repo) {
4647 const struct got_error *close_err = got_repo_close(repo);
4648 if (error == NULL)
4649 error = close_err;
4651 if (worktree)
4652 got_worktree_close(worktree);
4653 if (pack_fds) {
4654 const struct got_error *pack_err =
4655 got_repo_pack_fds_close(pack_fds);
4656 if (error == NULL)
4657 error = pack_err;
4659 tog_free_refs();
4660 return error;
4663 __dead static void
4664 usage_diff(void)
4666 endwin();
4667 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4668 "object1 object2\n", getprogname());
4669 exit(1);
4672 static int
4673 match_line(const char *line, regex_t *regex, size_t nmatch,
4674 regmatch_t *regmatch)
4676 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4679 static struct tog_color *
4680 match_color(struct tog_colors *colors, const char *line)
4682 struct tog_color *tc = NULL;
4684 STAILQ_FOREACH(tc, colors, entry) {
4685 if (match_line(line, &tc->regex, 0, NULL))
4686 return tc;
4689 return NULL;
4692 static const struct got_error *
4693 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4694 WINDOW *window, int skipcol, regmatch_t *regmatch)
4696 const struct got_error *err = NULL;
4697 char *exstr = NULL;
4698 wchar_t *wline = NULL;
4699 int rme, rms, n, width, scrollx;
4700 int width0 = 0, width1 = 0, width2 = 0;
4701 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4703 *wtotal = 0;
4705 rms = regmatch->rm_so;
4706 rme = regmatch->rm_eo;
4708 err = expand_tab(&exstr, line);
4709 if (err)
4710 return err;
4712 /* Split the line into 3 segments, according to match offsets. */
4713 seg0 = strndup(exstr, rms);
4714 if (seg0 == NULL) {
4715 err = got_error_from_errno("strndup");
4716 goto done;
4718 seg1 = strndup(exstr + rms, rme - rms);
4719 if (seg1 == NULL) {
4720 err = got_error_from_errno("strndup");
4721 goto done;
4723 seg2 = strdup(exstr + rme);
4724 if (seg2 == NULL) {
4725 err = got_error_from_errno("strndup");
4726 goto done;
4729 /* draw up to matched token if we haven't scrolled past it */
4730 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4731 col_tab_align, 1);
4732 if (err)
4733 goto done;
4734 n = MAX(width0 - skipcol, 0);
4735 if (n) {
4736 free(wline);
4737 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4738 wlimit, col_tab_align, 1);
4739 if (err)
4740 goto done;
4741 waddwstr(window, &wline[scrollx]);
4742 wlimit -= width;
4743 *wtotal += width;
4746 if (wlimit > 0) {
4747 int i = 0, w = 0;
4748 size_t wlen;
4750 free(wline);
4751 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4752 col_tab_align, 1);
4753 if (err)
4754 goto done;
4755 wlen = wcslen(wline);
4756 while (i < wlen) {
4757 width = wcwidth(wline[i]);
4758 if (width == -1) {
4759 /* should not happen, tabs are expanded */
4760 err = got_error(GOT_ERR_RANGE);
4761 goto done;
4763 if (width0 + w + width > skipcol)
4764 break;
4765 w += width;
4766 i++;
4768 /* draw (visible part of) matched token (if scrolled into it) */
4769 if (width1 - w > 0) {
4770 wattron(window, A_STANDOUT);
4771 waddwstr(window, &wline[i]);
4772 wattroff(window, A_STANDOUT);
4773 wlimit -= (width1 - w);
4774 *wtotal += (width1 - w);
4778 if (wlimit > 0) { /* draw rest of line */
4779 free(wline);
4780 if (skipcol > width0 + width1) {
4781 err = format_line(&wline, &width2, &scrollx, seg2,
4782 skipcol - (width0 + width1), wlimit,
4783 col_tab_align, 1);
4784 if (err)
4785 goto done;
4786 waddwstr(window, &wline[scrollx]);
4787 } else {
4788 err = format_line(&wline, &width2, NULL, seg2, 0,
4789 wlimit, col_tab_align, 1);
4790 if (err)
4791 goto done;
4792 waddwstr(window, wline);
4794 *wtotal += width2;
4796 done:
4797 free(wline);
4798 free(exstr);
4799 free(seg0);
4800 free(seg1);
4801 free(seg2);
4802 return err;
4805 static int
4806 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4808 FILE *f = NULL;
4809 int *eof, *first, *selected;
4811 if (view->type == TOG_VIEW_DIFF) {
4812 struct tog_diff_view_state *s = &view->state.diff;
4814 first = &s->first_displayed_line;
4815 selected = first;
4816 eof = &s->eof;
4817 f = s->f;
4818 } else if (view->type == TOG_VIEW_HELP) {
4819 struct tog_help_view_state *s = &view->state.help;
4821 first = &s->first_displayed_line;
4822 selected = first;
4823 eof = &s->eof;
4824 f = s->f;
4825 } else if (view->type == TOG_VIEW_BLAME) {
4826 struct tog_blame_view_state *s = &view->state.blame;
4828 first = &s->first_displayed_line;
4829 selected = &s->selected_line;
4830 eof = &s->eof;
4831 f = s->blame.f;
4832 } else
4833 return 0;
4835 /* Center gline in the middle of the page like vi(1). */
4836 if (*lineno < view->gline - (view->nlines - 3) / 2)
4837 return 0;
4838 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4839 rewind(f);
4840 *eof = 0;
4841 *first = 1;
4842 *lineno = 0;
4843 *nprinted = 0;
4844 return 0;
4847 *selected = view->gline <= (view->nlines - 3) / 2 ?
4848 view->gline : (view->nlines - 3) / 2 + 1;
4849 view->gline = 0;
4851 return 1;
4854 static const struct got_error *
4855 draw_file(struct tog_view *view, const char *header)
4857 struct tog_diff_view_state *s = &view->state.diff;
4858 regmatch_t *regmatch = &view->regmatch;
4859 const struct got_error *err;
4860 int nprinted = 0;
4861 char *line;
4862 size_t linesize = 0;
4863 ssize_t linelen;
4864 wchar_t *wline;
4865 int width;
4866 int max_lines = view->nlines;
4867 int nlines = s->nlines;
4868 off_t line_offset;
4870 s->lineno = s->first_displayed_line - 1;
4871 line_offset = s->lines[s->first_displayed_line - 1].offset;
4872 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4873 return got_error_from_errno("fseek");
4875 werase(view->window);
4877 if (view->gline > s->nlines - 1)
4878 view->gline = s->nlines - 1;
4880 if (header) {
4881 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4882 1 : view->gline - (view->nlines - 3) / 2 :
4883 s->lineno + s->selected_line;
4885 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4886 return got_error_from_errno("asprintf");
4887 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4888 0, 0);
4889 free(line);
4890 if (err)
4891 return err;
4893 if (view_needs_focus_indication(view))
4894 wstandout(view->window);
4895 waddwstr(view->window, wline);
4896 free(wline);
4897 wline = NULL;
4898 while (width++ < view->ncols)
4899 waddch(view->window, ' ');
4900 if (view_needs_focus_indication(view))
4901 wstandend(view->window);
4903 if (max_lines <= 1)
4904 return NULL;
4905 max_lines--;
4908 s->eof = 0;
4909 view->maxx = 0;
4910 line = NULL;
4911 while (max_lines > 0 && nprinted < max_lines) {
4912 enum got_diff_line_type linetype;
4913 attr_t attr = 0;
4915 linelen = getline(&line, &linesize, s->f);
4916 if (linelen == -1) {
4917 if (feof(s->f)) {
4918 s->eof = 1;
4919 break;
4921 free(line);
4922 return got_ferror(s->f, GOT_ERR_IO);
4925 if (++s->lineno < s->first_displayed_line)
4926 continue;
4927 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4928 continue;
4929 if (s->lineno == view->hiline)
4930 attr = A_STANDOUT;
4932 /* Set view->maxx based on full line length. */
4933 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4934 view->x ? 1 : 0);
4935 if (err) {
4936 free(line);
4937 return err;
4939 view->maxx = MAX(view->maxx, width);
4940 free(wline);
4941 wline = NULL;
4943 linetype = s->lines[s->lineno].type;
4944 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4945 linetype < GOT_DIFF_LINE_CONTEXT)
4946 attr |= COLOR_PAIR(linetype);
4947 if (attr)
4948 wattron(view->window, attr);
4949 if (s->first_displayed_line + nprinted == s->matched_line &&
4950 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4951 err = add_matched_line(&width, line, view->ncols, 0,
4952 view->window, view->x, regmatch);
4953 if (err) {
4954 free(line);
4955 return err;
4957 } else {
4958 int skip;
4959 err = format_line(&wline, &width, &skip, line,
4960 view->x, view->ncols, 0, view->x ? 1 : 0);
4961 if (err) {
4962 free(line);
4963 return err;
4965 waddwstr(view->window, &wline[skip]);
4966 free(wline);
4967 wline = NULL;
4969 if (s->lineno == view->hiline) {
4970 /* highlight full gline length */
4971 while (width++ < view->ncols)
4972 waddch(view->window, ' ');
4973 } else {
4974 if (width <= view->ncols - 1)
4975 waddch(view->window, '\n');
4977 if (attr)
4978 wattroff(view->window, attr);
4979 if (++nprinted == 1)
4980 s->first_displayed_line = s->lineno;
4982 free(line);
4983 if (nprinted >= 1)
4984 s->last_displayed_line = s->first_displayed_line +
4985 (nprinted - 1);
4986 else
4987 s->last_displayed_line = s->first_displayed_line;
4989 view_border(view);
4991 if (s->eof) {
4992 while (nprinted < view->nlines) {
4993 waddch(view->window, '\n');
4994 nprinted++;
4997 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4998 view->ncols, 0, 0);
4999 if (err) {
5000 return err;
5003 wstandout(view->window);
5004 waddwstr(view->window, wline);
5005 free(wline);
5006 wline = NULL;
5007 wstandend(view->window);
5010 return NULL;
5013 static char *
5014 get_datestr(time_t *time, char *datebuf)
5016 struct tm mytm, *tm;
5017 char *p, *s;
5019 tm = gmtime_r(time, &mytm);
5020 if (tm == NULL)
5021 return NULL;
5022 s = asctime_r(tm, datebuf);
5023 if (s == NULL)
5024 return NULL;
5025 p = strchr(s, '\n');
5026 if (p)
5027 *p = '\0';
5028 return s;
5031 static const struct got_error *
5032 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
5033 off_t off, uint8_t type)
5035 struct got_diff_line *p;
5037 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
5038 if (p == NULL)
5039 return got_error_from_errno("reallocarray");
5040 *lines = p;
5041 (*lines)[*nlines].offset = off;
5042 (*lines)[*nlines].type = type;
5043 (*nlines)++;
5045 return NULL;
5048 static const struct got_error *
5049 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
5050 struct got_diff_line *s_lines, size_t s_nlines)
5052 struct got_diff_line *p;
5053 char buf[BUFSIZ];
5054 size_t i, r;
5056 if (fseeko(src, 0L, SEEK_SET) == -1)
5057 return got_error_from_errno("fseeko");
5059 for (;;) {
5060 r = fread(buf, 1, sizeof(buf), src);
5061 if (r == 0) {
5062 if (ferror(src))
5063 return got_error_from_errno("fread");
5064 if (feof(src))
5065 break;
5067 if (fwrite(buf, 1, r, dst) != r)
5068 return got_ferror(dst, GOT_ERR_IO);
5071 if (s_nlines == 0 && *d_nlines == 0)
5072 return NULL;
5075 * If commit info was in dst, increment line offsets
5076 * of the appended diff content, but skip s_lines[0]
5077 * because offset zero is already in *d_lines.
5079 if (*d_nlines > 0) {
5080 for (i = 1; i < s_nlines; ++i)
5081 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
5083 if (s_nlines > 0) {
5084 --s_nlines;
5085 ++s_lines;
5089 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
5090 if (p == NULL) {
5091 /* d_lines is freed in close_diff_view() */
5092 return got_error_from_errno("reallocarray");
5095 *d_lines = p;
5097 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
5098 *d_nlines += s_nlines;
5100 return NULL;
5103 static const struct got_error *
5104 write_commit_info(struct got_diff_line **lines, size_t *nlines,
5105 struct got_object_id *commit_id, struct got_reflist_head *refs,
5106 struct got_repository *repo, int ignore_ws, int force_text_diff,
5107 struct got_diffstat_cb_arg *dsa, FILE *outfile)
5109 const struct got_error *err = NULL;
5110 char datebuf[26], *datestr;
5111 struct got_commit_object *commit;
5112 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
5113 time_t committer_time;
5114 const char *author, *committer;
5115 char *refs_str = NULL;
5116 struct got_pathlist_entry *pe;
5117 off_t outoff = 0;
5118 int n;
5120 err = build_refs_str(&refs_str, refs, commit_id, repo);
5121 if (err)
5122 return err;
5124 err = got_object_open_as_commit(&commit, repo, commit_id);
5125 if (err)
5126 return err;
5128 err = got_object_id_str(&id_str, commit_id);
5129 if (err) {
5130 err = got_error_from_errno("got_object_id_str");
5131 goto done;
5134 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
5135 if (err)
5136 goto done;
5138 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
5139 refs_str ? refs_str : "", refs_str ? ")" : "");
5140 if (n < 0) {
5141 err = got_error_from_errno("fprintf");
5142 goto done;
5144 outoff += n;
5145 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
5146 if (err)
5147 goto done;
5149 n = fprintf(outfile, "from: %s\n",
5150 got_object_commit_get_author(commit));
5151 if (n < 0) {
5152 err = got_error_from_errno("fprintf");
5153 goto done;
5155 outoff += n;
5156 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
5157 if (err)
5158 goto done;
5160 author = got_object_commit_get_author(commit);
5161 committer = got_object_commit_get_committer(commit);
5162 if (strcmp(author, committer) != 0) {
5163 n = fprintf(outfile, "via: %s\n", committer);
5164 if (n < 0) {
5165 err = got_error_from_errno("fprintf");
5166 goto done;
5168 outoff += n;
5169 err = add_line_metadata(lines, nlines, outoff,
5170 GOT_DIFF_LINE_AUTHOR);
5171 if (err)
5172 goto done;
5174 committer_time = got_object_commit_get_committer_time(commit);
5175 datestr = get_datestr(&committer_time, datebuf);
5176 if (datestr) {
5177 n = fprintf(outfile, "date: %s UTC\n", datestr);
5178 if (n < 0) {
5179 err = got_error_from_errno("fprintf");
5180 goto done;
5182 outoff += n;
5183 err = add_line_metadata(lines, nlines, outoff,
5184 GOT_DIFF_LINE_DATE);
5185 if (err)
5186 goto done;
5188 if (got_object_commit_get_nparents(commit) > 1) {
5189 const struct got_object_id_queue *parent_ids;
5190 struct got_object_qid *qid;
5191 int pn = 1;
5192 parent_ids = got_object_commit_get_parent_ids(commit);
5193 STAILQ_FOREACH(qid, parent_ids, entry) {
5194 err = got_object_id_str(&id_str, &qid->id);
5195 if (err)
5196 goto done;
5197 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
5198 if (n < 0) {
5199 err = got_error_from_errno("fprintf");
5200 goto done;
5202 outoff += n;
5203 err = add_line_metadata(lines, nlines, outoff,
5204 GOT_DIFF_LINE_META);
5205 if (err)
5206 goto done;
5207 free(id_str);
5208 id_str = NULL;
5212 err = got_object_commit_get_logmsg(&logmsg, commit);
5213 if (err)
5214 goto done;
5215 s = logmsg;
5216 while ((line = strsep(&s, "\n")) != NULL) {
5217 n = fprintf(outfile, "%s\n", line);
5218 if (n < 0) {
5219 err = got_error_from_errno("fprintf");
5220 goto done;
5222 outoff += n;
5223 err = add_line_metadata(lines, nlines, outoff,
5224 GOT_DIFF_LINE_LOGMSG);
5225 if (err)
5226 goto done;
5229 TAILQ_FOREACH(pe, dsa->paths, entry) {
5230 struct got_diff_changed_path *cp = pe->data;
5231 int pad = dsa->max_path_len - pe->path_len + 1;
5233 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5234 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5235 dsa->rm_cols + 1, cp->rm);
5236 if (n < 0) {
5237 err = got_error_from_errno("fprintf");
5238 goto done;
5240 outoff += n;
5241 err = add_line_metadata(lines, nlines, outoff,
5242 GOT_DIFF_LINE_CHANGES);
5243 if (err)
5244 goto done;
5247 fputc('\n', outfile);
5248 outoff++;
5249 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5250 if (err)
5251 goto done;
5253 n = fprintf(outfile,
5254 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5255 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5256 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5257 if (n < 0) {
5258 err = got_error_from_errno("fprintf");
5259 goto done;
5261 outoff += n;
5262 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5263 if (err)
5264 goto done;
5266 fputc('\n', outfile);
5267 outoff++;
5268 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5269 done:
5270 free(id_str);
5271 free(logmsg);
5272 free(refs_str);
5273 got_object_commit_close(commit);
5274 if (err) {
5275 free(*lines);
5276 *lines = NULL;
5277 *nlines = 0;
5279 return err;
5282 static const struct got_error *
5283 create_diff(struct tog_diff_view_state *s)
5285 const struct got_error *err = NULL;
5286 FILE *f = NULL, *tmp_diff_file = NULL;
5287 int obj_type;
5288 struct got_diff_line *lines = NULL;
5289 struct got_pathlist_head changed_paths;
5291 TAILQ_INIT(&changed_paths);
5293 free(s->lines);
5294 s->lines = malloc(sizeof(*s->lines));
5295 if (s->lines == NULL)
5296 return got_error_from_errno("malloc");
5297 s->nlines = 0;
5299 f = got_opentemp();
5300 if (f == NULL) {
5301 err = got_error_from_errno("got_opentemp");
5302 goto done;
5304 tmp_diff_file = got_opentemp();
5305 if (tmp_diff_file == NULL) {
5306 err = got_error_from_errno("got_opentemp");
5307 goto done;
5309 if (s->f && fclose(s->f) == EOF) {
5310 err = got_error_from_errno("fclose");
5311 goto done;
5313 s->f = f;
5315 if (s->id1)
5316 err = got_object_get_type(&obj_type, s->repo, s->id1);
5317 else
5318 err = got_object_get_type(&obj_type, s->repo, s->id2);
5319 if (err)
5320 goto done;
5322 switch (obj_type) {
5323 case GOT_OBJ_TYPE_BLOB:
5324 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5325 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5326 s->label1, s->label2, tog_diff_algo, s->diff_context,
5327 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5328 s->f);
5329 break;
5330 case GOT_OBJ_TYPE_TREE:
5331 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5332 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5333 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5334 s->force_text_diff, NULL, s->repo, s->f);
5335 break;
5336 case GOT_OBJ_TYPE_COMMIT: {
5337 const struct got_object_id_queue *parent_ids;
5338 struct got_object_qid *pid;
5339 struct got_commit_object *commit2;
5340 struct got_reflist_head *refs;
5341 size_t nlines = 0;
5342 struct got_diffstat_cb_arg dsa = {
5343 0, 0, 0, 0, 0, 0,
5344 &changed_paths,
5345 s->ignore_whitespace,
5346 s->force_text_diff,
5347 tog_diff_algo
5350 lines = malloc(sizeof(*lines));
5351 if (lines == NULL) {
5352 err = got_error_from_errno("malloc");
5353 goto done;
5356 /* build diff first in tmp file then append to commit info */
5357 err = got_diff_objects_as_commits(&lines, &nlines,
5358 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5359 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5360 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5361 if (err)
5362 break;
5364 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5365 if (err)
5366 goto done;
5367 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5368 /* Show commit info if we're diffing to a parent/root commit. */
5369 if (s->id1 == NULL) {
5370 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5371 refs, s->repo, s->ignore_whitespace,
5372 s->force_text_diff, &dsa, s->f);
5373 if (err)
5374 goto done;
5375 } else {
5376 parent_ids = got_object_commit_get_parent_ids(commit2);
5377 STAILQ_FOREACH(pid, parent_ids, entry) {
5378 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5379 err = write_commit_info(&s->lines,
5380 &s->nlines, s->id2, refs, s->repo,
5381 s->ignore_whitespace,
5382 s->force_text_diff, &dsa, s->f);
5383 if (err)
5384 goto done;
5385 break;
5389 got_object_commit_close(commit2);
5391 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5392 lines, nlines);
5393 break;
5395 default:
5396 err = got_error(GOT_ERR_OBJ_TYPE);
5397 break;
5399 done:
5400 free(lines);
5401 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5402 if (s->f && fflush(s->f) != 0 && err == NULL)
5403 err = got_error_from_errno("fflush");
5404 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5405 err = got_error_from_errno("fclose");
5406 return err;
5409 static void
5410 diff_view_indicate_progress(struct tog_view *view)
5412 mvwaddstr(view->window, 0, 0, "diffing...");
5413 update_panels();
5414 doupdate();
5417 static const struct got_error *
5418 search_start_diff_view(struct tog_view *view)
5420 struct tog_diff_view_state *s = &view->state.diff;
5422 s->matched_line = 0;
5423 return NULL;
5426 static void
5427 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5428 size_t *nlines, int **first, int **last, int **match, int **selected)
5430 struct tog_diff_view_state *s = &view->state.diff;
5432 *f = s->f;
5433 *nlines = s->nlines;
5434 *line_offsets = NULL;
5435 *match = &s->matched_line;
5436 *first = &s->first_displayed_line;
5437 *last = &s->last_displayed_line;
5438 *selected = &s->selected_line;
5441 static const struct got_error *
5442 search_next_view_match(struct tog_view *view)
5444 const struct got_error *err = NULL;
5445 FILE *f;
5446 int lineno;
5447 char *line = NULL;
5448 size_t linesize = 0;
5449 ssize_t linelen;
5450 off_t *line_offsets;
5451 size_t nlines = 0;
5452 int *first, *last, *match, *selected;
5454 if (!view->search_setup)
5455 return got_error_msg(GOT_ERR_NOT_IMPL,
5456 "view search not supported");
5457 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5458 &match, &selected);
5460 if (!view->searching) {
5461 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5462 return NULL;
5465 if (*match) {
5466 if (view->searching == TOG_SEARCH_FORWARD)
5467 lineno = *first + 1;
5468 else
5469 lineno = *first - 1;
5470 } else
5471 lineno = *first - 1 + *selected;
5473 while (1) {
5474 off_t offset;
5476 if (lineno <= 0 || lineno > nlines) {
5477 if (*match == 0) {
5478 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5479 break;
5482 if (view->searching == TOG_SEARCH_FORWARD)
5483 lineno = 1;
5484 else
5485 lineno = nlines;
5488 offset = view->type == TOG_VIEW_DIFF ?
5489 view->state.diff.lines[lineno - 1].offset :
5490 line_offsets[lineno - 1];
5491 if (fseeko(f, offset, SEEK_SET) != 0) {
5492 free(line);
5493 return got_error_from_errno("fseeko");
5495 linelen = getline(&line, &linesize, f);
5496 if (linelen != -1) {
5497 char *exstr;
5498 err = expand_tab(&exstr, line);
5499 if (err)
5500 break;
5501 if (match_line(exstr, &view->regex, 1,
5502 &view->regmatch)) {
5503 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5504 *match = lineno;
5505 free(exstr);
5506 break;
5508 free(exstr);
5510 if (view->searching == TOG_SEARCH_FORWARD)
5511 lineno++;
5512 else
5513 lineno--;
5515 free(line);
5517 if (*match) {
5518 *first = *match;
5519 *selected = 1;
5522 return err;
5525 static const struct got_error *
5526 close_diff_view(struct tog_view *view)
5528 const struct got_error *err = NULL;
5529 struct tog_diff_view_state *s = &view->state.diff;
5531 free(s->id1);
5532 s->id1 = NULL;
5533 free(s->id2);
5534 s->id2 = NULL;
5535 if (s->f && fclose(s->f) == EOF)
5536 err = got_error_from_errno("fclose");
5537 s->f = NULL;
5538 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5539 err = got_error_from_errno("fclose");
5540 s->f1 = NULL;
5541 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5542 err = got_error_from_errno("fclose");
5543 s->f2 = NULL;
5544 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5545 err = got_error_from_errno("close");
5546 s->fd1 = -1;
5547 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5548 err = got_error_from_errno("close");
5549 s->fd2 = -1;
5550 free(s->lines);
5551 s->lines = NULL;
5552 s->nlines = 0;
5553 return err;
5556 static const struct got_error *
5557 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5558 struct got_object_id *id2, const char *label1, const char *label2,
5559 int diff_context, int ignore_whitespace, int force_text_diff,
5560 struct tog_view *parent_view, struct got_repository *repo)
5562 const struct got_error *err;
5563 struct tog_diff_view_state *s = &view->state.diff;
5565 memset(s, 0, sizeof(*s));
5566 s->fd1 = -1;
5567 s->fd2 = -1;
5569 if (id1 != NULL && id2 != NULL) {
5570 int type1, type2;
5572 err = got_object_get_type(&type1, repo, id1);
5573 if (err)
5574 goto done;
5575 err = got_object_get_type(&type2, repo, id2);
5576 if (err)
5577 goto done;
5579 if (type1 != type2) {
5580 err = got_error(GOT_ERR_OBJ_TYPE);
5581 goto done;
5584 s->first_displayed_line = 1;
5585 s->last_displayed_line = view->nlines;
5586 s->selected_line = 1;
5587 s->repo = repo;
5588 s->id1 = id1;
5589 s->id2 = id2;
5590 s->label1 = label1;
5591 s->label2 = label2;
5593 if (id1) {
5594 s->id1 = got_object_id_dup(id1);
5595 if (s->id1 == NULL) {
5596 err = got_error_from_errno("got_object_id_dup");
5597 goto done;
5599 } else
5600 s->id1 = NULL;
5602 s->id2 = got_object_id_dup(id2);
5603 if (s->id2 == NULL) {
5604 err = got_error_from_errno("got_object_id_dup");
5605 goto done;
5608 s->f1 = got_opentemp();
5609 if (s->f1 == NULL) {
5610 err = got_error_from_errno("got_opentemp");
5611 goto done;
5614 s->f2 = got_opentemp();
5615 if (s->f2 == NULL) {
5616 err = got_error_from_errno("got_opentemp");
5617 goto done;
5620 s->fd1 = got_opentempfd();
5621 if (s->fd1 == -1) {
5622 err = got_error_from_errno("got_opentempfd");
5623 goto done;
5626 s->fd2 = got_opentempfd();
5627 if (s->fd2 == -1) {
5628 err = got_error_from_errno("got_opentempfd");
5629 goto done;
5632 s->diff_context = diff_context;
5633 s->ignore_whitespace = ignore_whitespace;
5634 s->force_text_diff = force_text_diff;
5635 s->parent_view = parent_view;
5636 s->repo = repo;
5638 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5639 int rc;
5641 rc = init_pair(GOT_DIFF_LINE_MINUS,
5642 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5643 if (rc != ERR)
5644 rc = init_pair(GOT_DIFF_LINE_PLUS,
5645 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5646 if (rc != ERR)
5647 rc = init_pair(GOT_DIFF_LINE_HUNK,
5648 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5649 if (rc != ERR)
5650 rc = init_pair(GOT_DIFF_LINE_META,
5651 get_color_value("TOG_COLOR_DIFF_META"), -1);
5652 if (rc != ERR)
5653 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5654 get_color_value("TOG_COLOR_DIFF_META"), -1);
5655 if (rc != ERR)
5656 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5657 get_color_value("TOG_COLOR_DIFF_META"), -1);
5658 if (rc != ERR)
5659 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5660 get_color_value("TOG_COLOR_DIFF_META"), -1);
5661 if (rc != ERR)
5662 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5663 get_color_value("TOG_COLOR_AUTHOR"), -1);
5664 if (rc != ERR)
5665 rc = init_pair(GOT_DIFF_LINE_DATE,
5666 get_color_value("TOG_COLOR_DATE"), -1);
5667 if (rc == ERR) {
5668 err = got_error(GOT_ERR_RANGE);
5669 goto done;
5673 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5674 view_is_splitscreen(view))
5675 show_log_view(parent_view); /* draw border */
5676 diff_view_indicate_progress(view);
5678 err = create_diff(s);
5680 view->show = show_diff_view;
5681 view->input = input_diff_view;
5682 view->reset = reset_diff_view;
5683 view->close = close_diff_view;
5684 view->search_start = search_start_diff_view;
5685 view->search_setup = search_setup_diff_view;
5686 view->search_next = search_next_view_match;
5687 done:
5688 if (err) {
5689 if (view->close == NULL)
5690 close_diff_view(view);
5691 view_close(view);
5693 return err;
5696 static const struct got_error *
5697 show_diff_view(struct tog_view *view)
5699 const struct got_error *err;
5700 struct tog_diff_view_state *s = &view->state.diff;
5701 char *id_str1 = NULL, *id_str2, *header;
5702 const char *label1, *label2;
5704 if (s->id1) {
5705 err = got_object_id_str(&id_str1, s->id1);
5706 if (err)
5707 return err;
5708 label1 = s->label1 ? s->label1 : id_str1;
5709 } else
5710 label1 = "/dev/null";
5712 err = got_object_id_str(&id_str2, s->id2);
5713 if (err)
5714 return err;
5715 label2 = s->label2 ? s->label2 : id_str2;
5717 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5718 err = got_error_from_errno("asprintf");
5719 free(id_str1);
5720 free(id_str2);
5721 return err;
5723 free(id_str1);
5724 free(id_str2);
5726 err = draw_file(view, header);
5727 free(header);
5728 return err;
5731 static const struct got_error *
5732 set_selected_commit(struct tog_diff_view_state *s,
5733 struct commit_queue_entry *entry)
5735 const struct got_error *err;
5736 const struct got_object_id_queue *parent_ids;
5737 struct got_commit_object *selected_commit;
5738 struct got_object_qid *pid;
5740 free(s->id2);
5741 s->id2 = got_object_id_dup(entry->id);
5742 if (s->id2 == NULL)
5743 return got_error_from_errno("got_object_id_dup");
5745 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5746 if (err)
5747 return err;
5748 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5749 free(s->id1);
5750 pid = STAILQ_FIRST(parent_ids);
5751 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5752 got_object_commit_close(selected_commit);
5753 return NULL;
5756 static const struct got_error *
5757 reset_diff_view(struct tog_view *view)
5759 struct tog_diff_view_state *s = &view->state.diff;
5761 view->count = 0;
5762 wclear(view->window);
5763 s->first_displayed_line = 1;
5764 s->last_displayed_line = view->nlines;
5765 s->matched_line = 0;
5766 diff_view_indicate_progress(view);
5767 return create_diff(s);
5770 static void
5771 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5773 int start, i;
5775 i = start = s->first_displayed_line - 1;
5777 while (s->lines[i].type != type) {
5778 if (i == 0)
5779 i = s->nlines - 1;
5780 if (--i == start)
5781 return; /* do nothing, requested type not in file */
5784 s->selected_line = 1;
5785 s->first_displayed_line = i;
5788 static void
5789 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5791 int start, i;
5793 i = start = s->first_displayed_line + 1;
5795 while (s->lines[i].type != type) {
5796 if (i == s->nlines - 1)
5797 i = 0;
5798 if (++i == start)
5799 return; /* do nothing, requested type not in file */
5802 s->selected_line = 1;
5803 s->first_displayed_line = i;
5806 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5807 int, int, int);
5808 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5809 int, int);
5811 static const struct got_error *
5812 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5814 const struct got_error *err = NULL;
5815 struct tog_diff_view_state *s = &view->state.diff;
5816 struct tog_log_view_state *ls;
5817 struct commit_queue_entry *old_selected_entry;
5818 char *line = NULL;
5819 size_t linesize = 0;
5820 ssize_t linelen;
5821 int i, nscroll = view->nlines - 1, up = 0;
5823 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5825 switch (ch) {
5826 case '0':
5827 case '$':
5828 case KEY_RIGHT:
5829 case 'l':
5830 case KEY_LEFT:
5831 case 'h':
5832 horizontal_scroll_input(view, ch);
5833 break;
5834 case 'a':
5835 case 'w':
5836 if (ch == 'a') {
5837 s->force_text_diff = !s->force_text_diff;
5838 view->action = s->force_text_diff ?
5839 "force ASCII text enabled" :
5840 "force ASCII text disabled";
5842 else if (ch == 'w') {
5843 s->ignore_whitespace = !s->ignore_whitespace;
5844 view->action = s->ignore_whitespace ?
5845 "ignore whitespace enabled" :
5846 "ignore whitespace disabled";
5848 err = reset_diff_view(view);
5849 break;
5850 case 'g':
5851 case KEY_HOME:
5852 s->first_displayed_line = 1;
5853 view->count = 0;
5854 break;
5855 case 'G':
5856 case KEY_END:
5857 view->count = 0;
5858 if (s->eof)
5859 break;
5861 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5862 s->eof = 1;
5863 break;
5864 case 'k':
5865 case KEY_UP:
5866 case CTRL('p'):
5867 if (s->first_displayed_line > 1)
5868 s->first_displayed_line--;
5869 else
5870 view->count = 0;
5871 break;
5872 case CTRL('u'):
5873 case 'u':
5874 nscroll /= 2;
5875 /* FALL THROUGH */
5876 case KEY_PPAGE:
5877 case CTRL('b'):
5878 case 'b':
5879 if (s->first_displayed_line == 1) {
5880 view->count = 0;
5881 break;
5883 i = 0;
5884 while (i++ < nscroll && s->first_displayed_line > 1)
5885 s->first_displayed_line--;
5886 break;
5887 case 'j':
5888 case KEY_DOWN:
5889 case CTRL('n'):
5890 if (!s->eof)
5891 s->first_displayed_line++;
5892 else
5893 view->count = 0;
5894 break;
5895 case CTRL('d'):
5896 case 'd':
5897 nscroll /= 2;
5898 /* FALL THROUGH */
5899 case KEY_NPAGE:
5900 case CTRL('f'):
5901 case 'f':
5902 case ' ':
5903 if (s->eof) {
5904 view->count = 0;
5905 break;
5907 i = 0;
5908 while (!s->eof && i++ < nscroll) {
5909 linelen = getline(&line, &linesize, s->f);
5910 s->first_displayed_line++;
5911 if (linelen == -1) {
5912 if (feof(s->f)) {
5913 s->eof = 1;
5914 } else
5915 err = got_ferror(s->f, GOT_ERR_IO);
5916 break;
5919 free(line);
5920 break;
5921 case '(':
5922 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5923 break;
5924 case ')':
5925 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5926 break;
5927 case '{':
5928 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5929 break;
5930 case '}':
5931 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5932 break;
5933 case '[':
5934 if (s->diff_context > 0) {
5935 s->diff_context--;
5936 s->matched_line = 0;
5937 diff_view_indicate_progress(view);
5938 err = create_diff(s);
5939 if (s->first_displayed_line + view->nlines - 1 >
5940 s->nlines) {
5941 s->first_displayed_line = 1;
5942 s->last_displayed_line = view->nlines;
5944 } else
5945 view->count = 0;
5946 break;
5947 case ']':
5948 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5949 s->diff_context++;
5950 s->matched_line = 0;
5951 diff_view_indicate_progress(view);
5952 err = create_diff(s);
5953 } else
5954 view->count = 0;
5955 break;
5956 case '<':
5957 case ',':
5958 case 'K':
5959 up = 1;
5960 /* FALL THROUGH */
5961 case '>':
5962 case '.':
5963 case 'J':
5964 if (s->parent_view == NULL) {
5965 view->count = 0;
5966 break;
5968 s->parent_view->count = view->count;
5970 if (s->parent_view->type == TOG_VIEW_LOG) {
5971 ls = &s->parent_view->state.log;
5972 old_selected_entry = ls->selected_entry;
5974 err = input_log_view(NULL, s->parent_view,
5975 up ? KEY_UP : KEY_DOWN);
5976 if (err)
5977 break;
5978 view->count = s->parent_view->count;
5980 if (old_selected_entry == ls->selected_entry)
5981 break;
5983 err = set_selected_commit(s, ls->selected_entry);
5984 if (err)
5985 break;
5986 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5987 struct tog_blame_view_state *bs;
5988 struct got_object_id *id, *prev_id;
5990 bs = &s->parent_view->state.blame;
5991 prev_id = get_annotation_for_line(bs->blame.lines,
5992 bs->blame.nlines, bs->last_diffed_line);
5994 err = input_blame_view(&view, s->parent_view,
5995 up ? KEY_UP : KEY_DOWN);
5996 if (err)
5997 break;
5998 view->count = s->parent_view->count;
6000 if (prev_id == NULL)
6001 break;
6002 id = get_selected_commit_id(bs->blame.lines,
6003 bs->blame.nlines, bs->first_displayed_line,
6004 bs->selected_line);
6005 if (id == NULL)
6006 break;
6008 if (!got_object_id_cmp(prev_id, id))
6009 break;
6011 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
6012 if (err)
6013 break;
6015 s->first_displayed_line = 1;
6016 s->last_displayed_line = view->nlines;
6017 s->matched_line = 0;
6018 view->x = 0;
6020 diff_view_indicate_progress(view);
6021 err = create_diff(s);
6022 break;
6023 default:
6024 view->count = 0;
6025 break;
6028 return err;
6031 static const struct got_error *
6032 cmd_diff(int argc, char *argv[])
6034 const struct got_error *error;
6035 struct got_repository *repo = NULL;
6036 struct got_worktree *worktree = NULL;
6037 struct got_object_id *id1 = NULL, *id2 = NULL;
6038 char *repo_path = NULL, *cwd = NULL;
6039 char *id_str1 = NULL, *id_str2 = NULL;
6040 char *keyword_idstr1 = NULL, *keyword_idstr2 = NULL;
6041 char *label1 = NULL, *label2 = NULL;
6042 int diff_context = 3, ignore_whitespace = 0;
6043 int ch, force_text_diff = 0;
6044 const char *errstr;
6045 struct tog_view *view;
6046 int *pack_fds = NULL;
6048 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
6049 switch (ch) {
6050 case 'a':
6051 force_text_diff = 1;
6052 break;
6053 case 'C':
6054 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
6055 &errstr);
6056 if (errstr != NULL)
6057 errx(1, "number of context lines is %s: %s",
6058 errstr, errstr);
6059 break;
6060 case 'r':
6061 repo_path = realpath(optarg, NULL);
6062 if (repo_path == NULL)
6063 return got_error_from_errno2("realpath",
6064 optarg);
6065 got_path_strip_trailing_slashes(repo_path);
6066 break;
6067 case 'w':
6068 ignore_whitespace = 1;
6069 break;
6070 default:
6071 usage_diff();
6072 /* NOTREACHED */
6076 argc -= optind;
6077 argv += optind;
6079 if (argc == 0) {
6080 usage_diff(); /* TODO show local worktree changes */
6081 } else if (argc == 2) {
6082 id_str1 = argv[0];
6083 id_str2 = argv[1];
6084 } else
6085 usage_diff();
6087 error = got_repo_pack_fds_open(&pack_fds);
6088 if (error)
6089 goto done;
6091 if (repo_path == NULL) {
6092 cwd = getcwd(NULL, 0);
6093 if (cwd == NULL)
6094 return got_error_from_errno("getcwd");
6095 error = got_worktree_open(&worktree, cwd, NULL);
6096 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6097 goto done;
6098 if (worktree)
6099 repo_path =
6100 strdup(got_worktree_get_repo_path(worktree));
6101 else
6102 repo_path = strdup(cwd);
6103 if (repo_path == NULL) {
6104 error = got_error_from_errno("strdup");
6105 goto done;
6109 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6110 if (error)
6111 goto done;
6113 init_curses();
6115 error = apply_unveil(got_repo_get_path(repo), NULL);
6116 if (error)
6117 goto done;
6119 error = tog_load_refs(repo, 0);
6120 if (error)
6121 goto done;
6123 if (id_str1 != NULL) {
6124 error = got_keyword_to_idstr(&keyword_idstr1, id_str1,
6125 repo, worktree);
6126 if (error != NULL)
6127 goto done;
6128 if (keyword_idstr1 != NULL)
6129 id_str1 = keyword_idstr1;
6131 if (id_str2 != NULL) {
6132 error = got_keyword_to_idstr(&keyword_idstr2, id_str2,
6133 repo, worktree);
6134 if (error != NULL)
6135 goto done;
6136 if (keyword_idstr2 != NULL)
6137 id_str2 = keyword_idstr2;
6140 error = got_repo_match_object_id(&id1, &label1, id_str1,
6141 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6142 if (error)
6143 goto done;
6145 error = got_repo_match_object_id(&id2, &label2, id_str2,
6146 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
6147 if (error)
6148 goto done;
6150 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
6151 if (view == NULL) {
6152 error = got_error_from_errno("view_open");
6153 goto done;
6155 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
6156 ignore_whitespace, force_text_diff, NULL, repo);
6157 if (error)
6158 goto done;
6160 if (worktree) {
6161 error = set_tog_base_commit(repo, worktree);
6162 if (error != NULL)
6163 goto done;
6166 error = view_loop(view);
6168 done:
6169 free(tog_base_commit.id);
6170 free(keyword_idstr1);
6171 free(keyword_idstr2);
6172 free(label1);
6173 free(label2);
6174 free(repo_path);
6175 free(cwd);
6176 if (repo) {
6177 const struct got_error *close_err = got_repo_close(repo);
6178 if (error == NULL)
6179 error = close_err;
6181 if (worktree)
6182 got_worktree_close(worktree);
6183 if (pack_fds) {
6184 const struct got_error *pack_err =
6185 got_repo_pack_fds_close(pack_fds);
6186 if (error == NULL)
6187 error = pack_err;
6189 tog_free_refs();
6190 return error;
6193 __dead static void
6194 usage_blame(void)
6196 endwin();
6197 fprintf(stderr,
6198 "usage: %s blame [-c commit] [-r repository-path] path\n",
6199 getprogname());
6200 exit(1);
6203 struct tog_blame_line {
6204 int annotated;
6205 struct got_object_id *id;
6208 static const struct got_error *
6209 draw_blame(struct tog_view *view)
6211 struct tog_blame_view_state *s = &view->state.blame;
6212 struct tog_blame *blame = &s->blame;
6213 regmatch_t *regmatch = &view->regmatch;
6214 const struct got_error *err;
6215 int lineno = 0, nprinted = 0;
6216 char *line = NULL;
6217 size_t linesize = 0;
6218 ssize_t linelen;
6219 wchar_t *wline;
6220 int width;
6221 struct tog_blame_line *blame_line;
6222 struct got_object_id *prev_id = NULL;
6223 char *id_str;
6224 struct tog_color *tc;
6226 err = got_object_id_str(&id_str, &s->blamed_commit->id);
6227 if (err)
6228 return err;
6230 rewind(blame->f);
6231 werase(view->window);
6233 if (asprintf(&line, "commit %s", id_str) == -1) {
6234 err = got_error_from_errno("asprintf");
6235 free(id_str);
6236 return err;
6239 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6240 free(line);
6241 line = NULL;
6242 if (err)
6243 return err;
6244 if (view_needs_focus_indication(view))
6245 wstandout(view->window);
6246 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6247 if (tc)
6248 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
6249 waddwstr(view->window, wline);
6250 while (width++ < view->ncols)
6251 waddch(view->window, ' ');
6252 if (tc)
6253 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
6254 if (view_needs_focus_indication(view))
6255 wstandend(view->window);
6256 free(wline);
6257 wline = NULL;
6259 if (view->gline > blame->nlines)
6260 view->gline = blame->nlines;
6262 if (tog_io.wait_for_ui) {
6263 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6264 int rc;
6266 rc = pthread_cond_wait(&bta->blame_complete, &tog_mutex);
6267 if (rc)
6268 return got_error_set_errno(rc, "pthread_cond_wait");
6269 tog_io.wait_for_ui = 0;
6272 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6273 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6274 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6275 free(id_str);
6276 return got_error_from_errno("asprintf");
6278 free(id_str);
6279 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6280 free(line);
6281 line = NULL;
6282 if (err)
6283 return err;
6284 waddwstr(view->window, wline);
6285 free(wline);
6286 wline = NULL;
6287 if (width < view->ncols - 1)
6288 waddch(view->window, '\n');
6290 s->eof = 0;
6291 view->maxx = 0;
6292 while (nprinted < view->nlines - 2) {
6293 linelen = getline(&line, &linesize, blame->f);
6294 if (linelen == -1) {
6295 if (feof(blame->f)) {
6296 s->eof = 1;
6297 break;
6299 free(line);
6300 return got_ferror(blame->f, GOT_ERR_IO);
6302 if (++lineno < s->first_displayed_line)
6303 continue;
6304 if (view->gline && !gotoline(view, &lineno, &nprinted))
6305 continue;
6307 /* Set view->maxx based on full line length. */
6308 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6309 if (err) {
6310 free(line);
6311 return err;
6313 free(wline);
6314 wline = NULL;
6315 view->maxx = MAX(view->maxx, width);
6317 if (nprinted == s->selected_line - 1)
6318 wstandout(view->window);
6320 if (blame->nlines > 0) {
6321 blame_line = &blame->lines[lineno - 1];
6322 if (blame_line->annotated && prev_id &&
6323 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6324 !(nprinted == s->selected_line - 1)) {
6325 waddstr(view->window, " ");
6326 } else if (blame_line->annotated) {
6327 char *id_str;
6328 err = got_object_id_str(&id_str,
6329 blame_line->id);
6330 if (err) {
6331 free(line);
6332 return err;
6334 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6335 if (tc)
6336 wattr_on(view->window,
6337 COLOR_PAIR(tc->colorpair), NULL);
6338 wprintw(view->window, "%.8s", id_str);
6339 if (tc)
6340 wattr_off(view->window,
6341 COLOR_PAIR(tc->colorpair), NULL);
6342 free(id_str);
6343 prev_id = blame_line->id;
6344 } else {
6345 waddstr(view->window, "........");
6346 prev_id = NULL;
6348 } else {
6349 waddstr(view->window, "........");
6350 prev_id = NULL;
6353 if (nprinted == s->selected_line - 1)
6354 wstandend(view->window);
6355 waddstr(view->window, " ");
6357 if (view->ncols <= 9) {
6358 width = 9;
6359 } else if (s->first_displayed_line + nprinted ==
6360 s->matched_line &&
6361 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6362 err = add_matched_line(&width, line, view->ncols - 9, 9,
6363 view->window, view->x, regmatch);
6364 if (err) {
6365 free(line);
6366 return err;
6368 width += 9;
6369 } else {
6370 int skip;
6371 err = format_line(&wline, &width, &skip, line,
6372 view->x, view->ncols - 9, 9, 1);
6373 if (err) {
6374 free(line);
6375 return err;
6377 waddwstr(view->window, &wline[skip]);
6378 width += 9;
6379 free(wline);
6380 wline = NULL;
6383 if (width <= view->ncols - 1)
6384 waddch(view->window, '\n');
6385 if (++nprinted == 1)
6386 s->first_displayed_line = lineno;
6388 free(line);
6389 s->last_displayed_line = lineno;
6391 view_border(view);
6393 return NULL;
6396 static const struct got_error *
6397 blame_cb(void *arg, int nlines, int lineno,
6398 struct got_commit_object *commit, struct got_object_id *id)
6400 const struct got_error *err = NULL;
6401 struct tog_blame_cb_args *a = arg;
6402 struct tog_blame_line *line;
6403 int errcode;
6405 if (nlines != a->nlines ||
6406 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6407 return got_error(GOT_ERR_RANGE);
6409 errcode = pthread_mutex_lock(&tog_mutex);
6410 if (errcode)
6411 return got_error_set_errno(errcode, "pthread_mutex_lock");
6413 if (*a->quit) { /* user has quit the blame view */
6414 err = got_error(GOT_ERR_ITER_COMPLETED);
6415 goto done;
6418 if (lineno == -1)
6419 goto done; /* no change in this commit */
6421 line = &a->lines[lineno - 1];
6422 if (line->annotated)
6423 goto done;
6425 line->id = got_object_id_dup(id);
6426 if (line->id == NULL) {
6427 err = got_error_from_errno("got_object_id_dup");
6428 goto done;
6430 line->annotated = 1;
6431 done:
6432 errcode = pthread_mutex_unlock(&tog_mutex);
6433 if (errcode)
6434 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6435 return err;
6438 static void *
6439 blame_thread(void *arg)
6441 const struct got_error *err, *close_err;
6442 struct tog_blame_thread_args *ta = arg;
6443 struct tog_blame_cb_args *a = ta->cb_args;
6444 int errcode, fd1 = -1, fd2 = -1;
6445 FILE *f1 = NULL, *f2 = NULL;
6447 fd1 = got_opentempfd();
6448 if (fd1 == -1)
6449 return (void *)got_error_from_errno("got_opentempfd");
6451 fd2 = got_opentempfd();
6452 if (fd2 == -1) {
6453 err = got_error_from_errno("got_opentempfd");
6454 goto done;
6457 f1 = got_opentemp();
6458 if (f1 == NULL) {
6459 err = (void *)got_error_from_errno("got_opentemp");
6460 goto done;
6462 f2 = got_opentemp();
6463 if (f2 == NULL) {
6464 err = (void *)got_error_from_errno("got_opentemp");
6465 goto done;
6468 err = block_signals_used_by_main_thread();
6469 if (err)
6470 goto done;
6472 err = got_blame(ta->path, a->commit_id, ta->repo,
6473 tog_diff_algo, blame_cb, ta->cb_args,
6474 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6475 if (err && err->code == GOT_ERR_CANCELLED)
6476 err = NULL;
6478 errcode = pthread_mutex_lock(&tog_mutex);
6479 if (errcode) {
6480 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6481 goto done;
6484 close_err = got_repo_close(ta->repo);
6485 if (err == NULL)
6486 err = close_err;
6487 ta->repo = NULL;
6488 *ta->complete = 1;
6490 if (tog_io.wait_for_ui) {
6491 errcode = pthread_cond_signal(&ta->blame_complete);
6492 if (errcode && err == NULL)
6493 err = got_error_set_errno(errcode,
6494 "pthread_cond_signal");
6497 errcode = pthread_mutex_unlock(&tog_mutex);
6498 if (errcode && err == NULL)
6499 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6501 done:
6502 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6503 err = got_error_from_errno("close");
6504 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6505 err = got_error_from_errno("close");
6506 if (f1 && fclose(f1) == EOF && err == NULL)
6507 err = got_error_from_errno("fclose");
6508 if (f2 && fclose(f2) == EOF && err == NULL)
6509 err = got_error_from_errno("fclose");
6511 return (void *)err;
6514 static struct got_object_id *
6515 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6516 int first_displayed_line, int selected_line)
6518 struct tog_blame_line *line;
6520 if (nlines <= 0)
6521 return NULL;
6523 line = &lines[first_displayed_line - 1 + selected_line - 1];
6524 if (!line->annotated)
6525 return NULL;
6527 return line->id;
6530 static struct got_object_id *
6531 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6532 int lineno)
6534 struct tog_blame_line *line;
6536 if (nlines <= 0 || lineno >= nlines)
6537 return NULL;
6539 line = &lines[lineno - 1];
6540 if (!line->annotated)
6541 return NULL;
6543 return line->id;
6546 static const struct got_error *
6547 stop_blame(struct tog_blame *blame)
6549 const struct got_error *err = NULL;
6550 int i;
6552 if (blame->thread) {
6553 int errcode;
6554 errcode = pthread_mutex_unlock(&tog_mutex);
6555 if (errcode)
6556 return got_error_set_errno(errcode,
6557 "pthread_mutex_unlock");
6558 errcode = pthread_join(blame->thread, (void **)&err);
6559 if (errcode)
6560 return got_error_set_errno(errcode, "pthread_join");
6561 errcode = pthread_mutex_lock(&tog_mutex);
6562 if (errcode)
6563 return got_error_set_errno(errcode,
6564 "pthread_mutex_lock");
6565 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6566 err = NULL;
6567 blame->thread = 0; //NULL;
6569 if (blame->thread_args.repo) {
6570 const struct got_error *close_err;
6571 close_err = got_repo_close(blame->thread_args.repo);
6572 if (err == NULL)
6573 err = close_err;
6574 blame->thread_args.repo = NULL;
6576 if (blame->f) {
6577 if (fclose(blame->f) == EOF && err == NULL)
6578 err = got_error_from_errno("fclose");
6579 blame->f = NULL;
6581 if (blame->lines) {
6582 for (i = 0; i < blame->nlines; i++)
6583 free(blame->lines[i].id);
6584 free(blame->lines);
6585 blame->lines = NULL;
6587 free(blame->cb_args.commit_id);
6588 blame->cb_args.commit_id = NULL;
6589 if (blame->pack_fds) {
6590 const struct got_error *pack_err =
6591 got_repo_pack_fds_close(blame->pack_fds);
6592 if (err == NULL)
6593 err = pack_err;
6594 blame->pack_fds = NULL;
6596 return err;
6599 static const struct got_error *
6600 cancel_blame_view(void *arg)
6602 const struct got_error *err = NULL;
6603 int *done = arg;
6604 int errcode;
6606 errcode = pthread_mutex_lock(&tog_mutex);
6607 if (errcode)
6608 return got_error_set_errno(errcode,
6609 "pthread_mutex_unlock");
6611 if (*done)
6612 err = got_error(GOT_ERR_CANCELLED);
6614 errcode = pthread_mutex_unlock(&tog_mutex);
6615 if (errcode)
6616 return got_error_set_errno(errcode,
6617 "pthread_mutex_lock");
6619 return err;
6622 static const struct got_error *
6623 run_blame(struct tog_view *view)
6625 struct tog_blame_view_state *s = &view->state.blame;
6626 struct tog_blame *blame = &s->blame;
6627 const struct got_error *err = NULL;
6628 struct got_commit_object *commit = NULL;
6629 struct got_blob_object *blob = NULL;
6630 struct got_repository *thread_repo = NULL;
6631 struct got_object_id *obj_id = NULL;
6632 int obj_type, fd = -1;
6633 int *pack_fds = NULL;
6635 err = got_object_open_as_commit(&commit, s->repo,
6636 &s->blamed_commit->id);
6637 if (err)
6638 return err;
6640 fd = got_opentempfd();
6641 if (fd == -1) {
6642 err = got_error_from_errno("got_opentempfd");
6643 goto done;
6646 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6647 if (err)
6648 goto done;
6650 err = got_object_get_type(&obj_type, s->repo, obj_id);
6651 if (err)
6652 goto done;
6654 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6655 err = got_error(GOT_ERR_OBJ_TYPE);
6656 goto done;
6659 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6660 if (err)
6661 goto done;
6662 blame->f = got_opentemp();
6663 if (blame->f == NULL) {
6664 err = got_error_from_errno("got_opentemp");
6665 goto done;
6667 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6668 &blame->line_offsets, blame->f, blob);
6669 if (err)
6670 goto done;
6671 if (blame->nlines == 0) {
6672 s->blame_complete = 1;
6673 goto done;
6676 /* Don't include \n at EOF in the blame line count. */
6677 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6678 blame->nlines--;
6680 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6681 if (blame->lines == NULL) {
6682 err = got_error_from_errno("calloc");
6683 goto done;
6686 err = got_repo_pack_fds_open(&pack_fds);
6687 if (err)
6688 goto done;
6689 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6690 pack_fds);
6691 if (err)
6692 goto done;
6694 blame->pack_fds = pack_fds;
6695 blame->cb_args.view = view;
6696 blame->cb_args.lines = blame->lines;
6697 blame->cb_args.nlines = blame->nlines;
6698 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6699 if (blame->cb_args.commit_id == NULL) {
6700 err = got_error_from_errno("got_object_id_dup");
6701 goto done;
6703 blame->cb_args.quit = &s->done;
6705 blame->thread_args.path = s->path;
6706 blame->thread_args.repo = thread_repo;
6707 blame->thread_args.cb_args = &blame->cb_args;
6708 blame->thread_args.complete = &s->blame_complete;
6709 blame->thread_args.cancel_cb = cancel_blame_view;
6710 blame->thread_args.cancel_arg = &s->done;
6711 s->blame_complete = 0;
6713 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6714 s->first_displayed_line = 1;
6715 s->last_displayed_line = view->nlines;
6716 s->selected_line = 1;
6718 s->matched_line = 0;
6720 done:
6721 if (commit)
6722 got_object_commit_close(commit);
6723 if (fd != -1 && close(fd) == -1 && err == NULL)
6724 err = got_error_from_errno("close");
6725 if (blob)
6726 got_object_blob_close(blob);
6727 free(obj_id);
6728 if (err)
6729 stop_blame(blame);
6730 return err;
6733 static const struct got_error *
6734 open_blame_view(struct tog_view *view, char *path,
6735 struct got_object_id *commit_id, struct got_repository *repo)
6737 const struct got_error *err = NULL;
6738 struct tog_blame_view_state *s = &view->state.blame;
6740 STAILQ_INIT(&s->blamed_commits);
6742 s->path = strdup(path);
6743 if (s->path == NULL)
6744 return got_error_from_errno("strdup");
6746 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6747 if (err) {
6748 free(s->path);
6749 return err;
6752 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6753 s->first_displayed_line = 1;
6754 s->last_displayed_line = view->nlines;
6755 s->selected_line = 1;
6756 s->blame_complete = 0;
6757 s->repo = repo;
6758 s->commit_id = commit_id;
6759 memset(&s->blame, 0, sizeof(s->blame));
6761 STAILQ_INIT(&s->colors);
6762 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6763 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6764 get_color_value("TOG_COLOR_COMMIT"));
6765 if (err)
6766 return err;
6769 view->show = show_blame_view;
6770 view->input = input_blame_view;
6771 view->reset = reset_blame_view;
6772 view->close = close_blame_view;
6773 view->search_start = search_start_blame_view;
6774 view->search_setup = search_setup_blame_view;
6775 view->search_next = search_next_view_match;
6777 if (using_mock_io) {
6778 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6779 int rc;
6781 rc = pthread_cond_init(&bta->blame_complete, NULL);
6782 if (rc)
6783 return got_error_set_errno(rc, "pthread_cond_init");
6786 return run_blame(view);
6789 static const struct got_error *
6790 close_blame_view(struct tog_view *view)
6792 const struct got_error *err = NULL;
6793 struct tog_blame_view_state *s = &view->state.blame;
6795 if (s->blame.thread)
6796 err = stop_blame(&s->blame);
6798 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6799 struct got_object_qid *blamed_commit;
6800 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6801 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6802 got_object_qid_free(blamed_commit);
6805 if (using_mock_io) {
6806 struct tog_blame_thread_args *bta = &s->blame.thread_args;
6807 int rc;
6809 rc = pthread_cond_destroy(&bta->blame_complete);
6810 if (rc && err == NULL)
6811 err = got_error_set_errno(rc, "pthread_cond_destroy");
6814 free(s->path);
6815 free_colors(&s->colors);
6816 return err;
6819 static const struct got_error *
6820 search_start_blame_view(struct tog_view *view)
6822 struct tog_blame_view_state *s = &view->state.blame;
6824 s->matched_line = 0;
6825 return NULL;
6828 static void
6829 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6830 size_t *nlines, int **first, int **last, int **match, int **selected)
6832 struct tog_blame_view_state *s = &view->state.blame;
6834 *f = s->blame.f;
6835 *nlines = s->blame.nlines;
6836 *line_offsets = s->blame.line_offsets;
6837 *match = &s->matched_line;
6838 *first = &s->first_displayed_line;
6839 *last = &s->last_displayed_line;
6840 *selected = &s->selected_line;
6843 static const struct got_error *
6844 show_blame_view(struct tog_view *view)
6846 const struct got_error *err = NULL;
6847 struct tog_blame_view_state *s = &view->state.blame;
6848 int errcode;
6850 if (s->blame.thread == 0 && !s->blame_complete) {
6851 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6852 &s->blame.thread_args);
6853 if (errcode)
6854 return got_error_set_errno(errcode, "pthread_create");
6856 if (!using_mock_io)
6857 halfdelay(1); /* fast refresh while annotating */
6860 if (s->blame_complete && !using_mock_io)
6861 halfdelay(10); /* disable fast refresh */
6863 err = draw_blame(view);
6865 view_border(view);
6866 return err;
6869 static const struct got_error *
6870 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6871 struct got_repository *repo, struct got_object_id *id)
6873 struct tog_view *log_view;
6874 const struct got_error *err = NULL;
6876 *new_view = NULL;
6878 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6879 if (log_view == NULL)
6880 return got_error_from_errno("view_open");
6882 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0, NULL);
6883 if (err)
6884 view_close(log_view);
6885 else
6886 *new_view = log_view;
6888 return err;
6891 static const struct got_error *
6892 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6894 const struct got_error *err = NULL, *thread_err = NULL;
6895 struct tog_view *diff_view;
6896 struct tog_blame_view_state *s = &view->state.blame;
6897 int eos, nscroll, begin_y = 0, begin_x = 0;
6899 eos = nscroll = view->nlines - 2;
6900 if (view_is_hsplit_top(view))
6901 --eos; /* border */
6903 switch (ch) {
6904 case '0':
6905 case '$':
6906 case KEY_RIGHT:
6907 case 'l':
6908 case KEY_LEFT:
6909 case 'h':
6910 horizontal_scroll_input(view, ch);
6911 break;
6912 case 'q':
6913 s->done = 1;
6914 break;
6915 case 'g':
6916 case KEY_HOME:
6917 s->selected_line = 1;
6918 s->first_displayed_line = 1;
6919 view->count = 0;
6920 break;
6921 case 'G':
6922 case KEY_END:
6923 if (s->blame.nlines < eos) {
6924 s->selected_line = s->blame.nlines;
6925 s->first_displayed_line = 1;
6926 } else {
6927 s->selected_line = eos;
6928 s->first_displayed_line = s->blame.nlines - (eos - 1);
6930 view->count = 0;
6931 break;
6932 case 'k':
6933 case KEY_UP:
6934 case CTRL('p'):
6935 if (s->selected_line > 1)
6936 s->selected_line--;
6937 else if (s->selected_line == 1 &&
6938 s->first_displayed_line > 1)
6939 s->first_displayed_line--;
6940 else
6941 view->count = 0;
6942 break;
6943 case CTRL('u'):
6944 case 'u':
6945 nscroll /= 2;
6946 /* FALL THROUGH */
6947 case KEY_PPAGE:
6948 case CTRL('b'):
6949 case 'b':
6950 if (s->first_displayed_line == 1) {
6951 if (view->count > 1)
6952 nscroll += nscroll;
6953 s->selected_line = MAX(1, s->selected_line - nscroll);
6954 view->count = 0;
6955 break;
6957 if (s->first_displayed_line > nscroll)
6958 s->first_displayed_line -= nscroll;
6959 else
6960 s->first_displayed_line = 1;
6961 break;
6962 case 'j':
6963 case KEY_DOWN:
6964 case CTRL('n'):
6965 if (s->selected_line < eos && s->first_displayed_line +
6966 s->selected_line <= s->blame.nlines)
6967 s->selected_line++;
6968 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6969 s->first_displayed_line++;
6970 else
6971 view->count = 0;
6972 break;
6973 case 'c':
6974 case 'p': {
6975 struct got_object_id *id = NULL;
6977 view->count = 0;
6978 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6979 s->first_displayed_line, s->selected_line);
6980 if (id == NULL)
6981 break;
6982 if (ch == 'p') {
6983 struct got_commit_object *commit, *pcommit;
6984 struct got_object_qid *pid;
6985 struct got_object_id *blob_id = NULL;
6986 int obj_type;
6987 err = got_object_open_as_commit(&commit,
6988 s->repo, id);
6989 if (err)
6990 break;
6991 pid = STAILQ_FIRST(
6992 got_object_commit_get_parent_ids(commit));
6993 if (pid == NULL) {
6994 got_object_commit_close(commit);
6995 break;
6997 /* Check if path history ends here. */
6998 err = got_object_open_as_commit(&pcommit,
6999 s->repo, &pid->id);
7000 if (err)
7001 break;
7002 err = got_object_id_by_path(&blob_id, s->repo,
7003 pcommit, s->path);
7004 got_object_commit_close(pcommit);
7005 if (err) {
7006 if (err->code == GOT_ERR_NO_TREE_ENTRY)
7007 err = NULL;
7008 got_object_commit_close(commit);
7009 break;
7011 err = got_object_get_type(&obj_type, s->repo,
7012 blob_id);
7013 free(blob_id);
7014 /* Can't blame non-blob type objects. */
7015 if (obj_type != GOT_OBJ_TYPE_BLOB) {
7016 got_object_commit_close(commit);
7017 break;
7019 err = got_object_qid_alloc(&s->blamed_commit,
7020 &pid->id);
7021 got_object_commit_close(commit);
7022 } else {
7023 if (got_object_id_cmp(id,
7024 &s->blamed_commit->id) == 0)
7025 break;
7026 err = got_object_qid_alloc(&s->blamed_commit,
7027 id);
7029 if (err)
7030 break;
7031 s->done = 1;
7032 thread_err = stop_blame(&s->blame);
7033 s->done = 0;
7034 if (thread_err)
7035 break;
7036 STAILQ_INSERT_HEAD(&s->blamed_commits,
7037 s->blamed_commit, entry);
7038 err = run_blame(view);
7039 if (err)
7040 break;
7041 break;
7043 case 'C': {
7044 struct got_object_qid *first;
7046 view->count = 0;
7047 first = STAILQ_FIRST(&s->blamed_commits);
7048 if (!got_object_id_cmp(&first->id, s->commit_id))
7049 break;
7050 s->done = 1;
7051 thread_err = stop_blame(&s->blame);
7052 s->done = 0;
7053 if (thread_err)
7054 break;
7055 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
7056 got_object_qid_free(s->blamed_commit);
7057 s->blamed_commit =
7058 STAILQ_FIRST(&s->blamed_commits);
7059 err = run_blame(view);
7060 if (err)
7061 break;
7062 break;
7064 case 'L':
7065 view->count = 0;
7066 s->id_to_log = get_selected_commit_id(s->blame.lines,
7067 s->blame.nlines, s->first_displayed_line, s->selected_line);
7068 if (s->id_to_log)
7069 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7070 break;
7071 case KEY_ENTER:
7072 case '\r': {
7073 struct got_object_id *id = NULL;
7074 struct got_object_qid *pid;
7075 struct got_commit_object *commit = NULL;
7077 view->count = 0;
7078 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
7079 s->first_displayed_line, s->selected_line);
7080 if (id == NULL)
7081 break;
7082 err = got_object_open_as_commit(&commit, s->repo, id);
7083 if (err)
7084 break;
7085 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
7086 if (*new_view) {
7087 /* traversed from diff view, release diff resources */
7088 err = close_diff_view(*new_view);
7089 if (err)
7090 break;
7091 diff_view = *new_view;
7092 } else {
7093 if (view_is_parent_view(view))
7094 view_get_split(view, &begin_y, &begin_x);
7096 diff_view = view_open(0, 0, begin_y, begin_x,
7097 TOG_VIEW_DIFF);
7098 if (diff_view == NULL) {
7099 got_object_commit_close(commit);
7100 err = got_error_from_errno("view_open");
7101 break;
7104 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
7105 id, NULL, NULL, 3, 0, 0, view, s->repo);
7106 got_object_commit_close(commit);
7107 if (err)
7108 break;
7109 s->last_diffed_line = s->first_displayed_line - 1 +
7110 s->selected_line;
7111 if (*new_view)
7112 break; /* still open from active diff view */
7113 if (view_is_parent_view(view) &&
7114 view->mode == TOG_VIEW_SPLIT_HRZN) {
7115 err = view_init_hsplit(view, begin_y);
7116 if (err)
7117 break;
7120 view->focussed = 0;
7121 diff_view->focussed = 1;
7122 diff_view->mode = view->mode;
7123 diff_view->nlines = view->lines - begin_y;
7124 if (view_is_parent_view(view)) {
7125 view_transfer_size(diff_view, view);
7126 err = view_close_child(view);
7127 if (err)
7128 break;
7129 err = view_set_child(view, diff_view);
7130 if (err)
7131 break;
7132 view->focus_child = 1;
7133 } else
7134 *new_view = diff_view;
7135 if (err)
7136 break;
7137 break;
7139 case CTRL('d'):
7140 case 'd':
7141 nscroll /= 2;
7142 /* FALL THROUGH */
7143 case KEY_NPAGE:
7144 case CTRL('f'):
7145 case 'f':
7146 case ' ':
7147 if (s->last_displayed_line >= s->blame.nlines &&
7148 s->selected_line >= MIN(s->blame.nlines,
7149 view->nlines - 2)) {
7150 view->count = 0;
7151 break;
7153 if (s->last_displayed_line >= s->blame.nlines &&
7154 s->selected_line < view->nlines - 2) {
7155 s->selected_line +=
7156 MIN(nscroll, s->last_displayed_line -
7157 s->first_displayed_line - s->selected_line + 1);
7159 if (s->last_displayed_line + nscroll <= s->blame.nlines)
7160 s->first_displayed_line += nscroll;
7161 else
7162 s->first_displayed_line =
7163 s->blame.nlines - (view->nlines - 3);
7164 break;
7165 case KEY_RESIZE:
7166 if (s->selected_line > view->nlines - 2) {
7167 s->selected_line = MIN(s->blame.nlines,
7168 view->nlines - 2);
7170 break;
7171 default:
7172 view->count = 0;
7173 break;
7175 return thread_err ? thread_err : err;
7178 static const struct got_error *
7179 reset_blame_view(struct tog_view *view)
7181 const struct got_error *err;
7182 struct tog_blame_view_state *s = &view->state.blame;
7184 view->count = 0;
7185 s->done = 1;
7186 err = stop_blame(&s->blame);
7187 s->done = 0;
7188 if (err)
7189 return err;
7190 return run_blame(view);
7193 static const struct got_error *
7194 cmd_blame(int argc, char *argv[])
7196 const struct got_error *error;
7197 struct got_repository *repo = NULL;
7198 struct got_worktree *worktree = NULL;
7199 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7200 char *link_target = NULL;
7201 struct got_object_id *commit_id = NULL;
7202 struct got_commit_object *commit = NULL;
7203 char *keyword_idstr = NULL, *commit_id_str = NULL;
7204 int ch;
7205 struct tog_view *view = NULL;
7206 int *pack_fds = NULL;
7208 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7209 switch (ch) {
7210 case 'c':
7211 commit_id_str = optarg;
7212 break;
7213 case 'r':
7214 repo_path = realpath(optarg, NULL);
7215 if (repo_path == NULL)
7216 return got_error_from_errno2("realpath",
7217 optarg);
7218 break;
7219 default:
7220 usage_blame();
7221 /* NOTREACHED */
7225 argc -= optind;
7226 argv += optind;
7228 if (argc != 1)
7229 usage_blame();
7231 error = got_repo_pack_fds_open(&pack_fds);
7232 if (error != NULL)
7233 goto done;
7235 if (repo_path == NULL) {
7236 cwd = getcwd(NULL, 0);
7237 if (cwd == NULL)
7238 return got_error_from_errno("getcwd");
7239 error = got_worktree_open(&worktree, cwd, NULL);
7240 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7241 goto done;
7242 if (worktree)
7243 repo_path =
7244 strdup(got_worktree_get_repo_path(worktree));
7245 else
7246 repo_path = strdup(cwd);
7247 if (repo_path == NULL) {
7248 error = got_error_from_errno("strdup");
7249 goto done;
7253 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7254 if (error != NULL)
7255 goto done;
7257 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
7258 worktree);
7259 if (error)
7260 goto done;
7262 init_curses();
7264 error = apply_unveil(got_repo_get_path(repo), NULL);
7265 if (error)
7266 goto done;
7268 error = tog_load_refs(repo, 0);
7269 if (error)
7270 goto done;
7272 if (commit_id_str == NULL) {
7273 struct got_reference *head_ref;
7274 error = got_ref_open(&head_ref, repo, worktree ?
7275 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
7276 if (error != NULL)
7277 goto done;
7278 error = got_ref_resolve(&commit_id, repo, head_ref);
7279 got_ref_close(head_ref);
7280 } else {
7281 error = got_keyword_to_idstr(&keyword_idstr, commit_id_str,
7282 repo, worktree);
7283 if (error != NULL)
7284 goto done;
7285 if (keyword_idstr != NULL)
7286 commit_id_str = keyword_idstr;
7288 error = got_repo_match_object_id(&commit_id, NULL,
7289 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7291 if (error != NULL)
7292 goto done;
7294 error = got_object_open_as_commit(&commit, repo, commit_id);
7295 if (error)
7296 goto done;
7298 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7299 commit, repo);
7300 if (error)
7301 goto done;
7303 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7304 if (view == NULL) {
7305 error = got_error_from_errno("view_open");
7306 goto done;
7308 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7309 commit_id, repo);
7310 if (error != NULL) {
7311 if (view->close == NULL)
7312 close_blame_view(view);
7313 view_close(view);
7314 goto done;
7317 if (worktree) {
7318 error = set_tog_base_commit(repo, worktree);
7319 if (error != NULL)
7320 goto done;
7322 /* Release work tree lock. */
7323 got_worktree_close(worktree);
7324 worktree = NULL;
7327 error = view_loop(view);
7329 done:
7330 free(tog_base_commit.id);
7331 free(repo_path);
7332 free(in_repo_path);
7333 free(link_target);
7334 free(cwd);
7335 free(commit_id);
7336 free(keyword_idstr);
7337 if (commit)
7338 got_object_commit_close(commit);
7339 if (worktree)
7340 got_worktree_close(worktree);
7341 if (repo) {
7342 const struct got_error *close_err = got_repo_close(repo);
7343 if (error == NULL)
7344 error = close_err;
7346 if (pack_fds) {
7347 const struct got_error *pack_err =
7348 got_repo_pack_fds_close(pack_fds);
7349 if (error == NULL)
7350 error = pack_err;
7352 tog_free_refs();
7353 return error;
7356 static const struct got_error *
7357 draw_tree_entries(struct tog_view *view, const char *parent_path)
7359 struct tog_tree_view_state *s = &view->state.tree;
7360 const struct got_error *err = NULL;
7361 struct got_tree_entry *te;
7362 wchar_t *wline;
7363 char *index = NULL;
7364 struct tog_color *tc;
7365 int width, n, nentries, scrollx, i = 1;
7366 int limit = view->nlines;
7368 s->ndisplayed = 0;
7369 if (view_is_hsplit_top(view))
7370 --limit; /* border */
7372 werase(view->window);
7374 if (limit == 0)
7375 return NULL;
7377 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7378 0, 0);
7379 if (err)
7380 return err;
7381 if (view_needs_focus_indication(view))
7382 wstandout(view->window);
7383 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7384 if (tc)
7385 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7386 waddwstr(view->window, wline);
7387 free(wline);
7388 wline = NULL;
7389 while (width++ < view->ncols)
7390 waddch(view->window, ' ');
7391 if (tc)
7392 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7393 if (view_needs_focus_indication(view))
7394 wstandend(view->window);
7395 if (--limit <= 0)
7396 return NULL;
7398 i += s->selected;
7399 if (s->first_displayed_entry) {
7400 i += got_tree_entry_get_index(s->first_displayed_entry);
7401 if (s->tree != s->root)
7402 ++i; /* account for ".." entry */
7404 nentries = got_object_tree_get_nentries(s->tree);
7405 if (asprintf(&index, "[%d/%d] %s",
7406 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7407 return got_error_from_errno("asprintf");
7408 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7409 free(index);
7410 if (err)
7411 return err;
7412 waddwstr(view->window, wline);
7413 free(wline);
7414 wline = NULL;
7415 if (width < view->ncols - 1)
7416 waddch(view->window, '\n');
7417 if (--limit <= 0)
7418 return NULL;
7419 waddch(view->window, '\n');
7420 if (--limit <= 0)
7421 return NULL;
7423 if (s->first_displayed_entry == NULL) {
7424 te = got_object_tree_get_first_entry(s->tree);
7425 if (s->selected == 0) {
7426 if (view->focussed)
7427 wstandout(view->window);
7428 s->selected_entry = NULL;
7430 waddstr(view->window, " ..\n"); /* parent directory */
7431 if (s->selected == 0 && view->focussed)
7432 wstandend(view->window);
7433 s->ndisplayed++;
7434 if (--limit <= 0)
7435 return NULL;
7436 n = 1;
7437 } else {
7438 n = 0;
7439 te = s->first_displayed_entry;
7442 view->maxx = 0;
7443 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7444 char *line = NULL, *id_str = NULL, *link_target = NULL;
7445 const char *modestr = "";
7446 mode_t mode;
7448 te = got_object_tree_get_entry(s->tree, i);
7449 mode = got_tree_entry_get_mode(te);
7451 if (s->show_ids) {
7452 err = got_object_id_str(&id_str,
7453 got_tree_entry_get_id(te));
7454 if (err)
7455 return got_error_from_errno(
7456 "got_object_id_str");
7458 if (got_object_tree_entry_is_submodule(te))
7459 modestr = "$";
7460 else if (S_ISLNK(mode)) {
7461 int i;
7463 err = got_tree_entry_get_symlink_target(&link_target,
7464 te, s->repo);
7465 if (err) {
7466 free(id_str);
7467 return err;
7469 for (i = 0; link_target[i] != '\0'; i++) {
7470 if (!isprint((unsigned char)link_target[i]))
7471 link_target[i] = '?';
7473 modestr = "@";
7475 else if (S_ISDIR(mode))
7476 modestr = "/";
7477 else if (mode & S_IXUSR)
7478 modestr = "*";
7479 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7480 got_tree_entry_get_name(te), modestr,
7481 link_target ? " -> ": "",
7482 link_target ? link_target : "") == -1) {
7483 free(id_str);
7484 free(link_target);
7485 return got_error_from_errno("asprintf");
7487 free(id_str);
7488 free(link_target);
7490 /* use full line width to determine view->maxx */
7491 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7492 if (err) {
7493 free(line);
7494 break;
7496 view->maxx = MAX(view->maxx, width);
7497 free(wline);
7498 wline = NULL;
7500 err = format_line(&wline, &width, &scrollx, line, view->x,
7501 view->ncols, 0, 0);
7502 if (err) {
7503 free(line);
7504 break;
7506 if (n == s->selected) {
7507 if (view->focussed)
7508 wstandout(view->window);
7509 s->selected_entry = te;
7511 tc = match_color(&s->colors, line);
7512 if (tc)
7513 wattr_on(view->window,
7514 COLOR_PAIR(tc->colorpair), NULL);
7515 waddwstr(view->window, &wline[scrollx]);
7516 if (tc)
7517 wattr_off(view->window,
7518 COLOR_PAIR(tc->colorpair), NULL);
7519 if (width < view->ncols)
7520 waddch(view->window, '\n');
7521 if (n == s->selected && view->focussed)
7522 wstandend(view->window);
7523 free(line);
7524 free(wline);
7525 wline = NULL;
7526 n++;
7527 s->ndisplayed++;
7528 s->last_displayed_entry = te;
7529 if (--limit <= 0)
7530 break;
7533 return err;
7536 static void
7537 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7539 struct got_tree_entry *te;
7540 int isroot = s->tree == s->root;
7541 int i = 0;
7543 if (s->first_displayed_entry == NULL)
7544 return;
7546 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7547 while (i++ < maxscroll) {
7548 if (te == NULL) {
7549 if (!isroot)
7550 s->first_displayed_entry = NULL;
7551 break;
7553 s->first_displayed_entry = te;
7554 te = got_tree_entry_get_prev(s->tree, te);
7558 static const struct got_error *
7559 tree_scroll_down(struct tog_view *view, int maxscroll)
7561 struct tog_tree_view_state *s = &view->state.tree;
7562 struct got_tree_entry *next, *last;
7563 int n = 0;
7565 if (s->first_displayed_entry)
7566 next = got_tree_entry_get_next(s->tree,
7567 s->first_displayed_entry);
7568 else
7569 next = got_object_tree_get_first_entry(s->tree);
7571 last = s->last_displayed_entry;
7572 while (next && n++ < maxscroll) {
7573 if (last) {
7574 s->last_displayed_entry = last;
7575 last = got_tree_entry_get_next(s->tree, last);
7577 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7578 s->first_displayed_entry = next;
7579 next = got_tree_entry_get_next(s->tree, next);
7583 return NULL;
7586 static const struct got_error *
7587 tree_entry_path(char **path, struct tog_parent_trees *parents,
7588 struct got_tree_entry *te)
7590 const struct got_error *err = NULL;
7591 struct tog_parent_tree *pt;
7592 size_t len = 2; /* for leading slash and NUL */
7594 TAILQ_FOREACH(pt, parents, entry)
7595 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7596 + 1 /* slash */;
7597 if (te)
7598 len += strlen(got_tree_entry_get_name(te));
7600 *path = calloc(1, len);
7601 if (path == NULL)
7602 return got_error_from_errno("calloc");
7604 (*path)[0] = '/';
7605 pt = TAILQ_LAST(parents, tog_parent_trees);
7606 while (pt) {
7607 const char *name = got_tree_entry_get_name(pt->selected_entry);
7608 if (strlcat(*path, name, len) >= len) {
7609 err = got_error(GOT_ERR_NO_SPACE);
7610 goto done;
7612 if (strlcat(*path, "/", len) >= len) {
7613 err = got_error(GOT_ERR_NO_SPACE);
7614 goto done;
7616 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7618 if (te) {
7619 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7620 err = got_error(GOT_ERR_NO_SPACE);
7621 goto done;
7624 done:
7625 if (err) {
7626 free(*path);
7627 *path = NULL;
7629 return err;
7632 static const struct got_error *
7633 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7634 struct got_tree_entry *te, struct tog_parent_trees *parents,
7635 struct got_object_id *commit_id, struct got_repository *repo)
7637 const struct got_error *err = NULL;
7638 char *path;
7639 struct tog_view *blame_view;
7641 *new_view = NULL;
7643 err = tree_entry_path(&path, parents, te);
7644 if (err)
7645 return err;
7647 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7648 if (blame_view == NULL) {
7649 err = got_error_from_errno("view_open");
7650 goto done;
7653 err = open_blame_view(blame_view, path, commit_id, repo);
7654 if (err) {
7655 if (err->code == GOT_ERR_CANCELLED)
7656 err = NULL;
7657 view_close(blame_view);
7658 } else
7659 *new_view = blame_view;
7660 done:
7661 free(path);
7662 return err;
7665 static const struct got_error *
7666 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7667 struct tog_tree_view_state *s)
7669 struct tog_view *log_view;
7670 const struct got_error *err = NULL;
7671 char *path;
7673 *new_view = NULL;
7675 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7676 if (log_view == NULL)
7677 return got_error_from_errno("view_open");
7679 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7680 if (err)
7681 return err;
7683 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7684 path, 0, NULL);
7685 if (err)
7686 view_close(log_view);
7687 else
7688 *new_view = log_view;
7689 free(path);
7690 return err;
7693 static const struct got_error *
7694 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7695 const char *head_ref_name, struct got_repository *repo)
7697 const struct got_error *err = NULL;
7698 char *commit_id_str = NULL;
7699 struct tog_tree_view_state *s = &view->state.tree;
7700 struct got_commit_object *commit = NULL;
7702 TAILQ_INIT(&s->parents);
7703 STAILQ_INIT(&s->colors);
7705 s->commit_id = got_object_id_dup(commit_id);
7706 if (s->commit_id == NULL) {
7707 err = got_error_from_errno("got_object_id_dup");
7708 goto done;
7711 err = got_object_open_as_commit(&commit, repo, commit_id);
7712 if (err)
7713 goto done;
7716 * The root is opened here and will be closed when the view is closed.
7717 * Any visited subtrees and their path-wise parents are opened and
7718 * closed on demand.
7720 err = got_object_open_as_tree(&s->root, repo,
7721 got_object_commit_get_tree_id(commit));
7722 if (err)
7723 goto done;
7724 s->tree = s->root;
7726 err = got_object_id_str(&commit_id_str, commit_id);
7727 if (err != NULL)
7728 goto done;
7730 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7731 err = got_error_from_errno("asprintf");
7732 goto done;
7735 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7736 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7737 if (head_ref_name) {
7738 s->head_ref_name = strdup(head_ref_name);
7739 if (s->head_ref_name == NULL) {
7740 err = got_error_from_errno("strdup");
7741 goto done;
7744 s->repo = repo;
7746 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7747 err = add_color(&s->colors, "\\$$",
7748 TOG_COLOR_TREE_SUBMODULE,
7749 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7750 if (err)
7751 goto done;
7752 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7753 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7754 if (err)
7755 goto done;
7756 err = add_color(&s->colors, "/$",
7757 TOG_COLOR_TREE_DIRECTORY,
7758 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7759 if (err)
7760 goto done;
7762 err = add_color(&s->colors, "\\*$",
7763 TOG_COLOR_TREE_EXECUTABLE,
7764 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7765 if (err)
7766 goto done;
7768 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7769 get_color_value("TOG_COLOR_COMMIT"));
7770 if (err)
7771 goto done;
7774 view->show = show_tree_view;
7775 view->input = input_tree_view;
7776 view->close = close_tree_view;
7777 view->search_start = search_start_tree_view;
7778 view->search_next = search_next_tree_view;
7779 done:
7780 free(commit_id_str);
7781 if (commit)
7782 got_object_commit_close(commit);
7783 if (err) {
7784 if (view->close == NULL)
7785 close_tree_view(view);
7786 view_close(view);
7788 return err;
7791 static const struct got_error *
7792 close_tree_view(struct tog_view *view)
7794 struct tog_tree_view_state *s = &view->state.tree;
7796 free_colors(&s->colors);
7797 free(s->tree_label);
7798 s->tree_label = NULL;
7799 free(s->commit_id);
7800 s->commit_id = NULL;
7801 free(s->head_ref_name);
7802 s->head_ref_name = NULL;
7803 while (!TAILQ_EMPTY(&s->parents)) {
7804 struct tog_parent_tree *parent;
7805 parent = TAILQ_FIRST(&s->parents);
7806 TAILQ_REMOVE(&s->parents, parent, entry);
7807 if (parent->tree != s->root)
7808 got_object_tree_close(parent->tree);
7809 free(parent);
7812 if (s->tree != NULL && s->tree != s->root)
7813 got_object_tree_close(s->tree);
7814 if (s->root)
7815 got_object_tree_close(s->root);
7816 return NULL;
7819 static const struct got_error *
7820 search_start_tree_view(struct tog_view *view)
7822 struct tog_tree_view_state *s = &view->state.tree;
7824 s->matched_entry = NULL;
7825 return NULL;
7828 static int
7829 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7831 regmatch_t regmatch;
7833 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7834 0) == 0;
7837 static const struct got_error *
7838 search_next_tree_view(struct tog_view *view)
7840 struct tog_tree_view_state *s = &view->state.tree;
7841 struct got_tree_entry *te = NULL;
7843 if (!view->searching) {
7844 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7845 return NULL;
7848 if (s->matched_entry) {
7849 if (view->searching == TOG_SEARCH_FORWARD) {
7850 if (s->selected_entry)
7851 te = got_tree_entry_get_next(s->tree,
7852 s->selected_entry);
7853 else
7854 te = got_object_tree_get_first_entry(s->tree);
7855 } else {
7856 if (s->selected_entry == NULL)
7857 te = got_object_tree_get_last_entry(s->tree);
7858 else
7859 te = got_tree_entry_get_prev(s->tree,
7860 s->selected_entry);
7862 } else {
7863 if (s->selected_entry)
7864 te = s->selected_entry;
7865 else if (view->searching == TOG_SEARCH_FORWARD)
7866 te = got_object_tree_get_first_entry(s->tree);
7867 else
7868 te = got_object_tree_get_last_entry(s->tree);
7871 while (1) {
7872 if (te == NULL) {
7873 if (s->matched_entry == NULL) {
7874 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7875 return NULL;
7877 if (view->searching == TOG_SEARCH_FORWARD)
7878 te = got_object_tree_get_first_entry(s->tree);
7879 else
7880 te = got_object_tree_get_last_entry(s->tree);
7883 if (match_tree_entry(te, &view->regex)) {
7884 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7885 s->matched_entry = te;
7886 break;
7889 if (view->searching == TOG_SEARCH_FORWARD)
7890 te = got_tree_entry_get_next(s->tree, te);
7891 else
7892 te = got_tree_entry_get_prev(s->tree, te);
7895 if (s->matched_entry) {
7896 s->first_displayed_entry = s->matched_entry;
7897 s->selected = 0;
7900 return NULL;
7903 static const struct got_error *
7904 show_tree_view(struct tog_view *view)
7906 const struct got_error *err = NULL;
7907 struct tog_tree_view_state *s = &view->state.tree;
7908 char *parent_path;
7910 err = tree_entry_path(&parent_path, &s->parents, NULL);
7911 if (err)
7912 return err;
7914 err = draw_tree_entries(view, parent_path);
7915 free(parent_path);
7917 view_border(view);
7918 return err;
7921 static const struct got_error *
7922 tree_goto_line(struct tog_view *view, int nlines)
7924 const struct got_error *err = NULL;
7925 struct tog_tree_view_state *s = &view->state.tree;
7926 struct got_tree_entry **fte, **lte, **ste;
7927 int g, last, first = 1, i = 1;
7928 int root = s->tree == s->root;
7929 int off = root ? 1 : 2;
7931 g = view->gline;
7932 view->gline = 0;
7934 if (g == 0)
7935 g = 1;
7936 else if (g > got_object_tree_get_nentries(s->tree))
7937 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7939 fte = &s->first_displayed_entry;
7940 lte = &s->last_displayed_entry;
7941 ste = &s->selected_entry;
7943 if (*fte != NULL) {
7944 first = got_tree_entry_get_index(*fte);
7945 first += off; /* account for ".." */
7947 last = got_tree_entry_get_index(*lte);
7948 last += off;
7950 if (g >= first && g <= last && g - first < nlines) {
7951 s->selected = g - first;
7952 return NULL; /* gline is on the current page */
7955 if (*ste != NULL) {
7956 i = got_tree_entry_get_index(*ste);
7957 i += off;
7960 if (i < g) {
7961 err = tree_scroll_down(view, g - i);
7962 if (err)
7963 return err;
7964 if (got_tree_entry_get_index(*lte) >=
7965 got_object_tree_get_nentries(s->tree) - 1 &&
7966 first + s->selected < g &&
7967 s->selected < s->ndisplayed - 1) {
7968 first = got_tree_entry_get_index(*fte);
7969 first += off;
7970 s->selected = g - first;
7972 } else if (i > g)
7973 tree_scroll_up(s, i - g);
7975 if (g < nlines &&
7976 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7977 s->selected = g - 1;
7979 return NULL;
7982 static const struct got_error *
7983 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7985 const struct got_error *err = NULL;
7986 struct tog_tree_view_state *s = &view->state.tree;
7987 struct got_tree_entry *te;
7988 int n, nscroll = view->nlines - 3;
7990 if (view->gline)
7991 return tree_goto_line(view, nscroll);
7993 switch (ch) {
7994 case '0':
7995 case '$':
7996 case KEY_RIGHT:
7997 case 'l':
7998 case KEY_LEFT:
7999 case 'h':
8000 horizontal_scroll_input(view, ch);
8001 break;
8002 case 'i':
8003 s->show_ids = !s->show_ids;
8004 view->count = 0;
8005 break;
8006 case 'L':
8007 view->count = 0;
8008 if (!s->selected_entry)
8009 break;
8010 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8011 break;
8012 case 'R':
8013 view->count = 0;
8014 err = view_request_new(new_view, view, TOG_VIEW_REF);
8015 break;
8016 case 'g':
8017 case '=':
8018 case KEY_HOME:
8019 s->selected = 0;
8020 view->count = 0;
8021 if (s->tree == s->root)
8022 s->first_displayed_entry =
8023 got_object_tree_get_first_entry(s->tree);
8024 else
8025 s->first_displayed_entry = NULL;
8026 break;
8027 case 'G':
8028 case '*':
8029 case KEY_END: {
8030 int eos = view->nlines - 3;
8032 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8033 --eos; /* border */
8034 s->selected = 0;
8035 view->count = 0;
8036 te = got_object_tree_get_last_entry(s->tree);
8037 for (n = 0; n < eos; n++) {
8038 if (te == NULL) {
8039 if (s->tree != s->root) {
8040 s->first_displayed_entry = NULL;
8041 n++;
8043 break;
8045 s->first_displayed_entry = te;
8046 te = got_tree_entry_get_prev(s->tree, te);
8048 if (n > 0)
8049 s->selected = n - 1;
8050 break;
8052 case 'k':
8053 case KEY_UP:
8054 case CTRL('p'):
8055 if (s->selected > 0) {
8056 s->selected--;
8057 break;
8059 tree_scroll_up(s, 1);
8060 if (s->selected_entry == NULL ||
8061 (s->tree == s->root && s->selected_entry ==
8062 got_object_tree_get_first_entry(s->tree)))
8063 view->count = 0;
8064 break;
8065 case CTRL('u'):
8066 case 'u':
8067 nscroll /= 2;
8068 /* FALL THROUGH */
8069 case KEY_PPAGE:
8070 case CTRL('b'):
8071 case 'b':
8072 if (s->tree == s->root) {
8073 if (got_object_tree_get_first_entry(s->tree) ==
8074 s->first_displayed_entry)
8075 s->selected -= MIN(s->selected, nscroll);
8076 } else {
8077 if (s->first_displayed_entry == NULL)
8078 s->selected -= MIN(s->selected, nscroll);
8080 tree_scroll_up(s, MAX(0, nscroll));
8081 if (s->selected_entry == NULL ||
8082 (s->tree == s->root && s->selected_entry ==
8083 got_object_tree_get_first_entry(s->tree)))
8084 view->count = 0;
8085 break;
8086 case 'j':
8087 case KEY_DOWN:
8088 case CTRL('n'):
8089 if (s->selected < s->ndisplayed - 1) {
8090 s->selected++;
8091 break;
8093 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
8094 == NULL) {
8095 /* can't scroll any further */
8096 view->count = 0;
8097 break;
8099 tree_scroll_down(view, 1);
8100 break;
8101 case CTRL('d'):
8102 case 'd':
8103 nscroll /= 2;
8104 /* FALL THROUGH */
8105 case KEY_NPAGE:
8106 case CTRL('f'):
8107 case 'f':
8108 case ' ':
8109 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
8110 == NULL) {
8111 /* can't scroll any further; move cursor down */
8112 if (s->selected < s->ndisplayed - 1)
8113 s->selected += MIN(nscroll,
8114 s->ndisplayed - s->selected - 1);
8115 else
8116 view->count = 0;
8117 break;
8119 tree_scroll_down(view, nscroll);
8120 break;
8121 case KEY_ENTER:
8122 case '\r':
8123 case KEY_BACKSPACE:
8124 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
8125 struct tog_parent_tree *parent;
8126 /* user selected '..' */
8127 if (s->tree == s->root) {
8128 view->count = 0;
8129 break;
8131 parent = TAILQ_FIRST(&s->parents);
8132 TAILQ_REMOVE(&s->parents, parent,
8133 entry);
8134 got_object_tree_close(s->tree);
8135 s->tree = parent->tree;
8136 s->first_displayed_entry =
8137 parent->first_displayed_entry;
8138 s->selected_entry =
8139 parent->selected_entry;
8140 s->selected = parent->selected;
8141 if (s->selected > view->nlines - 3) {
8142 err = offset_selection_down(view);
8143 if (err)
8144 break;
8146 free(parent);
8147 } else if (S_ISDIR(got_tree_entry_get_mode(
8148 s->selected_entry))) {
8149 struct got_tree_object *subtree;
8150 view->count = 0;
8151 err = got_object_open_as_tree(&subtree, s->repo,
8152 got_tree_entry_get_id(s->selected_entry));
8153 if (err)
8154 break;
8155 err = tree_view_visit_subtree(s, subtree);
8156 if (err) {
8157 got_object_tree_close(subtree);
8158 break;
8160 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
8161 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
8162 break;
8163 case KEY_RESIZE:
8164 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
8165 s->selected = view->nlines - 4;
8166 view->count = 0;
8167 break;
8168 default:
8169 view->count = 0;
8170 break;
8173 return err;
8176 __dead static void
8177 usage_tree(void)
8179 endwin();
8180 fprintf(stderr,
8181 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
8182 getprogname());
8183 exit(1);
8186 static const struct got_error *
8187 cmd_tree(int argc, char *argv[])
8189 const struct got_error *error;
8190 struct got_repository *repo = NULL;
8191 struct got_worktree *worktree = NULL;
8192 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8193 struct got_object_id *commit_id = NULL;
8194 struct got_commit_object *commit = NULL;
8195 const char *commit_id_arg = NULL;
8196 char *keyword_idstr = NULL, *label = NULL;
8197 struct got_reference *ref = NULL;
8198 const char *head_ref_name = NULL;
8199 int ch;
8200 struct tog_view *view;
8201 int *pack_fds = NULL;
8203 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
8204 switch (ch) {
8205 case 'c':
8206 commit_id_arg = optarg;
8207 break;
8208 case 'r':
8209 repo_path = realpath(optarg, NULL);
8210 if (repo_path == NULL)
8211 return got_error_from_errno2("realpath",
8212 optarg);
8213 break;
8214 default:
8215 usage_tree();
8216 /* NOTREACHED */
8220 argc -= optind;
8221 argv += optind;
8223 if (argc > 1)
8224 usage_tree();
8226 error = got_repo_pack_fds_open(&pack_fds);
8227 if (error != NULL)
8228 goto done;
8230 if (repo_path == NULL) {
8231 cwd = getcwd(NULL, 0);
8232 if (cwd == NULL)
8233 return got_error_from_errno("getcwd");
8234 error = got_worktree_open(&worktree, cwd, NULL);
8235 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8236 goto done;
8237 if (worktree)
8238 repo_path =
8239 strdup(got_worktree_get_repo_path(worktree));
8240 else
8241 repo_path = strdup(cwd);
8242 if (repo_path == NULL) {
8243 error = got_error_from_errno("strdup");
8244 goto done;
8248 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8249 if (error != NULL)
8250 goto done;
8252 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8253 repo, worktree);
8254 if (error)
8255 goto done;
8257 init_curses();
8259 error = apply_unveil(got_repo_get_path(repo), NULL);
8260 if (error)
8261 goto done;
8263 error = tog_load_refs(repo, 0);
8264 if (error)
8265 goto done;
8267 if (commit_id_arg == NULL) {
8268 error = got_repo_match_object_id(&commit_id, &label,
8269 worktree ? got_worktree_get_head_ref_name(worktree) :
8270 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8271 if (error)
8272 goto done;
8273 head_ref_name = label;
8274 } else {
8275 error = got_keyword_to_idstr(&keyword_idstr, commit_id_arg,
8276 repo, worktree);
8277 if (error != NULL)
8278 goto done;
8279 if (keyword_idstr != NULL)
8280 commit_id_arg = keyword_idstr;
8282 error = got_ref_open(&ref, repo, commit_id_arg, 0);
8283 if (error == NULL)
8284 head_ref_name = got_ref_get_name(ref);
8285 else if (error->code != GOT_ERR_NOT_REF)
8286 goto done;
8287 error = got_repo_match_object_id(&commit_id, NULL,
8288 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8289 if (error)
8290 goto done;
8293 error = got_object_open_as_commit(&commit, repo, commit_id);
8294 if (error)
8295 goto done;
8297 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
8298 if (view == NULL) {
8299 error = got_error_from_errno("view_open");
8300 goto done;
8302 error = open_tree_view(view, commit_id, head_ref_name, repo);
8303 if (error)
8304 goto done;
8305 if (!got_path_is_root_dir(in_repo_path)) {
8306 error = tree_view_walk_path(&view->state.tree, commit,
8307 in_repo_path);
8308 if (error)
8309 goto done;
8312 if (worktree) {
8313 error = set_tog_base_commit(repo, worktree);
8314 if (error != NULL)
8315 goto done;
8317 /* Release work tree lock. */
8318 got_worktree_close(worktree);
8319 worktree = NULL;
8322 error = view_loop(view);
8324 done:
8325 free(tog_base_commit.id);
8326 free(keyword_idstr);
8327 free(repo_path);
8328 free(cwd);
8329 free(commit_id);
8330 free(label);
8331 if (ref)
8332 got_ref_close(ref);
8333 if (worktree != NULL)
8334 got_worktree_close(worktree);
8335 if (repo) {
8336 const struct got_error *close_err = got_repo_close(repo);
8337 if (error == NULL)
8338 error = close_err;
8340 if (pack_fds) {
8341 const struct got_error *pack_err =
8342 got_repo_pack_fds_close(pack_fds);
8343 if (error == NULL)
8344 error = pack_err;
8346 tog_free_refs();
8347 return error;
8350 static const struct got_error *
8351 ref_view_load_refs(struct tog_ref_view_state *s)
8353 struct got_reflist_entry *sre;
8354 struct tog_reflist_entry *re;
8356 s->nrefs = 0;
8357 TAILQ_FOREACH(sre, &tog_refs, entry) {
8358 if (strncmp(got_ref_get_name(sre->ref),
8359 "refs/got/", 9) == 0 &&
8360 strncmp(got_ref_get_name(sre->ref),
8361 "refs/got/backup/", 16) != 0)
8362 continue;
8364 re = malloc(sizeof(*re));
8365 if (re == NULL)
8366 return got_error_from_errno("malloc");
8368 re->ref = got_ref_dup(sre->ref);
8369 if (re->ref == NULL)
8370 return got_error_from_errno("got_ref_dup");
8371 re->idx = s->nrefs++;
8372 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8375 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8376 return NULL;
8379 static void
8380 ref_view_free_refs(struct tog_ref_view_state *s)
8382 struct tog_reflist_entry *re;
8384 while (!TAILQ_EMPTY(&s->refs)) {
8385 re = TAILQ_FIRST(&s->refs);
8386 TAILQ_REMOVE(&s->refs, re, entry);
8387 got_ref_close(re->ref);
8388 free(re);
8392 static const struct got_error *
8393 open_ref_view(struct tog_view *view, struct got_repository *repo)
8395 const struct got_error *err = NULL;
8396 struct tog_ref_view_state *s = &view->state.ref;
8398 s->selected_entry = 0;
8399 s->repo = repo;
8401 TAILQ_INIT(&s->refs);
8402 STAILQ_INIT(&s->colors);
8404 err = ref_view_load_refs(s);
8405 if (err)
8406 goto done;
8408 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8409 err = add_color(&s->colors, "^refs/heads/",
8410 TOG_COLOR_REFS_HEADS,
8411 get_color_value("TOG_COLOR_REFS_HEADS"));
8412 if (err)
8413 goto done;
8415 err = add_color(&s->colors, "^refs/tags/",
8416 TOG_COLOR_REFS_TAGS,
8417 get_color_value("TOG_COLOR_REFS_TAGS"));
8418 if (err)
8419 goto done;
8421 err = add_color(&s->colors, "^refs/remotes/",
8422 TOG_COLOR_REFS_REMOTES,
8423 get_color_value("TOG_COLOR_REFS_REMOTES"));
8424 if (err)
8425 goto done;
8427 err = add_color(&s->colors, "^refs/got/backup/",
8428 TOG_COLOR_REFS_BACKUP,
8429 get_color_value("TOG_COLOR_REFS_BACKUP"));
8430 if (err)
8431 goto done;
8434 view->show = show_ref_view;
8435 view->input = input_ref_view;
8436 view->close = close_ref_view;
8437 view->search_start = search_start_ref_view;
8438 view->search_next = search_next_ref_view;
8439 done:
8440 if (err) {
8441 if (view->close == NULL)
8442 close_ref_view(view);
8443 view_close(view);
8445 return err;
8448 static const struct got_error *
8449 close_ref_view(struct tog_view *view)
8451 struct tog_ref_view_state *s = &view->state.ref;
8453 ref_view_free_refs(s);
8454 free_colors(&s->colors);
8456 return NULL;
8459 static const struct got_error *
8460 resolve_reflist_entry(struct got_object_id **commit_id,
8461 struct tog_reflist_entry *re, struct got_repository *repo)
8463 const struct got_error *err = NULL;
8464 struct got_object_id *obj_id;
8465 struct got_tag_object *tag = NULL;
8466 int obj_type;
8468 *commit_id = NULL;
8470 err = got_ref_resolve(&obj_id, repo, re->ref);
8471 if (err)
8472 return err;
8474 err = got_object_get_type(&obj_type, repo, obj_id);
8475 if (err)
8476 goto done;
8478 switch (obj_type) {
8479 case GOT_OBJ_TYPE_COMMIT:
8480 *commit_id = obj_id;
8481 break;
8482 case GOT_OBJ_TYPE_TAG:
8483 err = got_object_open_as_tag(&tag, repo, obj_id);
8484 if (err)
8485 goto done;
8486 free(obj_id);
8487 err = got_object_get_type(&obj_type, repo,
8488 got_object_tag_get_object_id(tag));
8489 if (err)
8490 goto done;
8491 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8492 err = got_error(GOT_ERR_OBJ_TYPE);
8493 goto done;
8495 *commit_id = got_object_id_dup(
8496 got_object_tag_get_object_id(tag));
8497 if (*commit_id == NULL) {
8498 err = got_error_from_errno("got_object_id_dup");
8499 goto done;
8501 break;
8502 default:
8503 err = got_error(GOT_ERR_OBJ_TYPE);
8504 break;
8507 done:
8508 if (tag)
8509 got_object_tag_close(tag);
8510 if (err) {
8511 free(*commit_id);
8512 *commit_id = NULL;
8514 return err;
8517 static const struct got_error *
8518 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8519 struct tog_reflist_entry *re, struct got_repository *repo)
8521 struct tog_view *log_view;
8522 const struct got_error *err = NULL;
8523 struct got_object_id *commit_id = NULL;
8525 *new_view = NULL;
8527 err = resolve_reflist_entry(&commit_id, re, repo);
8528 if (err) {
8529 if (err->code != GOT_ERR_OBJ_TYPE)
8530 return err;
8531 else
8532 return NULL;
8535 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8536 if (log_view == NULL) {
8537 err = got_error_from_errno("view_open");
8538 goto done;
8541 err = open_log_view(log_view, commit_id, repo,
8542 got_ref_get_name(re->ref), "", 0, NULL);
8543 done:
8544 if (err)
8545 view_close(log_view);
8546 else
8547 *new_view = log_view;
8548 free(commit_id);
8549 return err;
8552 static void
8553 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8555 struct tog_reflist_entry *re;
8556 int i = 0;
8558 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8559 return;
8561 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8562 while (i++ < maxscroll) {
8563 if (re == NULL)
8564 break;
8565 s->first_displayed_entry = re;
8566 re = TAILQ_PREV(re, tog_reflist_head, entry);
8570 static const struct got_error *
8571 ref_scroll_down(struct tog_view *view, int maxscroll)
8573 struct tog_ref_view_state *s = &view->state.ref;
8574 struct tog_reflist_entry *next, *last;
8575 int n = 0;
8577 if (s->first_displayed_entry)
8578 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8579 else
8580 next = TAILQ_FIRST(&s->refs);
8582 last = s->last_displayed_entry;
8583 while (next && n++ < maxscroll) {
8584 if (last) {
8585 s->last_displayed_entry = last;
8586 last = TAILQ_NEXT(last, entry);
8588 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8589 s->first_displayed_entry = next;
8590 next = TAILQ_NEXT(next, entry);
8594 return NULL;
8597 static const struct got_error *
8598 search_start_ref_view(struct tog_view *view)
8600 struct tog_ref_view_state *s = &view->state.ref;
8602 s->matched_entry = NULL;
8603 return NULL;
8606 static int
8607 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8609 regmatch_t regmatch;
8611 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8612 0) == 0;
8615 static const struct got_error *
8616 search_next_ref_view(struct tog_view *view)
8618 struct tog_ref_view_state *s = &view->state.ref;
8619 struct tog_reflist_entry *re = NULL;
8621 if (!view->searching) {
8622 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8623 return NULL;
8626 if (s->matched_entry) {
8627 if (view->searching == TOG_SEARCH_FORWARD) {
8628 if (s->selected_entry)
8629 re = TAILQ_NEXT(s->selected_entry, entry);
8630 else
8631 re = TAILQ_PREV(s->selected_entry,
8632 tog_reflist_head, entry);
8633 } else {
8634 if (s->selected_entry == NULL)
8635 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8636 else
8637 re = TAILQ_PREV(s->selected_entry,
8638 tog_reflist_head, entry);
8640 } else {
8641 if (s->selected_entry)
8642 re = s->selected_entry;
8643 else if (view->searching == TOG_SEARCH_FORWARD)
8644 re = TAILQ_FIRST(&s->refs);
8645 else
8646 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8649 while (1) {
8650 if (re == NULL) {
8651 if (s->matched_entry == NULL) {
8652 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8653 return NULL;
8655 if (view->searching == TOG_SEARCH_FORWARD)
8656 re = TAILQ_FIRST(&s->refs);
8657 else
8658 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8661 if (match_reflist_entry(re, &view->regex)) {
8662 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8663 s->matched_entry = re;
8664 break;
8667 if (view->searching == TOG_SEARCH_FORWARD)
8668 re = TAILQ_NEXT(re, entry);
8669 else
8670 re = TAILQ_PREV(re, tog_reflist_head, entry);
8673 if (s->matched_entry) {
8674 s->first_displayed_entry = s->matched_entry;
8675 s->selected = 0;
8678 return NULL;
8681 static const struct got_error *
8682 show_ref_view(struct tog_view *view)
8684 const struct got_error *err = NULL;
8685 struct tog_ref_view_state *s = &view->state.ref;
8686 struct tog_reflist_entry *re;
8687 char *line = NULL;
8688 wchar_t *wline;
8689 struct tog_color *tc;
8690 int width, n, scrollx;
8691 int limit = view->nlines;
8693 werase(view->window);
8695 s->ndisplayed = 0;
8696 if (view_is_hsplit_top(view))
8697 --limit; /* border */
8699 if (limit == 0)
8700 return NULL;
8702 re = s->first_displayed_entry;
8704 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8705 s->nrefs) == -1)
8706 return got_error_from_errno("asprintf");
8708 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8709 if (err) {
8710 free(line);
8711 return err;
8713 if (view_needs_focus_indication(view))
8714 wstandout(view->window);
8715 waddwstr(view->window, wline);
8716 while (width++ < view->ncols)
8717 waddch(view->window, ' ');
8718 if (view_needs_focus_indication(view))
8719 wstandend(view->window);
8720 free(wline);
8721 wline = NULL;
8722 free(line);
8723 line = NULL;
8724 if (--limit <= 0)
8725 return NULL;
8727 n = 0;
8728 view->maxx = 0;
8729 while (re && limit > 0) {
8730 char *line = NULL;
8731 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8733 if (s->show_date) {
8734 struct got_commit_object *ci;
8735 struct got_tag_object *tag;
8736 struct got_object_id *id;
8737 struct tm tm;
8738 time_t t;
8740 err = got_ref_resolve(&id, s->repo, re->ref);
8741 if (err)
8742 return err;
8743 err = got_object_open_as_tag(&tag, s->repo, id);
8744 if (err) {
8745 if (err->code != GOT_ERR_OBJ_TYPE) {
8746 free(id);
8747 return err;
8749 err = got_object_open_as_commit(&ci, s->repo,
8750 id);
8751 if (err) {
8752 free(id);
8753 return err;
8755 t = got_object_commit_get_committer_time(ci);
8756 got_object_commit_close(ci);
8757 } else {
8758 t = got_object_tag_get_tagger_time(tag);
8759 got_object_tag_close(tag);
8761 free(id);
8762 if (gmtime_r(&t, &tm) == NULL)
8763 return got_error_from_errno("gmtime_r");
8764 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8765 return got_error(GOT_ERR_NO_SPACE);
8767 if (got_ref_is_symbolic(re->ref)) {
8768 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8769 ymd : "", got_ref_get_name(re->ref),
8770 got_ref_get_symref_target(re->ref)) == -1)
8771 return got_error_from_errno("asprintf");
8772 } else if (s->show_ids) {
8773 struct got_object_id *id;
8774 char *id_str;
8775 err = got_ref_resolve(&id, s->repo, re->ref);
8776 if (err)
8777 return err;
8778 err = got_object_id_str(&id_str, id);
8779 if (err) {
8780 free(id);
8781 return err;
8783 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8784 got_ref_get_name(re->ref), id_str) == -1) {
8785 err = got_error_from_errno("asprintf");
8786 free(id);
8787 free(id_str);
8788 return err;
8790 free(id);
8791 free(id_str);
8792 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8793 got_ref_get_name(re->ref)) == -1)
8794 return got_error_from_errno("asprintf");
8796 /* use full line width to determine view->maxx */
8797 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8798 if (err) {
8799 free(line);
8800 return err;
8802 view->maxx = MAX(view->maxx, width);
8803 free(wline);
8804 wline = NULL;
8806 err = format_line(&wline, &width, &scrollx, line, view->x,
8807 view->ncols, 0, 0);
8808 if (err) {
8809 free(line);
8810 return err;
8812 if (n == s->selected) {
8813 if (view->focussed)
8814 wstandout(view->window);
8815 s->selected_entry = re;
8817 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8818 if (tc)
8819 wattr_on(view->window,
8820 COLOR_PAIR(tc->colorpair), NULL);
8821 waddwstr(view->window, &wline[scrollx]);
8822 if (tc)
8823 wattr_off(view->window,
8824 COLOR_PAIR(tc->colorpair), NULL);
8825 if (width < view->ncols)
8826 waddch(view->window, '\n');
8827 if (n == s->selected && view->focussed)
8828 wstandend(view->window);
8829 free(line);
8830 free(wline);
8831 wline = NULL;
8832 n++;
8833 s->ndisplayed++;
8834 s->last_displayed_entry = re;
8836 limit--;
8837 re = TAILQ_NEXT(re, entry);
8840 view_border(view);
8841 return err;
8844 static const struct got_error *
8845 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8846 struct tog_reflist_entry *re, struct got_repository *repo)
8848 const struct got_error *err = NULL;
8849 struct got_object_id *commit_id = NULL;
8850 struct tog_view *tree_view;
8852 *new_view = NULL;
8854 err = resolve_reflist_entry(&commit_id, re, repo);
8855 if (err) {
8856 if (err->code != GOT_ERR_OBJ_TYPE)
8857 return err;
8858 else
8859 return NULL;
8863 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8864 if (tree_view == NULL) {
8865 err = got_error_from_errno("view_open");
8866 goto done;
8869 err = open_tree_view(tree_view, commit_id,
8870 got_ref_get_name(re->ref), repo);
8871 if (err)
8872 goto done;
8874 *new_view = tree_view;
8875 done:
8876 free(commit_id);
8877 return err;
8880 static const struct got_error *
8881 ref_goto_line(struct tog_view *view, int nlines)
8883 const struct got_error *err = NULL;
8884 struct tog_ref_view_state *s = &view->state.ref;
8885 int g, idx = s->selected_entry->idx;
8887 g = view->gline;
8888 view->gline = 0;
8890 if (g == 0)
8891 g = 1;
8892 else if (g > s->nrefs)
8893 g = s->nrefs;
8895 if (g >= s->first_displayed_entry->idx + 1 &&
8896 g <= s->last_displayed_entry->idx + 1 &&
8897 g - s->first_displayed_entry->idx - 1 < nlines) {
8898 s->selected = g - s->first_displayed_entry->idx - 1;
8899 return NULL;
8902 if (idx + 1 < g) {
8903 err = ref_scroll_down(view, g - idx - 1);
8904 if (err)
8905 return err;
8906 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8907 s->first_displayed_entry->idx + s->selected < g &&
8908 s->selected < s->ndisplayed - 1)
8909 s->selected = g - s->first_displayed_entry->idx - 1;
8910 } else if (idx + 1 > g)
8911 ref_scroll_up(s, idx - g + 1);
8913 if (g < nlines && s->first_displayed_entry->idx == 0)
8914 s->selected = g - 1;
8916 return NULL;
8920 static const struct got_error *
8921 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8923 const struct got_error *err = NULL;
8924 struct tog_ref_view_state *s = &view->state.ref;
8925 struct tog_reflist_entry *re;
8926 int n, nscroll = view->nlines - 1;
8928 if (view->gline)
8929 return ref_goto_line(view, nscroll);
8931 switch (ch) {
8932 case '0':
8933 case '$':
8934 case KEY_RIGHT:
8935 case 'l':
8936 case KEY_LEFT:
8937 case 'h':
8938 horizontal_scroll_input(view, ch);
8939 break;
8940 case 'i':
8941 s->show_ids = !s->show_ids;
8942 view->count = 0;
8943 break;
8944 case 'm':
8945 s->show_date = !s->show_date;
8946 view->count = 0;
8947 break;
8948 case 'o':
8949 s->sort_by_date = !s->sort_by_date;
8950 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8951 view->count = 0;
8952 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8953 got_ref_cmp_by_commit_timestamp_descending :
8954 tog_ref_cmp_by_name, s->repo);
8955 if (err)
8956 break;
8957 got_reflist_object_id_map_free(tog_refs_idmap);
8958 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8959 &tog_refs, s->repo);
8960 if (err)
8961 break;
8962 ref_view_free_refs(s);
8963 err = ref_view_load_refs(s);
8964 break;
8965 case KEY_ENTER:
8966 case '\r':
8967 view->count = 0;
8968 if (!s->selected_entry)
8969 break;
8970 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8971 break;
8972 case 'T':
8973 view->count = 0;
8974 if (!s->selected_entry)
8975 break;
8976 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8977 break;
8978 case 'g':
8979 case '=':
8980 case KEY_HOME:
8981 s->selected = 0;
8982 view->count = 0;
8983 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8984 break;
8985 case 'G':
8986 case '*':
8987 case KEY_END: {
8988 int eos = view->nlines - 1;
8990 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8991 --eos; /* border */
8992 s->selected = 0;
8993 view->count = 0;
8994 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8995 for (n = 0; n < eos; n++) {
8996 if (re == NULL)
8997 break;
8998 s->first_displayed_entry = re;
8999 re = TAILQ_PREV(re, tog_reflist_head, entry);
9001 if (n > 0)
9002 s->selected = n - 1;
9003 break;
9005 case 'k':
9006 case KEY_UP:
9007 case CTRL('p'):
9008 if (s->selected > 0) {
9009 s->selected--;
9010 break;
9012 ref_scroll_up(s, 1);
9013 if (s->selected_entry == TAILQ_FIRST(&s->refs))
9014 view->count = 0;
9015 break;
9016 case CTRL('u'):
9017 case 'u':
9018 nscroll /= 2;
9019 /* FALL THROUGH */
9020 case KEY_PPAGE:
9021 case CTRL('b'):
9022 case 'b':
9023 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
9024 s->selected -= MIN(nscroll, s->selected);
9025 ref_scroll_up(s, MAX(0, nscroll));
9026 if (s->selected_entry == TAILQ_FIRST(&s->refs))
9027 view->count = 0;
9028 break;
9029 case 'j':
9030 case KEY_DOWN:
9031 case CTRL('n'):
9032 if (s->selected < s->ndisplayed - 1) {
9033 s->selected++;
9034 break;
9036 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
9037 /* can't scroll any further */
9038 view->count = 0;
9039 break;
9041 ref_scroll_down(view, 1);
9042 break;
9043 case CTRL('d'):
9044 case 'd':
9045 nscroll /= 2;
9046 /* FALL THROUGH */
9047 case KEY_NPAGE:
9048 case CTRL('f'):
9049 case 'f':
9050 case ' ':
9051 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
9052 /* can't scroll any further; move cursor down */
9053 if (s->selected < s->ndisplayed - 1)
9054 s->selected += MIN(nscroll,
9055 s->ndisplayed - s->selected - 1);
9056 if (view->count > 1 && s->selected < s->ndisplayed - 1)
9057 s->selected += s->ndisplayed - s->selected - 1;
9058 view->count = 0;
9059 break;
9061 ref_scroll_down(view, nscroll);
9062 break;
9063 case CTRL('l'):
9064 view->count = 0;
9065 tog_free_refs();
9066 err = tog_load_refs(s->repo, s->sort_by_date);
9067 if (err)
9068 break;
9069 ref_view_free_refs(s);
9070 err = ref_view_load_refs(s);
9071 break;
9072 case KEY_RESIZE:
9073 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
9074 s->selected = view->nlines - 2;
9075 break;
9076 default:
9077 view->count = 0;
9078 break;
9081 return err;
9084 __dead static void
9085 usage_ref(void)
9087 endwin();
9088 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
9089 getprogname());
9090 exit(1);
9093 static const struct got_error *
9094 cmd_ref(int argc, char *argv[])
9096 const struct got_error *error;
9097 struct got_repository *repo = NULL;
9098 struct got_worktree *worktree = NULL;
9099 char *cwd = NULL, *repo_path = NULL;
9100 int ch;
9101 struct tog_view *view;
9102 int *pack_fds = NULL;
9104 while ((ch = getopt(argc, argv, "r:")) != -1) {
9105 switch (ch) {
9106 case 'r':
9107 repo_path = realpath(optarg, NULL);
9108 if (repo_path == NULL)
9109 return got_error_from_errno2("realpath",
9110 optarg);
9111 break;
9112 default:
9113 usage_ref();
9114 /* NOTREACHED */
9118 argc -= optind;
9119 argv += optind;
9121 if (argc > 1)
9122 usage_ref();
9124 error = got_repo_pack_fds_open(&pack_fds);
9125 if (error != NULL)
9126 goto done;
9128 if (repo_path == NULL) {
9129 cwd = getcwd(NULL, 0);
9130 if (cwd == NULL)
9131 return got_error_from_errno("getcwd");
9132 error = got_worktree_open(&worktree, cwd, NULL);
9133 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9134 goto done;
9135 if (worktree)
9136 repo_path =
9137 strdup(got_worktree_get_repo_path(worktree));
9138 else
9139 repo_path = strdup(cwd);
9140 if (repo_path == NULL) {
9141 error = got_error_from_errno("strdup");
9142 goto done;
9146 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9147 if (error != NULL)
9148 goto done;
9150 init_curses();
9152 error = apply_unveil(got_repo_get_path(repo), NULL);
9153 if (error)
9154 goto done;
9156 error = tog_load_refs(repo, 0);
9157 if (error)
9158 goto done;
9160 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
9161 if (view == NULL) {
9162 error = got_error_from_errno("view_open");
9163 goto done;
9166 error = open_ref_view(view, repo);
9167 if (error)
9168 goto done;
9170 if (worktree) {
9171 error = set_tog_base_commit(repo, worktree);
9172 if (error != NULL)
9173 goto done;
9175 /* Release work tree lock. */
9176 got_worktree_close(worktree);
9177 worktree = NULL;
9180 error = view_loop(view);
9182 done:
9183 free(tog_base_commit.id);
9184 free(repo_path);
9185 free(cwd);
9186 if (worktree != NULL)
9187 got_worktree_close(worktree);
9188 if (repo) {
9189 const struct got_error *close_err = got_repo_close(repo);
9190 if (close_err)
9191 error = close_err;
9193 if (pack_fds) {
9194 const struct got_error *pack_err =
9195 got_repo_pack_fds_close(pack_fds);
9196 if (error == NULL)
9197 error = pack_err;
9199 tog_free_refs();
9200 return error;
9203 static const struct got_error*
9204 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
9205 const char *str)
9207 size_t len;
9209 if (win == NULL)
9210 win = stdscr;
9212 len = strlen(str);
9213 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
9215 if (focus)
9216 wstandout(win);
9217 if (mvwprintw(win, y, x, "%s", str) == ERR)
9218 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
9219 if (focus)
9220 wstandend(win);
9222 return NULL;
9225 static const struct got_error *
9226 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
9228 off_t *p;
9230 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
9231 if (p == NULL) {
9232 free(*line_offsets);
9233 *line_offsets = NULL;
9234 return got_error_from_errno("reallocarray");
9237 *line_offsets = p;
9238 (*line_offsets)[*nlines] = off;
9239 ++(*nlines);
9240 return NULL;
9243 static const struct got_error *
9244 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
9246 *ret = 0;
9248 for (;n > 0; --n, ++km) {
9249 char *t0, *t, *k;
9250 size_t len = 1;
9252 if (km->keys == NULL)
9253 continue;
9255 t = t0 = strdup(km->keys);
9256 if (t0 == NULL)
9257 return got_error_from_errno("strdup");
9259 len += strlen(t);
9260 while ((k = strsep(&t, " ")) != NULL)
9261 len += strlen(k) > 1 ? 2 : 0;
9262 free(t0);
9263 *ret = MAX(*ret, len);
9266 return NULL;
9270 * Write keymap section headers, keys, and key info in km to f.
9271 * Save line offset to *off. If terminal has UTF8 encoding enabled,
9272 * wrap control and symbolic keys in guillemets, else use <>.
9274 static const struct got_error *
9275 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
9277 int n, len = width;
9279 if (km->keys) {
9280 static const char *u8_glyph[] = {
9281 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
9282 "\xe2\x80\xba" /* U+203A (utf8 >) */
9284 char *t0, *t, *k;
9285 int cs, s, first = 1;
9287 cs = got_locale_is_utf8();
9289 t = t0 = strdup(km->keys);
9290 if (t0 == NULL)
9291 return got_error_from_errno("strdup");
9293 len = strlen(km->keys);
9294 while ((k = strsep(&t, " ")) != NULL) {
9295 s = strlen(k) > 1; /* control or symbolic key */
9296 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
9297 cs && s ? u8_glyph[0] : s ? "<" : "", k,
9298 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
9299 if (n < 0) {
9300 free(t0);
9301 return got_error_from_errno("fprintf");
9303 first = 0;
9304 len += s ? 2 : 0;
9305 *off += n;
9307 free(t0);
9309 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
9310 if (n < 0)
9311 return got_error_from_errno("fprintf");
9312 *off += n;
9314 return NULL;
9317 static const struct got_error *
9318 format_help(struct tog_help_view_state *s)
9320 const struct got_error *err = NULL;
9321 off_t off = 0;
9322 int i, max, n, show = s->all;
9323 static const struct tog_key_map km[] = {
9324 #define KEYMAP_(info, type) { NULL, (info), type }
9325 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
9326 GENERATE_HELP
9327 #undef KEYMAP_
9328 #undef KEY_
9331 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
9332 if (err)
9333 return err;
9335 n = nitems(km);
9336 err = max_key_str(&max, km, n);
9337 if (err)
9338 return err;
9340 for (i = 0; i < n; ++i) {
9341 if (km[i].keys == NULL) {
9342 show = s->all;
9343 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9344 km[i].type == s->type || s->all)
9345 show = 1;
9347 if (show) {
9348 err = format_help_line(&off, s->f, &km[i], max);
9349 if (err)
9350 return err;
9351 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9352 if (err)
9353 return err;
9356 fputc('\n', s->f);
9357 ++off;
9358 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9359 return err;
9362 static const struct got_error *
9363 create_help(struct tog_help_view_state *s)
9365 FILE *f;
9366 const struct got_error *err;
9368 free(s->line_offsets);
9369 s->line_offsets = NULL;
9370 s->nlines = 0;
9372 f = got_opentemp();
9373 if (f == NULL)
9374 return got_error_from_errno("got_opentemp");
9375 s->f = f;
9377 err = format_help(s);
9378 if (err)
9379 return err;
9381 if (s->f && fflush(s->f) != 0)
9382 return got_error_from_errno("fflush");
9384 return NULL;
9387 static const struct got_error *
9388 search_start_help_view(struct tog_view *view)
9390 view->state.help.matched_line = 0;
9391 return NULL;
9394 static void
9395 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9396 size_t *nlines, int **first, int **last, int **match, int **selected)
9398 struct tog_help_view_state *s = &view->state.help;
9400 *f = s->f;
9401 *nlines = s->nlines;
9402 *line_offsets = s->line_offsets;
9403 *match = &s->matched_line;
9404 *first = &s->first_displayed_line;
9405 *last = &s->last_displayed_line;
9406 *selected = &s->selected_line;
9409 static const struct got_error *
9410 show_help_view(struct tog_view *view)
9412 struct tog_help_view_state *s = &view->state.help;
9413 const struct got_error *err;
9414 regmatch_t *regmatch = &view->regmatch;
9415 wchar_t *wline;
9416 char *line;
9417 ssize_t linelen;
9418 size_t linesz = 0;
9419 int width, nprinted = 0, rc = 0;
9420 int eos = view->nlines;
9422 if (view_is_hsplit_top(view))
9423 --eos; /* account for border */
9425 s->lineno = 0;
9426 rewind(s->f);
9427 werase(view->window);
9429 if (view->gline > s->nlines - 1)
9430 view->gline = s->nlines - 1;
9432 err = win_draw_center(view->window, 0, 0, view->ncols,
9433 view_needs_focus_indication(view),
9434 "tog help (press q to return to tog)");
9435 if (err)
9436 return err;
9437 if (eos <= 1)
9438 return NULL;
9439 waddstr(view->window, "\n\n");
9440 eos -= 2;
9442 s->eof = 0;
9443 view->maxx = 0;
9444 line = NULL;
9445 while (eos > 0 && nprinted < eos) {
9446 attr_t attr = 0;
9448 linelen = getline(&line, &linesz, s->f);
9449 if (linelen == -1) {
9450 if (!feof(s->f)) {
9451 free(line);
9452 return got_ferror(s->f, GOT_ERR_IO);
9454 s->eof = 1;
9455 break;
9457 if (++s->lineno < s->first_displayed_line)
9458 continue;
9459 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9460 continue;
9461 if (s->lineno == view->hiline)
9462 attr = A_STANDOUT;
9464 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9465 view->x ? 1 : 0);
9466 if (err) {
9467 free(line);
9468 return err;
9470 view->maxx = MAX(view->maxx, width);
9471 free(wline);
9472 wline = NULL;
9474 if (attr)
9475 wattron(view->window, attr);
9476 if (s->first_displayed_line + nprinted == s->matched_line &&
9477 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9478 err = add_matched_line(&width, line, view->ncols - 1, 0,
9479 view->window, view->x, regmatch);
9480 if (err) {
9481 free(line);
9482 return err;
9484 } else {
9485 int skip;
9487 err = format_line(&wline, &width, &skip, line,
9488 view->x, view->ncols, 0, view->x ? 1 : 0);
9489 if (err) {
9490 free(line);
9491 return err;
9493 waddwstr(view->window, &wline[skip]);
9494 free(wline);
9495 wline = NULL;
9497 if (s->lineno == view->hiline) {
9498 while (width++ < view->ncols)
9499 waddch(view->window, ' ');
9500 } else {
9501 if (width < view->ncols)
9502 waddch(view->window, '\n');
9504 if (attr)
9505 wattroff(view->window, attr);
9506 if (++nprinted == 1)
9507 s->first_displayed_line = s->lineno;
9509 free(line);
9510 if (nprinted > 0)
9511 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9512 else
9513 s->last_displayed_line = s->first_displayed_line;
9515 view_border(view);
9517 if (s->eof) {
9518 rc = waddnstr(view->window,
9519 "See the tog(1) manual page for full documentation",
9520 view->ncols - 1);
9521 if (rc == ERR)
9522 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9523 } else {
9524 wmove(view->window, view->nlines - 1, 0);
9525 wclrtoeol(view->window);
9526 wstandout(view->window);
9527 rc = waddnstr(view->window, "scroll down for more...",
9528 view->ncols - 1);
9529 if (rc == ERR)
9530 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9531 if (getcurx(view->window) < view->ncols - 6) {
9532 rc = wprintw(view->window, "[%.0f%%]",
9533 100.00 * s->last_displayed_line / s->nlines);
9534 if (rc == ERR)
9535 return got_error_msg(GOT_ERR_IO, "wprintw");
9537 wstandend(view->window);
9540 return NULL;
9543 static const struct got_error *
9544 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9546 struct tog_help_view_state *s = &view->state.help;
9547 const struct got_error *err = NULL;
9548 char *line = NULL;
9549 ssize_t linelen;
9550 size_t linesz = 0;
9551 int eos, nscroll;
9553 eos = nscroll = view->nlines;
9554 if (view_is_hsplit_top(view))
9555 --eos; /* border */
9557 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9559 switch (ch) {
9560 case '0':
9561 case '$':
9562 case KEY_RIGHT:
9563 case 'l':
9564 case KEY_LEFT:
9565 case 'h':
9566 horizontal_scroll_input(view, ch);
9567 break;
9568 case 'g':
9569 case KEY_HOME:
9570 s->first_displayed_line = 1;
9571 view->count = 0;
9572 break;
9573 case 'G':
9574 case KEY_END:
9575 view->count = 0;
9576 if (s->eof)
9577 break;
9578 s->first_displayed_line = (s->nlines - eos) + 3;
9579 s->eof = 1;
9580 break;
9581 case 'k':
9582 case KEY_UP:
9583 if (s->first_displayed_line > 1)
9584 --s->first_displayed_line;
9585 else
9586 view->count = 0;
9587 break;
9588 case CTRL('u'):
9589 case 'u':
9590 nscroll /= 2;
9591 /* FALL THROUGH */
9592 case KEY_PPAGE:
9593 case CTRL('b'):
9594 case 'b':
9595 if (s->first_displayed_line == 1) {
9596 view->count = 0;
9597 break;
9599 while (--nscroll > 0 && s->first_displayed_line > 1)
9600 s->first_displayed_line--;
9601 break;
9602 case 'j':
9603 case KEY_DOWN:
9604 case CTRL('n'):
9605 if (!s->eof)
9606 ++s->first_displayed_line;
9607 else
9608 view->count = 0;
9609 break;
9610 case CTRL('d'):
9611 case 'd':
9612 nscroll /= 2;
9613 /* FALL THROUGH */
9614 case KEY_NPAGE:
9615 case CTRL('f'):
9616 case 'f':
9617 case ' ':
9618 if (s->eof) {
9619 view->count = 0;
9620 break;
9622 while (!s->eof && --nscroll > 0) {
9623 linelen = getline(&line, &linesz, s->f);
9624 s->first_displayed_line++;
9625 if (linelen == -1) {
9626 if (feof(s->f))
9627 s->eof = 1;
9628 else
9629 err = got_ferror(s->f, GOT_ERR_IO);
9630 break;
9633 free(line);
9634 break;
9635 default:
9636 view->count = 0;
9637 break;
9640 return err;
9643 static const struct got_error *
9644 close_help_view(struct tog_view *view)
9646 struct tog_help_view_state *s = &view->state.help;
9648 free(s->line_offsets);
9649 s->line_offsets = NULL;
9650 if (fclose(s->f) == EOF)
9651 return got_error_from_errno("fclose");
9653 return NULL;
9656 static const struct got_error *
9657 reset_help_view(struct tog_view *view)
9659 struct tog_help_view_state *s = &view->state.help;
9662 if (s->f && fclose(s->f) == EOF)
9663 return got_error_from_errno("fclose");
9665 wclear(view->window);
9666 view->count = 0;
9667 view->x = 0;
9668 s->all = !s->all;
9669 s->first_displayed_line = 1;
9670 s->last_displayed_line = view->nlines;
9671 s->matched_line = 0;
9673 return create_help(s);
9676 static const struct got_error *
9677 open_help_view(struct tog_view *view, struct tog_view *parent)
9679 const struct got_error *err = NULL;
9680 struct tog_help_view_state *s = &view->state.help;
9682 s->type = (enum tog_keymap_type)parent->type;
9683 s->first_displayed_line = 1;
9684 s->last_displayed_line = view->nlines;
9685 s->selected_line = 1;
9687 view->show = show_help_view;
9688 view->input = input_help_view;
9689 view->reset = reset_help_view;
9690 view->close = close_help_view;
9691 view->search_start = search_start_help_view;
9692 view->search_setup = search_setup_help_view;
9693 view->search_next = search_next_view_match;
9695 err = create_help(s);
9696 return err;
9699 static const struct got_error *
9700 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9701 enum tog_view_type request, int y, int x)
9703 const struct got_error *err = NULL;
9705 *new_view = NULL;
9707 switch (request) {
9708 case TOG_VIEW_DIFF:
9709 if (view->type == TOG_VIEW_LOG) {
9710 struct tog_log_view_state *s = &view->state.log;
9712 err = open_diff_view_for_commit(new_view, y, x,
9713 s->selected_entry->commit, s->selected_entry->id,
9714 view, s->repo);
9715 } else
9716 return got_error_msg(GOT_ERR_NOT_IMPL,
9717 "parent/child view pair not supported");
9718 break;
9719 case TOG_VIEW_BLAME:
9720 if (view->type == TOG_VIEW_TREE) {
9721 struct tog_tree_view_state *s = &view->state.tree;
9723 err = blame_tree_entry(new_view, y, x,
9724 s->selected_entry, &s->parents, s->commit_id,
9725 s->repo);
9726 } else
9727 return got_error_msg(GOT_ERR_NOT_IMPL,
9728 "parent/child view pair not supported");
9729 break;
9730 case TOG_VIEW_LOG:
9731 if (view->type == TOG_VIEW_BLAME)
9732 err = log_annotated_line(new_view, y, x,
9733 view->state.blame.repo, view->state.blame.id_to_log);
9734 else if (view->type == TOG_VIEW_TREE)
9735 err = log_selected_tree_entry(new_view, y, x,
9736 &view->state.tree);
9737 else if (view->type == TOG_VIEW_REF)
9738 err = log_ref_entry(new_view, y, x,
9739 view->state.ref.selected_entry,
9740 view->state.ref.repo);
9741 else
9742 return got_error_msg(GOT_ERR_NOT_IMPL,
9743 "parent/child view pair not supported");
9744 break;
9745 case TOG_VIEW_TREE:
9746 if (view->type == TOG_VIEW_LOG)
9747 err = browse_commit_tree(new_view, y, x,
9748 view->state.log.selected_entry,
9749 view->state.log.in_repo_path,
9750 view->state.log.head_ref_name,
9751 view->state.log.repo);
9752 else if (view->type == TOG_VIEW_REF)
9753 err = browse_ref_tree(new_view, y, x,
9754 view->state.ref.selected_entry,
9755 view->state.ref.repo);
9756 else
9757 return got_error_msg(GOT_ERR_NOT_IMPL,
9758 "parent/child view pair not supported");
9759 break;
9760 case TOG_VIEW_REF:
9761 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9762 if (*new_view == NULL)
9763 return got_error_from_errno("view_open");
9764 if (view->type == TOG_VIEW_LOG)
9765 err = open_ref_view(*new_view, view->state.log.repo);
9766 else if (view->type == TOG_VIEW_TREE)
9767 err = open_ref_view(*new_view, view->state.tree.repo);
9768 else
9769 err = got_error_msg(GOT_ERR_NOT_IMPL,
9770 "parent/child view pair not supported");
9771 if (err)
9772 view_close(*new_view);
9773 break;
9774 case TOG_VIEW_HELP:
9775 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9776 if (*new_view == NULL)
9777 return got_error_from_errno("view_open");
9778 err = open_help_view(*new_view, view);
9779 if (err)
9780 view_close(*new_view);
9781 break;
9782 default:
9783 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9786 return err;
9790 * If view was scrolled down to move the selected line into view when opening a
9791 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9793 static void
9794 offset_selection_up(struct tog_view *view)
9796 switch (view->type) {
9797 case TOG_VIEW_BLAME: {
9798 struct tog_blame_view_state *s = &view->state.blame;
9799 if (s->first_displayed_line == 1) {
9800 s->selected_line = MAX(s->selected_line - view->offset,
9801 1);
9802 break;
9804 if (s->first_displayed_line > view->offset)
9805 s->first_displayed_line -= view->offset;
9806 else
9807 s->first_displayed_line = 1;
9808 s->selected_line += view->offset;
9809 break;
9811 case TOG_VIEW_LOG:
9812 log_scroll_up(&view->state.log, view->offset);
9813 view->state.log.selected += view->offset;
9814 break;
9815 case TOG_VIEW_REF:
9816 ref_scroll_up(&view->state.ref, view->offset);
9817 view->state.ref.selected += view->offset;
9818 break;
9819 case TOG_VIEW_TREE:
9820 tree_scroll_up(&view->state.tree, view->offset);
9821 view->state.tree.selected += view->offset;
9822 break;
9823 default:
9824 break;
9827 view->offset = 0;
9831 * If the selected line is in the section of screen covered by the bottom split,
9832 * scroll down offset lines to move it into view and index its new position.
9834 static const struct got_error *
9835 offset_selection_down(struct tog_view *view)
9837 const struct got_error *err = NULL;
9838 const struct got_error *(*scrolld)(struct tog_view *, int);
9839 int *selected = NULL;
9840 int header, offset;
9842 switch (view->type) {
9843 case TOG_VIEW_BLAME: {
9844 struct tog_blame_view_state *s = &view->state.blame;
9845 header = 3;
9846 scrolld = NULL;
9847 if (s->selected_line > view->nlines - header) {
9848 offset = abs(view->nlines - s->selected_line - header);
9849 s->first_displayed_line += offset;
9850 s->selected_line -= offset;
9851 view->offset = offset;
9853 break;
9855 case TOG_VIEW_LOG: {
9856 struct tog_log_view_state *s = &view->state.log;
9857 scrolld = &log_scroll_down;
9858 header = view_is_parent_view(view) ? 3 : 2;
9859 selected = &s->selected;
9860 break;
9862 case TOG_VIEW_REF: {
9863 struct tog_ref_view_state *s = &view->state.ref;
9864 scrolld = &ref_scroll_down;
9865 header = 3;
9866 selected = &s->selected;
9867 break;
9869 case TOG_VIEW_TREE: {
9870 struct tog_tree_view_state *s = &view->state.tree;
9871 scrolld = &tree_scroll_down;
9872 header = 5;
9873 selected = &s->selected;
9874 break;
9876 default:
9877 selected = NULL;
9878 scrolld = NULL;
9879 header = 0;
9880 break;
9883 if (selected && *selected > view->nlines - header) {
9884 offset = abs(view->nlines - *selected - header);
9885 view->offset = offset;
9886 if (scrolld && offset) {
9887 err = scrolld(view, offset);
9888 *selected -= offset;
9892 return err;
9895 static void
9896 list_commands(FILE *fp)
9898 size_t i;
9900 fprintf(fp, "commands:");
9901 for (i = 0; i < nitems(tog_commands); i++) {
9902 const struct tog_cmd *cmd = &tog_commands[i];
9903 fprintf(fp, " %s", cmd->name);
9905 fputc('\n', fp);
9908 __dead static void
9909 usage(int hflag, int status)
9911 FILE *fp = (status == 0) ? stdout : stderr;
9913 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9914 getprogname());
9915 if (hflag) {
9916 fprintf(fp, "lazy usage: %s path\n", getprogname());
9917 list_commands(fp);
9919 exit(status);
9922 static char **
9923 make_argv(int argc, ...)
9925 va_list ap;
9926 char **argv;
9927 int i;
9929 va_start(ap, argc);
9931 argv = calloc(argc, sizeof(char *));
9932 if (argv == NULL)
9933 err(1, "calloc");
9934 for (i = 0; i < argc; i++) {
9935 argv[i] = strdup(va_arg(ap, char *));
9936 if (argv[i] == NULL)
9937 err(1, "strdup");
9940 va_end(ap);
9941 return argv;
9945 * Try to convert 'tog path' into a 'tog log path' command.
9946 * The user could simply have mistyped the command rather than knowingly
9947 * provided a path. So check whether argv[0] can in fact be resolved
9948 * to a path in the HEAD commit and print a special error if not.
9949 * This hack is for mpi@ <3
9951 static const struct got_error *
9952 tog_log_with_path(int argc, char *argv[])
9954 const struct got_error *error = NULL, *close_err;
9955 const struct tog_cmd *cmd = NULL;
9956 struct got_repository *repo = NULL;
9957 struct got_worktree *worktree = NULL;
9958 struct got_object_id *commit_id = NULL, *id = NULL;
9959 struct got_commit_object *commit = NULL;
9960 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9961 char *commit_id_str = NULL, **cmd_argv = NULL;
9962 int *pack_fds = NULL;
9964 cwd = getcwd(NULL, 0);
9965 if (cwd == NULL)
9966 return got_error_from_errno("getcwd");
9968 error = got_repo_pack_fds_open(&pack_fds);
9969 if (error != NULL)
9970 goto done;
9972 error = got_worktree_open(&worktree, cwd, NULL);
9973 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9974 goto done;
9976 if (worktree)
9977 repo_path = strdup(got_worktree_get_repo_path(worktree));
9978 else
9979 repo_path = strdup(cwd);
9980 if (repo_path == NULL) {
9981 error = got_error_from_errno("strdup");
9982 goto done;
9985 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9986 if (error != NULL)
9987 goto done;
9989 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9990 repo, worktree);
9991 if (error)
9992 goto done;
9994 error = tog_load_refs(repo, 0);
9995 if (error)
9996 goto done;
9997 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9998 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9999 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
10000 if (error)
10001 goto done;
10003 if (worktree) {
10004 got_worktree_close(worktree);
10005 worktree = NULL;
10008 error = got_object_open_as_commit(&commit, repo, commit_id);
10009 if (error)
10010 goto done;
10012 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
10013 if (error) {
10014 if (error->code != GOT_ERR_NO_TREE_ENTRY)
10015 goto done;
10016 fprintf(stderr, "%s: '%s' is no known command or path\n",
10017 getprogname(), argv[0]);
10018 usage(1, 1);
10019 /* not reached */
10022 error = got_object_id_str(&commit_id_str, commit_id);
10023 if (error)
10024 goto done;
10026 cmd = &tog_commands[0]; /* log */
10027 argc = 4;
10028 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
10029 error = cmd->cmd_main(argc, cmd_argv);
10030 done:
10031 if (repo) {
10032 close_err = got_repo_close(repo);
10033 if (error == NULL)
10034 error = close_err;
10036 if (commit)
10037 got_object_commit_close(commit);
10038 if (worktree)
10039 got_worktree_close(worktree);
10040 if (pack_fds) {
10041 const struct got_error *pack_err =
10042 got_repo_pack_fds_close(pack_fds);
10043 if (error == NULL)
10044 error = pack_err;
10046 free(id);
10047 free(commit_id_str);
10048 free(commit_id);
10049 free(cwd);
10050 free(repo_path);
10051 free(in_repo_path);
10052 if (cmd_argv) {
10053 int i;
10054 for (i = 0; i < argc; i++)
10055 free(cmd_argv[i]);
10056 free(cmd_argv);
10058 tog_free_refs();
10059 return error;
10062 int
10063 main(int argc, char *argv[])
10065 const struct got_error *io_err, *error = NULL;
10066 const struct tog_cmd *cmd = NULL;
10067 int ch, hflag = 0, Vflag = 0;
10068 char **cmd_argv = NULL;
10069 static const struct option longopts[] = {
10070 { "version", no_argument, NULL, 'V' },
10071 { NULL, 0, NULL, 0}
10073 char *diff_algo_str = NULL;
10074 const char *test_script_path;
10076 setlocale(LC_CTYPE, "");
10079 * Override default signal handlers before starting ncurses.
10080 * This should prevent ncurses from installing its own
10081 * broken cleanup() signal handler.
10083 signal(SIGWINCH, tog_sigwinch);
10084 signal(SIGPIPE, tog_sigpipe);
10085 signal(SIGCONT, tog_sigcont);
10086 signal(SIGINT, tog_sigint);
10087 signal(SIGTERM, tog_sigterm);
10090 * Test mode init must happen before pledge() because "tty" will
10091 * not allow TTY-related ioctls to occur via regular files.
10093 test_script_path = getenv("TOG_TEST_SCRIPT");
10094 if (test_script_path != NULL) {
10095 error = init_mock_term(test_script_path);
10096 if (error) {
10097 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
10098 return 1;
10100 } else if (!isatty(STDIN_FILENO))
10101 errx(1, "standard input is not a tty");
10103 #if !defined(PROFILE)
10104 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
10105 NULL) == -1)
10106 err(1, "pledge");
10107 #endif
10109 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
10110 switch (ch) {
10111 case 'h':
10112 hflag = 1;
10113 break;
10114 case 'V':
10115 Vflag = 1;
10116 break;
10117 default:
10118 usage(hflag, 1);
10119 /* NOTREACHED */
10123 argc -= optind;
10124 argv += optind;
10125 optind = 1;
10126 optreset = 1;
10128 if (Vflag) {
10129 got_version_print_str();
10130 return 0;
10133 if (argc == 0) {
10134 if (hflag)
10135 usage(hflag, 0);
10136 /* Build an argument vector which runs a default command. */
10137 cmd = &tog_commands[0];
10138 argc = 1;
10139 cmd_argv = make_argv(argc, cmd->name);
10140 } else {
10141 size_t i;
10143 /* Did the user specify a command? */
10144 for (i = 0; i < nitems(tog_commands); i++) {
10145 if (strncmp(tog_commands[i].name, argv[0],
10146 strlen(argv[0])) == 0) {
10147 cmd = &tog_commands[i];
10148 break;
10153 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
10154 if (diff_algo_str) {
10155 if (strcasecmp(diff_algo_str, "patience") == 0)
10156 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
10157 if (strcasecmp(diff_algo_str, "myers") == 0)
10158 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
10161 tog_base_commit.idx = -1;
10162 tog_base_commit.marker = GOT_WORKTREE_STATE_UNKNOWN;
10164 if (cmd == NULL) {
10165 if (argc != 1)
10166 usage(0, 1);
10167 /* No command specified; try log with a path */
10168 error = tog_log_with_path(argc, argv);
10169 } else {
10170 if (hflag)
10171 cmd->cmd_usage();
10172 else
10173 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
10176 if (using_mock_io) {
10177 io_err = tog_io_close();
10178 if (error == NULL)
10179 error = io_err;
10181 endwin();
10182 if (cmd_argv) {
10183 int i;
10184 for (i = 0; i < argc; i++)
10185 free(cmd_argv[i]);
10186 free(cmd_argv);
10189 if (error && error->code != GOT_ERR_CANCELLED &&
10190 error->code != GOT_ERR_EOF &&
10191 error->code != GOT_ERR_PRIVSEP_EXIT &&
10192 error->code != GOT_ERR_PRIVSEP_PIPE &&
10193 !(error->code == GOT_ERR_ERRNO && errno == EINTR)) {
10194 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
10195 return 1;
10197 return 0;