Blob


1 /*
2 * Copyright (c) 2018, 2019, 2020 Stefan Sperling <stsp@openbsd.org>
3 *
4 * Permission to use, copy, modify, and distribute this software for any
5 * purpose with or without fee is hereby granted, provided that the above
6 * copyright notice and this permission notice appear in all copies.
7 *
8 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15 */
17 #include <sys/queue.h>
18 #include <sys/stat.h>
19 #include <sys/ioctl.h>
21 #include <ctype.h>
22 #include <errno.h>
23 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
24 #include <curses.h>
25 #include <panel.h>
26 #include <locale.h>
27 #include <sha1.h>
28 #include <sha2.h>
29 #include <signal.h>
30 #include <stdlib.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <getopt.h>
34 #include <string.h>
35 #include <err.h>
36 #include <unistd.h>
37 #include <limits.h>
38 #include <wchar.h>
39 #include <time.h>
40 #include <pthread.h>
41 #include <libgen.h>
42 #include <regex.h>
43 #include <sched.h>
45 #include "got_version.h"
46 #include "got_error.h"
47 #include "got_object.h"
48 #include "got_reference.h"
49 #include "got_repository.h"
50 #include "got_diff.h"
51 #include "got_opentemp.h"
52 #include "got_utf8.h"
53 #include "got_cancel.h"
54 #include "got_commit_graph.h"
55 #include "got_blame.h"
56 #include "got_privsep.h"
57 #include "got_path.h"
58 #include "got_worktree.h"
60 #ifndef MIN
61 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
62 #endif
64 #ifndef MAX
65 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
66 #endif
68 #define CTRL(x) ((x) & 0x1f)
70 #ifndef nitems
71 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
72 #endif
74 struct tog_cmd {
75 const char *name;
76 const struct got_error *(*cmd_main)(int, char *[]);
77 void (*cmd_usage)(void);
78 };
80 __dead static void usage(int, int);
81 __dead static void usage_log(void);
82 __dead static void usage_diff(void);
83 __dead static void usage_blame(void);
84 __dead static void usage_tree(void);
85 __dead static void usage_ref(void);
87 static const struct got_error* cmd_log(int, char *[]);
88 static const struct got_error* cmd_diff(int, char *[]);
89 static const struct got_error* cmd_blame(int, char *[]);
90 static const struct got_error* cmd_tree(int, char *[]);
91 static const struct got_error* cmd_ref(int, char *[]);
93 static const struct tog_cmd tog_commands[] = {
94 { "log", cmd_log, usage_log },
95 { "diff", cmd_diff, usage_diff },
96 { "blame", cmd_blame, usage_blame },
97 { "tree", cmd_tree, usage_tree },
98 { "ref", cmd_ref, usage_ref },
99 };
101 enum tog_view_type {
102 TOG_VIEW_DIFF,
103 TOG_VIEW_LOG,
104 TOG_VIEW_BLAME,
105 TOG_VIEW_TREE,
106 TOG_VIEW_REF,
107 TOG_VIEW_HELP
108 };
110 /* Match _DIFF to _HELP with enum tog_view_type TOG_VIEW_* counterparts. */
111 enum tog_keymap_type {
112 TOG_KEYMAP_KEYS = -2,
113 TOG_KEYMAP_GLOBAL,
114 TOG_KEYMAP_DIFF,
115 TOG_KEYMAP_LOG,
116 TOG_KEYMAP_BLAME,
117 TOG_KEYMAP_TREE,
118 TOG_KEYMAP_REF,
119 TOG_KEYMAP_HELP
120 };
122 enum tog_view_mode {
123 TOG_VIEW_SPLIT_NONE,
124 TOG_VIEW_SPLIT_VERT,
125 TOG_VIEW_SPLIT_HRZN
126 };
128 #define HSPLIT_SCALE 0.3 /* default horizontal split scale */
130 #define TOG_EOF_STRING "(END)"
132 struct commit_queue_entry {
133 TAILQ_ENTRY(commit_queue_entry) entry;
134 struct got_object_id *id;
135 struct got_commit_object *commit;
136 int idx;
137 };
138 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
139 struct commit_queue {
140 int ncommits;
141 struct commit_queue_head head;
142 };
144 struct tog_color {
145 STAILQ_ENTRY(tog_color) entry;
146 regex_t regex;
147 short colorpair;
148 };
149 STAILQ_HEAD(tog_colors, tog_color);
151 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
152 static struct got_reflist_object_id_map *tog_refs_idmap;
153 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
155 static const struct got_error *
156 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
157 struct got_reference* re2)
159 const char *name1 = got_ref_get_name(re1);
160 const char *name2 = got_ref_get_name(re2);
161 int isbackup1, isbackup2;
163 /* Sort backup refs towards the bottom of the list. */
164 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
165 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
166 if (!isbackup1 && isbackup2) {
167 *cmp = -1;
168 return NULL;
169 } else if (isbackup1 && !isbackup2) {
170 *cmp = 1;
171 return NULL;
174 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
175 return NULL;
178 static const struct got_error *
179 tog_load_refs(struct got_repository *repo, int sort_by_date)
181 const struct got_error *err;
183 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
184 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
185 repo);
186 if (err)
187 return err;
189 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
190 repo);
193 static void
194 tog_free_refs(void)
196 if (tog_refs_idmap) {
197 got_reflist_object_id_map_free(tog_refs_idmap);
198 tog_refs_idmap = NULL;
200 got_ref_list_free(&tog_refs);
203 static const struct got_error *
204 add_color(struct tog_colors *colors, const char *pattern,
205 int idx, short color)
207 const struct got_error *err = NULL;
208 struct tog_color *tc;
209 int regerr = 0;
211 if (idx < 1 || idx > COLOR_PAIRS - 1)
212 return NULL;
214 init_pair(idx, color, -1);
216 tc = calloc(1, sizeof(*tc));
217 if (tc == NULL)
218 return got_error_from_errno("calloc");
219 regerr = regcomp(&tc->regex, pattern,
220 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
221 if (regerr) {
222 static char regerr_msg[512];
223 static char err_msg[512];
224 regerror(regerr, &tc->regex, regerr_msg,
225 sizeof(regerr_msg));
226 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
227 regerr_msg);
228 err = got_error_msg(GOT_ERR_REGEX, err_msg);
229 free(tc);
230 return err;
232 tc->colorpair = idx;
233 STAILQ_INSERT_HEAD(colors, tc, entry);
234 return NULL;
237 static void
238 free_colors(struct tog_colors *colors)
240 struct tog_color *tc;
242 while (!STAILQ_EMPTY(colors)) {
243 tc = STAILQ_FIRST(colors);
244 STAILQ_REMOVE_HEAD(colors, entry);
245 regfree(&tc->regex);
246 free(tc);
250 static struct tog_color *
251 get_color(struct tog_colors *colors, int colorpair)
253 struct tog_color *tc = NULL;
255 STAILQ_FOREACH(tc, colors, entry) {
256 if (tc->colorpair == colorpair)
257 return tc;
260 return NULL;
263 static int
264 default_color_value(const char *envvar)
266 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
267 return COLOR_MAGENTA;
268 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
269 return COLOR_CYAN;
270 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
271 return COLOR_YELLOW;
272 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
273 return COLOR_GREEN;
274 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
275 return COLOR_MAGENTA;
276 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
277 return COLOR_MAGENTA;
278 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
279 return COLOR_CYAN;
280 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
281 return COLOR_GREEN;
282 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
283 return COLOR_GREEN;
284 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
285 return COLOR_CYAN;
286 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
287 return COLOR_YELLOW;
288 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
289 return COLOR_GREEN;
290 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
291 return COLOR_MAGENTA;
292 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
293 return COLOR_YELLOW;
294 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
295 return COLOR_CYAN;
297 return -1;
300 static int
301 get_color_value(const char *envvar)
303 const char *val = getenv(envvar);
305 if (val == NULL)
306 return default_color_value(envvar);
308 if (strcasecmp(val, "black") == 0)
309 return COLOR_BLACK;
310 if (strcasecmp(val, "red") == 0)
311 return COLOR_RED;
312 if (strcasecmp(val, "green") == 0)
313 return COLOR_GREEN;
314 if (strcasecmp(val, "yellow") == 0)
315 return COLOR_YELLOW;
316 if (strcasecmp(val, "blue") == 0)
317 return COLOR_BLUE;
318 if (strcasecmp(val, "magenta") == 0)
319 return COLOR_MAGENTA;
320 if (strcasecmp(val, "cyan") == 0)
321 return COLOR_CYAN;
322 if (strcasecmp(val, "white") == 0)
323 return COLOR_WHITE;
324 if (strcasecmp(val, "default") == 0)
325 return -1;
327 return default_color_value(envvar);
330 struct tog_diff_view_state {
331 struct got_object_id *id1, *id2;
332 const char *label1, *label2;
333 FILE *f, *f1, *f2;
334 int fd1, fd2;
335 int lineno;
336 int first_displayed_line;
337 int last_displayed_line;
338 int eof;
339 int diff_context;
340 int ignore_whitespace;
341 int force_text_diff;
342 struct got_repository *repo;
343 struct got_diff_line *lines;
344 size_t nlines;
345 int matched_line;
346 int selected_line;
348 /* passed from log or blame view; may be NULL */
349 struct tog_view *parent_view;
350 };
352 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
353 static volatile sig_atomic_t tog_thread_error;
355 struct tog_log_thread_args {
356 pthread_cond_t need_commits;
357 pthread_cond_t commit_loaded;
358 int commits_needed;
359 int load_all;
360 struct got_commit_graph *graph;
361 struct commit_queue *real_commits;
362 const char *in_repo_path;
363 struct got_object_id *start_id;
364 struct got_repository *repo;
365 int *pack_fds;
366 int log_complete;
367 sig_atomic_t *quit;
368 struct commit_queue_entry **first_displayed_entry;
369 struct commit_queue_entry **selected_entry;
370 int *searching;
371 int *search_next_done;
372 regex_t *regex;
373 int *limiting;
374 int limit_match;
375 regex_t *limit_regex;
376 struct commit_queue *limit_commits;
377 };
379 struct tog_log_view_state {
380 struct commit_queue *commits;
381 struct commit_queue_entry *first_displayed_entry;
382 struct commit_queue_entry *last_displayed_entry;
383 struct commit_queue_entry *selected_entry;
384 struct commit_queue real_commits;
385 int selected;
386 char *in_repo_path;
387 char *head_ref_name;
388 int log_branches;
389 struct got_repository *repo;
390 struct got_object_id *start_id;
391 sig_atomic_t quit;
392 pthread_t thread;
393 struct tog_log_thread_args thread_args;
394 struct commit_queue_entry *matched_entry;
395 struct commit_queue_entry *search_entry;
396 struct tog_colors colors;
397 int use_committer;
398 int limit_view;
399 regex_t limit_regex;
400 struct commit_queue limit_commits;
401 };
403 #define TOG_COLOR_DIFF_MINUS 1
404 #define TOG_COLOR_DIFF_PLUS 2
405 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
406 #define TOG_COLOR_DIFF_META 4
407 #define TOG_COLOR_TREE_SUBMODULE 5
408 #define TOG_COLOR_TREE_SYMLINK 6
409 #define TOG_COLOR_TREE_DIRECTORY 7
410 #define TOG_COLOR_TREE_EXECUTABLE 8
411 #define TOG_COLOR_COMMIT 9
412 #define TOG_COLOR_AUTHOR 10
413 #define TOG_COLOR_DATE 11
414 #define TOG_COLOR_REFS_HEADS 12
415 #define TOG_COLOR_REFS_TAGS 13
416 #define TOG_COLOR_REFS_REMOTES 14
417 #define TOG_COLOR_REFS_BACKUP 15
419 struct tog_blame_cb_args {
420 struct tog_blame_line *lines; /* one per line */
421 int nlines;
423 struct tog_view *view;
424 struct got_object_id *commit_id;
425 int *quit;
426 };
428 struct tog_blame_thread_args {
429 const char *path;
430 struct got_repository *repo;
431 struct tog_blame_cb_args *cb_args;
432 int *complete;
433 got_cancel_cb cancel_cb;
434 void *cancel_arg;
435 };
437 struct tog_blame {
438 FILE *f;
439 off_t filesize;
440 struct tog_blame_line *lines;
441 int nlines;
442 off_t *line_offsets;
443 pthread_t thread;
444 struct tog_blame_thread_args thread_args;
445 struct tog_blame_cb_args cb_args;
446 const char *path;
447 int *pack_fds;
448 };
450 struct tog_blame_view_state {
451 int first_displayed_line;
452 int last_displayed_line;
453 int selected_line;
454 int last_diffed_line;
455 int blame_complete;
456 int eof;
457 int done;
458 struct got_object_id_queue blamed_commits;
459 struct got_object_qid *blamed_commit;
460 char *path;
461 struct got_repository *repo;
462 struct got_object_id *commit_id;
463 struct got_object_id *id_to_log;
464 struct tog_blame blame;
465 int matched_line;
466 struct tog_colors colors;
467 };
469 struct tog_parent_tree {
470 TAILQ_ENTRY(tog_parent_tree) entry;
471 struct got_tree_object *tree;
472 struct got_tree_entry *first_displayed_entry;
473 struct got_tree_entry *selected_entry;
474 int selected;
475 };
477 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
479 struct tog_tree_view_state {
480 char *tree_label;
481 struct got_object_id *commit_id;/* commit which this tree belongs to */
482 struct got_tree_object *root; /* the commit's root tree entry */
483 struct got_tree_object *tree; /* currently displayed (sub-)tree */
484 struct got_tree_entry *first_displayed_entry;
485 struct got_tree_entry *last_displayed_entry;
486 struct got_tree_entry *selected_entry;
487 int ndisplayed, selected, show_ids;
488 struct tog_parent_trees parents; /* parent trees of current sub-tree */
489 char *head_ref_name;
490 struct got_repository *repo;
491 struct got_tree_entry *matched_entry;
492 struct tog_colors colors;
493 };
495 struct tog_reflist_entry {
496 TAILQ_ENTRY(tog_reflist_entry) entry;
497 struct got_reference *ref;
498 int idx;
499 };
501 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
503 struct tog_ref_view_state {
504 struct tog_reflist_head refs;
505 struct tog_reflist_entry *first_displayed_entry;
506 struct tog_reflist_entry *last_displayed_entry;
507 struct tog_reflist_entry *selected_entry;
508 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
509 struct got_repository *repo;
510 struct tog_reflist_entry *matched_entry;
511 struct tog_colors colors;
512 };
514 struct tog_help_view_state {
515 FILE *f;
516 off_t *line_offsets;
517 size_t nlines;
518 int lineno;
519 int first_displayed_line;
520 int last_displayed_line;
521 int eof;
522 int matched_line;
523 int selected_line;
524 int all;
525 enum tog_keymap_type type;
526 };
528 #define GENERATE_HELP \
529 KEYMAP_("Global", TOG_KEYMAP_GLOBAL), \
530 KEY_("H F1", "Open view-specific help (double tap for all help)"), \
531 KEY_("k C-p Up", "Move cursor or page up one line"), \
532 KEY_("j C-n Down", "Move cursor or page down one line"), \
533 KEY_("C-b b PgUp", "Scroll the view up one page"), \
534 KEY_("C-f f PgDn Space", "Scroll the view down one page"), \
535 KEY_("C-u u", "Scroll the view up one half page"), \
536 KEY_("C-d d", "Scroll the view down one half page"), \
537 KEY_("g", "Go to line N (default: first line)"), \
538 KEY_("Home =", "Go to the first line"), \
539 KEY_("G", "Go to line N (default: last line)"), \
540 KEY_("End *", "Go to the last line"), \
541 KEY_("l Right", "Scroll the view right"), \
542 KEY_("h Left", "Scroll the view left"), \
543 KEY_("$", "Scroll view to the rightmost position"), \
544 KEY_("0", "Scroll view to the leftmost position"), \
545 KEY_("-", "Decrease size of the focussed split"), \
546 KEY_("+", "Increase size of the focussed split"), \
547 KEY_("Tab", "Switch focus between views"), \
548 KEY_("F", "Toggle fullscreen mode"), \
549 KEY_("S", "Switch split-screen layout"), \
550 KEY_("/", "Open prompt to enter search term"), \
551 KEY_("n", "Find next line/token matching the current search term"), \
552 KEY_("N", "Find previous line/token matching the current search term"),\
553 KEY_("q", "Quit the focussed view; Quit help screen"), \
554 KEY_("Q", "Quit tog"), \
556 KEYMAP_("Log view", TOG_KEYMAP_LOG), \
557 KEY_("< ,", "Move cursor up one commit"), \
558 KEY_("> .", "Move cursor down one commit"), \
559 KEY_("Enter", "Open diff view of the selected commit"), \
560 KEY_("B", "Reload the log view and toggle display of merged commits"), \
561 KEY_("R", "Open ref view of all repository references"), \
562 KEY_("T", "Display tree view of the repository from the selected" \
563 " commit"), \
564 KEY_("@", "Toggle between displaying author and committer name"), \
565 KEY_("&", "Open prompt to enter term to limit commits displayed"), \
566 KEY_("C-g Backspace", "Cancel current search or log operation"), \
567 KEY_("C-l", "Reload the log view with new commits in the repository"), \
569 KEYMAP_("Diff view", TOG_KEYMAP_DIFF), \
570 KEY_("K < ,", "Display diff of next line in the file/log entry"), \
571 KEY_("J > .", "Display diff of previous line in the file/log entry"), \
572 KEY_("A", "Toggle between Myers and Patience diff algorithm"), \
573 KEY_("a", "Toggle treatment of file as ASCII irrespective of binary" \
574 " data"), \
575 KEY_("(", "Go to the previous file in the diff"), \
576 KEY_(")", "Go to the next file in the diff"), \
577 KEY_("{", "Go to the previous hunk in the diff"), \
578 KEY_("}", "Go to the next hunk in the diff"), \
579 KEY_("[", "Decrease the number of context lines"), \
580 KEY_("]", "Increase the number of context lines"), \
581 KEY_("w", "Toggle ignore whitespace-only changes in the diff"), \
583 KEYMAP_("Blame view", TOG_KEYMAP_BLAME), \
584 KEY_("Enter", "Display diff view of the selected line's commit"), \
585 KEY_("A", "Toggle diff algorithm between Myers and Patience"), \
586 KEY_("L", "Open log view for the currently selected annotated line"), \
587 KEY_("C", "Reload view with the previously blamed commit"), \
588 KEY_("c", "Reload view with the version of the file found in the" \
589 " selected line's commit"), \
590 KEY_("p", "Reload view with the version of the file found in the" \
591 " selected line's parent commit"), \
593 KEYMAP_("Tree view", TOG_KEYMAP_TREE), \
594 KEY_("Enter", "Enter selected directory or open blame view of the" \
595 " selected file"), \
596 KEY_("L", "Open log view for the selected entry"), \
597 KEY_("R", "Open ref view of all repository references"), \
598 KEY_("i", "Show object IDs for all tree entries"), \
599 KEY_("Backspace", "Return to the parent directory"), \
601 KEYMAP_("Ref view", TOG_KEYMAP_REF), \
602 KEY_("Enter", "Display log view of the selected reference"), \
603 KEY_("T", "Display tree view of the selected reference"), \
604 KEY_("i", "Toggle display of IDs for all non-symbolic references"), \
605 KEY_("m", "Toggle display of last modified date for each reference"), \
606 KEY_("o", "Toggle reference sort order (name -> timestamp)"), \
607 KEY_("C-l", "Reload view with all repository references")
609 struct tog_key_map {
610 const char *keys;
611 const char *info;
612 enum tog_keymap_type type;
613 };
615 /* curses io for tog regress */
616 struct tog_io {
617 FILE *cin;
618 FILE *cout;
619 FILE *f;
620 int wait_for_ui;
621 } tog_io;
622 static int using_mock_io;
624 #define TOG_SCREEN_DUMP "SCREENDUMP"
625 #define TOG_SCREEN_DUMP_LEN (sizeof(TOG_SCREEN_DUMP) - 1)
626 #define TOG_KEY_SCRDUMP SHRT_MIN
628 /*
629 * We implement two types of views: parent views and child views.
631 * The 'Tab' key switches focus between a parent view and its child view.
632 * Child views are shown side-by-side to their parent view, provided
633 * there is enough screen estate.
635 * When a new view is opened from within a parent view, this new view
636 * becomes a child view of the parent view, replacing any existing child.
638 * When a new view is opened from within a child view, this new view
639 * becomes a parent view which will obscure the views below until the
640 * user quits the new parent view by typing 'q'.
642 * This list of views contains parent views only.
643 * Child views are only pointed to by their parent view.
644 */
645 TAILQ_HEAD(tog_view_list_head, tog_view);
647 struct tog_view {
648 TAILQ_ENTRY(tog_view) entry;
649 WINDOW *window;
650 PANEL *panel;
651 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
652 int resized_y, resized_x; /* begin_y/x based on user resizing */
653 int maxx, x; /* max column and current start column */
654 int lines, cols; /* copies of LINES and COLS */
655 int nscrolled, offset; /* lines scrolled and hsplit line offset */
656 int gline, hiline; /* navigate to and highlight this nG line */
657 int ch, count; /* current keymap and count prefix */
658 int resized; /* set when in a resize event */
659 int focussed; /* Only set on one parent or child view at a time. */
660 int dying;
661 struct tog_view *parent;
662 struct tog_view *child;
664 /*
665 * This flag is initially set on parent views when a new child view
666 * is created. It gets toggled when the 'Tab' key switches focus
667 * between parent and child.
668 * The flag indicates whether focus should be passed on to our child
669 * view if this parent view gets picked for focus after another parent
670 * view was closed. This prevents child views from losing focus in such
671 * situations.
672 */
673 int focus_child;
675 enum tog_view_mode mode;
676 /* type-specific state */
677 enum tog_view_type type;
678 union {
679 struct tog_diff_view_state diff;
680 struct tog_log_view_state log;
681 struct tog_blame_view_state blame;
682 struct tog_tree_view_state tree;
683 struct tog_ref_view_state ref;
684 struct tog_help_view_state help;
685 } state;
687 const struct got_error *(*show)(struct tog_view *);
688 const struct got_error *(*input)(struct tog_view **,
689 struct tog_view *, int);
690 const struct got_error *(*reset)(struct tog_view *);
691 const struct got_error *(*resize)(struct tog_view *, int);
692 const struct got_error *(*close)(struct tog_view *);
694 const struct got_error *(*search_start)(struct tog_view *);
695 const struct got_error *(*search_next)(struct tog_view *);
696 void (*search_setup)(struct tog_view *, FILE **, off_t **, size_t *,
697 int **, int **, int **, int **);
698 int search_started;
699 int searching;
700 #define TOG_SEARCH_FORWARD 1
701 #define TOG_SEARCH_BACKWARD 2
702 int search_next_done;
703 #define TOG_SEARCH_HAVE_MORE 1
704 #define TOG_SEARCH_NO_MORE 2
705 #define TOG_SEARCH_HAVE_NONE 3
706 regex_t regex;
707 regmatch_t regmatch;
708 const char *action;
709 };
711 static const struct got_error *open_diff_view(struct tog_view *,
712 struct got_object_id *, struct got_object_id *,
713 const char *, const char *, int, int, int, struct tog_view *,
714 struct got_repository *);
715 static const struct got_error *show_diff_view(struct tog_view *);
716 static const struct got_error *input_diff_view(struct tog_view **,
717 struct tog_view *, int);
718 static const struct got_error *reset_diff_view(struct tog_view *);
719 static const struct got_error* close_diff_view(struct tog_view *);
720 static const struct got_error *search_start_diff_view(struct tog_view *);
721 static void search_setup_diff_view(struct tog_view *, FILE **, off_t **,
722 size_t *, int **, int **, int **, int **);
723 static const struct got_error *search_next_view_match(struct tog_view *);
725 static const struct got_error *open_log_view(struct tog_view *,
726 struct got_object_id *, struct got_repository *,
727 const char *, const char *, int);
728 static const struct got_error * show_log_view(struct tog_view *);
729 static const struct got_error *input_log_view(struct tog_view **,
730 struct tog_view *, int);
731 static const struct got_error *resize_log_view(struct tog_view *, int);
732 static const struct got_error *close_log_view(struct tog_view *);
733 static const struct got_error *search_start_log_view(struct tog_view *);
734 static const struct got_error *search_next_log_view(struct tog_view *);
736 static const struct got_error *open_blame_view(struct tog_view *, char *,
737 struct got_object_id *, struct got_repository *);
738 static const struct got_error *show_blame_view(struct tog_view *);
739 static const struct got_error *input_blame_view(struct tog_view **,
740 struct tog_view *, int);
741 static const struct got_error *reset_blame_view(struct tog_view *);
742 static const struct got_error *close_blame_view(struct tog_view *);
743 static const struct got_error *search_start_blame_view(struct tog_view *);
744 static void search_setup_blame_view(struct tog_view *, FILE **, off_t **,
745 size_t *, int **, int **, int **, int **);
747 static const struct got_error *open_tree_view(struct tog_view *,
748 struct got_object_id *, const char *, struct got_repository *);
749 static const struct got_error *show_tree_view(struct tog_view *);
750 static const struct got_error *input_tree_view(struct tog_view **,
751 struct tog_view *, int);
752 static const struct got_error *close_tree_view(struct tog_view *);
753 static const struct got_error *search_start_tree_view(struct tog_view *);
754 static const struct got_error *search_next_tree_view(struct tog_view *);
756 static const struct got_error *open_ref_view(struct tog_view *,
757 struct got_repository *);
758 static const struct got_error *show_ref_view(struct tog_view *);
759 static const struct got_error *input_ref_view(struct tog_view **,
760 struct tog_view *, int);
761 static const struct got_error *close_ref_view(struct tog_view *);
762 static const struct got_error *search_start_ref_view(struct tog_view *);
763 static const struct got_error *search_next_ref_view(struct tog_view *);
765 static const struct got_error *open_help_view(struct tog_view *,
766 struct tog_view *);
767 static const struct got_error *show_help_view(struct tog_view *);
768 static const struct got_error *input_help_view(struct tog_view **,
769 struct tog_view *, int);
770 static const struct got_error *reset_help_view(struct tog_view *);
771 static const struct got_error* close_help_view(struct tog_view *);
772 static const struct got_error *search_start_help_view(struct tog_view *);
773 static void search_setup_help_view(struct tog_view *, FILE **, off_t **,
774 size_t *, int **, int **, int **, int **);
776 static volatile sig_atomic_t tog_sigwinch_received;
777 static volatile sig_atomic_t tog_sigpipe_received;
778 static volatile sig_atomic_t tog_sigcont_received;
779 static volatile sig_atomic_t tog_sigint_received;
780 static volatile sig_atomic_t tog_sigterm_received;
782 static void
783 tog_sigwinch(int signo)
785 tog_sigwinch_received = 1;
788 static void
789 tog_sigpipe(int signo)
791 tog_sigpipe_received = 1;
794 static void
795 tog_sigcont(int signo)
797 tog_sigcont_received = 1;
800 static void
801 tog_sigint(int signo)
803 tog_sigint_received = 1;
806 static void
807 tog_sigterm(int signo)
809 tog_sigterm_received = 1;
812 static int
813 tog_fatal_signal_received(void)
815 return (tog_sigpipe_received ||
816 tog_sigint_received || tog_sigterm_received);
819 static const struct got_error *
820 view_close(struct tog_view *view)
822 const struct got_error *err = NULL, *child_err = NULL;
824 if (view->child) {
825 child_err = view_close(view->child);
826 view->child = NULL;
828 if (view->close)
829 err = view->close(view);
830 if (view->panel)
831 del_panel(view->panel);
832 if (view->window)
833 delwin(view->window);
834 free(view);
835 return err ? err : child_err;
838 static struct tog_view *
839 view_open(int nlines, int ncols, int begin_y, int begin_x,
840 enum tog_view_type type)
842 struct tog_view *view = calloc(1, sizeof(*view));
844 if (view == NULL)
845 return NULL;
847 view->type = type;
848 view->lines = LINES;
849 view->cols = COLS;
850 view->nlines = nlines ? nlines : LINES - begin_y;
851 view->ncols = ncols ? ncols : COLS - begin_x;
852 view->begin_y = begin_y;
853 view->begin_x = begin_x;
854 view->window = newwin(nlines, ncols, begin_y, begin_x);
855 if (view->window == NULL) {
856 view_close(view);
857 return NULL;
859 view->panel = new_panel(view->window);
860 if (view->panel == NULL ||
861 set_panel_userptr(view->panel, view) != OK) {
862 view_close(view);
863 return NULL;
866 keypad(view->window, TRUE);
867 return view;
870 static int
871 view_split_begin_x(int begin_x)
873 if (begin_x > 0 || COLS < 120)
874 return 0;
875 return (COLS - MAX(COLS / 2, 80));
878 /* XXX Stub till we decide what to do. */
879 static int
880 view_split_begin_y(int lines)
882 return lines * HSPLIT_SCALE;
885 static const struct got_error *view_resize(struct tog_view *);
887 static const struct got_error *
888 view_splitscreen(struct tog_view *view)
890 const struct got_error *err = NULL;
892 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
893 if (view->resized_y && view->resized_y < view->lines)
894 view->begin_y = view->resized_y;
895 else
896 view->begin_y = view_split_begin_y(view->nlines);
897 view->begin_x = 0;
898 } else if (!view->resized) {
899 if (view->resized_x && view->resized_x < view->cols - 1 &&
900 view->cols > 119)
901 view->begin_x = view->resized_x;
902 else
903 view->begin_x = view_split_begin_x(0);
904 view->begin_y = 0;
906 view->nlines = LINES - view->begin_y;
907 view->ncols = COLS - view->begin_x;
908 view->lines = LINES;
909 view->cols = COLS;
910 err = view_resize(view);
911 if (err)
912 return err;
914 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
915 view->parent->nlines = view->begin_y;
917 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
918 return got_error_from_errno("mvwin");
920 return NULL;
923 static const struct got_error *
924 view_fullscreen(struct tog_view *view)
926 const struct got_error *err = NULL;
928 view->begin_x = 0;
929 view->begin_y = view->resized ? view->begin_y : 0;
930 view->nlines = view->resized ? view->nlines : LINES;
931 view->ncols = COLS;
932 view->lines = LINES;
933 view->cols = COLS;
934 err = view_resize(view);
935 if (err)
936 return err;
938 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
939 return got_error_from_errno("mvwin");
941 return NULL;
944 static int
945 view_is_parent_view(struct tog_view *view)
947 return view->parent == NULL;
950 static int
951 view_is_splitscreen(struct tog_view *view)
953 return view->begin_x > 0 || view->begin_y > 0;
956 static int
957 view_is_fullscreen(struct tog_view *view)
959 return view->nlines == LINES && view->ncols == COLS;
962 static int
963 view_is_hsplit_top(struct tog_view *view)
965 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
966 view_is_splitscreen(view->child);
969 static void
970 view_border(struct tog_view *view)
972 PANEL *panel;
973 const struct tog_view *view_above;
975 if (view->parent)
976 return view_border(view->parent);
978 panel = panel_above(view->panel);
979 if (panel == NULL)
980 return;
982 view_above = panel_userptr(panel);
983 if (view->mode == TOG_VIEW_SPLIT_HRZN)
984 mvwhline(view->window, view_above->begin_y - 1,
985 view->begin_x, got_locale_is_utf8() ?
986 ACS_HLINE : '-', view->ncols);
987 else
988 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
989 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
992 static const struct got_error *view_init_hsplit(struct tog_view *, int);
993 static const struct got_error *request_log_commits(struct tog_view *);
994 static const struct got_error *offset_selection_down(struct tog_view *);
995 static void offset_selection_up(struct tog_view *);
996 static void view_get_split(struct tog_view *, int *, int *);
998 static const struct got_error *
999 view_resize(struct tog_view *view)
1001 const struct got_error *err = NULL;
1002 int dif, nlines, ncols;
1004 dif = LINES - view->lines; /* line difference */
1006 if (view->lines > LINES)
1007 nlines = view->nlines - (view->lines - LINES);
1008 else
1009 nlines = view->nlines + (LINES - view->lines);
1010 if (view->cols > COLS)
1011 ncols = view->ncols - (view->cols - COLS);
1012 else
1013 ncols = view->ncols + (COLS - view->cols);
1015 if (view->child) {
1016 int hs = view->child->begin_y;
1018 if (!view_is_fullscreen(view))
1019 view->child->begin_x = view_split_begin_x(view->begin_x);
1020 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
1021 view->child->begin_x == 0) {
1022 ncols = COLS;
1024 view_fullscreen(view->child);
1025 if (view->child->focussed)
1026 show_panel(view->child->panel);
1027 else
1028 show_panel(view->panel);
1029 } else {
1030 ncols = view->child->begin_x;
1032 view_splitscreen(view->child);
1033 show_panel(view->child->panel);
1036 * XXX This is ugly and needs to be moved into the above
1037 * logic but "works" for now and my attempts at moving it
1038 * break either 'tab' or 'F' key maps in horizontal splits.
1040 if (hs) {
1041 err = view_splitscreen(view->child);
1042 if (err)
1043 return err;
1044 if (dif < 0) { /* top split decreased */
1045 err = offset_selection_down(view);
1046 if (err)
1047 return err;
1049 view_border(view);
1050 update_panels();
1051 doupdate();
1052 show_panel(view->child->panel);
1053 nlines = view->nlines;
1055 } else if (view->parent == NULL)
1056 ncols = COLS;
1058 if (view->resize && dif > 0) {
1059 err = view->resize(view, dif);
1060 if (err)
1061 return err;
1064 if (wresize(view->window, nlines, ncols) == ERR)
1065 return got_error_from_errno("wresize");
1066 if (replace_panel(view->panel, view->window) == ERR)
1067 return got_error_from_errno("replace_panel");
1068 wclear(view->window);
1070 view->nlines = nlines;
1071 view->ncols = ncols;
1072 view->lines = LINES;
1073 view->cols = COLS;
1075 return NULL;
1078 static const struct got_error *
1079 resize_log_view(struct tog_view *view, int increase)
1081 struct tog_log_view_state *s = &view->state.log;
1082 const struct got_error *err = NULL;
1083 int n = 0;
1085 if (s->selected_entry)
1086 n = s->selected_entry->idx + view->lines - s->selected;
1089 * Request commits to account for the increased
1090 * height so we have enough to populate the view.
1092 if (s->commits->ncommits < n) {
1093 view->nscrolled = n - s->commits->ncommits + increase + 1;
1094 err = request_log_commits(view);
1097 return err;
1100 static void
1101 view_adjust_offset(struct tog_view *view, int n)
1103 if (n == 0)
1104 return;
1106 if (view->parent && view->parent->offset) {
1107 if (view->parent->offset + n >= 0)
1108 view->parent->offset += n;
1109 else
1110 view->parent->offset = 0;
1111 } else if (view->offset) {
1112 if (view->offset - n >= 0)
1113 view->offset -= n;
1114 else
1115 view->offset = 0;
1119 static const struct got_error *
1120 view_resize_split(struct tog_view *view, int resize)
1122 const struct got_error *err = NULL;
1123 struct tog_view *v = NULL;
1125 if (view->parent)
1126 v = view->parent;
1127 else
1128 v = view;
1130 if (!v->child || !view_is_splitscreen(v->child))
1131 return NULL;
1133 v->resized = v->child->resized = resize; /* lock for resize event */
1135 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
1136 if (v->child->resized_y)
1137 v->child->begin_y = v->child->resized_y;
1138 if (view->parent)
1139 v->child->begin_y -= resize;
1140 else
1141 v->child->begin_y += resize;
1142 if (v->child->begin_y < 3) {
1143 view->count = 0;
1144 v->child->begin_y = 3;
1145 } else if (v->child->begin_y > LINES - 1) {
1146 view->count = 0;
1147 v->child->begin_y = LINES - 1;
1149 v->ncols = COLS;
1150 v->child->ncols = COLS;
1151 view_adjust_offset(view, resize);
1152 err = view_init_hsplit(v, v->child->begin_y);
1153 if (err)
1154 return err;
1155 v->child->resized_y = v->child->begin_y;
1156 } else {
1157 if (v->child->resized_x)
1158 v->child->begin_x = v->child->resized_x;
1159 if (view->parent)
1160 v->child->begin_x -= resize;
1161 else
1162 v->child->begin_x += resize;
1163 if (v->child->begin_x < 11) {
1164 view->count = 0;
1165 v->child->begin_x = 11;
1166 } else if (v->child->begin_x > COLS - 1) {
1167 view->count = 0;
1168 v->child->begin_x = COLS - 1;
1170 v->child->resized_x = v->child->begin_x;
1173 v->child->mode = v->mode;
1174 v->child->nlines = v->lines - v->child->begin_y;
1175 v->child->ncols = v->cols - v->child->begin_x;
1176 v->focus_child = 1;
1178 err = view_fullscreen(v);
1179 if (err)
1180 return err;
1181 err = view_splitscreen(v->child);
1182 if (err)
1183 return err;
1185 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1186 err = offset_selection_down(v->child);
1187 if (err)
1188 return err;
1191 if (v->resize)
1192 err = v->resize(v, 0);
1193 else if (v->child->resize)
1194 err = v->child->resize(v->child, 0);
1196 v->resized = v->child->resized = 0;
1198 return err;
1201 static void
1202 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1204 struct tog_view *v = src->child ? src->child : src;
1206 dst->resized_x = v->resized_x;
1207 dst->resized_y = v->resized_y;
1210 static const struct got_error *
1211 view_close_child(struct tog_view *view)
1213 const struct got_error *err = NULL;
1215 if (view->child == NULL)
1216 return NULL;
1218 err = view_close(view->child);
1219 view->child = NULL;
1220 return err;
1223 static const struct got_error *
1224 view_set_child(struct tog_view *view, struct tog_view *child)
1226 const struct got_error *err = NULL;
1228 view->child = child;
1229 child->parent = view;
1231 err = view_resize(view);
1232 if (err)
1233 return err;
1235 if (view->child->resized_x || view->child->resized_y)
1236 err = view_resize_split(view, 0);
1238 return err;
1241 static const struct got_error *view_dispatch_request(struct tog_view **,
1242 struct tog_view *, enum tog_view_type, int, int);
1244 static const struct got_error *
1245 view_request_new(struct tog_view **requested, struct tog_view *view,
1246 enum tog_view_type request)
1248 struct tog_view *new_view = NULL;
1249 const struct got_error *err;
1250 int y = 0, x = 0;
1252 *requested = NULL;
1254 if (view_is_parent_view(view) && request != TOG_VIEW_HELP)
1255 view_get_split(view, &y, &x);
1257 err = view_dispatch_request(&new_view, view, request, y, x);
1258 if (err)
1259 return err;
1261 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN &&
1262 request != TOG_VIEW_HELP) {
1263 err = view_init_hsplit(view, y);
1264 if (err)
1265 return err;
1268 view->focussed = 0;
1269 new_view->focussed = 1;
1270 new_view->mode = view->mode;
1271 new_view->nlines = request == TOG_VIEW_HELP ?
1272 view->lines : view->lines - y;
1274 if (view_is_parent_view(view) && request != TOG_VIEW_HELP) {
1275 view_transfer_size(new_view, view);
1276 err = view_close_child(view);
1277 if (err)
1278 return err;
1279 err = view_set_child(view, new_view);
1280 if (err)
1281 return err;
1282 view->focus_child = 1;
1283 } else
1284 *requested = new_view;
1286 return NULL;
1289 static void
1290 tog_resizeterm(void)
1292 int cols, lines;
1293 struct winsize size;
1295 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1296 cols = 80; /* Default */
1297 lines = 24;
1298 } else {
1299 cols = size.ws_col;
1300 lines = size.ws_row;
1302 resize_term(lines, cols);
1305 static const struct got_error *
1306 view_search_start(struct tog_view *view, int fast_refresh)
1308 const struct got_error *err = NULL;
1309 struct tog_view *v = view;
1310 char pattern[1024];
1311 int ret;
1313 if (view->search_started) {
1314 regfree(&view->regex);
1315 view->searching = 0;
1316 memset(&view->regmatch, 0, sizeof(view->regmatch));
1318 view->search_started = 0;
1320 if (view->nlines < 1)
1321 return NULL;
1323 if (view_is_hsplit_top(view))
1324 v = view->child;
1325 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1326 v = view->parent;
1328 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1329 wclrtoeol(v->window);
1331 nodelay(v->window, FALSE); /* block for search term input */
1332 nocbreak();
1333 echo();
1334 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1335 wrefresh(v->window);
1336 cbreak();
1337 noecho();
1338 nodelay(v->window, TRUE);
1339 if (!fast_refresh && !using_mock_io)
1340 halfdelay(10);
1341 if (ret == ERR)
1342 return NULL;
1344 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1345 err = view->search_start(view);
1346 if (err) {
1347 regfree(&view->regex);
1348 return err;
1350 view->search_started = 1;
1351 view->searching = TOG_SEARCH_FORWARD;
1352 view->search_next_done = 0;
1353 view->search_next(view);
1356 return NULL;
1359 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1360 static const struct got_error *
1361 switch_split(struct tog_view *view)
1363 const struct got_error *err = NULL;
1364 struct tog_view *v = NULL;
1366 if (view->parent)
1367 v = view->parent;
1368 else
1369 v = view;
1371 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1372 v->mode = TOG_VIEW_SPLIT_VERT;
1373 else
1374 v->mode = TOG_VIEW_SPLIT_HRZN;
1376 if (!v->child)
1377 return NULL;
1378 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1379 v->mode = TOG_VIEW_SPLIT_NONE;
1381 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1382 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1383 v->child->begin_y = v->child->resized_y;
1384 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1385 v->child->begin_x = v->child->resized_x;
1388 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1389 v->ncols = COLS;
1390 v->child->ncols = COLS;
1391 v->child->nscrolled = LINES - v->child->nlines;
1393 err = view_init_hsplit(v, v->child->begin_y);
1394 if (err)
1395 return err;
1397 v->child->mode = v->mode;
1398 v->child->nlines = v->lines - v->child->begin_y;
1399 v->focus_child = 1;
1401 err = view_fullscreen(v);
1402 if (err)
1403 return err;
1404 err = view_splitscreen(v->child);
1405 if (err)
1406 return err;
1408 if (v->mode == TOG_VIEW_SPLIT_NONE)
1409 v->mode = TOG_VIEW_SPLIT_VERT;
1410 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1411 err = offset_selection_down(v);
1412 if (err)
1413 return err;
1414 err = offset_selection_down(v->child);
1415 if (err)
1416 return err;
1417 } else {
1418 offset_selection_up(v);
1419 offset_selection_up(v->child);
1421 if (v->resize)
1422 err = v->resize(v, 0);
1423 else if (v->child->resize)
1424 err = v->child->resize(v->child, 0);
1426 return err;
1430 * Strip trailing whitespace from str starting at byte *n;
1431 * if *n < 0, use strlen(str). Return new str length in *n.
1433 static void
1434 strip_trailing_ws(char *str, int *n)
1436 size_t x = *n;
1438 if (str == NULL || *str == '\0')
1439 return;
1441 if (x < 0)
1442 x = strlen(str);
1444 while (x-- > 0 && isspace((unsigned char)str[x]))
1445 str[x] = '\0';
1447 *n = x + 1;
1451 * Extract visible substring of line y from the curses screen
1452 * and strip trailing whitespace. If vline is set and locale is
1453 * UTF-8, overwrite line[vline] with '|' because the ACS_VLINE
1454 * character is written out as 'x'. Write the line to file f.
1456 static const struct got_error *
1457 view_write_line(FILE *f, int y, int vline)
1459 char line[COLS * MB_LEN_MAX]; /* allow for multibyte chars */
1460 int r, w;
1462 r = mvwinnstr(curscr, y, 0, line, sizeof(line));
1463 if (r == ERR)
1464 return got_error_fmt(GOT_ERR_RANGE,
1465 "failed to extract line %d", y);
1468 * In some views, lines are padded with blanks to COLS width.
1469 * Strip them so we can diff without the -b flag when testing.
1471 strip_trailing_ws(line, &r);
1473 if (vline > 0 && got_locale_is_utf8())
1474 line[vline] = '|';
1476 w = fprintf(f, "%s\n", line);
1477 if (w != r + 1) /* \n */
1478 return got_ferror(f, GOT_ERR_IO);
1480 return NULL;
1484 * Capture the visible curses screen by writing each line to the
1485 * file at the path set via the TOG_SCR_DUMP environment variable.
1487 static const struct got_error *
1488 screendump(struct tog_view *view)
1490 const struct got_error *err;
1491 FILE *f = NULL;
1492 const char *path;
1493 int i;
1495 path = getenv("TOG_SCR_DUMP");
1496 if (path == NULL || *path == '\0')
1497 return got_error_msg(GOT_ERR_BAD_PATH,
1498 "TOG_SCR_DUMP path not set to capture screen dump");
1499 f = fopen(path, "wex");
1500 if (f == NULL)
1501 return got_error_from_errno_fmt("fopen: %s", path);
1503 if ((view->child && view->child->begin_x) ||
1504 (view->parent && view->begin_x)) {
1505 int ncols = view->child ? view->ncols : view->parent->ncols;
1507 /* vertical splitscreen */
1508 for (i = 0; i < view->nlines; ++i) {
1509 err = view_write_line(f, i, ncols - 1);
1510 if (err)
1511 goto done;
1513 } else {
1514 int hline = 0;
1516 /* fullscreen or horizontal splitscreen */
1517 if ((view->child && view->child->begin_y) ||
1518 (view->parent && view->begin_y)) /* hsplit */
1519 hline = view->child ?
1520 view->child->begin_y : view->begin_y;
1522 for (i = 0; i < view->lines; i++) {
1523 if (hline && got_locale_is_utf8() && i == hline - 1) {
1524 int c;
1526 /* ACS_HLINE writes out as 'q', overwrite it */
1527 for (c = 0; c < view->cols; ++c)
1528 fputc('-', f);
1529 fputc('\n', f);
1530 continue;
1533 err = view_write_line(f, i, 0);
1534 if (err)
1535 goto done;
1539 done:
1540 if (f && fclose(f) == EOF && err == NULL)
1541 err = got_ferror(f, GOT_ERR_IO);
1542 return err;
1546 * Compute view->count from numeric input. Assign total to view->count and
1547 * return first non-numeric key entered.
1549 static int
1550 get_compound_key(struct tog_view *view, int c)
1552 struct tog_view *v = view;
1553 int x, n = 0;
1555 if (view_is_hsplit_top(view))
1556 v = view->child;
1557 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1558 v = view->parent;
1560 view->count = 0;
1561 cbreak(); /* block for input */
1562 nodelay(view->window, FALSE);
1563 wmove(v->window, v->nlines - 1, 0);
1564 wclrtoeol(v->window);
1565 waddch(v->window, ':');
1567 do {
1568 x = getcurx(v->window);
1569 if (x != ERR && x < view->ncols) {
1570 waddch(v->window, c);
1571 wrefresh(v->window);
1575 * Don't overflow. Max valid request should be the greatest
1576 * between the longest and total lines; cap at 10 million.
1578 if (n >= 9999999)
1579 n = 9999999;
1580 else
1581 n = n * 10 + (c - '0');
1582 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1584 if (c == 'G' || c == 'g') { /* nG key map */
1585 view->gline = view->hiline = n;
1586 n = 0;
1587 c = 0;
1590 /* Massage excessive or inapplicable values at the input handler. */
1591 view->count = n;
1593 return c;
1596 static void
1597 action_report(struct tog_view *view)
1599 struct tog_view *v = view;
1601 if (view_is_hsplit_top(view))
1602 v = view->child;
1603 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1604 v = view->parent;
1606 wmove(v->window, v->nlines - 1, 0);
1607 wclrtoeol(v->window);
1608 wprintw(v->window, ":%s", view->action);
1609 wrefresh(v->window);
1612 * Clear action status report. Only clear in blame view
1613 * once annotating is complete, otherwise it's too fast.
1615 if (view->type == TOG_VIEW_BLAME) {
1616 if (view->state.blame.blame_complete)
1617 view->action = NULL;
1618 } else
1619 view->action = NULL;
1623 * Read the next line from the test script and assign
1624 * key instruction to *ch. If at EOF, set the *done flag.
1626 static const struct got_error *
1627 tog_read_script_key(FILE *script, int *ch, int *done)
1629 const struct got_error *err = NULL;
1630 char *line = NULL;
1631 size_t linesz = 0;
1633 *ch = -1;
1635 if (tog_io.wait_for_ui)
1636 goto done;
1638 if (getline(&line, &linesz, script) == -1) {
1639 if (feof(script)) {
1640 *done = 1;
1641 goto done;
1642 } else {
1643 err = got_ferror(script, GOT_ERR_IO);
1644 goto done;
1647 if (strncasecmp(line, "WAIT_FOR_UI", 11) == 0)
1648 tog_io.wait_for_ui = 1;
1649 else if (strncasecmp(line, "KEY_ENTER", 9) == 0)
1650 *ch = KEY_ENTER;
1651 else if (strncasecmp(line, "KEY_RIGHT", 9) == 0)
1652 *ch = KEY_RIGHT;
1653 else if (strncasecmp(line, "KEY_LEFT", 8) == 0)
1654 *ch = KEY_LEFT;
1655 else if (strncasecmp(line, "KEY_DOWN", 8) == 0)
1656 *ch = KEY_DOWN;
1657 else if (strncasecmp(line, "KEY_UP", 6) == 0)
1658 *ch = KEY_UP;
1659 else if (strncasecmp(line, TOG_SCREEN_DUMP, TOG_SCREEN_DUMP_LEN) == 0)
1660 *ch = TOG_KEY_SCRDUMP;
1661 else
1662 *ch = *line;
1664 done:
1665 free(line);
1666 return err;
1669 static const struct got_error *
1670 view_input(struct tog_view **new, int *done, struct tog_view *view,
1671 struct tog_view_list_head *views, int fast_refresh)
1673 const struct got_error *err = NULL;
1674 struct tog_view *v;
1675 int ch, errcode;
1677 *new = NULL;
1679 if (view->action)
1680 action_report(view);
1682 /* Clear "no matches" indicator. */
1683 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1684 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1685 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1686 view->count = 0;
1689 if (view->searching && !view->search_next_done) {
1690 errcode = pthread_mutex_unlock(&tog_mutex);
1691 if (errcode)
1692 return got_error_set_errno(errcode,
1693 "pthread_mutex_unlock");
1694 sched_yield();
1695 errcode = pthread_mutex_lock(&tog_mutex);
1696 if (errcode)
1697 return got_error_set_errno(errcode,
1698 "pthread_mutex_lock");
1699 view->search_next(view);
1700 return NULL;
1703 /* Allow threads to make progress while we are waiting for input. */
1704 errcode = pthread_mutex_unlock(&tog_mutex);
1705 if (errcode)
1706 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1708 if (using_mock_io) {
1709 err = tog_read_script_key(tog_io.f, &ch, done);
1710 if (err)
1711 return err;
1712 } else if (view->count && --view->count) {
1713 cbreak();
1714 nodelay(view->window, TRUE);
1715 ch = wgetch(view->window);
1716 /* let C-g or backspace abort unfinished count */
1717 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1718 view->count = 0;
1719 else
1720 ch = view->ch;
1721 } else {
1722 ch = wgetch(view->window);
1723 if (ch >= '1' && ch <= '9')
1724 view->ch = ch = get_compound_key(view, ch);
1726 if (view->hiline && ch != ERR && ch != 0)
1727 view->hiline = 0; /* key pressed, clear line highlight */
1728 nodelay(view->window, TRUE);
1729 errcode = pthread_mutex_lock(&tog_mutex);
1730 if (errcode)
1731 return got_error_set_errno(errcode, "pthread_mutex_lock");
1733 if (tog_sigwinch_received || tog_sigcont_received) {
1734 tog_resizeterm();
1735 tog_sigwinch_received = 0;
1736 tog_sigcont_received = 0;
1737 TAILQ_FOREACH(v, views, entry) {
1738 err = view_resize(v);
1739 if (err)
1740 return err;
1741 err = v->input(new, v, KEY_RESIZE);
1742 if (err)
1743 return err;
1744 if (v->child) {
1745 err = view_resize(v->child);
1746 if (err)
1747 return err;
1748 err = v->child->input(new, v->child,
1749 KEY_RESIZE);
1750 if (err)
1751 return err;
1752 if (v->child->resized_x || v->child->resized_y) {
1753 err = view_resize_split(v, 0);
1754 if (err)
1755 return err;
1761 switch (ch) {
1762 case '?':
1763 case 'H':
1764 case KEY_F(1):
1765 if (view->type == TOG_VIEW_HELP)
1766 err = view->reset(view);
1767 else
1768 err = view_request_new(new, view, TOG_VIEW_HELP);
1769 break;
1770 case '\t':
1771 view->count = 0;
1772 if (view->child) {
1773 view->focussed = 0;
1774 view->child->focussed = 1;
1775 view->focus_child = 1;
1776 } else if (view->parent) {
1777 view->focussed = 0;
1778 view->parent->focussed = 1;
1779 view->parent->focus_child = 0;
1780 if (!view_is_splitscreen(view)) {
1781 if (view->parent->resize) {
1782 err = view->parent->resize(view->parent,
1783 0);
1784 if (err)
1785 return err;
1787 offset_selection_up(view->parent);
1788 err = view_fullscreen(view->parent);
1789 if (err)
1790 return err;
1793 break;
1794 case 'q':
1795 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1796 if (view->parent->resize) {
1797 /* might need more commits to fill fullscreen */
1798 err = view->parent->resize(view->parent, 0);
1799 if (err)
1800 break;
1802 offset_selection_up(view->parent);
1804 err = view->input(new, view, ch);
1805 view->dying = 1;
1806 break;
1807 case 'Q':
1808 *done = 1;
1809 break;
1810 case 'F':
1811 view->count = 0;
1812 if (view_is_parent_view(view)) {
1813 if (view->child == NULL)
1814 break;
1815 if (view_is_splitscreen(view->child)) {
1816 view->focussed = 0;
1817 view->child->focussed = 1;
1818 err = view_fullscreen(view->child);
1819 } else {
1820 err = view_splitscreen(view->child);
1821 if (!err)
1822 err = view_resize_split(view, 0);
1824 if (err)
1825 break;
1826 err = view->child->input(new, view->child,
1827 KEY_RESIZE);
1828 } else {
1829 if (view_is_splitscreen(view)) {
1830 view->parent->focussed = 0;
1831 view->focussed = 1;
1832 err = view_fullscreen(view);
1833 } else {
1834 err = view_splitscreen(view);
1835 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1836 err = view_resize(view->parent);
1837 if (!err)
1838 err = view_resize_split(view, 0);
1840 if (err)
1841 break;
1842 err = view->input(new, view, KEY_RESIZE);
1844 if (err)
1845 break;
1846 if (view->resize) {
1847 err = view->resize(view, 0);
1848 if (err)
1849 break;
1851 if (view->parent)
1852 err = offset_selection_down(view->parent);
1853 if (!err)
1854 err = offset_selection_down(view);
1855 break;
1856 case 'S':
1857 view->count = 0;
1858 err = switch_split(view);
1859 break;
1860 case '-':
1861 err = view_resize_split(view, -1);
1862 break;
1863 case '+':
1864 err = view_resize_split(view, 1);
1865 break;
1866 case KEY_RESIZE:
1867 break;
1868 case '/':
1869 view->count = 0;
1870 if (view->search_start)
1871 view_search_start(view, fast_refresh);
1872 else
1873 err = view->input(new, view, ch);
1874 break;
1875 case 'N':
1876 case 'n':
1877 if (view->search_started && view->search_next) {
1878 view->searching = (ch == 'n' ?
1879 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1880 view->search_next_done = 0;
1881 view->search_next(view);
1882 } else
1883 err = view->input(new, view, ch);
1884 break;
1885 case 'A':
1886 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS) {
1887 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1888 view->action = "Patience diff algorithm";
1889 } else {
1890 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1891 view->action = "Myers diff algorithm";
1893 TAILQ_FOREACH(v, views, entry) {
1894 if (v->reset) {
1895 err = v->reset(v);
1896 if (err)
1897 return err;
1899 if (v->child && v->child->reset) {
1900 err = v->child->reset(v->child);
1901 if (err)
1902 return err;
1905 break;
1906 case TOG_KEY_SCRDUMP:
1907 err = screendump(view);
1908 break;
1909 default:
1910 err = view->input(new, view, ch);
1911 break;
1914 return err;
1917 static int
1918 view_needs_focus_indication(struct tog_view *view)
1920 if (view_is_parent_view(view)) {
1921 if (view->child == NULL || view->child->focussed)
1922 return 0;
1923 if (!view_is_splitscreen(view->child))
1924 return 0;
1925 } else if (!view_is_splitscreen(view))
1926 return 0;
1928 return view->focussed;
1931 static const struct got_error *
1932 tog_io_close(void)
1934 const struct got_error *err = NULL;
1936 if (tog_io.cin && fclose(tog_io.cin) == EOF)
1937 err = got_ferror(tog_io.cin, GOT_ERR_IO);
1938 if (tog_io.cout && fclose(tog_io.cout) == EOF && err == NULL)
1939 err = got_ferror(tog_io.cout, GOT_ERR_IO);
1940 if (tog_io.f && fclose(tog_io.f) == EOF && err == NULL)
1941 err = got_ferror(tog_io.f, GOT_ERR_IO);
1943 return err;
1946 static const struct got_error *
1947 view_loop(struct tog_view *view)
1949 const struct got_error *err = NULL;
1950 struct tog_view_list_head views;
1951 struct tog_view *new_view;
1952 char *mode;
1953 int fast_refresh = 10;
1954 int done = 0, errcode;
1956 mode = getenv("TOG_VIEW_SPLIT_MODE");
1957 if (!mode || !(*mode == 'h' || *mode == 'H'))
1958 view->mode = TOG_VIEW_SPLIT_VERT;
1959 else
1960 view->mode = TOG_VIEW_SPLIT_HRZN;
1962 errcode = pthread_mutex_lock(&tog_mutex);
1963 if (errcode)
1964 return got_error_set_errno(errcode, "pthread_mutex_lock");
1966 TAILQ_INIT(&views);
1967 TAILQ_INSERT_HEAD(&views, view, entry);
1969 view->focussed = 1;
1970 err = view->show(view);
1971 if (err)
1972 return err;
1973 update_panels();
1974 doupdate();
1975 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1976 !tog_fatal_signal_received()) {
1977 /* Refresh fast during initialization, then become slower. */
1978 if (fast_refresh && --fast_refresh == 0 && !using_mock_io)
1979 halfdelay(10); /* switch to once per second */
1981 err = view_input(&new_view, &done, view, &views, fast_refresh);
1982 if (err)
1983 break;
1985 if (view->dying && view == TAILQ_FIRST(&views) &&
1986 TAILQ_NEXT(view, entry) == NULL)
1987 done = 1;
1988 if (done) {
1989 struct tog_view *v;
1992 * When we quit, scroll the screen up a single line
1993 * so we don't lose any information.
1995 TAILQ_FOREACH(v, &views, entry) {
1996 wmove(v->window, 0, 0);
1997 wdeleteln(v->window);
1998 wnoutrefresh(v->window);
1999 if (v->child && !view_is_fullscreen(v)) {
2000 wmove(v->child->window, 0, 0);
2001 wdeleteln(v->child->window);
2002 wnoutrefresh(v->child->window);
2005 doupdate();
2008 if (view->dying) {
2009 struct tog_view *v, *prev = NULL;
2011 if (view_is_parent_view(view))
2012 prev = TAILQ_PREV(view, tog_view_list_head,
2013 entry);
2014 else if (view->parent)
2015 prev = view->parent;
2017 if (view->parent) {
2018 view->parent->child = NULL;
2019 view->parent->focus_child = 0;
2020 /* Restore fullscreen line height. */
2021 view->parent->nlines = view->parent->lines;
2022 err = view_resize(view->parent);
2023 if (err)
2024 break;
2025 /* Make resized splits persist. */
2026 view_transfer_size(view->parent, view);
2027 } else
2028 TAILQ_REMOVE(&views, view, entry);
2030 err = view_close(view);
2031 if (err)
2032 goto done;
2034 view = NULL;
2035 TAILQ_FOREACH(v, &views, entry) {
2036 if (v->focussed)
2037 break;
2039 if (view == NULL && new_view == NULL) {
2040 /* No view has focus. Try to pick one. */
2041 if (prev)
2042 view = prev;
2043 else if (!TAILQ_EMPTY(&views)) {
2044 view = TAILQ_LAST(&views,
2045 tog_view_list_head);
2047 if (view) {
2048 if (view->focus_child) {
2049 view->child->focussed = 1;
2050 view = view->child;
2051 } else
2052 view->focussed = 1;
2056 if (new_view) {
2057 struct tog_view *v, *t;
2058 /* Only allow one parent view per type. */
2059 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
2060 if (v->type != new_view->type)
2061 continue;
2062 TAILQ_REMOVE(&views, v, entry);
2063 err = view_close(v);
2064 if (err)
2065 goto done;
2066 break;
2068 TAILQ_INSERT_TAIL(&views, new_view, entry);
2069 view = new_view;
2071 if (view && !done) {
2072 if (view_is_parent_view(view)) {
2073 if (view->child && view->child->focussed)
2074 view = view->child;
2075 } else {
2076 if (view->parent && view->parent->focussed)
2077 view = view->parent;
2079 show_panel(view->panel);
2080 if (view->child && view_is_splitscreen(view->child))
2081 show_panel(view->child->panel);
2082 if (view->parent && view_is_splitscreen(view)) {
2083 err = view->parent->show(view->parent);
2084 if (err)
2085 goto done;
2087 err = view->show(view);
2088 if (err)
2089 goto done;
2090 if (view->child) {
2091 err = view->child->show(view->child);
2092 if (err)
2093 goto done;
2095 update_panels();
2096 doupdate();
2099 done:
2100 while (!TAILQ_EMPTY(&views)) {
2101 const struct got_error *close_err;
2102 view = TAILQ_FIRST(&views);
2103 TAILQ_REMOVE(&views, view, entry);
2104 close_err = view_close(view);
2105 if (close_err && err == NULL)
2106 err = close_err;
2109 errcode = pthread_mutex_unlock(&tog_mutex);
2110 if (errcode && err == NULL)
2111 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2113 return err;
2116 __dead static void
2117 usage_log(void)
2119 endwin();
2120 fprintf(stderr,
2121 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
2122 getprogname());
2123 exit(1);
2126 /* Create newly allocated wide-character string equivalent to a byte string. */
2127 static const struct got_error *
2128 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
2130 char *vis = NULL;
2131 const struct got_error *err = NULL;
2133 *ws = NULL;
2134 *wlen = mbstowcs(NULL, s, 0);
2135 if (*wlen == (size_t)-1) {
2136 int vislen;
2137 if (errno != EILSEQ)
2138 return got_error_from_errno("mbstowcs");
2140 /* byte string invalid in current encoding; try to "fix" it */
2141 err = got_mbsavis(&vis, &vislen, s);
2142 if (err)
2143 return err;
2144 *wlen = mbstowcs(NULL, vis, 0);
2145 if (*wlen == (size_t)-1) {
2146 err = got_error_from_errno("mbstowcs"); /* give up */
2147 goto done;
2151 *ws = calloc(*wlen + 1, sizeof(**ws));
2152 if (*ws == NULL) {
2153 err = got_error_from_errno("calloc");
2154 goto done;
2157 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
2158 err = got_error_from_errno("mbstowcs");
2159 done:
2160 free(vis);
2161 if (err) {
2162 free(*ws);
2163 *ws = NULL;
2164 *wlen = 0;
2166 return err;
2169 static const struct got_error *
2170 expand_tab(char **ptr, const char *src)
2172 char *dst;
2173 size_t len, n, idx = 0, sz = 0;
2175 *ptr = NULL;
2176 n = len = strlen(src);
2177 dst = malloc(n + 1);
2178 if (dst == NULL)
2179 return got_error_from_errno("malloc");
2181 while (idx < len && src[idx]) {
2182 const char c = src[idx];
2184 if (c == '\t') {
2185 size_t nb = TABSIZE - sz % TABSIZE;
2186 char *p;
2188 p = realloc(dst, n + nb);
2189 if (p == NULL) {
2190 free(dst);
2191 return got_error_from_errno("realloc");
2194 dst = p;
2195 n += nb;
2196 memset(dst + sz, ' ', nb);
2197 sz += nb;
2198 } else
2199 dst[sz++] = src[idx];
2200 ++idx;
2203 dst[sz] = '\0';
2204 *ptr = dst;
2205 return NULL;
2209 * Advance at most n columns from wline starting at offset off.
2210 * Return the index to the first character after the span operation.
2211 * Return the combined column width of all spanned wide character in
2212 * *rcol.
2214 static int
2215 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
2217 int width, i, cols = 0;
2219 if (n == 0) {
2220 *rcol = cols;
2221 return off;
2224 for (i = off; wline[i] != L'\0'; ++i) {
2225 if (wline[i] == L'\t')
2226 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
2227 else
2228 width = wcwidth(wline[i]);
2230 if (width == -1) {
2231 width = 1;
2232 wline[i] = L'.';
2235 if (cols + width > n)
2236 break;
2237 cols += width;
2240 *rcol = cols;
2241 return i;
2245 * Format a line for display, ensuring that it won't overflow a width limit.
2246 * With scrolling, the width returned refers to the scrolled version of the
2247 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
2249 static const struct got_error *
2250 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
2251 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
2253 const struct got_error *err = NULL;
2254 int cols;
2255 wchar_t *wline = NULL;
2256 char *exstr = NULL;
2257 size_t wlen;
2258 int i, scrollx;
2260 *wlinep = NULL;
2261 *widthp = 0;
2263 if (expand) {
2264 err = expand_tab(&exstr, line);
2265 if (err)
2266 return err;
2269 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
2270 free(exstr);
2271 if (err)
2272 return err;
2274 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
2276 if (wlen > 0 && wline[wlen - 1] == L'\n') {
2277 wline[wlen - 1] = L'\0';
2278 wlen--;
2280 if (wlen > 0 && wline[wlen - 1] == L'\r') {
2281 wline[wlen - 1] = L'\0';
2282 wlen--;
2285 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
2286 wline[i] = L'\0';
2288 if (widthp)
2289 *widthp = cols;
2290 if (scrollxp)
2291 *scrollxp = scrollx;
2292 if (err)
2293 free(wline);
2294 else
2295 *wlinep = wline;
2296 return err;
2299 static const struct got_error*
2300 build_refs_str(char **refs_str, struct got_reflist_head *refs,
2301 struct got_object_id *id, struct got_repository *repo)
2303 static const struct got_error *err = NULL;
2304 struct got_reflist_entry *re;
2305 char *s;
2306 const char *name;
2308 *refs_str = NULL;
2310 TAILQ_FOREACH(re, refs, entry) {
2311 struct got_tag_object *tag = NULL;
2312 struct got_object_id *ref_id;
2313 int cmp;
2315 name = got_ref_get_name(re->ref);
2316 if (strcmp(name, GOT_REF_HEAD) == 0)
2317 continue;
2318 if (strncmp(name, "refs/", 5) == 0)
2319 name += 5;
2320 if (strncmp(name, "got/", 4) == 0 &&
2321 strncmp(name, "got/backup/", 11) != 0)
2322 continue;
2323 if (strncmp(name, "heads/", 6) == 0)
2324 name += 6;
2325 if (strncmp(name, "remotes/", 8) == 0) {
2326 name += 8;
2327 s = strstr(name, "/" GOT_REF_HEAD);
2328 if (s != NULL && s[strlen(s)] == '\0')
2329 continue;
2331 err = got_ref_resolve(&ref_id, repo, re->ref);
2332 if (err)
2333 break;
2334 if (strncmp(name, "tags/", 5) == 0) {
2335 err = got_object_open_as_tag(&tag, repo, ref_id);
2336 if (err) {
2337 if (err->code != GOT_ERR_OBJ_TYPE) {
2338 free(ref_id);
2339 break;
2341 /* Ref points at something other than a tag. */
2342 err = NULL;
2343 tag = NULL;
2346 cmp = got_object_id_cmp(tag ?
2347 got_object_tag_get_object_id(tag) : ref_id, id);
2348 free(ref_id);
2349 if (tag)
2350 got_object_tag_close(tag);
2351 if (cmp != 0)
2352 continue;
2353 s = *refs_str;
2354 if (asprintf(refs_str, "%s%s%s", s ? s : "",
2355 s ? ", " : "", name) == -1) {
2356 err = got_error_from_errno("asprintf");
2357 free(s);
2358 *refs_str = NULL;
2359 break;
2361 free(s);
2364 return err;
2367 static const struct got_error *
2368 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
2369 int col_tab_align)
2371 char *smallerthan;
2373 smallerthan = strchr(author, '<');
2374 if (smallerthan && smallerthan[1] != '\0')
2375 author = smallerthan + 1;
2376 author[strcspn(author, "@>")] = '\0';
2377 return format_line(wauthor, author_width, NULL, author, 0, limit,
2378 col_tab_align, 0);
2381 static const struct got_error *
2382 draw_commit(struct tog_view *view, struct got_commit_object *commit,
2383 struct got_object_id *id, const size_t date_display_cols,
2384 int author_display_cols)
2386 struct tog_log_view_state *s = &view->state.log;
2387 const struct got_error *err = NULL;
2388 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
2389 char *logmsg0 = NULL, *logmsg = NULL;
2390 char *author = NULL;
2391 wchar_t *wlogmsg = NULL, *wauthor = NULL;
2392 int author_width, logmsg_width;
2393 char *newline, *line = NULL;
2394 int col, limit, scrollx;
2395 const int avail = view->ncols;
2396 struct tm tm;
2397 time_t committer_time;
2398 struct tog_color *tc;
2400 committer_time = got_object_commit_get_committer_time(commit);
2401 if (gmtime_r(&committer_time, &tm) == NULL)
2402 return got_error_from_errno("gmtime_r");
2403 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
2404 return got_error(GOT_ERR_NO_SPACE);
2406 if (avail <= date_display_cols)
2407 limit = MIN(sizeof(datebuf) - 1, avail);
2408 else
2409 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2410 tc = get_color(&s->colors, TOG_COLOR_DATE);
2411 if (tc)
2412 wattr_on(view->window,
2413 COLOR_PAIR(tc->colorpair), NULL);
2414 waddnstr(view->window, datebuf, limit);
2415 if (tc)
2416 wattr_off(view->window,
2417 COLOR_PAIR(tc->colorpair), NULL);
2418 col = limit;
2419 if (col > avail)
2420 goto done;
2422 if (avail >= 120) {
2423 char *id_str;
2424 err = got_object_id_str(&id_str, id);
2425 if (err)
2426 goto done;
2427 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2428 if (tc)
2429 wattr_on(view->window,
2430 COLOR_PAIR(tc->colorpair), NULL);
2431 wprintw(view->window, "%.8s ", id_str);
2432 if (tc)
2433 wattr_off(view->window,
2434 COLOR_PAIR(tc->colorpair), NULL);
2435 free(id_str);
2436 col += 9;
2437 if (col > avail)
2438 goto done;
2441 if (s->use_committer)
2442 author = strdup(got_object_commit_get_committer(commit));
2443 else
2444 author = strdup(got_object_commit_get_author(commit));
2445 if (author == NULL) {
2446 err = got_error_from_errno("strdup");
2447 goto done;
2449 err = format_author(&wauthor, &author_width, author, avail - col, col);
2450 if (err)
2451 goto done;
2452 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2453 if (tc)
2454 wattr_on(view->window,
2455 COLOR_PAIR(tc->colorpair), NULL);
2456 waddwstr(view->window, wauthor);
2457 col += author_width;
2458 while (col < avail && author_width < author_display_cols + 2) {
2459 waddch(view->window, ' ');
2460 col++;
2461 author_width++;
2463 if (tc)
2464 wattr_off(view->window,
2465 COLOR_PAIR(tc->colorpair), NULL);
2466 if (col > avail)
2467 goto done;
2469 err = got_object_commit_get_logmsg(&logmsg0, commit);
2470 if (err)
2471 goto done;
2472 logmsg = logmsg0;
2473 while (*logmsg == '\n')
2474 logmsg++;
2475 newline = strchr(logmsg, '\n');
2476 if (newline)
2477 *newline = '\0';
2478 limit = avail - col;
2479 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2480 limit--; /* for the border */
2481 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2482 limit, col, 1);
2483 if (err)
2484 goto done;
2485 waddwstr(view->window, &wlogmsg[scrollx]);
2486 col += MAX(logmsg_width, 0);
2487 while (col < avail) {
2488 waddch(view->window, ' ');
2489 col++;
2491 done:
2492 free(logmsg0);
2493 free(wlogmsg);
2494 free(author);
2495 free(wauthor);
2496 free(line);
2497 return err;
2500 static struct commit_queue_entry *
2501 alloc_commit_queue_entry(struct got_commit_object *commit,
2502 struct got_object_id *id)
2504 struct commit_queue_entry *entry;
2505 struct got_object_id *dup;
2507 entry = calloc(1, sizeof(*entry));
2508 if (entry == NULL)
2509 return NULL;
2511 dup = got_object_id_dup(id);
2512 if (dup == NULL) {
2513 free(entry);
2514 return NULL;
2517 entry->id = dup;
2518 entry->commit = commit;
2519 return entry;
2522 static void
2523 pop_commit(struct commit_queue *commits)
2525 struct commit_queue_entry *entry;
2527 entry = TAILQ_FIRST(&commits->head);
2528 TAILQ_REMOVE(&commits->head, entry, entry);
2529 got_object_commit_close(entry->commit);
2530 commits->ncommits--;
2531 free(entry->id);
2532 free(entry);
2535 static void
2536 free_commits(struct commit_queue *commits)
2538 while (!TAILQ_EMPTY(&commits->head))
2539 pop_commit(commits);
2542 static const struct got_error *
2543 match_commit(int *have_match, struct got_object_id *id,
2544 struct got_commit_object *commit, regex_t *regex)
2546 const struct got_error *err = NULL;
2547 regmatch_t regmatch;
2548 char *id_str = NULL, *logmsg = NULL;
2550 *have_match = 0;
2552 err = got_object_id_str(&id_str, id);
2553 if (err)
2554 return err;
2556 err = got_object_commit_get_logmsg(&logmsg, commit);
2557 if (err)
2558 goto done;
2560 if (regexec(regex, got_object_commit_get_author(commit), 1,
2561 &regmatch, 0) == 0 ||
2562 regexec(regex, got_object_commit_get_committer(commit), 1,
2563 &regmatch, 0) == 0 ||
2564 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2565 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2566 *have_match = 1;
2567 done:
2568 free(id_str);
2569 free(logmsg);
2570 return err;
2573 static const struct got_error *
2574 queue_commits(struct tog_log_thread_args *a)
2576 const struct got_error *err = NULL;
2579 * We keep all commits open throughout the lifetime of the log
2580 * view in order to avoid having to re-fetch commits from disk
2581 * while updating the display.
2583 do {
2584 struct got_object_id id;
2585 struct got_commit_object *commit;
2586 struct commit_queue_entry *entry;
2587 int limit_match = 0;
2588 int errcode;
2590 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2591 NULL, NULL);
2592 if (err)
2593 break;
2595 err = got_object_open_as_commit(&commit, a->repo, &id);
2596 if (err)
2597 break;
2598 entry = alloc_commit_queue_entry(commit, &id);
2599 if (entry == NULL) {
2600 err = got_error_from_errno("alloc_commit_queue_entry");
2601 break;
2604 errcode = pthread_mutex_lock(&tog_mutex);
2605 if (errcode) {
2606 err = got_error_set_errno(errcode,
2607 "pthread_mutex_lock");
2608 break;
2611 entry->idx = a->real_commits->ncommits;
2612 TAILQ_INSERT_TAIL(&a->real_commits->head, entry, entry);
2613 a->real_commits->ncommits++;
2615 if (*a->limiting) {
2616 err = match_commit(&limit_match, &id, commit,
2617 a->limit_regex);
2618 if (err)
2619 break;
2621 if (limit_match) {
2622 struct commit_queue_entry *matched;
2624 matched = alloc_commit_queue_entry(
2625 entry->commit, entry->id);
2626 if (matched == NULL) {
2627 err = got_error_from_errno(
2628 "alloc_commit_queue_entry");
2629 break;
2631 matched->commit = entry->commit;
2632 got_object_commit_retain(entry->commit);
2634 matched->idx = a->limit_commits->ncommits;
2635 TAILQ_INSERT_TAIL(&a->limit_commits->head,
2636 matched, entry);
2637 a->limit_commits->ncommits++;
2641 * This is how we signal log_thread() that we
2642 * have found a match, and that it should be
2643 * counted as a new entry for the view.
2645 a->limit_match = limit_match;
2648 if (*a->searching == TOG_SEARCH_FORWARD &&
2649 !*a->search_next_done) {
2650 int have_match;
2651 err = match_commit(&have_match, &id, commit, a->regex);
2652 if (err)
2653 break;
2655 if (*a->limiting) {
2656 if (limit_match && have_match)
2657 *a->search_next_done =
2658 TOG_SEARCH_HAVE_MORE;
2659 } else if (have_match)
2660 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2663 errcode = pthread_mutex_unlock(&tog_mutex);
2664 if (errcode && err == NULL)
2665 err = got_error_set_errno(errcode,
2666 "pthread_mutex_unlock");
2667 if (err)
2668 break;
2669 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2671 return err;
2674 static void
2675 select_commit(struct tog_log_view_state *s)
2677 struct commit_queue_entry *entry;
2678 int ncommits = 0;
2680 entry = s->first_displayed_entry;
2681 while (entry) {
2682 if (ncommits == s->selected) {
2683 s->selected_entry = entry;
2684 break;
2686 entry = TAILQ_NEXT(entry, entry);
2687 ncommits++;
2691 static const struct got_error *
2692 draw_commits(struct tog_view *view)
2694 const struct got_error *err = NULL;
2695 struct tog_log_view_state *s = &view->state.log;
2696 struct commit_queue_entry *entry = s->selected_entry;
2697 int limit = view->nlines;
2698 int width;
2699 int ncommits, author_cols = 4;
2700 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2701 char *refs_str = NULL;
2702 wchar_t *wline;
2703 struct tog_color *tc;
2704 static const size_t date_display_cols = 12;
2706 if (view_is_hsplit_top(view))
2707 --limit; /* account for border */
2709 if (s->selected_entry &&
2710 !(view->searching && view->search_next_done == 0)) {
2711 struct got_reflist_head *refs;
2712 err = got_object_id_str(&id_str, s->selected_entry->id);
2713 if (err)
2714 return err;
2715 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2716 s->selected_entry->id);
2717 if (refs) {
2718 err = build_refs_str(&refs_str, refs,
2719 s->selected_entry->id, s->repo);
2720 if (err)
2721 goto done;
2725 if (s->thread_args.commits_needed == 0 && !using_mock_io)
2726 halfdelay(10); /* disable fast refresh */
2728 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2729 if (asprintf(&ncommits_str, " [%d/%d] %s",
2730 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2731 (view->searching && !view->search_next_done) ?
2732 "searching..." : "loading...") == -1) {
2733 err = got_error_from_errno("asprintf");
2734 goto done;
2736 } else {
2737 const char *search_str = NULL;
2738 const char *limit_str = NULL;
2740 if (view->searching) {
2741 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2742 search_str = "no more matches";
2743 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2744 search_str = "no matches found";
2745 else if (!view->search_next_done)
2746 search_str = "searching...";
2749 if (s->limit_view && s->commits->ncommits == 0)
2750 limit_str = "no matches found";
2752 if (asprintf(&ncommits_str, " [%d/%d] %s %s",
2753 entry ? entry->idx + 1 : 0, s->commits->ncommits,
2754 search_str ? search_str : (refs_str ? refs_str : ""),
2755 limit_str ? limit_str : "") == -1) {
2756 err = got_error_from_errno("asprintf");
2757 goto done;
2761 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2762 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2763 "........................................",
2764 s->in_repo_path, ncommits_str) == -1) {
2765 err = got_error_from_errno("asprintf");
2766 header = NULL;
2767 goto done;
2769 } else if (asprintf(&header, "commit %s%s",
2770 id_str ? id_str : "........................................",
2771 ncommits_str) == -1) {
2772 err = got_error_from_errno("asprintf");
2773 header = NULL;
2774 goto done;
2776 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2777 if (err)
2778 goto done;
2780 werase(view->window);
2782 if (view_needs_focus_indication(view))
2783 wstandout(view->window);
2784 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2785 if (tc)
2786 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
2787 waddwstr(view->window, wline);
2788 while (width < view->ncols) {
2789 waddch(view->window, ' ');
2790 width++;
2792 if (tc)
2793 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
2794 if (view_needs_focus_indication(view))
2795 wstandend(view->window);
2796 free(wline);
2797 if (limit <= 1)
2798 goto done;
2800 /* Grow author column size if necessary, and set view->maxx. */
2801 entry = s->first_displayed_entry;
2802 ncommits = 0;
2803 view->maxx = 0;
2804 while (entry) {
2805 struct got_commit_object *c = entry->commit;
2806 char *author, *eol, *msg, *msg0;
2807 wchar_t *wauthor, *wmsg;
2808 int width;
2809 if (ncommits >= limit - 1)
2810 break;
2811 if (s->use_committer)
2812 author = strdup(got_object_commit_get_committer(c));
2813 else
2814 author = strdup(got_object_commit_get_author(c));
2815 if (author == NULL) {
2816 err = got_error_from_errno("strdup");
2817 goto done;
2819 err = format_author(&wauthor, &width, author, COLS,
2820 date_display_cols);
2821 if (author_cols < width)
2822 author_cols = width;
2823 free(wauthor);
2824 free(author);
2825 if (err)
2826 goto done;
2827 err = got_object_commit_get_logmsg(&msg0, c);
2828 if (err)
2829 goto done;
2830 msg = msg0;
2831 while (*msg == '\n')
2832 ++msg;
2833 if ((eol = strchr(msg, '\n')))
2834 *eol = '\0';
2835 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2836 date_display_cols + author_cols, 0);
2837 if (err)
2838 goto done;
2839 view->maxx = MAX(view->maxx, width);
2840 free(msg0);
2841 free(wmsg);
2842 ncommits++;
2843 entry = TAILQ_NEXT(entry, entry);
2846 entry = s->first_displayed_entry;
2847 s->last_displayed_entry = s->first_displayed_entry;
2848 ncommits = 0;
2849 while (entry) {
2850 if (ncommits >= limit - 1)
2851 break;
2852 if (ncommits == s->selected)
2853 wstandout(view->window);
2854 err = draw_commit(view, entry->commit, entry->id,
2855 date_display_cols, author_cols);
2856 if (ncommits == s->selected)
2857 wstandend(view->window);
2858 if (err)
2859 goto done;
2860 ncommits++;
2861 s->last_displayed_entry = entry;
2862 entry = TAILQ_NEXT(entry, entry);
2865 view_border(view);
2866 done:
2867 free(id_str);
2868 free(refs_str);
2869 free(ncommits_str);
2870 free(header);
2871 return err;
2874 static void
2875 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2877 struct commit_queue_entry *entry;
2878 int nscrolled = 0;
2880 entry = TAILQ_FIRST(&s->commits->head);
2881 if (s->first_displayed_entry == entry)
2882 return;
2884 entry = s->first_displayed_entry;
2885 while (entry && nscrolled < maxscroll) {
2886 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2887 if (entry) {
2888 s->first_displayed_entry = entry;
2889 nscrolled++;
2894 static const struct got_error *
2895 trigger_log_thread(struct tog_view *view, int wait)
2897 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2898 int errcode;
2900 if (!using_mock_io)
2901 halfdelay(1); /* fast refresh while loading commits */
2903 while (!ta->log_complete && !tog_thread_error &&
2904 (ta->commits_needed > 0 || ta->load_all)) {
2905 /* Wake the log thread. */
2906 errcode = pthread_cond_signal(&ta->need_commits);
2907 if (errcode)
2908 return got_error_set_errno(errcode,
2909 "pthread_cond_signal");
2912 * The mutex will be released while the view loop waits
2913 * in wgetch(), at which time the log thread will run.
2915 if (!wait)
2916 break;
2918 /* Display progress update in log view. */
2919 show_log_view(view);
2920 update_panels();
2921 doupdate();
2923 /* Wait right here while next commit is being loaded. */
2924 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2925 if (errcode)
2926 return got_error_set_errno(errcode,
2927 "pthread_cond_wait");
2929 /* Display progress update in log view. */
2930 show_log_view(view);
2931 update_panels();
2932 doupdate();
2935 return NULL;
2938 static const struct got_error *
2939 request_log_commits(struct tog_view *view)
2941 struct tog_log_view_state *state = &view->state.log;
2942 const struct got_error *err = NULL;
2944 if (state->thread_args.log_complete)
2945 return NULL;
2947 state->thread_args.commits_needed += view->nscrolled;
2948 err = trigger_log_thread(view, 1);
2949 view->nscrolled = 0;
2951 return err;
2954 static const struct got_error *
2955 log_scroll_down(struct tog_view *view, int maxscroll)
2957 struct tog_log_view_state *s = &view->state.log;
2958 const struct got_error *err = NULL;
2959 struct commit_queue_entry *pentry;
2960 int nscrolled = 0, ncommits_needed;
2962 if (s->last_displayed_entry == NULL)
2963 return NULL;
2965 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2966 if (s->commits->ncommits < ncommits_needed &&
2967 !s->thread_args.log_complete) {
2969 * Ask the log thread for required amount of commits.
2971 s->thread_args.commits_needed +=
2972 ncommits_needed - s->commits->ncommits;
2973 err = trigger_log_thread(view, 1);
2974 if (err)
2975 return err;
2978 do {
2979 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2980 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2981 break;
2983 s->last_displayed_entry = pentry ?
2984 pentry : s->last_displayed_entry;
2986 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2987 if (pentry == NULL)
2988 break;
2989 s->first_displayed_entry = pentry;
2990 } while (++nscrolled < maxscroll);
2992 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2993 view->nscrolled += nscrolled;
2994 else
2995 view->nscrolled = 0;
2997 return err;
3000 static const struct got_error *
3001 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
3002 struct got_commit_object *commit, struct got_object_id *commit_id,
3003 struct tog_view *log_view, struct got_repository *repo)
3005 const struct got_error *err;
3006 struct got_object_qid *parent_id;
3007 struct tog_view *diff_view;
3009 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
3010 if (diff_view == NULL)
3011 return got_error_from_errno("view_open");
3013 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
3014 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
3015 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
3016 if (err == NULL)
3017 *new_view = diff_view;
3018 return err;
3021 static const struct got_error *
3022 tree_view_visit_subtree(struct tog_tree_view_state *s,
3023 struct got_tree_object *subtree)
3025 struct tog_parent_tree *parent;
3027 parent = calloc(1, sizeof(*parent));
3028 if (parent == NULL)
3029 return got_error_from_errno("calloc");
3031 parent->tree = s->tree;
3032 parent->first_displayed_entry = s->first_displayed_entry;
3033 parent->selected_entry = s->selected_entry;
3034 parent->selected = s->selected;
3035 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
3036 s->tree = subtree;
3037 s->selected = 0;
3038 s->first_displayed_entry = NULL;
3039 return NULL;
3042 static const struct got_error *
3043 tree_view_walk_path(struct tog_tree_view_state *s,
3044 struct got_commit_object *commit, const char *path)
3046 const struct got_error *err = NULL;
3047 struct got_tree_object *tree = NULL;
3048 const char *p;
3049 char *slash, *subpath = NULL;
3051 /* Walk the path and open corresponding tree objects. */
3052 p = path;
3053 while (*p) {
3054 struct got_tree_entry *te;
3055 struct got_object_id *tree_id;
3056 char *te_name;
3058 while (p[0] == '/')
3059 p++;
3061 /* Ensure the correct subtree entry is selected. */
3062 slash = strchr(p, '/');
3063 if (slash == NULL)
3064 te_name = strdup(p);
3065 else
3066 te_name = strndup(p, slash - p);
3067 if (te_name == NULL) {
3068 err = got_error_from_errno("strndup");
3069 break;
3071 te = got_object_tree_find_entry(s->tree, te_name);
3072 if (te == NULL) {
3073 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
3074 free(te_name);
3075 break;
3077 free(te_name);
3078 s->first_displayed_entry = s->selected_entry = te;
3080 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
3081 break; /* jump to this file's entry */
3083 slash = strchr(p, '/');
3084 if (slash)
3085 subpath = strndup(path, slash - path);
3086 else
3087 subpath = strdup(path);
3088 if (subpath == NULL) {
3089 err = got_error_from_errno("strdup");
3090 break;
3093 err = got_object_id_by_path(&tree_id, s->repo, commit,
3094 subpath);
3095 if (err)
3096 break;
3098 err = got_object_open_as_tree(&tree, s->repo, tree_id);
3099 free(tree_id);
3100 if (err)
3101 break;
3103 err = tree_view_visit_subtree(s, tree);
3104 if (err) {
3105 got_object_tree_close(tree);
3106 break;
3108 if (slash == NULL)
3109 break;
3110 free(subpath);
3111 subpath = NULL;
3112 p = slash;
3115 free(subpath);
3116 return err;
3119 static const struct got_error *
3120 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
3121 struct commit_queue_entry *entry, const char *path,
3122 const char *head_ref_name, struct got_repository *repo)
3124 const struct got_error *err = NULL;
3125 struct tog_tree_view_state *s;
3126 struct tog_view *tree_view;
3128 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
3129 if (tree_view == NULL)
3130 return got_error_from_errno("view_open");
3132 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
3133 if (err)
3134 return err;
3135 s = &tree_view->state.tree;
3137 *new_view = tree_view;
3139 if (got_path_is_root_dir(path))
3140 return NULL;
3142 return tree_view_walk_path(s, entry->commit, path);
3145 static const struct got_error *
3146 block_signals_used_by_main_thread(void)
3148 sigset_t sigset;
3149 int errcode;
3151 if (sigemptyset(&sigset) == -1)
3152 return got_error_from_errno("sigemptyset");
3154 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
3155 if (sigaddset(&sigset, SIGWINCH) == -1)
3156 return got_error_from_errno("sigaddset");
3157 if (sigaddset(&sigset, SIGCONT) == -1)
3158 return got_error_from_errno("sigaddset");
3159 if (sigaddset(&sigset, SIGINT) == -1)
3160 return got_error_from_errno("sigaddset");
3161 if (sigaddset(&sigset, SIGTERM) == -1)
3162 return got_error_from_errno("sigaddset");
3164 /* ncurses handles SIGTSTP */
3165 if (sigaddset(&sigset, SIGTSTP) == -1)
3166 return got_error_from_errno("sigaddset");
3168 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
3169 if (errcode)
3170 return got_error_set_errno(errcode, "pthread_sigmask");
3172 return NULL;
3175 static void *
3176 log_thread(void *arg)
3178 const struct got_error *err = NULL;
3179 int errcode = 0;
3180 struct tog_log_thread_args *a = arg;
3181 int done = 0;
3184 * Sync startup with main thread such that we begin our
3185 * work once view_input() has released the mutex.
3187 errcode = pthread_mutex_lock(&tog_mutex);
3188 if (errcode) {
3189 err = got_error_set_errno(errcode, "pthread_mutex_lock");
3190 return (void *)err;
3193 err = block_signals_used_by_main_thread();
3194 if (err) {
3195 pthread_mutex_unlock(&tog_mutex);
3196 goto done;
3199 while (!done && !err && !tog_fatal_signal_received()) {
3200 errcode = pthread_mutex_unlock(&tog_mutex);
3201 if (errcode) {
3202 err = got_error_set_errno(errcode,
3203 "pthread_mutex_unlock");
3204 goto done;
3206 err = queue_commits(a);
3207 if (err) {
3208 if (err->code != GOT_ERR_ITER_COMPLETED)
3209 goto done;
3210 err = NULL;
3211 done = 1;
3212 } else if (a->commits_needed > 0 && !a->load_all) {
3213 if (*a->limiting) {
3214 if (a->limit_match)
3215 a->commits_needed--;
3216 } else
3217 a->commits_needed--;
3220 errcode = pthread_mutex_lock(&tog_mutex);
3221 if (errcode) {
3222 err = got_error_set_errno(errcode,
3223 "pthread_mutex_lock");
3224 goto done;
3225 } else if (*a->quit)
3226 done = 1;
3227 else if (*a->limiting && *a->first_displayed_entry == NULL) {
3228 *a->first_displayed_entry =
3229 TAILQ_FIRST(&a->limit_commits->head);
3230 *a->selected_entry = *a->first_displayed_entry;
3231 } else if (*a->first_displayed_entry == NULL) {
3232 *a->first_displayed_entry =
3233 TAILQ_FIRST(&a->real_commits->head);
3234 *a->selected_entry = *a->first_displayed_entry;
3237 errcode = pthread_cond_signal(&a->commit_loaded);
3238 if (errcode) {
3239 err = got_error_set_errno(errcode,
3240 "pthread_cond_signal");
3241 pthread_mutex_unlock(&tog_mutex);
3242 goto done;
3245 if (done)
3246 a->commits_needed = 0;
3247 else {
3248 if (a->commits_needed == 0 && !a->load_all) {
3249 errcode = pthread_cond_wait(&a->need_commits,
3250 &tog_mutex);
3251 if (errcode) {
3252 err = got_error_set_errno(errcode,
3253 "pthread_cond_wait");
3254 pthread_mutex_unlock(&tog_mutex);
3255 goto done;
3257 if (*a->quit)
3258 done = 1;
3262 a->log_complete = 1;
3263 errcode = pthread_mutex_unlock(&tog_mutex);
3264 if (errcode)
3265 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
3266 done:
3267 if (err) {
3268 tog_thread_error = 1;
3269 pthread_cond_signal(&a->commit_loaded);
3271 return (void *)err;
3274 static const struct got_error *
3275 stop_log_thread(struct tog_log_view_state *s)
3277 const struct got_error *err = NULL, *thread_err = NULL;
3278 int errcode;
3280 if (s->thread) {
3281 s->quit = 1;
3282 errcode = pthread_cond_signal(&s->thread_args.need_commits);
3283 if (errcode)
3284 return got_error_set_errno(errcode,
3285 "pthread_cond_signal");
3286 errcode = pthread_mutex_unlock(&tog_mutex);
3287 if (errcode)
3288 return got_error_set_errno(errcode,
3289 "pthread_mutex_unlock");
3290 errcode = pthread_join(s->thread, (void **)&thread_err);
3291 if (errcode)
3292 return got_error_set_errno(errcode, "pthread_join");
3293 errcode = pthread_mutex_lock(&tog_mutex);
3294 if (errcode)
3295 return got_error_set_errno(errcode,
3296 "pthread_mutex_lock");
3297 s->thread = NULL;
3300 if (s->thread_args.repo) {
3301 err = got_repo_close(s->thread_args.repo);
3302 s->thread_args.repo = NULL;
3305 if (s->thread_args.pack_fds) {
3306 const struct got_error *pack_err =
3307 got_repo_pack_fds_close(s->thread_args.pack_fds);
3308 if (err == NULL)
3309 err = pack_err;
3310 s->thread_args.pack_fds = NULL;
3313 if (s->thread_args.graph) {
3314 got_commit_graph_close(s->thread_args.graph);
3315 s->thread_args.graph = NULL;
3318 return err ? err : thread_err;
3321 static const struct got_error *
3322 close_log_view(struct tog_view *view)
3324 const struct got_error *err = NULL;
3325 struct tog_log_view_state *s = &view->state.log;
3326 int errcode;
3328 err = stop_log_thread(s);
3330 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
3331 if (errcode && err == NULL)
3332 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3334 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
3335 if (errcode && err == NULL)
3336 err = got_error_set_errno(errcode, "pthread_cond_destroy");
3338 free_commits(&s->limit_commits);
3339 free_commits(&s->real_commits);
3340 free(s->in_repo_path);
3341 s->in_repo_path = NULL;
3342 free(s->start_id);
3343 s->start_id = NULL;
3344 free(s->head_ref_name);
3345 s->head_ref_name = NULL;
3346 return err;
3350 * We use two queues to implement the limit feature: first consists of
3351 * commits matching the current limit_regex; second is the real queue
3352 * of all known commits (real_commits). When the user starts limiting,
3353 * we swap queues such that all movement and displaying functionality
3354 * works with very slight change.
3356 static const struct got_error *
3357 limit_log_view(struct tog_view *view)
3359 struct tog_log_view_state *s = &view->state.log;
3360 struct commit_queue_entry *entry;
3361 struct tog_view *v = view;
3362 const struct got_error *err = NULL;
3363 char pattern[1024];
3364 int ret;
3366 if (view_is_hsplit_top(view))
3367 v = view->child;
3368 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
3369 v = view->parent;
3371 /* Get the pattern */
3372 wmove(v->window, v->nlines - 1, 0);
3373 wclrtoeol(v->window);
3374 mvwaddstr(v->window, v->nlines - 1, 0, "&/");
3375 nodelay(v->window, FALSE);
3376 nocbreak();
3377 echo();
3378 ret = wgetnstr(v->window, pattern, sizeof(pattern));
3379 cbreak();
3380 noecho();
3381 nodelay(v->window, TRUE);
3382 if (ret == ERR)
3383 return NULL;
3385 if (*pattern == '\0') {
3387 * Safety measure for the situation where the user
3388 * resets limit without previously limiting anything.
3390 if (!s->limit_view)
3391 return NULL;
3394 * User could have pressed Ctrl+L, which refreshed the
3395 * commit queues, it means we can't save previously
3396 * (before limit took place) displayed entries,
3397 * because they would point to already free'ed memory,
3398 * so we are forced to always select first entry of
3399 * the queue.
3401 s->commits = &s->real_commits;
3402 s->first_displayed_entry = TAILQ_FIRST(&s->real_commits.head);
3403 s->selected_entry = s->first_displayed_entry;
3404 s->selected = 0;
3405 s->limit_view = 0;
3407 return NULL;
3410 if (regcomp(&s->limit_regex, pattern, REG_EXTENDED | REG_NEWLINE))
3411 return NULL;
3413 s->limit_view = 1;
3415 /* Clear the screen while loading limit view */
3416 s->first_displayed_entry = NULL;
3417 s->last_displayed_entry = NULL;
3418 s->selected_entry = NULL;
3419 s->commits = &s->limit_commits;
3421 /* Prepare limit queue for new search */
3422 free_commits(&s->limit_commits);
3423 s->limit_commits.ncommits = 0;
3425 /* First process commits, which are in queue already */
3426 TAILQ_FOREACH(entry, &s->real_commits.head, entry) {
3427 int have_match = 0;
3429 err = match_commit(&have_match, entry->id,
3430 entry->commit, &s->limit_regex);
3431 if (err)
3432 return err;
3434 if (have_match) {
3435 struct commit_queue_entry *matched;
3437 matched = alloc_commit_queue_entry(entry->commit,
3438 entry->id);
3439 if (matched == NULL) {
3440 err = got_error_from_errno(
3441 "alloc_commit_queue_entry");
3442 break;
3444 matched->commit = entry->commit;
3445 got_object_commit_retain(entry->commit);
3447 matched->idx = s->limit_commits.ncommits;
3448 TAILQ_INSERT_TAIL(&s->limit_commits.head,
3449 matched, entry);
3450 s->limit_commits.ncommits++;
3454 /* Second process all the commits, until we fill the screen */
3455 if (s->limit_commits.ncommits < view->nlines - 1 &&
3456 !s->thread_args.log_complete) {
3457 s->thread_args.commits_needed +=
3458 view->nlines - s->limit_commits.ncommits - 1;
3459 err = trigger_log_thread(view, 1);
3460 if (err)
3461 return err;
3464 s->first_displayed_entry = TAILQ_FIRST(&s->commits->head);
3465 s->selected_entry = TAILQ_FIRST(&s->commits->head);
3466 s->selected = 0;
3468 return NULL;
3471 static const struct got_error *
3472 search_start_log_view(struct tog_view *view)
3474 struct tog_log_view_state *s = &view->state.log;
3476 s->matched_entry = NULL;
3477 s->search_entry = NULL;
3478 return NULL;
3481 static const struct got_error *
3482 search_next_log_view(struct tog_view *view)
3484 const struct got_error *err = NULL;
3485 struct tog_log_view_state *s = &view->state.log;
3486 struct commit_queue_entry *entry;
3488 /* Display progress update in log view. */
3489 show_log_view(view);
3490 update_panels();
3491 doupdate();
3493 if (s->search_entry) {
3494 int errcode, ch;
3495 errcode = pthread_mutex_unlock(&tog_mutex);
3496 if (errcode)
3497 return got_error_set_errno(errcode,
3498 "pthread_mutex_unlock");
3499 ch = wgetch(view->window);
3500 errcode = pthread_mutex_lock(&tog_mutex);
3501 if (errcode)
3502 return got_error_set_errno(errcode,
3503 "pthread_mutex_lock");
3504 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
3505 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3506 return NULL;
3508 if (view->searching == TOG_SEARCH_FORWARD)
3509 entry = TAILQ_NEXT(s->search_entry, entry);
3510 else
3511 entry = TAILQ_PREV(s->search_entry,
3512 commit_queue_head, entry);
3513 } else if (s->matched_entry) {
3515 * If the user has moved the cursor after we hit a match,
3516 * the position from where we should continue searching
3517 * might have changed.
3519 if (view->searching == TOG_SEARCH_FORWARD)
3520 entry = TAILQ_NEXT(s->selected_entry, entry);
3521 else
3522 entry = TAILQ_PREV(s->selected_entry, commit_queue_head,
3523 entry);
3524 } else {
3525 entry = s->selected_entry;
3528 while (1) {
3529 int have_match = 0;
3531 if (entry == NULL) {
3532 if (s->thread_args.log_complete ||
3533 view->searching == TOG_SEARCH_BACKWARD) {
3534 view->search_next_done =
3535 (s->matched_entry == NULL ?
3536 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
3537 s->search_entry = NULL;
3538 return NULL;
3541 * Poke the log thread for more commits and return,
3542 * allowing the main loop to make progress. Search
3543 * will resume at s->search_entry once we come back.
3545 s->thread_args.commits_needed++;
3546 return trigger_log_thread(view, 0);
3549 err = match_commit(&have_match, entry->id, entry->commit,
3550 &view->regex);
3551 if (err)
3552 break;
3553 if (have_match) {
3554 view->search_next_done = TOG_SEARCH_HAVE_MORE;
3555 s->matched_entry = entry;
3556 break;
3559 s->search_entry = entry;
3560 if (view->searching == TOG_SEARCH_FORWARD)
3561 entry = TAILQ_NEXT(entry, entry);
3562 else
3563 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3566 if (s->matched_entry) {
3567 int cur = s->selected_entry->idx;
3568 while (cur < s->matched_entry->idx) {
3569 err = input_log_view(NULL, view, KEY_DOWN);
3570 if (err)
3571 return err;
3572 cur++;
3574 while (cur > s->matched_entry->idx) {
3575 err = input_log_view(NULL, view, KEY_UP);
3576 if (err)
3577 return err;
3578 cur--;
3582 s->search_entry = NULL;
3584 return NULL;
3587 static const struct got_error *
3588 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3589 struct got_repository *repo, const char *head_ref_name,
3590 const char *in_repo_path, int log_branches)
3592 const struct got_error *err = NULL;
3593 struct tog_log_view_state *s = &view->state.log;
3594 struct got_repository *thread_repo = NULL;
3595 struct got_commit_graph *thread_graph = NULL;
3596 int errcode;
3598 if (in_repo_path != s->in_repo_path) {
3599 free(s->in_repo_path);
3600 s->in_repo_path = strdup(in_repo_path);
3601 if (s->in_repo_path == NULL) {
3602 err = got_error_from_errno("strdup");
3603 goto done;
3607 /* The commit queue only contains commits being displayed. */
3608 TAILQ_INIT(&s->real_commits.head);
3609 s->real_commits.ncommits = 0;
3610 s->commits = &s->real_commits;
3612 TAILQ_INIT(&s->limit_commits.head);
3613 s->limit_view = 0;
3614 s->limit_commits.ncommits = 0;
3616 s->repo = repo;
3617 if (head_ref_name) {
3618 s->head_ref_name = strdup(head_ref_name);
3619 if (s->head_ref_name == NULL) {
3620 err = got_error_from_errno("strdup");
3621 goto done;
3624 s->start_id = got_object_id_dup(start_id);
3625 if (s->start_id == NULL) {
3626 err = got_error_from_errno("got_object_id_dup");
3627 goto done;
3629 s->log_branches = log_branches;
3630 s->use_committer = 1;
3632 STAILQ_INIT(&s->colors);
3633 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3634 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3635 get_color_value("TOG_COLOR_COMMIT"));
3636 if (err)
3637 goto done;
3638 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3639 get_color_value("TOG_COLOR_AUTHOR"));
3640 if (err) {
3641 free_colors(&s->colors);
3642 goto done;
3644 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3645 get_color_value("TOG_COLOR_DATE"));
3646 if (err) {
3647 free_colors(&s->colors);
3648 goto done;
3652 view->show = show_log_view;
3653 view->input = input_log_view;
3654 view->resize = resize_log_view;
3655 view->close = close_log_view;
3656 view->search_start = search_start_log_view;
3657 view->search_next = search_next_log_view;
3659 if (s->thread_args.pack_fds == NULL) {
3660 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3661 if (err)
3662 goto done;
3664 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3665 s->thread_args.pack_fds);
3666 if (err)
3667 goto done;
3668 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3669 !s->log_branches);
3670 if (err)
3671 goto done;
3672 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3673 s->repo, NULL, NULL);
3674 if (err)
3675 goto done;
3677 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3678 if (errcode) {
3679 err = got_error_set_errno(errcode, "pthread_cond_init");
3680 goto done;
3682 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3683 if (errcode) {
3684 err = got_error_set_errno(errcode, "pthread_cond_init");
3685 goto done;
3688 s->thread_args.commits_needed = view->nlines;
3689 s->thread_args.graph = thread_graph;
3690 s->thread_args.real_commits = &s->real_commits;
3691 s->thread_args.limit_commits = &s->limit_commits;
3692 s->thread_args.in_repo_path = s->in_repo_path;
3693 s->thread_args.start_id = s->start_id;
3694 s->thread_args.repo = thread_repo;
3695 s->thread_args.log_complete = 0;
3696 s->thread_args.quit = &s->quit;
3697 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3698 s->thread_args.selected_entry = &s->selected_entry;
3699 s->thread_args.searching = &view->searching;
3700 s->thread_args.search_next_done = &view->search_next_done;
3701 s->thread_args.regex = &view->regex;
3702 s->thread_args.limiting = &s->limit_view;
3703 s->thread_args.limit_regex = &s->limit_regex;
3704 s->thread_args.limit_commits = &s->limit_commits;
3705 done:
3706 if (err) {
3707 if (view->close == NULL)
3708 close_log_view(view);
3709 view_close(view);
3711 return err;
3714 static const struct got_error *
3715 show_log_view(struct tog_view *view)
3717 const struct got_error *err;
3718 struct tog_log_view_state *s = &view->state.log;
3720 if (s->thread == NULL) {
3721 int errcode = pthread_create(&s->thread, NULL, log_thread,
3722 &s->thread_args);
3723 if (errcode)
3724 return got_error_set_errno(errcode, "pthread_create");
3725 if (s->thread_args.commits_needed > 0) {
3726 err = trigger_log_thread(view, 1);
3727 if (err)
3728 return err;
3732 return draw_commits(view);
3735 static void
3736 log_move_cursor_up(struct tog_view *view, int page, int home)
3738 struct tog_log_view_state *s = &view->state.log;
3740 if (s->first_displayed_entry == NULL)
3741 return;
3742 if (s->selected_entry->idx == 0)
3743 view->count = 0;
3745 if ((page && TAILQ_FIRST(&s->commits->head) == s->first_displayed_entry)
3746 || home)
3747 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3749 if (!page && !home && s->selected > 0)
3750 --s->selected;
3751 else
3752 log_scroll_up(s, home ? s->commits->ncommits : MAX(page, 1));
3754 select_commit(s);
3755 return;
3758 static const struct got_error *
3759 log_move_cursor_down(struct tog_view *view, int page)
3761 struct tog_log_view_state *s = &view->state.log;
3762 const struct got_error *err = NULL;
3763 int eos = view->nlines - 2;
3765 if (s->first_displayed_entry == NULL)
3766 return NULL;
3768 if (s->thread_args.log_complete &&
3769 s->selected_entry->idx >= s->commits->ncommits - 1)
3770 return NULL;
3772 if (view_is_hsplit_top(view))
3773 --eos; /* border consumes the last line */
3775 if (!page) {
3776 if (s->selected < MIN(eos, s->commits->ncommits - 1))
3777 ++s->selected;
3778 else
3779 err = log_scroll_down(view, 1);
3780 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3781 struct commit_queue_entry *entry;
3782 int n;
3784 s->selected = 0;
3785 entry = TAILQ_LAST(&s->commits->head, commit_queue_head);
3786 s->last_displayed_entry = entry;
3787 for (n = 0; n <= eos; n++) {
3788 if (entry == NULL)
3789 break;
3790 s->first_displayed_entry = entry;
3791 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3793 if (n > 0)
3794 s->selected = n - 1;
3795 } else {
3796 if (s->last_displayed_entry->idx == s->commits->ncommits - 1 &&
3797 s->thread_args.log_complete)
3798 s->selected += MIN(page,
3799 s->commits->ncommits - s->selected_entry->idx - 1);
3800 else
3801 err = log_scroll_down(view, page);
3803 if (err)
3804 return err;
3807 * We might necessarily overshoot in horizontal
3808 * splits; if so, select the last displayed commit.
3810 if (s->first_displayed_entry && s->last_displayed_entry) {
3811 s->selected = MIN(s->selected,
3812 s->last_displayed_entry->idx -
3813 s->first_displayed_entry->idx);
3816 select_commit(s);
3818 if (s->thread_args.log_complete &&
3819 s->selected_entry->idx == s->commits->ncommits - 1)
3820 view->count = 0;
3822 return NULL;
3825 static void
3826 view_get_split(struct tog_view *view, int *y, int *x)
3828 *x = 0;
3829 *y = 0;
3831 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3832 if (view->child && view->child->resized_y)
3833 *y = view->child->resized_y;
3834 else if (view->resized_y)
3835 *y = view->resized_y;
3836 else
3837 *y = view_split_begin_y(view->lines);
3838 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3839 if (view->child && view->child->resized_x)
3840 *x = view->child->resized_x;
3841 else if (view->resized_x)
3842 *x = view->resized_x;
3843 else
3844 *x = view_split_begin_x(view->begin_x);
3848 /* Split view horizontally at y and offset view->state->selected line. */
3849 static const struct got_error *
3850 view_init_hsplit(struct tog_view *view, int y)
3852 const struct got_error *err = NULL;
3854 view->nlines = y;
3855 view->ncols = COLS;
3856 err = view_resize(view);
3857 if (err)
3858 return err;
3860 err = offset_selection_down(view);
3862 return err;
3865 static const struct got_error *
3866 log_goto_line(struct tog_view *view, int nlines)
3868 const struct got_error *err = NULL;
3869 struct tog_log_view_state *s = &view->state.log;
3870 int g, idx = s->selected_entry->idx;
3872 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3873 return NULL;
3875 g = view->gline;
3876 view->gline = 0;
3878 if (g >= s->first_displayed_entry->idx + 1 &&
3879 g <= s->last_displayed_entry->idx + 1 &&
3880 g - s->first_displayed_entry->idx - 1 < nlines) {
3881 s->selected = g - s->first_displayed_entry->idx - 1;
3882 select_commit(s);
3883 return NULL;
3886 if (idx + 1 < g) {
3887 err = log_move_cursor_down(view, g - idx - 1);
3888 if (!err && g > s->selected_entry->idx + 1)
3889 err = log_move_cursor_down(view,
3890 g - s->first_displayed_entry->idx - 1);
3891 if (err)
3892 return err;
3893 } else if (idx + 1 > g)
3894 log_move_cursor_up(view, idx - g + 1, 0);
3896 if (g < nlines && s->first_displayed_entry->idx == 0)
3897 s->selected = g - 1;
3899 select_commit(s);
3900 return NULL;
3904 static void
3905 horizontal_scroll_input(struct tog_view *view, int ch)
3908 switch (ch) {
3909 case KEY_LEFT:
3910 case 'h':
3911 view->x -= MIN(view->x, 2);
3912 if (view->x <= 0)
3913 view->count = 0;
3914 break;
3915 case KEY_RIGHT:
3916 case 'l':
3917 if (view->x + view->ncols / 2 < view->maxx)
3918 view->x += 2;
3919 else
3920 view->count = 0;
3921 break;
3922 case '0':
3923 view->x = 0;
3924 break;
3925 case '$':
3926 view->x = MAX(view->maxx - view->ncols / 2, 0);
3927 view->count = 0;
3928 break;
3929 default:
3930 break;
3934 static const struct got_error *
3935 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3937 const struct got_error *err = NULL;
3938 struct tog_log_view_state *s = &view->state.log;
3939 int eos, nscroll;
3941 if (s->thread_args.load_all) {
3942 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3943 s->thread_args.load_all = 0;
3944 else if (s->thread_args.log_complete) {
3945 err = log_move_cursor_down(view, s->commits->ncommits);
3946 s->thread_args.load_all = 0;
3948 if (err)
3949 return err;
3952 eos = nscroll = view->nlines - 1;
3953 if (view_is_hsplit_top(view))
3954 --eos; /* border */
3956 if (view->gline)
3957 return log_goto_line(view, eos);
3959 switch (ch) {
3960 case '&':
3961 err = limit_log_view(view);
3962 break;
3963 case 'q':
3964 s->quit = 1;
3965 break;
3966 case '0':
3967 case '$':
3968 case KEY_RIGHT:
3969 case 'l':
3970 case KEY_LEFT:
3971 case 'h':
3972 horizontal_scroll_input(view, ch);
3973 break;
3974 case 'k':
3975 case KEY_UP:
3976 case '<':
3977 case ',':
3978 case CTRL('p'):
3979 log_move_cursor_up(view, 0, 0);
3980 break;
3981 case 'g':
3982 case '=':
3983 case KEY_HOME:
3984 log_move_cursor_up(view, 0, 1);
3985 view->count = 0;
3986 break;
3987 case CTRL('u'):
3988 case 'u':
3989 nscroll /= 2;
3990 /* FALL THROUGH */
3991 case KEY_PPAGE:
3992 case CTRL('b'):
3993 case 'b':
3994 log_move_cursor_up(view, nscroll, 0);
3995 break;
3996 case 'j':
3997 case KEY_DOWN:
3998 case '>':
3999 case '.':
4000 case CTRL('n'):
4001 err = log_move_cursor_down(view, 0);
4002 break;
4003 case '@':
4004 s->use_committer = !s->use_committer;
4005 view->action = s->use_committer ?
4006 "show committer" : "show commit author";
4007 break;
4008 case 'G':
4009 case '*':
4010 case KEY_END: {
4011 /* We don't know yet how many commits, so we're forced to
4012 * traverse them all. */
4013 view->count = 0;
4014 s->thread_args.load_all = 1;
4015 if (!s->thread_args.log_complete)
4016 return trigger_log_thread(view, 0);
4017 err = log_move_cursor_down(view, s->commits->ncommits);
4018 s->thread_args.load_all = 0;
4019 break;
4021 case CTRL('d'):
4022 case 'd':
4023 nscroll /= 2;
4024 /* FALL THROUGH */
4025 case KEY_NPAGE:
4026 case CTRL('f'):
4027 case 'f':
4028 case ' ':
4029 err = log_move_cursor_down(view, nscroll);
4030 break;
4031 case KEY_RESIZE:
4032 if (s->selected > view->nlines - 2)
4033 s->selected = view->nlines - 2;
4034 if (s->selected > s->commits->ncommits - 1)
4035 s->selected = s->commits->ncommits - 1;
4036 select_commit(s);
4037 if (s->commits->ncommits < view->nlines - 1 &&
4038 !s->thread_args.log_complete) {
4039 s->thread_args.commits_needed += (view->nlines - 1) -
4040 s->commits->ncommits;
4041 err = trigger_log_thread(view, 1);
4043 break;
4044 case KEY_ENTER:
4045 case '\r':
4046 view->count = 0;
4047 if (s->selected_entry == NULL)
4048 break;
4049 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
4050 break;
4051 case 'T':
4052 view->count = 0;
4053 if (s->selected_entry == NULL)
4054 break;
4055 err = view_request_new(new_view, view, TOG_VIEW_TREE);
4056 break;
4057 case KEY_BACKSPACE:
4058 case CTRL('l'):
4059 case 'B':
4060 view->count = 0;
4061 if (ch == KEY_BACKSPACE &&
4062 got_path_is_root_dir(s->in_repo_path))
4063 break;
4064 err = stop_log_thread(s);
4065 if (err)
4066 return err;
4067 if (ch == KEY_BACKSPACE) {
4068 char *parent_path;
4069 err = got_path_dirname(&parent_path, s->in_repo_path);
4070 if (err)
4071 return err;
4072 free(s->in_repo_path);
4073 s->in_repo_path = parent_path;
4074 s->thread_args.in_repo_path = s->in_repo_path;
4075 } else if (ch == CTRL('l')) {
4076 struct got_object_id *start_id;
4077 err = got_repo_match_object_id(&start_id, NULL,
4078 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
4079 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
4080 if (err) {
4081 if (s->head_ref_name == NULL ||
4082 err->code != GOT_ERR_NOT_REF)
4083 return err;
4084 /* Try to cope with deleted references. */
4085 free(s->head_ref_name);
4086 s->head_ref_name = NULL;
4087 err = got_repo_match_object_id(&start_id,
4088 NULL, GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT,
4089 &tog_refs, s->repo);
4090 if (err)
4091 return err;
4093 free(s->start_id);
4094 s->start_id = start_id;
4095 s->thread_args.start_id = s->start_id;
4096 } else /* 'B' */
4097 s->log_branches = !s->log_branches;
4099 if (s->thread_args.pack_fds == NULL) {
4100 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
4101 if (err)
4102 return err;
4104 err = got_repo_open(&s->thread_args.repo,
4105 got_repo_get_path(s->repo), NULL,
4106 s->thread_args.pack_fds);
4107 if (err)
4108 return err;
4109 tog_free_refs();
4110 err = tog_load_refs(s->repo, 0);
4111 if (err)
4112 return err;
4113 err = got_commit_graph_open(&s->thread_args.graph,
4114 s->in_repo_path, !s->log_branches);
4115 if (err)
4116 return err;
4117 err = got_commit_graph_iter_start(s->thread_args.graph,
4118 s->start_id, s->repo, NULL, NULL);
4119 if (err)
4120 return err;
4121 free_commits(&s->real_commits);
4122 free_commits(&s->limit_commits);
4123 s->first_displayed_entry = NULL;
4124 s->last_displayed_entry = NULL;
4125 s->selected_entry = NULL;
4126 s->selected = 0;
4127 s->thread_args.log_complete = 0;
4128 s->quit = 0;
4129 s->thread_args.commits_needed = view->lines;
4130 s->matched_entry = NULL;
4131 s->search_entry = NULL;
4132 view->offset = 0;
4133 break;
4134 case 'R':
4135 view->count = 0;
4136 err = view_request_new(new_view, view, TOG_VIEW_REF);
4137 break;
4138 default:
4139 view->count = 0;
4140 break;
4143 return err;
4146 static const struct got_error *
4147 apply_unveil(const char *repo_path, const char *worktree_path)
4149 const struct got_error *error;
4151 #ifdef PROFILE
4152 if (unveil("gmon.out", "rwc") != 0)
4153 return got_error_from_errno2("unveil", "gmon.out");
4154 #endif
4155 if (repo_path && unveil(repo_path, "r") != 0)
4156 return got_error_from_errno2("unveil", repo_path);
4158 if (worktree_path && unveil(worktree_path, "rwc") != 0)
4159 return got_error_from_errno2("unveil", worktree_path);
4161 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
4162 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
4164 error = got_privsep_unveil_exec_helpers();
4165 if (error != NULL)
4166 return error;
4168 if (unveil(NULL, NULL) != 0)
4169 return got_error_from_errno("unveil");
4171 return NULL;
4174 static const struct got_error *
4175 init_mock_term(const char *test_script_path)
4177 const struct got_error *err = NULL;
4179 if (test_script_path == NULL || *test_script_path == '\0')
4180 return got_error_msg(GOT_ERR_IO, "TOG_TEST_SCRIPT not defined");
4182 tog_io.f = fopen(test_script_path, "re");
4183 if (tog_io.f == NULL) {
4184 err = got_error_from_errno_fmt("fopen: %s",
4185 test_script_path);
4186 goto done;
4189 /* test mode, we don't want any output */
4190 tog_io.cout = fopen("/dev/null", "w+");
4191 if (tog_io.cout == NULL) {
4192 err = got_error_from_errno("fopen: /dev/null");
4193 goto done;
4196 tog_io.cin = fopen("/dev/tty", "r+");
4197 if (tog_io.cin == NULL) {
4198 err = got_error_from_errno("fopen: /dev/tty");
4199 goto done;
4202 if (fseeko(tog_io.f, 0L, SEEK_SET) == -1) {
4203 err = got_error_from_errno("fseeko");
4204 goto done;
4207 /* use local TERM so we test in different environments */
4208 if (newterm(NULL, tog_io.cout, tog_io.cin) == NULL)
4209 err = got_error_msg(GOT_ERR_IO,
4210 "newterm: failed to initialise curses");
4212 using_mock_io = 1;
4213 done:
4214 if (err)
4215 tog_io_close();
4216 return err;
4219 static void
4220 init_curses(void)
4223 * Override default signal handlers before starting ncurses.
4224 * This should prevent ncurses from installing its own
4225 * broken cleanup() signal handler.
4227 signal(SIGWINCH, tog_sigwinch);
4228 signal(SIGPIPE, tog_sigpipe);
4229 signal(SIGCONT, tog_sigcont);
4230 signal(SIGINT, tog_sigint);
4231 signal(SIGTERM, tog_sigterm);
4233 if (using_mock_io) /* In test mode we use a fake terminal */
4234 return;
4236 initscr();
4238 cbreak();
4239 halfdelay(1); /* Fast refresh while initial view is loading. */
4240 noecho();
4241 nonl();
4242 intrflush(stdscr, FALSE);
4243 keypad(stdscr, TRUE);
4244 curs_set(0);
4245 if (getenv("TOG_COLORS") != NULL) {
4246 start_color();
4247 use_default_colors();
4250 return;
4253 static const struct got_error *
4254 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
4255 struct got_repository *repo, struct got_worktree *worktree)
4257 const struct got_error *err = NULL;
4259 if (argc == 0) {
4260 *in_repo_path = strdup("/");
4261 if (*in_repo_path == NULL)
4262 return got_error_from_errno("strdup");
4263 return NULL;
4266 if (worktree) {
4267 const char *prefix = got_worktree_get_path_prefix(worktree);
4268 char *p;
4270 err = got_worktree_resolve_path(&p, worktree, argv[0]);
4271 if (err)
4272 return err;
4273 if (asprintf(in_repo_path, "%s%s%s", prefix,
4274 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
4275 p) == -1) {
4276 err = got_error_from_errno("asprintf");
4277 *in_repo_path = NULL;
4279 free(p);
4280 } else
4281 err = got_repo_map_path(in_repo_path, repo, argv[0]);
4283 return err;
4286 static const struct got_error *
4287 cmd_log(int argc, char *argv[])
4289 const struct got_error *error;
4290 struct got_repository *repo = NULL;
4291 struct got_worktree *worktree = NULL;
4292 struct got_object_id *start_id = NULL;
4293 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
4294 char *start_commit = NULL, *label = NULL;
4295 struct got_reference *ref = NULL;
4296 const char *head_ref_name = NULL;
4297 int ch, log_branches = 0;
4298 struct tog_view *view;
4299 int *pack_fds = NULL;
4301 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
4302 switch (ch) {
4303 case 'b':
4304 log_branches = 1;
4305 break;
4306 case 'c':
4307 start_commit = optarg;
4308 break;
4309 case 'r':
4310 repo_path = realpath(optarg, NULL);
4311 if (repo_path == NULL)
4312 return got_error_from_errno2("realpath",
4313 optarg);
4314 break;
4315 default:
4316 usage_log();
4317 /* NOTREACHED */
4321 argc -= optind;
4322 argv += optind;
4324 if (argc > 1)
4325 usage_log();
4327 error = got_repo_pack_fds_open(&pack_fds);
4328 if (error != NULL)
4329 goto done;
4331 if (repo_path == NULL) {
4332 cwd = getcwd(NULL, 0);
4333 if (cwd == NULL)
4334 return got_error_from_errno("getcwd");
4335 error = got_worktree_open(&worktree, cwd);
4336 if (error && error->code != GOT_ERR_NOT_WORKTREE)
4337 goto done;
4338 if (worktree)
4339 repo_path =
4340 strdup(got_worktree_get_repo_path(worktree));
4341 else
4342 repo_path = strdup(cwd);
4343 if (repo_path == NULL) {
4344 error = got_error_from_errno("strdup");
4345 goto done;
4349 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
4350 if (error != NULL)
4351 goto done;
4353 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
4354 repo, worktree);
4355 if (error)
4356 goto done;
4358 init_curses();
4360 error = apply_unveil(got_repo_get_path(repo),
4361 worktree ? got_worktree_get_root_path(worktree) : NULL);
4362 if (error)
4363 goto done;
4365 /* already loaded by tog_log_with_path()? */
4366 if (TAILQ_EMPTY(&tog_refs)) {
4367 error = tog_load_refs(repo, 0);
4368 if (error)
4369 goto done;
4372 if (start_commit == NULL) {
4373 error = got_repo_match_object_id(&start_id, &label,
4374 worktree ? got_worktree_get_head_ref_name(worktree) :
4375 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4376 if (error)
4377 goto done;
4378 head_ref_name = label;
4379 } else {
4380 error = got_ref_open(&ref, repo, start_commit, 0);
4381 if (error == NULL)
4382 head_ref_name = got_ref_get_name(ref);
4383 else if (error->code != GOT_ERR_NOT_REF)
4384 goto done;
4385 error = got_repo_match_object_id(&start_id, NULL,
4386 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
4387 if (error)
4388 goto done;
4391 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
4392 if (view == NULL) {
4393 error = got_error_from_errno("view_open");
4394 goto done;
4396 error = open_log_view(view, start_id, repo, head_ref_name,
4397 in_repo_path, log_branches);
4398 if (error)
4399 goto done;
4400 if (worktree) {
4401 /* Release work tree lock. */
4402 got_worktree_close(worktree);
4403 worktree = NULL;
4405 error = view_loop(view);
4406 done:
4407 free(in_repo_path);
4408 free(repo_path);
4409 free(cwd);
4410 free(start_id);
4411 free(label);
4412 if (ref)
4413 got_ref_close(ref);
4414 if (repo) {
4415 const struct got_error *close_err = got_repo_close(repo);
4416 if (error == NULL)
4417 error = close_err;
4419 if (worktree)
4420 got_worktree_close(worktree);
4421 if (pack_fds) {
4422 const struct got_error *pack_err =
4423 got_repo_pack_fds_close(pack_fds);
4424 if (error == NULL)
4425 error = pack_err;
4427 tog_free_refs();
4428 return error;
4431 __dead static void
4432 usage_diff(void)
4434 endwin();
4435 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
4436 "object1 object2\n", getprogname());
4437 exit(1);
4440 static int
4441 match_line(const char *line, regex_t *regex, size_t nmatch,
4442 regmatch_t *regmatch)
4444 return regexec(regex, line, nmatch, regmatch, 0) == 0;
4447 static struct tog_color *
4448 match_color(struct tog_colors *colors, const char *line)
4450 struct tog_color *tc = NULL;
4452 STAILQ_FOREACH(tc, colors, entry) {
4453 if (match_line(line, &tc->regex, 0, NULL))
4454 return tc;
4457 return NULL;
4460 static const struct got_error *
4461 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
4462 WINDOW *window, int skipcol, regmatch_t *regmatch)
4464 const struct got_error *err = NULL;
4465 char *exstr = NULL;
4466 wchar_t *wline = NULL;
4467 int rme, rms, n, width, scrollx;
4468 int width0 = 0, width1 = 0, width2 = 0;
4469 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
4471 *wtotal = 0;
4473 rms = regmatch->rm_so;
4474 rme = regmatch->rm_eo;
4476 err = expand_tab(&exstr, line);
4477 if (err)
4478 return err;
4480 /* Split the line into 3 segments, according to match offsets. */
4481 seg0 = strndup(exstr, rms);
4482 if (seg0 == NULL) {
4483 err = got_error_from_errno("strndup");
4484 goto done;
4486 seg1 = strndup(exstr + rms, rme - rms);
4487 if (seg1 == NULL) {
4488 err = got_error_from_errno("strndup");
4489 goto done;
4491 seg2 = strdup(exstr + rme);
4492 if (seg2 == NULL) {
4493 err = got_error_from_errno("strndup");
4494 goto done;
4497 /* draw up to matched token if we haven't scrolled past it */
4498 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
4499 col_tab_align, 1);
4500 if (err)
4501 goto done;
4502 n = MAX(width0 - skipcol, 0);
4503 if (n) {
4504 free(wline);
4505 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
4506 wlimit, col_tab_align, 1);
4507 if (err)
4508 goto done;
4509 waddwstr(window, &wline[scrollx]);
4510 wlimit -= width;
4511 *wtotal += width;
4514 if (wlimit > 0) {
4515 int i = 0, w = 0;
4516 size_t wlen;
4518 free(wline);
4519 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
4520 col_tab_align, 1);
4521 if (err)
4522 goto done;
4523 wlen = wcslen(wline);
4524 while (i < wlen) {
4525 width = wcwidth(wline[i]);
4526 if (width == -1) {
4527 /* should not happen, tabs are expanded */
4528 err = got_error(GOT_ERR_RANGE);
4529 goto done;
4531 if (width0 + w + width > skipcol)
4532 break;
4533 w += width;
4534 i++;
4536 /* draw (visible part of) matched token (if scrolled into it) */
4537 if (width1 - w > 0) {
4538 wattron(window, A_STANDOUT);
4539 waddwstr(window, &wline[i]);
4540 wattroff(window, A_STANDOUT);
4541 wlimit -= (width1 - w);
4542 *wtotal += (width1 - w);
4546 if (wlimit > 0) { /* draw rest of line */
4547 free(wline);
4548 if (skipcol > width0 + width1) {
4549 err = format_line(&wline, &width2, &scrollx, seg2,
4550 skipcol - (width0 + width1), wlimit,
4551 col_tab_align, 1);
4552 if (err)
4553 goto done;
4554 waddwstr(window, &wline[scrollx]);
4555 } else {
4556 err = format_line(&wline, &width2, NULL, seg2, 0,
4557 wlimit, col_tab_align, 1);
4558 if (err)
4559 goto done;
4560 waddwstr(window, wline);
4562 *wtotal += width2;
4564 done:
4565 free(wline);
4566 free(exstr);
4567 free(seg0);
4568 free(seg1);
4569 free(seg2);
4570 return err;
4573 static int
4574 gotoline(struct tog_view *view, int *lineno, int *nprinted)
4576 FILE *f = NULL;
4577 int *eof, *first, *selected;
4579 if (view->type == TOG_VIEW_DIFF) {
4580 struct tog_diff_view_state *s = &view->state.diff;
4582 first = &s->first_displayed_line;
4583 selected = first;
4584 eof = &s->eof;
4585 f = s->f;
4586 } else if (view->type == TOG_VIEW_HELP) {
4587 struct tog_help_view_state *s = &view->state.help;
4589 first = &s->first_displayed_line;
4590 selected = first;
4591 eof = &s->eof;
4592 f = s->f;
4593 } else if (view->type == TOG_VIEW_BLAME) {
4594 struct tog_blame_view_state *s = &view->state.blame;
4596 first = &s->first_displayed_line;
4597 selected = &s->selected_line;
4598 eof = &s->eof;
4599 f = s->blame.f;
4600 } else
4601 return 0;
4603 /* Center gline in the middle of the page like vi(1). */
4604 if (*lineno < view->gline - (view->nlines - 3) / 2)
4605 return 0;
4606 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
4607 rewind(f);
4608 *eof = 0;
4609 *first = 1;
4610 *lineno = 0;
4611 *nprinted = 0;
4612 return 0;
4615 *selected = view->gline <= (view->nlines - 3) / 2 ?
4616 view->gline : (view->nlines - 3) / 2 + 1;
4617 view->gline = 0;
4619 return 1;
4622 static const struct got_error *
4623 draw_file(struct tog_view *view, const char *header)
4625 struct tog_diff_view_state *s = &view->state.diff;
4626 regmatch_t *regmatch = &view->regmatch;
4627 const struct got_error *err;
4628 int nprinted = 0;
4629 char *line;
4630 size_t linesize = 0;
4631 ssize_t linelen;
4632 wchar_t *wline;
4633 int width;
4634 int max_lines = view->nlines;
4635 int nlines = s->nlines;
4636 off_t line_offset;
4638 s->lineno = s->first_displayed_line - 1;
4639 line_offset = s->lines[s->first_displayed_line - 1].offset;
4640 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
4641 return got_error_from_errno("fseek");
4643 werase(view->window);
4645 if (view->gline > s->nlines - 1)
4646 view->gline = s->nlines - 1;
4648 if (header) {
4649 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
4650 1 : view->gline - (view->nlines - 3) / 2 :
4651 s->lineno + s->selected_line;
4653 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
4654 return got_error_from_errno("asprintf");
4655 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
4656 0, 0);
4657 free(line);
4658 if (err)
4659 return err;
4661 if (view_needs_focus_indication(view))
4662 wstandout(view->window);
4663 waddwstr(view->window, wline);
4664 free(wline);
4665 wline = NULL;
4666 while (width++ < view->ncols)
4667 waddch(view->window, ' ');
4668 if (view_needs_focus_indication(view))
4669 wstandend(view->window);
4671 if (max_lines <= 1)
4672 return NULL;
4673 max_lines--;
4676 s->eof = 0;
4677 view->maxx = 0;
4678 line = NULL;
4679 while (max_lines > 0 && nprinted < max_lines) {
4680 enum got_diff_line_type linetype;
4681 attr_t attr = 0;
4683 linelen = getline(&line, &linesize, s->f);
4684 if (linelen == -1) {
4685 if (feof(s->f)) {
4686 s->eof = 1;
4687 break;
4689 free(line);
4690 return got_ferror(s->f, GOT_ERR_IO);
4693 if (++s->lineno < s->first_displayed_line)
4694 continue;
4695 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4696 continue;
4697 if (s->lineno == view->hiline)
4698 attr = A_STANDOUT;
4700 /* Set view->maxx based on full line length. */
4701 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4702 view->x ? 1 : 0);
4703 if (err) {
4704 free(line);
4705 return err;
4707 view->maxx = MAX(view->maxx, width);
4708 free(wline);
4709 wline = NULL;
4711 linetype = s->lines[s->lineno].type;
4712 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4713 linetype < GOT_DIFF_LINE_CONTEXT)
4714 attr |= COLOR_PAIR(linetype);
4715 if (attr)
4716 wattron(view->window, attr);
4717 if (s->first_displayed_line + nprinted == s->matched_line &&
4718 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4719 err = add_matched_line(&width, line, view->ncols, 0,
4720 view->window, view->x, regmatch);
4721 if (err) {
4722 free(line);
4723 return err;
4725 } else {
4726 int skip;
4727 err = format_line(&wline, &width, &skip, line,
4728 view->x, view->ncols, 0, view->x ? 1 : 0);
4729 if (err) {
4730 free(line);
4731 return err;
4733 waddwstr(view->window, &wline[skip]);
4734 free(wline);
4735 wline = NULL;
4737 if (s->lineno == view->hiline) {
4738 /* highlight full gline length */
4739 while (width++ < view->ncols)
4740 waddch(view->window, ' ');
4741 } else {
4742 if (width <= view->ncols - 1)
4743 waddch(view->window, '\n');
4745 if (attr)
4746 wattroff(view->window, attr);
4747 if (++nprinted == 1)
4748 s->first_displayed_line = s->lineno;
4750 free(line);
4751 if (nprinted >= 1)
4752 s->last_displayed_line = s->first_displayed_line +
4753 (nprinted - 1);
4754 else
4755 s->last_displayed_line = s->first_displayed_line;
4757 view_border(view);
4759 if (s->eof) {
4760 while (nprinted < view->nlines) {
4761 waddch(view->window, '\n');
4762 nprinted++;
4765 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4766 view->ncols, 0, 0);
4767 if (err) {
4768 return err;
4771 wstandout(view->window);
4772 waddwstr(view->window, wline);
4773 free(wline);
4774 wline = NULL;
4775 wstandend(view->window);
4778 return NULL;
4781 static char *
4782 get_datestr(time_t *time, char *datebuf)
4784 struct tm mytm, *tm;
4785 char *p, *s;
4787 tm = gmtime_r(time, &mytm);
4788 if (tm == NULL)
4789 return NULL;
4790 s = asctime_r(tm, datebuf);
4791 if (s == NULL)
4792 return NULL;
4793 p = strchr(s, '\n');
4794 if (p)
4795 *p = '\0';
4796 return s;
4799 static const struct got_error *
4800 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4801 off_t off, uint8_t type)
4803 struct got_diff_line *p;
4805 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4806 if (p == NULL)
4807 return got_error_from_errno("reallocarray");
4808 *lines = p;
4809 (*lines)[*nlines].offset = off;
4810 (*lines)[*nlines].type = type;
4811 (*nlines)++;
4813 return NULL;
4816 static const struct got_error *
4817 cat_diff(FILE *dst, FILE *src, struct got_diff_line **d_lines, size_t *d_nlines,
4818 struct got_diff_line *s_lines, size_t s_nlines)
4820 struct got_diff_line *p;
4821 char buf[BUFSIZ];
4822 size_t i, r;
4824 if (fseeko(src, 0L, SEEK_SET) == -1)
4825 return got_error_from_errno("fseeko");
4827 for (;;) {
4828 r = fread(buf, 1, sizeof(buf), src);
4829 if (r == 0) {
4830 if (ferror(src))
4831 return got_error_from_errno("fread");
4832 if (feof(src))
4833 break;
4835 if (fwrite(buf, 1, r, dst) != r)
4836 return got_ferror(dst, GOT_ERR_IO);
4839 if (s_nlines == 0 && *d_nlines == 0)
4840 return NULL;
4843 * If commit info was in dst, increment line offsets
4844 * of the appended diff content, but skip s_lines[0]
4845 * because offset zero is already in *d_lines.
4847 if (*d_nlines > 0) {
4848 for (i = 1; i < s_nlines; ++i)
4849 s_lines[i].offset += (*d_lines)[*d_nlines - 1].offset;
4851 if (s_nlines > 0) {
4852 --s_nlines;
4853 ++s_lines;
4857 p = reallocarray(*d_lines, *d_nlines + s_nlines, sizeof(*p));
4858 if (p == NULL) {
4859 /* d_lines is freed in close_diff_view() */
4860 return got_error_from_errno("reallocarray");
4863 *d_lines = p;
4865 memcpy(*d_lines + *d_nlines, s_lines, s_nlines * sizeof(*s_lines));
4866 *d_nlines += s_nlines;
4868 return NULL;
4871 static const struct got_error *
4872 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4873 struct got_object_id *commit_id, struct got_reflist_head *refs,
4874 struct got_repository *repo, int ignore_ws, int force_text_diff,
4875 struct got_diffstat_cb_arg *dsa, FILE *outfile)
4877 const struct got_error *err = NULL;
4878 char datebuf[26], *datestr;
4879 struct got_commit_object *commit;
4880 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4881 time_t committer_time;
4882 const char *author, *committer;
4883 char *refs_str = NULL;
4884 struct got_pathlist_entry *pe;
4885 off_t outoff = 0;
4886 int n;
4888 if (refs) {
4889 err = build_refs_str(&refs_str, refs, commit_id, repo);
4890 if (err)
4891 return err;
4894 err = got_object_open_as_commit(&commit, repo, commit_id);
4895 if (err)
4896 return err;
4898 err = got_object_id_str(&id_str, commit_id);
4899 if (err) {
4900 err = got_error_from_errno("got_object_id_str");
4901 goto done;
4904 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4905 if (err)
4906 goto done;
4908 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4909 refs_str ? refs_str : "", refs_str ? ")" : "");
4910 if (n < 0) {
4911 err = got_error_from_errno("fprintf");
4912 goto done;
4914 outoff += n;
4915 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4916 if (err)
4917 goto done;
4919 n = fprintf(outfile, "from: %s\n",
4920 got_object_commit_get_author(commit));
4921 if (n < 0) {
4922 err = got_error_from_errno("fprintf");
4923 goto done;
4925 outoff += n;
4926 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4927 if (err)
4928 goto done;
4930 author = got_object_commit_get_author(commit);
4931 committer = got_object_commit_get_committer(commit);
4932 if (strcmp(author, committer) != 0) {
4933 n = fprintf(outfile, "via: %s\n", committer);
4934 if (n < 0) {
4935 err = got_error_from_errno("fprintf");
4936 goto done;
4938 outoff += n;
4939 err = add_line_metadata(lines, nlines, outoff,
4940 GOT_DIFF_LINE_AUTHOR);
4941 if (err)
4942 goto done;
4944 committer_time = got_object_commit_get_committer_time(commit);
4945 datestr = get_datestr(&committer_time, datebuf);
4946 if (datestr) {
4947 n = fprintf(outfile, "date: %s UTC\n", datestr);
4948 if (n < 0) {
4949 err = got_error_from_errno("fprintf");
4950 goto done;
4952 outoff += n;
4953 err = add_line_metadata(lines, nlines, outoff,
4954 GOT_DIFF_LINE_DATE);
4955 if (err)
4956 goto done;
4958 if (got_object_commit_get_nparents(commit) > 1) {
4959 const struct got_object_id_queue *parent_ids;
4960 struct got_object_qid *qid;
4961 int pn = 1;
4962 parent_ids = got_object_commit_get_parent_ids(commit);
4963 STAILQ_FOREACH(qid, parent_ids, entry) {
4964 err = got_object_id_str(&id_str, &qid->id);
4965 if (err)
4966 goto done;
4967 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4968 if (n < 0) {
4969 err = got_error_from_errno("fprintf");
4970 goto done;
4972 outoff += n;
4973 err = add_line_metadata(lines, nlines, outoff,
4974 GOT_DIFF_LINE_META);
4975 if (err)
4976 goto done;
4977 free(id_str);
4978 id_str = NULL;
4982 err = got_object_commit_get_logmsg(&logmsg, commit);
4983 if (err)
4984 goto done;
4985 s = logmsg;
4986 while ((line = strsep(&s, "\n")) != NULL) {
4987 n = fprintf(outfile, "%s\n", line);
4988 if (n < 0) {
4989 err = got_error_from_errno("fprintf");
4990 goto done;
4992 outoff += n;
4993 err = add_line_metadata(lines, nlines, outoff,
4994 GOT_DIFF_LINE_LOGMSG);
4995 if (err)
4996 goto done;
4999 TAILQ_FOREACH(pe, dsa->paths, entry) {
5000 struct got_diff_changed_path *cp = pe->data;
5001 int pad = dsa->max_path_len - pe->path_len + 1;
5003 n = fprintf(outfile, "%c %s%*c | %*d+ %*d-\n", cp->status,
5004 pe->path, pad, ' ', dsa->add_cols + 1, cp->add,
5005 dsa->rm_cols + 1, cp->rm);
5006 if (n < 0) {
5007 err = got_error_from_errno("fprintf");
5008 goto done;
5010 outoff += n;
5011 err = add_line_metadata(lines, nlines, outoff,
5012 GOT_DIFF_LINE_CHANGES);
5013 if (err)
5014 goto done;
5017 fputc('\n', outfile);
5018 outoff++;
5019 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5020 if (err)
5021 goto done;
5023 n = fprintf(outfile,
5024 "%d file%s changed, %d insertion%s(+), %d deletion%s(-)\n",
5025 dsa->nfiles, dsa->nfiles > 1 ? "s" : "", dsa->ins,
5026 dsa->ins != 1 ? "s" : "", dsa->del, dsa->del != 1 ? "s" : "");
5027 if (n < 0) {
5028 err = got_error_from_errno("fprintf");
5029 goto done;
5031 outoff += n;
5032 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5033 if (err)
5034 goto done;
5036 fputc('\n', outfile);
5037 outoff++;
5038 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
5039 done:
5040 free(id_str);
5041 free(logmsg);
5042 free(refs_str);
5043 got_object_commit_close(commit);
5044 if (err) {
5045 free(*lines);
5046 *lines = NULL;
5047 *nlines = 0;
5049 return err;
5052 static const struct got_error *
5053 create_diff(struct tog_diff_view_state *s)
5055 const struct got_error *err = NULL;
5056 FILE *f = NULL, *tmp_diff_file = NULL;
5057 int obj_type;
5058 struct got_diff_line *lines = NULL;
5059 struct got_pathlist_head changed_paths;
5061 TAILQ_INIT(&changed_paths);
5063 free(s->lines);
5064 s->lines = malloc(sizeof(*s->lines));
5065 if (s->lines == NULL)
5066 return got_error_from_errno("malloc");
5067 s->nlines = 0;
5069 f = got_opentemp();
5070 if (f == NULL) {
5071 err = got_error_from_errno("got_opentemp");
5072 goto done;
5074 tmp_diff_file = got_opentemp();
5075 if (tmp_diff_file == NULL) {
5076 err = got_error_from_errno("got_opentemp");
5077 goto done;
5079 if (s->f && fclose(s->f) == EOF) {
5080 err = got_error_from_errno("fclose");
5081 goto done;
5083 s->f = f;
5085 if (s->id1)
5086 err = got_object_get_type(&obj_type, s->repo, s->id1);
5087 else
5088 err = got_object_get_type(&obj_type, s->repo, s->id2);
5089 if (err)
5090 goto done;
5092 switch (obj_type) {
5093 case GOT_OBJ_TYPE_BLOB:
5094 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
5095 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
5096 s->label1, s->label2, tog_diff_algo, s->diff_context,
5097 s->ignore_whitespace, s->force_text_diff, NULL, s->repo,
5098 s->f);
5099 break;
5100 case GOT_OBJ_TYPE_TREE:
5101 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
5102 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
5103 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5104 s->force_text_diff, NULL, s->repo, s->f);
5105 break;
5106 case GOT_OBJ_TYPE_COMMIT: {
5107 const struct got_object_id_queue *parent_ids;
5108 struct got_object_qid *pid;
5109 struct got_commit_object *commit2;
5110 struct got_reflist_head *refs;
5111 size_t nlines = 0;
5112 struct got_diffstat_cb_arg dsa = {
5113 0, 0, 0, 0, 0, 0,
5114 &changed_paths,
5115 s->ignore_whitespace,
5116 s->force_text_diff,
5117 tog_diff_algo
5120 lines = malloc(sizeof(*lines));
5121 if (lines == NULL) {
5122 err = got_error_from_errno("malloc");
5123 goto done;
5126 /* build diff first in tmp file then append to commit info */
5127 err = got_diff_objects_as_commits(&lines, &nlines,
5128 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
5129 tog_diff_algo, s->diff_context, s->ignore_whitespace,
5130 s->force_text_diff, &dsa, s->repo, tmp_diff_file);
5131 if (err)
5132 break;
5134 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
5135 if (err)
5136 goto done;
5137 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
5138 /* Show commit info if we're diffing to a parent/root commit. */
5139 if (s->id1 == NULL) {
5140 err = write_commit_info(&s->lines, &s->nlines, s->id2,
5141 refs, s->repo, s->ignore_whitespace,
5142 s->force_text_diff, &dsa, s->f);
5143 if (err)
5144 goto done;
5145 } else {
5146 parent_ids = got_object_commit_get_parent_ids(commit2);
5147 STAILQ_FOREACH(pid, parent_ids, entry) {
5148 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
5149 err = write_commit_info(&s->lines,
5150 &s->nlines, s->id2, refs, s->repo,
5151 s->ignore_whitespace,
5152 s->force_text_diff, &dsa, s->f);
5153 if (err)
5154 goto done;
5155 break;
5159 got_object_commit_close(commit2);
5161 err = cat_diff(s->f, tmp_diff_file, &s->lines, &s->nlines,
5162 lines, nlines);
5163 break;
5165 default:
5166 err = got_error(GOT_ERR_OBJ_TYPE);
5167 break;
5169 done:
5170 free(lines);
5171 got_pathlist_free(&changed_paths, GOT_PATHLIST_FREE_ALL);
5172 if (s->f && fflush(s->f) != 0 && err == NULL)
5173 err = got_error_from_errno("fflush");
5174 if (tmp_diff_file && fclose(tmp_diff_file) == EOF && err == NULL)
5175 err = got_error_from_errno("fclose");
5176 return err;
5179 static void
5180 diff_view_indicate_progress(struct tog_view *view)
5182 mvwaddstr(view->window, 0, 0, "diffing...");
5183 update_panels();
5184 doupdate();
5187 static const struct got_error *
5188 search_start_diff_view(struct tog_view *view)
5190 struct tog_diff_view_state *s = &view->state.diff;
5192 s->matched_line = 0;
5193 return NULL;
5196 static void
5197 search_setup_diff_view(struct tog_view *view, FILE **f, off_t **line_offsets,
5198 size_t *nlines, int **first, int **last, int **match, int **selected)
5200 struct tog_diff_view_state *s = &view->state.diff;
5202 *f = s->f;
5203 *nlines = s->nlines;
5204 *line_offsets = NULL;
5205 *match = &s->matched_line;
5206 *first = &s->first_displayed_line;
5207 *last = &s->last_displayed_line;
5208 *selected = &s->selected_line;
5211 static const struct got_error *
5212 search_next_view_match(struct tog_view *view)
5214 const struct got_error *err = NULL;
5215 FILE *f;
5216 int lineno;
5217 char *line = NULL;
5218 size_t linesize = 0;
5219 ssize_t linelen;
5220 off_t *line_offsets;
5221 size_t nlines = 0;
5222 int *first, *last, *match, *selected;
5224 if (!view->search_setup)
5225 return got_error_msg(GOT_ERR_NOT_IMPL,
5226 "view search not supported");
5227 view->search_setup(view, &f, &line_offsets, &nlines, &first, &last,
5228 &match, &selected);
5230 if (!view->searching) {
5231 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5232 return NULL;
5235 if (*match) {
5236 if (view->searching == TOG_SEARCH_FORWARD)
5237 lineno = *first + 1;
5238 else
5239 lineno = *first - 1;
5240 } else
5241 lineno = *first - 1 + *selected;
5243 while (1) {
5244 off_t offset;
5246 if (lineno <= 0 || lineno > nlines) {
5247 if (*match == 0) {
5248 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5249 break;
5252 if (view->searching == TOG_SEARCH_FORWARD)
5253 lineno = 1;
5254 else
5255 lineno = nlines;
5258 offset = view->type == TOG_VIEW_DIFF ?
5259 view->state.diff.lines[lineno - 1].offset :
5260 line_offsets[lineno - 1];
5261 if (fseeko(f, offset, SEEK_SET) != 0) {
5262 free(line);
5263 return got_error_from_errno("fseeko");
5265 linelen = getline(&line, &linesize, f);
5266 if (linelen != -1) {
5267 char *exstr;
5268 err = expand_tab(&exstr, line);
5269 if (err)
5270 break;
5271 if (match_line(exstr, &view->regex, 1,
5272 &view->regmatch)) {
5273 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5274 *match = lineno;
5275 free(exstr);
5276 break;
5278 free(exstr);
5280 if (view->searching == TOG_SEARCH_FORWARD)
5281 lineno++;
5282 else
5283 lineno--;
5285 free(line);
5287 if (*match) {
5288 *first = *match;
5289 *selected = 1;
5292 return err;
5295 static const struct got_error *
5296 close_diff_view(struct tog_view *view)
5298 const struct got_error *err = NULL;
5299 struct tog_diff_view_state *s = &view->state.diff;
5301 free(s->id1);
5302 s->id1 = NULL;
5303 free(s->id2);
5304 s->id2 = NULL;
5305 if (s->f && fclose(s->f) == EOF)
5306 err = got_error_from_errno("fclose");
5307 s->f = NULL;
5308 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
5309 err = got_error_from_errno("fclose");
5310 s->f1 = NULL;
5311 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
5312 err = got_error_from_errno("fclose");
5313 s->f2 = NULL;
5314 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
5315 err = got_error_from_errno("close");
5316 s->fd1 = -1;
5317 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
5318 err = got_error_from_errno("close");
5319 s->fd2 = -1;
5320 free(s->lines);
5321 s->lines = NULL;
5322 s->nlines = 0;
5323 return err;
5326 static const struct got_error *
5327 open_diff_view(struct tog_view *view, struct got_object_id *id1,
5328 struct got_object_id *id2, const char *label1, const char *label2,
5329 int diff_context, int ignore_whitespace, int force_text_diff,
5330 struct tog_view *parent_view, struct got_repository *repo)
5332 const struct got_error *err;
5333 struct tog_diff_view_state *s = &view->state.diff;
5335 memset(s, 0, sizeof(*s));
5336 s->fd1 = -1;
5337 s->fd2 = -1;
5339 if (id1 != NULL && id2 != NULL) {
5340 int type1, type2;
5342 err = got_object_get_type(&type1, repo, id1);
5343 if (err)
5344 goto done;
5345 err = got_object_get_type(&type2, repo, id2);
5346 if (err)
5347 goto done;
5349 if (type1 != type2) {
5350 err = got_error(GOT_ERR_OBJ_TYPE);
5351 goto done;
5354 s->first_displayed_line = 1;
5355 s->last_displayed_line = view->nlines;
5356 s->selected_line = 1;
5357 s->repo = repo;
5358 s->id1 = id1;
5359 s->id2 = id2;
5360 s->label1 = label1;
5361 s->label2 = label2;
5363 if (id1) {
5364 s->id1 = got_object_id_dup(id1);
5365 if (s->id1 == NULL) {
5366 err = got_error_from_errno("got_object_id_dup");
5367 goto done;
5369 } else
5370 s->id1 = NULL;
5372 s->id2 = got_object_id_dup(id2);
5373 if (s->id2 == NULL) {
5374 err = got_error_from_errno("got_object_id_dup");
5375 goto done;
5378 s->f1 = got_opentemp();
5379 if (s->f1 == NULL) {
5380 err = got_error_from_errno("got_opentemp");
5381 goto done;
5384 s->f2 = got_opentemp();
5385 if (s->f2 == NULL) {
5386 err = got_error_from_errno("got_opentemp");
5387 goto done;
5390 s->fd1 = got_opentempfd();
5391 if (s->fd1 == -1) {
5392 err = got_error_from_errno("got_opentempfd");
5393 goto done;
5396 s->fd2 = got_opentempfd();
5397 if (s->fd2 == -1) {
5398 err = got_error_from_errno("got_opentempfd");
5399 goto done;
5402 s->diff_context = diff_context;
5403 s->ignore_whitespace = ignore_whitespace;
5404 s->force_text_diff = force_text_diff;
5405 s->parent_view = parent_view;
5406 s->repo = repo;
5408 if (has_colors() && getenv("TOG_COLORS") != NULL && !using_mock_io) {
5409 int rc;
5411 rc = init_pair(GOT_DIFF_LINE_MINUS,
5412 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
5413 if (rc != ERR)
5414 rc = init_pair(GOT_DIFF_LINE_PLUS,
5415 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
5416 if (rc != ERR)
5417 rc = init_pair(GOT_DIFF_LINE_HUNK,
5418 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
5419 if (rc != ERR)
5420 rc = init_pair(GOT_DIFF_LINE_META,
5421 get_color_value("TOG_COLOR_DIFF_META"), -1);
5422 if (rc != ERR)
5423 rc = init_pair(GOT_DIFF_LINE_CHANGES,
5424 get_color_value("TOG_COLOR_DIFF_META"), -1);
5425 if (rc != ERR)
5426 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
5427 get_color_value("TOG_COLOR_DIFF_META"), -1);
5428 if (rc != ERR)
5429 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
5430 get_color_value("TOG_COLOR_DIFF_META"), -1);
5431 if (rc != ERR)
5432 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
5433 get_color_value("TOG_COLOR_AUTHOR"), -1);
5434 if (rc != ERR)
5435 rc = init_pair(GOT_DIFF_LINE_DATE,
5436 get_color_value("TOG_COLOR_DATE"), -1);
5437 if (rc == ERR) {
5438 err = got_error(GOT_ERR_RANGE);
5439 goto done;
5443 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
5444 view_is_splitscreen(view))
5445 show_log_view(parent_view); /* draw border */
5446 diff_view_indicate_progress(view);
5448 err = create_diff(s);
5450 view->show = show_diff_view;
5451 view->input = input_diff_view;
5452 view->reset = reset_diff_view;
5453 view->close = close_diff_view;
5454 view->search_start = search_start_diff_view;
5455 view->search_setup = search_setup_diff_view;
5456 view->search_next = search_next_view_match;
5457 done:
5458 if (err) {
5459 if (view->close == NULL)
5460 close_diff_view(view);
5461 view_close(view);
5463 return err;
5466 static const struct got_error *
5467 show_diff_view(struct tog_view *view)
5469 const struct got_error *err;
5470 struct tog_diff_view_state *s = &view->state.diff;
5471 char *id_str1 = NULL, *id_str2, *header;
5472 const char *label1, *label2;
5474 if (s->id1) {
5475 err = got_object_id_str(&id_str1, s->id1);
5476 if (err)
5477 return err;
5478 label1 = s->label1 ? s->label1 : id_str1;
5479 } else
5480 label1 = "/dev/null";
5482 err = got_object_id_str(&id_str2, s->id2);
5483 if (err)
5484 return err;
5485 label2 = s->label2 ? s->label2 : id_str2;
5487 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
5488 err = got_error_from_errno("asprintf");
5489 free(id_str1);
5490 free(id_str2);
5491 return err;
5493 free(id_str1);
5494 free(id_str2);
5496 err = draw_file(view, header);
5497 free(header);
5498 return err;
5501 static const struct got_error *
5502 set_selected_commit(struct tog_diff_view_state *s,
5503 struct commit_queue_entry *entry)
5505 const struct got_error *err;
5506 const struct got_object_id_queue *parent_ids;
5507 struct got_commit_object *selected_commit;
5508 struct got_object_qid *pid;
5510 free(s->id2);
5511 s->id2 = got_object_id_dup(entry->id);
5512 if (s->id2 == NULL)
5513 return got_error_from_errno("got_object_id_dup");
5515 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
5516 if (err)
5517 return err;
5518 parent_ids = got_object_commit_get_parent_ids(selected_commit);
5519 free(s->id1);
5520 pid = STAILQ_FIRST(parent_ids);
5521 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
5522 got_object_commit_close(selected_commit);
5523 return NULL;
5526 static const struct got_error *
5527 reset_diff_view(struct tog_view *view)
5529 struct tog_diff_view_state *s = &view->state.diff;
5531 view->count = 0;
5532 wclear(view->window);
5533 s->first_displayed_line = 1;
5534 s->last_displayed_line = view->nlines;
5535 s->matched_line = 0;
5536 diff_view_indicate_progress(view);
5537 return create_diff(s);
5540 static void
5541 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5543 int start, i;
5545 i = start = s->first_displayed_line - 1;
5547 while (s->lines[i].type != type) {
5548 if (i == 0)
5549 i = s->nlines - 1;
5550 if (--i == start)
5551 return; /* do nothing, requested type not in file */
5554 s->selected_line = 1;
5555 s->first_displayed_line = i;
5558 static void
5559 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
5561 int start, i;
5563 i = start = s->first_displayed_line + 1;
5565 while (s->lines[i].type != type) {
5566 if (i == s->nlines - 1)
5567 i = 0;
5568 if (++i == start)
5569 return; /* do nothing, requested type not in file */
5572 s->selected_line = 1;
5573 s->first_displayed_line = i;
5576 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
5577 int, int, int);
5578 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
5579 int, int);
5581 static const struct got_error *
5582 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
5584 const struct got_error *err = NULL;
5585 struct tog_diff_view_state *s = &view->state.diff;
5586 struct tog_log_view_state *ls;
5587 struct commit_queue_entry *old_selected_entry;
5588 char *line = NULL;
5589 size_t linesize = 0;
5590 ssize_t linelen;
5591 int i, nscroll = view->nlines - 1, up = 0;
5593 s->lineno = s->first_displayed_line - 1 + s->selected_line;
5595 switch (ch) {
5596 case '0':
5597 case '$':
5598 case KEY_RIGHT:
5599 case 'l':
5600 case KEY_LEFT:
5601 case 'h':
5602 horizontal_scroll_input(view, ch);
5603 break;
5604 case 'a':
5605 case 'w':
5606 if (ch == 'a') {
5607 s->force_text_diff = !s->force_text_diff;
5608 view->action = s->force_text_diff ?
5609 "force ASCII text enabled" :
5610 "force ASCII text disabled";
5612 else if (ch == 'w') {
5613 s->ignore_whitespace = !s->ignore_whitespace;
5614 view->action = s->ignore_whitespace ?
5615 "ignore whitespace enabled" :
5616 "ignore whitespace disabled";
5618 err = reset_diff_view(view);
5619 break;
5620 case 'g':
5621 case KEY_HOME:
5622 s->first_displayed_line = 1;
5623 view->count = 0;
5624 break;
5625 case 'G':
5626 case KEY_END:
5627 view->count = 0;
5628 if (s->eof)
5629 break;
5631 s->first_displayed_line = (s->nlines - view->nlines) + 2;
5632 s->eof = 1;
5633 break;
5634 case 'k':
5635 case KEY_UP:
5636 case CTRL('p'):
5637 if (s->first_displayed_line > 1)
5638 s->first_displayed_line--;
5639 else
5640 view->count = 0;
5641 break;
5642 case CTRL('u'):
5643 case 'u':
5644 nscroll /= 2;
5645 /* FALL THROUGH */
5646 case KEY_PPAGE:
5647 case CTRL('b'):
5648 case 'b':
5649 if (s->first_displayed_line == 1) {
5650 view->count = 0;
5651 break;
5653 i = 0;
5654 while (i++ < nscroll && s->first_displayed_line > 1)
5655 s->first_displayed_line--;
5656 break;
5657 case 'j':
5658 case KEY_DOWN:
5659 case CTRL('n'):
5660 if (!s->eof)
5661 s->first_displayed_line++;
5662 else
5663 view->count = 0;
5664 break;
5665 case CTRL('d'):
5666 case 'd':
5667 nscroll /= 2;
5668 /* FALL THROUGH */
5669 case KEY_NPAGE:
5670 case CTRL('f'):
5671 case 'f':
5672 case ' ':
5673 if (s->eof) {
5674 view->count = 0;
5675 break;
5677 i = 0;
5678 while (!s->eof && i++ < nscroll) {
5679 linelen = getline(&line, &linesize, s->f);
5680 s->first_displayed_line++;
5681 if (linelen == -1) {
5682 if (feof(s->f)) {
5683 s->eof = 1;
5684 } else
5685 err = got_ferror(s->f, GOT_ERR_IO);
5686 break;
5689 free(line);
5690 break;
5691 case '(':
5692 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
5693 break;
5694 case ')':
5695 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
5696 break;
5697 case '{':
5698 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
5699 break;
5700 case '}':
5701 diff_next_index(s, GOT_DIFF_LINE_HUNK);
5702 break;
5703 case '[':
5704 if (s->diff_context > 0) {
5705 s->diff_context--;
5706 s->matched_line = 0;
5707 diff_view_indicate_progress(view);
5708 err = create_diff(s);
5709 if (s->first_displayed_line + view->nlines - 1 >
5710 s->nlines) {
5711 s->first_displayed_line = 1;
5712 s->last_displayed_line = view->nlines;
5714 } else
5715 view->count = 0;
5716 break;
5717 case ']':
5718 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
5719 s->diff_context++;
5720 s->matched_line = 0;
5721 diff_view_indicate_progress(view);
5722 err = create_diff(s);
5723 } else
5724 view->count = 0;
5725 break;
5726 case '<':
5727 case ',':
5728 case 'K':
5729 up = 1;
5730 /* FALL THROUGH */
5731 case '>':
5732 case '.':
5733 case 'J':
5734 if (s->parent_view == NULL) {
5735 view->count = 0;
5736 break;
5738 s->parent_view->count = view->count;
5740 if (s->parent_view->type == TOG_VIEW_LOG) {
5741 ls = &s->parent_view->state.log;
5742 old_selected_entry = ls->selected_entry;
5744 err = input_log_view(NULL, s->parent_view,
5745 up ? KEY_UP : KEY_DOWN);
5746 if (err)
5747 break;
5748 view->count = s->parent_view->count;
5750 if (old_selected_entry == ls->selected_entry)
5751 break;
5753 err = set_selected_commit(s, ls->selected_entry);
5754 if (err)
5755 break;
5756 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
5757 struct tog_blame_view_state *bs;
5758 struct got_object_id *id, *prev_id;
5760 bs = &s->parent_view->state.blame;
5761 prev_id = get_annotation_for_line(bs->blame.lines,
5762 bs->blame.nlines, bs->last_diffed_line);
5764 err = input_blame_view(&view, s->parent_view,
5765 up ? KEY_UP : KEY_DOWN);
5766 if (err)
5767 break;
5768 view->count = s->parent_view->count;
5770 if (prev_id == NULL)
5771 break;
5772 id = get_selected_commit_id(bs->blame.lines,
5773 bs->blame.nlines, bs->first_displayed_line,
5774 bs->selected_line);
5775 if (id == NULL)
5776 break;
5778 if (!got_object_id_cmp(prev_id, id))
5779 break;
5781 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5782 if (err)
5783 break;
5785 s->first_displayed_line = 1;
5786 s->last_displayed_line = view->nlines;
5787 s->matched_line = 0;
5788 view->x = 0;
5790 diff_view_indicate_progress(view);
5791 err = create_diff(s);
5792 break;
5793 default:
5794 view->count = 0;
5795 break;
5798 return err;
5801 static const struct got_error *
5802 cmd_diff(int argc, char *argv[])
5804 const struct got_error *error;
5805 struct got_repository *repo = NULL;
5806 struct got_worktree *worktree = NULL;
5807 struct got_object_id *id1 = NULL, *id2 = NULL;
5808 char *repo_path = NULL, *cwd = NULL;
5809 char *id_str1 = NULL, *id_str2 = NULL;
5810 char *label1 = NULL, *label2 = NULL;
5811 int diff_context = 3, ignore_whitespace = 0;
5812 int ch, force_text_diff = 0;
5813 const char *errstr;
5814 struct tog_view *view;
5815 int *pack_fds = NULL;
5817 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5818 switch (ch) {
5819 case 'a':
5820 force_text_diff = 1;
5821 break;
5822 case 'C':
5823 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5824 &errstr);
5825 if (errstr != NULL)
5826 errx(1, "number of context lines is %s: %s",
5827 errstr, errstr);
5828 break;
5829 case 'r':
5830 repo_path = realpath(optarg, NULL);
5831 if (repo_path == NULL)
5832 return got_error_from_errno2("realpath",
5833 optarg);
5834 got_path_strip_trailing_slashes(repo_path);
5835 break;
5836 case 'w':
5837 ignore_whitespace = 1;
5838 break;
5839 default:
5840 usage_diff();
5841 /* NOTREACHED */
5845 argc -= optind;
5846 argv += optind;
5848 if (argc == 0) {
5849 usage_diff(); /* TODO show local worktree changes */
5850 } else if (argc == 2) {
5851 id_str1 = argv[0];
5852 id_str2 = argv[1];
5853 } else
5854 usage_diff();
5856 error = got_repo_pack_fds_open(&pack_fds);
5857 if (error)
5858 goto done;
5860 if (repo_path == NULL) {
5861 cwd = getcwd(NULL, 0);
5862 if (cwd == NULL)
5863 return got_error_from_errno("getcwd");
5864 error = got_worktree_open(&worktree, cwd);
5865 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5866 goto done;
5867 if (worktree)
5868 repo_path =
5869 strdup(got_worktree_get_repo_path(worktree));
5870 else
5871 repo_path = strdup(cwd);
5872 if (repo_path == NULL) {
5873 error = got_error_from_errno("strdup");
5874 goto done;
5878 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5879 if (error)
5880 goto done;
5882 init_curses();
5884 error = apply_unveil(got_repo_get_path(repo), NULL);
5885 if (error)
5886 goto done;
5888 error = tog_load_refs(repo, 0);
5889 if (error)
5890 goto done;
5892 error = got_repo_match_object_id(&id1, &label1, id_str1,
5893 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5894 if (error)
5895 goto done;
5897 error = got_repo_match_object_id(&id2, &label2, id_str2,
5898 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5899 if (error)
5900 goto done;
5902 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5903 if (view == NULL) {
5904 error = got_error_from_errno("view_open");
5905 goto done;
5907 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5908 ignore_whitespace, force_text_diff, NULL, repo);
5909 if (error)
5910 goto done;
5911 error = view_loop(view);
5912 done:
5913 free(label1);
5914 free(label2);
5915 free(repo_path);
5916 free(cwd);
5917 if (repo) {
5918 const struct got_error *close_err = got_repo_close(repo);
5919 if (error == NULL)
5920 error = close_err;
5922 if (worktree)
5923 got_worktree_close(worktree);
5924 if (pack_fds) {
5925 const struct got_error *pack_err =
5926 got_repo_pack_fds_close(pack_fds);
5927 if (error == NULL)
5928 error = pack_err;
5930 tog_free_refs();
5931 return error;
5934 __dead static void
5935 usage_blame(void)
5937 endwin();
5938 fprintf(stderr,
5939 "usage: %s blame [-c commit] [-r repository-path] path\n",
5940 getprogname());
5941 exit(1);
5944 struct tog_blame_line {
5945 int annotated;
5946 struct got_object_id *id;
5949 static const struct got_error *
5950 draw_blame(struct tog_view *view)
5952 struct tog_blame_view_state *s = &view->state.blame;
5953 struct tog_blame *blame = &s->blame;
5954 regmatch_t *regmatch = &view->regmatch;
5955 const struct got_error *err;
5956 int lineno = 0, nprinted = 0;
5957 char *line = NULL;
5958 size_t linesize = 0;
5959 ssize_t linelen;
5960 wchar_t *wline;
5961 int width;
5962 struct tog_blame_line *blame_line;
5963 struct got_object_id *prev_id = NULL;
5964 char *id_str;
5965 struct tog_color *tc;
5967 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5968 if (err)
5969 return err;
5971 rewind(blame->f);
5972 werase(view->window);
5974 if (asprintf(&line, "commit %s", id_str) == -1) {
5975 err = got_error_from_errno("asprintf");
5976 free(id_str);
5977 return err;
5980 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5981 free(line);
5982 line = NULL;
5983 if (err)
5984 return err;
5985 if (view_needs_focus_indication(view))
5986 wstandout(view->window);
5987 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5988 if (tc)
5989 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
5990 waddwstr(view->window, wline);
5991 while (width++ < view->ncols)
5992 waddch(view->window, ' ');
5993 if (tc)
5994 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
5995 if (view_needs_focus_indication(view))
5996 wstandend(view->window);
5997 free(wline);
5998 wline = NULL;
6000 if (view->gline > blame->nlines)
6001 view->gline = blame->nlines;
6003 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
6004 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
6005 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
6006 free(id_str);
6007 return got_error_from_errno("asprintf");
6009 free(id_str);
6010 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
6011 free(line);
6012 line = NULL;
6013 if (err)
6014 return err;
6015 waddwstr(view->window, wline);
6016 free(wline);
6017 wline = NULL;
6018 if (width < view->ncols - 1)
6019 waddch(view->window, '\n');
6021 s->eof = 0;
6022 view->maxx = 0;
6023 while (nprinted < view->nlines - 2) {
6024 linelen = getline(&line, &linesize, blame->f);
6025 if (linelen == -1) {
6026 if (feof(blame->f)) {
6027 s->eof = 1;
6028 break;
6030 free(line);
6031 return got_ferror(blame->f, GOT_ERR_IO);
6033 if (++lineno < s->first_displayed_line)
6034 continue;
6035 if (view->gline && !gotoline(view, &lineno, &nprinted))
6036 continue;
6038 /* Set view->maxx based on full line length. */
6039 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
6040 if (err) {
6041 free(line);
6042 return err;
6044 free(wline);
6045 wline = NULL;
6046 view->maxx = MAX(view->maxx, width);
6048 if (nprinted == s->selected_line - 1)
6049 wstandout(view->window);
6051 if (blame->nlines > 0) {
6052 blame_line = &blame->lines[lineno - 1];
6053 if (blame_line->annotated && prev_id &&
6054 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
6055 !(nprinted == s->selected_line - 1)) {
6056 waddstr(view->window, " ");
6057 } else if (blame_line->annotated) {
6058 char *id_str;
6059 err = got_object_id_str(&id_str,
6060 blame_line->id);
6061 if (err) {
6062 free(line);
6063 return err;
6065 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6066 if (tc)
6067 wattr_on(view->window,
6068 COLOR_PAIR(tc->colorpair), NULL);
6069 wprintw(view->window, "%.8s", id_str);
6070 if (tc)
6071 wattr_off(view->window,
6072 COLOR_PAIR(tc->colorpair), NULL);
6073 free(id_str);
6074 prev_id = blame_line->id;
6075 } else {
6076 waddstr(view->window, "........");
6077 prev_id = NULL;
6079 } else {
6080 waddstr(view->window, "........");
6081 prev_id = NULL;
6084 if (nprinted == s->selected_line - 1)
6085 wstandend(view->window);
6086 waddstr(view->window, " ");
6088 if (view->ncols <= 9) {
6089 width = 9;
6090 } else if (s->first_displayed_line + nprinted ==
6091 s->matched_line &&
6092 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
6093 err = add_matched_line(&width, line, view->ncols - 9, 9,
6094 view->window, view->x, regmatch);
6095 if (err) {
6096 free(line);
6097 return err;
6099 width += 9;
6100 } else {
6101 int skip;
6102 err = format_line(&wline, &width, &skip, line,
6103 view->x, view->ncols - 9, 9, 1);
6104 if (err) {
6105 free(line);
6106 return err;
6108 waddwstr(view->window, &wline[skip]);
6109 width += 9;
6110 free(wline);
6111 wline = NULL;
6114 if (width <= view->ncols - 1)
6115 waddch(view->window, '\n');
6116 if (++nprinted == 1)
6117 s->first_displayed_line = lineno;
6119 free(line);
6120 s->last_displayed_line = lineno;
6122 view_border(view);
6124 if (tog_io.wait_for_ui) {
6125 if (s->blame_complete)
6126 tog_io.wait_for_ui = 0;
6129 return NULL;
6132 static const struct got_error *
6133 blame_cb(void *arg, int nlines, int lineno,
6134 struct got_commit_object *commit, struct got_object_id *id)
6136 const struct got_error *err = NULL;
6137 struct tog_blame_cb_args *a = arg;
6138 struct tog_blame_line *line;
6139 int errcode;
6141 if (nlines != a->nlines ||
6142 (lineno != -1 && lineno < 1) || lineno > a->nlines)
6143 return got_error(GOT_ERR_RANGE);
6145 errcode = pthread_mutex_lock(&tog_mutex);
6146 if (errcode)
6147 return got_error_set_errno(errcode, "pthread_mutex_lock");
6149 if (*a->quit) { /* user has quit the blame view */
6150 err = got_error(GOT_ERR_ITER_COMPLETED);
6151 goto done;
6154 if (lineno == -1)
6155 goto done; /* no change in this commit */
6157 line = &a->lines[lineno - 1];
6158 if (line->annotated)
6159 goto done;
6161 line->id = got_object_id_dup(id);
6162 if (line->id == NULL) {
6163 err = got_error_from_errno("got_object_id_dup");
6164 goto done;
6166 line->annotated = 1;
6167 done:
6168 errcode = pthread_mutex_unlock(&tog_mutex);
6169 if (errcode)
6170 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6171 return err;
6174 static void *
6175 blame_thread(void *arg)
6177 const struct got_error *err, *close_err;
6178 struct tog_blame_thread_args *ta = arg;
6179 struct tog_blame_cb_args *a = ta->cb_args;
6180 int errcode, fd1 = -1, fd2 = -1;
6181 FILE *f1 = NULL, *f2 = NULL;
6183 fd1 = got_opentempfd();
6184 if (fd1 == -1)
6185 return (void *)got_error_from_errno("got_opentempfd");
6187 fd2 = got_opentempfd();
6188 if (fd2 == -1) {
6189 err = got_error_from_errno("got_opentempfd");
6190 goto done;
6193 f1 = got_opentemp();
6194 if (f1 == NULL) {
6195 err = (void *)got_error_from_errno("got_opentemp");
6196 goto done;
6198 f2 = got_opentemp();
6199 if (f2 == NULL) {
6200 err = (void *)got_error_from_errno("got_opentemp");
6201 goto done;
6204 err = block_signals_used_by_main_thread();
6205 if (err)
6206 goto done;
6208 err = got_blame(ta->path, a->commit_id, ta->repo,
6209 tog_diff_algo, blame_cb, ta->cb_args,
6210 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
6211 if (err && err->code == GOT_ERR_CANCELLED)
6212 err = NULL;
6214 errcode = pthread_mutex_lock(&tog_mutex);
6215 if (errcode) {
6216 err = got_error_set_errno(errcode, "pthread_mutex_lock");
6217 goto done;
6220 close_err = got_repo_close(ta->repo);
6221 if (err == NULL)
6222 err = close_err;
6223 ta->repo = NULL;
6224 *ta->complete = 1;
6226 errcode = pthread_mutex_unlock(&tog_mutex);
6227 if (errcode && err == NULL)
6228 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
6230 done:
6231 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
6232 err = got_error_from_errno("close");
6233 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
6234 err = got_error_from_errno("close");
6235 if (f1 && fclose(f1) == EOF && err == NULL)
6236 err = got_error_from_errno("fclose");
6237 if (f2 && fclose(f2) == EOF && err == NULL)
6238 err = got_error_from_errno("fclose");
6240 return (void *)err;
6243 static struct got_object_id *
6244 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
6245 int first_displayed_line, int selected_line)
6247 struct tog_blame_line *line;
6249 if (nlines <= 0)
6250 return NULL;
6252 line = &lines[first_displayed_line - 1 + selected_line - 1];
6253 if (!line->annotated)
6254 return NULL;
6256 return line->id;
6259 static struct got_object_id *
6260 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
6261 int lineno)
6263 struct tog_blame_line *line;
6265 if (nlines <= 0 || lineno >= nlines)
6266 return NULL;
6268 line = &lines[lineno - 1];
6269 if (!line->annotated)
6270 return NULL;
6272 return line->id;
6275 static const struct got_error *
6276 stop_blame(struct tog_blame *blame)
6278 const struct got_error *err = NULL;
6279 int i;
6281 if (blame->thread) {
6282 int errcode;
6283 errcode = pthread_mutex_unlock(&tog_mutex);
6284 if (errcode)
6285 return got_error_set_errno(errcode,
6286 "pthread_mutex_unlock");
6287 errcode = pthread_join(blame->thread, (void **)&err);
6288 if (errcode)
6289 return got_error_set_errno(errcode, "pthread_join");
6290 errcode = pthread_mutex_lock(&tog_mutex);
6291 if (errcode)
6292 return got_error_set_errno(errcode,
6293 "pthread_mutex_lock");
6294 if (err && err->code == GOT_ERR_ITER_COMPLETED)
6295 err = NULL;
6296 blame->thread = NULL;
6298 if (blame->thread_args.repo) {
6299 const struct got_error *close_err;
6300 close_err = got_repo_close(blame->thread_args.repo);
6301 if (err == NULL)
6302 err = close_err;
6303 blame->thread_args.repo = NULL;
6305 if (blame->f) {
6306 if (fclose(blame->f) == EOF && err == NULL)
6307 err = got_error_from_errno("fclose");
6308 blame->f = NULL;
6310 if (blame->lines) {
6311 for (i = 0; i < blame->nlines; i++)
6312 free(blame->lines[i].id);
6313 free(blame->lines);
6314 blame->lines = NULL;
6316 free(blame->cb_args.commit_id);
6317 blame->cb_args.commit_id = NULL;
6318 if (blame->pack_fds) {
6319 const struct got_error *pack_err =
6320 got_repo_pack_fds_close(blame->pack_fds);
6321 if (err == NULL)
6322 err = pack_err;
6323 blame->pack_fds = NULL;
6325 return err;
6328 static const struct got_error *
6329 cancel_blame_view(void *arg)
6331 const struct got_error *err = NULL;
6332 int *done = arg;
6333 int errcode;
6335 errcode = pthread_mutex_lock(&tog_mutex);
6336 if (errcode)
6337 return got_error_set_errno(errcode,
6338 "pthread_mutex_unlock");
6340 if (*done)
6341 err = got_error(GOT_ERR_CANCELLED);
6343 errcode = pthread_mutex_unlock(&tog_mutex);
6344 if (errcode)
6345 return got_error_set_errno(errcode,
6346 "pthread_mutex_lock");
6348 return err;
6351 static const struct got_error *
6352 run_blame(struct tog_view *view)
6354 struct tog_blame_view_state *s = &view->state.blame;
6355 struct tog_blame *blame = &s->blame;
6356 const struct got_error *err = NULL;
6357 struct got_commit_object *commit = NULL;
6358 struct got_blob_object *blob = NULL;
6359 struct got_repository *thread_repo = NULL;
6360 struct got_object_id *obj_id = NULL;
6361 int obj_type, fd = -1;
6362 int *pack_fds = NULL;
6364 err = got_object_open_as_commit(&commit, s->repo,
6365 &s->blamed_commit->id);
6366 if (err)
6367 return err;
6369 fd = got_opentempfd();
6370 if (fd == -1) {
6371 err = got_error_from_errno("got_opentempfd");
6372 goto done;
6375 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
6376 if (err)
6377 goto done;
6379 err = got_object_get_type(&obj_type, s->repo, obj_id);
6380 if (err)
6381 goto done;
6383 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6384 err = got_error(GOT_ERR_OBJ_TYPE);
6385 goto done;
6388 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
6389 if (err)
6390 goto done;
6391 blame->f = got_opentemp();
6392 if (blame->f == NULL) {
6393 err = got_error_from_errno("got_opentemp");
6394 goto done;
6396 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
6397 &blame->line_offsets, blame->f, blob);
6398 if (err)
6399 goto done;
6400 if (blame->nlines == 0) {
6401 s->blame_complete = 1;
6402 goto done;
6405 /* Don't include \n at EOF in the blame line count. */
6406 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
6407 blame->nlines--;
6409 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
6410 if (blame->lines == NULL) {
6411 err = got_error_from_errno("calloc");
6412 goto done;
6415 err = got_repo_pack_fds_open(&pack_fds);
6416 if (err)
6417 goto done;
6418 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
6419 pack_fds);
6420 if (err)
6421 goto done;
6423 blame->pack_fds = pack_fds;
6424 blame->cb_args.view = view;
6425 blame->cb_args.lines = blame->lines;
6426 blame->cb_args.nlines = blame->nlines;
6427 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
6428 if (blame->cb_args.commit_id == NULL) {
6429 err = got_error_from_errno("got_object_id_dup");
6430 goto done;
6432 blame->cb_args.quit = &s->done;
6434 blame->thread_args.path = s->path;
6435 blame->thread_args.repo = thread_repo;
6436 blame->thread_args.cb_args = &blame->cb_args;
6437 blame->thread_args.complete = &s->blame_complete;
6438 blame->thread_args.cancel_cb = cancel_blame_view;
6439 blame->thread_args.cancel_arg = &s->done;
6440 s->blame_complete = 0;
6442 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
6443 s->first_displayed_line = 1;
6444 s->last_displayed_line = view->nlines;
6445 s->selected_line = 1;
6447 s->matched_line = 0;
6449 done:
6450 if (commit)
6451 got_object_commit_close(commit);
6452 if (fd != -1 && close(fd) == -1 && err == NULL)
6453 err = got_error_from_errno("close");
6454 if (blob)
6455 got_object_blob_close(blob);
6456 free(obj_id);
6457 if (err)
6458 stop_blame(blame);
6459 return err;
6462 static const struct got_error *
6463 open_blame_view(struct tog_view *view, char *path,
6464 struct got_object_id *commit_id, struct got_repository *repo)
6466 const struct got_error *err = NULL;
6467 struct tog_blame_view_state *s = &view->state.blame;
6469 STAILQ_INIT(&s->blamed_commits);
6471 s->path = strdup(path);
6472 if (s->path == NULL)
6473 return got_error_from_errno("strdup");
6475 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
6476 if (err) {
6477 free(s->path);
6478 return err;
6481 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
6482 s->first_displayed_line = 1;
6483 s->last_displayed_line = view->nlines;
6484 s->selected_line = 1;
6485 s->blame_complete = 0;
6486 s->repo = repo;
6487 s->commit_id = commit_id;
6488 memset(&s->blame, 0, sizeof(s->blame));
6490 STAILQ_INIT(&s->colors);
6491 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6492 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
6493 get_color_value("TOG_COLOR_COMMIT"));
6494 if (err)
6495 return err;
6498 view->show = show_blame_view;
6499 view->input = input_blame_view;
6500 view->reset = reset_blame_view;
6501 view->close = close_blame_view;
6502 view->search_start = search_start_blame_view;
6503 view->search_setup = search_setup_blame_view;
6504 view->search_next = search_next_view_match;
6506 return run_blame(view);
6509 static const struct got_error *
6510 close_blame_view(struct tog_view *view)
6512 const struct got_error *err = NULL;
6513 struct tog_blame_view_state *s = &view->state.blame;
6515 if (s->blame.thread)
6516 err = stop_blame(&s->blame);
6518 while (!STAILQ_EMPTY(&s->blamed_commits)) {
6519 struct got_object_qid *blamed_commit;
6520 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
6521 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6522 got_object_qid_free(blamed_commit);
6525 free(s->path);
6526 free_colors(&s->colors);
6527 return err;
6530 static const struct got_error *
6531 search_start_blame_view(struct tog_view *view)
6533 struct tog_blame_view_state *s = &view->state.blame;
6535 s->matched_line = 0;
6536 return NULL;
6539 static void
6540 search_setup_blame_view(struct tog_view *view, FILE **f, off_t **line_offsets,
6541 size_t *nlines, int **first, int **last, int **match, int **selected)
6543 struct tog_blame_view_state *s = &view->state.blame;
6545 *f = s->blame.f;
6546 *nlines = s->blame.nlines;
6547 *line_offsets = s->blame.line_offsets;
6548 *match = &s->matched_line;
6549 *first = &s->first_displayed_line;
6550 *last = &s->last_displayed_line;
6551 *selected = &s->selected_line;
6554 static const struct got_error *
6555 show_blame_view(struct tog_view *view)
6557 const struct got_error *err = NULL;
6558 struct tog_blame_view_state *s = &view->state.blame;
6559 int errcode;
6561 if (s->blame.thread == NULL && !s->blame_complete) {
6562 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
6563 &s->blame.thread_args);
6564 if (errcode)
6565 return got_error_set_errno(errcode, "pthread_create");
6567 if (!using_mock_io)
6568 halfdelay(1); /* fast refresh while annotating */
6571 if (s->blame_complete && !using_mock_io)
6572 halfdelay(10); /* disable fast refresh */
6574 err = draw_blame(view);
6576 view_border(view);
6577 return err;
6580 static const struct got_error *
6581 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
6582 struct got_repository *repo, struct got_object_id *id)
6584 struct tog_view *log_view;
6585 const struct got_error *err = NULL;
6587 *new_view = NULL;
6589 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6590 if (log_view == NULL)
6591 return got_error_from_errno("view_open");
6593 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
6594 if (err)
6595 view_close(log_view);
6596 else
6597 *new_view = log_view;
6599 return err;
6602 static const struct got_error *
6603 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
6605 const struct got_error *err = NULL, *thread_err = NULL;
6606 struct tog_view *diff_view;
6607 struct tog_blame_view_state *s = &view->state.blame;
6608 int eos, nscroll, begin_y = 0, begin_x = 0;
6610 eos = nscroll = view->nlines - 2;
6611 if (view_is_hsplit_top(view))
6612 --eos; /* border */
6614 switch (ch) {
6615 case '0':
6616 case '$':
6617 case KEY_RIGHT:
6618 case 'l':
6619 case KEY_LEFT:
6620 case 'h':
6621 horizontal_scroll_input(view, ch);
6622 break;
6623 case 'q':
6624 s->done = 1;
6625 break;
6626 case 'g':
6627 case KEY_HOME:
6628 s->selected_line = 1;
6629 s->first_displayed_line = 1;
6630 view->count = 0;
6631 break;
6632 case 'G':
6633 case KEY_END:
6634 if (s->blame.nlines < eos) {
6635 s->selected_line = s->blame.nlines;
6636 s->first_displayed_line = 1;
6637 } else {
6638 s->selected_line = eos;
6639 s->first_displayed_line = s->blame.nlines - (eos - 1);
6641 view->count = 0;
6642 break;
6643 case 'k':
6644 case KEY_UP:
6645 case CTRL('p'):
6646 if (s->selected_line > 1)
6647 s->selected_line--;
6648 else if (s->selected_line == 1 &&
6649 s->first_displayed_line > 1)
6650 s->first_displayed_line--;
6651 else
6652 view->count = 0;
6653 break;
6654 case CTRL('u'):
6655 case 'u':
6656 nscroll /= 2;
6657 /* FALL THROUGH */
6658 case KEY_PPAGE:
6659 case CTRL('b'):
6660 case 'b':
6661 if (s->first_displayed_line == 1) {
6662 if (view->count > 1)
6663 nscroll += nscroll;
6664 s->selected_line = MAX(1, s->selected_line - nscroll);
6665 view->count = 0;
6666 break;
6668 if (s->first_displayed_line > nscroll)
6669 s->first_displayed_line -= nscroll;
6670 else
6671 s->first_displayed_line = 1;
6672 break;
6673 case 'j':
6674 case KEY_DOWN:
6675 case CTRL('n'):
6676 if (s->selected_line < eos && s->first_displayed_line +
6677 s->selected_line <= s->blame.nlines)
6678 s->selected_line++;
6679 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
6680 s->first_displayed_line++;
6681 else
6682 view->count = 0;
6683 break;
6684 case 'c':
6685 case 'p': {
6686 struct got_object_id *id = NULL;
6688 view->count = 0;
6689 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6690 s->first_displayed_line, s->selected_line);
6691 if (id == NULL)
6692 break;
6693 if (ch == 'p') {
6694 struct got_commit_object *commit, *pcommit;
6695 struct got_object_qid *pid;
6696 struct got_object_id *blob_id = NULL;
6697 int obj_type;
6698 err = got_object_open_as_commit(&commit,
6699 s->repo, id);
6700 if (err)
6701 break;
6702 pid = STAILQ_FIRST(
6703 got_object_commit_get_parent_ids(commit));
6704 if (pid == NULL) {
6705 got_object_commit_close(commit);
6706 break;
6708 /* Check if path history ends here. */
6709 err = got_object_open_as_commit(&pcommit,
6710 s->repo, &pid->id);
6711 if (err)
6712 break;
6713 err = got_object_id_by_path(&blob_id, s->repo,
6714 pcommit, s->path);
6715 got_object_commit_close(pcommit);
6716 if (err) {
6717 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6718 err = NULL;
6719 got_object_commit_close(commit);
6720 break;
6722 err = got_object_get_type(&obj_type, s->repo,
6723 blob_id);
6724 free(blob_id);
6725 /* Can't blame non-blob type objects. */
6726 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6727 got_object_commit_close(commit);
6728 break;
6730 err = got_object_qid_alloc(&s->blamed_commit,
6731 &pid->id);
6732 got_object_commit_close(commit);
6733 } else {
6734 if (got_object_id_cmp(id,
6735 &s->blamed_commit->id) == 0)
6736 break;
6737 err = got_object_qid_alloc(&s->blamed_commit,
6738 id);
6740 if (err)
6741 break;
6742 s->done = 1;
6743 thread_err = stop_blame(&s->blame);
6744 s->done = 0;
6745 if (thread_err)
6746 break;
6747 STAILQ_INSERT_HEAD(&s->blamed_commits,
6748 s->blamed_commit, entry);
6749 err = run_blame(view);
6750 if (err)
6751 break;
6752 break;
6754 case 'C': {
6755 struct got_object_qid *first;
6757 view->count = 0;
6758 first = STAILQ_FIRST(&s->blamed_commits);
6759 if (!got_object_id_cmp(&first->id, s->commit_id))
6760 break;
6761 s->done = 1;
6762 thread_err = stop_blame(&s->blame);
6763 s->done = 0;
6764 if (thread_err)
6765 break;
6766 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6767 got_object_qid_free(s->blamed_commit);
6768 s->blamed_commit =
6769 STAILQ_FIRST(&s->blamed_commits);
6770 err = run_blame(view);
6771 if (err)
6772 break;
6773 break;
6775 case 'L':
6776 view->count = 0;
6777 s->id_to_log = get_selected_commit_id(s->blame.lines,
6778 s->blame.nlines, s->first_displayed_line, s->selected_line);
6779 if (s->id_to_log)
6780 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6781 break;
6782 case KEY_ENTER:
6783 case '\r': {
6784 struct got_object_id *id = NULL;
6785 struct got_object_qid *pid;
6786 struct got_commit_object *commit = NULL;
6788 view->count = 0;
6789 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6790 s->first_displayed_line, s->selected_line);
6791 if (id == NULL)
6792 break;
6793 err = got_object_open_as_commit(&commit, s->repo, id);
6794 if (err)
6795 break;
6796 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6797 if (*new_view) {
6798 /* traversed from diff view, release diff resources */
6799 err = close_diff_view(*new_view);
6800 if (err)
6801 break;
6802 diff_view = *new_view;
6803 } else {
6804 if (view_is_parent_view(view))
6805 view_get_split(view, &begin_y, &begin_x);
6807 diff_view = view_open(0, 0, begin_y, begin_x,
6808 TOG_VIEW_DIFF);
6809 if (diff_view == NULL) {
6810 got_object_commit_close(commit);
6811 err = got_error_from_errno("view_open");
6812 break;
6815 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6816 id, NULL, NULL, 3, 0, 0, view, s->repo);
6817 got_object_commit_close(commit);
6818 if (err) {
6819 view_close(diff_view);
6820 break;
6822 s->last_diffed_line = s->first_displayed_line - 1 +
6823 s->selected_line;
6824 if (*new_view)
6825 break; /* still open from active diff view */
6826 if (view_is_parent_view(view) &&
6827 view->mode == TOG_VIEW_SPLIT_HRZN) {
6828 err = view_init_hsplit(view, begin_y);
6829 if (err)
6830 break;
6833 view->focussed = 0;
6834 diff_view->focussed = 1;
6835 diff_view->mode = view->mode;
6836 diff_view->nlines = view->lines - begin_y;
6837 if (view_is_parent_view(view)) {
6838 view_transfer_size(diff_view, view);
6839 err = view_close_child(view);
6840 if (err)
6841 break;
6842 err = view_set_child(view, diff_view);
6843 if (err)
6844 break;
6845 view->focus_child = 1;
6846 } else
6847 *new_view = diff_view;
6848 if (err)
6849 break;
6850 break;
6852 case CTRL('d'):
6853 case 'd':
6854 nscroll /= 2;
6855 /* FALL THROUGH */
6856 case KEY_NPAGE:
6857 case CTRL('f'):
6858 case 'f':
6859 case ' ':
6860 if (s->last_displayed_line >= s->blame.nlines &&
6861 s->selected_line >= MIN(s->blame.nlines,
6862 view->nlines - 2)) {
6863 view->count = 0;
6864 break;
6866 if (s->last_displayed_line >= s->blame.nlines &&
6867 s->selected_line < view->nlines - 2) {
6868 s->selected_line +=
6869 MIN(nscroll, s->last_displayed_line -
6870 s->first_displayed_line - s->selected_line + 1);
6872 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6873 s->first_displayed_line += nscroll;
6874 else
6875 s->first_displayed_line =
6876 s->blame.nlines - (view->nlines - 3);
6877 break;
6878 case KEY_RESIZE:
6879 if (s->selected_line > view->nlines - 2) {
6880 s->selected_line = MIN(s->blame.nlines,
6881 view->nlines - 2);
6883 break;
6884 default:
6885 view->count = 0;
6886 break;
6888 return thread_err ? thread_err : err;
6891 static const struct got_error *
6892 reset_blame_view(struct tog_view *view)
6894 const struct got_error *err;
6895 struct tog_blame_view_state *s = &view->state.blame;
6897 view->count = 0;
6898 s->done = 1;
6899 err = stop_blame(&s->blame);
6900 s->done = 0;
6901 if (err)
6902 return err;
6903 return run_blame(view);
6906 static const struct got_error *
6907 cmd_blame(int argc, char *argv[])
6909 const struct got_error *error;
6910 struct got_repository *repo = NULL;
6911 struct got_worktree *worktree = NULL;
6912 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6913 char *link_target = NULL;
6914 struct got_object_id *commit_id = NULL;
6915 struct got_commit_object *commit = NULL;
6916 char *commit_id_str = NULL;
6917 int ch;
6918 struct tog_view *view = NULL;
6919 int *pack_fds = NULL;
6921 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6922 switch (ch) {
6923 case 'c':
6924 commit_id_str = optarg;
6925 break;
6926 case 'r':
6927 repo_path = realpath(optarg, NULL);
6928 if (repo_path == NULL)
6929 return got_error_from_errno2("realpath",
6930 optarg);
6931 break;
6932 default:
6933 usage_blame();
6934 /* NOTREACHED */
6938 argc -= optind;
6939 argv += optind;
6941 if (argc != 1)
6942 usage_blame();
6944 error = got_repo_pack_fds_open(&pack_fds);
6945 if (error != NULL)
6946 goto done;
6948 if (repo_path == NULL) {
6949 cwd = getcwd(NULL, 0);
6950 if (cwd == NULL)
6951 return got_error_from_errno("getcwd");
6952 error = got_worktree_open(&worktree, cwd);
6953 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6954 goto done;
6955 if (worktree)
6956 repo_path =
6957 strdup(got_worktree_get_repo_path(worktree));
6958 else
6959 repo_path = strdup(cwd);
6960 if (repo_path == NULL) {
6961 error = got_error_from_errno("strdup");
6962 goto done;
6966 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6967 if (error != NULL)
6968 goto done;
6970 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6971 worktree);
6972 if (error)
6973 goto done;
6975 init_curses();
6977 error = apply_unveil(got_repo_get_path(repo), NULL);
6978 if (error)
6979 goto done;
6981 error = tog_load_refs(repo, 0);
6982 if (error)
6983 goto done;
6985 if (commit_id_str == NULL) {
6986 struct got_reference *head_ref;
6987 error = got_ref_open(&head_ref, repo, worktree ?
6988 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6989 if (error != NULL)
6990 goto done;
6991 error = got_ref_resolve(&commit_id, repo, head_ref);
6992 got_ref_close(head_ref);
6993 } else {
6994 error = got_repo_match_object_id(&commit_id, NULL,
6995 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6997 if (error != NULL)
6998 goto done;
7000 error = got_object_open_as_commit(&commit, repo, commit_id);
7001 if (error)
7002 goto done;
7004 error = got_object_resolve_symlinks(&link_target, in_repo_path,
7005 commit, repo);
7006 if (error)
7007 goto done;
7009 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
7010 if (view == NULL) {
7011 error = got_error_from_errno("view_open");
7012 goto done;
7014 error = open_blame_view(view, link_target ? link_target : in_repo_path,
7015 commit_id, repo);
7016 if (error != NULL) {
7017 if (view->close == NULL)
7018 close_blame_view(view);
7019 view_close(view);
7020 goto done;
7022 if (worktree) {
7023 /* Release work tree lock. */
7024 got_worktree_close(worktree);
7025 worktree = NULL;
7027 error = view_loop(view);
7028 done:
7029 free(repo_path);
7030 free(in_repo_path);
7031 free(link_target);
7032 free(cwd);
7033 free(commit_id);
7034 if (commit)
7035 got_object_commit_close(commit);
7036 if (worktree)
7037 got_worktree_close(worktree);
7038 if (repo) {
7039 const struct got_error *close_err = got_repo_close(repo);
7040 if (error == NULL)
7041 error = close_err;
7043 if (pack_fds) {
7044 const struct got_error *pack_err =
7045 got_repo_pack_fds_close(pack_fds);
7046 if (error == NULL)
7047 error = pack_err;
7049 tog_free_refs();
7050 return error;
7053 static const struct got_error *
7054 draw_tree_entries(struct tog_view *view, const char *parent_path)
7056 struct tog_tree_view_state *s = &view->state.tree;
7057 const struct got_error *err = NULL;
7058 struct got_tree_entry *te;
7059 wchar_t *wline;
7060 char *index = NULL;
7061 struct tog_color *tc;
7062 int width, n, nentries, scrollx, i = 1;
7063 int limit = view->nlines;
7065 s->ndisplayed = 0;
7066 if (view_is_hsplit_top(view))
7067 --limit; /* border */
7069 werase(view->window);
7071 if (limit == 0)
7072 return NULL;
7074 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
7075 0, 0);
7076 if (err)
7077 return err;
7078 if (view_needs_focus_indication(view))
7079 wstandout(view->window);
7080 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
7081 if (tc)
7082 wattr_on(view->window, COLOR_PAIR(tc->colorpair), NULL);
7083 waddwstr(view->window, wline);
7084 free(wline);
7085 wline = NULL;
7086 while (width++ < view->ncols)
7087 waddch(view->window, ' ');
7088 if (tc)
7089 wattr_off(view->window, COLOR_PAIR(tc->colorpair), NULL);
7090 if (view_needs_focus_indication(view))
7091 wstandend(view->window);
7092 if (--limit <= 0)
7093 return NULL;
7095 i += s->selected;
7096 if (s->first_displayed_entry) {
7097 i += got_tree_entry_get_index(s->first_displayed_entry);
7098 if (s->tree != s->root)
7099 ++i; /* account for ".." entry */
7101 nentries = got_object_tree_get_nentries(s->tree);
7102 if (asprintf(&index, "[%d/%d] %s",
7103 i, nentries + (s->tree == s->root ? 0 : 1), parent_path) == -1)
7104 return got_error_from_errno("asprintf");
7105 err = format_line(&wline, &width, NULL, index, 0, view->ncols, 0, 0);
7106 free(index);
7107 if (err)
7108 return err;
7109 waddwstr(view->window, wline);
7110 free(wline);
7111 wline = NULL;
7112 if (width < view->ncols - 1)
7113 waddch(view->window, '\n');
7114 if (--limit <= 0)
7115 return NULL;
7116 waddch(view->window, '\n');
7117 if (--limit <= 0)
7118 return NULL;
7120 if (s->first_displayed_entry == NULL) {
7121 te = got_object_tree_get_first_entry(s->tree);
7122 if (s->selected == 0) {
7123 if (view->focussed)
7124 wstandout(view->window);
7125 s->selected_entry = NULL;
7127 waddstr(view->window, " ..\n"); /* parent directory */
7128 if (s->selected == 0 && view->focussed)
7129 wstandend(view->window);
7130 s->ndisplayed++;
7131 if (--limit <= 0)
7132 return NULL;
7133 n = 1;
7134 } else {
7135 n = 0;
7136 te = s->first_displayed_entry;
7139 view->maxx = 0;
7140 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
7141 char *line = NULL, *id_str = NULL, *link_target = NULL;
7142 const char *modestr = "";
7143 mode_t mode;
7145 te = got_object_tree_get_entry(s->tree, i);
7146 mode = got_tree_entry_get_mode(te);
7148 if (s->show_ids) {
7149 err = got_object_id_str(&id_str,
7150 got_tree_entry_get_id(te));
7151 if (err)
7152 return got_error_from_errno(
7153 "got_object_id_str");
7155 if (got_object_tree_entry_is_submodule(te))
7156 modestr = "$";
7157 else if (S_ISLNK(mode)) {
7158 int i;
7160 err = got_tree_entry_get_symlink_target(&link_target,
7161 te, s->repo);
7162 if (err) {
7163 free(id_str);
7164 return err;
7166 for (i = 0; i < strlen(link_target); i++) {
7167 if (!isprint((unsigned char)link_target[i]))
7168 link_target[i] = '?';
7170 modestr = "@";
7172 else if (S_ISDIR(mode))
7173 modestr = "/";
7174 else if (mode & S_IXUSR)
7175 modestr = "*";
7176 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
7177 got_tree_entry_get_name(te), modestr,
7178 link_target ? " -> ": "",
7179 link_target ? link_target : "") == -1) {
7180 free(id_str);
7181 free(link_target);
7182 return got_error_from_errno("asprintf");
7184 free(id_str);
7185 free(link_target);
7187 /* use full line width to determine view->maxx */
7188 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
7189 if (err) {
7190 free(line);
7191 break;
7193 view->maxx = MAX(view->maxx, width);
7194 free(wline);
7195 wline = NULL;
7197 err = format_line(&wline, &width, &scrollx, line, view->x,
7198 view->ncols, 0, 0);
7199 if (err) {
7200 free(line);
7201 break;
7203 if (n == s->selected) {
7204 if (view->focussed)
7205 wstandout(view->window);
7206 s->selected_entry = te;
7208 tc = match_color(&s->colors, line);
7209 if (tc)
7210 wattr_on(view->window,
7211 COLOR_PAIR(tc->colorpair), NULL);
7212 waddwstr(view->window, &wline[scrollx]);
7213 if (tc)
7214 wattr_off(view->window,
7215 COLOR_PAIR(tc->colorpair), NULL);
7216 if (width < view->ncols)
7217 waddch(view->window, '\n');
7218 if (n == s->selected && view->focussed)
7219 wstandend(view->window);
7220 free(line);
7221 free(wline);
7222 wline = NULL;
7223 n++;
7224 s->ndisplayed++;
7225 s->last_displayed_entry = te;
7226 if (--limit <= 0)
7227 break;
7230 return err;
7233 static void
7234 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
7236 struct got_tree_entry *te;
7237 int isroot = s->tree == s->root;
7238 int i = 0;
7240 if (s->first_displayed_entry == NULL)
7241 return;
7243 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
7244 while (i++ < maxscroll) {
7245 if (te == NULL) {
7246 if (!isroot)
7247 s->first_displayed_entry = NULL;
7248 break;
7250 s->first_displayed_entry = te;
7251 te = got_tree_entry_get_prev(s->tree, te);
7255 static const struct got_error *
7256 tree_scroll_down(struct tog_view *view, int maxscroll)
7258 struct tog_tree_view_state *s = &view->state.tree;
7259 struct got_tree_entry *next, *last;
7260 int n = 0;
7262 if (s->first_displayed_entry)
7263 next = got_tree_entry_get_next(s->tree,
7264 s->first_displayed_entry);
7265 else
7266 next = got_object_tree_get_first_entry(s->tree);
7268 last = s->last_displayed_entry;
7269 while (next && n++ < maxscroll) {
7270 if (last) {
7271 s->last_displayed_entry = last;
7272 last = got_tree_entry_get_next(s->tree, last);
7274 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
7275 s->first_displayed_entry = next;
7276 next = got_tree_entry_get_next(s->tree, next);
7280 return NULL;
7283 static const struct got_error *
7284 tree_entry_path(char **path, struct tog_parent_trees *parents,
7285 struct got_tree_entry *te)
7287 const struct got_error *err = NULL;
7288 struct tog_parent_tree *pt;
7289 size_t len = 2; /* for leading slash and NUL */
7291 TAILQ_FOREACH(pt, parents, entry)
7292 len += strlen(got_tree_entry_get_name(pt->selected_entry))
7293 + 1 /* slash */;
7294 if (te)
7295 len += strlen(got_tree_entry_get_name(te));
7297 *path = calloc(1, len);
7298 if (path == NULL)
7299 return got_error_from_errno("calloc");
7301 (*path)[0] = '/';
7302 pt = TAILQ_LAST(parents, tog_parent_trees);
7303 while (pt) {
7304 const char *name = got_tree_entry_get_name(pt->selected_entry);
7305 if (strlcat(*path, name, len) >= len) {
7306 err = got_error(GOT_ERR_NO_SPACE);
7307 goto done;
7309 if (strlcat(*path, "/", len) >= len) {
7310 err = got_error(GOT_ERR_NO_SPACE);
7311 goto done;
7313 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
7315 if (te) {
7316 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
7317 err = got_error(GOT_ERR_NO_SPACE);
7318 goto done;
7321 done:
7322 if (err) {
7323 free(*path);
7324 *path = NULL;
7326 return err;
7329 static const struct got_error *
7330 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7331 struct got_tree_entry *te, struct tog_parent_trees *parents,
7332 struct got_object_id *commit_id, struct got_repository *repo)
7334 const struct got_error *err = NULL;
7335 char *path;
7336 struct tog_view *blame_view;
7338 *new_view = NULL;
7340 err = tree_entry_path(&path, parents, te);
7341 if (err)
7342 return err;
7344 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
7345 if (blame_view == NULL) {
7346 err = got_error_from_errno("view_open");
7347 goto done;
7350 err = open_blame_view(blame_view, path, commit_id, repo);
7351 if (err) {
7352 if (err->code == GOT_ERR_CANCELLED)
7353 err = NULL;
7354 view_close(blame_view);
7355 } else
7356 *new_view = blame_view;
7357 done:
7358 free(path);
7359 return err;
7362 static const struct got_error *
7363 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
7364 struct tog_tree_view_state *s)
7366 struct tog_view *log_view;
7367 const struct got_error *err = NULL;
7368 char *path;
7370 *new_view = NULL;
7372 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7373 if (log_view == NULL)
7374 return got_error_from_errno("view_open");
7376 err = tree_entry_path(&path, &s->parents, s->selected_entry);
7377 if (err)
7378 return err;
7380 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
7381 path, 0);
7382 if (err)
7383 view_close(log_view);
7384 else
7385 *new_view = log_view;
7386 free(path);
7387 return err;
7390 static const struct got_error *
7391 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
7392 const char *head_ref_name, struct got_repository *repo)
7394 const struct got_error *err = NULL;
7395 char *commit_id_str = NULL;
7396 struct tog_tree_view_state *s = &view->state.tree;
7397 struct got_commit_object *commit = NULL;
7399 TAILQ_INIT(&s->parents);
7400 STAILQ_INIT(&s->colors);
7402 s->commit_id = got_object_id_dup(commit_id);
7403 if (s->commit_id == NULL) {
7404 err = got_error_from_errno("got_object_id_dup");
7405 goto done;
7408 err = got_object_open_as_commit(&commit, repo, commit_id);
7409 if (err)
7410 goto done;
7413 * The root is opened here and will be closed when the view is closed.
7414 * Any visited subtrees and their path-wise parents are opened and
7415 * closed on demand.
7417 err = got_object_open_as_tree(&s->root, repo,
7418 got_object_commit_get_tree_id(commit));
7419 if (err)
7420 goto done;
7421 s->tree = s->root;
7423 err = got_object_id_str(&commit_id_str, commit_id);
7424 if (err != NULL)
7425 goto done;
7427 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
7428 err = got_error_from_errno("asprintf");
7429 goto done;
7432 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
7433 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
7434 if (head_ref_name) {
7435 s->head_ref_name = strdup(head_ref_name);
7436 if (s->head_ref_name == NULL) {
7437 err = got_error_from_errno("strdup");
7438 goto done;
7441 s->repo = repo;
7443 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7444 err = add_color(&s->colors, "\\$$",
7445 TOG_COLOR_TREE_SUBMODULE,
7446 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
7447 if (err)
7448 goto done;
7449 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
7450 get_color_value("TOG_COLOR_TREE_SYMLINK"));
7451 if (err)
7452 goto done;
7453 err = add_color(&s->colors, "/$",
7454 TOG_COLOR_TREE_DIRECTORY,
7455 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
7456 if (err)
7457 goto done;
7459 err = add_color(&s->colors, "\\*$",
7460 TOG_COLOR_TREE_EXECUTABLE,
7461 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
7462 if (err)
7463 goto done;
7465 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
7466 get_color_value("TOG_COLOR_COMMIT"));
7467 if (err)
7468 goto done;
7471 view->show = show_tree_view;
7472 view->input = input_tree_view;
7473 view->close = close_tree_view;
7474 view->search_start = search_start_tree_view;
7475 view->search_next = search_next_tree_view;
7476 done:
7477 free(commit_id_str);
7478 if (commit)
7479 got_object_commit_close(commit);
7480 if (err) {
7481 if (view->close == NULL)
7482 close_tree_view(view);
7483 view_close(view);
7485 return err;
7488 static const struct got_error *
7489 close_tree_view(struct tog_view *view)
7491 struct tog_tree_view_state *s = &view->state.tree;
7493 free_colors(&s->colors);
7494 free(s->tree_label);
7495 s->tree_label = NULL;
7496 free(s->commit_id);
7497 s->commit_id = NULL;
7498 free(s->head_ref_name);
7499 s->head_ref_name = NULL;
7500 while (!TAILQ_EMPTY(&s->parents)) {
7501 struct tog_parent_tree *parent;
7502 parent = TAILQ_FIRST(&s->parents);
7503 TAILQ_REMOVE(&s->parents, parent, entry);
7504 if (parent->tree != s->root)
7505 got_object_tree_close(parent->tree);
7506 free(parent);
7509 if (s->tree != NULL && s->tree != s->root)
7510 got_object_tree_close(s->tree);
7511 if (s->root)
7512 got_object_tree_close(s->root);
7513 return NULL;
7516 static const struct got_error *
7517 search_start_tree_view(struct tog_view *view)
7519 struct tog_tree_view_state *s = &view->state.tree;
7521 s->matched_entry = NULL;
7522 return NULL;
7525 static int
7526 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
7528 regmatch_t regmatch;
7530 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
7531 0) == 0;
7534 static const struct got_error *
7535 search_next_tree_view(struct tog_view *view)
7537 struct tog_tree_view_state *s = &view->state.tree;
7538 struct got_tree_entry *te = NULL;
7540 if (!view->searching) {
7541 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7542 return NULL;
7545 if (s->matched_entry) {
7546 if (view->searching == TOG_SEARCH_FORWARD) {
7547 if (s->selected_entry)
7548 te = got_tree_entry_get_next(s->tree,
7549 s->selected_entry);
7550 else
7551 te = got_object_tree_get_first_entry(s->tree);
7552 } else {
7553 if (s->selected_entry == NULL)
7554 te = got_object_tree_get_last_entry(s->tree);
7555 else
7556 te = got_tree_entry_get_prev(s->tree,
7557 s->selected_entry);
7559 } else {
7560 if (s->selected_entry)
7561 te = s->selected_entry;
7562 else if (view->searching == TOG_SEARCH_FORWARD)
7563 te = got_object_tree_get_first_entry(s->tree);
7564 else
7565 te = got_object_tree_get_last_entry(s->tree);
7568 while (1) {
7569 if (te == NULL) {
7570 if (s->matched_entry == NULL) {
7571 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7572 return NULL;
7574 if (view->searching == TOG_SEARCH_FORWARD)
7575 te = got_object_tree_get_first_entry(s->tree);
7576 else
7577 te = got_object_tree_get_last_entry(s->tree);
7580 if (match_tree_entry(te, &view->regex)) {
7581 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7582 s->matched_entry = te;
7583 break;
7586 if (view->searching == TOG_SEARCH_FORWARD)
7587 te = got_tree_entry_get_next(s->tree, te);
7588 else
7589 te = got_tree_entry_get_prev(s->tree, te);
7592 if (s->matched_entry) {
7593 s->first_displayed_entry = s->matched_entry;
7594 s->selected = 0;
7597 return NULL;
7600 static const struct got_error *
7601 show_tree_view(struct tog_view *view)
7603 const struct got_error *err = NULL;
7604 struct tog_tree_view_state *s = &view->state.tree;
7605 char *parent_path;
7607 err = tree_entry_path(&parent_path, &s->parents, NULL);
7608 if (err)
7609 return err;
7611 err = draw_tree_entries(view, parent_path);
7612 free(parent_path);
7614 view_border(view);
7615 return err;
7618 static const struct got_error *
7619 tree_goto_line(struct tog_view *view, int nlines)
7621 const struct got_error *err = NULL;
7622 struct tog_tree_view_state *s = &view->state.tree;
7623 struct got_tree_entry **fte, **lte, **ste;
7624 int g, last, first = 1, i = 1;
7625 int root = s->tree == s->root;
7626 int off = root ? 1 : 2;
7628 g = view->gline;
7629 view->gline = 0;
7631 if (g == 0)
7632 g = 1;
7633 else if (g > got_object_tree_get_nentries(s->tree))
7634 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
7636 fte = &s->first_displayed_entry;
7637 lte = &s->last_displayed_entry;
7638 ste = &s->selected_entry;
7640 if (*fte != NULL) {
7641 first = got_tree_entry_get_index(*fte);
7642 first += off; /* account for ".." */
7644 last = got_tree_entry_get_index(*lte);
7645 last += off;
7647 if (g >= first && g <= last && g - first < nlines) {
7648 s->selected = g - first;
7649 return NULL; /* gline is on the current page */
7652 if (*ste != NULL) {
7653 i = got_tree_entry_get_index(*ste);
7654 i += off;
7657 if (i < g) {
7658 err = tree_scroll_down(view, g - i);
7659 if (err)
7660 return err;
7661 if (got_tree_entry_get_index(*lte) >=
7662 got_object_tree_get_nentries(s->tree) - 1 &&
7663 first + s->selected < g &&
7664 s->selected < s->ndisplayed - 1) {
7665 first = got_tree_entry_get_index(*fte);
7666 first += off;
7667 s->selected = g - first;
7669 } else if (i > g)
7670 tree_scroll_up(s, i - g);
7672 if (g < nlines &&
7673 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
7674 s->selected = g - 1;
7676 return NULL;
7679 static const struct got_error *
7680 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
7682 const struct got_error *err = NULL;
7683 struct tog_tree_view_state *s = &view->state.tree;
7684 struct got_tree_entry *te;
7685 int n, nscroll = view->nlines - 3;
7687 if (view->gline)
7688 return tree_goto_line(view, nscroll);
7690 switch (ch) {
7691 case '0':
7692 case '$':
7693 case KEY_RIGHT:
7694 case 'l':
7695 case KEY_LEFT:
7696 case 'h':
7697 horizontal_scroll_input(view, ch);
7698 break;
7699 case 'i':
7700 s->show_ids = !s->show_ids;
7701 view->count = 0;
7702 break;
7703 case 'L':
7704 view->count = 0;
7705 if (!s->selected_entry)
7706 break;
7707 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7708 break;
7709 case 'R':
7710 view->count = 0;
7711 err = view_request_new(new_view, view, TOG_VIEW_REF);
7712 break;
7713 case 'g':
7714 case '=':
7715 case KEY_HOME:
7716 s->selected = 0;
7717 view->count = 0;
7718 if (s->tree == s->root)
7719 s->first_displayed_entry =
7720 got_object_tree_get_first_entry(s->tree);
7721 else
7722 s->first_displayed_entry = NULL;
7723 break;
7724 case 'G':
7725 case '*':
7726 case KEY_END: {
7727 int eos = view->nlines - 3;
7729 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7730 --eos; /* border */
7731 s->selected = 0;
7732 view->count = 0;
7733 te = got_object_tree_get_last_entry(s->tree);
7734 for (n = 0; n < eos; n++) {
7735 if (te == NULL) {
7736 if (s->tree != s->root) {
7737 s->first_displayed_entry = NULL;
7738 n++;
7740 break;
7742 s->first_displayed_entry = te;
7743 te = got_tree_entry_get_prev(s->tree, te);
7745 if (n > 0)
7746 s->selected = n - 1;
7747 break;
7749 case 'k':
7750 case KEY_UP:
7751 case CTRL('p'):
7752 if (s->selected > 0) {
7753 s->selected--;
7754 break;
7756 tree_scroll_up(s, 1);
7757 if (s->selected_entry == NULL ||
7758 (s->tree == s->root && s->selected_entry ==
7759 got_object_tree_get_first_entry(s->tree)))
7760 view->count = 0;
7761 break;
7762 case CTRL('u'):
7763 case 'u':
7764 nscroll /= 2;
7765 /* FALL THROUGH */
7766 case KEY_PPAGE:
7767 case CTRL('b'):
7768 case 'b':
7769 if (s->tree == s->root) {
7770 if (got_object_tree_get_first_entry(s->tree) ==
7771 s->first_displayed_entry)
7772 s->selected -= MIN(s->selected, nscroll);
7773 } else {
7774 if (s->first_displayed_entry == NULL)
7775 s->selected -= MIN(s->selected, nscroll);
7777 tree_scroll_up(s, MAX(0, nscroll));
7778 if (s->selected_entry == NULL ||
7779 (s->tree == s->root && s->selected_entry ==
7780 got_object_tree_get_first_entry(s->tree)))
7781 view->count = 0;
7782 break;
7783 case 'j':
7784 case KEY_DOWN:
7785 case CTRL('n'):
7786 if (s->selected < s->ndisplayed - 1) {
7787 s->selected++;
7788 break;
7790 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7791 == NULL) {
7792 /* can't scroll any further */
7793 view->count = 0;
7794 break;
7796 tree_scroll_down(view, 1);
7797 break;
7798 case CTRL('d'):
7799 case 'd':
7800 nscroll /= 2;
7801 /* FALL THROUGH */
7802 case KEY_NPAGE:
7803 case CTRL('f'):
7804 case 'f':
7805 case ' ':
7806 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7807 == NULL) {
7808 /* can't scroll any further; move cursor down */
7809 if (s->selected < s->ndisplayed - 1)
7810 s->selected += MIN(nscroll,
7811 s->ndisplayed - s->selected - 1);
7812 else
7813 view->count = 0;
7814 break;
7816 tree_scroll_down(view, nscroll);
7817 break;
7818 case KEY_ENTER:
7819 case '\r':
7820 case KEY_BACKSPACE:
7821 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7822 struct tog_parent_tree *parent;
7823 /* user selected '..' */
7824 if (s->tree == s->root) {
7825 view->count = 0;
7826 break;
7828 parent = TAILQ_FIRST(&s->parents);
7829 TAILQ_REMOVE(&s->parents, parent,
7830 entry);
7831 got_object_tree_close(s->tree);
7832 s->tree = parent->tree;
7833 s->first_displayed_entry =
7834 parent->first_displayed_entry;
7835 s->selected_entry =
7836 parent->selected_entry;
7837 s->selected = parent->selected;
7838 if (s->selected > view->nlines - 3) {
7839 err = offset_selection_down(view);
7840 if (err)
7841 break;
7843 free(parent);
7844 } else if (S_ISDIR(got_tree_entry_get_mode(
7845 s->selected_entry))) {
7846 struct got_tree_object *subtree;
7847 view->count = 0;
7848 err = got_object_open_as_tree(&subtree, s->repo,
7849 got_tree_entry_get_id(s->selected_entry));
7850 if (err)
7851 break;
7852 err = tree_view_visit_subtree(s, subtree);
7853 if (err) {
7854 got_object_tree_close(subtree);
7855 break;
7857 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7858 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7859 break;
7860 case KEY_RESIZE:
7861 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7862 s->selected = view->nlines - 4;
7863 view->count = 0;
7864 break;
7865 default:
7866 view->count = 0;
7867 break;
7870 return err;
7873 __dead static void
7874 usage_tree(void)
7876 endwin();
7877 fprintf(stderr,
7878 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7879 getprogname());
7880 exit(1);
7883 static const struct got_error *
7884 cmd_tree(int argc, char *argv[])
7886 const struct got_error *error;
7887 struct got_repository *repo = NULL;
7888 struct got_worktree *worktree = NULL;
7889 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7890 struct got_object_id *commit_id = NULL;
7891 struct got_commit_object *commit = NULL;
7892 const char *commit_id_arg = NULL;
7893 char *label = NULL;
7894 struct got_reference *ref = NULL;
7895 const char *head_ref_name = NULL;
7896 int ch;
7897 struct tog_view *view;
7898 int *pack_fds = NULL;
7900 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7901 switch (ch) {
7902 case 'c':
7903 commit_id_arg = optarg;
7904 break;
7905 case 'r':
7906 repo_path = realpath(optarg, NULL);
7907 if (repo_path == NULL)
7908 return got_error_from_errno2("realpath",
7909 optarg);
7910 break;
7911 default:
7912 usage_tree();
7913 /* NOTREACHED */
7917 argc -= optind;
7918 argv += optind;
7920 if (argc > 1)
7921 usage_tree();
7923 error = got_repo_pack_fds_open(&pack_fds);
7924 if (error != NULL)
7925 goto done;
7927 if (repo_path == NULL) {
7928 cwd = getcwd(NULL, 0);
7929 if (cwd == NULL)
7930 return got_error_from_errno("getcwd");
7931 error = got_worktree_open(&worktree, cwd);
7932 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7933 goto done;
7934 if (worktree)
7935 repo_path =
7936 strdup(got_worktree_get_repo_path(worktree));
7937 else
7938 repo_path = strdup(cwd);
7939 if (repo_path == NULL) {
7940 error = got_error_from_errno("strdup");
7941 goto done;
7945 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7946 if (error != NULL)
7947 goto done;
7949 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7950 repo, worktree);
7951 if (error)
7952 goto done;
7954 init_curses();
7956 error = apply_unveil(got_repo_get_path(repo), NULL);
7957 if (error)
7958 goto done;
7960 error = tog_load_refs(repo, 0);
7961 if (error)
7962 goto done;
7964 if (commit_id_arg == NULL) {
7965 error = got_repo_match_object_id(&commit_id, &label,
7966 worktree ? got_worktree_get_head_ref_name(worktree) :
7967 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7968 if (error)
7969 goto done;
7970 head_ref_name = label;
7971 } else {
7972 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7973 if (error == NULL)
7974 head_ref_name = got_ref_get_name(ref);
7975 else if (error->code != GOT_ERR_NOT_REF)
7976 goto done;
7977 error = got_repo_match_object_id(&commit_id, NULL,
7978 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7979 if (error)
7980 goto done;
7983 error = got_object_open_as_commit(&commit, repo, commit_id);
7984 if (error)
7985 goto done;
7987 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7988 if (view == NULL) {
7989 error = got_error_from_errno("view_open");
7990 goto done;
7992 error = open_tree_view(view, commit_id, head_ref_name, repo);
7993 if (error)
7994 goto done;
7995 if (!got_path_is_root_dir(in_repo_path)) {
7996 error = tree_view_walk_path(&view->state.tree, commit,
7997 in_repo_path);
7998 if (error)
7999 goto done;
8002 if (worktree) {
8003 /* Release work tree lock. */
8004 got_worktree_close(worktree);
8005 worktree = NULL;
8007 error = view_loop(view);
8008 done:
8009 free(repo_path);
8010 free(cwd);
8011 free(commit_id);
8012 free(label);
8013 if (ref)
8014 got_ref_close(ref);
8015 if (repo) {
8016 const struct got_error *close_err = got_repo_close(repo);
8017 if (error == NULL)
8018 error = close_err;
8020 if (pack_fds) {
8021 const struct got_error *pack_err =
8022 got_repo_pack_fds_close(pack_fds);
8023 if (error == NULL)
8024 error = pack_err;
8026 tog_free_refs();
8027 return error;
8030 static const struct got_error *
8031 ref_view_load_refs(struct tog_ref_view_state *s)
8033 struct got_reflist_entry *sre;
8034 struct tog_reflist_entry *re;
8036 s->nrefs = 0;
8037 TAILQ_FOREACH(sre, &tog_refs, entry) {
8038 if (strncmp(got_ref_get_name(sre->ref),
8039 "refs/got/", 9) == 0 &&
8040 strncmp(got_ref_get_name(sre->ref),
8041 "refs/got/backup/", 16) != 0)
8042 continue;
8044 re = malloc(sizeof(*re));
8045 if (re == NULL)
8046 return got_error_from_errno("malloc");
8048 re->ref = got_ref_dup(sre->ref);
8049 if (re->ref == NULL)
8050 return got_error_from_errno("got_ref_dup");
8051 re->idx = s->nrefs++;
8052 TAILQ_INSERT_TAIL(&s->refs, re, entry);
8055 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8056 return NULL;
8059 static void
8060 ref_view_free_refs(struct tog_ref_view_state *s)
8062 struct tog_reflist_entry *re;
8064 while (!TAILQ_EMPTY(&s->refs)) {
8065 re = TAILQ_FIRST(&s->refs);
8066 TAILQ_REMOVE(&s->refs, re, entry);
8067 got_ref_close(re->ref);
8068 free(re);
8072 static const struct got_error *
8073 open_ref_view(struct tog_view *view, struct got_repository *repo)
8075 const struct got_error *err = NULL;
8076 struct tog_ref_view_state *s = &view->state.ref;
8078 s->selected_entry = 0;
8079 s->repo = repo;
8081 TAILQ_INIT(&s->refs);
8082 STAILQ_INIT(&s->colors);
8084 err = ref_view_load_refs(s);
8085 if (err)
8086 goto done;
8088 if (has_colors() && getenv("TOG_COLORS") != NULL) {
8089 err = add_color(&s->colors, "^refs/heads/",
8090 TOG_COLOR_REFS_HEADS,
8091 get_color_value("TOG_COLOR_REFS_HEADS"));
8092 if (err)
8093 goto done;
8095 err = add_color(&s->colors, "^refs/tags/",
8096 TOG_COLOR_REFS_TAGS,
8097 get_color_value("TOG_COLOR_REFS_TAGS"));
8098 if (err)
8099 goto done;
8101 err = add_color(&s->colors, "^refs/remotes/",
8102 TOG_COLOR_REFS_REMOTES,
8103 get_color_value("TOG_COLOR_REFS_REMOTES"));
8104 if (err)
8105 goto done;
8107 err = add_color(&s->colors, "^refs/got/backup/",
8108 TOG_COLOR_REFS_BACKUP,
8109 get_color_value("TOG_COLOR_REFS_BACKUP"));
8110 if (err)
8111 goto done;
8114 view->show = show_ref_view;
8115 view->input = input_ref_view;
8116 view->close = close_ref_view;
8117 view->search_start = search_start_ref_view;
8118 view->search_next = search_next_ref_view;
8119 done:
8120 if (err) {
8121 if (view->close == NULL)
8122 close_ref_view(view);
8123 view_close(view);
8125 return err;
8128 static const struct got_error *
8129 close_ref_view(struct tog_view *view)
8131 struct tog_ref_view_state *s = &view->state.ref;
8133 ref_view_free_refs(s);
8134 free_colors(&s->colors);
8136 return NULL;
8139 static const struct got_error *
8140 resolve_reflist_entry(struct got_object_id **commit_id,
8141 struct tog_reflist_entry *re, struct got_repository *repo)
8143 const struct got_error *err = NULL;
8144 struct got_object_id *obj_id;
8145 struct got_tag_object *tag = NULL;
8146 int obj_type;
8148 *commit_id = NULL;
8150 err = got_ref_resolve(&obj_id, repo, re->ref);
8151 if (err)
8152 return err;
8154 err = got_object_get_type(&obj_type, repo, obj_id);
8155 if (err)
8156 goto done;
8158 switch (obj_type) {
8159 case GOT_OBJ_TYPE_COMMIT:
8160 *commit_id = obj_id;
8161 break;
8162 case GOT_OBJ_TYPE_TAG:
8163 err = got_object_open_as_tag(&tag, repo, obj_id);
8164 if (err)
8165 goto done;
8166 free(obj_id);
8167 err = got_object_get_type(&obj_type, repo,
8168 got_object_tag_get_object_id(tag));
8169 if (err)
8170 goto done;
8171 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
8172 err = got_error(GOT_ERR_OBJ_TYPE);
8173 goto done;
8175 *commit_id = got_object_id_dup(
8176 got_object_tag_get_object_id(tag));
8177 if (*commit_id == NULL) {
8178 err = got_error_from_errno("got_object_id_dup");
8179 goto done;
8181 break;
8182 default:
8183 err = got_error(GOT_ERR_OBJ_TYPE);
8184 break;
8187 done:
8188 if (tag)
8189 got_object_tag_close(tag);
8190 if (err) {
8191 free(*commit_id);
8192 *commit_id = NULL;
8194 return err;
8197 static const struct got_error *
8198 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
8199 struct tog_reflist_entry *re, struct got_repository *repo)
8201 struct tog_view *log_view;
8202 const struct got_error *err = NULL;
8203 struct got_object_id *commit_id = NULL;
8205 *new_view = NULL;
8207 err = resolve_reflist_entry(&commit_id, re, repo);
8208 if (err) {
8209 if (err->code != GOT_ERR_OBJ_TYPE)
8210 return err;
8211 else
8212 return NULL;
8215 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
8216 if (log_view == NULL) {
8217 err = got_error_from_errno("view_open");
8218 goto done;
8221 err = open_log_view(log_view, commit_id, repo,
8222 got_ref_get_name(re->ref), "", 0);
8223 done:
8224 if (err)
8225 view_close(log_view);
8226 else
8227 *new_view = log_view;
8228 free(commit_id);
8229 return err;
8232 static void
8233 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
8235 struct tog_reflist_entry *re;
8236 int i = 0;
8238 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8239 return;
8241 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
8242 while (i++ < maxscroll) {
8243 if (re == NULL)
8244 break;
8245 s->first_displayed_entry = re;
8246 re = TAILQ_PREV(re, tog_reflist_head, entry);
8250 static const struct got_error *
8251 ref_scroll_down(struct tog_view *view, int maxscroll)
8253 struct tog_ref_view_state *s = &view->state.ref;
8254 struct tog_reflist_entry *next, *last;
8255 int n = 0;
8257 if (s->first_displayed_entry)
8258 next = TAILQ_NEXT(s->first_displayed_entry, entry);
8259 else
8260 next = TAILQ_FIRST(&s->refs);
8262 last = s->last_displayed_entry;
8263 while (next && n++ < maxscroll) {
8264 if (last) {
8265 s->last_displayed_entry = last;
8266 last = TAILQ_NEXT(last, entry);
8268 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
8269 s->first_displayed_entry = next;
8270 next = TAILQ_NEXT(next, entry);
8274 return NULL;
8277 static const struct got_error *
8278 search_start_ref_view(struct tog_view *view)
8280 struct tog_ref_view_state *s = &view->state.ref;
8282 s->matched_entry = NULL;
8283 return NULL;
8286 static int
8287 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
8289 regmatch_t regmatch;
8291 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
8292 0) == 0;
8295 static const struct got_error *
8296 search_next_ref_view(struct tog_view *view)
8298 struct tog_ref_view_state *s = &view->state.ref;
8299 struct tog_reflist_entry *re = NULL;
8301 if (!view->searching) {
8302 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8303 return NULL;
8306 if (s->matched_entry) {
8307 if (view->searching == TOG_SEARCH_FORWARD) {
8308 if (s->selected_entry)
8309 re = TAILQ_NEXT(s->selected_entry, entry);
8310 else
8311 re = TAILQ_PREV(s->selected_entry,
8312 tog_reflist_head, entry);
8313 } else {
8314 if (s->selected_entry == NULL)
8315 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8316 else
8317 re = TAILQ_PREV(s->selected_entry,
8318 tog_reflist_head, entry);
8320 } else {
8321 if (s->selected_entry)
8322 re = s->selected_entry;
8323 else if (view->searching == TOG_SEARCH_FORWARD)
8324 re = TAILQ_FIRST(&s->refs);
8325 else
8326 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8329 while (1) {
8330 if (re == NULL) {
8331 if (s->matched_entry == NULL) {
8332 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8333 return NULL;
8335 if (view->searching == TOG_SEARCH_FORWARD)
8336 re = TAILQ_FIRST(&s->refs);
8337 else
8338 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8341 if (match_reflist_entry(re, &view->regex)) {
8342 view->search_next_done = TOG_SEARCH_HAVE_MORE;
8343 s->matched_entry = re;
8344 break;
8347 if (view->searching == TOG_SEARCH_FORWARD)
8348 re = TAILQ_NEXT(re, entry);
8349 else
8350 re = TAILQ_PREV(re, tog_reflist_head, entry);
8353 if (s->matched_entry) {
8354 s->first_displayed_entry = s->matched_entry;
8355 s->selected = 0;
8358 return NULL;
8361 static const struct got_error *
8362 show_ref_view(struct tog_view *view)
8364 const struct got_error *err = NULL;
8365 struct tog_ref_view_state *s = &view->state.ref;
8366 struct tog_reflist_entry *re;
8367 char *line = NULL;
8368 wchar_t *wline;
8369 struct tog_color *tc;
8370 int width, n, scrollx;
8371 int limit = view->nlines;
8373 werase(view->window);
8375 s->ndisplayed = 0;
8376 if (view_is_hsplit_top(view))
8377 --limit; /* border */
8379 if (limit == 0)
8380 return NULL;
8382 re = s->first_displayed_entry;
8384 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
8385 s->nrefs) == -1)
8386 return got_error_from_errno("asprintf");
8388 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
8389 if (err) {
8390 free(line);
8391 return err;
8393 if (view_needs_focus_indication(view))
8394 wstandout(view->window);
8395 waddwstr(view->window, wline);
8396 while (width++ < view->ncols)
8397 waddch(view->window, ' ');
8398 if (view_needs_focus_indication(view))
8399 wstandend(view->window);
8400 free(wline);
8401 wline = NULL;
8402 free(line);
8403 line = NULL;
8404 if (--limit <= 0)
8405 return NULL;
8407 n = 0;
8408 view->maxx = 0;
8409 while (re && limit > 0) {
8410 char *line = NULL;
8411 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
8413 if (s->show_date) {
8414 struct got_commit_object *ci;
8415 struct got_tag_object *tag;
8416 struct got_object_id *id;
8417 struct tm tm;
8418 time_t t;
8420 err = got_ref_resolve(&id, s->repo, re->ref);
8421 if (err)
8422 return err;
8423 err = got_object_open_as_tag(&tag, s->repo, id);
8424 if (err) {
8425 if (err->code != GOT_ERR_OBJ_TYPE) {
8426 free(id);
8427 return err;
8429 err = got_object_open_as_commit(&ci, s->repo,
8430 id);
8431 if (err) {
8432 free(id);
8433 return err;
8435 t = got_object_commit_get_committer_time(ci);
8436 got_object_commit_close(ci);
8437 } else {
8438 t = got_object_tag_get_tagger_time(tag);
8439 got_object_tag_close(tag);
8441 free(id);
8442 if (gmtime_r(&t, &tm) == NULL)
8443 return got_error_from_errno("gmtime_r");
8444 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
8445 return got_error(GOT_ERR_NO_SPACE);
8447 if (got_ref_is_symbolic(re->ref)) {
8448 if (asprintf(&line, "%s%s -> %s", s->show_date ?
8449 ymd : "", got_ref_get_name(re->ref),
8450 got_ref_get_symref_target(re->ref)) == -1)
8451 return got_error_from_errno("asprintf");
8452 } else if (s->show_ids) {
8453 struct got_object_id *id;
8454 char *id_str;
8455 err = got_ref_resolve(&id, s->repo, re->ref);
8456 if (err)
8457 return err;
8458 err = got_object_id_str(&id_str, id);
8459 if (err) {
8460 free(id);
8461 return err;
8463 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
8464 got_ref_get_name(re->ref), id_str) == -1) {
8465 err = got_error_from_errno("asprintf");
8466 free(id);
8467 free(id_str);
8468 return err;
8470 free(id);
8471 free(id_str);
8472 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
8473 got_ref_get_name(re->ref)) == -1)
8474 return got_error_from_errno("asprintf");
8476 /* use full line width to determine view->maxx */
8477 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0, 0);
8478 if (err) {
8479 free(line);
8480 return err;
8482 view->maxx = MAX(view->maxx, width);
8483 free(wline);
8484 wline = NULL;
8486 err = format_line(&wline, &width, &scrollx, line, view->x,
8487 view->ncols, 0, 0);
8488 if (err) {
8489 free(line);
8490 return err;
8492 if (n == s->selected) {
8493 if (view->focussed)
8494 wstandout(view->window);
8495 s->selected_entry = re;
8497 tc = match_color(&s->colors, got_ref_get_name(re->ref));
8498 if (tc)
8499 wattr_on(view->window,
8500 COLOR_PAIR(tc->colorpair), NULL);
8501 waddwstr(view->window, &wline[scrollx]);
8502 if (tc)
8503 wattr_off(view->window,
8504 COLOR_PAIR(tc->colorpair), NULL);
8505 if (width < view->ncols)
8506 waddch(view->window, '\n');
8507 if (n == s->selected && view->focussed)
8508 wstandend(view->window);
8509 free(line);
8510 free(wline);
8511 wline = NULL;
8512 n++;
8513 s->ndisplayed++;
8514 s->last_displayed_entry = re;
8516 limit--;
8517 re = TAILQ_NEXT(re, entry);
8520 view_border(view);
8521 return err;
8524 static const struct got_error *
8525 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
8526 struct tog_reflist_entry *re, struct got_repository *repo)
8528 const struct got_error *err = NULL;
8529 struct got_object_id *commit_id = NULL;
8530 struct tog_view *tree_view;
8532 *new_view = NULL;
8534 err = resolve_reflist_entry(&commit_id, re, repo);
8535 if (err) {
8536 if (err->code != GOT_ERR_OBJ_TYPE)
8537 return err;
8538 else
8539 return NULL;
8543 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
8544 if (tree_view == NULL) {
8545 err = got_error_from_errno("view_open");
8546 goto done;
8549 err = open_tree_view(tree_view, commit_id,
8550 got_ref_get_name(re->ref), repo);
8551 if (err)
8552 goto done;
8554 *new_view = tree_view;
8555 done:
8556 free(commit_id);
8557 return err;
8560 static const struct got_error *
8561 ref_goto_line(struct tog_view *view, int nlines)
8563 const struct got_error *err = NULL;
8564 struct tog_ref_view_state *s = &view->state.ref;
8565 int g, idx = s->selected_entry->idx;
8567 g = view->gline;
8568 view->gline = 0;
8570 if (g == 0)
8571 g = 1;
8572 else if (g > s->nrefs)
8573 g = s->nrefs;
8575 if (g >= s->first_displayed_entry->idx + 1 &&
8576 g <= s->last_displayed_entry->idx + 1 &&
8577 g - s->first_displayed_entry->idx - 1 < nlines) {
8578 s->selected = g - s->first_displayed_entry->idx - 1;
8579 return NULL;
8582 if (idx + 1 < g) {
8583 err = ref_scroll_down(view, g - idx - 1);
8584 if (err)
8585 return err;
8586 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
8587 s->first_displayed_entry->idx + s->selected < g &&
8588 s->selected < s->ndisplayed - 1)
8589 s->selected = g - s->first_displayed_entry->idx - 1;
8590 } else if (idx + 1 > g)
8591 ref_scroll_up(s, idx - g + 1);
8593 if (g < nlines && s->first_displayed_entry->idx == 0)
8594 s->selected = g - 1;
8596 return NULL;
8600 static const struct got_error *
8601 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
8603 const struct got_error *err = NULL;
8604 struct tog_ref_view_state *s = &view->state.ref;
8605 struct tog_reflist_entry *re;
8606 int n, nscroll = view->nlines - 1;
8608 if (view->gline)
8609 return ref_goto_line(view, nscroll);
8611 switch (ch) {
8612 case '0':
8613 case '$':
8614 case KEY_RIGHT:
8615 case 'l':
8616 case KEY_LEFT:
8617 case 'h':
8618 horizontal_scroll_input(view, ch);
8619 break;
8620 case 'i':
8621 s->show_ids = !s->show_ids;
8622 view->count = 0;
8623 break;
8624 case 'm':
8625 s->show_date = !s->show_date;
8626 view->count = 0;
8627 break;
8628 case 'o':
8629 s->sort_by_date = !s->sort_by_date;
8630 view->action = s->sort_by_date ? "sort by date" : "sort by name";
8631 view->count = 0;
8632 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
8633 got_ref_cmp_by_commit_timestamp_descending :
8634 tog_ref_cmp_by_name, s->repo);
8635 if (err)
8636 break;
8637 got_reflist_object_id_map_free(tog_refs_idmap);
8638 err = got_reflist_object_id_map_create(&tog_refs_idmap,
8639 &tog_refs, s->repo);
8640 if (err)
8641 break;
8642 ref_view_free_refs(s);
8643 err = ref_view_load_refs(s);
8644 break;
8645 case KEY_ENTER:
8646 case '\r':
8647 view->count = 0;
8648 if (!s->selected_entry)
8649 break;
8650 err = view_request_new(new_view, view, TOG_VIEW_LOG);
8651 break;
8652 case 'T':
8653 view->count = 0;
8654 if (!s->selected_entry)
8655 break;
8656 err = view_request_new(new_view, view, TOG_VIEW_TREE);
8657 break;
8658 case 'g':
8659 case '=':
8660 case KEY_HOME:
8661 s->selected = 0;
8662 view->count = 0;
8663 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
8664 break;
8665 case 'G':
8666 case '*':
8667 case KEY_END: {
8668 int eos = view->nlines - 1;
8670 if (view->mode == TOG_VIEW_SPLIT_HRZN)
8671 --eos; /* border */
8672 s->selected = 0;
8673 view->count = 0;
8674 re = TAILQ_LAST(&s->refs, tog_reflist_head);
8675 for (n = 0; n < eos; n++) {
8676 if (re == NULL)
8677 break;
8678 s->first_displayed_entry = re;
8679 re = TAILQ_PREV(re, tog_reflist_head, entry);
8681 if (n > 0)
8682 s->selected = n - 1;
8683 break;
8685 case 'k':
8686 case KEY_UP:
8687 case CTRL('p'):
8688 if (s->selected > 0) {
8689 s->selected--;
8690 break;
8692 ref_scroll_up(s, 1);
8693 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8694 view->count = 0;
8695 break;
8696 case CTRL('u'):
8697 case 'u':
8698 nscroll /= 2;
8699 /* FALL THROUGH */
8700 case KEY_PPAGE:
8701 case CTRL('b'):
8702 case 'b':
8703 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
8704 s->selected -= MIN(nscroll, s->selected);
8705 ref_scroll_up(s, MAX(0, nscroll));
8706 if (s->selected_entry == TAILQ_FIRST(&s->refs))
8707 view->count = 0;
8708 break;
8709 case 'j':
8710 case KEY_DOWN:
8711 case CTRL('n'):
8712 if (s->selected < s->ndisplayed - 1) {
8713 s->selected++;
8714 break;
8716 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8717 /* can't scroll any further */
8718 view->count = 0;
8719 break;
8721 ref_scroll_down(view, 1);
8722 break;
8723 case CTRL('d'):
8724 case 'd':
8725 nscroll /= 2;
8726 /* FALL THROUGH */
8727 case KEY_NPAGE:
8728 case CTRL('f'):
8729 case 'f':
8730 case ' ':
8731 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
8732 /* can't scroll any further; move cursor down */
8733 if (s->selected < s->ndisplayed - 1)
8734 s->selected += MIN(nscroll,
8735 s->ndisplayed - s->selected - 1);
8736 if (view->count > 1 && s->selected < s->ndisplayed - 1)
8737 s->selected += s->ndisplayed - s->selected - 1;
8738 view->count = 0;
8739 break;
8741 ref_scroll_down(view, nscroll);
8742 break;
8743 case CTRL('l'):
8744 view->count = 0;
8745 tog_free_refs();
8746 err = tog_load_refs(s->repo, s->sort_by_date);
8747 if (err)
8748 break;
8749 ref_view_free_refs(s);
8750 err = ref_view_load_refs(s);
8751 break;
8752 case KEY_RESIZE:
8753 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
8754 s->selected = view->nlines - 2;
8755 break;
8756 default:
8757 view->count = 0;
8758 break;
8761 return err;
8764 __dead static void
8765 usage_ref(void)
8767 endwin();
8768 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8769 getprogname());
8770 exit(1);
8773 static const struct got_error *
8774 cmd_ref(int argc, char *argv[])
8776 const struct got_error *error;
8777 struct got_repository *repo = NULL;
8778 struct got_worktree *worktree = NULL;
8779 char *cwd = NULL, *repo_path = NULL;
8780 int ch;
8781 struct tog_view *view;
8782 int *pack_fds = NULL;
8784 while ((ch = getopt(argc, argv, "r:")) != -1) {
8785 switch (ch) {
8786 case 'r':
8787 repo_path = realpath(optarg, NULL);
8788 if (repo_path == NULL)
8789 return got_error_from_errno2("realpath",
8790 optarg);
8791 break;
8792 default:
8793 usage_ref();
8794 /* NOTREACHED */
8798 argc -= optind;
8799 argv += optind;
8801 if (argc > 1)
8802 usage_ref();
8804 error = got_repo_pack_fds_open(&pack_fds);
8805 if (error != NULL)
8806 goto done;
8808 if (repo_path == NULL) {
8809 cwd = getcwd(NULL, 0);
8810 if (cwd == NULL)
8811 return got_error_from_errno("getcwd");
8812 error = got_worktree_open(&worktree, cwd);
8813 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8814 goto done;
8815 if (worktree)
8816 repo_path =
8817 strdup(got_worktree_get_repo_path(worktree));
8818 else
8819 repo_path = strdup(cwd);
8820 if (repo_path == NULL) {
8821 error = got_error_from_errno("strdup");
8822 goto done;
8826 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8827 if (error != NULL)
8828 goto done;
8830 init_curses();
8832 error = apply_unveil(got_repo_get_path(repo), NULL);
8833 if (error)
8834 goto done;
8836 error = tog_load_refs(repo, 0);
8837 if (error)
8838 goto done;
8840 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8841 if (view == NULL) {
8842 error = got_error_from_errno("view_open");
8843 goto done;
8846 error = open_ref_view(view, repo);
8847 if (error)
8848 goto done;
8850 if (worktree) {
8851 /* Release work tree lock. */
8852 got_worktree_close(worktree);
8853 worktree = NULL;
8855 error = view_loop(view);
8856 done:
8857 free(repo_path);
8858 free(cwd);
8859 if (repo) {
8860 const struct got_error *close_err = got_repo_close(repo);
8861 if (close_err)
8862 error = close_err;
8864 if (pack_fds) {
8865 const struct got_error *pack_err =
8866 got_repo_pack_fds_close(pack_fds);
8867 if (error == NULL)
8868 error = pack_err;
8870 tog_free_refs();
8871 return error;
8874 static const struct got_error*
8875 win_draw_center(WINDOW *win, size_t y, size_t x, size_t maxx, int focus,
8876 const char *str)
8878 size_t len;
8880 if (win == NULL)
8881 win = stdscr;
8883 len = strlen(str);
8884 x = x ? x : maxx > len ? (maxx - len) / 2 : 0;
8886 if (focus)
8887 wstandout(win);
8888 if (mvwprintw(win, y, x, "%s", str) == ERR)
8889 return got_error_msg(GOT_ERR_RANGE, "mvwprintw");
8890 if (focus)
8891 wstandend(win);
8893 return NULL;
8896 static const struct got_error *
8897 add_line_offset(off_t **line_offsets, size_t *nlines, off_t off)
8899 off_t *p;
8901 p = reallocarray(*line_offsets, *nlines + 1, sizeof(off_t));
8902 if (p == NULL) {
8903 free(*line_offsets);
8904 *line_offsets = NULL;
8905 return got_error_from_errno("reallocarray");
8908 *line_offsets = p;
8909 (*line_offsets)[*nlines] = off;
8910 ++(*nlines);
8911 return NULL;
8914 static const struct got_error *
8915 max_key_str(int *ret, const struct tog_key_map *km, size_t n)
8917 *ret = 0;
8919 for (;n > 0; --n, ++km) {
8920 char *t0, *t, *k;
8921 size_t len = 1;
8923 if (km->keys == NULL)
8924 continue;
8926 t = t0 = strdup(km->keys);
8927 if (t0 == NULL)
8928 return got_error_from_errno("strdup");
8930 len += strlen(t);
8931 while ((k = strsep(&t, " ")) != NULL)
8932 len += strlen(k) > 1 ? 2 : 0;
8933 free(t0);
8934 *ret = MAX(*ret, len);
8937 return NULL;
8941 * Write keymap section headers, keys, and key info in km to f.
8942 * Save line offset to *off. If terminal has UTF8 encoding enabled,
8943 * wrap control and symbolic keys in guillemets, else use <>.
8945 static const struct got_error *
8946 format_help_line(off_t *off, FILE *f, const struct tog_key_map *km, int width)
8948 int n, len = width;
8950 if (km->keys) {
8951 static const char *u8_glyph[] = {
8952 "\xe2\x80\xb9", /* U+2039 (utf8 <) */
8953 "\xe2\x80\xba" /* U+203A (utf8 >) */
8955 char *t0, *t, *k;
8956 int cs, s, first = 1;
8958 cs = got_locale_is_utf8();
8960 t = t0 = strdup(km->keys);
8961 if (t0 == NULL)
8962 return got_error_from_errno("strdup");
8964 len = strlen(km->keys);
8965 while ((k = strsep(&t, " ")) != NULL) {
8966 s = strlen(k) > 1; /* control or symbolic key */
8967 n = fprintf(f, "%s%s%s%s%s", first ? " " : "",
8968 cs && s ? u8_glyph[0] : s ? "<" : "", k,
8969 cs && s ? u8_glyph[1] : s ? ">" : "", t ? " " : "");
8970 if (n < 0) {
8971 free(t0);
8972 return got_error_from_errno("fprintf");
8974 first = 0;
8975 len += s ? 2 : 0;
8976 *off += n;
8978 free(t0);
8980 n = fprintf(f, "%*s%s\n", width - len, width - len ? " " : "", km->info);
8981 if (n < 0)
8982 return got_error_from_errno("fprintf");
8983 *off += n;
8985 return NULL;
8988 static const struct got_error *
8989 format_help(struct tog_help_view_state *s)
8991 const struct got_error *err = NULL;
8992 off_t off = 0;
8993 int i, max, n, show = s->all;
8994 static const struct tog_key_map km[] = {
8995 #define KEYMAP_(info, type) { NULL, (info), type }
8996 #define KEY_(keys, info) { (keys), (info), TOG_KEYMAP_KEYS }
8997 GENERATE_HELP
8998 #undef KEYMAP_
8999 #undef KEY_
9002 err = add_line_offset(&s->line_offsets, &s->nlines, 0);
9003 if (err)
9004 return err;
9006 n = nitems(km);
9007 err = max_key_str(&max, km, n);
9008 if (err)
9009 return err;
9011 for (i = 0; i < n; ++i) {
9012 if (km[i].keys == NULL) {
9013 show = s->all;
9014 if (km[i].type == TOG_KEYMAP_GLOBAL ||
9015 km[i].type == s->type || s->all)
9016 show = 1;
9018 if (show) {
9019 err = format_help_line(&off, s->f, &km[i], max);
9020 if (err)
9021 return err;
9022 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9023 if (err)
9024 return err;
9027 fputc('\n', s->f);
9028 ++off;
9029 err = add_line_offset(&s->line_offsets, &s->nlines, off);
9030 return err;
9033 static const struct got_error *
9034 create_help(struct tog_help_view_state *s)
9036 FILE *f;
9037 const struct got_error *err;
9039 free(s->line_offsets);
9040 s->line_offsets = NULL;
9041 s->nlines = 0;
9043 f = got_opentemp();
9044 if (f == NULL)
9045 return got_error_from_errno("got_opentemp");
9046 s->f = f;
9048 err = format_help(s);
9049 if (err)
9050 return err;
9052 if (s->f && fflush(s->f) != 0)
9053 return got_error_from_errno("fflush");
9055 return NULL;
9058 static const struct got_error *
9059 search_start_help_view(struct tog_view *view)
9061 view->state.help.matched_line = 0;
9062 return NULL;
9065 static void
9066 search_setup_help_view(struct tog_view *view, FILE **f, off_t **line_offsets,
9067 size_t *nlines, int **first, int **last, int **match, int **selected)
9069 struct tog_help_view_state *s = &view->state.help;
9071 *f = s->f;
9072 *nlines = s->nlines;
9073 *line_offsets = s->line_offsets;
9074 *match = &s->matched_line;
9075 *first = &s->first_displayed_line;
9076 *last = &s->last_displayed_line;
9077 *selected = &s->selected_line;
9080 static const struct got_error *
9081 show_help_view(struct tog_view *view)
9083 struct tog_help_view_state *s = &view->state.help;
9084 const struct got_error *err;
9085 regmatch_t *regmatch = &view->regmatch;
9086 wchar_t *wline;
9087 char *line;
9088 ssize_t linelen;
9089 size_t linesz = 0;
9090 int width, nprinted = 0, rc = 0;
9091 int eos = view->nlines;
9093 if (view_is_hsplit_top(view))
9094 --eos; /* account for border */
9096 s->lineno = 0;
9097 rewind(s->f);
9098 werase(view->window);
9100 if (view->gline > s->nlines - 1)
9101 view->gline = s->nlines - 1;
9103 err = win_draw_center(view->window, 0, 0, view->ncols,
9104 view_needs_focus_indication(view),
9105 "tog help (press q to return to tog)");
9106 if (err)
9107 return err;
9108 if (eos <= 1)
9109 return NULL;
9110 waddstr(view->window, "\n\n");
9111 eos -= 2;
9113 s->eof = 0;
9114 view->maxx = 0;
9115 line = NULL;
9116 while (eos > 0 && nprinted < eos) {
9117 attr_t attr = 0;
9119 linelen = getline(&line, &linesz, s->f);
9120 if (linelen == -1) {
9121 if (!feof(s->f)) {
9122 free(line);
9123 return got_ferror(s->f, GOT_ERR_IO);
9125 s->eof = 1;
9126 break;
9128 if (++s->lineno < s->first_displayed_line)
9129 continue;
9130 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
9131 continue;
9132 if (s->lineno == view->hiline)
9133 attr = A_STANDOUT;
9135 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
9136 view->x ? 1 : 0);
9137 if (err) {
9138 free(line);
9139 return err;
9141 view->maxx = MAX(view->maxx, width);
9142 free(wline);
9143 wline = NULL;
9145 if (attr)
9146 wattron(view->window, attr);
9147 if (s->first_displayed_line + nprinted == s->matched_line &&
9148 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
9149 err = add_matched_line(&width, line, view->ncols - 1, 0,
9150 view->window, view->x, regmatch);
9151 if (err) {
9152 free(line);
9153 return err;
9155 } else {
9156 int skip;
9158 err = format_line(&wline, &width, &skip, line,
9159 view->x, view->ncols, 0, view->x ? 1 : 0);
9160 if (err) {
9161 free(line);
9162 return err;
9164 waddwstr(view->window, &wline[skip]);
9165 free(wline);
9166 wline = NULL;
9168 if (s->lineno == view->hiline) {
9169 while (width++ < view->ncols)
9170 waddch(view->window, ' ');
9171 } else {
9172 if (width < view->ncols)
9173 waddch(view->window, '\n');
9175 if (attr)
9176 wattroff(view->window, attr);
9177 if (++nprinted == 1)
9178 s->first_displayed_line = s->lineno;
9180 free(line);
9181 if (nprinted > 0)
9182 s->last_displayed_line = s->first_displayed_line + nprinted - 1;
9183 else
9184 s->last_displayed_line = s->first_displayed_line;
9186 view_border(view);
9188 if (s->eof) {
9189 rc = waddnstr(view->window,
9190 "See the tog(1) manual page for full documentation",
9191 view->ncols - 1);
9192 if (rc == ERR)
9193 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9194 } else {
9195 wmove(view->window, view->nlines - 1, 0);
9196 wclrtoeol(view->window);
9197 wstandout(view->window);
9198 rc = waddnstr(view->window, "scroll down for more...",
9199 view->ncols - 1);
9200 if (rc == ERR)
9201 return got_error_msg(GOT_ERR_RANGE, "waddnstr");
9202 if (getcurx(view->window) < view->ncols - 6) {
9203 rc = wprintw(view->window, "[%.0f%%]",
9204 100.00 * s->last_displayed_line / s->nlines);
9205 if (rc == ERR)
9206 return got_error_msg(GOT_ERR_IO, "wprintw");
9208 wstandend(view->window);
9211 return NULL;
9214 static const struct got_error *
9215 input_help_view(struct tog_view **new_view, struct tog_view *view, int ch)
9217 struct tog_help_view_state *s = &view->state.help;
9218 const struct got_error *err = NULL;
9219 char *line = NULL;
9220 ssize_t linelen;
9221 size_t linesz = 0;
9222 int eos, nscroll;
9224 eos = nscroll = view->nlines;
9225 if (view_is_hsplit_top(view))
9226 --eos; /* border */
9228 s->lineno = s->first_displayed_line - 1 + s->selected_line;
9230 switch (ch) {
9231 case '0':
9232 case '$':
9233 case KEY_RIGHT:
9234 case 'l':
9235 case KEY_LEFT:
9236 case 'h':
9237 horizontal_scroll_input(view, ch);
9238 break;
9239 case 'g':
9240 case KEY_HOME:
9241 s->first_displayed_line = 1;
9242 view->count = 0;
9243 break;
9244 case 'G':
9245 case KEY_END:
9246 view->count = 0;
9247 if (s->eof)
9248 break;
9249 s->first_displayed_line = (s->nlines - eos) + 3;
9250 s->eof = 1;
9251 break;
9252 case 'k':
9253 case KEY_UP:
9254 if (s->first_displayed_line > 1)
9255 --s->first_displayed_line;
9256 else
9257 view->count = 0;
9258 break;
9259 case CTRL('u'):
9260 case 'u':
9261 nscroll /= 2;
9262 /* FALL THROUGH */
9263 case KEY_PPAGE:
9264 case CTRL('b'):
9265 case 'b':
9266 if (s->first_displayed_line == 1) {
9267 view->count = 0;
9268 break;
9270 while (--nscroll > 0 && s->first_displayed_line > 1)
9271 s->first_displayed_line--;
9272 break;
9273 case 'j':
9274 case KEY_DOWN:
9275 case CTRL('n'):
9276 if (!s->eof)
9277 ++s->first_displayed_line;
9278 else
9279 view->count = 0;
9280 break;
9281 case CTRL('d'):
9282 case 'd':
9283 nscroll /= 2;
9284 /* FALL THROUGH */
9285 case KEY_NPAGE:
9286 case CTRL('f'):
9287 case 'f':
9288 case ' ':
9289 if (s->eof) {
9290 view->count = 0;
9291 break;
9293 while (!s->eof && --nscroll > 0) {
9294 linelen = getline(&line, &linesz, s->f);
9295 s->first_displayed_line++;
9296 if (linelen == -1) {
9297 if (feof(s->f))
9298 s->eof = 1;
9299 else
9300 err = got_ferror(s->f, GOT_ERR_IO);
9301 break;
9304 free(line);
9305 break;
9306 default:
9307 view->count = 0;
9308 break;
9311 return err;
9314 static const struct got_error *
9315 close_help_view(struct tog_view *view)
9317 struct tog_help_view_state *s = &view->state.help;
9319 free(s->line_offsets);
9320 s->line_offsets = NULL;
9321 if (fclose(s->f) == EOF)
9322 return got_error_from_errno("fclose");
9324 return NULL;
9327 static const struct got_error *
9328 reset_help_view(struct tog_view *view)
9330 struct tog_help_view_state *s = &view->state.help;
9333 if (s->f && fclose(s->f) == EOF)
9334 return got_error_from_errno("fclose");
9336 wclear(view->window);
9337 view->count = 0;
9338 view->x = 0;
9339 s->all = !s->all;
9340 s->first_displayed_line = 1;
9341 s->last_displayed_line = view->nlines;
9342 s->matched_line = 0;
9344 return create_help(s);
9347 static const struct got_error *
9348 open_help_view(struct tog_view *view, struct tog_view *parent)
9350 const struct got_error *err = NULL;
9351 struct tog_help_view_state *s = &view->state.help;
9353 s->type = (enum tog_keymap_type)parent->type;
9354 s->first_displayed_line = 1;
9355 s->last_displayed_line = view->nlines;
9356 s->selected_line = 1;
9358 view->show = show_help_view;
9359 view->input = input_help_view;
9360 view->reset = reset_help_view;
9361 view->close = close_help_view;
9362 view->search_start = search_start_help_view;
9363 view->search_setup = search_setup_help_view;
9364 view->search_next = search_next_view_match;
9366 err = create_help(s);
9367 return err;
9370 static const struct got_error *
9371 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
9372 enum tog_view_type request, int y, int x)
9374 const struct got_error *err = NULL;
9376 *new_view = NULL;
9378 switch (request) {
9379 case TOG_VIEW_DIFF:
9380 if (view->type == TOG_VIEW_LOG) {
9381 struct tog_log_view_state *s = &view->state.log;
9383 err = open_diff_view_for_commit(new_view, y, x,
9384 s->selected_entry->commit, s->selected_entry->id,
9385 view, s->repo);
9386 } else
9387 return got_error_msg(GOT_ERR_NOT_IMPL,
9388 "parent/child view pair not supported");
9389 break;
9390 case TOG_VIEW_BLAME:
9391 if (view->type == TOG_VIEW_TREE) {
9392 struct tog_tree_view_state *s = &view->state.tree;
9394 err = blame_tree_entry(new_view, y, x,
9395 s->selected_entry, &s->parents, s->commit_id,
9396 s->repo);
9397 } else
9398 return got_error_msg(GOT_ERR_NOT_IMPL,
9399 "parent/child view pair not supported");
9400 break;
9401 case TOG_VIEW_LOG:
9402 if (view->type == TOG_VIEW_BLAME)
9403 err = log_annotated_line(new_view, y, x,
9404 view->state.blame.repo, view->state.blame.id_to_log);
9405 else if (view->type == TOG_VIEW_TREE)
9406 err = log_selected_tree_entry(new_view, y, x,
9407 &view->state.tree);
9408 else if (view->type == TOG_VIEW_REF)
9409 err = log_ref_entry(new_view, y, x,
9410 view->state.ref.selected_entry,
9411 view->state.ref.repo);
9412 else
9413 return got_error_msg(GOT_ERR_NOT_IMPL,
9414 "parent/child view pair not supported");
9415 break;
9416 case TOG_VIEW_TREE:
9417 if (view->type == TOG_VIEW_LOG)
9418 err = browse_commit_tree(new_view, y, x,
9419 view->state.log.selected_entry,
9420 view->state.log.in_repo_path,
9421 view->state.log.head_ref_name,
9422 view->state.log.repo);
9423 else if (view->type == TOG_VIEW_REF)
9424 err = browse_ref_tree(new_view, y, x,
9425 view->state.ref.selected_entry,
9426 view->state.ref.repo);
9427 else
9428 return got_error_msg(GOT_ERR_NOT_IMPL,
9429 "parent/child view pair not supported");
9430 break;
9431 case TOG_VIEW_REF:
9432 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
9433 if (*new_view == NULL)
9434 return got_error_from_errno("view_open");
9435 if (view->type == TOG_VIEW_LOG)
9436 err = open_ref_view(*new_view, view->state.log.repo);
9437 else if (view->type == TOG_VIEW_TREE)
9438 err = open_ref_view(*new_view, view->state.tree.repo);
9439 else
9440 err = got_error_msg(GOT_ERR_NOT_IMPL,
9441 "parent/child view pair not supported");
9442 if (err)
9443 view_close(*new_view);
9444 break;
9445 case TOG_VIEW_HELP:
9446 *new_view = view_open(0, 0, 0, 0, TOG_VIEW_HELP);
9447 if (*new_view == NULL)
9448 return got_error_from_errno("view_open");
9449 err = open_help_view(*new_view, view);
9450 if (err)
9451 view_close(*new_view);
9452 break;
9453 default:
9454 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
9457 return err;
9461 * If view was scrolled down to move the selected line into view when opening a
9462 * horizontal split, scroll back up when closing the split/toggling fullscreen.
9464 static void
9465 offset_selection_up(struct tog_view *view)
9467 switch (view->type) {
9468 case TOG_VIEW_BLAME: {
9469 struct tog_blame_view_state *s = &view->state.blame;
9470 if (s->first_displayed_line == 1) {
9471 s->selected_line = MAX(s->selected_line - view->offset,
9472 1);
9473 break;
9475 if (s->first_displayed_line > view->offset)
9476 s->first_displayed_line -= view->offset;
9477 else
9478 s->first_displayed_line = 1;
9479 s->selected_line += view->offset;
9480 break;
9482 case TOG_VIEW_LOG:
9483 log_scroll_up(&view->state.log, view->offset);
9484 view->state.log.selected += view->offset;
9485 break;
9486 case TOG_VIEW_REF:
9487 ref_scroll_up(&view->state.ref, view->offset);
9488 view->state.ref.selected += view->offset;
9489 break;
9490 case TOG_VIEW_TREE:
9491 tree_scroll_up(&view->state.tree, view->offset);
9492 view->state.tree.selected += view->offset;
9493 break;
9494 default:
9495 break;
9498 view->offset = 0;
9502 * If the selected line is in the section of screen covered by the bottom split,
9503 * scroll down offset lines to move it into view and index its new position.
9505 static const struct got_error *
9506 offset_selection_down(struct tog_view *view)
9508 const struct got_error *err = NULL;
9509 const struct got_error *(*scrolld)(struct tog_view *, int);
9510 int *selected = NULL;
9511 int header, offset;
9513 switch (view->type) {
9514 case TOG_VIEW_BLAME: {
9515 struct tog_blame_view_state *s = &view->state.blame;
9516 header = 3;
9517 scrolld = NULL;
9518 if (s->selected_line > view->nlines - header) {
9519 offset = abs(view->nlines - s->selected_line - header);
9520 s->first_displayed_line += offset;
9521 s->selected_line -= offset;
9522 view->offset = offset;
9524 break;
9526 case TOG_VIEW_LOG: {
9527 struct tog_log_view_state *s = &view->state.log;
9528 scrolld = &log_scroll_down;
9529 header = view_is_parent_view(view) ? 3 : 2;
9530 selected = &s->selected;
9531 break;
9533 case TOG_VIEW_REF: {
9534 struct tog_ref_view_state *s = &view->state.ref;
9535 scrolld = &ref_scroll_down;
9536 header = 3;
9537 selected = &s->selected;
9538 break;
9540 case TOG_VIEW_TREE: {
9541 struct tog_tree_view_state *s = &view->state.tree;
9542 scrolld = &tree_scroll_down;
9543 header = 5;
9544 selected = &s->selected;
9545 break;
9547 default:
9548 selected = NULL;
9549 scrolld = NULL;
9550 header = 0;
9551 break;
9554 if (selected && *selected > view->nlines - header) {
9555 offset = abs(view->nlines - *selected - header);
9556 view->offset = offset;
9557 if (scrolld && offset) {
9558 err = scrolld(view, offset);
9559 *selected -= offset;
9563 return err;
9566 static void
9567 list_commands(FILE *fp)
9569 size_t i;
9571 fprintf(fp, "commands:");
9572 for (i = 0; i < nitems(tog_commands); i++) {
9573 const struct tog_cmd *cmd = &tog_commands[i];
9574 fprintf(fp, " %s", cmd->name);
9576 fputc('\n', fp);
9579 __dead static void
9580 usage(int hflag, int status)
9582 FILE *fp = (status == 0) ? stdout : stderr;
9584 fprintf(fp, "usage: %s [-hV] command [arg ...]\n",
9585 getprogname());
9586 if (hflag) {
9587 fprintf(fp, "lazy usage: %s path\n", getprogname());
9588 list_commands(fp);
9590 exit(status);
9593 static char **
9594 make_argv(int argc, ...)
9596 va_list ap;
9597 char **argv;
9598 int i;
9600 va_start(ap, argc);
9602 argv = calloc(argc, sizeof(char *));
9603 if (argv == NULL)
9604 err(1, "calloc");
9605 for (i = 0; i < argc; i++) {
9606 argv[i] = strdup(va_arg(ap, char *));
9607 if (argv[i] == NULL)
9608 err(1, "strdup");
9611 va_end(ap);
9612 return argv;
9616 * Try to convert 'tog path' into a 'tog log path' command.
9617 * The user could simply have mistyped the command rather than knowingly
9618 * provided a path. So check whether argv[0] can in fact be resolved
9619 * to a path in the HEAD commit and print a special error if not.
9620 * This hack is for mpi@ <3
9622 static const struct got_error *
9623 tog_log_with_path(int argc, char *argv[])
9625 const struct got_error *error = NULL, *close_err;
9626 const struct tog_cmd *cmd = NULL;
9627 struct got_repository *repo = NULL;
9628 struct got_worktree *worktree = NULL;
9629 struct got_object_id *commit_id = NULL, *id = NULL;
9630 struct got_commit_object *commit = NULL;
9631 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
9632 char *commit_id_str = NULL, **cmd_argv = NULL;
9633 int *pack_fds = NULL;
9635 cwd = getcwd(NULL, 0);
9636 if (cwd == NULL)
9637 return got_error_from_errno("getcwd");
9639 error = got_repo_pack_fds_open(&pack_fds);
9640 if (error != NULL)
9641 goto done;
9643 error = got_worktree_open(&worktree, cwd);
9644 if (error && error->code != GOT_ERR_NOT_WORKTREE)
9645 goto done;
9647 if (worktree)
9648 repo_path = strdup(got_worktree_get_repo_path(worktree));
9649 else
9650 repo_path = strdup(cwd);
9651 if (repo_path == NULL) {
9652 error = got_error_from_errno("strdup");
9653 goto done;
9656 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
9657 if (error != NULL)
9658 goto done;
9660 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
9661 repo, worktree);
9662 if (error)
9663 goto done;
9665 error = tog_load_refs(repo, 0);
9666 if (error)
9667 goto done;
9668 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
9669 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
9670 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
9671 if (error)
9672 goto done;
9674 if (worktree) {
9675 got_worktree_close(worktree);
9676 worktree = NULL;
9679 error = got_object_open_as_commit(&commit, repo, commit_id);
9680 if (error)
9681 goto done;
9683 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
9684 if (error) {
9685 if (error->code != GOT_ERR_NO_TREE_ENTRY)
9686 goto done;
9687 fprintf(stderr, "%s: '%s' is no known command or path\n",
9688 getprogname(), argv[0]);
9689 usage(1, 1);
9690 /* not reached */
9693 error = got_object_id_str(&commit_id_str, commit_id);
9694 if (error)
9695 goto done;
9697 cmd = &tog_commands[0]; /* log */
9698 argc = 4;
9699 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
9700 error = cmd->cmd_main(argc, cmd_argv);
9701 done:
9702 if (repo) {
9703 close_err = got_repo_close(repo);
9704 if (error == NULL)
9705 error = close_err;
9707 if (commit)
9708 got_object_commit_close(commit);
9709 if (worktree)
9710 got_worktree_close(worktree);
9711 if (pack_fds) {
9712 const struct got_error *pack_err =
9713 got_repo_pack_fds_close(pack_fds);
9714 if (error == NULL)
9715 error = pack_err;
9717 free(id);
9718 free(commit_id_str);
9719 free(commit_id);
9720 free(cwd);
9721 free(repo_path);
9722 free(in_repo_path);
9723 if (cmd_argv) {
9724 int i;
9725 for (i = 0; i < argc; i++)
9726 free(cmd_argv[i]);
9727 free(cmd_argv);
9729 tog_free_refs();
9730 return error;
9733 int
9734 main(int argc, char *argv[])
9736 const struct got_error *io_err, *error = NULL;
9737 const struct tog_cmd *cmd = NULL;
9738 int ch, hflag = 0, Vflag = 0;
9739 char **cmd_argv = NULL;
9740 static const struct option longopts[] = {
9741 { "version", no_argument, NULL, 'V' },
9742 { NULL, 0, NULL, 0}
9744 char *diff_algo_str = NULL;
9745 const char *test_script_path;
9747 setlocale(LC_CTYPE, "");
9750 * Test mode init must happen before pledge() because "tty" will
9751 * not allow TTY-related ioctls to occur via regular files.
9753 test_script_path = getenv("TOG_TEST_SCRIPT");
9754 if (test_script_path != NULL) {
9755 error = init_mock_term(test_script_path);
9756 if (error) {
9757 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9758 return 1;
9762 #if !defined(PROFILE)
9763 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
9764 NULL) == -1)
9765 err(1, "pledge");
9766 #endif
9768 if (!isatty(STDIN_FILENO))
9769 errx(1, "standard input is not a tty");
9771 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
9772 switch (ch) {
9773 case 'h':
9774 hflag = 1;
9775 break;
9776 case 'V':
9777 Vflag = 1;
9778 break;
9779 default:
9780 usage(hflag, 1);
9781 /* NOTREACHED */
9785 argc -= optind;
9786 argv += optind;
9787 optind = 1;
9788 optreset = 1;
9790 if (Vflag) {
9791 got_version_print_str();
9792 return 0;
9795 if (argc == 0) {
9796 if (hflag)
9797 usage(hflag, 0);
9798 /* Build an argument vector which runs a default command. */
9799 cmd = &tog_commands[0];
9800 argc = 1;
9801 cmd_argv = make_argv(argc, cmd->name);
9802 } else {
9803 size_t i;
9805 /* Did the user specify a command? */
9806 for (i = 0; i < nitems(tog_commands); i++) {
9807 if (strncmp(tog_commands[i].name, argv[0],
9808 strlen(argv[0])) == 0) {
9809 cmd = &tog_commands[i];
9810 break;
9815 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
9816 if (diff_algo_str) {
9817 if (strcasecmp(diff_algo_str, "patience") == 0)
9818 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
9819 if (strcasecmp(diff_algo_str, "myers") == 0)
9820 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
9823 if (cmd == NULL) {
9824 if (argc != 1)
9825 usage(0, 1);
9826 /* No command specified; try log with a path */
9827 error = tog_log_with_path(argc, argv);
9828 } else {
9829 if (hflag)
9830 cmd->cmd_usage();
9831 else
9832 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
9835 if (using_mock_io) {
9836 io_err = tog_io_close();
9837 if (error == NULL)
9838 error = io_err;
9840 endwin();
9841 if (cmd_argv) {
9842 int i;
9843 for (i = 0; i < argc; i++)
9844 free(cmd_argv[i]);
9845 free(cmd_argv);
9848 if (error && error->code != GOT_ERR_CANCELLED &&
9849 error->code != GOT_ERR_EOF &&
9850 error->code != GOT_ERR_PRIVSEP_EXIT &&
9851 error->code != GOT_ERR_PRIVSEP_PIPE &&
9852 !(error->code == GOT_ERR_ERRNO && errno == EINTR))
9853 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
9854 return 0;