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 <signal.h>
29 #include <stdlib.h>
30 #include <stdarg.h>
31 #include <stdio.h>
32 #include <getopt.h>
33 #include <string.h>
34 #include <err.h>
35 #include <unistd.h>
36 #include <limits.h>
37 #include <wchar.h>
38 #include <time.h>
39 #include <pthread.h>
40 #include <libgen.h>
41 #include <regex.h>
42 #include <sched.h>
44 #include "got_version.h"
45 #include "got_error.h"
46 #include "got_object.h"
47 #include "got_reference.h"
48 #include "got_repository.h"
49 #include "got_diff.h"
50 #include "got_opentemp.h"
51 #include "got_utf8.h"
52 #include "got_cancel.h"
53 #include "got_commit_graph.h"
54 #include "got_blame.h"
55 #include "got_privsep.h"
56 #include "got_path.h"
57 #include "got_worktree.h"
59 #ifndef MIN
60 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
61 #endif
63 #ifndef MAX
64 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
65 #endif
67 #define CTRL(x) ((x) & 0x1f)
69 #ifndef nitems
70 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
71 #endif
73 struct tog_cmd {
74 const char *name;
75 const struct got_error *(*cmd_main)(int, char *[]);
76 void (*cmd_usage)(void);
77 };
79 __dead static void usage(int, int);
80 __dead static void usage_log(void);
81 __dead static void usage_diff(void);
82 __dead static void usage_blame(void);
83 __dead static void usage_tree(void);
84 __dead static void usage_ref(void);
86 static const struct got_error* cmd_log(int, char *[]);
87 static const struct got_error* cmd_diff(int, char *[]);
88 static const struct got_error* cmd_blame(int, char *[]);
89 static const struct got_error* cmd_tree(int, char *[]);
90 static const struct got_error* cmd_ref(int, char *[]);
92 static const struct tog_cmd tog_commands[] = {
93 { "log", cmd_log, usage_log },
94 { "diff", cmd_diff, usage_diff },
95 { "blame", cmd_blame, usage_blame },
96 { "tree", cmd_tree, usage_tree },
97 { "ref", cmd_ref, usage_ref },
98 };
100 enum tog_view_type {
101 TOG_VIEW_DIFF,
102 TOG_VIEW_LOG,
103 TOG_VIEW_BLAME,
104 TOG_VIEW_TREE,
105 TOG_VIEW_REF,
106 };
108 enum tog_view_mode {
109 TOG_VIEW_SPLIT_NONE,
110 TOG_VIEW_SPLIT_VERT,
111 TOG_VIEW_SPLIT_HRZN
112 };
114 #define HSPLIT_SCALE 0.3 /* default horizontal split scale */
116 #define TOG_EOF_STRING "(END)"
118 struct commit_queue_entry {
119 TAILQ_ENTRY(commit_queue_entry) entry;
120 struct got_object_id *id;
121 struct got_commit_object *commit;
122 int idx;
123 };
124 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
125 struct commit_queue {
126 int ncommits;
127 struct commit_queue_head head;
128 };
130 struct tog_color {
131 STAILQ_ENTRY(tog_color) entry;
132 regex_t regex;
133 short colorpair;
134 };
135 STAILQ_HEAD(tog_colors, tog_color);
137 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
138 static struct got_reflist_object_id_map *tog_refs_idmap;
139 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
141 static const struct got_error *
142 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
143 struct got_reference* re2)
145 const char *name1 = got_ref_get_name(re1);
146 const char *name2 = got_ref_get_name(re2);
147 int isbackup1, isbackup2;
149 /* Sort backup refs towards the bottom of the list. */
150 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
151 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
152 if (!isbackup1 && isbackup2) {
153 *cmp = -1;
154 return NULL;
155 } else if (isbackup1 && !isbackup2) {
156 *cmp = 1;
157 return NULL;
160 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
161 return NULL;
164 static const struct got_error *
165 tog_load_refs(struct got_repository *repo, int sort_by_date)
167 const struct got_error *err;
169 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
170 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
171 repo);
172 if (err)
173 return err;
175 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
176 repo);
179 static void
180 tog_free_refs(void)
182 if (tog_refs_idmap) {
183 got_reflist_object_id_map_free(tog_refs_idmap);
184 tog_refs_idmap = NULL;
186 got_ref_list_free(&tog_refs);
189 static const struct got_error *
190 add_color(struct tog_colors *colors, const char *pattern,
191 int idx, short color)
193 const struct got_error *err = NULL;
194 struct tog_color *tc;
195 int regerr = 0;
197 if (idx < 1 || idx > COLOR_PAIRS - 1)
198 return NULL;
200 init_pair(idx, color, -1);
202 tc = calloc(1, sizeof(*tc));
203 if (tc == NULL)
204 return got_error_from_errno("calloc");
205 regerr = regcomp(&tc->regex, pattern,
206 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
207 if (regerr) {
208 static char regerr_msg[512];
209 static char err_msg[512];
210 regerror(regerr, &tc->regex, regerr_msg,
211 sizeof(regerr_msg));
212 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
213 regerr_msg);
214 err = got_error_msg(GOT_ERR_REGEX, err_msg);
215 free(tc);
216 return err;
218 tc->colorpair = idx;
219 STAILQ_INSERT_HEAD(colors, tc, entry);
220 return NULL;
223 static void
224 free_colors(struct tog_colors *colors)
226 struct tog_color *tc;
228 while (!STAILQ_EMPTY(colors)) {
229 tc = STAILQ_FIRST(colors);
230 STAILQ_REMOVE_HEAD(colors, entry);
231 regfree(&tc->regex);
232 free(tc);
236 static struct tog_color *
237 get_color(struct tog_colors *colors, int colorpair)
239 struct tog_color *tc = NULL;
241 STAILQ_FOREACH(tc, colors, entry) {
242 if (tc->colorpair == colorpair)
243 return tc;
246 return NULL;
249 static int
250 default_color_value(const char *envvar)
252 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
253 return COLOR_MAGENTA;
254 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
255 return COLOR_CYAN;
256 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
257 return COLOR_YELLOW;
258 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
259 return COLOR_GREEN;
260 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
261 return COLOR_MAGENTA;
262 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
263 return COLOR_MAGENTA;
264 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
265 return COLOR_CYAN;
266 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
267 return COLOR_GREEN;
268 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
269 return COLOR_GREEN;
270 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
271 return COLOR_CYAN;
272 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
273 return COLOR_YELLOW;
274 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
275 return COLOR_GREEN;
276 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
277 return COLOR_MAGENTA;
278 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
279 return COLOR_YELLOW;
280 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
281 return COLOR_CYAN;
283 return -1;
286 static int
287 get_color_value(const char *envvar)
289 const char *val = getenv(envvar);
291 if (val == NULL)
292 return default_color_value(envvar);
294 if (strcasecmp(val, "black") == 0)
295 return COLOR_BLACK;
296 if (strcasecmp(val, "red") == 0)
297 return COLOR_RED;
298 if (strcasecmp(val, "green") == 0)
299 return COLOR_GREEN;
300 if (strcasecmp(val, "yellow") == 0)
301 return COLOR_YELLOW;
302 if (strcasecmp(val, "blue") == 0)
303 return COLOR_BLUE;
304 if (strcasecmp(val, "magenta") == 0)
305 return COLOR_MAGENTA;
306 if (strcasecmp(val, "cyan") == 0)
307 return COLOR_CYAN;
308 if (strcasecmp(val, "white") == 0)
309 return COLOR_WHITE;
310 if (strcasecmp(val, "default") == 0)
311 return -1;
313 return default_color_value(envvar);
316 struct tog_diff_view_state {
317 struct got_object_id *id1, *id2;
318 const char *label1, *label2;
319 FILE *f, *f1, *f2;
320 int fd1, fd2;
321 int lineno;
322 int first_displayed_line;
323 int last_displayed_line;
324 int eof;
325 int diff_context;
326 int ignore_whitespace;
327 int force_text_diff;
328 struct got_repository *repo;
329 struct got_diff_line *lines;
330 size_t nlines;
331 int matched_line;
332 int selected_line;
334 /* passed from log or blame view; may be NULL */
335 struct tog_view *parent_view;
336 };
338 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
339 static volatile sig_atomic_t tog_thread_error;
341 struct tog_log_thread_args {
342 pthread_cond_t need_commits;
343 pthread_cond_t commit_loaded;
344 int commits_needed;
345 int load_all;
346 struct got_commit_graph *graph;
347 struct commit_queue *commits;
348 const char *in_repo_path;
349 struct got_object_id *start_id;
350 struct got_repository *repo;
351 int *pack_fds;
352 int log_complete;
353 sig_atomic_t *quit;
354 struct commit_queue_entry **first_displayed_entry;
355 struct commit_queue_entry **selected_entry;
356 int *searching;
357 int *search_next_done;
358 regex_t *regex;
359 };
361 struct tog_log_view_state {
362 struct commit_queue commits;
363 struct commit_queue_entry *first_displayed_entry;
364 struct commit_queue_entry *last_displayed_entry;
365 struct commit_queue_entry *selected_entry;
366 int selected;
367 char *in_repo_path;
368 char *head_ref_name;
369 int log_branches;
370 struct got_repository *repo;
371 struct got_object_id *start_id;
372 sig_atomic_t quit;
373 pthread_t thread;
374 struct tog_log_thread_args thread_args;
375 struct commit_queue_entry *matched_entry;
376 struct commit_queue_entry *search_entry;
377 struct tog_colors colors;
378 int use_committer;
379 };
381 #define TOG_COLOR_DIFF_MINUS 1
382 #define TOG_COLOR_DIFF_PLUS 2
383 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
384 #define TOG_COLOR_DIFF_META 4
385 #define TOG_COLOR_TREE_SUBMODULE 5
386 #define TOG_COLOR_TREE_SYMLINK 6
387 #define TOG_COLOR_TREE_DIRECTORY 7
388 #define TOG_COLOR_TREE_EXECUTABLE 8
389 #define TOG_COLOR_COMMIT 9
390 #define TOG_COLOR_AUTHOR 10
391 #define TOG_COLOR_DATE 11
392 #define TOG_COLOR_REFS_HEADS 12
393 #define TOG_COLOR_REFS_TAGS 13
394 #define TOG_COLOR_REFS_REMOTES 14
395 #define TOG_COLOR_REFS_BACKUP 15
397 struct tog_blame_cb_args {
398 struct tog_blame_line *lines; /* one per line */
399 int nlines;
401 struct tog_view *view;
402 struct got_object_id *commit_id;
403 int *quit;
404 };
406 struct tog_blame_thread_args {
407 const char *path;
408 struct got_repository *repo;
409 struct tog_blame_cb_args *cb_args;
410 int *complete;
411 got_cancel_cb cancel_cb;
412 void *cancel_arg;
413 };
415 struct tog_blame {
416 FILE *f;
417 off_t filesize;
418 struct tog_blame_line *lines;
419 int nlines;
420 off_t *line_offsets;
421 pthread_t thread;
422 struct tog_blame_thread_args thread_args;
423 struct tog_blame_cb_args cb_args;
424 const char *path;
425 int *pack_fds;
426 };
428 struct tog_blame_view_state {
429 int first_displayed_line;
430 int last_displayed_line;
431 int selected_line;
432 int last_diffed_line;
433 int blame_complete;
434 int eof;
435 int done;
436 struct got_object_id_queue blamed_commits;
437 struct got_object_qid *blamed_commit;
438 char *path;
439 struct got_repository *repo;
440 struct got_object_id *commit_id;
441 struct got_object_id *id_to_log;
442 struct tog_blame blame;
443 int matched_line;
444 struct tog_colors colors;
445 };
447 struct tog_parent_tree {
448 TAILQ_ENTRY(tog_parent_tree) entry;
449 struct got_tree_object *tree;
450 struct got_tree_entry *first_displayed_entry;
451 struct got_tree_entry *selected_entry;
452 int selected;
453 };
455 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
457 struct tog_tree_view_state {
458 char *tree_label;
459 struct got_object_id *commit_id;/* commit which this tree belongs to */
460 struct got_tree_object *root; /* the commit's root tree entry */
461 struct got_tree_object *tree; /* currently displayed (sub-)tree */
462 struct got_tree_entry *first_displayed_entry;
463 struct got_tree_entry *last_displayed_entry;
464 struct got_tree_entry *selected_entry;
465 int ndisplayed, selected, show_ids;
466 struct tog_parent_trees parents; /* parent trees of current sub-tree */
467 char *head_ref_name;
468 struct got_repository *repo;
469 struct got_tree_entry *matched_entry;
470 struct tog_colors colors;
471 };
473 struct tog_reflist_entry {
474 TAILQ_ENTRY(tog_reflist_entry) entry;
475 struct got_reference *ref;
476 int idx;
477 };
479 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
481 struct tog_ref_view_state {
482 struct tog_reflist_head refs;
483 struct tog_reflist_entry *first_displayed_entry;
484 struct tog_reflist_entry *last_displayed_entry;
485 struct tog_reflist_entry *selected_entry;
486 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
487 struct got_repository *repo;
488 struct tog_reflist_entry *matched_entry;
489 struct tog_colors colors;
490 };
492 /*
493 * We implement two types of views: parent views and child views.
495 * The 'Tab' key switches focus between a parent view and its child view.
496 * Child views are shown side-by-side to their parent view, provided
497 * there is enough screen estate.
499 * When a new view is opened from within a parent view, this new view
500 * becomes a child view of the parent view, replacing any existing child.
502 * When a new view is opened from within a child view, this new view
503 * becomes a parent view which will obscure the views below until the
504 * user quits the new parent view by typing 'q'.
506 * This list of views contains parent views only.
507 * Child views are only pointed to by their parent view.
508 */
509 TAILQ_HEAD(tog_view_list_head, tog_view);
511 struct tog_view {
512 TAILQ_ENTRY(tog_view) entry;
513 WINDOW *window;
514 PANEL *panel;
515 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
516 int resized_y, resized_x; /* begin_y/x based on user resizing */
517 int maxx, x; /* max column and current start column */
518 int lines, cols; /* copies of LINES and COLS */
519 int nscrolled, offset; /* lines scrolled and hsplit line offset */
520 int gline, hiline; /* navigate to and highlight this nG line */
521 int ch, count; /* current keymap and count prefix */
522 int resized; /* set when in a resize event */
523 int focussed; /* Only set on one parent or child view at a time. */
524 int dying;
525 struct tog_view *parent;
526 struct tog_view *child;
528 /*
529 * This flag is initially set on parent views when a new child view
530 * is created. It gets toggled when the 'Tab' key switches focus
531 * between parent and child.
532 * The flag indicates whether focus should be passed on to our child
533 * view if this parent view gets picked for focus after another parent
534 * view was closed. This prevents child views from losing focus in such
535 * situations.
536 */
537 int focus_child;
539 enum tog_view_mode mode;
540 /* type-specific state */
541 enum tog_view_type type;
542 union {
543 struct tog_diff_view_state diff;
544 struct tog_log_view_state log;
545 struct tog_blame_view_state blame;
546 struct tog_tree_view_state tree;
547 struct tog_ref_view_state ref;
548 } state;
550 const struct got_error *(*show)(struct tog_view *);
551 const struct got_error *(*input)(struct tog_view **,
552 struct tog_view *, int);
553 const struct got_error *(*reset)(struct tog_view *);
554 const struct got_error *(*resize)(struct tog_view *, int);
555 const struct got_error *(*close)(struct tog_view *);
557 const struct got_error *(*search_start)(struct tog_view *);
558 const struct got_error *(*search_next)(struct tog_view *);
559 int search_started;
560 int searching;
561 #define TOG_SEARCH_FORWARD 1
562 #define TOG_SEARCH_BACKWARD 2
563 int search_next_done;
564 #define TOG_SEARCH_HAVE_MORE 1
565 #define TOG_SEARCH_NO_MORE 2
566 #define TOG_SEARCH_HAVE_NONE 3
567 regex_t regex;
568 regmatch_t regmatch;
569 };
571 static const struct got_error *open_diff_view(struct tog_view *,
572 struct got_object_id *, struct got_object_id *,
573 const char *, const char *, int, int, int, struct tog_view *,
574 struct got_repository *);
575 static const struct got_error *show_diff_view(struct tog_view *);
576 static const struct got_error *input_diff_view(struct tog_view **,
577 struct tog_view *, int);
578 static const struct got_error *reset_diff_view(struct tog_view *);
579 static const struct got_error* close_diff_view(struct tog_view *);
580 static const struct got_error *search_start_diff_view(struct tog_view *);
581 static const struct got_error *search_next_diff_view(struct tog_view *);
583 static const struct got_error *open_log_view(struct tog_view *,
584 struct got_object_id *, struct got_repository *,
585 const char *, const char *, int);
586 static const struct got_error * show_log_view(struct tog_view *);
587 static const struct got_error *input_log_view(struct tog_view **,
588 struct tog_view *, int);
589 static const struct got_error *resize_log_view(struct tog_view *, int);
590 static const struct got_error *close_log_view(struct tog_view *);
591 static const struct got_error *search_start_log_view(struct tog_view *);
592 static const struct got_error *search_next_log_view(struct tog_view *);
594 static const struct got_error *open_blame_view(struct tog_view *, char *,
595 struct got_object_id *, struct got_repository *);
596 static const struct got_error *show_blame_view(struct tog_view *);
597 static const struct got_error *input_blame_view(struct tog_view **,
598 struct tog_view *, int);
599 static const struct got_error *reset_blame_view(struct tog_view *);
600 static const struct got_error *close_blame_view(struct tog_view *);
601 static const struct got_error *search_start_blame_view(struct tog_view *);
602 static const struct got_error *search_next_blame_view(struct tog_view *);
604 static const struct got_error *open_tree_view(struct tog_view *,
605 struct got_object_id *, const char *, struct got_repository *);
606 static const struct got_error *show_tree_view(struct tog_view *);
607 static const struct got_error *input_tree_view(struct tog_view **,
608 struct tog_view *, int);
609 static const struct got_error *close_tree_view(struct tog_view *);
610 static const struct got_error *search_start_tree_view(struct tog_view *);
611 static const struct got_error *search_next_tree_view(struct tog_view *);
613 static const struct got_error *open_ref_view(struct tog_view *,
614 struct got_repository *);
615 static const struct got_error *show_ref_view(struct tog_view *);
616 static const struct got_error *input_ref_view(struct tog_view **,
617 struct tog_view *, int);
618 static const struct got_error *close_ref_view(struct tog_view *);
619 static const struct got_error *search_start_ref_view(struct tog_view *);
620 static const struct got_error *search_next_ref_view(struct tog_view *);
622 static volatile sig_atomic_t tog_sigwinch_received;
623 static volatile sig_atomic_t tog_sigpipe_received;
624 static volatile sig_atomic_t tog_sigcont_received;
625 static volatile sig_atomic_t tog_sigint_received;
626 static volatile sig_atomic_t tog_sigterm_received;
628 static void
629 tog_sigwinch(int signo)
631 tog_sigwinch_received = 1;
634 static void
635 tog_sigpipe(int signo)
637 tog_sigpipe_received = 1;
640 static void
641 tog_sigcont(int signo)
643 tog_sigcont_received = 1;
646 static void
647 tog_sigint(int signo)
649 tog_sigint_received = 1;
652 static void
653 tog_sigterm(int signo)
655 tog_sigterm_received = 1;
658 static int
659 tog_fatal_signal_received(void)
661 return (tog_sigpipe_received ||
662 tog_sigint_received || tog_sigint_received);
665 static const struct got_error *
666 view_close(struct tog_view *view)
668 const struct got_error *err = NULL, *child_err = NULL;
670 if (view->child) {
671 child_err = view_close(view->child);
672 view->child = NULL;
674 if (view->close)
675 err = view->close(view);
676 if (view->panel)
677 del_panel(view->panel);
678 if (view->window)
679 delwin(view->window);
680 free(view);
681 return err ? err : child_err;
684 static struct tog_view *
685 view_open(int nlines, int ncols, int begin_y, int begin_x,
686 enum tog_view_type type)
688 struct tog_view *view = calloc(1, sizeof(*view));
690 if (view == NULL)
691 return NULL;
693 view->type = type;
694 view->lines = LINES;
695 view->cols = COLS;
696 view->nlines = nlines ? nlines : LINES - begin_y;
697 view->ncols = ncols ? ncols : COLS - begin_x;
698 view->begin_y = begin_y;
699 view->begin_x = begin_x;
700 view->window = newwin(nlines, ncols, begin_y, begin_x);
701 if (view->window == NULL) {
702 view_close(view);
703 return NULL;
705 view->panel = new_panel(view->window);
706 if (view->panel == NULL ||
707 set_panel_userptr(view->panel, view) != OK) {
708 view_close(view);
709 return NULL;
712 keypad(view->window, TRUE);
713 return view;
716 static int
717 view_split_begin_x(int begin_x)
719 if (begin_x > 0 || COLS < 120)
720 return 0;
721 return (COLS - MAX(COLS / 2, 80));
724 /* XXX Stub till we decide what to do. */
725 static int
726 view_split_begin_y(int lines)
728 return lines * HSPLIT_SCALE;
731 static const struct got_error *view_resize(struct tog_view *);
733 static const struct got_error *
734 view_splitscreen(struct tog_view *view)
736 const struct got_error *err = NULL;
738 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
739 if (view->resized_y && view->resized_y < view->lines)
740 view->begin_y = view->resized_y;
741 else
742 view->begin_y = view_split_begin_y(view->nlines);
743 view->begin_x = 0;
744 } else if (!view->resized) {
745 if (view->resized_x && view->resized_x < view->cols - 1 &&
746 view->cols > 119)
747 view->begin_x = view->resized_x;
748 else
749 view->begin_x = view_split_begin_x(0);
750 view->begin_y = 0;
752 view->nlines = LINES - view->begin_y;
753 view->ncols = COLS - view->begin_x;
754 view->lines = LINES;
755 view->cols = COLS;
756 err = view_resize(view);
757 if (err)
758 return err;
760 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
761 view->parent->nlines = view->begin_y;
763 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
764 return got_error_from_errno("mvwin");
766 return NULL;
769 static const struct got_error *
770 view_fullscreen(struct tog_view *view)
772 const struct got_error *err = NULL;
774 view->begin_x = 0;
775 view->begin_y = view->resized ? view->begin_y : 0;
776 view->nlines = view->resized ? view->nlines : LINES;
777 view->ncols = COLS;
778 view->lines = LINES;
779 view->cols = COLS;
780 err = view_resize(view);
781 if (err)
782 return err;
784 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
785 return got_error_from_errno("mvwin");
787 return NULL;
790 static int
791 view_is_parent_view(struct tog_view *view)
793 return view->parent == NULL;
796 static int
797 view_is_splitscreen(struct tog_view *view)
799 return view->begin_x > 0 || view->begin_y > 0;
802 static int
803 view_is_fullscreen(struct tog_view *view)
805 return view->nlines == LINES && view->ncols == COLS;
808 static int
809 view_is_hsplit_top(struct tog_view *view)
811 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
812 view_is_splitscreen(view->child);
815 static void
816 view_border(struct tog_view *view)
818 PANEL *panel;
819 const struct tog_view *view_above;
821 if (view->parent)
822 return view_border(view->parent);
824 panel = panel_above(view->panel);
825 if (panel == NULL)
826 return;
828 view_above = panel_userptr(panel);
829 if (view->mode == TOG_VIEW_SPLIT_HRZN)
830 mvwhline(view->window, view_above->begin_y - 1,
831 view->begin_x, got_locale_is_utf8() ?
832 ACS_HLINE : '-', view->ncols);
833 else
834 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
835 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
838 static const struct got_error *view_init_hsplit(struct tog_view *, int);
839 static const struct got_error *request_log_commits(struct tog_view *);
840 static const struct got_error *offset_selection_down(struct tog_view *);
841 static void offset_selection_up(struct tog_view *);
842 static void view_get_split(struct tog_view *, int *, int *);
844 static const struct got_error *
845 view_resize(struct tog_view *view)
847 const struct got_error *err = NULL;
848 int dif, nlines, ncols;
850 dif = LINES - view->lines; /* line difference */
852 if (view->lines > LINES)
853 nlines = view->nlines - (view->lines - LINES);
854 else
855 nlines = view->nlines + (LINES - view->lines);
856 if (view->cols > COLS)
857 ncols = view->ncols - (view->cols - COLS);
858 else
859 ncols = view->ncols + (COLS - view->cols);
861 if (view->child) {
862 int hs = view->child->begin_y;
864 if (!view_is_fullscreen(view))
865 view->child->begin_x = view_split_begin_x(view->begin_x);
866 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
867 view->child->begin_x == 0) {
868 ncols = COLS;
870 view_fullscreen(view->child);
871 if (view->child->focussed)
872 show_panel(view->child->panel);
873 else
874 show_panel(view->panel);
875 } else {
876 ncols = view->child->begin_x;
878 view_splitscreen(view->child);
879 show_panel(view->child->panel);
881 /*
882 * XXX This is ugly and needs to be moved into the above
883 * logic but "works" for now and my attempts at moving it
884 * break either 'tab' or 'F' key maps in horizontal splits.
885 */
886 if (hs) {
887 err = view_splitscreen(view->child);
888 if (err)
889 return err;
890 if (dif < 0) { /* top split decreased */
891 err = offset_selection_down(view);
892 if (err)
893 return err;
895 view_border(view);
896 update_panels();
897 doupdate();
898 show_panel(view->child->panel);
899 nlines = view->nlines;
901 } else if (view->parent == NULL)
902 ncols = COLS;
904 if (view->resize && dif > 0) {
905 err = view->resize(view, dif);
906 if (err)
907 return err;
910 if (wresize(view->window, nlines, ncols) == ERR)
911 return got_error_from_errno("wresize");
912 if (replace_panel(view->panel, view->window) == ERR)
913 return got_error_from_errno("replace_panel");
914 wclear(view->window);
916 view->nlines = nlines;
917 view->ncols = ncols;
918 view->lines = LINES;
919 view->cols = COLS;
921 return NULL;
924 static const struct got_error *
925 resize_log_view(struct tog_view *view, int increase)
927 struct tog_log_view_state *s = &view->state.log;
928 const struct got_error *err = NULL;
929 int n = 0;
931 if (s->selected_entry)
932 n = s->selected_entry->idx + view->lines - s->selected;
934 /*
935 * Request commits to account for the increased
936 * height so we have enough to populate the view.
937 */
938 if (s->commits.ncommits < n) {
939 view->nscrolled = n - s->commits.ncommits + increase + 1;
940 err = request_log_commits(view);
943 return err;
946 static void
947 view_adjust_offset(struct tog_view *view, int n)
949 if (n == 0)
950 return;
952 if (view->parent && view->parent->offset) {
953 if (view->parent->offset + n >= 0)
954 view->parent->offset += n;
955 else
956 view->parent->offset = 0;
957 } else if (view->offset) {
958 if (view->offset - n >= 0)
959 view->offset -= n;
960 else
961 view->offset = 0;
965 static const struct got_error *
966 view_resize_split(struct tog_view *view, int resize)
968 const struct got_error *err = NULL;
969 struct tog_view *v = NULL;
971 if (view->parent)
972 v = view->parent;
973 else
974 v = view;
976 if (!v->child || !view_is_splitscreen(v->child))
977 return NULL;
979 v->resized = v->child->resized = resize; /* lock for resize event */
981 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
982 if (v->child->resized_y)
983 v->child->begin_y = v->child->resized_y;
984 if (view->parent)
985 v->child->begin_y -= resize;
986 else
987 v->child->begin_y += resize;
988 if (v->child->begin_y < 3) {
989 view->count = 0;
990 v->child->begin_y = 3;
991 } else if (v->child->begin_y > LINES - 1) {
992 view->count = 0;
993 v->child->begin_y = LINES - 1;
995 v->ncols = COLS;
996 v->child->ncols = COLS;
997 view_adjust_offset(view, resize);
998 err = view_init_hsplit(v, v->child->begin_y);
999 if (err)
1000 return err;
1001 v->child->resized_y = v->child->begin_y;
1002 } else {
1003 if (v->child->resized_x)
1004 v->child->begin_x = v->child->resized_x;
1005 if (view->parent)
1006 v->child->begin_x -= resize;
1007 else
1008 v->child->begin_x += resize;
1009 if (v->child->begin_x < 11) {
1010 view->count = 0;
1011 v->child->begin_x = 11;
1012 } else if (v->child->begin_x > COLS - 1) {
1013 view->count = 0;
1014 v->child->begin_x = COLS - 1;
1016 v->child->resized_x = v->child->begin_x;
1019 v->child->mode = v->mode;
1020 v->child->nlines = v->lines - v->child->begin_y;
1021 v->child->ncols = v->cols - v->child->begin_x;
1022 v->focus_child = 1;
1024 err = view_fullscreen(v);
1025 if (err)
1026 return err;
1027 err = view_splitscreen(v->child);
1028 if (err)
1029 return err;
1031 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1032 err = offset_selection_down(v->child);
1033 if (err)
1034 return err;
1037 if (v->resize)
1038 err = v->resize(v, 0);
1039 else if (v->child->resize)
1040 err = v->child->resize(v->child, 0);
1042 v->resized = v->child->resized = 0;
1044 return err;
1047 static void
1048 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1050 struct tog_view *v = src->child ? src->child : src;
1052 dst->resized_x = v->resized_x;
1053 dst->resized_y = v->resized_y;
1056 static const struct got_error *
1057 view_close_child(struct tog_view *view)
1059 const struct got_error *err = NULL;
1061 if (view->child == NULL)
1062 return NULL;
1064 err = view_close(view->child);
1065 view->child = NULL;
1066 return err;
1069 static const struct got_error *
1070 view_set_child(struct tog_view *view, struct tog_view *child)
1072 const struct got_error *err = NULL;
1074 view->child = child;
1075 child->parent = view;
1077 err = view_resize(view);
1078 if (err)
1079 return err;
1081 if (view->child->resized_x || view->child->resized_y)
1082 err = view_resize_split(view, 0);
1084 return err;
1087 static const struct got_error *view_dispatch_request(struct tog_view **,
1088 struct tog_view *, enum tog_view_type, int, int);
1090 static const struct got_error *
1091 view_request_new(struct tog_view **requested, struct tog_view *view,
1092 enum tog_view_type request)
1094 struct tog_view *new_view = NULL;
1095 const struct got_error *err;
1096 int y = 0, x = 0;
1098 *requested = NULL;
1100 if (view_is_parent_view(view))
1101 view_get_split(view, &y, &x);
1103 err = view_dispatch_request(&new_view, view, request, y, x);
1104 if (err)
1105 return err;
1107 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN) {
1108 err = view_init_hsplit(view, y);
1109 if (err)
1110 return err;
1113 view->focussed = 0;
1114 new_view->focussed = 1;
1115 new_view->mode = view->mode;
1116 new_view->nlines = view->lines - y;
1118 if (view_is_parent_view(view)) {
1119 view_transfer_size(new_view, view);
1120 err = view_close_child(view);
1121 if (err)
1122 return err;
1123 err = view_set_child(view, new_view);
1124 if (err)
1125 return err;
1126 view->focus_child = 1;
1127 } else
1128 *requested = new_view;
1130 return NULL;
1133 static void
1134 tog_resizeterm(void)
1136 int cols, lines;
1137 struct winsize size;
1139 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1140 cols = 80; /* Default */
1141 lines = 24;
1142 } else {
1143 cols = size.ws_col;
1144 lines = size.ws_row;
1146 resize_term(lines, cols);
1149 static const struct got_error *
1150 view_search_start(struct tog_view *view)
1152 const struct got_error *err = NULL;
1153 struct tog_view *v = view;
1154 char pattern[1024];
1155 int ret;
1157 if (view->search_started) {
1158 regfree(&view->regex);
1159 view->searching = 0;
1160 memset(&view->regmatch, 0, sizeof(view->regmatch));
1162 view->search_started = 0;
1164 if (view->nlines < 1)
1165 return NULL;
1167 if (view_is_hsplit_top(view))
1168 v = view->child;
1170 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1171 wclrtoeol(v->window);
1173 nodelay(view->window, FALSE); /* block for search term input */
1174 nocbreak();
1175 echo();
1176 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1177 wrefresh(v->window);
1178 cbreak();
1179 noecho();
1180 nodelay(view->window, TRUE);
1181 if (ret == ERR)
1182 return NULL;
1184 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1185 err = view->search_start(view);
1186 if (err) {
1187 regfree(&view->regex);
1188 return err;
1190 view->search_started = 1;
1191 view->searching = TOG_SEARCH_FORWARD;
1192 view->search_next_done = 0;
1193 view->search_next(view);
1196 return NULL;
1199 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1200 static const struct got_error *
1201 switch_split(struct tog_view *view)
1203 const struct got_error *err = NULL;
1204 struct tog_view *v = NULL;
1206 if (view->parent)
1207 v = view->parent;
1208 else
1209 v = view;
1211 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1212 v->mode = TOG_VIEW_SPLIT_VERT;
1213 else
1214 v->mode = TOG_VIEW_SPLIT_HRZN;
1216 if (!v->child)
1217 return NULL;
1218 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1219 v->mode = TOG_VIEW_SPLIT_NONE;
1221 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1222 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1223 v->child->begin_y = v->child->resized_y;
1224 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1225 v->child->begin_x = v->child->resized_x;
1228 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1229 v->ncols = COLS;
1230 v->child->ncols = COLS;
1231 v->child->nscrolled = LINES - v->child->nlines;
1233 err = view_init_hsplit(v, v->child->begin_y);
1234 if (err)
1235 return err;
1237 v->child->mode = v->mode;
1238 v->child->nlines = v->lines - v->child->begin_y;
1239 v->focus_child = 1;
1241 err = view_fullscreen(v);
1242 if (err)
1243 return err;
1244 err = view_splitscreen(v->child);
1245 if (err)
1246 return err;
1248 if (v->mode == TOG_VIEW_SPLIT_NONE)
1249 v->mode = TOG_VIEW_SPLIT_VERT;
1250 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1251 err = offset_selection_down(v);
1252 if (err)
1253 return err;
1254 err = offset_selection_down(v->child);
1255 if (err)
1256 return err;
1257 } else {
1258 offset_selection_up(v);
1259 offset_selection_up(v->child);
1261 if (v->resize)
1262 err = v->resize(v, 0);
1263 else if (v->child->resize)
1264 err = v->child->resize(v->child, 0);
1266 return err;
1270 * Compute view->count from numeric input. Assign total to view->count and
1271 * return first non-numeric key entered.
1273 static int
1274 get_compound_key(struct tog_view *view, int c)
1276 struct tog_view *v = view;
1277 int x, n = 0;
1279 if (view_is_hsplit_top(view))
1280 v = view->child;
1281 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1282 v = view->parent;
1284 view->count = 0;
1285 cbreak(); /* block for input */
1286 nodelay(view->window, FALSE);
1287 wmove(v->window, v->nlines - 1, 0);
1288 wclrtoeol(v->window);
1289 waddch(v->window, ':');
1291 do {
1292 x = getcurx(v->window);
1293 if (x != ERR && x < view->ncols) {
1294 waddch(v->window, c);
1295 wrefresh(v->window);
1299 * Don't overflow. Max valid request should be the greatest
1300 * between the longest and total lines; cap at 10 million.
1302 if (n >= 9999999)
1303 n = 9999999;
1304 else
1305 n = n * 10 + (c - '0');
1306 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1308 if (c == 'G' || c == 'g') { /* nG key map */
1309 view->gline = view->hiline = n;
1310 n = 0;
1311 c = 0;
1314 /* Massage excessive or inapplicable values at the input handler. */
1315 view->count = n;
1317 return c;
1320 static const struct got_error *
1321 view_input(struct tog_view **new, int *done, struct tog_view *view,
1322 struct tog_view_list_head *views)
1324 const struct got_error *err = NULL;
1325 struct tog_view *v;
1326 int ch, errcode;
1328 *new = NULL;
1330 /* Clear "no matches" indicator. */
1331 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1332 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1333 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1334 view->count = 0;
1337 if (view->searching && !view->search_next_done) {
1338 errcode = pthread_mutex_unlock(&tog_mutex);
1339 if (errcode)
1340 return got_error_set_errno(errcode,
1341 "pthread_mutex_unlock");
1342 sched_yield();
1343 errcode = pthread_mutex_lock(&tog_mutex);
1344 if (errcode)
1345 return got_error_set_errno(errcode,
1346 "pthread_mutex_lock");
1347 view->search_next(view);
1348 return NULL;
1351 /* Allow threads to make progress while we are waiting for input. */
1352 errcode = pthread_mutex_unlock(&tog_mutex);
1353 if (errcode)
1354 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1355 /* If we have an unfinished count, let C-g or backspace abort. */
1356 if (view->count && --view->count) {
1357 cbreak();
1358 nodelay(view->window, TRUE);
1359 ch = wgetch(view->window);
1360 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1361 view->count = 0;
1362 else
1363 ch = view->ch;
1364 } else {
1365 ch = wgetch(view->window);
1366 if (ch >= '1' && ch <= '9')
1367 view->ch = ch = get_compound_key(view, ch);
1369 if (view->hiline && ch != ERR && ch != 0)
1370 view->hiline = 0; /* key pressed, clear line highlight */
1371 nodelay(view->window, TRUE);
1372 errcode = pthread_mutex_lock(&tog_mutex);
1373 if (errcode)
1374 return got_error_set_errno(errcode, "pthread_mutex_lock");
1376 if (tog_sigwinch_received || tog_sigcont_received) {
1377 tog_resizeterm();
1378 tog_sigwinch_received = 0;
1379 tog_sigcont_received = 0;
1380 TAILQ_FOREACH(v, views, entry) {
1381 err = view_resize(v);
1382 if (err)
1383 return err;
1384 err = v->input(new, v, KEY_RESIZE);
1385 if (err)
1386 return err;
1387 if (v->child) {
1388 err = view_resize(v->child);
1389 if (err)
1390 return err;
1391 err = v->child->input(new, v->child,
1392 KEY_RESIZE);
1393 if (err)
1394 return err;
1395 if (v->child->resized_x || v->child->resized_y) {
1396 err = view_resize_split(v, 0);
1397 if (err)
1398 return err;
1404 switch (ch) {
1405 case '\t':
1406 view->count = 0;
1407 if (view->child) {
1408 view->focussed = 0;
1409 view->child->focussed = 1;
1410 view->focus_child = 1;
1411 } else if (view->parent) {
1412 view->focussed = 0;
1413 view->parent->focussed = 1;
1414 view->parent->focus_child = 0;
1415 if (!view_is_splitscreen(view)) {
1416 if (view->parent->resize) {
1417 err = view->parent->resize(view->parent,
1418 0);
1419 if (err)
1420 return err;
1422 offset_selection_up(view->parent);
1423 err = view_fullscreen(view->parent);
1424 if (err)
1425 return err;
1428 break;
1429 case 'q':
1430 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1431 if (view->parent->resize) {
1432 /* might need more commits to fill fullscreen */
1433 err = view->parent->resize(view->parent, 0);
1434 if (err)
1435 break;
1437 offset_selection_up(view->parent);
1439 err = view->input(new, view, ch);
1440 view->dying = 1;
1441 break;
1442 case 'Q':
1443 *done = 1;
1444 break;
1445 case 'F':
1446 view->count = 0;
1447 if (view_is_parent_view(view)) {
1448 if (view->child == NULL)
1449 break;
1450 if (view_is_splitscreen(view->child)) {
1451 view->focussed = 0;
1452 view->child->focussed = 1;
1453 err = view_fullscreen(view->child);
1454 } else {
1455 err = view_splitscreen(view->child);
1456 if (!err)
1457 err = view_resize_split(view, 0);
1459 if (err)
1460 break;
1461 err = view->child->input(new, view->child,
1462 KEY_RESIZE);
1463 } else {
1464 if (view_is_splitscreen(view)) {
1465 view->parent->focussed = 0;
1466 view->focussed = 1;
1467 err = view_fullscreen(view);
1468 } else {
1469 err = view_splitscreen(view);
1470 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1471 err = view_resize(view->parent);
1472 if (!err)
1473 err = view_resize_split(view, 0);
1475 if (err)
1476 break;
1477 err = view->input(new, view, KEY_RESIZE);
1479 if (err)
1480 break;
1481 if (view->resize) {
1482 err = view->resize(view, 0);
1483 if (err)
1484 break;
1486 if (view->parent)
1487 err = offset_selection_down(view->parent);
1488 if (!err)
1489 err = offset_selection_down(view);
1490 break;
1491 case 'S':
1492 view->count = 0;
1493 err = switch_split(view);
1494 break;
1495 case '-':
1496 err = view_resize_split(view, -1);
1497 break;
1498 case '+':
1499 err = view_resize_split(view, 1);
1500 break;
1501 case KEY_RESIZE:
1502 break;
1503 case '/':
1504 view->count = 0;
1505 if (view->search_start)
1506 view_search_start(view);
1507 else
1508 err = view->input(new, view, ch);
1509 break;
1510 case 'N':
1511 case 'n':
1512 if (view->search_started && view->search_next) {
1513 view->searching = (ch == 'n' ?
1514 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1515 view->search_next_done = 0;
1516 view->search_next(view);
1517 } else
1518 err = view->input(new, view, ch);
1519 break;
1520 case 'A':
1521 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS)
1522 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1523 else
1524 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1525 TAILQ_FOREACH(v, views, entry) {
1526 if (v->reset) {
1527 err = v->reset(v);
1528 if (err)
1529 return err;
1531 if (v->child && v->child->reset) {
1532 err = v->child->reset(v->child);
1533 if (err)
1534 return err;
1537 break;
1538 default:
1539 err = view->input(new, view, ch);
1540 break;
1543 return err;
1546 static int
1547 view_needs_focus_indication(struct tog_view *view)
1549 if (view_is_parent_view(view)) {
1550 if (view->child == NULL || view->child->focussed)
1551 return 0;
1552 if (!view_is_splitscreen(view->child))
1553 return 0;
1554 } else if (!view_is_splitscreen(view))
1555 return 0;
1557 return view->focussed;
1560 static const struct got_error *
1561 view_loop(struct tog_view *view)
1563 const struct got_error *err = NULL;
1564 struct tog_view_list_head views;
1565 struct tog_view *new_view;
1566 char *mode;
1567 int fast_refresh = 10;
1568 int done = 0, errcode;
1570 mode = getenv("TOG_VIEW_SPLIT_MODE");
1571 if (!mode || !(*mode == 'h' || *mode == 'H'))
1572 view->mode = TOG_VIEW_SPLIT_VERT;
1573 else
1574 view->mode = TOG_VIEW_SPLIT_HRZN;
1576 errcode = pthread_mutex_lock(&tog_mutex);
1577 if (errcode)
1578 return got_error_set_errno(errcode, "pthread_mutex_lock");
1580 TAILQ_INIT(&views);
1581 TAILQ_INSERT_HEAD(&views, view, entry);
1583 view->focussed = 1;
1584 err = view->show(view);
1585 if (err)
1586 return err;
1587 update_panels();
1588 doupdate();
1589 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1590 !tog_fatal_signal_received()) {
1591 /* Refresh fast during initialization, then become slower. */
1592 if (fast_refresh && fast_refresh-- == 0)
1593 halfdelay(10); /* switch to once per second */
1595 err = view_input(&new_view, &done, view, &views);
1596 if (err)
1597 break;
1598 if (view->dying) {
1599 struct tog_view *v, *prev = NULL;
1601 if (view_is_parent_view(view))
1602 prev = TAILQ_PREV(view, tog_view_list_head,
1603 entry);
1604 else if (view->parent)
1605 prev = view->parent;
1607 if (view->parent) {
1608 view->parent->child = NULL;
1609 view->parent->focus_child = 0;
1610 /* Restore fullscreen line height. */
1611 view->parent->nlines = view->parent->lines;
1612 err = view_resize(view->parent);
1613 if (err)
1614 break;
1615 /* Make resized splits persist. */
1616 view_transfer_size(view->parent, view);
1617 } else
1618 TAILQ_REMOVE(&views, view, entry);
1620 err = view_close(view);
1621 if (err)
1622 goto done;
1624 view = NULL;
1625 TAILQ_FOREACH(v, &views, entry) {
1626 if (v->focussed)
1627 break;
1629 if (view == NULL && new_view == NULL) {
1630 /* No view has focus. Try to pick one. */
1631 if (prev)
1632 view = prev;
1633 else if (!TAILQ_EMPTY(&views)) {
1634 view = TAILQ_LAST(&views,
1635 tog_view_list_head);
1637 if (view) {
1638 if (view->focus_child) {
1639 view->child->focussed = 1;
1640 view = view->child;
1641 } else
1642 view->focussed = 1;
1646 if (new_view) {
1647 struct tog_view *v, *t;
1648 /* Only allow one parent view per type. */
1649 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1650 if (v->type != new_view->type)
1651 continue;
1652 TAILQ_REMOVE(&views, v, entry);
1653 err = view_close(v);
1654 if (err)
1655 goto done;
1656 break;
1658 TAILQ_INSERT_TAIL(&views, new_view, entry);
1659 view = new_view;
1661 if (view) {
1662 if (view_is_parent_view(view)) {
1663 if (view->child && view->child->focussed)
1664 view = view->child;
1665 } else {
1666 if (view->parent && view->parent->focussed)
1667 view = view->parent;
1669 show_panel(view->panel);
1670 if (view->child && view_is_splitscreen(view->child))
1671 show_panel(view->child->panel);
1672 if (view->parent && view_is_splitscreen(view)) {
1673 err = view->parent->show(view->parent);
1674 if (err)
1675 goto done;
1677 err = view->show(view);
1678 if (err)
1679 goto done;
1680 if (view->child) {
1681 err = view->child->show(view->child);
1682 if (err)
1683 goto done;
1685 update_panels();
1686 doupdate();
1689 done:
1690 while (!TAILQ_EMPTY(&views)) {
1691 const struct got_error *close_err;
1692 view = TAILQ_FIRST(&views);
1693 TAILQ_REMOVE(&views, view, entry);
1694 close_err = view_close(view);
1695 if (close_err && err == NULL)
1696 err = close_err;
1699 errcode = pthread_mutex_unlock(&tog_mutex);
1700 if (errcode && err == NULL)
1701 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1703 return err;
1706 __dead static void
1707 usage_log(void)
1709 endwin();
1710 fprintf(stderr,
1711 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1712 getprogname());
1713 exit(1);
1716 /* Create newly allocated wide-character string equivalent to a byte string. */
1717 static const struct got_error *
1718 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1720 char *vis = NULL;
1721 const struct got_error *err = NULL;
1723 *ws = NULL;
1724 *wlen = mbstowcs(NULL, s, 0);
1725 if (*wlen == (size_t)-1) {
1726 int vislen;
1727 if (errno != EILSEQ)
1728 return got_error_from_errno("mbstowcs");
1730 /* byte string invalid in current encoding; try to "fix" it */
1731 err = got_mbsavis(&vis, &vislen, s);
1732 if (err)
1733 return err;
1734 *wlen = mbstowcs(NULL, vis, 0);
1735 if (*wlen == (size_t)-1) {
1736 err = got_error_from_errno("mbstowcs"); /* give up */
1737 goto done;
1741 *ws = calloc(*wlen + 1, sizeof(**ws));
1742 if (*ws == NULL) {
1743 err = got_error_from_errno("calloc");
1744 goto done;
1747 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1748 err = got_error_from_errno("mbstowcs");
1749 done:
1750 free(vis);
1751 if (err) {
1752 free(*ws);
1753 *ws = NULL;
1754 *wlen = 0;
1756 return err;
1759 static const struct got_error *
1760 expand_tab(char **ptr, const char *src)
1762 char *dst;
1763 size_t len, n, idx = 0, sz = 0;
1765 *ptr = NULL;
1766 n = len = strlen(src);
1767 dst = malloc(n + 1);
1768 if (dst == NULL)
1769 return got_error_from_errno("malloc");
1771 while (idx < len && src[idx]) {
1772 const char c = src[idx];
1774 if (c == '\t') {
1775 size_t nb = TABSIZE - sz % TABSIZE;
1776 char *p;
1778 p = realloc(dst, n + nb);
1779 if (p == NULL) {
1780 free(dst);
1781 return got_error_from_errno("realloc");
1784 dst = p;
1785 n += nb;
1786 memset(dst + sz, ' ', nb);
1787 sz += nb;
1788 } else
1789 dst[sz++] = src[idx];
1790 ++idx;
1793 dst[sz] = '\0';
1794 *ptr = dst;
1795 return NULL;
1799 * Advance at most n columns from wline starting at offset off.
1800 * Return the index to the first character after the span operation.
1801 * Return the combined column width of all spanned wide character in
1802 * *rcol.
1804 static int
1805 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
1807 int width, i, cols = 0;
1809 if (n == 0) {
1810 *rcol = cols;
1811 return off;
1814 for (i = off; wline[i] != L'\0'; ++i) {
1815 if (wline[i] == L'\t')
1816 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
1817 else
1818 width = wcwidth(wline[i]);
1820 if (width == -1) {
1821 width = 1;
1822 wline[i] = L'.';
1825 if (cols + width > n)
1826 break;
1827 cols += width;
1830 *rcol = cols;
1831 return i;
1835 * Format a line for display, ensuring that it won't overflow a width limit.
1836 * With scrolling, the width returned refers to the scrolled version of the
1837 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
1839 static const struct got_error *
1840 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
1841 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
1843 const struct got_error *err = NULL;
1844 int cols;
1845 wchar_t *wline = NULL;
1846 char *exstr = NULL;
1847 size_t wlen;
1848 int i, scrollx;
1850 *wlinep = NULL;
1851 *widthp = 0;
1853 if (expand) {
1854 err = expand_tab(&exstr, line);
1855 if (err)
1856 return err;
1859 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
1860 free(exstr);
1861 if (err)
1862 return err;
1864 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
1866 if (wlen > 0 && wline[wlen - 1] == L'\n') {
1867 wline[wlen - 1] = L'\0';
1868 wlen--;
1870 if (wlen > 0 && wline[wlen - 1] == L'\r') {
1871 wline[wlen - 1] = L'\0';
1872 wlen--;
1875 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
1876 wline[i] = L'\0';
1878 if (widthp)
1879 *widthp = cols;
1880 if (scrollxp)
1881 *scrollxp = scrollx;
1882 if (err)
1883 free(wline);
1884 else
1885 *wlinep = wline;
1886 return err;
1889 static const struct got_error*
1890 build_refs_str(char **refs_str, struct got_reflist_head *refs,
1891 struct got_object_id *id, struct got_repository *repo)
1893 static const struct got_error *err = NULL;
1894 struct got_reflist_entry *re;
1895 char *s;
1896 const char *name;
1898 *refs_str = NULL;
1900 TAILQ_FOREACH(re, refs, entry) {
1901 struct got_tag_object *tag = NULL;
1902 struct got_object_id *ref_id;
1903 int cmp;
1905 name = got_ref_get_name(re->ref);
1906 if (strcmp(name, GOT_REF_HEAD) == 0)
1907 continue;
1908 if (strncmp(name, "refs/", 5) == 0)
1909 name += 5;
1910 if (strncmp(name, "got/", 4) == 0 &&
1911 strncmp(name, "got/backup/", 11) != 0)
1912 continue;
1913 if (strncmp(name, "heads/", 6) == 0)
1914 name += 6;
1915 if (strncmp(name, "remotes/", 8) == 0) {
1916 name += 8;
1917 s = strstr(name, "/" GOT_REF_HEAD);
1918 if (s != NULL && s[strlen(s)] == '\0')
1919 continue;
1921 err = got_ref_resolve(&ref_id, repo, re->ref);
1922 if (err)
1923 break;
1924 if (strncmp(name, "tags/", 5) == 0) {
1925 err = got_object_open_as_tag(&tag, repo, ref_id);
1926 if (err) {
1927 if (err->code != GOT_ERR_OBJ_TYPE) {
1928 free(ref_id);
1929 break;
1931 /* Ref points at something other than a tag. */
1932 err = NULL;
1933 tag = NULL;
1936 cmp = got_object_id_cmp(tag ?
1937 got_object_tag_get_object_id(tag) : ref_id, id);
1938 free(ref_id);
1939 if (tag)
1940 got_object_tag_close(tag);
1941 if (cmp != 0)
1942 continue;
1943 s = *refs_str;
1944 if (asprintf(refs_str, "%s%s%s", s ? s : "",
1945 s ? ", " : "", name) == -1) {
1946 err = got_error_from_errno("asprintf");
1947 free(s);
1948 *refs_str = NULL;
1949 break;
1951 free(s);
1954 return err;
1957 static const struct got_error *
1958 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
1959 int col_tab_align)
1961 char *smallerthan;
1963 smallerthan = strchr(author, '<');
1964 if (smallerthan && smallerthan[1] != '\0')
1965 author = smallerthan + 1;
1966 author[strcspn(author, "@>")] = '\0';
1967 return format_line(wauthor, author_width, NULL, author, 0, limit,
1968 col_tab_align, 0);
1971 static const struct got_error *
1972 draw_commit(struct tog_view *view, struct got_commit_object *commit,
1973 struct got_object_id *id, const size_t date_display_cols,
1974 int author_display_cols)
1976 struct tog_log_view_state *s = &view->state.log;
1977 const struct got_error *err = NULL;
1978 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
1979 char *logmsg0 = NULL, *logmsg = NULL;
1980 char *author = NULL;
1981 wchar_t *wlogmsg = NULL, *wauthor = NULL;
1982 int author_width, logmsg_width;
1983 char *newline, *line = NULL;
1984 int col, limit, scrollx;
1985 const int avail = view->ncols;
1986 struct tm tm;
1987 time_t committer_time;
1988 struct tog_color *tc;
1990 committer_time = got_object_commit_get_committer_time(commit);
1991 if (gmtime_r(&committer_time, &tm) == NULL)
1992 return got_error_from_errno("gmtime_r");
1993 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
1994 return got_error(GOT_ERR_NO_SPACE);
1996 if (avail <= date_display_cols)
1997 limit = MIN(sizeof(datebuf) - 1, avail);
1998 else
1999 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2000 tc = get_color(&s->colors, TOG_COLOR_DATE);
2001 if (tc)
2002 wattr_on(view->window,
2003 COLOR_PAIR(tc->colorpair), NULL);
2004 waddnstr(view->window, datebuf, limit);
2005 if (tc)
2006 wattr_off(view->window,
2007 COLOR_PAIR(tc->colorpair), NULL);
2008 col = limit;
2009 if (col > avail)
2010 goto done;
2012 if (avail >= 120) {
2013 char *id_str;
2014 err = got_object_id_str(&id_str, id);
2015 if (err)
2016 goto done;
2017 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2018 if (tc)
2019 wattr_on(view->window,
2020 COLOR_PAIR(tc->colorpair), NULL);
2021 wprintw(view->window, "%.8s ", id_str);
2022 if (tc)
2023 wattr_off(view->window,
2024 COLOR_PAIR(tc->colorpair), NULL);
2025 free(id_str);
2026 col += 9;
2027 if (col > avail)
2028 goto done;
2031 if (s->use_committer)
2032 author = strdup(got_object_commit_get_committer(commit));
2033 else
2034 author = strdup(got_object_commit_get_author(commit));
2035 if (author == NULL) {
2036 err = got_error_from_errno("strdup");
2037 goto done;
2039 err = format_author(&wauthor, &author_width, author, avail - col, col);
2040 if (err)
2041 goto done;
2042 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2043 if (tc)
2044 wattr_on(view->window,
2045 COLOR_PAIR(tc->colorpair), NULL);
2046 waddwstr(view->window, wauthor);
2047 if (tc)
2048 wattr_off(view->window,
2049 COLOR_PAIR(tc->colorpair), NULL);
2050 col += author_width;
2051 while (col < avail && author_width < author_display_cols + 2) {
2052 waddch(view->window, ' ');
2053 col++;
2054 author_width++;
2056 if (col > avail)
2057 goto done;
2059 err = got_object_commit_get_logmsg(&logmsg0, commit);
2060 if (err)
2061 goto done;
2062 logmsg = logmsg0;
2063 while (*logmsg == '\n')
2064 logmsg++;
2065 newline = strchr(logmsg, '\n');
2066 if (newline)
2067 *newline = '\0';
2068 limit = avail - col;
2069 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2070 limit--; /* for the border */
2071 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2072 limit, col, 1);
2073 if (err)
2074 goto done;
2075 waddwstr(view->window, &wlogmsg[scrollx]);
2076 col += MAX(logmsg_width, 0);
2077 while (col < avail) {
2078 waddch(view->window, ' ');
2079 col++;
2081 done:
2082 free(logmsg0);
2083 free(wlogmsg);
2084 free(author);
2085 free(wauthor);
2086 free(line);
2087 return err;
2090 static struct commit_queue_entry *
2091 alloc_commit_queue_entry(struct got_commit_object *commit,
2092 struct got_object_id *id)
2094 struct commit_queue_entry *entry;
2096 entry = calloc(1, sizeof(*entry));
2097 if (entry == NULL)
2098 return NULL;
2100 entry->id = id;
2101 entry->commit = commit;
2102 return entry;
2105 static void
2106 pop_commit(struct commit_queue *commits)
2108 struct commit_queue_entry *entry;
2110 entry = TAILQ_FIRST(&commits->head);
2111 TAILQ_REMOVE(&commits->head, entry, entry);
2112 got_object_commit_close(entry->commit);
2113 commits->ncommits--;
2114 /* Don't free entry->id! It is owned by the commit graph. */
2115 free(entry);
2118 static void
2119 free_commits(struct commit_queue *commits)
2121 while (!TAILQ_EMPTY(&commits->head))
2122 pop_commit(commits);
2125 static const struct got_error *
2126 match_commit(int *have_match, struct got_object_id *id,
2127 struct got_commit_object *commit, regex_t *regex)
2129 const struct got_error *err = NULL;
2130 regmatch_t regmatch;
2131 char *id_str = NULL, *logmsg = NULL;
2133 *have_match = 0;
2135 err = got_object_id_str(&id_str, id);
2136 if (err)
2137 return err;
2139 err = got_object_commit_get_logmsg(&logmsg, commit);
2140 if (err)
2141 goto done;
2143 if (regexec(regex, got_object_commit_get_author(commit), 1,
2144 &regmatch, 0) == 0 ||
2145 regexec(regex, got_object_commit_get_committer(commit), 1,
2146 &regmatch, 0) == 0 ||
2147 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2148 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2149 *have_match = 1;
2150 done:
2151 free(id_str);
2152 free(logmsg);
2153 return err;
2156 static const struct got_error *
2157 queue_commits(struct tog_log_thread_args *a)
2159 const struct got_error *err = NULL;
2162 * We keep all commits open throughout the lifetime of the log
2163 * view in order to avoid having to re-fetch commits from disk
2164 * while updating the display.
2166 do {
2167 struct got_object_id *id;
2168 struct got_commit_object *commit;
2169 struct commit_queue_entry *entry;
2170 int errcode;
2172 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2173 NULL, NULL);
2174 if (err || id == NULL)
2175 break;
2177 err = got_object_open_as_commit(&commit, a->repo, id);
2178 if (err)
2179 break;
2180 entry = alloc_commit_queue_entry(commit, id);
2181 if (entry == NULL) {
2182 err = got_error_from_errno("alloc_commit_queue_entry");
2183 break;
2186 errcode = pthread_mutex_lock(&tog_mutex);
2187 if (errcode) {
2188 err = got_error_set_errno(errcode,
2189 "pthread_mutex_lock");
2190 break;
2193 entry->idx = a->commits->ncommits;
2194 TAILQ_INSERT_TAIL(&a->commits->head, entry, entry);
2195 a->commits->ncommits++;
2197 if (*a->searching == TOG_SEARCH_FORWARD &&
2198 !*a->search_next_done) {
2199 int have_match;
2200 err = match_commit(&have_match, id, commit, a->regex);
2201 if (err)
2202 break;
2203 if (have_match)
2204 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2207 errcode = pthread_mutex_unlock(&tog_mutex);
2208 if (errcode && err == NULL)
2209 err = got_error_set_errno(errcode,
2210 "pthread_mutex_unlock");
2211 if (err)
2212 break;
2213 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2215 return err;
2218 static void
2219 select_commit(struct tog_log_view_state *s)
2221 struct commit_queue_entry *entry;
2222 int ncommits = 0;
2224 entry = s->first_displayed_entry;
2225 while (entry) {
2226 if (ncommits == s->selected) {
2227 s->selected_entry = entry;
2228 break;
2230 entry = TAILQ_NEXT(entry, entry);
2231 ncommits++;
2235 static const struct got_error *
2236 draw_commits(struct tog_view *view)
2238 const struct got_error *err = NULL;
2239 struct tog_log_view_state *s = &view->state.log;
2240 struct commit_queue_entry *entry = s->selected_entry;
2241 int limit = view->nlines;
2242 int width;
2243 int ncommits, author_cols = 4;
2244 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2245 char *refs_str = NULL;
2246 wchar_t *wline;
2247 struct tog_color *tc;
2248 static const size_t date_display_cols = 12;
2250 if (view_is_hsplit_top(view))
2251 --limit; /* account for border */
2253 if (s->selected_entry &&
2254 !(view->searching && view->search_next_done == 0)) {
2255 struct got_reflist_head *refs;
2256 err = got_object_id_str(&id_str, s->selected_entry->id);
2257 if (err)
2258 return err;
2259 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2260 s->selected_entry->id);
2261 if (refs) {
2262 err = build_refs_str(&refs_str, refs,
2263 s->selected_entry->id, s->repo);
2264 if (err)
2265 goto done;
2269 if (s->thread_args.commits_needed == 0)
2270 halfdelay(10); /* disable fast refresh */
2272 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2273 if (asprintf(&ncommits_str, " [%d/%d] %s",
2274 entry ? entry->idx + 1 : 0, s->commits.ncommits,
2275 (view->searching && !view->search_next_done) ?
2276 "searching..." : "loading...") == -1) {
2277 err = got_error_from_errno("asprintf");
2278 goto done;
2280 } else {
2281 const char *search_str = NULL;
2283 if (view->searching) {
2284 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2285 search_str = "no more matches";
2286 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2287 search_str = "no matches found";
2288 else if (!view->search_next_done)
2289 search_str = "searching...";
2292 if (asprintf(&ncommits_str, " [%d/%d] %s",
2293 entry ? entry->idx + 1 : 0, s->commits.ncommits,
2294 search_str ? search_str :
2295 (refs_str ? refs_str : "")) == -1) {
2296 err = got_error_from_errno("asprintf");
2297 goto done;
2301 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2302 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2303 "........................................",
2304 s->in_repo_path, ncommits_str) == -1) {
2305 err = got_error_from_errno("asprintf");
2306 header = NULL;
2307 goto done;
2309 } else if (asprintf(&header, "commit %s%s",
2310 id_str ? id_str : "........................................",
2311 ncommits_str) == -1) {
2312 err = got_error_from_errno("asprintf");
2313 header = NULL;
2314 goto done;
2316 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2317 if (err)
2318 goto done;
2320 werase(view->window);
2322 if (view_needs_focus_indication(view))
2323 wstandout(view->window);
2324 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2325 if (tc)
2326 wattr_on(view->window,
2327 COLOR_PAIR(tc->colorpair), NULL);
2328 waddwstr(view->window, wline);
2329 if (tc)
2330 wattr_off(view->window,
2331 COLOR_PAIR(tc->colorpair), NULL);
2332 while (width < view->ncols) {
2333 waddch(view->window, ' ');
2334 width++;
2336 if (view_needs_focus_indication(view))
2337 wstandend(view->window);
2338 free(wline);
2339 if (limit <= 1)
2340 goto done;
2342 /* Grow author column size if necessary, and set view->maxx. */
2343 entry = s->first_displayed_entry;
2344 ncommits = 0;
2345 view->maxx = 0;
2346 while (entry) {
2347 struct got_commit_object *c = entry->commit;
2348 char *author, *eol, *msg, *msg0;
2349 wchar_t *wauthor, *wmsg;
2350 int width;
2351 if (ncommits >= limit - 1)
2352 break;
2353 if (s->use_committer)
2354 author = strdup(got_object_commit_get_committer(c));
2355 else
2356 author = strdup(got_object_commit_get_author(c));
2357 if (author == NULL) {
2358 err = got_error_from_errno("strdup");
2359 goto done;
2361 err = format_author(&wauthor, &width, author, COLS,
2362 date_display_cols);
2363 if (author_cols < width)
2364 author_cols = width;
2365 free(wauthor);
2366 free(author);
2367 if (err)
2368 goto done;
2369 err = got_object_commit_get_logmsg(&msg0, c);
2370 if (err)
2371 goto done;
2372 msg = msg0;
2373 while (*msg == '\n')
2374 ++msg;
2375 if ((eol = strchr(msg, '\n')))
2376 *eol = '\0';
2377 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2378 date_display_cols + author_cols, 0);
2379 if (err)
2380 goto done;
2381 view->maxx = MAX(view->maxx, width);
2382 free(msg0);
2383 free(wmsg);
2384 ncommits++;
2385 entry = TAILQ_NEXT(entry, entry);
2388 entry = s->first_displayed_entry;
2389 s->last_displayed_entry = s->first_displayed_entry;
2390 ncommits = 0;
2391 while (entry) {
2392 if (ncommits >= limit - 1)
2393 break;
2394 if (ncommits == s->selected)
2395 wstandout(view->window);
2396 err = draw_commit(view, entry->commit, entry->id,
2397 date_display_cols, author_cols);
2398 if (ncommits == s->selected)
2399 wstandend(view->window);
2400 if (err)
2401 goto done;
2402 ncommits++;
2403 s->last_displayed_entry = entry;
2404 entry = TAILQ_NEXT(entry, entry);
2407 view_border(view);
2408 done:
2409 free(id_str);
2410 free(refs_str);
2411 free(ncommits_str);
2412 free(header);
2413 return err;
2416 static void
2417 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2419 struct commit_queue_entry *entry;
2420 int nscrolled = 0;
2422 entry = TAILQ_FIRST(&s->commits.head);
2423 if (s->first_displayed_entry == entry)
2424 return;
2426 entry = s->first_displayed_entry;
2427 while (entry && nscrolled < maxscroll) {
2428 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2429 if (entry) {
2430 s->first_displayed_entry = entry;
2431 nscrolled++;
2436 static const struct got_error *
2437 trigger_log_thread(struct tog_view *view, int wait)
2439 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2440 int errcode;
2442 halfdelay(1); /* fast refresh while loading commits */
2444 while (!ta->log_complete && !tog_thread_error &&
2445 (ta->commits_needed > 0 || ta->load_all)) {
2446 /* Wake the log thread. */
2447 errcode = pthread_cond_signal(&ta->need_commits);
2448 if (errcode)
2449 return got_error_set_errno(errcode,
2450 "pthread_cond_signal");
2453 * The mutex will be released while the view loop waits
2454 * in wgetch(), at which time the log thread will run.
2456 if (!wait)
2457 break;
2459 /* Display progress update in log view. */
2460 show_log_view(view);
2461 update_panels();
2462 doupdate();
2464 /* Wait right here while next commit is being loaded. */
2465 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2466 if (errcode)
2467 return got_error_set_errno(errcode,
2468 "pthread_cond_wait");
2470 /* Display progress update in log view. */
2471 show_log_view(view);
2472 update_panels();
2473 doupdate();
2476 return NULL;
2479 static const struct got_error *
2480 request_log_commits(struct tog_view *view)
2482 struct tog_log_view_state *state = &view->state.log;
2483 const struct got_error *err = NULL;
2485 if (state->thread_args.log_complete)
2486 return NULL;
2488 state->thread_args.commits_needed += view->nscrolled;
2489 err = trigger_log_thread(view, 1);
2490 view->nscrolled = 0;
2492 return err;
2495 static const struct got_error *
2496 log_scroll_down(struct tog_view *view, int maxscroll)
2498 struct tog_log_view_state *s = &view->state.log;
2499 const struct got_error *err = NULL;
2500 struct commit_queue_entry *pentry;
2501 int nscrolled = 0, ncommits_needed;
2503 if (s->last_displayed_entry == NULL)
2504 return NULL;
2506 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2507 if (s->commits.ncommits < ncommits_needed &&
2508 !s->thread_args.log_complete) {
2510 * Ask the log thread for required amount of commits.
2512 s->thread_args.commits_needed +=
2513 ncommits_needed - s->commits.ncommits;
2514 err = trigger_log_thread(view, 1);
2515 if (err)
2516 return err;
2519 do {
2520 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2521 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2522 break;
2524 s->last_displayed_entry = pentry ?
2525 pentry : s->last_displayed_entry;;
2527 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2528 if (pentry == NULL)
2529 break;
2530 s->first_displayed_entry = pentry;
2531 } while (++nscrolled < maxscroll);
2533 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2534 view->nscrolled += nscrolled;
2535 else
2536 view->nscrolled = 0;
2538 return err;
2541 static const struct got_error *
2542 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2543 struct got_commit_object *commit, struct got_object_id *commit_id,
2544 struct tog_view *log_view, struct got_repository *repo)
2546 const struct got_error *err;
2547 struct got_object_qid *parent_id;
2548 struct tog_view *diff_view;
2550 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2551 if (diff_view == NULL)
2552 return got_error_from_errno("view_open");
2554 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2555 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2556 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2557 if (err == NULL)
2558 *new_view = diff_view;
2559 return err;
2562 static const struct got_error *
2563 tree_view_visit_subtree(struct tog_tree_view_state *s,
2564 struct got_tree_object *subtree)
2566 struct tog_parent_tree *parent;
2568 parent = calloc(1, sizeof(*parent));
2569 if (parent == NULL)
2570 return got_error_from_errno("calloc");
2572 parent->tree = s->tree;
2573 parent->first_displayed_entry = s->first_displayed_entry;
2574 parent->selected_entry = s->selected_entry;
2575 parent->selected = s->selected;
2576 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2577 s->tree = subtree;
2578 s->selected = 0;
2579 s->first_displayed_entry = NULL;
2580 return NULL;
2583 static const struct got_error *
2584 tree_view_walk_path(struct tog_tree_view_state *s,
2585 struct got_commit_object *commit, const char *path)
2587 const struct got_error *err = NULL;
2588 struct got_tree_object *tree = NULL;
2589 const char *p;
2590 char *slash, *subpath = NULL;
2592 /* Walk the path and open corresponding tree objects. */
2593 p = path;
2594 while (*p) {
2595 struct got_tree_entry *te;
2596 struct got_object_id *tree_id;
2597 char *te_name;
2599 while (p[0] == '/')
2600 p++;
2602 /* Ensure the correct subtree entry is selected. */
2603 slash = strchr(p, '/');
2604 if (slash == NULL)
2605 te_name = strdup(p);
2606 else
2607 te_name = strndup(p, slash - p);
2608 if (te_name == NULL) {
2609 err = got_error_from_errno("strndup");
2610 break;
2612 te = got_object_tree_find_entry(s->tree, te_name);
2613 if (te == NULL) {
2614 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2615 free(te_name);
2616 break;
2618 free(te_name);
2619 s->first_displayed_entry = s->selected_entry = te;
2621 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2622 break; /* jump to this file's entry */
2624 slash = strchr(p, '/');
2625 if (slash)
2626 subpath = strndup(path, slash - path);
2627 else
2628 subpath = strdup(path);
2629 if (subpath == NULL) {
2630 err = got_error_from_errno("strdup");
2631 break;
2634 err = got_object_id_by_path(&tree_id, s->repo, commit,
2635 subpath);
2636 if (err)
2637 break;
2639 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2640 free(tree_id);
2641 if (err)
2642 break;
2644 err = tree_view_visit_subtree(s, tree);
2645 if (err) {
2646 got_object_tree_close(tree);
2647 break;
2649 if (slash == NULL)
2650 break;
2651 free(subpath);
2652 subpath = NULL;
2653 p = slash;
2656 free(subpath);
2657 return err;
2660 static const struct got_error *
2661 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
2662 struct commit_queue_entry *entry, const char *path,
2663 const char *head_ref_name, struct got_repository *repo)
2665 const struct got_error *err = NULL;
2666 struct tog_tree_view_state *s;
2667 struct tog_view *tree_view;
2669 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
2670 if (tree_view == NULL)
2671 return got_error_from_errno("view_open");
2673 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2674 if (err)
2675 return err;
2676 s = &tree_view->state.tree;
2678 *new_view = tree_view;
2680 if (got_path_is_root_dir(path))
2681 return NULL;
2683 return tree_view_walk_path(s, entry->commit, path);
2686 static const struct got_error *
2687 block_signals_used_by_main_thread(void)
2689 sigset_t sigset;
2690 int errcode;
2692 if (sigemptyset(&sigset) == -1)
2693 return got_error_from_errno("sigemptyset");
2695 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2696 if (sigaddset(&sigset, SIGWINCH) == -1)
2697 return got_error_from_errno("sigaddset");
2698 if (sigaddset(&sigset, SIGCONT) == -1)
2699 return got_error_from_errno("sigaddset");
2700 if (sigaddset(&sigset, SIGINT) == -1)
2701 return got_error_from_errno("sigaddset");
2702 if (sigaddset(&sigset, SIGTERM) == -1)
2703 return got_error_from_errno("sigaddset");
2705 /* ncurses handles SIGTSTP */
2706 if (sigaddset(&sigset, SIGTSTP) == -1)
2707 return got_error_from_errno("sigaddset");
2709 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2710 if (errcode)
2711 return got_error_set_errno(errcode, "pthread_sigmask");
2713 return NULL;
2716 static void *
2717 log_thread(void *arg)
2719 const struct got_error *err = NULL;
2720 int errcode = 0;
2721 struct tog_log_thread_args *a = arg;
2722 int done = 0;
2725 * Sync startup with main thread such that we begin our
2726 * work once view_input() has released the mutex.
2728 errcode = pthread_mutex_lock(&tog_mutex);
2729 if (errcode) {
2730 err = got_error_set_errno(errcode, "pthread_mutex_lock");
2731 return (void *)err;
2734 err = block_signals_used_by_main_thread();
2735 if (err) {
2736 pthread_mutex_unlock(&tog_mutex);
2737 goto done;
2740 while (!done && !err && !tog_fatal_signal_received()) {
2741 errcode = pthread_mutex_unlock(&tog_mutex);
2742 if (errcode) {
2743 err = got_error_set_errno(errcode,
2744 "pthread_mutex_unlock");
2745 goto done;
2747 err = queue_commits(a);
2748 if (err) {
2749 if (err->code != GOT_ERR_ITER_COMPLETED)
2750 goto done;
2751 err = NULL;
2752 done = 1;
2753 } else if (a->commits_needed > 0 && !a->load_all)
2754 a->commits_needed--;
2756 errcode = pthread_mutex_lock(&tog_mutex);
2757 if (errcode) {
2758 err = got_error_set_errno(errcode,
2759 "pthread_mutex_lock");
2760 goto done;
2761 } else if (*a->quit)
2762 done = 1;
2763 else if (*a->first_displayed_entry == NULL) {
2764 *a->first_displayed_entry =
2765 TAILQ_FIRST(&a->commits->head);
2766 *a->selected_entry = *a->first_displayed_entry;
2769 errcode = pthread_cond_signal(&a->commit_loaded);
2770 if (errcode) {
2771 err = got_error_set_errno(errcode,
2772 "pthread_cond_signal");
2773 pthread_mutex_unlock(&tog_mutex);
2774 goto done;
2777 if (done)
2778 a->commits_needed = 0;
2779 else {
2780 if (a->commits_needed == 0 && !a->load_all) {
2781 errcode = pthread_cond_wait(&a->need_commits,
2782 &tog_mutex);
2783 if (errcode) {
2784 err = got_error_set_errno(errcode,
2785 "pthread_cond_wait");
2786 pthread_mutex_unlock(&tog_mutex);
2787 goto done;
2789 if (*a->quit)
2790 done = 1;
2794 a->log_complete = 1;
2795 errcode = pthread_mutex_unlock(&tog_mutex);
2796 if (errcode)
2797 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2798 done:
2799 if (err) {
2800 tog_thread_error = 1;
2801 pthread_cond_signal(&a->commit_loaded);
2803 return (void *)err;
2806 static const struct got_error *
2807 stop_log_thread(struct tog_log_view_state *s)
2809 const struct got_error *err = NULL, *thread_err = NULL;
2810 int errcode;
2812 if (s->thread) {
2813 s->quit = 1;
2814 errcode = pthread_cond_signal(&s->thread_args.need_commits);
2815 if (errcode)
2816 return got_error_set_errno(errcode,
2817 "pthread_cond_signal");
2818 errcode = pthread_mutex_unlock(&tog_mutex);
2819 if (errcode)
2820 return got_error_set_errno(errcode,
2821 "pthread_mutex_unlock");
2822 errcode = pthread_join(s->thread, (void **)&thread_err);
2823 if (errcode)
2824 return got_error_set_errno(errcode, "pthread_join");
2825 errcode = pthread_mutex_lock(&tog_mutex);
2826 if (errcode)
2827 return got_error_set_errno(errcode,
2828 "pthread_mutex_lock");
2829 s->thread = NULL;
2832 if (s->thread_args.repo) {
2833 err = got_repo_close(s->thread_args.repo);
2834 s->thread_args.repo = NULL;
2837 if (s->thread_args.pack_fds) {
2838 const struct got_error *pack_err =
2839 got_repo_pack_fds_close(s->thread_args.pack_fds);
2840 if (err == NULL)
2841 err = pack_err;
2842 s->thread_args.pack_fds = NULL;
2845 if (s->thread_args.graph) {
2846 got_commit_graph_close(s->thread_args.graph);
2847 s->thread_args.graph = NULL;
2850 return err ? err : thread_err;
2853 static const struct got_error *
2854 close_log_view(struct tog_view *view)
2856 const struct got_error *err = NULL;
2857 struct tog_log_view_state *s = &view->state.log;
2858 int errcode;
2860 err = stop_log_thread(s);
2862 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
2863 if (errcode && err == NULL)
2864 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2866 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
2867 if (errcode && err == NULL)
2868 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2870 free_commits(&s->commits);
2871 free(s->in_repo_path);
2872 s->in_repo_path = NULL;
2873 free(s->start_id);
2874 s->start_id = NULL;
2875 free(s->head_ref_name);
2876 s->head_ref_name = NULL;
2877 return err;
2880 static const struct got_error *
2881 search_start_log_view(struct tog_view *view)
2883 struct tog_log_view_state *s = &view->state.log;
2885 s->matched_entry = NULL;
2886 s->search_entry = NULL;
2887 return NULL;
2890 static const struct got_error *
2891 search_next_log_view(struct tog_view *view)
2893 const struct got_error *err = NULL;
2894 struct tog_log_view_state *s = &view->state.log;
2895 struct commit_queue_entry *entry;
2897 /* Display progress update in log view. */
2898 show_log_view(view);
2899 update_panels();
2900 doupdate();
2902 if (s->search_entry) {
2903 int errcode, ch;
2904 errcode = pthread_mutex_unlock(&tog_mutex);
2905 if (errcode)
2906 return got_error_set_errno(errcode,
2907 "pthread_mutex_unlock");
2908 ch = wgetch(view->window);
2909 errcode = pthread_mutex_lock(&tog_mutex);
2910 if (errcode)
2911 return got_error_set_errno(errcode,
2912 "pthread_mutex_lock");
2913 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
2914 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2915 return NULL;
2917 if (view->searching == TOG_SEARCH_FORWARD)
2918 entry = TAILQ_NEXT(s->search_entry, entry);
2919 else
2920 entry = TAILQ_PREV(s->search_entry,
2921 commit_queue_head, entry);
2922 } else if (s->matched_entry) {
2923 int matched_idx = s->matched_entry->idx;
2924 int selected_idx = s->selected_entry->idx;
2927 * If the user has moved the cursor after we hit a match,
2928 * the position from where we should continue searching
2929 * might have changed.
2931 if (view->searching == TOG_SEARCH_FORWARD) {
2932 if (matched_idx > selected_idx)
2933 entry = TAILQ_NEXT(s->selected_entry, entry);
2934 else
2935 entry = TAILQ_NEXT(s->matched_entry, entry);
2936 } else {
2937 if (matched_idx < selected_idx)
2938 entry = TAILQ_PREV(s->selected_entry,
2939 commit_queue_head, entry);
2940 else
2941 entry = TAILQ_PREV(s->matched_entry,
2942 commit_queue_head, entry);
2944 } else {
2945 entry = s->selected_entry;
2948 while (1) {
2949 int have_match = 0;
2951 if (entry == NULL) {
2952 if (s->thread_args.log_complete ||
2953 view->searching == TOG_SEARCH_BACKWARD) {
2954 view->search_next_done =
2955 (s->matched_entry == NULL ?
2956 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
2957 s->search_entry = NULL;
2958 return NULL;
2961 * Poke the log thread for more commits and return,
2962 * allowing the main loop to make progress. Search
2963 * will resume at s->search_entry once we come back.
2965 s->thread_args.commits_needed++;
2966 return trigger_log_thread(view, 0);
2969 err = match_commit(&have_match, entry->id, entry->commit,
2970 &view->regex);
2971 if (err)
2972 break;
2973 if (have_match) {
2974 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2975 s->matched_entry = entry;
2976 break;
2979 s->search_entry = entry;
2980 if (view->searching == TOG_SEARCH_FORWARD)
2981 entry = TAILQ_NEXT(entry, entry);
2982 else
2983 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2986 if (s->matched_entry) {
2987 int cur = s->selected_entry->idx;
2988 while (cur < s->matched_entry->idx) {
2989 err = input_log_view(NULL, view, KEY_DOWN);
2990 if (err)
2991 return err;
2992 cur++;
2994 while (cur > s->matched_entry->idx) {
2995 err = input_log_view(NULL, view, KEY_UP);
2996 if (err)
2997 return err;
2998 cur--;
3002 s->search_entry = NULL;
3004 return NULL;
3007 static const struct got_error *
3008 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3009 struct got_repository *repo, const char *head_ref_name,
3010 const char *in_repo_path, int log_branches)
3012 const struct got_error *err = NULL;
3013 struct tog_log_view_state *s = &view->state.log;
3014 struct got_repository *thread_repo = NULL;
3015 struct got_commit_graph *thread_graph = NULL;
3016 int errcode;
3018 if (in_repo_path != s->in_repo_path) {
3019 free(s->in_repo_path);
3020 s->in_repo_path = strdup(in_repo_path);
3021 if (s->in_repo_path == NULL)
3022 return got_error_from_errno("strdup");
3025 /* The commit queue only contains commits being displayed. */
3026 TAILQ_INIT(&s->commits.head);
3027 s->commits.ncommits = 0;
3029 s->repo = repo;
3030 if (head_ref_name) {
3031 s->head_ref_name = strdup(head_ref_name);
3032 if (s->head_ref_name == NULL) {
3033 err = got_error_from_errno("strdup");
3034 goto done;
3037 s->start_id = got_object_id_dup(start_id);
3038 if (s->start_id == NULL) {
3039 err = got_error_from_errno("got_object_id_dup");
3040 goto done;
3042 s->log_branches = log_branches;
3044 STAILQ_INIT(&s->colors);
3045 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3046 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3047 get_color_value("TOG_COLOR_COMMIT"));
3048 if (err)
3049 goto done;
3050 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3051 get_color_value("TOG_COLOR_AUTHOR"));
3052 if (err) {
3053 free_colors(&s->colors);
3054 goto done;
3056 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3057 get_color_value("TOG_COLOR_DATE"));
3058 if (err) {
3059 free_colors(&s->colors);
3060 goto done;
3064 view->show = show_log_view;
3065 view->input = input_log_view;
3066 view->resize = resize_log_view;
3067 view->close = close_log_view;
3068 view->search_start = search_start_log_view;
3069 view->search_next = search_next_log_view;
3071 if (s->thread_args.pack_fds == NULL) {
3072 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3073 if (err)
3074 goto done;
3076 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3077 s->thread_args.pack_fds);
3078 if (err)
3079 goto done;
3080 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3081 !s->log_branches);
3082 if (err)
3083 goto done;
3084 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3085 s->repo, NULL, NULL);
3086 if (err)
3087 goto done;
3089 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3090 if (errcode) {
3091 err = got_error_set_errno(errcode, "pthread_cond_init");
3092 goto done;
3094 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3095 if (errcode) {
3096 err = got_error_set_errno(errcode, "pthread_cond_init");
3097 goto done;
3100 s->thread_args.commits_needed = view->nlines;
3101 s->thread_args.graph = thread_graph;
3102 s->thread_args.commits = &s->commits;
3103 s->thread_args.in_repo_path = s->in_repo_path;
3104 s->thread_args.start_id = s->start_id;
3105 s->thread_args.repo = thread_repo;
3106 s->thread_args.log_complete = 0;
3107 s->thread_args.quit = &s->quit;
3108 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3109 s->thread_args.selected_entry = &s->selected_entry;
3110 s->thread_args.searching = &view->searching;
3111 s->thread_args.search_next_done = &view->search_next_done;
3112 s->thread_args.regex = &view->regex;
3113 done:
3114 if (err)
3115 close_log_view(view);
3116 return err;
3119 static const struct got_error *
3120 show_log_view(struct tog_view *view)
3122 const struct got_error *err;
3123 struct tog_log_view_state *s = &view->state.log;
3125 if (s->thread == NULL) {
3126 int errcode = pthread_create(&s->thread, NULL, log_thread,
3127 &s->thread_args);
3128 if (errcode)
3129 return got_error_set_errno(errcode, "pthread_create");
3130 if (s->thread_args.commits_needed > 0) {
3131 err = trigger_log_thread(view, 1);
3132 if (err)
3133 return err;
3137 return draw_commits(view);
3140 static void
3141 log_move_cursor_up(struct tog_view *view, int page, int home)
3143 struct tog_log_view_state *s = &view->state.log;
3145 if (s->selected_entry->idx == 0)
3146 view->count = 0;
3147 if (s->first_displayed_entry == NULL)
3148 return;
3150 if ((page && TAILQ_FIRST(&s->commits.head) == s->first_displayed_entry)
3151 || home)
3152 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3154 if (!page && !home && s->selected > 0)
3155 --s->selected;
3156 else
3157 log_scroll_up(s, home ? s->commits.ncommits : MAX(page, 1));
3159 select_commit(s);
3160 return;
3163 static const struct got_error *
3164 log_move_cursor_down(struct tog_view *view, int page)
3166 struct tog_log_view_state *s = &view->state.log;
3167 const struct got_error *err = NULL;
3168 int eos = view->nlines - 2;
3170 if (s->thread_args.log_complete &&
3171 s->selected_entry->idx >= s->commits.ncommits - 1)
3172 return NULL;
3174 if (view_is_hsplit_top(view))
3175 --eos; /* border consumes the last line */
3177 if (!page) {
3178 if (s->selected < MIN(eos, s->commits.ncommits - 1))
3179 ++s->selected;
3180 else
3181 err = log_scroll_down(view, 1);
3182 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3183 struct commit_queue_entry *entry;
3184 int n;
3186 s->selected = 0;
3187 entry = TAILQ_LAST(&s->commits.head, commit_queue_head);
3188 s->last_displayed_entry = entry;
3189 for (n = 0; n <= eos; n++) {
3190 if (entry == NULL)
3191 break;
3192 s->first_displayed_entry = entry;
3193 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3195 if (n > 0)
3196 s->selected = n - 1;
3197 } else {
3198 if (s->last_displayed_entry->idx == s->commits.ncommits - 1 &&
3199 s->thread_args.log_complete)
3200 s->selected += MIN(page,
3201 s->commits.ncommits - s->selected_entry->idx - 1);
3202 else
3203 err = log_scroll_down(view, page);
3205 if (err)
3206 return err;
3209 * We might necessarily overshoot in horizontal
3210 * splits; if so, select the last displayed commit.
3212 s->selected = MIN(s->selected,
3213 s->last_displayed_entry->idx - s->first_displayed_entry->idx);
3215 select_commit(s);
3217 if (s->thread_args.log_complete &&
3218 s->selected_entry->idx == s->commits.ncommits - 1)
3219 view->count = 0;
3221 return NULL;
3224 static void
3225 view_get_split(struct tog_view *view, int *y, int *x)
3227 *x = 0;
3228 *y = 0;
3230 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3231 if (view->child && view->child->resized_y)
3232 *y = view->child->resized_y;
3233 else if (view->resized_y)
3234 *y = view->resized_y;
3235 else
3236 *y = view_split_begin_y(view->lines);
3237 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3238 if (view->child && view->child->resized_x)
3239 *x = view->child->resized_x;
3240 else if (view->resized_x)
3241 *x = view->resized_x;
3242 else
3243 *x = view_split_begin_x(view->begin_x);
3247 /* Split view horizontally at y and offset view->state->selected line. */
3248 static const struct got_error *
3249 view_init_hsplit(struct tog_view *view, int y)
3251 const struct got_error *err = NULL;
3253 view->nlines = y;
3254 view->ncols = COLS;
3255 err = view_resize(view);
3256 if (err)
3257 return err;
3259 err = offset_selection_down(view);
3261 return err;
3264 static const struct got_error *
3265 log_goto_line(struct tog_view *view, int nlines)
3267 const struct got_error *err = NULL;
3268 struct tog_log_view_state *s = &view->state.log;
3269 int g, idx = s->selected_entry->idx;
3271 g = view->gline;
3272 view->gline = 0;
3274 if (g >= s->first_displayed_entry->idx + 1 &&
3275 g <= s->last_displayed_entry->idx + 1 &&
3276 g - s->first_displayed_entry->idx - 1 < nlines) {
3277 s->selected = g - s->first_displayed_entry->idx - 1;
3278 select_commit(s);
3279 return NULL;
3282 if (idx + 1 < g) {
3283 err = log_move_cursor_down(view, g - idx - 1);
3284 if (!err && g > s->selected_entry->idx + 1)
3285 err = log_move_cursor_down(view,
3286 g - s->first_displayed_entry->idx - 1);
3287 if (err)
3288 return err;
3289 } else if (idx + 1 > g)
3290 log_move_cursor_up(view, idx - g + 1, 0);
3292 if (g < nlines && s->first_displayed_entry->idx == 0)
3293 s->selected = g - 1;
3295 select_commit(s);
3296 return NULL;
3300 static const struct got_error *
3301 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3303 const struct got_error *err = NULL;
3304 struct tog_log_view_state *s = &view->state.log;
3305 int eos, nscroll;
3307 if (s->thread_args.load_all) {
3308 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3309 s->thread_args.load_all = 0;
3310 else if (s->thread_args.log_complete) {
3311 err = log_move_cursor_down(view, s->commits.ncommits);
3312 s->thread_args.load_all = 0;
3314 if (err)
3315 return err;
3318 eos = nscroll = view->nlines - 1;
3319 if (view_is_hsplit_top(view))
3320 --eos; /* border */
3322 if (view->gline)
3323 return log_goto_line(view, eos);
3325 switch (ch) {
3326 case 'q':
3327 s->quit = 1;
3328 break;
3329 case '0':
3330 view->x = 0;
3331 break;
3332 case '$':
3333 view->x = MAX(view->maxx - view->ncols / 2, 0);
3334 view->count = 0;
3335 break;
3336 case KEY_RIGHT:
3337 case 'l':
3338 if (view->x + view->ncols / 2 < view->maxx)
3339 view->x += 2; /* move two columns right */
3340 else
3341 view->count = 0;
3342 break;
3343 case KEY_LEFT:
3344 case 'h':
3345 view->x -= MIN(view->x, 2); /* move two columns back */
3346 if (view->x <= 0)
3347 view->count = 0;
3348 break;
3349 case 'k':
3350 case KEY_UP:
3351 case '<':
3352 case ',':
3353 case CTRL('p'):
3354 log_move_cursor_up(view, 0, 0);
3355 break;
3356 case 'g':
3357 case KEY_HOME:
3358 log_move_cursor_up(view, 0, 1);
3359 view->count = 0;
3360 break;
3361 case CTRL('u'):
3362 case 'u':
3363 nscroll /= 2;
3364 /* FALL THROUGH */
3365 case KEY_PPAGE:
3366 case CTRL('b'):
3367 case 'b':
3368 log_move_cursor_up(view, nscroll, 0);
3369 break;
3370 case 'j':
3371 case KEY_DOWN:
3372 case '>':
3373 case '.':
3374 case CTRL('n'):
3375 err = log_move_cursor_down(view, 0);
3376 break;
3377 case '@':
3378 s->use_committer = !s->use_committer;
3379 break;
3380 case 'G':
3381 case KEY_END: {
3382 /* We don't know yet how many commits, so we're forced to
3383 * traverse them all. */
3384 view->count = 0;
3385 s->thread_args.load_all = 1;
3386 if (!s->thread_args.log_complete)
3387 return trigger_log_thread(view, 0);
3388 err = log_move_cursor_down(view, s->commits.ncommits);
3389 s->thread_args.load_all = 0;
3390 break;
3392 case CTRL('d'):
3393 case 'd':
3394 nscroll /= 2;
3395 /* FALL THROUGH */
3396 case KEY_NPAGE:
3397 case CTRL('f'):
3398 case 'f':
3399 case ' ':
3400 err = log_move_cursor_down(view, nscroll);
3401 break;
3402 case KEY_RESIZE:
3403 if (s->selected > view->nlines - 2)
3404 s->selected = view->nlines - 2;
3405 if (s->selected > s->commits.ncommits - 1)
3406 s->selected = s->commits.ncommits - 1;
3407 select_commit(s);
3408 if (s->commits.ncommits < view->nlines - 1 &&
3409 !s->thread_args.log_complete) {
3410 s->thread_args.commits_needed += (view->nlines - 1) -
3411 s->commits.ncommits;
3412 err = trigger_log_thread(view, 1);
3414 break;
3415 case KEY_ENTER:
3416 case '\r':
3417 view->count = 0;
3418 if (s->selected_entry == NULL)
3419 break;
3420 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
3421 break;
3422 case 'T':
3423 view->count = 0;
3424 if (s->selected_entry == NULL)
3425 break;
3426 err = view_request_new(new_view, view, TOG_VIEW_TREE);
3427 break;
3428 case KEY_BACKSPACE:
3429 case CTRL('l'):
3430 case 'B':
3431 view->count = 0;
3432 if (ch == KEY_BACKSPACE &&
3433 got_path_is_root_dir(s->in_repo_path))
3434 break;
3435 err = stop_log_thread(s);
3436 if (err)
3437 return err;
3438 if (ch == KEY_BACKSPACE) {
3439 char *parent_path;
3440 err = got_path_dirname(&parent_path, s->in_repo_path);
3441 if (err)
3442 return err;
3443 free(s->in_repo_path);
3444 s->in_repo_path = parent_path;
3445 s->thread_args.in_repo_path = s->in_repo_path;
3446 } else if (ch == CTRL('l')) {
3447 struct got_object_id *start_id;
3448 err = got_repo_match_object_id(&start_id, NULL,
3449 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3450 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3451 if (err)
3452 return err;
3453 free(s->start_id);
3454 s->start_id = start_id;
3455 s->thread_args.start_id = s->start_id;
3456 } else /* 'B' */
3457 s->log_branches = !s->log_branches;
3459 if (s->thread_args.pack_fds == NULL) {
3460 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3461 if (err)
3462 return err;
3464 err = got_repo_open(&s->thread_args.repo,
3465 got_repo_get_path(s->repo), NULL,
3466 s->thread_args.pack_fds);
3467 if (err)
3468 return err;
3469 tog_free_refs();
3470 err = tog_load_refs(s->repo, 0);
3471 if (err)
3472 return err;
3473 err = got_commit_graph_open(&s->thread_args.graph,
3474 s->in_repo_path, !s->log_branches);
3475 if (err)
3476 return err;
3477 err = got_commit_graph_iter_start(s->thread_args.graph,
3478 s->start_id, s->repo, NULL, NULL);
3479 if (err)
3480 return err;
3481 free_commits(&s->commits);
3482 s->first_displayed_entry = NULL;
3483 s->last_displayed_entry = NULL;
3484 s->selected_entry = NULL;
3485 s->selected = 0;
3486 s->thread_args.log_complete = 0;
3487 s->quit = 0;
3488 s->thread_args.commits_needed = view->lines;
3489 s->matched_entry = NULL;
3490 s->search_entry = NULL;
3491 view->offset = 0;
3492 break;
3493 case 'R':
3494 view->count = 0;
3495 err = view_request_new(new_view, view, TOG_VIEW_REF);
3496 break;
3497 default:
3498 view->count = 0;
3499 break;
3502 return err;
3505 static const struct got_error *
3506 apply_unveil(const char *repo_path, const char *worktree_path)
3508 const struct got_error *error;
3510 #ifdef PROFILE
3511 if (unveil("gmon.out", "rwc") != 0)
3512 return got_error_from_errno2("unveil", "gmon.out");
3513 #endif
3514 if (repo_path && unveil(repo_path, "r") != 0)
3515 return got_error_from_errno2("unveil", repo_path);
3517 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3518 return got_error_from_errno2("unveil", worktree_path);
3520 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3521 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3523 error = got_privsep_unveil_exec_helpers();
3524 if (error != NULL)
3525 return error;
3527 if (unveil(NULL, NULL) != 0)
3528 return got_error_from_errno("unveil");
3530 return NULL;
3533 static void
3534 init_curses(void)
3537 * Override default signal handlers before starting ncurses.
3538 * This should prevent ncurses from installing its own
3539 * broken cleanup() signal handler.
3541 signal(SIGWINCH, tog_sigwinch);
3542 signal(SIGPIPE, tog_sigpipe);
3543 signal(SIGCONT, tog_sigcont);
3544 signal(SIGINT, tog_sigint);
3545 signal(SIGTERM, tog_sigterm);
3547 initscr();
3548 cbreak();
3549 halfdelay(1); /* Do fast refresh while initial view is loading. */
3550 noecho();
3551 nonl();
3552 intrflush(stdscr, FALSE);
3553 keypad(stdscr, TRUE);
3554 curs_set(0);
3555 if (getenv("TOG_COLORS") != NULL) {
3556 start_color();
3557 use_default_colors();
3561 static const struct got_error *
3562 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
3563 struct got_repository *repo, struct got_worktree *worktree)
3565 const struct got_error *err = NULL;
3567 if (argc == 0) {
3568 *in_repo_path = strdup("/");
3569 if (*in_repo_path == NULL)
3570 return got_error_from_errno("strdup");
3571 return NULL;
3574 if (worktree) {
3575 const char *prefix = got_worktree_get_path_prefix(worktree);
3576 char *p;
3578 err = got_worktree_resolve_path(&p, worktree, argv[0]);
3579 if (err)
3580 return err;
3581 if (asprintf(in_repo_path, "%s%s%s", prefix,
3582 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
3583 p) == -1) {
3584 err = got_error_from_errno("asprintf");
3585 *in_repo_path = NULL;
3587 free(p);
3588 } else
3589 err = got_repo_map_path(in_repo_path, repo, argv[0]);
3591 return err;
3594 static const struct got_error *
3595 cmd_log(int argc, char *argv[])
3597 const struct got_error *error;
3598 struct got_repository *repo = NULL;
3599 struct got_worktree *worktree = NULL;
3600 struct got_object_id *start_id = NULL;
3601 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
3602 char *start_commit = NULL, *label = NULL;
3603 struct got_reference *ref = NULL;
3604 const char *head_ref_name = NULL;
3605 int ch, log_branches = 0;
3606 struct tog_view *view;
3607 int *pack_fds = NULL;
3609 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
3610 switch (ch) {
3611 case 'b':
3612 log_branches = 1;
3613 break;
3614 case 'c':
3615 start_commit = optarg;
3616 break;
3617 case 'r':
3618 repo_path = realpath(optarg, NULL);
3619 if (repo_path == NULL)
3620 return got_error_from_errno2("realpath",
3621 optarg);
3622 break;
3623 default:
3624 usage_log();
3625 /* NOTREACHED */
3629 argc -= optind;
3630 argv += optind;
3632 if (argc > 1)
3633 usage_log();
3635 error = got_repo_pack_fds_open(&pack_fds);
3636 if (error != NULL)
3637 goto done;
3639 if (repo_path == NULL) {
3640 cwd = getcwd(NULL, 0);
3641 if (cwd == NULL)
3642 return got_error_from_errno("getcwd");
3643 error = got_worktree_open(&worktree, cwd);
3644 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3645 goto done;
3646 if (worktree)
3647 repo_path =
3648 strdup(got_worktree_get_repo_path(worktree));
3649 else
3650 repo_path = strdup(cwd);
3651 if (repo_path == NULL) {
3652 error = got_error_from_errno("strdup");
3653 goto done;
3657 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3658 if (error != NULL)
3659 goto done;
3661 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
3662 repo, worktree);
3663 if (error)
3664 goto done;
3666 init_curses();
3668 error = apply_unveil(got_repo_get_path(repo),
3669 worktree ? got_worktree_get_root_path(worktree) : NULL);
3670 if (error)
3671 goto done;
3673 /* already loaded by tog_log_with_path()? */
3674 if (TAILQ_EMPTY(&tog_refs)) {
3675 error = tog_load_refs(repo, 0);
3676 if (error)
3677 goto done;
3680 if (start_commit == NULL) {
3681 error = got_repo_match_object_id(&start_id, &label,
3682 worktree ? got_worktree_get_head_ref_name(worktree) :
3683 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3684 if (error)
3685 goto done;
3686 head_ref_name = label;
3687 } else {
3688 error = got_ref_open(&ref, repo, start_commit, 0);
3689 if (error == NULL)
3690 head_ref_name = got_ref_get_name(ref);
3691 else if (error->code != GOT_ERR_NOT_REF)
3692 goto done;
3693 error = got_repo_match_object_id(&start_id, NULL,
3694 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3695 if (error)
3696 goto done;
3699 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
3700 if (view == NULL) {
3701 error = got_error_from_errno("view_open");
3702 goto done;
3704 error = open_log_view(view, start_id, repo, head_ref_name,
3705 in_repo_path, log_branches);
3706 if (error)
3707 goto done;
3708 if (worktree) {
3709 /* Release work tree lock. */
3710 got_worktree_close(worktree);
3711 worktree = NULL;
3713 error = view_loop(view);
3714 done:
3715 free(in_repo_path);
3716 free(repo_path);
3717 free(cwd);
3718 free(start_id);
3719 free(label);
3720 if (ref)
3721 got_ref_close(ref);
3722 if (repo) {
3723 const struct got_error *close_err = got_repo_close(repo);
3724 if (error == NULL)
3725 error = close_err;
3727 if (worktree)
3728 got_worktree_close(worktree);
3729 if (pack_fds) {
3730 const struct got_error *pack_err =
3731 got_repo_pack_fds_close(pack_fds);
3732 if (error == NULL)
3733 error = pack_err;
3735 tog_free_refs();
3736 return error;
3739 __dead static void
3740 usage_diff(void)
3742 endwin();
3743 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
3744 "[-w] object1 object2\n", getprogname());
3745 exit(1);
3748 static int
3749 match_line(const char *line, regex_t *regex, size_t nmatch,
3750 regmatch_t *regmatch)
3752 return regexec(regex, line, nmatch, regmatch, 0) == 0;
3755 static struct tog_color *
3756 match_color(struct tog_colors *colors, const char *line)
3758 struct tog_color *tc = NULL;
3760 STAILQ_FOREACH(tc, colors, entry) {
3761 if (match_line(line, &tc->regex, 0, NULL))
3762 return tc;
3765 return NULL;
3768 static const struct got_error *
3769 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
3770 WINDOW *window, int skipcol, regmatch_t *regmatch)
3772 const struct got_error *err = NULL;
3773 char *exstr = NULL;
3774 wchar_t *wline = NULL;
3775 int rme, rms, n, width, scrollx;
3776 int width0 = 0, width1 = 0, width2 = 0;
3777 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
3779 *wtotal = 0;
3781 rms = regmatch->rm_so;
3782 rme = regmatch->rm_eo;
3784 err = expand_tab(&exstr, line);
3785 if (err)
3786 return err;
3788 /* Split the line into 3 segments, according to match offsets. */
3789 seg0 = strndup(exstr, rms);
3790 if (seg0 == NULL) {
3791 err = got_error_from_errno("strndup");
3792 goto done;
3794 seg1 = strndup(exstr + rms, rme - rms);
3795 if (seg1 == NULL) {
3796 err = got_error_from_errno("strndup");
3797 goto done;
3799 seg2 = strdup(exstr + rme);
3800 if (seg2 == NULL) {
3801 err = got_error_from_errno("strndup");
3802 goto done;
3805 /* draw up to matched token if we haven't scrolled past it */
3806 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
3807 col_tab_align, 1);
3808 if (err)
3809 goto done;
3810 n = MAX(width0 - skipcol, 0);
3811 if (n) {
3812 free(wline);
3813 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
3814 wlimit, col_tab_align, 1);
3815 if (err)
3816 goto done;
3817 waddwstr(window, &wline[scrollx]);
3818 wlimit -= width;
3819 *wtotal += width;
3822 if (wlimit > 0) {
3823 int i = 0, w = 0;
3824 size_t wlen;
3826 free(wline);
3827 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
3828 col_tab_align, 1);
3829 if (err)
3830 goto done;
3831 wlen = wcslen(wline);
3832 while (i < wlen) {
3833 width = wcwidth(wline[i]);
3834 if (width == -1) {
3835 /* should not happen, tabs are expanded */
3836 err = got_error(GOT_ERR_RANGE);
3837 goto done;
3839 if (width0 + w + width > skipcol)
3840 break;
3841 w += width;
3842 i++;
3844 /* draw (visible part of) matched token (if scrolled into it) */
3845 if (width1 - w > 0) {
3846 wattron(window, A_STANDOUT);
3847 waddwstr(window, &wline[i]);
3848 wattroff(window, A_STANDOUT);
3849 wlimit -= (width1 - w);
3850 *wtotal += (width1 - w);
3854 if (wlimit > 0) { /* draw rest of line */
3855 free(wline);
3856 if (skipcol > width0 + width1) {
3857 err = format_line(&wline, &width2, &scrollx, seg2,
3858 skipcol - (width0 + width1), wlimit,
3859 col_tab_align, 1);
3860 if (err)
3861 goto done;
3862 waddwstr(window, &wline[scrollx]);
3863 } else {
3864 err = format_line(&wline, &width2, NULL, seg2, 0,
3865 wlimit, col_tab_align, 1);
3866 if (err)
3867 goto done;
3868 waddwstr(window, wline);
3870 *wtotal += width2;
3872 done:
3873 free(wline);
3874 free(exstr);
3875 free(seg0);
3876 free(seg1);
3877 free(seg2);
3878 return err;
3881 static int
3882 gotoline(struct tog_view *view, int *lineno, int *nprinted)
3884 FILE *f = NULL;
3885 int *eof, *first, *selected;
3887 if (view->type == TOG_VIEW_DIFF) {
3888 struct tog_diff_view_state *s = &view->state.diff;
3890 first = &s->first_displayed_line;
3891 selected = first;
3892 eof = &s->eof;
3893 f = s->f;
3894 } else if (view->type == TOG_VIEW_BLAME) {
3895 struct tog_blame_view_state *s = &view->state.blame;
3897 first = &s->first_displayed_line;
3898 selected = &s->selected_line;
3899 eof = &s->eof;
3900 f = s->blame.f;
3901 } else
3902 return 0;
3904 /* Center gline in the middle of the page like vi(1). */
3905 if (*lineno < view->gline - (view->nlines - 3) / 2)
3906 return 0;
3907 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
3908 rewind(f);
3909 *eof = 0;
3910 *first = 1;
3911 *lineno = 0;
3912 *nprinted = 0;
3913 return 0;
3916 *selected = view->gline <= (view->nlines - 3) / 2 ?
3917 view->gline : (view->nlines - 3) / 2 + 1;
3918 view->gline = 0;
3920 return 1;
3923 static const struct got_error *
3924 draw_file(struct tog_view *view, const char *header)
3926 struct tog_diff_view_state *s = &view->state.diff;
3927 regmatch_t *regmatch = &view->regmatch;
3928 const struct got_error *err;
3929 int nprinted = 0;
3930 char *line;
3931 size_t linesize = 0;
3932 ssize_t linelen;
3933 wchar_t *wline;
3934 int width;
3935 int max_lines = view->nlines;
3936 int nlines = s->nlines;
3937 off_t line_offset;
3939 s->lineno = s->first_displayed_line - 1;
3940 line_offset = s->lines[s->first_displayed_line - 1].offset;
3941 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
3942 return got_error_from_errno("fseek");
3944 werase(view->window);
3946 if (view->gline > s->nlines - 1)
3947 view->gline = s->nlines - 1;
3949 if (header) {
3950 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
3951 1 : view->gline - (view->nlines - 3) / 2 :
3952 s->lineno + s->selected_line;
3954 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
3955 return got_error_from_errno("asprintf");
3956 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
3957 0, 0);
3958 free(line);
3959 if (err)
3960 return err;
3962 if (view_needs_focus_indication(view))
3963 wstandout(view->window);
3964 waddwstr(view->window, wline);
3965 free(wline);
3966 wline = NULL;
3967 if (view_needs_focus_indication(view))
3968 wstandend(view->window);
3969 if (width <= view->ncols - 1)
3970 waddch(view->window, '\n');
3972 if (max_lines <= 1)
3973 return NULL;
3974 max_lines--;
3977 s->eof = 0;
3978 view->maxx = 0;
3979 line = NULL;
3980 while (max_lines > 0 && nprinted < max_lines) {
3981 enum got_diff_line_type linetype;
3982 attr_t attr = 0;
3984 linelen = getline(&line, &linesize, s->f);
3985 if (linelen == -1) {
3986 if (feof(s->f)) {
3987 s->eof = 1;
3988 break;
3990 free(line);
3991 return got_ferror(s->f, GOT_ERR_IO);
3994 if (++s->lineno < s->first_displayed_line)
3995 continue;
3996 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
3997 continue;
3998 if (s->lineno == view->hiline)
3999 attr = A_STANDOUT;
4001 /* Set view->maxx based on full line length. */
4002 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4003 view->x ? 1 : 0);
4004 if (err) {
4005 free(line);
4006 return err;
4008 view->maxx = MAX(view->maxx, width);
4009 free(wline);
4010 wline = NULL;
4012 linetype = s->lines[s->lineno].type;
4013 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4014 linetype < GOT_DIFF_LINE_CONTEXT)
4015 attr |= COLOR_PAIR(linetype);
4016 if (attr)
4017 wattron(view->window, attr);
4018 if (s->first_displayed_line + nprinted == s->matched_line &&
4019 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4020 err = add_matched_line(&width, line, view->ncols, 0,
4021 view->window, view->x, regmatch);
4022 if (err) {
4023 free(line);
4024 return err;
4026 } else {
4027 int skip;
4028 err = format_line(&wline, &width, &skip, line,
4029 view->x, view->ncols, 0, view->x ? 1 : 0);
4030 if (err) {
4031 free(line);
4032 return err;
4034 waddwstr(view->window, &wline[skip]);
4035 free(wline);
4036 wline = NULL;
4038 if (s->lineno == view->hiline) {
4039 /* highlight full gline length */
4040 while (width++ < view->ncols)
4041 waddch(view->window, ' ');
4042 } else {
4043 if (width <= view->ncols - 1)
4044 waddch(view->window, '\n');
4046 if (attr)
4047 wattroff(view->window, attr);
4048 if (++nprinted == 1)
4049 s->first_displayed_line = s->lineno;
4051 free(line);
4052 if (nprinted >= 1)
4053 s->last_displayed_line = s->first_displayed_line +
4054 (nprinted - 1);
4055 else
4056 s->last_displayed_line = s->first_displayed_line;
4058 view_border(view);
4060 if (s->eof) {
4061 while (nprinted < view->nlines) {
4062 waddch(view->window, '\n');
4063 nprinted++;
4066 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4067 view->ncols, 0, 0);
4068 if (err) {
4069 return err;
4072 wstandout(view->window);
4073 waddwstr(view->window, wline);
4074 free(wline);
4075 wline = NULL;
4076 wstandend(view->window);
4079 return NULL;
4082 static char *
4083 get_datestr(time_t *time, char *datebuf)
4085 struct tm mytm, *tm;
4086 char *p, *s;
4088 tm = gmtime_r(time, &mytm);
4089 if (tm == NULL)
4090 return NULL;
4091 s = asctime_r(tm, datebuf);
4092 if (s == NULL)
4093 return NULL;
4094 p = strchr(s, '\n');
4095 if (p)
4096 *p = '\0';
4097 return s;
4100 static const struct got_error *
4101 get_changed_paths(struct got_pathlist_head *paths,
4102 struct got_commit_object *commit, struct got_repository *repo)
4104 const struct got_error *err = NULL;
4105 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
4106 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
4107 struct got_object_qid *qid;
4109 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
4110 if (qid != NULL) {
4111 struct got_commit_object *pcommit;
4112 err = got_object_open_as_commit(&pcommit, repo,
4113 &qid->id);
4114 if (err)
4115 return err;
4117 tree_id1 = got_object_id_dup(
4118 got_object_commit_get_tree_id(pcommit));
4119 if (tree_id1 == NULL) {
4120 got_object_commit_close(pcommit);
4121 return got_error_from_errno("got_object_id_dup");
4123 got_object_commit_close(pcommit);
4127 if (tree_id1) {
4128 err = got_object_open_as_tree(&tree1, repo, tree_id1);
4129 if (err)
4130 goto done;
4133 tree_id2 = got_object_commit_get_tree_id(commit);
4134 err = got_object_open_as_tree(&tree2, repo, tree_id2);
4135 if (err)
4136 goto done;
4138 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
4139 got_diff_tree_collect_changed_paths, paths, 0);
4140 done:
4141 if (tree1)
4142 got_object_tree_close(tree1);
4143 if (tree2)
4144 got_object_tree_close(tree2);
4145 free(tree_id1);
4146 return err;
4149 static const struct got_error *
4150 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4151 off_t off, uint8_t type)
4153 struct got_diff_line *p;
4155 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4156 if (p == NULL)
4157 return got_error_from_errno("reallocarray");
4158 *lines = p;
4159 (*lines)[*nlines].offset = off;
4160 (*lines)[*nlines].type = type;
4161 (*nlines)++;
4163 return NULL;
4166 static const struct got_error *
4167 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4168 struct got_object_id *commit_id, struct got_reflist_head *refs,
4169 struct got_repository *repo, FILE *outfile)
4171 const struct got_error *err = NULL;
4172 char datebuf[26], *datestr;
4173 struct got_commit_object *commit;
4174 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4175 time_t committer_time;
4176 const char *author, *committer;
4177 char *refs_str = NULL;
4178 struct got_pathlist_head changed_paths;
4179 struct got_pathlist_entry *pe;
4180 off_t outoff = 0;
4181 int n;
4183 TAILQ_INIT(&changed_paths);
4185 if (refs) {
4186 err = build_refs_str(&refs_str, refs, commit_id, repo);
4187 if (err)
4188 return err;
4191 err = got_object_open_as_commit(&commit, repo, commit_id);
4192 if (err)
4193 return err;
4195 err = got_object_id_str(&id_str, commit_id);
4196 if (err) {
4197 err = got_error_from_errno("got_object_id_str");
4198 goto done;
4201 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4202 if (err)
4203 goto done;
4205 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4206 refs_str ? refs_str : "", refs_str ? ")" : "");
4207 if (n < 0) {
4208 err = got_error_from_errno("fprintf");
4209 goto done;
4211 outoff += n;
4212 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4213 if (err)
4214 goto done;
4216 n = fprintf(outfile, "from: %s\n",
4217 got_object_commit_get_author(commit));
4218 if (n < 0) {
4219 err = got_error_from_errno("fprintf");
4220 goto done;
4222 outoff += n;
4223 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4224 if (err)
4225 goto done;
4227 committer_time = got_object_commit_get_committer_time(commit);
4228 datestr = get_datestr(&committer_time, datebuf);
4229 if (datestr) {
4230 n = fprintf(outfile, "date: %s UTC\n", datestr);
4231 if (n < 0) {
4232 err = got_error_from_errno("fprintf");
4233 goto done;
4235 outoff += n;
4236 err = add_line_metadata(lines, nlines, outoff,
4237 GOT_DIFF_LINE_DATE);
4238 if (err)
4239 goto done;
4241 author = got_object_commit_get_author(commit);
4242 committer = got_object_commit_get_committer(commit);
4243 if (strcmp(author, committer) != 0) {
4244 n = fprintf(outfile, "via: %s\n", committer);
4245 if (n < 0) {
4246 err = got_error_from_errno("fprintf");
4247 goto done;
4249 outoff += n;
4250 err = add_line_metadata(lines, nlines, outoff,
4251 GOT_DIFF_LINE_AUTHOR);
4252 if (err)
4253 goto done;
4255 if (got_object_commit_get_nparents(commit) > 1) {
4256 const struct got_object_id_queue *parent_ids;
4257 struct got_object_qid *qid;
4258 int pn = 1;
4259 parent_ids = got_object_commit_get_parent_ids(commit);
4260 STAILQ_FOREACH(qid, parent_ids, entry) {
4261 err = got_object_id_str(&id_str, &qid->id);
4262 if (err)
4263 goto done;
4264 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4265 if (n < 0) {
4266 err = got_error_from_errno("fprintf");
4267 goto done;
4269 outoff += n;
4270 err = add_line_metadata(lines, nlines, outoff,
4271 GOT_DIFF_LINE_META);
4272 if (err)
4273 goto done;
4274 free(id_str);
4275 id_str = NULL;
4279 err = got_object_commit_get_logmsg(&logmsg, commit);
4280 if (err)
4281 goto done;
4282 s = logmsg;
4283 while ((line = strsep(&s, "\n")) != NULL) {
4284 n = fprintf(outfile, "%s\n", line);
4285 if (n < 0) {
4286 err = got_error_from_errno("fprintf");
4287 goto done;
4289 outoff += n;
4290 err = add_line_metadata(lines, nlines, outoff,
4291 GOT_DIFF_LINE_LOGMSG);
4292 if (err)
4293 goto done;
4296 err = get_changed_paths(&changed_paths, commit, repo);
4297 if (err)
4298 goto done;
4299 TAILQ_FOREACH(pe, &changed_paths, entry) {
4300 struct got_diff_changed_path *cp = pe->data;
4301 n = fprintf(outfile, "%c %s\n", cp->status, pe->path);
4302 if (n < 0) {
4303 err = got_error_from_errno("fprintf");
4304 goto done;
4306 outoff += n;
4307 err = add_line_metadata(lines, nlines, outoff,
4308 GOT_DIFF_LINE_CHANGES);
4309 if (err)
4310 goto done;
4311 free((char *)pe->path);
4312 free(pe->data);
4315 fputc('\n', outfile);
4316 outoff++;
4317 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4318 done:
4319 got_pathlist_free(&changed_paths);
4320 free(id_str);
4321 free(logmsg);
4322 free(refs_str);
4323 got_object_commit_close(commit);
4324 if (err) {
4325 free(*lines);
4326 *lines = NULL;
4327 *nlines = 0;
4329 return err;
4332 static const struct got_error *
4333 create_diff(struct tog_diff_view_state *s)
4335 const struct got_error *err = NULL;
4336 FILE *f = NULL;
4337 int obj_type;
4339 free(s->lines);
4340 s->lines = malloc(sizeof(*s->lines));
4341 if (s->lines == NULL)
4342 return got_error_from_errno("malloc");
4343 s->nlines = 0;
4345 f = got_opentemp();
4346 if (f == NULL) {
4347 err = got_error_from_errno("got_opentemp");
4348 goto done;
4350 if (s->f && fclose(s->f) == EOF) {
4351 err = got_error_from_errno("fclose");
4352 goto done;
4354 s->f = f;
4356 if (s->id1)
4357 err = got_object_get_type(&obj_type, s->repo, s->id1);
4358 else
4359 err = got_object_get_type(&obj_type, s->repo, s->id2);
4360 if (err)
4361 goto done;
4363 switch (obj_type) {
4364 case GOT_OBJ_TYPE_BLOB:
4365 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
4366 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4367 s->label1, s->label2, tog_diff_algo, s->diff_context,
4368 s->ignore_whitespace, s->force_text_diff, s->repo, s->f);
4369 break;
4370 case GOT_OBJ_TYPE_TREE:
4371 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
4372 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4373 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4374 s->force_text_diff, s->repo, s->f);
4375 break;
4376 case GOT_OBJ_TYPE_COMMIT: {
4377 const struct got_object_id_queue *parent_ids;
4378 struct got_object_qid *pid;
4379 struct got_commit_object *commit2;
4380 struct got_reflist_head *refs;
4382 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4383 if (err)
4384 goto done;
4385 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4386 /* Show commit info if we're diffing to a parent/root commit. */
4387 if (s->id1 == NULL) {
4388 err = write_commit_info(&s->lines, &s->nlines, s->id2,
4389 refs, s->repo, s->f);
4390 if (err)
4391 goto done;
4392 } else {
4393 parent_ids = got_object_commit_get_parent_ids(commit2);
4394 STAILQ_FOREACH(pid, parent_ids, entry) {
4395 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4396 err = write_commit_info(&s->lines,
4397 &s->nlines, s->id2, refs, s->repo,
4398 s->f);
4399 if (err)
4400 goto done;
4401 break;
4405 got_object_commit_close(commit2);
4407 err = got_diff_objects_as_commits(&s->lines, &s->nlines,
4408 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4409 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4410 s->force_text_diff, s->repo, s->f);
4411 break;
4413 default:
4414 err = got_error(GOT_ERR_OBJ_TYPE);
4415 break;
4417 done:
4418 if (s->f && fflush(s->f) != 0 && err == NULL)
4419 err = got_error_from_errno("fflush");
4420 return err;
4423 static void
4424 diff_view_indicate_progress(struct tog_view *view)
4426 mvwaddstr(view->window, 0, 0, "diffing...");
4427 update_panels();
4428 doupdate();
4431 static const struct got_error *
4432 search_start_diff_view(struct tog_view *view)
4434 struct tog_diff_view_state *s = &view->state.diff;
4436 s->matched_line = 0;
4437 return NULL;
4440 static const struct got_error *
4441 search_next_diff_view(struct tog_view *view)
4443 struct tog_diff_view_state *s = &view->state.diff;
4444 const struct got_error *err = NULL;
4445 int lineno;
4446 char *line = NULL;
4447 size_t linesize = 0;
4448 ssize_t linelen;
4450 if (!view->searching) {
4451 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4452 return NULL;
4455 if (s->matched_line) {
4456 if (view->searching == TOG_SEARCH_FORWARD)
4457 lineno = s->matched_line + 1;
4458 else
4459 lineno = s->matched_line - 1;
4460 } else
4461 lineno = s->first_displayed_line;
4463 while (1) {
4464 off_t offset;
4466 if (lineno <= 0 || lineno > s->nlines) {
4467 if (s->matched_line == 0) {
4468 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4469 break;
4472 if (view->searching == TOG_SEARCH_FORWARD)
4473 lineno = 1;
4474 else
4475 lineno = s->nlines;
4478 offset = s->lines[lineno - 1].offset;
4479 if (fseeko(s->f, offset, SEEK_SET) != 0) {
4480 free(line);
4481 return got_error_from_errno("fseeko");
4483 linelen = getline(&line, &linesize, s->f);
4484 if (linelen != -1) {
4485 char *exstr;
4486 err = expand_tab(&exstr, line);
4487 if (err)
4488 break;
4489 if (match_line(exstr, &view->regex, 1,
4490 &view->regmatch)) {
4491 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4492 s->matched_line = lineno;
4493 free(exstr);
4494 break;
4496 free(exstr);
4498 if (view->searching == TOG_SEARCH_FORWARD)
4499 lineno++;
4500 else
4501 lineno--;
4503 free(line);
4505 if (s->matched_line) {
4506 s->first_displayed_line = s->matched_line;
4507 s->selected_line = 1;
4510 return err;
4513 static const struct got_error *
4514 close_diff_view(struct tog_view *view)
4516 const struct got_error *err = NULL;
4517 struct tog_diff_view_state *s = &view->state.diff;
4519 free(s->id1);
4520 s->id1 = NULL;
4521 free(s->id2);
4522 s->id2 = NULL;
4523 if (s->f && fclose(s->f) == EOF)
4524 err = got_error_from_errno("fclose");
4525 s->f = NULL;
4526 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
4527 err = got_error_from_errno("fclose");
4528 s->f1 = NULL;
4529 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
4530 err = got_error_from_errno("fclose");
4531 s->f2 = NULL;
4532 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
4533 err = got_error_from_errno("close");
4534 s->fd1 = -1;
4535 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
4536 err = got_error_from_errno("close");
4537 s->fd2 = -1;
4538 free(s->lines);
4539 s->lines = NULL;
4540 s->nlines = 0;
4541 return err;
4544 static const struct got_error *
4545 open_diff_view(struct tog_view *view, struct got_object_id *id1,
4546 struct got_object_id *id2, const char *label1, const char *label2,
4547 int diff_context, int ignore_whitespace, int force_text_diff,
4548 struct tog_view *parent_view, struct got_repository *repo)
4550 const struct got_error *err;
4551 struct tog_diff_view_state *s = &view->state.diff;
4553 memset(s, 0, sizeof(*s));
4554 s->fd1 = -1;
4555 s->fd2 = -1;
4557 if (id1 != NULL && id2 != NULL) {
4558 int type1, type2;
4559 err = got_object_get_type(&type1, repo, id1);
4560 if (err)
4561 return err;
4562 err = got_object_get_type(&type2, repo, id2);
4563 if (err)
4564 return err;
4566 if (type1 != type2)
4567 return got_error(GOT_ERR_OBJ_TYPE);
4569 s->first_displayed_line = 1;
4570 s->last_displayed_line = view->nlines;
4571 s->selected_line = 1;
4572 s->repo = repo;
4573 s->id1 = id1;
4574 s->id2 = id2;
4575 s->label1 = label1;
4576 s->label2 = label2;
4578 if (id1) {
4579 s->id1 = got_object_id_dup(id1);
4580 if (s->id1 == NULL)
4581 return got_error_from_errno("got_object_id_dup");
4582 } else
4583 s->id1 = NULL;
4585 s->id2 = got_object_id_dup(id2);
4586 if (s->id2 == NULL) {
4587 err = got_error_from_errno("got_object_id_dup");
4588 goto done;
4591 s->f1 = got_opentemp();
4592 if (s->f1 == NULL) {
4593 err = got_error_from_errno("got_opentemp");
4594 goto done;
4597 s->f2 = got_opentemp();
4598 if (s->f2 == NULL) {
4599 err = got_error_from_errno("got_opentemp");
4600 goto done;
4603 s->fd1 = got_opentempfd();
4604 if (s->fd1 == -1) {
4605 err = got_error_from_errno("got_opentempfd");
4606 goto done;
4609 s->fd2 = got_opentempfd();
4610 if (s->fd2 == -1) {
4611 err = got_error_from_errno("got_opentempfd");
4612 goto done;
4615 s->first_displayed_line = 1;
4616 s->last_displayed_line = view->nlines;
4617 s->diff_context = diff_context;
4618 s->ignore_whitespace = ignore_whitespace;
4619 s->force_text_diff = force_text_diff;
4620 s->parent_view = parent_view;
4621 s->repo = repo;
4623 if (has_colors() && getenv("TOG_COLORS") != NULL) {
4624 int rc;
4626 rc = init_pair(GOT_DIFF_LINE_MINUS,
4627 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
4628 if (rc != ERR)
4629 rc = init_pair(GOT_DIFF_LINE_PLUS,
4630 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
4631 if (rc != ERR)
4632 rc = init_pair(GOT_DIFF_LINE_HUNK,
4633 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
4634 if (rc != ERR)
4635 rc = init_pair(GOT_DIFF_LINE_META,
4636 get_color_value("TOG_COLOR_DIFF_META"), -1);
4637 if (rc != ERR)
4638 rc = init_pair(GOT_DIFF_LINE_CHANGES,
4639 get_color_value("TOG_COLOR_DIFF_META"), -1);
4640 if (rc != ERR)
4641 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
4642 get_color_value("TOG_COLOR_DIFF_META"), -1);
4643 if (rc != ERR)
4644 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
4645 get_color_value("TOG_COLOR_DIFF_META"), -1);
4646 if (rc != ERR)
4647 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
4648 get_color_value("TOG_COLOR_AUTHOR"), -1);
4649 if (rc != ERR)
4650 rc = init_pair(GOT_DIFF_LINE_DATE,
4651 get_color_value("TOG_COLOR_DATE"), -1);
4652 if (rc == ERR) {
4653 err = got_error(GOT_ERR_RANGE);
4654 goto done;
4658 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
4659 view_is_splitscreen(view))
4660 show_log_view(parent_view); /* draw border */
4661 diff_view_indicate_progress(view);
4663 err = create_diff(s);
4665 view->show = show_diff_view;
4666 view->input = input_diff_view;
4667 view->reset = reset_diff_view;
4668 view->close = close_diff_view;
4669 view->search_start = search_start_diff_view;
4670 view->search_next = search_next_diff_view;
4671 done:
4672 if (err)
4673 close_diff_view(view);
4674 return err;
4677 static const struct got_error *
4678 show_diff_view(struct tog_view *view)
4680 const struct got_error *err;
4681 struct tog_diff_view_state *s = &view->state.diff;
4682 char *id_str1 = NULL, *id_str2, *header;
4683 const char *label1, *label2;
4685 if (s->id1) {
4686 err = got_object_id_str(&id_str1, s->id1);
4687 if (err)
4688 return err;
4689 label1 = s->label1 ? : id_str1;
4690 } else
4691 label1 = "/dev/null";
4693 err = got_object_id_str(&id_str2, s->id2);
4694 if (err)
4695 return err;
4696 label2 = s->label2 ? : id_str2;
4698 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
4699 err = got_error_from_errno("asprintf");
4700 free(id_str1);
4701 free(id_str2);
4702 return err;
4704 free(id_str1);
4705 free(id_str2);
4707 err = draw_file(view, header);
4708 free(header);
4709 return err;
4712 static const struct got_error *
4713 set_selected_commit(struct tog_diff_view_state *s,
4714 struct commit_queue_entry *entry)
4716 const struct got_error *err;
4717 const struct got_object_id_queue *parent_ids;
4718 struct got_commit_object *selected_commit;
4719 struct got_object_qid *pid;
4721 free(s->id2);
4722 s->id2 = got_object_id_dup(entry->id);
4723 if (s->id2 == NULL)
4724 return got_error_from_errno("got_object_id_dup");
4726 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
4727 if (err)
4728 return err;
4729 parent_ids = got_object_commit_get_parent_ids(selected_commit);
4730 free(s->id1);
4731 pid = STAILQ_FIRST(parent_ids);
4732 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
4733 got_object_commit_close(selected_commit);
4734 return NULL;
4737 static const struct got_error *
4738 reset_diff_view(struct tog_view *view)
4740 struct tog_diff_view_state *s = &view->state.diff;
4742 view->count = 0;
4743 wclear(view->window);
4744 s->first_displayed_line = 1;
4745 s->last_displayed_line = view->nlines;
4746 s->matched_line = 0;
4747 diff_view_indicate_progress(view);
4748 return create_diff(s);
4751 static void
4752 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
4754 int start, i;
4756 i = start = s->first_displayed_line - 1;
4758 while (s->lines[i].type != type) {
4759 if (i == 0)
4760 i = s->nlines - 1;
4761 if (--i == start)
4762 return; /* do nothing, requested type not in file */
4765 s->selected_line = 1;
4766 s->first_displayed_line = i;
4769 static void
4770 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
4772 int start, i;
4774 i = start = s->first_displayed_line + 1;
4776 while (s->lines[i].type != type) {
4777 if (i == s->nlines - 1)
4778 i = 0;
4779 if (++i == start)
4780 return; /* do nothing, requested type not in file */
4783 s->selected_line = 1;
4784 s->first_displayed_line = i;
4787 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
4788 int, int, int);
4789 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
4790 int, int);
4792 static const struct got_error *
4793 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
4795 const struct got_error *err = NULL;
4796 struct tog_diff_view_state *s = &view->state.diff;
4797 struct tog_log_view_state *ls;
4798 struct commit_queue_entry *old_selected_entry;
4799 char *line = NULL;
4800 size_t linesize = 0;
4801 ssize_t linelen;
4802 int i, nscroll = view->nlines - 1, up = 0;
4804 s->lineno = s->first_displayed_line - 1 + s->selected_line;
4806 switch (ch) {
4807 case '0':
4808 view->x = 0;
4809 break;
4810 case '$':
4811 view->x = MAX(view->maxx - view->ncols / 3, 0);
4812 view->count = 0;
4813 break;
4814 case KEY_RIGHT:
4815 case 'l':
4816 if (view->x + view->ncols / 3 < view->maxx)
4817 view->x += 2; /* move two columns right */
4818 else
4819 view->count = 0;
4820 break;
4821 case KEY_LEFT:
4822 case 'h':
4823 view->x -= MIN(view->x, 2); /* move two columns back */
4824 if (view->x <= 0)
4825 view->count = 0;
4826 break;
4827 case 'a':
4828 case 'w':
4829 if (ch == 'a')
4830 s->force_text_diff = !s->force_text_diff;
4831 if (ch == 'w')
4832 s->ignore_whitespace = !s->ignore_whitespace;
4833 err = reset_diff_view(view);
4834 break;
4835 case 'g':
4836 case KEY_HOME:
4837 s->first_displayed_line = 1;
4838 view->count = 0;
4839 break;
4840 case 'G':
4841 case KEY_END:
4842 view->count = 0;
4843 if (s->eof)
4844 break;
4846 s->first_displayed_line = (s->nlines - view->nlines) + 2;
4847 s->eof = 1;
4848 break;
4849 case 'k':
4850 case KEY_UP:
4851 case CTRL('p'):
4852 if (s->first_displayed_line > 1)
4853 s->first_displayed_line--;
4854 else
4855 view->count = 0;
4856 break;
4857 case CTRL('u'):
4858 case 'u':
4859 nscroll /= 2;
4860 /* FALL THROUGH */
4861 case KEY_PPAGE:
4862 case CTRL('b'):
4863 case 'b':
4864 if (s->first_displayed_line == 1) {
4865 view->count = 0;
4866 break;
4868 i = 0;
4869 while (i++ < nscroll && s->first_displayed_line > 1)
4870 s->first_displayed_line--;
4871 break;
4872 case 'j':
4873 case KEY_DOWN:
4874 case CTRL('n'):
4875 if (!s->eof)
4876 s->first_displayed_line++;
4877 else
4878 view->count = 0;
4879 break;
4880 case CTRL('d'):
4881 case 'd':
4882 nscroll /= 2;
4883 /* FALL THROUGH */
4884 case KEY_NPAGE:
4885 case CTRL('f'):
4886 case 'f':
4887 case ' ':
4888 if (s->eof) {
4889 view->count = 0;
4890 break;
4892 i = 0;
4893 while (!s->eof && i++ < nscroll) {
4894 linelen = getline(&line, &linesize, s->f);
4895 s->first_displayed_line++;
4896 if (linelen == -1) {
4897 if (feof(s->f)) {
4898 s->eof = 1;
4899 } else
4900 err = got_ferror(s->f, GOT_ERR_IO);
4901 break;
4904 free(line);
4905 break;
4906 case '(':
4907 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
4908 break;
4909 case ')':
4910 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
4911 break;
4912 case '{':
4913 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
4914 break;
4915 case '}':
4916 diff_next_index(s, GOT_DIFF_LINE_HUNK);
4917 break;
4918 case '[':
4919 if (s->diff_context > 0) {
4920 s->diff_context--;
4921 s->matched_line = 0;
4922 diff_view_indicate_progress(view);
4923 err = create_diff(s);
4924 if (s->first_displayed_line + view->nlines - 1 >
4925 s->nlines) {
4926 s->first_displayed_line = 1;
4927 s->last_displayed_line = view->nlines;
4929 } else
4930 view->count = 0;
4931 break;
4932 case ']':
4933 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
4934 s->diff_context++;
4935 s->matched_line = 0;
4936 diff_view_indicate_progress(view);
4937 err = create_diff(s);
4938 } else
4939 view->count = 0;
4940 break;
4941 case '<':
4942 case ',':
4943 case 'K':
4944 up = 1;
4945 /* FALL THROUGH */
4946 case '>':
4947 case '.':
4948 case 'J':
4949 if (s->parent_view == NULL) {
4950 view->count = 0;
4951 break;
4953 s->parent_view->count = view->count;
4955 if (s->parent_view->type == TOG_VIEW_LOG) {
4956 ls = &s->parent_view->state.log;
4957 old_selected_entry = ls->selected_entry;
4959 err = input_log_view(NULL, s->parent_view,
4960 up ? KEY_UP : KEY_DOWN);
4961 if (err)
4962 break;
4963 view->count = s->parent_view->count;
4965 if (old_selected_entry == ls->selected_entry)
4966 break;
4968 err = set_selected_commit(s, ls->selected_entry);
4969 if (err)
4970 break;
4971 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
4972 struct tog_blame_view_state *bs;
4973 struct got_object_id *id, *prev_id;
4975 bs = &s->parent_view->state.blame;
4976 prev_id = get_annotation_for_line(bs->blame.lines,
4977 bs->blame.nlines, bs->last_diffed_line);
4979 err = input_blame_view(&view, s->parent_view,
4980 up ? KEY_UP : KEY_DOWN);
4981 if (err)
4982 break;
4983 view->count = s->parent_view->count;
4985 if (prev_id == NULL)
4986 break;
4987 id = get_selected_commit_id(bs->blame.lines,
4988 bs->blame.nlines, bs->first_displayed_line,
4989 bs->selected_line);
4990 if (id == NULL)
4991 break;
4993 if (!got_object_id_cmp(prev_id, id))
4994 break;
4996 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
4997 if (err)
4998 break;
5000 s->first_displayed_line = 1;
5001 s->last_displayed_line = view->nlines;
5002 s->matched_line = 0;
5003 view->x = 0;
5005 diff_view_indicate_progress(view);
5006 err = create_diff(s);
5007 break;
5008 default:
5009 view->count = 0;
5010 break;
5013 return err;
5016 static const struct got_error *
5017 cmd_diff(int argc, char *argv[])
5019 const struct got_error *error = NULL;
5020 struct got_repository *repo = NULL;
5021 struct got_worktree *worktree = NULL;
5022 struct got_object_id *id1 = NULL, *id2 = NULL;
5023 char *repo_path = NULL, *cwd = NULL;
5024 char *id_str1 = NULL, *id_str2 = NULL;
5025 char *label1 = NULL, *label2 = NULL;
5026 int diff_context = 3, ignore_whitespace = 0;
5027 int ch, force_text_diff = 0;
5028 const char *errstr;
5029 struct tog_view *view;
5030 int *pack_fds = NULL;
5032 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5033 switch (ch) {
5034 case 'a':
5035 force_text_diff = 1;
5036 break;
5037 case 'C':
5038 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5039 &errstr);
5040 if (errstr != NULL)
5041 errx(1, "number of context lines is %s: %s",
5042 errstr, errstr);
5043 break;
5044 case 'r':
5045 repo_path = realpath(optarg, NULL);
5046 if (repo_path == NULL)
5047 return got_error_from_errno2("realpath",
5048 optarg);
5049 got_path_strip_trailing_slashes(repo_path);
5050 break;
5051 case 'w':
5052 ignore_whitespace = 1;
5053 break;
5054 default:
5055 usage_diff();
5056 /* NOTREACHED */
5060 argc -= optind;
5061 argv += optind;
5063 if (argc == 0) {
5064 usage_diff(); /* TODO show local worktree changes */
5065 } else if (argc == 2) {
5066 id_str1 = argv[0];
5067 id_str2 = argv[1];
5068 } else
5069 usage_diff();
5071 error = got_repo_pack_fds_open(&pack_fds);
5072 if (error)
5073 goto done;
5075 if (repo_path == NULL) {
5076 cwd = getcwd(NULL, 0);
5077 if (cwd == NULL)
5078 return got_error_from_errno("getcwd");
5079 error = got_worktree_open(&worktree, cwd);
5080 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5081 goto done;
5082 if (worktree)
5083 repo_path =
5084 strdup(got_worktree_get_repo_path(worktree));
5085 else
5086 repo_path = strdup(cwd);
5087 if (repo_path == NULL) {
5088 error = got_error_from_errno("strdup");
5089 goto done;
5093 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5094 if (error)
5095 goto done;
5097 init_curses();
5099 error = apply_unveil(got_repo_get_path(repo), NULL);
5100 if (error)
5101 goto done;
5103 error = tog_load_refs(repo, 0);
5104 if (error)
5105 goto done;
5107 error = got_repo_match_object_id(&id1, &label1, id_str1,
5108 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5109 if (error)
5110 goto done;
5112 error = got_repo_match_object_id(&id2, &label2, id_str2,
5113 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5114 if (error)
5115 goto done;
5117 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5118 if (view == NULL) {
5119 error = got_error_from_errno("view_open");
5120 goto done;
5122 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5123 ignore_whitespace, force_text_diff, NULL, repo);
5124 if (error)
5125 goto done;
5126 error = view_loop(view);
5127 done:
5128 free(label1);
5129 free(label2);
5130 free(repo_path);
5131 free(cwd);
5132 if (repo) {
5133 const struct got_error *close_err = got_repo_close(repo);
5134 if (error == NULL)
5135 error = close_err;
5137 if (worktree)
5138 got_worktree_close(worktree);
5139 if (pack_fds) {
5140 const struct got_error *pack_err =
5141 got_repo_pack_fds_close(pack_fds);
5142 if (error == NULL)
5143 error = pack_err;
5145 tog_free_refs();
5146 return error;
5149 __dead static void
5150 usage_blame(void)
5152 endwin();
5153 fprintf(stderr,
5154 "usage: %s blame [-c commit] [-r repository-path] path\n",
5155 getprogname());
5156 exit(1);
5159 struct tog_blame_line {
5160 int annotated;
5161 struct got_object_id *id;
5164 static const struct got_error *
5165 draw_blame(struct tog_view *view)
5167 struct tog_blame_view_state *s = &view->state.blame;
5168 struct tog_blame *blame = &s->blame;
5169 regmatch_t *regmatch = &view->regmatch;
5170 const struct got_error *err;
5171 int lineno = 0, nprinted = 0;
5172 char *line = NULL;
5173 size_t linesize = 0;
5174 ssize_t linelen;
5175 wchar_t *wline;
5176 int width;
5177 struct tog_blame_line *blame_line;
5178 struct got_object_id *prev_id = NULL;
5179 char *id_str;
5180 struct tog_color *tc;
5182 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5183 if (err)
5184 return err;
5186 rewind(blame->f);
5187 werase(view->window);
5189 if (asprintf(&line, "commit %s", id_str) == -1) {
5190 err = got_error_from_errno("asprintf");
5191 free(id_str);
5192 return err;
5195 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5196 free(line);
5197 line = NULL;
5198 if (err)
5199 return err;
5200 if (view_needs_focus_indication(view))
5201 wstandout(view->window);
5202 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5203 if (tc)
5204 wattr_on(view->window,
5205 COLOR_PAIR(tc->colorpair), NULL);
5206 waddwstr(view->window, wline);
5207 if (tc)
5208 wattr_off(view->window,
5209 COLOR_PAIR(tc->colorpair), NULL);
5210 if (view_needs_focus_indication(view))
5211 wstandend(view->window);
5212 free(wline);
5213 wline = NULL;
5214 if (width < view->ncols - 1)
5215 waddch(view->window, '\n');
5217 if (view->gline > blame->nlines)
5218 view->gline = blame->nlines;
5220 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5221 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5222 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5223 free(id_str);
5224 return got_error_from_errno("asprintf");
5226 free(id_str);
5227 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5228 free(line);
5229 line = NULL;
5230 if (err)
5231 return err;
5232 waddwstr(view->window, wline);
5233 free(wline);
5234 wline = NULL;
5235 if (width < view->ncols - 1)
5236 waddch(view->window, '\n');
5238 s->eof = 0;
5239 view->maxx = 0;
5240 while (nprinted < view->nlines - 2) {
5241 linelen = getline(&line, &linesize, blame->f);
5242 if (linelen == -1) {
5243 if (feof(blame->f)) {
5244 s->eof = 1;
5245 break;
5247 free(line);
5248 return got_ferror(blame->f, GOT_ERR_IO);
5250 if (++lineno < s->first_displayed_line)
5251 continue;
5252 if (view->gline && !gotoline(view, &lineno, &nprinted))
5253 continue;
5255 /* Set view->maxx based on full line length. */
5256 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5257 if (err) {
5258 free(line);
5259 return err;
5261 free(wline);
5262 wline = NULL;
5263 view->maxx = MAX(view->maxx, width);
5265 if (nprinted == s->selected_line - 1)
5266 wstandout(view->window);
5268 if (blame->nlines > 0) {
5269 blame_line = &blame->lines[lineno - 1];
5270 if (blame_line->annotated && prev_id &&
5271 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5272 !(nprinted == s->selected_line - 1)) {
5273 waddstr(view->window, " ");
5274 } else if (blame_line->annotated) {
5275 char *id_str;
5276 err = got_object_id_str(&id_str,
5277 blame_line->id);
5278 if (err) {
5279 free(line);
5280 return err;
5282 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5283 if (tc)
5284 wattr_on(view->window,
5285 COLOR_PAIR(tc->colorpair), NULL);
5286 wprintw(view->window, "%.8s", id_str);
5287 if (tc)
5288 wattr_off(view->window,
5289 COLOR_PAIR(tc->colorpair), NULL);
5290 free(id_str);
5291 prev_id = blame_line->id;
5292 } else {
5293 waddstr(view->window, "........");
5294 prev_id = NULL;
5296 } else {
5297 waddstr(view->window, "........");
5298 prev_id = NULL;
5301 if (nprinted == s->selected_line - 1)
5302 wstandend(view->window);
5303 waddstr(view->window, " ");
5305 if (view->ncols <= 9) {
5306 width = 9;
5307 } else if (s->first_displayed_line + nprinted ==
5308 s->matched_line &&
5309 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5310 err = add_matched_line(&width, line, view->ncols - 9, 9,
5311 view->window, view->x, regmatch);
5312 if (err) {
5313 free(line);
5314 return err;
5316 width += 9;
5317 } else {
5318 int skip;
5319 err = format_line(&wline, &width, &skip, line,
5320 view->x, view->ncols - 9, 9, 1);
5321 if (err) {
5322 free(line);
5323 return err;
5325 waddwstr(view->window, &wline[skip]);
5326 width += 9;
5327 free(wline);
5328 wline = NULL;
5331 if (width <= view->ncols - 1)
5332 waddch(view->window, '\n');
5333 if (++nprinted == 1)
5334 s->first_displayed_line = lineno;
5336 free(line);
5337 s->last_displayed_line = lineno;
5339 view_border(view);
5341 return NULL;
5344 static const struct got_error *
5345 blame_cb(void *arg, int nlines, int lineno,
5346 struct got_commit_object *commit, struct got_object_id *id)
5348 const struct got_error *err = NULL;
5349 struct tog_blame_cb_args *a = arg;
5350 struct tog_blame_line *line;
5351 int errcode;
5353 if (nlines != a->nlines ||
5354 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5355 return got_error(GOT_ERR_RANGE);
5357 errcode = pthread_mutex_lock(&tog_mutex);
5358 if (errcode)
5359 return got_error_set_errno(errcode, "pthread_mutex_lock");
5361 if (*a->quit) { /* user has quit the blame view */
5362 err = got_error(GOT_ERR_ITER_COMPLETED);
5363 goto done;
5366 if (lineno == -1)
5367 goto done; /* no change in this commit */
5369 line = &a->lines[lineno - 1];
5370 if (line->annotated)
5371 goto done;
5373 line->id = got_object_id_dup(id);
5374 if (line->id == NULL) {
5375 err = got_error_from_errno("got_object_id_dup");
5376 goto done;
5378 line->annotated = 1;
5379 done:
5380 errcode = pthread_mutex_unlock(&tog_mutex);
5381 if (errcode)
5382 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5383 return err;
5386 static void *
5387 blame_thread(void *arg)
5389 const struct got_error *err, *close_err;
5390 struct tog_blame_thread_args *ta = arg;
5391 struct tog_blame_cb_args *a = ta->cb_args;
5392 int errcode, fd1 = -1, fd2 = -1;
5393 FILE *f1 = NULL, *f2 = NULL;
5395 fd1 = got_opentempfd();
5396 if (fd1 == -1)
5397 return (void *)got_error_from_errno("got_opentempfd");
5399 fd2 = got_opentempfd();
5400 if (fd2 == -1) {
5401 err = got_error_from_errno("got_opentempfd");
5402 goto done;
5405 f1 = got_opentemp();
5406 if (f1 == NULL) {
5407 err = (void *)got_error_from_errno("got_opentemp");
5408 goto done;
5410 f2 = got_opentemp();
5411 if (f2 == NULL) {
5412 err = (void *)got_error_from_errno("got_opentemp");
5413 goto done;
5416 err = block_signals_used_by_main_thread();
5417 if (err)
5418 goto done;
5420 err = got_blame(ta->path, a->commit_id, ta->repo,
5421 tog_diff_algo, blame_cb, ta->cb_args,
5422 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5423 if (err && err->code == GOT_ERR_CANCELLED)
5424 err = NULL;
5426 errcode = pthread_mutex_lock(&tog_mutex);
5427 if (errcode) {
5428 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5429 goto done;
5432 close_err = got_repo_close(ta->repo);
5433 if (err == NULL)
5434 err = close_err;
5435 ta->repo = NULL;
5436 *ta->complete = 1;
5438 errcode = pthread_mutex_unlock(&tog_mutex);
5439 if (errcode && err == NULL)
5440 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5442 done:
5443 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5444 err = got_error_from_errno("close");
5445 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5446 err = got_error_from_errno("close");
5447 if (f1 && fclose(f1) == EOF && err == NULL)
5448 err = got_error_from_errno("fclose");
5449 if (f2 && fclose(f2) == EOF && err == NULL)
5450 err = got_error_from_errno("fclose");
5452 return (void *)err;
5455 static struct got_object_id *
5456 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5457 int first_displayed_line, int selected_line)
5459 struct tog_blame_line *line;
5461 if (nlines <= 0)
5462 return NULL;
5464 line = &lines[first_displayed_line - 1 + selected_line - 1];
5465 if (!line->annotated)
5466 return NULL;
5468 return line->id;
5471 static struct got_object_id *
5472 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5473 int lineno)
5475 struct tog_blame_line *line;
5477 if (nlines <= 0 || lineno >= nlines)
5478 return NULL;
5480 line = &lines[lineno - 1];
5481 if (!line->annotated)
5482 return NULL;
5484 return line->id;
5487 static const struct got_error *
5488 stop_blame(struct tog_blame *blame)
5490 const struct got_error *err = NULL;
5491 int i;
5493 if (blame->thread) {
5494 int errcode;
5495 errcode = pthread_mutex_unlock(&tog_mutex);
5496 if (errcode)
5497 return got_error_set_errno(errcode,
5498 "pthread_mutex_unlock");
5499 errcode = pthread_join(blame->thread, (void **)&err);
5500 if (errcode)
5501 return got_error_set_errno(errcode, "pthread_join");
5502 errcode = pthread_mutex_lock(&tog_mutex);
5503 if (errcode)
5504 return got_error_set_errno(errcode,
5505 "pthread_mutex_lock");
5506 if (err && err->code == GOT_ERR_ITER_COMPLETED)
5507 err = NULL;
5508 blame->thread = NULL;
5510 if (blame->thread_args.repo) {
5511 const struct got_error *close_err;
5512 close_err = got_repo_close(blame->thread_args.repo);
5513 if (err == NULL)
5514 err = close_err;
5515 blame->thread_args.repo = NULL;
5517 if (blame->f) {
5518 if (fclose(blame->f) == EOF && err == NULL)
5519 err = got_error_from_errno("fclose");
5520 blame->f = NULL;
5522 if (blame->lines) {
5523 for (i = 0; i < blame->nlines; i++)
5524 free(blame->lines[i].id);
5525 free(blame->lines);
5526 blame->lines = NULL;
5528 free(blame->cb_args.commit_id);
5529 blame->cb_args.commit_id = NULL;
5530 if (blame->pack_fds) {
5531 const struct got_error *pack_err =
5532 got_repo_pack_fds_close(blame->pack_fds);
5533 if (err == NULL)
5534 err = pack_err;
5535 blame->pack_fds = NULL;
5537 return err;
5540 static const struct got_error *
5541 cancel_blame_view(void *arg)
5543 const struct got_error *err = NULL;
5544 int *done = arg;
5545 int errcode;
5547 errcode = pthread_mutex_lock(&tog_mutex);
5548 if (errcode)
5549 return got_error_set_errno(errcode,
5550 "pthread_mutex_unlock");
5552 if (*done)
5553 err = got_error(GOT_ERR_CANCELLED);
5555 errcode = pthread_mutex_unlock(&tog_mutex);
5556 if (errcode)
5557 return got_error_set_errno(errcode,
5558 "pthread_mutex_lock");
5560 return err;
5563 static const struct got_error *
5564 run_blame(struct tog_view *view)
5566 struct tog_blame_view_state *s = &view->state.blame;
5567 struct tog_blame *blame = &s->blame;
5568 const struct got_error *err = NULL;
5569 struct got_commit_object *commit = NULL;
5570 struct got_blob_object *blob = NULL;
5571 struct got_repository *thread_repo = NULL;
5572 struct got_object_id *obj_id = NULL;
5573 int obj_type, fd = -1;
5574 int *pack_fds = NULL;
5576 err = got_object_open_as_commit(&commit, s->repo,
5577 &s->blamed_commit->id);
5578 if (err)
5579 return err;
5581 fd = got_opentempfd();
5582 if (fd == -1) {
5583 err = got_error_from_errno("got_opentempfd");
5584 goto done;
5587 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
5588 if (err)
5589 goto done;
5591 err = got_object_get_type(&obj_type, s->repo, obj_id);
5592 if (err)
5593 goto done;
5595 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5596 err = got_error(GOT_ERR_OBJ_TYPE);
5597 goto done;
5600 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
5601 if (err)
5602 goto done;
5603 blame->f = got_opentemp();
5604 if (blame->f == NULL) {
5605 err = got_error_from_errno("got_opentemp");
5606 goto done;
5608 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
5609 &blame->line_offsets, blame->f, blob);
5610 if (err)
5611 goto done;
5612 if (blame->nlines == 0) {
5613 s->blame_complete = 1;
5614 goto done;
5617 /* Don't include \n at EOF in the blame line count. */
5618 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
5619 blame->nlines--;
5621 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
5622 if (blame->lines == NULL) {
5623 err = got_error_from_errno("calloc");
5624 goto done;
5627 err = got_repo_pack_fds_open(&pack_fds);
5628 if (err)
5629 goto done;
5630 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
5631 pack_fds);
5632 if (err)
5633 goto done;
5635 blame->pack_fds = pack_fds;
5636 blame->cb_args.view = view;
5637 blame->cb_args.lines = blame->lines;
5638 blame->cb_args.nlines = blame->nlines;
5639 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
5640 if (blame->cb_args.commit_id == NULL) {
5641 err = got_error_from_errno("got_object_id_dup");
5642 goto done;
5644 blame->cb_args.quit = &s->done;
5646 blame->thread_args.path = s->path;
5647 blame->thread_args.repo = thread_repo;
5648 blame->thread_args.cb_args = &blame->cb_args;
5649 blame->thread_args.complete = &s->blame_complete;
5650 blame->thread_args.cancel_cb = cancel_blame_view;
5651 blame->thread_args.cancel_arg = &s->done;
5652 s->blame_complete = 0;
5654 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
5655 s->first_displayed_line = 1;
5656 s->last_displayed_line = view->nlines;
5657 s->selected_line = 1;
5659 s->matched_line = 0;
5661 done:
5662 if (commit)
5663 got_object_commit_close(commit);
5664 if (fd != -1 && close(fd) == -1 && err == NULL)
5665 err = got_error_from_errno("close");
5666 if (blob)
5667 got_object_blob_close(blob);
5668 free(obj_id);
5669 if (err)
5670 stop_blame(blame);
5671 return err;
5674 static const struct got_error *
5675 open_blame_view(struct tog_view *view, char *path,
5676 struct got_object_id *commit_id, struct got_repository *repo)
5678 const struct got_error *err = NULL;
5679 struct tog_blame_view_state *s = &view->state.blame;
5681 STAILQ_INIT(&s->blamed_commits);
5683 s->path = strdup(path);
5684 if (s->path == NULL)
5685 return got_error_from_errno("strdup");
5687 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
5688 if (err) {
5689 free(s->path);
5690 return err;
5693 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
5694 s->first_displayed_line = 1;
5695 s->last_displayed_line = view->nlines;
5696 s->selected_line = 1;
5697 s->blame_complete = 0;
5698 s->repo = repo;
5699 s->commit_id = commit_id;
5700 memset(&s->blame, 0, sizeof(s->blame));
5702 STAILQ_INIT(&s->colors);
5703 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5704 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
5705 get_color_value("TOG_COLOR_COMMIT"));
5706 if (err)
5707 return err;
5710 view->show = show_blame_view;
5711 view->input = input_blame_view;
5712 view->reset = reset_blame_view;
5713 view->close = close_blame_view;
5714 view->search_start = search_start_blame_view;
5715 view->search_next = search_next_blame_view;
5717 return run_blame(view);
5720 static const struct got_error *
5721 close_blame_view(struct tog_view *view)
5723 const struct got_error *err = NULL;
5724 struct tog_blame_view_state *s = &view->state.blame;
5726 if (s->blame.thread)
5727 err = stop_blame(&s->blame);
5729 while (!STAILQ_EMPTY(&s->blamed_commits)) {
5730 struct got_object_qid *blamed_commit;
5731 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
5732 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5733 got_object_qid_free(blamed_commit);
5736 free(s->path);
5737 free_colors(&s->colors);
5738 return err;
5741 static const struct got_error *
5742 search_start_blame_view(struct tog_view *view)
5744 struct tog_blame_view_state *s = &view->state.blame;
5746 s->matched_line = 0;
5747 return NULL;
5750 static const struct got_error *
5751 search_next_blame_view(struct tog_view *view)
5753 struct tog_blame_view_state *s = &view->state.blame;
5754 const struct got_error *err = NULL;
5755 int lineno;
5756 char *line = NULL;
5757 size_t linesize = 0;
5758 ssize_t linelen;
5760 if (!view->searching) {
5761 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5762 return NULL;
5765 if (s->matched_line) {
5766 if (view->searching == TOG_SEARCH_FORWARD)
5767 lineno = s->matched_line + 1;
5768 else
5769 lineno = s->matched_line - 1;
5770 } else
5771 lineno = s->first_displayed_line - 1 + s->selected_line;
5773 while (1) {
5774 off_t offset;
5776 if (lineno <= 0 || lineno > s->blame.nlines) {
5777 if (s->matched_line == 0) {
5778 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5779 break;
5782 if (view->searching == TOG_SEARCH_FORWARD)
5783 lineno = 1;
5784 else
5785 lineno = s->blame.nlines;
5788 offset = s->blame.line_offsets[lineno - 1];
5789 if (fseeko(s->blame.f, offset, SEEK_SET) != 0) {
5790 free(line);
5791 return got_error_from_errno("fseeko");
5793 linelen = getline(&line, &linesize, s->blame.f);
5794 if (linelen != -1) {
5795 char *exstr;
5796 err = expand_tab(&exstr, line);
5797 if (err)
5798 break;
5799 if (match_line(exstr, &view->regex, 1,
5800 &view->regmatch)) {
5801 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5802 s->matched_line = lineno;
5803 free(exstr);
5804 break;
5806 free(exstr);
5808 if (view->searching == TOG_SEARCH_FORWARD)
5809 lineno++;
5810 else
5811 lineno--;
5813 free(line);
5815 if (s->matched_line) {
5816 s->first_displayed_line = s->matched_line;
5817 s->selected_line = 1;
5820 return err;
5823 static const struct got_error *
5824 show_blame_view(struct tog_view *view)
5826 const struct got_error *err = NULL;
5827 struct tog_blame_view_state *s = &view->state.blame;
5828 int errcode;
5830 if (s->blame.thread == NULL && !s->blame_complete) {
5831 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
5832 &s->blame.thread_args);
5833 if (errcode)
5834 return got_error_set_errno(errcode, "pthread_create");
5836 halfdelay(1); /* fast refresh while annotating */
5839 if (s->blame_complete)
5840 halfdelay(10); /* disable fast refresh */
5842 err = draw_blame(view);
5844 view_border(view);
5845 return err;
5848 static const struct got_error *
5849 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
5850 struct got_repository *repo, struct got_object_id *id)
5852 struct tog_view *log_view;
5853 const struct got_error *err = NULL;
5855 *new_view = NULL;
5857 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
5858 if (log_view == NULL)
5859 return got_error_from_errno("view_open");
5861 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
5862 if (err)
5863 view_close(log_view);
5864 else
5865 *new_view = log_view;
5867 return err;
5870 static const struct got_error *
5871 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
5873 const struct got_error *err = NULL, *thread_err = NULL;
5874 struct tog_view *diff_view;
5875 struct tog_blame_view_state *s = &view->state.blame;
5876 int eos, nscroll, begin_y = 0, begin_x = 0;
5878 eos = nscroll = view->nlines - 2;
5879 if (view_is_hsplit_top(view))
5880 --eos; /* border */
5882 switch (ch) {
5883 case '0':
5884 view->x = 0;
5885 break;
5886 case '$':
5887 view->x = MAX(view->maxx - view->ncols / 3, 0);
5888 view->count = 0;
5889 break;
5890 case KEY_RIGHT:
5891 case 'l':
5892 if (view->x + view->ncols / 3 < view->maxx)
5893 view->x += 2; /* move two columns right */
5894 else
5895 view->count = 0;
5896 break;
5897 case KEY_LEFT:
5898 case 'h':
5899 view->x -= MIN(view->x, 2); /* move two columns back */
5900 if (view->x <= 0)
5901 view->count = 0;
5902 break;
5903 case 'q':
5904 s->done = 1;
5905 break;
5906 case 'g':
5907 case KEY_HOME:
5908 s->selected_line = 1;
5909 s->first_displayed_line = 1;
5910 view->count = 0;
5911 break;
5912 case 'G':
5913 case KEY_END:
5914 if (s->blame.nlines < eos) {
5915 s->selected_line = s->blame.nlines;
5916 s->first_displayed_line = 1;
5917 } else {
5918 s->selected_line = eos;
5919 s->first_displayed_line = s->blame.nlines - (eos - 1);
5921 view->count = 0;
5922 break;
5923 case 'k':
5924 case KEY_UP:
5925 case CTRL('p'):
5926 if (s->selected_line > 1)
5927 s->selected_line--;
5928 else if (s->selected_line == 1 &&
5929 s->first_displayed_line > 1)
5930 s->first_displayed_line--;
5931 else
5932 view->count = 0;
5933 break;
5934 case CTRL('u'):
5935 case 'u':
5936 nscroll /= 2;
5937 /* FALL THROUGH */
5938 case KEY_PPAGE:
5939 case CTRL('b'):
5940 case 'b':
5941 if (s->first_displayed_line == 1) {
5942 if (view->count > 1)
5943 nscroll += nscroll;
5944 s->selected_line = MAX(1, s->selected_line - nscroll);
5945 view->count = 0;
5946 break;
5948 if (s->first_displayed_line > nscroll)
5949 s->first_displayed_line -= nscroll;
5950 else
5951 s->first_displayed_line = 1;
5952 break;
5953 case 'j':
5954 case KEY_DOWN:
5955 case CTRL('n'):
5956 if (s->selected_line < eos && s->first_displayed_line +
5957 s->selected_line <= s->blame.nlines)
5958 s->selected_line++;
5959 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
5960 s->first_displayed_line++;
5961 else
5962 view->count = 0;
5963 break;
5964 case 'c':
5965 case 'p': {
5966 struct got_object_id *id = NULL;
5968 view->count = 0;
5969 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5970 s->first_displayed_line, s->selected_line);
5971 if (id == NULL)
5972 break;
5973 if (ch == 'p') {
5974 struct got_commit_object *commit, *pcommit;
5975 struct got_object_qid *pid;
5976 struct got_object_id *blob_id = NULL;
5977 int obj_type;
5978 err = got_object_open_as_commit(&commit,
5979 s->repo, id);
5980 if (err)
5981 break;
5982 pid = STAILQ_FIRST(
5983 got_object_commit_get_parent_ids(commit));
5984 if (pid == NULL) {
5985 got_object_commit_close(commit);
5986 break;
5988 /* Check if path history ends here. */
5989 err = got_object_open_as_commit(&pcommit,
5990 s->repo, &pid->id);
5991 if (err)
5992 break;
5993 err = got_object_id_by_path(&blob_id, s->repo,
5994 pcommit, s->path);
5995 got_object_commit_close(pcommit);
5996 if (err) {
5997 if (err->code == GOT_ERR_NO_TREE_ENTRY)
5998 err = NULL;
5999 got_object_commit_close(commit);
6000 break;
6002 err = got_object_get_type(&obj_type, s->repo,
6003 blob_id);
6004 free(blob_id);
6005 /* Can't blame non-blob type objects. */
6006 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6007 got_object_commit_close(commit);
6008 break;
6010 err = got_object_qid_alloc(&s->blamed_commit,
6011 &pid->id);
6012 got_object_commit_close(commit);
6013 } else {
6014 if (got_object_id_cmp(id,
6015 &s->blamed_commit->id) == 0)
6016 break;
6017 err = got_object_qid_alloc(&s->blamed_commit,
6018 id);
6020 if (err)
6021 break;
6022 s->done = 1;
6023 thread_err = stop_blame(&s->blame);
6024 s->done = 0;
6025 if (thread_err)
6026 break;
6027 STAILQ_INSERT_HEAD(&s->blamed_commits,
6028 s->blamed_commit, entry);
6029 err = run_blame(view);
6030 if (err)
6031 break;
6032 break;
6034 case 'C': {
6035 struct got_object_qid *first;
6037 view->count = 0;
6038 first = STAILQ_FIRST(&s->blamed_commits);
6039 if (!got_object_id_cmp(&first->id, s->commit_id))
6040 break;
6041 s->done = 1;
6042 thread_err = stop_blame(&s->blame);
6043 s->done = 0;
6044 if (thread_err)
6045 break;
6046 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6047 got_object_qid_free(s->blamed_commit);
6048 s->blamed_commit =
6049 STAILQ_FIRST(&s->blamed_commits);
6050 err = run_blame(view);
6051 if (err)
6052 break;
6053 break;
6055 case 'L':
6056 view->count = 0;
6057 s->id_to_log = get_selected_commit_id(s->blame.lines,
6058 s->blame.nlines, s->first_displayed_line, s->selected_line);
6059 if (s->id_to_log)
6060 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6061 break;
6062 case KEY_ENTER:
6063 case '\r': {
6064 struct got_object_id *id = NULL;
6065 struct got_object_qid *pid;
6066 struct got_commit_object *commit = NULL;
6068 view->count = 0;
6069 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6070 s->first_displayed_line, s->selected_line);
6071 if (id == NULL)
6072 break;
6073 err = got_object_open_as_commit(&commit, s->repo, id);
6074 if (err)
6075 break;
6076 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6077 if (*new_view) {
6078 /* traversed from diff view, release diff resources */
6079 err = close_diff_view(*new_view);
6080 if (err)
6081 break;
6082 diff_view = *new_view;
6083 } else {
6084 if (view_is_parent_view(view))
6085 view_get_split(view, &begin_y, &begin_x);
6087 diff_view = view_open(0, 0, begin_y, begin_x,
6088 TOG_VIEW_DIFF);
6089 if (diff_view == NULL) {
6090 got_object_commit_close(commit);
6091 err = got_error_from_errno("view_open");
6092 break;
6095 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6096 id, NULL, NULL, 3, 0, 0, view, s->repo);
6097 got_object_commit_close(commit);
6098 if (err) {
6099 view_close(diff_view);
6100 break;
6102 s->last_diffed_line = s->first_displayed_line - 1 +
6103 s->selected_line;
6104 if (*new_view)
6105 break; /* still open from active diff view */
6106 if (view_is_parent_view(view) &&
6107 view->mode == TOG_VIEW_SPLIT_HRZN) {
6108 err = view_init_hsplit(view, begin_y);
6109 if (err)
6110 break;
6113 view->focussed = 0;
6114 diff_view->focussed = 1;
6115 diff_view->mode = view->mode;
6116 diff_view->nlines = view->lines - begin_y;
6117 if (view_is_parent_view(view)) {
6118 view_transfer_size(diff_view, view);
6119 err = view_close_child(view);
6120 if (err)
6121 break;
6122 err = view_set_child(view, diff_view);
6123 if (err)
6124 break;
6125 view->focus_child = 1;
6126 } else
6127 *new_view = diff_view;
6128 if (err)
6129 break;
6130 break;
6132 case CTRL('d'):
6133 case 'd':
6134 nscroll /= 2;
6135 /* FALL THROUGH */
6136 case KEY_NPAGE:
6137 case CTRL('f'):
6138 case 'f':
6139 case ' ':
6140 if (s->last_displayed_line >= s->blame.nlines &&
6141 s->selected_line >= MIN(s->blame.nlines,
6142 view->nlines - 2)) {
6143 view->count = 0;
6144 break;
6146 if (s->last_displayed_line >= s->blame.nlines &&
6147 s->selected_line < view->nlines - 2) {
6148 s->selected_line +=
6149 MIN(nscroll, s->last_displayed_line -
6150 s->first_displayed_line - s->selected_line + 1);
6152 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6153 s->first_displayed_line += nscroll;
6154 else
6155 s->first_displayed_line =
6156 s->blame.nlines - (view->nlines - 3);
6157 break;
6158 case KEY_RESIZE:
6159 if (s->selected_line > view->nlines - 2) {
6160 s->selected_line = MIN(s->blame.nlines,
6161 view->nlines - 2);
6163 break;
6164 default:
6165 view->count = 0;
6166 break;
6168 return thread_err ? thread_err : err;
6171 static const struct got_error *
6172 reset_blame_view(struct tog_view *view)
6174 const struct got_error *err;
6175 struct tog_blame_view_state *s = &view->state.blame;
6177 view->count = 0;
6178 s->done = 1;
6179 err = stop_blame(&s->blame);
6180 s->done = 0;
6181 if (err)
6182 return err;
6183 return run_blame(view);
6186 static const struct got_error *
6187 cmd_blame(int argc, char *argv[])
6189 const struct got_error *error;
6190 struct got_repository *repo = NULL;
6191 struct got_worktree *worktree = NULL;
6192 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6193 char *link_target = NULL;
6194 struct got_object_id *commit_id = NULL;
6195 struct got_commit_object *commit = NULL;
6196 char *commit_id_str = NULL;
6197 int ch;
6198 struct tog_view *view;
6199 int *pack_fds = NULL;
6201 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6202 switch (ch) {
6203 case 'c':
6204 commit_id_str = optarg;
6205 break;
6206 case 'r':
6207 repo_path = realpath(optarg, NULL);
6208 if (repo_path == NULL)
6209 return got_error_from_errno2("realpath",
6210 optarg);
6211 break;
6212 default:
6213 usage_blame();
6214 /* NOTREACHED */
6218 argc -= optind;
6219 argv += optind;
6221 if (argc != 1)
6222 usage_blame();
6224 error = got_repo_pack_fds_open(&pack_fds);
6225 if (error != NULL)
6226 goto done;
6228 if (repo_path == NULL) {
6229 cwd = getcwd(NULL, 0);
6230 if (cwd == NULL)
6231 return got_error_from_errno("getcwd");
6232 error = got_worktree_open(&worktree, cwd);
6233 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6234 goto done;
6235 if (worktree)
6236 repo_path =
6237 strdup(got_worktree_get_repo_path(worktree));
6238 else
6239 repo_path = strdup(cwd);
6240 if (repo_path == NULL) {
6241 error = got_error_from_errno("strdup");
6242 goto done;
6246 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6247 if (error != NULL)
6248 goto done;
6250 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6251 worktree);
6252 if (error)
6253 goto done;
6255 init_curses();
6257 error = apply_unveil(got_repo_get_path(repo), NULL);
6258 if (error)
6259 goto done;
6261 error = tog_load_refs(repo, 0);
6262 if (error)
6263 goto done;
6265 if (commit_id_str == NULL) {
6266 struct got_reference *head_ref;
6267 error = got_ref_open(&head_ref, repo, worktree ?
6268 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6269 if (error != NULL)
6270 goto done;
6271 error = got_ref_resolve(&commit_id, repo, head_ref);
6272 got_ref_close(head_ref);
6273 } else {
6274 error = got_repo_match_object_id(&commit_id, NULL,
6275 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6277 if (error != NULL)
6278 goto done;
6280 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6281 if (view == NULL) {
6282 error = got_error_from_errno("view_open");
6283 goto done;
6286 error = got_object_open_as_commit(&commit, repo, commit_id);
6287 if (error)
6288 goto done;
6290 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6291 commit, repo);
6292 if (error)
6293 goto done;
6295 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6296 commit_id, repo);
6297 if (error)
6298 goto done;
6299 if (worktree) {
6300 /* Release work tree lock. */
6301 got_worktree_close(worktree);
6302 worktree = NULL;
6304 error = view_loop(view);
6305 done:
6306 free(repo_path);
6307 free(in_repo_path);
6308 free(link_target);
6309 free(cwd);
6310 free(commit_id);
6311 if (commit)
6312 got_object_commit_close(commit);
6313 if (worktree)
6314 got_worktree_close(worktree);
6315 if (repo) {
6316 const struct got_error *close_err = got_repo_close(repo);
6317 if (error == NULL)
6318 error = close_err;
6320 if (pack_fds) {
6321 const struct got_error *pack_err =
6322 got_repo_pack_fds_close(pack_fds);
6323 if (error == NULL)
6324 error = pack_err;
6326 tog_free_refs();
6327 return error;
6330 static const struct got_error *
6331 draw_tree_entries(struct tog_view *view, const char *parent_path)
6333 struct tog_tree_view_state *s = &view->state.tree;
6334 const struct got_error *err = NULL;
6335 struct got_tree_entry *te;
6336 wchar_t *wline;
6337 struct tog_color *tc;
6338 int width, n, nentries, i = 1;
6339 int limit = view->nlines;
6341 s->ndisplayed = 0;
6342 if (view_is_hsplit_top(view))
6343 --limit; /* border */
6345 werase(view->window);
6347 if (limit == 0)
6348 return NULL;
6350 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6351 0, 0);
6352 if (err)
6353 return err;
6354 if (view_needs_focus_indication(view))
6355 wstandout(view->window);
6356 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6357 if (tc)
6358 wattr_on(view->window,
6359 COLOR_PAIR(tc->colorpair), NULL);
6360 waddwstr(view->window, wline);
6361 if (tc)
6362 wattr_off(view->window,
6363 COLOR_PAIR(tc->colorpair), NULL);
6364 if (view_needs_focus_indication(view))
6365 wstandend(view->window);
6366 free(wline);
6367 wline = NULL;
6369 i += s->selected;
6370 if (s->first_displayed_entry) {
6371 i += got_tree_entry_get_index(s->first_displayed_entry);
6372 if (s->tree != s->root)
6373 ++i; /* account for ".." entry */
6375 nentries = got_object_tree_get_nentries(s->tree);
6376 wprintw(view->window, " [%d/%d]", i,
6377 nentries + (s->tree == s->root ? 0 : 1)); /* ".." in !root tree */
6379 if (width < view->ncols - 1)
6380 waddch(view->window, '\n');
6381 if (--limit <= 0)
6382 return NULL;
6383 err = format_line(&wline, &width, NULL, parent_path, 0, view->ncols,
6384 0, 0);
6385 if (err)
6386 return err;
6387 waddwstr(view->window, wline);
6388 free(wline);
6389 wline = NULL;
6390 if (width < view->ncols - 1)
6391 waddch(view->window, '\n');
6392 if (--limit <= 0)
6393 return NULL;
6394 waddch(view->window, '\n');
6395 if (--limit <= 0)
6396 return NULL;
6398 if (s->first_displayed_entry == NULL) {
6399 te = got_object_tree_get_first_entry(s->tree);
6400 if (s->selected == 0) {
6401 if (view->focussed)
6402 wstandout(view->window);
6403 s->selected_entry = NULL;
6405 waddstr(view->window, " ..\n"); /* parent directory */
6406 if (s->selected == 0 && view->focussed)
6407 wstandend(view->window);
6408 s->ndisplayed++;
6409 if (--limit <= 0)
6410 return NULL;
6411 n = 1;
6412 } else {
6413 n = 0;
6414 te = s->first_displayed_entry;
6417 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6418 char *line = NULL, *id_str = NULL, *link_target = NULL;
6419 const char *modestr = "";
6420 mode_t mode;
6422 te = got_object_tree_get_entry(s->tree, i);
6423 mode = got_tree_entry_get_mode(te);
6425 if (s->show_ids) {
6426 err = got_object_id_str(&id_str,
6427 got_tree_entry_get_id(te));
6428 if (err)
6429 return got_error_from_errno(
6430 "got_object_id_str");
6432 if (got_object_tree_entry_is_submodule(te))
6433 modestr = "$";
6434 else if (S_ISLNK(mode)) {
6435 int i;
6437 err = got_tree_entry_get_symlink_target(&link_target,
6438 te, s->repo);
6439 if (err) {
6440 free(id_str);
6441 return err;
6443 for (i = 0; i < strlen(link_target); i++) {
6444 if (!isprint((unsigned char)link_target[i]))
6445 link_target[i] = '?';
6447 modestr = "@";
6449 else if (S_ISDIR(mode))
6450 modestr = "/";
6451 else if (mode & S_IXUSR)
6452 modestr = "*";
6453 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6454 got_tree_entry_get_name(te), modestr,
6455 link_target ? " -> ": "",
6456 link_target ? link_target : "") == -1) {
6457 free(id_str);
6458 free(link_target);
6459 return got_error_from_errno("asprintf");
6461 free(id_str);
6462 free(link_target);
6463 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
6464 0, 0);
6465 if (err) {
6466 free(line);
6467 break;
6469 if (n == s->selected) {
6470 if (view->focussed)
6471 wstandout(view->window);
6472 s->selected_entry = te;
6474 tc = match_color(&s->colors, line);
6475 if (tc)
6476 wattr_on(view->window,
6477 COLOR_PAIR(tc->colorpair), NULL);
6478 waddwstr(view->window, wline);
6479 if (tc)
6480 wattr_off(view->window,
6481 COLOR_PAIR(tc->colorpair), NULL);
6482 if (width < view->ncols - 1)
6483 waddch(view->window, '\n');
6484 if (n == s->selected && view->focussed)
6485 wstandend(view->window);
6486 free(line);
6487 free(wline);
6488 wline = NULL;
6489 n++;
6490 s->ndisplayed++;
6491 s->last_displayed_entry = te;
6492 if (--limit <= 0)
6493 break;
6496 return err;
6499 static void
6500 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6502 struct got_tree_entry *te;
6503 int isroot = s->tree == s->root;
6504 int i = 0;
6506 if (s->first_displayed_entry == NULL)
6507 return;
6509 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6510 while (i++ < maxscroll) {
6511 if (te == NULL) {
6512 if (!isroot)
6513 s->first_displayed_entry = NULL;
6514 break;
6516 s->first_displayed_entry = te;
6517 te = got_tree_entry_get_prev(s->tree, te);
6521 static const struct got_error *
6522 tree_scroll_down(struct tog_view *view, int maxscroll)
6524 struct tog_tree_view_state *s = &view->state.tree;
6525 struct got_tree_entry *next, *last;
6526 int n = 0;
6528 if (s->first_displayed_entry)
6529 next = got_tree_entry_get_next(s->tree,
6530 s->first_displayed_entry);
6531 else
6532 next = got_object_tree_get_first_entry(s->tree);
6534 last = s->last_displayed_entry;
6535 while (next && n++ < maxscroll) {
6536 if (last) {
6537 s->last_displayed_entry = last;
6538 last = got_tree_entry_get_next(s->tree, last);
6540 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
6541 s->first_displayed_entry = next;
6542 next = got_tree_entry_get_next(s->tree, next);
6546 return NULL;
6549 static const struct got_error *
6550 tree_entry_path(char **path, struct tog_parent_trees *parents,
6551 struct got_tree_entry *te)
6553 const struct got_error *err = NULL;
6554 struct tog_parent_tree *pt;
6555 size_t len = 2; /* for leading slash and NUL */
6557 TAILQ_FOREACH(pt, parents, entry)
6558 len += strlen(got_tree_entry_get_name(pt->selected_entry))
6559 + 1 /* slash */;
6560 if (te)
6561 len += strlen(got_tree_entry_get_name(te));
6563 *path = calloc(1, len);
6564 if (path == NULL)
6565 return got_error_from_errno("calloc");
6567 (*path)[0] = '/';
6568 pt = TAILQ_LAST(parents, tog_parent_trees);
6569 while (pt) {
6570 const char *name = got_tree_entry_get_name(pt->selected_entry);
6571 if (strlcat(*path, name, len) >= len) {
6572 err = got_error(GOT_ERR_NO_SPACE);
6573 goto done;
6575 if (strlcat(*path, "/", len) >= len) {
6576 err = got_error(GOT_ERR_NO_SPACE);
6577 goto done;
6579 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
6581 if (te) {
6582 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
6583 err = got_error(GOT_ERR_NO_SPACE);
6584 goto done;
6587 done:
6588 if (err) {
6589 free(*path);
6590 *path = NULL;
6592 return err;
6595 static const struct got_error *
6596 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6597 struct got_tree_entry *te, struct tog_parent_trees *parents,
6598 struct got_object_id *commit_id, struct got_repository *repo)
6600 const struct got_error *err = NULL;
6601 char *path;
6602 struct tog_view *blame_view;
6604 *new_view = NULL;
6606 err = tree_entry_path(&path, parents, te);
6607 if (err)
6608 return err;
6610 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
6611 if (blame_view == NULL) {
6612 err = got_error_from_errno("view_open");
6613 goto done;
6616 err = open_blame_view(blame_view, path, commit_id, repo);
6617 if (err) {
6618 if (err->code == GOT_ERR_CANCELLED)
6619 err = NULL;
6620 view_close(blame_view);
6621 } else
6622 *new_view = blame_view;
6623 done:
6624 free(path);
6625 return err;
6628 static const struct got_error *
6629 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6630 struct tog_tree_view_state *s)
6632 struct tog_view *log_view;
6633 const struct got_error *err = NULL;
6634 char *path;
6636 *new_view = NULL;
6638 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6639 if (log_view == NULL)
6640 return got_error_from_errno("view_open");
6642 err = tree_entry_path(&path, &s->parents, s->selected_entry);
6643 if (err)
6644 return err;
6646 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
6647 path, 0);
6648 if (err)
6649 view_close(log_view);
6650 else
6651 *new_view = log_view;
6652 free(path);
6653 return err;
6656 static const struct got_error *
6657 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
6658 const char *head_ref_name, struct got_repository *repo)
6660 const struct got_error *err = NULL;
6661 char *commit_id_str = NULL;
6662 struct tog_tree_view_state *s = &view->state.tree;
6663 struct got_commit_object *commit = NULL;
6665 TAILQ_INIT(&s->parents);
6666 STAILQ_INIT(&s->colors);
6668 s->commit_id = got_object_id_dup(commit_id);
6669 if (s->commit_id == NULL)
6670 return got_error_from_errno("got_object_id_dup");
6672 err = got_object_open_as_commit(&commit, repo, commit_id);
6673 if (err)
6674 goto done;
6677 * The root is opened here and will be closed when the view is closed.
6678 * Any visited subtrees and their path-wise parents are opened and
6679 * closed on demand.
6681 err = got_object_open_as_tree(&s->root, repo,
6682 got_object_commit_get_tree_id(commit));
6683 if (err)
6684 goto done;
6685 s->tree = s->root;
6687 err = got_object_id_str(&commit_id_str, commit_id);
6688 if (err != NULL)
6689 goto done;
6691 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
6692 err = got_error_from_errno("asprintf");
6693 goto done;
6696 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
6697 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
6698 if (head_ref_name) {
6699 s->head_ref_name = strdup(head_ref_name);
6700 if (s->head_ref_name == NULL) {
6701 err = got_error_from_errno("strdup");
6702 goto done;
6705 s->repo = repo;
6707 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6708 err = add_color(&s->colors, "\\$$",
6709 TOG_COLOR_TREE_SUBMODULE,
6710 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
6711 if (err)
6712 goto done;
6713 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
6714 get_color_value("TOG_COLOR_TREE_SYMLINK"));
6715 if (err)
6716 goto done;
6717 err = add_color(&s->colors, "/$",
6718 TOG_COLOR_TREE_DIRECTORY,
6719 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
6720 if (err)
6721 goto done;
6723 err = add_color(&s->colors, "\\*$",
6724 TOG_COLOR_TREE_EXECUTABLE,
6725 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
6726 if (err)
6727 goto done;
6729 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
6730 get_color_value("TOG_COLOR_COMMIT"));
6731 if (err)
6732 goto done;
6735 view->show = show_tree_view;
6736 view->input = input_tree_view;
6737 view->close = close_tree_view;
6738 view->search_start = search_start_tree_view;
6739 view->search_next = search_next_tree_view;
6740 done:
6741 free(commit_id_str);
6742 if (commit)
6743 got_object_commit_close(commit);
6744 if (err)
6745 close_tree_view(view);
6746 return err;
6749 static const struct got_error *
6750 close_tree_view(struct tog_view *view)
6752 struct tog_tree_view_state *s = &view->state.tree;
6754 free_colors(&s->colors);
6755 free(s->tree_label);
6756 s->tree_label = NULL;
6757 free(s->commit_id);
6758 s->commit_id = NULL;
6759 free(s->head_ref_name);
6760 s->head_ref_name = NULL;
6761 while (!TAILQ_EMPTY(&s->parents)) {
6762 struct tog_parent_tree *parent;
6763 parent = TAILQ_FIRST(&s->parents);
6764 TAILQ_REMOVE(&s->parents, parent, entry);
6765 if (parent->tree != s->root)
6766 got_object_tree_close(parent->tree);
6767 free(parent);
6770 if (s->tree != NULL && s->tree != s->root)
6771 got_object_tree_close(s->tree);
6772 if (s->root)
6773 got_object_tree_close(s->root);
6774 return NULL;
6777 static const struct got_error *
6778 search_start_tree_view(struct tog_view *view)
6780 struct tog_tree_view_state *s = &view->state.tree;
6782 s->matched_entry = NULL;
6783 return NULL;
6786 static int
6787 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
6789 regmatch_t regmatch;
6791 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
6792 0) == 0;
6795 static const struct got_error *
6796 search_next_tree_view(struct tog_view *view)
6798 struct tog_tree_view_state *s = &view->state.tree;
6799 struct got_tree_entry *te = NULL;
6801 if (!view->searching) {
6802 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6803 return NULL;
6806 if (s->matched_entry) {
6807 if (view->searching == TOG_SEARCH_FORWARD) {
6808 if (s->selected_entry)
6809 te = got_tree_entry_get_next(s->tree,
6810 s->selected_entry);
6811 else
6812 te = got_object_tree_get_first_entry(s->tree);
6813 } else {
6814 if (s->selected_entry == NULL)
6815 te = got_object_tree_get_last_entry(s->tree);
6816 else
6817 te = got_tree_entry_get_prev(s->tree,
6818 s->selected_entry);
6820 } else {
6821 if (s->selected_entry)
6822 te = s->selected_entry;
6823 else if (view->searching == TOG_SEARCH_FORWARD)
6824 te = got_object_tree_get_first_entry(s->tree);
6825 else
6826 te = got_object_tree_get_last_entry(s->tree);
6829 while (1) {
6830 if (te == NULL) {
6831 if (s->matched_entry == NULL) {
6832 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6833 return NULL;
6835 if (view->searching == TOG_SEARCH_FORWARD)
6836 te = got_object_tree_get_first_entry(s->tree);
6837 else
6838 te = got_object_tree_get_last_entry(s->tree);
6841 if (match_tree_entry(te, &view->regex)) {
6842 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6843 s->matched_entry = te;
6844 break;
6847 if (view->searching == TOG_SEARCH_FORWARD)
6848 te = got_tree_entry_get_next(s->tree, te);
6849 else
6850 te = got_tree_entry_get_prev(s->tree, te);
6853 if (s->matched_entry) {
6854 s->first_displayed_entry = s->matched_entry;
6855 s->selected = 0;
6858 return NULL;
6861 static const struct got_error *
6862 show_tree_view(struct tog_view *view)
6864 const struct got_error *err = NULL;
6865 struct tog_tree_view_state *s = &view->state.tree;
6866 char *parent_path;
6868 err = tree_entry_path(&parent_path, &s->parents, NULL);
6869 if (err)
6870 return err;
6872 err = draw_tree_entries(view, parent_path);
6873 free(parent_path);
6875 view_border(view);
6876 return err;
6879 static const struct got_error *
6880 tree_goto_line(struct tog_view *view, int nlines)
6882 const struct got_error *err = NULL;
6883 struct tog_tree_view_state *s = &view->state.tree;
6884 struct got_tree_entry **fte, **lte, **ste;
6885 int g, last, first = 1, i = 1;
6886 int root = s->tree == s->root;
6887 int off = root ? 1 : 2;
6889 g = view->gline;
6890 view->gline = 0;
6892 if (g == 0)
6893 g = 1;
6894 else if (g > got_object_tree_get_nentries(s->tree))
6895 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
6897 fte = &s->first_displayed_entry;
6898 lte = &s->last_displayed_entry;
6899 ste = &s->selected_entry;
6901 if (*fte != NULL) {
6902 first = got_tree_entry_get_index(*fte);
6903 first += off; /* account for ".." */
6905 last = got_tree_entry_get_index(*lte);
6906 last += off;
6908 if (g >= first && g <= last && g - first < nlines) {
6909 s->selected = g - first;
6910 return NULL; /* gline is on the current page */
6913 if (*ste != NULL) {
6914 i = got_tree_entry_get_index(*ste);
6915 i += off;
6918 if (i < g) {
6919 err = tree_scroll_down(view, g - i);
6920 if (err)
6921 return err;
6922 if (got_tree_entry_get_index(*lte) >=
6923 got_object_tree_get_nentries(s->tree) - 1 &&
6924 first + s->selected < g &&
6925 s->selected < s->ndisplayed - 1) {
6926 first = got_tree_entry_get_index(*fte);
6927 first += off;
6928 s->selected = g - first;
6930 } else if (i > g)
6931 tree_scroll_up(s, i - g);
6933 if (g < nlines &&
6934 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
6935 s->selected = g - 1;
6937 return NULL;
6940 static const struct got_error *
6941 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
6943 const struct got_error *err = NULL;
6944 struct tog_tree_view_state *s = &view->state.tree;
6945 struct got_tree_entry *te;
6946 int n, nscroll = view->nlines - 3;
6948 if (view->gline)
6949 return tree_goto_line(view, nscroll);
6951 switch (ch) {
6952 case 'i':
6953 s->show_ids = !s->show_ids;
6954 view->count = 0;
6955 break;
6956 case 'L':
6957 view->count = 0;
6958 if (!s->selected_entry)
6959 break;
6960 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6961 break;
6962 case 'R':
6963 view->count = 0;
6964 err = view_request_new(new_view, view, TOG_VIEW_REF);
6965 break;
6966 case 'g':
6967 case KEY_HOME:
6968 s->selected = 0;
6969 view->count = 0;
6970 if (s->tree == s->root)
6971 s->first_displayed_entry =
6972 got_object_tree_get_first_entry(s->tree);
6973 else
6974 s->first_displayed_entry = NULL;
6975 break;
6976 case 'G':
6977 case KEY_END: {
6978 int eos = view->nlines - 3;
6980 if (view->mode == TOG_VIEW_SPLIT_HRZN)
6981 --eos; /* border */
6982 s->selected = 0;
6983 view->count = 0;
6984 te = got_object_tree_get_last_entry(s->tree);
6985 for (n = 0; n < eos; n++) {
6986 if (te == NULL) {
6987 if (s->tree != s->root) {
6988 s->first_displayed_entry = NULL;
6989 n++;
6991 break;
6993 s->first_displayed_entry = te;
6994 te = got_tree_entry_get_prev(s->tree, te);
6996 if (n > 0)
6997 s->selected = n - 1;
6998 break;
7000 case 'k':
7001 case KEY_UP:
7002 case CTRL('p'):
7003 if (s->selected > 0) {
7004 s->selected--;
7005 break;
7007 tree_scroll_up(s, 1);
7008 if (s->selected_entry == NULL ||
7009 (s->tree == s->root && s->selected_entry ==
7010 got_object_tree_get_first_entry(s->tree)))
7011 view->count = 0;
7012 break;
7013 case CTRL('u'):
7014 case 'u':
7015 nscroll /= 2;
7016 /* FALL THROUGH */
7017 case KEY_PPAGE:
7018 case CTRL('b'):
7019 case 'b':
7020 if (s->tree == s->root) {
7021 if (got_object_tree_get_first_entry(s->tree) ==
7022 s->first_displayed_entry)
7023 s->selected -= MIN(s->selected, nscroll);
7024 } else {
7025 if (s->first_displayed_entry == NULL)
7026 s->selected -= MIN(s->selected, nscroll);
7028 tree_scroll_up(s, MAX(0, nscroll));
7029 if (s->selected_entry == NULL ||
7030 (s->tree == s->root && s->selected_entry ==
7031 got_object_tree_get_first_entry(s->tree)))
7032 view->count = 0;
7033 break;
7034 case 'j':
7035 case KEY_DOWN:
7036 case CTRL('n'):
7037 if (s->selected < s->ndisplayed - 1) {
7038 s->selected++;
7039 break;
7041 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7042 == NULL) {
7043 /* can't scroll any further */
7044 view->count = 0;
7045 break;
7047 tree_scroll_down(view, 1);
7048 break;
7049 case CTRL('d'):
7050 case 'd':
7051 nscroll /= 2;
7052 /* FALL THROUGH */
7053 case KEY_NPAGE:
7054 case CTRL('f'):
7055 case 'f':
7056 case ' ':
7057 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7058 == NULL) {
7059 /* can't scroll any further; move cursor down */
7060 if (s->selected < s->ndisplayed - 1)
7061 s->selected += MIN(nscroll,
7062 s->ndisplayed - s->selected - 1);
7063 else
7064 view->count = 0;
7065 break;
7067 tree_scroll_down(view, nscroll);
7068 break;
7069 case KEY_ENTER:
7070 case '\r':
7071 case KEY_BACKSPACE:
7072 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7073 struct tog_parent_tree *parent;
7074 /* user selected '..' */
7075 if (s->tree == s->root) {
7076 view->count = 0;
7077 break;
7079 parent = TAILQ_FIRST(&s->parents);
7080 TAILQ_REMOVE(&s->parents, parent,
7081 entry);
7082 got_object_tree_close(s->tree);
7083 s->tree = parent->tree;
7084 s->first_displayed_entry =
7085 parent->first_displayed_entry;
7086 s->selected_entry =
7087 parent->selected_entry;
7088 s->selected = parent->selected;
7089 if (s->selected > view->nlines - 3) {
7090 err = offset_selection_down(view);
7091 if (err)
7092 break;
7094 free(parent);
7095 } else if (S_ISDIR(got_tree_entry_get_mode(
7096 s->selected_entry))) {
7097 struct got_tree_object *subtree;
7098 view->count = 0;
7099 err = got_object_open_as_tree(&subtree, s->repo,
7100 got_tree_entry_get_id(s->selected_entry));
7101 if (err)
7102 break;
7103 err = tree_view_visit_subtree(s, subtree);
7104 if (err) {
7105 got_object_tree_close(subtree);
7106 break;
7108 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7109 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7110 break;
7111 case KEY_RESIZE:
7112 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7113 s->selected = view->nlines - 4;
7114 view->count = 0;
7115 break;
7116 default:
7117 view->count = 0;
7118 break;
7121 return err;
7124 __dead static void
7125 usage_tree(void)
7127 endwin();
7128 fprintf(stderr,
7129 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7130 getprogname());
7131 exit(1);
7134 static const struct got_error *
7135 cmd_tree(int argc, char *argv[])
7137 const struct got_error *error;
7138 struct got_repository *repo = NULL;
7139 struct got_worktree *worktree = NULL;
7140 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7141 struct got_object_id *commit_id = NULL;
7142 struct got_commit_object *commit = NULL;
7143 const char *commit_id_arg = NULL;
7144 char *label = NULL;
7145 struct got_reference *ref = NULL;
7146 const char *head_ref_name = NULL;
7147 int ch;
7148 struct tog_view *view;
7149 int *pack_fds = NULL;
7151 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7152 switch (ch) {
7153 case 'c':
7154 commit_id_arg = optarg;
7155 break;
7156 case 'r':
7157 repo_path = realpath(optarg, NULL);
7158 if (repo_path == NULL)
7159 return got_error_from_errno2("realpath",
7160 optarg);
7161 break;
7162 default:
7163 usage_tree();
7164 /* NOTREACHED */
7168 argc -= optind;
7169 argv += optind;
7171 if (argc > 1)
7172 usage_tree();
7174 error = got_repo_pack_fds_open(&pack_fds);
7175 if (error != NULL)
7176 goto done;
7178 if (repo_path == NULL) {
7179 cwd = getcwd(NULL, 0);
7180 if (cwd == NULL)
7181 return got_error_from_errno("getcwd");
7182 error = got_worktree_open(&worktree, cwd);
7183 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7184 goto done;
7185 if (worktree)
7186 repo_path =
7187 strdup(got_worktree_get_repo_path(worktree));
7188 else
7189 repo_path = strdup(cwd);
7190 if (repo_path == NULL) {
7191 error = got_error_from_errno("strdup");
7192 goto done;
7196 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7197 if (error != NULL)
7198 goto done;
7200 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7201 repo, worktree);
7202 if (error)
7203 goto done;
7205 init_curses();
7207 error = apply_unveil(got_repo_get_path(repo), NULL);
7208 if (error)
7209 goto done;
7211 error = tog_load_refs(repo, 0);
7212 if (error)
7213 goto done;
7215 if (commit_id_arg == NULL) {
7216 error = got_repo_match_object_id(&commit_id, &label,
7217 worktree ? got_worktree_get_head_ref_name(worktree) :
7218 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7219 if (error)
7220 goto done;
7221 head_ref_name = label;
7222 } else {
7223 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7224 if (error == NULL)
7225 head_ref_name = got_ref_get_name(ref);
7226 else if (error->code != GOT_ERR_NOT_REF)
7227 goto done;
7228 error = got_repo_match_object_id(&commit_id, NULL,
7229 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7230 if (error)
7231 goto done;
7234 error = got_object_open_as_commit(&commit, repo, commit_id);
7235 if (error)
7236 goto done;
7238 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7239 if (view == NULL) {
7240 error = got_error_from_errno("view_open");
7241 goto done;
7243 error = open_tree_view(view, commit_id, head_ref_name, repo);
7244 if (error)
7245 goto done;
7246 if (!got_path_is_root_dir(in_repo_path)) {
7247 error = tree_view_walk_path(&view->state.tree, commit,
7248 in_repo_path);
7249 if (error)
7250 goto done;
7253 if (worktree) {
7254 /* Release work tree lock. */
7255 got_worktree_close(worktree);
7256 worktree = NULL;
7258 error = view_loop(view);
7259 done:
7260 free(repo_path);
7261 free(cwd);
7262 free(commit_id);
7263 free(label);
7264 if (ref)
7265 got_ref_close(ref);
7266 if (repo) {
7267 const struct got_error *close_err = got_repo_close(repo);
7268 if (error == NULL)
7269 error = close_err;
7271 if (pack_fds) {
7272 const struct got_error *pack_err =
7273 got_repo_pack_fds_close(pack_fds);
7274 if (error == NULL)
7275 error = pack_err;
7277 tog_free_refs();
7278 return error;
7281 static const struct got_error *
7282 ref_view_load_refs(struct tog_ref_view_state *s)
7284 struct got_reflist_entry *sre;
7285 struct tog_reflist_entry *re;
7287 s->nrefs = 0;
7288 TAILQ_FOREACH(sre, &tog_refs, entry) {
7289 if (strncmp(got_ref_get_name(sre->ref),
7290 "refs/got/", 9) == 0 &&
7291 strncmp(got_ref_get_name(sre->ref),
7292 "refs/got/backup/", 16) != 0)
7293 continue;
7295 re = malloc(sizeof(*re));
7296 if (re == NULL)
7297 return got_error_from_errno("malloc");
7299 re->ref = got_ref_dup(sre->ref);
7300 if (re->ref == NULL)
7301 return got_error_from_errno("got_ref_dup");
7302 re->idx = s->nrefs++;
7303 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7306 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7307 return NULL;
7310 static void
7311 ref_view_free_refs(struct tog_ref_view_state *s)
7313 struct tog_reflist_entry *re;
7315 while (!TAILQ_EMPTY(&s->refs)) {
7316 re = TAILQ_FIRST(&s->refs);
7317 TAILQ_REMOVE(&s->refs, re, entry);
7318 got_ref_close(re->ref);
7319 free(re);
7323 static const struct got_error *
7324 open_ref_view(struct tog_view *view, struct got_repository *repo)
7326 const struct got_error *err = NULL;
7327 struct tog_ref_view_state *s = &view->state.ref;
7329 s->selected_entry = 0;
7330 s->repo = repo;
7332 TAILQ_INIT(&s->refs);
7333 STAILQ_INIT(&s->colors);
7335 err = ref_view_load_refs(s);
7336 if (err)
7337 return err;
7339 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7340 err = add_color(&s->colors, "^refs/heads/",
7341 TOG_COLOR_REFS_HEADS,
7342 get_color_value("TOG_COLOR_REFS_HEADS"));
7343 if (err)
7344 goto done;
7346 err = add_color(&s->colors, "^refs/tags/",
7347 TOG_COLOR_REFS_TAGS,
7348 get_color_value("TOG_COLOR_REFS_TAGS"));
7349 if (err)
7350 goto done;
7352 err = add_color(&s->colors, "^refs/remotes/",
7353 TOG_COLOR_REFS_REMOTES,
7354 get_color_value("TOG_COLOR_REFS_REMOTES"));
7355 if (err)
7356 goto done;
7358 err = add_color(&s->colors, "^refs/got/backup/",
7359 TOG_COLOR_REFS_BACKUP,
7360 get_color_value("TOG_COLOR_REFS_BACKUP"));
7361 if (err)
7362 goto done;
7365 view->show = show_ref_view;
7366 view->input = input_ref_view;
7367 view->close = close_ref_view;
7368 view->search_start = search_start_ref_view;
7369 view->search_next = search_next_ref_view;
7370 done:
7371 if (err)
7372 free_colors(&s->colors);
7373 return err;
7376 static const struct got_error *
7377 close_ref_view(struct tog_view *view)
7379 struct tog_ref_view_state *s = &view->state.ref;
7381 ref_view_free_refs(s);
7382 free_colors(&s->colors);
7384 return NULL;
7387 static const struct got_error *
7388 resolve_reflist_entry(struct got_object_id **commit_id,
7389 struct tog_reflist_entry *re, struct got_repository *repo)
7391 const struct got_error *err = NULL;
7392 struct got_object_id *obj_id;
7393 struct got_tag_object *tag = NULL;
7394 int obj_type;
7396 *commit_id = NULL;
7398 err = got_ref_resolve(&obj_id, repo, re->ref);
7399 if (err)
7400 return err;
7402 err = got_object_get_type(&obj_type, repo, obj_id);
7403 if (err)
7404 goto done;
7406 switch (obj_type) {
7407 case GOT_OBJ_TYPE_COMMIT:
7408 *commit_id = obj_id;
7409 break;
7410 case GOT_OBJ_TYPE_TAG:
7411 err = got_object_open_as_tag(&tag, repo, obj_id);
7412 if (err)
7413 goto done;
7414 free(obj_id);
7415 err = got_object_get_type(&obj_type, repo,
7416 got_object_tag_get_object_id(tag));
7417 if (err)
7418 goto done;
7419 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7420 err = got_error(GOT_ERR_OBJ_TYPE);
7421 goto done;
7423 *commit_id = got_object_id_dup(
7424 got_object_tag_get_object_id(tag));
7425 if (*commit_id == NULL) {
7426 err = got_error_from_errno("got_object_id_dup");
7427 goto done;
7429 break;
7430 default:
7431 err = got_error(GOT_ERR_OBJ_TYPE);
7432 break;
7435 done:
7436 if (tag)
7437 got_object_tag_close(tag);
7438 if (err) {
7439 free(*commit_id);
7440 *commit_id = NULL;
7442 return err;
7445 static const struct got_error *
7446 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7447 struct tog_reflist_entry *re, struct got_repository *repo)
7449 struct tog_view *log_view;
7450 const struct got_error *err = NULL;
7451 struct got_object_id *commit_id = NULL;
7453 *new_view = NULL;
7455 err = resolve_reflist_entry(&commit_id, re, repo);
7456 if (err) {
7457 if (err->code != GOT_ERR_OBJ_TYPE)
7458 return err;
7459 else
7460 return NULL;
7463 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7464 if (log_view == NULL) {
7465 err = got_error_from_errno("view_open");
7466 goto done;
7469 err = open_log_view(log_view, commit_id, repo,
7470 got_ref_get_name(re->ref), "", 0);
7471 done:
7472 if (err)
7473 view_close(log_view);
7474 else
7475 *new_view = log_view;
7476 free(commit_id);
7477 return err;
7480 static void
7481 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7483 struct tog_reflist_entry *re;
7484 int i = 0;
7486 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7487 return;
7489 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7490 while (i++ < maxscroll) {
7491 if (re == NULL)
7492 break;
7493 s->first_displayed_entry = re;
7494 re = TAILQ_PREV(re, tog_reflist_head, entry);
7498 static const struct got_error *
7499 ref_scroll_down(struct tog_view *view, int maxscroll)
7501 struct tog_ref_view_state *s = &view->state.ref;
7502 struct tog_reflist_entry *next, *last;
7503 int n = 0;
7505 if (s->first_displayed_entry)
7506 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7507 else
7508 next = TAILQ_FIRST(&s->refs);
7510 last = s->last_displayed_entry;
7511 while (next && n++ < maxscroll) {
7512 if (last) {
7513 s->last_displayed_entry = last;
7514 last = TAILQ_NEXT(last, entry);
7516 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7517 s->first_displayed_entry = next;
7518 next = TAILQ_NEXT(next, entry);
7522 return NULL;
7525 static const struct got_error *
7526 search_start_ref_view(struct tog_view *view)
7528 struct tog_ref_view_state *s = &view->state.ref;
7530 s->matched_entry = NULL;
7531 return NULL;
7534 static int
7535 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
7537 regmatch_t regmatch;
7539 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
7540 0) == 0;
7543 static const struct got_error *
7544 search_next_ref_view(struct tog_view *view)
7546 struct tog_ref_view_state *s = &view->state.ref;
7547 struct tog_reflist_entry *re = NULL;
7549 if (!view->searching) {
7550 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7551 return NULL;
7554 if (s->matched_entry) {
7555 if (view->searching == TOG_SEARCH_FORWARD) {
7556 if (s->selected_entry)
7557 re = TAILQ_NEXT(s->selected_entry, entry);
7558 else
7559 re = TAILQ_PREV(s->selected_entry,
7560 tog_reflist_head, entry);
7561 } else {
7562 if (s->selected_entry == NULL)
7563 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7564 else
7565 re = TAILQ_PREV(s->selected_entry,
7566 tog_reflist_head, entry);
7568 } else {
7569 if (s->selected_entry)
7570 re = s->selected_entry;
7571 else if (view->searching == TOG_SEARCH_FORWARD)
7572 re = TAILQ_FIRST(&s->refs);
7573 else
7574 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7577 while (1) {
7578 if (re == NULL) {
7579 if (s->matched_entry == NULL) {
7580 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7581 return NULL;
7583 if (view->searching == TOG_SEARCH_FORWARD)
7584 re = TAILQ_FIRST(&s->refs);
7585 else
7586 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7589 if (match_reflist_entry(re, &view->regex)) {
7590 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7591 s->matched_entry = re;
7592 break;
7595 if (view->searching == TOG_SEARCH_FORWARD)
7596 re = TAILQ_NEXT(re, entry);
7597 else
7598 re = TAILQ_PREV(re, tog_reflist_head, entry);
7601 if (s->matched_entry) {
7602 s->first_displayed_entry = s->matched_entry;
7603 s->selected = 0;
7606 return NULL;
7609 static const struct got_error *
7610 show_ref_view(struct tog_view *view)
7612 const struct got_error *err = NULL;
7613 struct tog_ref_view_state *s = &view->state.ref;
7614 struct tog_reflist_entry *re;
7615 char *line = NULL;
7616 wchar_t *wline;
7617 struct tog_color *tc;
7618 int width, n;
7619 int limit = view->nlines;
7621 werase(view->window);
7623 s->ndisplayed = 0;
7624 if (view_is_hsplit_top(view))
7625 --limit; /* border */
7627 if (limit == 0)
7628 return NULL;
7630 re = s->first_displayed_entry;
7632 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
7633 s->nrefs) == -1)
7634 return got_error_from_errno("asprintf");
7636 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
7637 if (err) {
7638 free(line);
7639 return err;
7641 if (view_needs_focus_indication(view))
7642 wstandout(view->window);
7643 waddwstr(view->window, wline);
7644 if (view_needs_focus_indication(view))
7645 wstandend(view->window);
7646 free(wline);
7647 wline = NULL;
7648 free(line);
7649 line = NULL;
7650 if (width < view->ncols - 1)
7651 waddch(view->window, '\n');
7652 if (--limit <= 0)
7653 return NULL;
7655 n = 0;
7656 while (re && limit > 0) {
7657 char *line = NULL;
7658 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
7660 if (s->show_date) {
7661 struct got_commit_object *ci;
7662 struct got_tag_object *tag;
7663 struct got_object_id *id;
7664 struct tm tm;
7665 time_t t;
7667 err = got_ref_resolve(&id, s->repo, re->ref);
7668 if (err)
7669 return err;
7670 err = got_object_open_as_tag(&tag, s->repo, id);
7671 if (err) {
7672 if (err->code != GOT_ERR_OBJ_TYPE) {
7673 free(id);
7674 return err;
7676 err = got_object_open_as_commit(&ci, s->repo,
7677 id);
7678 if (err) {
7679 free(id);
7680 return err;
7682 t = got_object_commit_get_committer_time(ci);
7683 got_object_commit_close(ci);
7684 } else {
7685 t = got_object_tag_get_tagger_time(tag);
7686 got_object_tag_close(tag);
7688 free(id);
7689 if (gmtime_r(&t, &tm) == NULL)
7690 return got_error_from_errno("gmtime_r");
7691 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
7692 return got_error(GOT_ERR_NO_SPACE);
7694 if (got_ref_is_symbolic(re->ref)) {
7695 if (asprintf(&line, "%s%s -> %s", s->show_date ?
7696 ymd : "", got_ref_get_name(re->ref),
7697 got_ref_get_symref_target(re->ref)) == -1)
7698 return got_error_from_errno("asprintf");
7699 } else if (s->show_ids) {
7700 struct got_object_id *id;
7701 char *id_str;
7702 err = got_ref_resolve(&id, s->repo, re->ref);
7703 if (err)
7704 return err;
7705 err = got_object_id_str(&id_str, id);
7706 if (err) {
7707 free(id);
7708 return err;
7710 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
7711 got_ref_get_name(re->ref), id_str) == -1) {
7712 err = got_error_from_errno("asprintf");
7713 free(id);
7714 free(id_str);
7715 return err;
7717 free(id);
7718 free(id_str);
7719 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
7720 got_ref_get_name(re->ref)) == -1)
7721 return got_error_from_errno("asprintf");
7723 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
7724 0, 0);
7725 if (err) {
7726 free(line);
7727 return err;
7729 if (n == s->selected) {
7730 if (view->focussed)
7731 wstandout(view->window);
7732 s->selected_entry = re;
7734 tc = match_color(&s->colors, got_ref_get_name(re->ref));
7735 if (tc)
7736 wattr_on(view->window,
7737 COLOR_PAIR(tc->colorpair), NULL);
7738 waddwstr(view->window, wline);
7739 if (tc)
7740 wattr_off(view->window,
7741 COLOR_PAIR(tc->colorpair), NULL);
7742 if (width < view->ncols - 1)
7743 waddch(view->window, '\n');
7744 if (n == s->selected && view->focussed)
7745 wstandend(view->window);
7746 free(line);
7747 free(wline);
7748 wline = NULL;
7749 n++;
7750 s->ndisplayed++;
7751 s->last_displayed_entry = re;
7753 limit--;
7754 re = TAILQ_NEXT(re, entry);
7757 view_border(view);
7758 return err;
7761 static const struct got_error *
7762 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
7763 struct tog_reflist_entry *re, struct got_repository *repo)
7765 const struct got_error *err = NULL;
7766 struct got_object_id *commit_id = NULL;
7767 struct tog_view *tree_view;
7769 *new_view = NULL;
7771 err = resolve_reflist_entry(&commit_id, re, repo);
7772 if (err) {
7773 if (err->code != GOT_ERR_OBJ_TYPE)
7774 return err;
7775 else
7776 return NULL;
7780 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
7781 if (tree_view == NULL) {
7782 err = got_error_from_errno("view_open");
7783 goto done;
7786 err = open_tree_view(tree_view, commit_id,
7787 got_ref_get_name(re->ref), repo);
7788 if (err)
7789 goto done;
7791 *new_view = tree_view;
7792 done:
7793 free(commit_id);
7794 return err;
7797 static const struct got_error *
7798 ref_goto_line(struct tog_view *view, int nlines)
7800 const struct got_error *err = NULL;
7801 struct tog_ref_view_state *s = &view->state.ref;
7802 int g, idx = s->selected_entry->idx;
7804 g = view->gline;
7805 view->gline = 0;
7807 if (g == 0)
7808 g = 1;
7809 else if (g > s->nrefs)
7810 g = s->nrefs;
7812 if (g >= s->first_displayed_entry->idx + 1 &&
7813 g <= s->last_displayed_entry->idx + 1 &&
7814 g - s->first_displayed_entry->idx - 1 < nlines) {
7815 s->selected = g - s->first_displayed_entry->idx - 1;
7816 return NULL;
7819 if (idx + 1 < g) {
7820 err = ref_scroll_down(view, g - idx - 1);
7821 if (err)
7822 return err;
7823 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
7824 s->first_displayed_entry->idx + s->selected < g &&
7825 s->selected < s->ndisplayed - 1)
7826 s->selected = g - s->first_displayed_entry->idx - 1;
7827 } else if (idx + 1 > g)
7828 ref_scroll_up(s, idx - g + 1);
7830 if (g < nlines && s->first_displayed_entry->idx == 0)
7831 s->selected = g - 1;
7833 return NULL;
7837 static const struct got_error *
7838 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
7840 const struct got_error *err = NULL;
7841 struct tog_ref_view_state *s = &view->state.ref;
7842 struct tog_reflist_entry *re;
7843 int n, nscroll = view->nlines - 1;
7845 if (view->gline)
7846 return ref_goto_line(view, nscroll);
7848 switch (ch) {
7849 case 'i':
7850 s->show_ids = !s->show_ids;
7851 view->count = 0;
7852 break;
7853 case 'm':
7854 s->show_date = !s->show_date;
7855 view->count = 0;
7856 break;
7857 case 'o':
7858 s->sort_by_date = !s->sort_by_date;
7859 view->count = 0;
7860 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
7861 got_ref_cmp_by_commit_timestamp_descending :
7862 tog_ref_cmp_by_name, s->repo);
7863 if (err)
7864 break;
7865 got_reflist_object_id_map_free(tog_refs_idmap);
7866 err = got_reflist_object_id_map_create(&tog_refs_idmap,
7867 &tog_refs, s->repo);
7868 if (err)
7869 break;
7870 ref_view_free_refs(s);
7871 err = ref_view_load_refs(s);
7872 break;
7873 case KEY_ENTER:
7874 case '\r':
7875 view->count = 0;
7876 if (!s->selected_entry)
7877 break;
7878 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7879 break;
7880 case 'T':
7881 view->count = 0;
7882 if (!s->selected_entry)
7883 break;
7884 err = view_request_new(new_view, view, TOG_VIEW_TREE);
7885 break;
7886 case 'g':
7887 case KEY_HOME:
7888 s->selected = 0;
7889 view->count = 0;
7890 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7891 break;
7892 case 'G':
7893 case KEY_END: {
7894 int eos = view->nlines - 1;
7896 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7897 --eos; /* border */
7898 s->selected = 0;
7899 view->count = 0;
7900 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7901 for (n = 0; n < eos; n++) {
7902 if (re == NULL)
7903 break;
7904 s->first_displayed_entry = re;
7905 re = TAILQ_PREV(re, tog_reflist_head, entry);
7907 if (n > 0)
7908 s->selected = n - 1;
7909 break;
7911 case 'k':
7912 case KEY_UP:
7913 case CTRL('p'):
7914 if (s->selected > 0) {
7915 s->selected--;
7916 break;
7918 ref_scroll_up(s, 1);
7919 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7920 view->count = 0;
7921 break;
7922 case CTRL('u'):
7923 case 'u':
7924 nscroll /= 2;
7925 /* FALL THROUGH */
7926 case KEY_PPAGE:
7927 case CTRL('b'):
7928 case 'b':
7929 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7930 s->selected -= MIN(nscroll, s->selected);
7931 ref_scroll_up(s, MAX(0, nscroll));
7932 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7933 view->count = 0;
7934 break;
7935 case 'j':
7936 case KEY_DOWN:
7937 case CTRL('n'):
7938 if (s->selected < s->ndisplayed - 1) {
7939 s->selected++;
7940 break;
7942 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7943 /* can't scroll any further */
7944 view->count = 0;
7945 break;
7947 ref_scroll_down(view, 1);
7948 break;
7949 case CTRL('d'):
7950 case 'd':
7951 nscroll /= 2;
7952 /* FALL THROUGH */
7953 case KEY_NPAGE:
7954 case CTRL('f'):
7955 case 'f':
7956 case ' ':
7957 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7958 /* can't scroll any further; move cursor down */
7959 if (s->selected < s->ndisplayed - 1)
7960 s->selected += MIN(nscroll,
7961 s->ndisplayed - s->selected - 1);
7962 if (view->count > 1 && s->selected < s->ndisplayed - 1)
7963 s->selected += s->ndisplayed - s->selected - 1;
7964 view->count = 0;
7965 break;
7967 ref_scroll_down(view, nscroll);
7968 break;
7969 case CTRL('l'):
7970 view->count = 0;
7971 tog_free_refs();
7972 err = tog_load_refs(s->repo, s->sort_by_date);
7973 if (err)
7974 break;
7975 ref_view_free_refs(s);
7976 err = ref_view_load_refs(s);
7977 break;
7978 case KEY_RESIZE:
7979 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
7980 s->selected = view->nlines - 2;
7981 break;
7982 default:
7983 view->count = 0;
7984 break;
7987 return err;
7990 __dead static void
7991 usage_ref(void)
7993 endwin();
7994 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
7995 getprogname());
7996 exit(1);
7999 static const struct got_error *
8000 cmd_ref(int argc, char *argv[])
8002 const struct got_error *error;
8003 struct got_repository *repo = NULL;
8004 struct got_worktree *worktree = NULL;
8005 char *cwd = NULL, *repo_path = NULL;
8006 int ch;
8007 struct tog_view *view;
8008 int *pack_fds = NULL;
8010 while ((ch = getopt(argc, argv, "r:")) != -1) {
8011 switch (ch) {
8012 case 'r':
8013 repo_path = realpath(optarg, NULL);
8014 if (repo_path == NULL)
8015 return got_error_from_errno2("realpath",
8016 optarg);
8017 break;
8018 default:
8019 usage_ref();
8020 /* NOTREACHED */
8024 argc -= optind;
8025 argv += optind;
8027 if (argc > 1)
8028 usage_ref();
8030 error = got_repo_pack_fds_open(&pack_fds);
8031 if (error != NULL)
8032 goto done;
8034 if (repo_path == NULL) {
8035 cwd = getcwd(NULL, 0);
8036 if (cwd == NULL)
8037 return got_error_from_errno("getcwd");
8038 error = got_worktree_open(&worktree, cwd);
8039 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8040 goto done;
8041 if (worktree)
8042 repo_path =
8043 strdup(got_worktree_get_repo_path(worktree));
8044 else
8045 repo_path = strdup(cwd);
8046 if (repo_path == NULL) {
8047 error = got_error_from_errno("strdup");
8048 goto done;
8052 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8053 if (error != NULL)
8054 goto done;
8056 init_curses();
8058 error = apply_unveil(got_repo_get_path(repo), NULL);
8059 if (error)
8060 goto done;
8062 error = tog_load_refs(repo, 0);
8063 if (error)
8064 goto done;
8066 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8067 if (view == NULL) {
8068 error = got_error_from_errno("view_open");
8069 goto done;
8072 error = open_ref_view(view, repo);
8073 if (error)
8074 goto done;
8076 if (worktree) {
8077 /* Release work tree lock. */
8078 got_worktree_close(worktree);
8079 worktree = NULL;
8081 error = view_loop(view);
8082 done:
8083 free(repo_path);
8084 free(cwd);
8085 if (repo) {
8086 const struct got_error *close_err = got_repo_close(repo);
8087 if (close_err)
8088 error = close_err;
8090 if (pack_fds) {
8091 const struct got_error *pack_err =
8092 got_repo_pack_fds_close(pack_fds);
8093 if (error == NULL)
8094 error = pack_err;
8096 tog_free_refs();
8097 return error;
8100 static const struct got_error *
8101 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
8102 enum tog_view_type request, int y, int x)
8104 const struct got_error *err = NULL;
8106 *new_view = NULL;
8108 switch (request) {
8109 case TOG_VIEW_DIFF:
8110 if (view->type == TOG_VIEW_LOG) {
8111 struct tog_log_view_state *s = &view->state.log;
8113 err = open_diff_view_for_commit(new_view, y, x,
8114 s->selected_entry->commit, s->selected_entry->id,
8115 view, s->repo);
8116 } else
8117 return got_error_msg(GOT_ERR_NOT_IMPL,
8118 "parent/child view pair not supported");
8119 break;
8120 case TOG_VIEW_BLAME:
8121 if (view->type == TOG_VIEW_TREE) {
8122 struct tog_tree_view_state *s = &view->state.tree;
8124 err = blame_tree_entry(new_view, y, x,
8125 s->selected_entry, &s->parents, s->commit_id,
8126 s->repo);
8127 } else
8128 return got_error_msg(GOT_ERR_NOT_IMPL,
8129 "parent/child view pair not supported");
8130 break;
8131 case TOG_VIEW_LOG:
8132 if (view->type == TOG_VIEW_BLAME)
8133 err = log_annotated_line(new_view, y, x,
8134 view->state.blame.repo, view->state.blame.id_to_log);
8135 else if (view->type == TOG_VIEW_TREE)
8136 err = log_selected_tree_entry(new_view, y, x,
8137 &view->state.tree);
8138 else if (view->type == TOG_VIEW_REF)
8139 err = log_ref_entry(new_view, y, x,
8140 view->state.ref.selected_entry,
8141 view->state.ref.repo);
8142 else
8143 return got_error_msg(GOT_ERR_NOT_IMPL,
8144 "parent/child view pair not supported");
8145 break;
8146 case TOG_VIEW_TREE:
8147 if (view->type == TOG_VIEW_LOG)
8148 err = browse_commit_tree(new_view, y, x,
8149 view->state.log.selected_entry,
8150 view->state.log.in_repo_path,
8151 view->state.log.head_ref_name,
8152 view->state.log.repo);
8153 else if (view->type == TOG_VIEW_REF)
8154 err = browse_ref_tree(new_view, y, x,
8155 view->state.ref.selected_entry,
8156 view->state.ref.repo);
8157 else
8158 return got_error_msg(GOT_ERR_NOT_IMPL,
8159 "parent/child view pair not supported");
8160 break;
8161 case TOG_VIEW_REF:
8162 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
8163 if (*new_view == NULL)
8164 return got_error_from_errno("view_open");
8165 if (view->type == TOG_VIEW_LOG)
8166 err = open_ref_view(*new_view, view->state.log.repo);
8167 else if (view->type == TOG_VIEW_TREE)
8168 err = open_ref_view(*new_view, view->state.tree.repo);
8169 else
8170 err = got_error_msg(GOT_ERR_NOT_IMPL,
8171 "parent/child view pair not supported");
8172 if (err)
8173 view_close(*new_view);
8174 break;
8175 default:
8176 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
8179 return err;
8183 * If view was scrolled down to move the selected line into view when opening a
8184 * horizontal split, scroll back up when closing the split/toggling fullscreen.
8186 static void
8187 offset_selection_up(struct tog_view *view)
8189 switch (view->type) {
8190 case TOG_VIEW_BLAME: {
8191 struct tog_blame_view_state *s = &view->state.blame;
8192 if (s->first_displayed_line == 1) {
8193 s->selected_line = MAX(s->selected_line - view->offset,
8194 1);
8195 break;
8197 if (s->first_displayed_line > view->offset)
8198 s->first_displayed_line -= view->offset;
8199 else
8200 s->first_displayed_line = 1;
8201 s->selected_line += view->offset;
8202 break;
8204 case TOG_VIEW_LOG:
8205 log_scroll_up(&view->state.log, view->offset);
8206 view->state.log.selected += view->offset;
8207 break;
8208 case TOG_VIEW_REF:
8209 ref_scroll_up(&view->state.ref, view->offset);
8210 view->state.ref.selected += view->offset;
8211 break;
8212 case TOG_VIEW_TREE:
8213 tree_scroll_up(&view->state.tree, view->offset);
8214 view->state.tree.selected += view->offset;
8215 break;
8216 default:
8217 break;
8220 view->offset = 0;
8224 * If the selected line is in the section of screen covered by the bottom split,
8225 * scroll down offset lines to move it into view and index its new position.
8227 static const struct got_error *
8228 offset_selection_down(struct tog_view *view)
8230 const struct got_error *err = NULL;
8231 const struct got_error *(*scrolld)(struct tog_view *, int);
8232 int *selected = NULL;
8233 int header, offset;
8235 switch (view->type) {
8236 case TOG_VIEW_BLAME: {
8237 struct tog_blame_view_state *s = &view->state.blame;
8238 header = 3;
8239 scrolld = NULL;
8240 if (s->selected_line > view->nlines - header) {
8241 offset = abs(view->nlines - s->selected_line - header);
8242 s->first_displayed_line += offset;
8243 s->selected_line -= offset;
8244 view->offset = offset;
8246 break;
8248 case TOG_VIEW_LOG: {
8249 struct tog_log_view_state *s = &view->state.log;
8250 scrolld = &log_scroll_down;
8251 header = view_is_parent_view(view) ? 3 : 2;
8252 selected = &s->selected;
8253 break;
8255 case TOG_VIEW_REF: {
8256 struct tog_ref_view_state *s = &view->state.ref;
8257 scrolld = &ref_scroll_down;
8258 header = 3;
8259 selected = &s->selected;
8260 break;
8262 case TOG_VIEW_TREE: {
8263 struct tog_tree_view_state *s = &view->state.tree;
8264 scrolld = &tree_scroll_down;
8265 header = 5;
8266 selected = &s->selected;
8267 break;
8269 default:
8270 selected = NULL;
8271 scrolld = NULL;
8272 header = 0;
8273 break;
8276 if (selected && *selected > view->nlines - header) {
8277 offset = abs(view->nlines - *selected - header);
8278 view->offset = offset;
8279 if (scrolld && offset) {
8280 err = scrolld(view, offset);
8281 *selected -= offset;
8285 return err;
8288 static void
8289 list_commands(FILE *fp)
8291 size_t i;
8293 fprintf(fp, "commands:");
8294 for (i = 0; i < nitems(tog_commands); i++) {
8295 const struct tog_cmd *cmd = &tog_commands[i];
8296 fprintf(fp, " %s", cmd->name);
8298 fputc('\n', fp);
8301 __dead static void
8302 usage(int hflag, int status)
8304 FILE *fp = (status == 0) ? stdout : stderr;
8306 fprintf(fp, "usage: %s [-h] [-V | --version] [command] [arg ...]\n",
8307 getprogname());
8308 if (hflag) {
8309 fprintf(fp, "lazy usage: %s path\n", getprogname());
8310 list_commands(fp);
8312 exit(status);
8315 static char **
8316 make_argv(int argc, ...)
8318 va_list ap;
8319 char **argv;
8320 int i;
8322 va_start(ap, argc);
8324 argv = calloc(argc, sizeof(char *));
8325 if (argv == NULL)
8326 err(1, "calloc");
8327 for (i = 0; i < argc; i++) {
8328 argv[i] = strdup(va_arg(ap, char *));
8329 if (argv[i] == NULL)
8330 err(1, "strdup");
8333 va_end(ap);
8334 return argv;
8338 * Try to convert 'tog path' into a 'tog log path' command.
8339 * The user could simply have mistyped the command rather than knowingly
8340 * provided a path. So check whether argv[0] can in fact be resolved
8341 * to a path in the HEAD commit and print a special error if not.
8342 * This hack is for mpi@ <3
8344 static const struct got_error *
8345 tog_log_with_path(int argc, char *argv[])
8347 const struct got_error *error = NULL, *close_err;
8348 const struct tog_cmd *cmd = NULL;
8349 struct got_repository *repo = NULL;
8350 struct got_worktree *worktree = NULL;
8351 struct got_object_id *commit_id = NULL, *id = NULL;
8352 struct got_commit_object *commit = NULL;
8353 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8354 char *commit_id_str = NULL, **cmd_argv = NULL;
8355 int *pack_fds = NULL;
8357 cwd = getcwd(NULL, 0);
8358 if (cwd == NULL)
8359 return got_error_from_errno("getcwd");
8361 error = got_repo_pack_fds_open(&pack_fds);
8362 if (error != NULL)
8363 goto done;
8365 error = got_worktree_open(&worktree, cwd);
8366 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8367 goto done;
8369 if (worktree)
8370 repo_path = strdup(got_worktree_get_repo_path(worktree));
8371 else
8372 repo_path = strdup(cwd);
8373 if (repo_path == NULL) {
8374 error = got_error_from_errno("strdup");
8375 goto done;
8378 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8379 if (error != NULL)
8380 goto done;
8382 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8383 repo, worktree);
8384 if (error)
8385 goto done;
8387 error = tog_load_refs(repo, 0);
8388 if (error)
8389 goto done;
8390 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
8391 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
8392 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8393 if (error)
8394 goto done;
8396 if (worktree) {
8397 got_worktree_close(worktree);
8398 worktree = NULL;
8401 error = got_object_open_as_commit(&commit, repo, commit_id);
8402 if (error)
8403 goto done;
8405 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
8406 if (error) {
8407 if (error->code != GOT_ERR_NO_TREE_ENTRY)
8408 goto done;
8409 fprintf(stderr, "%s: '%s' is no known command or path\n",
8410 getprogname(), argv[0]);
8411 usage(1, 1);
8412 /* not reached */
8415 error = got_object_id_str(&commit_id_str, commit_id);
8416 if (error)
8417 goto done;
8419 cmd = &tog_commands[0]; /* log */
8420 argc = 4;
8421 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
8422 error = cmd->cmd_main(argc, cmd_argv);
8423 done:
8424 if (repo) {
8425 close_err = got_repo_close(repo);
8426 if (error == NULL)
8427 error = close_err;
8429 if (commit)
8430 got_object_commit_close(commit);
8431 if (worktree)
8432 got_worktree_close(worktree);
8433 if (pack_fds) {
8434 const struct got_error *pack_err =
8435 got_repo_pack_fds_close(pack_fds);
8436 if (error == NULL)
8437 error = pack_err;
8439 free(id);
8440 free(commit_id_str);
8441 free(commit_id);
8442 free(cwd);
8443 free(repo_path);
8444 free(in_repo_path);
8445 if (cmd_argv) {
8446 int i;
8447 for (i = 0; i < argc; i++)
8448 free(cmd_argv[i]);
8449 free(cmd_argv);
8451 tog_free_refs();
8452 return error;
8455 int
8456 main(int argc, char *argv[])
8458 const struct got_error *error = NULL;
8459 const struct tog_cmd *cmd = NULL;
8460 int ch, hflag = 0, Vflag = 0;
8461 char **cmd_argv = NULL;
8462 static const struct option longopts[] = {
8463 { "version", no_argument, NULL, 'V' },
8464 { NULL, 0, NULL, 0}
8466 char *diff_algo_str = NULL;
8468 setlocale(LC_CTYPE, "");
8470 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
8471 switch (ch) {
8472 case 'h':
8473 hflag = 1;
8474 break;
8475 case 'V':
8476 Vflag = 1;
8477 break;
8478 default:
8479 usage(hflag, 1);
8480 /* NOTREACHED */
8484 argc -= optind;
8485 argv += optind;
8486 optind = 1;
8487 optreset = 1;
8489 if (Vflag) {
8490 got_version_print_str();
8491 return 0;
8494 #ifndef PROFILE
8495 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
8496 NULL) == -1)
8497 err(1, "pledge");
8498 #endif
8500 if (argc == 0) {
8501 if (hflag)
8502 usage(hflag, 0);
8503 /* Build an argument vector which runs a default command. */
8504 cmd = &tog_commands[0];
8505 argc = 1;
8506 cmd_argv = make_argv(argc, cmd->name);
8507 } else {
8508 size_t i;
8510 /* Did the user specify a command? */
8511 for (i = 0; i < nitems(tog_commands); i++) {
8512 if (strncmp(tog_commands[i].name, argv[0],
8513 strlen(argv[0])) == 0) {
8514 cmd = &tog_commands[i];
8515 break;
8520 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
8521 if (diff_algo_str) {
8522 if (strcasecmp(diff_algo_str, "patience") == 0)
8523 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
8524 if (strcasecmp(diff_algo_str, "myers") == 0)
8525 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
8528 if (cmd == NULL) {
8529 if (argc != 1)
8530 usage(0, 1);
8531 /* No command specified; try log with a path */
8532 error = tog_log_with_path(argc, argv);
8533 } else {
8534 if (hflag)
8535 cmd->cmd_usage();
8536 else
8537 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
8540 endwin();
8541 putchar('\n');
8542 if (cmd_argv) {
8543 int i;
8544 for (i = 0; i < argc; i++)
8545 free(cmd_argv[i]);
8546 free(cmd_argv);
8549 if (error && error->code != GOT_ERR_CANCELLED)
8550 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8551 return 0;