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;
2095 struct got_object_id *dup;
2097 entry = calloc(1, sizeof(*entry));
2098 if (entry == NULL)
2099 return NULL;
2101 dup = got_object_id_dup(id);
2102 if (dup == NULL) {
2103 free(entry);
2104 return NULL;
2107 entry->id = dup;
2108 entry->commit = commit;
2109 return entry;
2112 static void
2113 pop_commit(struct commit_queue *commits)
2115 struct commit_queue_entry *entry;
2117 entry = TAILQ_FIRST(&commits->head);
2118 TAILQ_REMOVE(&commits->head, entry, entry);
2119 got_object_commit_close(entry->commit);
2120 commits->ncommits--;
2121 free(entry->id);
2122 free(entry);
2125 static void
2126 free_commits(struct commit_queue *commits)
2128 while (!TAILQ_EMPTY(&commits->head))
2129 pop_commit(commits);
2132 static const struct got_error *
2133 match_commit(int *have_match, struct got_object_id *id,
2134 struct got_commit_object *commit, regex_t *regex)
2136 const struct got_error *err = NULL;
2137 regmatch_t regmatch;
2138 char *id_str = NULL, *logmsg = NULL;
2140 *have_match = 0;
2142 err = got_object_id_str(&id_str, id);
2143 if (err)
2144 return err;
2146 err = got_object_commit_get_logmsg(&logmsg, commit);
2147 if (err)
2148 goto done;
2150 if (regexec(regex, got_object_commit_get_author(commit), 1,
2151 &regmatch, 0) == 0 ||
2152 regexec(regex, got_object_commit_get_committer(commit), 1,
2153 &regmatch, 0) == 0 ||
2154 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2155 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2156 *have_match = 1;
2157 done:
2158 free(id_str);
2159 free(logmsg);
2160 return err;
2163 static const struct got_error *
2164 queue_commits(struct tog_log_thread_args *a)
2166 const struct got_error *err = NULL;
2169 * We keep all commits open throughout the lifetime of the log
2170 * view in order to avoid having to re-fetch commits from disk
2171 * while updating the display.
2173 do {
2174 struct got_object_id *id;
2175 struct got_commit_object *commit;
2176 struct commit_queue_entry *entry;
2177 int errcode;
2179 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2180 NULL, NULL);
2181 if (err || id == NULL)
2182 break;
2184 err = got_object_open_as_commit(&commit, a->repo, id);
2185 if (err)
2186 break;
2187 entry = alloc_commit_queue_entry(commit, id);
2188 if (entry == NULL) {
2189 err = got_error_from_errno("alloc_commit_queue_entry");
2190 break;
2193 errcode = pthread_mutex_lock(&tog_mutex);
2194 if (errcode) {
2195 err = got_error_set_errno(errcode,
2196 "pthread_mutex_lock");
2197 break;
2200 entry->idx = a->commits->ncommits;
2201 TAILQ_INSERT_TAIL(&a->commits->head, entry, entry);
2202 a->commits->ncommits++;
2204 if (*a->searching == TOG_SEARCH_FORWARD &&
2205 !*a->search_next_done) {
2206 int have_match;
2207 err = match_commit(&have_match, id, commit, a->regex);
2208 if (err)
2209 break;
2210 if (have_match)
2211 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2214 errcode = pthread_mutex_unlock(&tog_mutex);
2215 if (errcode && err == NULL)
2216 err = got_error_set_errno(errcode,
2217 "pthread_mutex_unlock");
2218 if (err)
2219 break;
2220 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2222 return err;
2225 static void
2226 select_commit(struct tog_log_view_state *s)
2228 struct commit_queue_entry *entry;
2229 int ncommits = 0;
2231 entry = s->first_displayed_entry;
2232 while (entry) {
2233 if (ncommits == s->selected) {
2234 s->selected_entry = entry;
2235 break;
2237 entry = TAILQ_NEXT(entry, entry);
2238 ncommits++;
2242 static const struct got_error *
2243 draw_commits(struct tog_view *view)
2245 const struct got_error *err = NULL;
2246 struct tog_log_view_state *s = &view->state.log;
2247 struct commit_queue_entry *entry = s->selected_entry;
2248 int limit = view->nlines;
2249 int width;
2250 int ncommits, author_cols = 4;
2251 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2252 char *refs_str = NULL;
2253 wchar_t *wline;
2254 struct tog_color *tc;
2255 static const size_t date_display_cols = 12;
2257 if (view_is_hsplit_top(view))
2258 --limit; /* account for border */
2260 if (s->selected_entry &&
2261 !(view->searching && view->search_next_done == 0)) {
2262 struct got_reflist_head *refs;
2263 err = got_object_id_str(&id_str, s->selected_entry->id);
2264 if (err)
2265 return err;
2266 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2267 s->selected_entry->id);
2268 if (refs) {
2269 err = build_refs_str(&refs_str, refs,
2270 s->selected_entry->id, s->repo);
2271 if (err)
2272 goto done;
2276 if (s->thread_args.commits_needed == 0)
2277 halfdelay(10); /* disable fast refresh */
2279 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2280 if (asprintf(&ncommits_str, " [%d/%d] %s",
2281 entry ? entry->idx + 1 : 0, s->commits.ncommits,
2282 (view->searching && !view->search_next_done) ?
2283 "searching..." : "loading...") == -1) {
2284 err = got_error_from_errno("asprintf");
2285 goto done;
2287 } else {
2288 const char *search_str = NULL;
2290 if (view->searching) {
2291 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2292 search_str = "no more matches";
2293 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2294 search_str = "no matches found";
2295 else if (!view->search_next_done)
2296 search_str = "searching...";
2299 if (asprintf(&ncommits_str, " [%d/%d] %s",
2300 entry ? entry->idx + 1 : 0, s->commits.ncommits,
2301 search_str ? search_str :
2302 (refs_str ? refs_str : "")) == -1) {
2303 err = got_error_from_errno("asprintf");
2304 goto done;
2308 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2309 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2310 "........................................",
2311 s->in_repo_path, ncommits_str) == -1) {
2312 err = got_error_from_errno("asprintf");
2313 header = NULL;
2314 goto done;
2316 } else if (asprintf(&header, "commit %s%s",
2317 id_str ? id_str : "........................................",
2318 ncommits_str) == -1) {
2319 err = got_error_from_errno("asprintf");
2320 header = NULL;
2321 goto done;
2323 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2324 if (err)
2325 goto done;
2327 werase(view->window);
2329 if (view_needs_focus_indication(view))
2330 wstandout(view->window);
2331 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2332 if (tc)
2333 wattr_on(view->window,
2334 COLOR_PAIR(tc->colorpair), NULL);
2335 waddwstr(view->window, wline);
2336 if (tc)
2337 wattr_off(view->window,
2338 COLOR_PAIR(tc->colorpair), NULL);
2339 while (width < view->ncols) {
2340 waddch(view->window, ' ');
2341 width++;
2343 if (view_needs_focus_indication(view))
2344 wstandend(view->window);
2345 free(wline);
2346 if (limit <= 1)
2347 goto done;
2349 /* Grow author column size if necessary, and set view->maxx. */
2350 entry = s->first_displayed_entry;
2351 ncommits = 0;
2352 view->maxx = 0;
2353 while (entry) {
2354 struct got_commit_object *c = entry->commit;
2355 char *author, *eol, *msg, *msg0;
2356 wchar_t *wauthor, *wmsg;
2357 int width;
2358 if (ncommits >= limit - 1)
2359 break;
2360 if (s->use_committer)
2361 author = strdup(got_object_commit_get_committer(c));
2362 else
2363 author = strdup(got_object_commit_get_author(c));
2364 if (author == NULL) {
2365 err = got_error_from_errno("strdup");
2366 goto done;
2368 err = format_author(&wauthor, &width, author, COLS,
2369 date_display_cols);
2370 if (author_cols < width)
2371 author_cols = width;
2372 free(wauthor);
2373 free(author);
2374 if (err)
2375 goto done;
2376 err = got_object_commit_get_logmsg(&msg0, c);
2377 if (err)
2378 goto done;
2379 msg = msg0;
2380 while (*msg == '\n')
2381 ++msg;
2382 if ((eol = strchr(msg, '\n')))
2383 *eol = '\0';
2384 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2385 date_display_cols + author_cols, 0);
2386 if (err)
2387 goto done;
2388 view->maxx = MAX(view->maxx, width);
2389 free(msg0);
2390 free(wmsg);
2391 ncommits++;
2392 entry = TAILQ_NEXT(entry, entry);
2395 entry = s->first_displayed_entry;
2396 s->last_displayed_entry = s->first_displayed_entry;
2397 ncommits = 0;
2398 while (entry) {
2399 if (ncommits >= limit - 1)
2400 break;
2401 if (ncommits == s->selected)
2402 wstandout(view->window);
2403 err = draw_commit(view, entry->commit, entry->id,
2404 date_display_cols, author_cols);
2405 if (ncommits == s->selected)
2406 wstandend(view->window);
2407 if (err)
2408 goto done;
2409 ncommits++;
2410 s->last_displayed_entry = entry;
2411 entry = TAILQ_NEXT(entry, entry);
2414 view_border(view);
2415 done:
2416 free(id_str);
2417 free(refs_str);
2418 free(ncommits_str);
2419 free(header);
2420 return err;
2423 static void
2424 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2426 struct commit_queue_entry *entry;
2427 int nscrolled = 0;
2429 entry = TAILQ_FIRST(&s->commits.head);
2430 if (s->first_displayed_entry == entry)
2431 return;
2433 entry = s->first_displayed_entry;
2434 while (entry && nscrolled < maxscroll) {
2435 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2436 if (entry) {
2437 s->first_displayed_entry = entry;
2438 nscrolled++;
2443 static const struct got_error *
2444 trigger_log_thread(struct tog_view *view, int wait)
2446 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2447 int errcode;
2449 halfdelay(1); /* fast refresh while loading commits */
2451 while (!ta->log_complete && !tog_thread_error &&
2452 (ta->commits_needed > 0 || ta->load_all)) {
2453 /* Wake the log thread. */
2454 errcode = pthread_cond_signal(&ta->need_commits);
2455 if (errcode)
2456 return got_error_set_errno(errcode,
2457 "pthread_cond_signal");
2460 * The mutex will be released while the view loop waits
2461 * in wgetch(), at which time the log thread will run.
2463 if (!wait)
2464 break;
2466 /* Display progress update in log view. */
2467 show_log_view(view);
2468 update_panels();
2469 doupdate();
2471 /* Wait right here while next commit is being loaded. */
2472 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2473 if (errcode)
2474 return got_error_set_errno(errcode,
2475 "pthread_cond_wait");
2477 /* Display progress update in log view. */
2478 show_log_view(view);
2479 update_panels();
2480 doupdate();
2483 return NULL;
2486 static const struct got_error *
2487 request_log_commits(struct tog_view *view)
2489 struct tog_log_view_state *state = &view->state.log;
2490 const struct got_error *err = NULL;
2492 if (state->thread_args.log_complete)
2493 return NULL;
2495 state->thread_args.commits_needed += view->nscrolled;
2496 err = trigger_log_thread(view, 1);
2497 view->nscrolled = 0;
2499 return err;
2502 static const struct got_error *
2503 log_scroll_down(struct tog_view *view, int maxscroll)
2505 struct tog_log_view_state *s = &view->state.log;
2506 const struct got_error *err = NULL;
2507 struct commit_queue_entry *pentry;
2508 int nscrolled = 0, ncommits_needed;
2510 if (s->last_displayed_entry == NULL)
2511 return NULL;
2513 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2514 if (s->commits.ncommits < ncommits_needed &&
2515 !s->thread_args.log_complete) {
2517 * Ask the log thread for required amount of commits.
2519 s->thread_args.commits_needed +=
2520 ncommits_needed - s->commits.ncommits;
2521 err = trigger_log_thread(view, 1);
2522 if (err)
2523 return err;
2526 do {
2527 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2528 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2529 break;
2531 s->last_displayed_entry = pentry ?
2532 pentry : s->last_displayed_entry;;
2534 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2535 if (pentry == NULL)
2536 break;
2537 s->first_displayed_entry = pentry;
2538 } while (++nscrolled < maxscroll);
2540 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2541 view->nscrolled += nscrolled;
2542 else
2543 view->nscrolled = 0;
2545 return err;
2548 static const struct got_error *
2549 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2550 struct got_commit_object *commit, struct got_object_id *commit_id,
2551 struct tog_view *log_view, struct got_repository *repo)
2553 const struct got_error *err;
2554 struct got_object_qid *parent_id;
2555 struct tog_view *diff_view;
2557 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2558 if (diff_view == NULL)
2559 return got_error_from_errno("view_open");
2561 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2562 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2563 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2564 if (err == NULL)
2565 *new_view = diff_view;
2566 return err;
2569 static const struct got_error *
2570 tree_view_visit_subtree(struct tog_tree_view_state *s,
2571 struct got_tree_object *subtree)
2573 struct tog_parent_tree *parent;
2575 parent = calloc(1, sizeof(*parent));
2576 if (parent == NULL)
2577 return got_error_from_errno("calloc");
2579 parent->tree = s->tree;
2580 parent->first_displayed_entry = s->first_displayed_entry;
2581 parent->selected_entry = s->selected_entry;
2582 parent->selected = s->selected;
2583 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2584 s->tree = subtree;
2585 s->selected = 0;
2586 s->first_displayed_entry = NULL;
2587 return NULL;
2590 static const struct got_error *
2591 tree_view_walk_path(struct tog_tree_view_state *s,
2592 struct got_commit_object *commit, const char *path)
2594 const struct got_error *err = NULL;
2595 struct got_tree_object *tree = NULL;
2596 const char *p;
2597 char *slash, *subpath = NULL;
2599 /* Walk the path and open corresponding tree objects. */
2600 p = path;
2601 while (*p) {
2602 struct got_tree_entry *te;
2603 struct got_object_id *tree_id;
2604 char *te_name;
2606 while (p[0] == '/')
2607 p++;
2609 /* Ensure the correct subtree entry is selected. */
2610 slash = strchr(p, '/');
2611 if (slash == NULL)
2612 te_name = strdup(p);
2613 else
2614 te_name = strndup(p, slash - p);
2615 if (te_name == NULL) {
2616 err = got_error_from_errno("strndup");
2617 break;
2619 te = got_object_tree_find_entry(s->tree, te_name);
2620 if (te == NULL) {
2621 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2622 free(te_name);
2623 break;
2625 free(te_name);
2626 s->first_displayed_entry = s->selected_entry = te;
2628 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2629 break; /* jump to this file's entry */
2631 slash = strchr(p, '/');
2632 if (slash)
2633 subpath = strndup(path, slash - path);
2634 else
2635 subpath = strdup(path);
2636 if (subpath == NULL) {
2637 err = got_error_from_errno("strdup");
2638 break;
2641 err = got_object_id_by_path(&tree_id, s->repo, commit,
2642 subpath);
2643 if (err)
2644 break;
2646 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2647 free(tree_id);
2648 if (err)
2649 break;
2651 err = tree_view_visit_subtree(s, tree);
2652 if (err) {
2653 got_object_tree_close(tree);
2654 break;
2656 if (slash == NULL)
2657 break;
2658 free(subpath);
2659 subpath = NULL;
2660 p = slash;
2663 free(subpath);
2664 return err;
2667 static const struct got_error *
2668 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
2669 struct commit_queue_entry *entry, const char *path,
2670 const char *head_ref_name, struct got_repository *repo)
2672 const struct got_error *err = NULL;
2673 struct tog_tree_view_state *s;
2674 struct tog_view *tree_view;
2676 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
2677 if (tree_view == NULL)
2678 return got_error_from_errno("view_open");
2680 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2681 if (err)
2682 return err;
2683 s = &tree_view->state.tree;
2685 *new_view = tree_view;
2687 if (got_path_is_root_dir(path))
2688 return NULL;
2690 return tree_view_walk_path(s, entry->commit, path);
2693 static const struct got_error *
2694 block_signals_used_by_main_thread(void)
2696 sigset_t sigset;
2697 int errcode;
2699 if (sigemptyset(&sigset) == -1)
2700 return got_error_from_errno("sigemptyset");
2702 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2703 if (sigaddset(&sigset, SIGWINCH) == -1)
2704 return got_error_from_errno("sigaddset");
2705 if (sigaddset(&sigset, SIGCONT) == -1)
2706 return got_error_from_errno("sigaddset");
2707 if (sigaddset(&sigset, SIGINT) == -1)
2708 return got_error_from_errno("sigaddset");
2709 if (sigaddset(&sigset, SIGTERM) == -1)
2710 return got_error_from_errno("sigaddset");
2712 /* ncurses handles SIGTSTP */
2713 if (sigaddset(&sigset, SIGTSTP) == -1)
2714 return got_error_from_errno("sigaddset");
2716 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2717 if (errcode)
2718 return got_error_set_errno(errcode, "pthread_sigmask");
2720 return NULL;
2723 static void *
2724 log_thread(void *arg)
2726 const struct got_error *err = NULL;
2727 int errcode = 0;
2728 struct tog_log_thread_args *a = arg;
2729 int done = 0;
2732 * Sync startup with main thread such that we begin our
2733 * work once view_input() has released the mutex.
2735 errcode = pthread_mutex_lock(&tog_mutex);
2736 if (errcode) {
2737 err = got_error_set_errno(errcode, "pthread_mutex_lock");
2738 return (void *)err;
2741 err = block_signals_used_by_main_thread();
2742 if (err) {
2743 pthread_mutex_unlock(&tog_mutex);
2744 goto done;
2747 while (!done && !err && !tog_fatal_signal_received()) {
2748 errcode = pthread_mutex_unlock(&tog_mutex);
2749 if (errcode) {
2750 err = got_error_set_errno(errcode,
2751 "pthread_mutex_unlock");
2752 goto done;
2754 err = queue_commits(a);
2755 if (err) {
2756 if (err->code != GOT_ERR_ITER_COMPLETED)
2757 goto done;
2758 err = NULL;
2759 done = 1;
2760 } else if (a->commits_needed > 0 && !a->load_all)
2761 a->commits_needed--;
2763 errcode = pthread_mutex_lock(&tog_mutex);
2764 if (errcode) {
2765 err = got_error_set_errno(errcode,
2766 "pthread_mutex_lock");
2767 goto done;
2768 } else if (*a->quit)
2769 done = 1;
2770 else if (*a->first_displayed_entry == NULL) {
2771 *a->first_displayed_entry =
2772 TAILQ_FIRST(&a->commits->head);
2773 *a->selected_entry = *a->first_displayed_entry;
2776 errcode = pthread_cond_signal(&a->commit_loaded);
2777 if (errcode) {
2778 err = got_error_set_errno(errcode,
2779 "pthread_cond_signal");
2780 pthread_mutex_unlock(&tog_mutex);
2781 goto done;
2784 if (done)
2785 a->commits_needed = 0;
2786 else {
2787 if (a->commits_needed == 0 && !a->load_all) {
2788 errcode = pthread_cond_wait(&a->need_commits,
2789 &tog_mutex);
2790 if (errcode) {
2791 err = got_error_set_errno(errcode,
2792 "pthread_cond_wait");
2793 pthread_mutex_unlock(&tog_mutex);
2794 goto done;
2796 if (*a->quit)
2797 done = 1;
2801 a->log_complete = 1;
2802 errcode = pthread_mutex_unlock(&tog_mutex);
2803 if (errcode)
2804 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2805 done:
2806 if (err) {
2807 tog_thread_error = 1;
2808 pthread_cond_signal(&a->commit_loaded);
2810 return (void *)err;
2813 static const struct got_error *
2814 stop_log_thread(struct tog_log_view_state *s)
2816 const struct got_error *err = NULL, *thread_err = NULL;
2817 int errcode;
2819 if (s->thread) {
2820 s->quit = 1;
2821 errcode = pthread_cond_signal(&s->thread_args.need_commits);
2822 if (errcode)
2823 return got_error_set_errno(errcode,
2824 "pthread_cond_signal");
2825 errcode = pthread_mutex_unlock(&tog_mutex);
2826 if (errcode)
2827 return got_error_set_errno(errcode,
2828 "pthread_mutex_unlock");
2829 errcode = pthread_join(s->thread, (void **)&thread_err);
2830 if (errcode)
2831 return got_error_set_errno(errcode, "pthread_join");
2832 errcode = pthread_mutex_lock(&tog_mutex);
2833 if (errcode)
2834 return got_error_set_errno(errcode,
2835 "pthread_mutex_lock");
2836 s->thread = NULL;
2839 if (s->thread_args.repo) {
2840 err = got_repo_close(s->thread_args.repo);
2841 s->thread_args.repo = NULL;
2844 if (s->thread_args.pack_fds) {
2845 const struct got_error *pack_err =
2846 got_repo_pack_fds_close(s->thread_args.pack_fds);
2847 if (err == NULL)
2848 err = pack_err;
2849 s->thread_args.pack_fds = NULL;
2852 if (s->thread_args.graph) {
2853 got_commit_graph_close(s->thread_args.graph);
2854 s->thread_args.graph = NULL;
2857 return err ? err : thread_err;
2860 static const struct got_error *
2861 close_log_view(struct tog_view *view)
2863 const struct got_error *err = NULL;
2864 struct tog_log_view_state *s = &view->state.log;
2865 int errcode;
2867 err = stop_log_thread(s);
2869 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
2870 if (errcode && err == NULL)
2871 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2873 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
2874 if (errcode && err == NULL)
2875 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2877 free_commits(&s->commits);
2878 free(s->in_repo_path);
2879 s->in_repo_path = NULL;
2880 free(s->start_id);
2881 s->start_id = NULL;
2882 free(s->head_ref_name);
2883 s->head_ref_name = NULL;
2884 return err;
2887 static const struct got_error *
2888 search_start_log_view(struct tog_view *view)
2890 struct tog_log_view_state *s = &view->state.log;
2892 s->matched_entry = NULL;
2893 s->search_entry = NULL;
2894 return NULL;
2897 static const struct got_error *
2898 search_next_log_view(struct tog_view *view)
2900 const struct got_error *err = NULL;
2901 struct tog_log_view_state *s = &view->state.log;
2902 struct commit_queue_entry *entry;
2904 /* Display progress update in log view. */
2905 show_log_view(view);
2906 update_panels();
2907 doupdate();
2909 if (s->search_entry) {
2910 int errcode, ch;
2911 errcode = pthread_mutex_unlock(&tog_mutex);
2912 if (errcode)
2913 return got_error_set_errno(errcode,
2914 "pthread_mutex_unlock");
2915 ch = wgetch(view->window);
2916 errcode = pthread_mutex_lock(&tog_mutex);
2917 if (errcode)
2918 return got_error_set_errno(errcode,
2919 "pthread_mutex_lock");
2920 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
2921 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2922 return NULL;
2924 if (view->searching == TOG_SEARCH_FORWARD)
2925 entry = TAILQ_NEXT(s->search_entry, entry);
2926 else
2927 entry = TAILQ_PREV(s->search_entry,
2928 commit_queue_head, entry);
2929 } else if (s->matched_entry) {
2930 int matched_idx = s->matched_entry->idx;
2931 int selected_idx = s->selected_entry->idx;
2934 * If the user has moved the cursor after we hit a match,
2935 * the position from where we should continue searching
2936 * might have changed.
2938 if (view->searching == TOG_SEARCH_FORWARD) {
2939 if (matched_idx > selected_idx)
2940 entry = TAILQ_NEXT(s->selected_entry, entry);
2941 else
2942 entry = TAILQ_NEXT(s->matched_entry, entry);
2943 } else {
2944 if (matched_idx < selected_idx)
2945 entry = TAILQ_PREV(s->selected_entry,
2946 commit_queue_head, entry);
2947 else
2948 entry = TAILQ_PREV(s->matched_entry,
2949 commit_queue_head, entry);
2951 } else {
2952 entry = s->selected_entry;
2955 while (1) {
2956 int have_match = 0;
2958 if (entry == NULL) {
2959 if (s->thread_args.log_complete ||
2960 view->searching == TOG_SEARCH_BACKWARD) {
2961 view->search_next_done =
2962 (s->matched_entry == NULL ?
2963 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
2964 s->search_entry = NULL;
2965 return NULL;
2968 * Poke the log thread for more commits and return,
2969 * allowing the main loop to make progress. Search
2970 * will resume at s->search_entry once we come back.
2972 s->thread_args.commits_needed++;
2973 return trigger_log_thread(view, 0);
2976 err = match_commit(&have_match, entry->id, entry->commit,
2977 &view->regex);
2978 if (err)
2979 break;
2980 if (have_match) {
2981 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2982 s->matched_entry = entry;
2983 break;
2986 s->search_entry = entry;
2987 if (view->searching == TOG_SEARCH_FORWARD)
2988 entry = TAILQ_NEXT(entry, entry);
2989 else
2990 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2993 if (s->matched_entry) {
2994 int cur = s->selected_entry->idx;
2995 while (cur < s->matched_entry->idx) {
2996 err = input_log_view(NULL, view, KEY_DOWN);
2997 if (err)
2998 return err;
2999 cur++;
3001 while (cur > s->matched_entry->idx) {
3002 err = input_log_view(NULL, view, KEY_UP);
3003 if (err)
3004 return err;
3005 cur--;
3009 s->search_entry = NULL;
3011 return NULL;
3014 static const struct got_error *
3015 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3016 struct got_repository *repo, const char *head_ref_name,
3017 const char *in_repo_path, int log_branches)
3019 const struct got_error *err = NULL;
3020 struct tog_log_view_state *s = &view->state.log;
3021 struct got_repository *thread_repo = NULL;
3022 struct got_commit_graph *thread_graph = NULL;
3023 int errcode;
3025 if (in_repo_path != s->in_repo_path) {
3026 free(s->in_repo_path);
3027 s->in_repo_path = strdup(in_repo_path);
3028 if (s->in_repo_path == NULL)
3029 return got_error_from_errno("strdup");
3032 /* The commit queue only contains commits being displayed. */
3033 TAILQ_INIT(&s->commits.head);
3034 s->commits.ncommits = 0;
3036 s->repo = repo;
3037 if (head_ref_name) {
3038 s->head_ref_name = strdup(head_ref_name);
3039 if (s->head_ref_name == NULL) {
3040 err = got_error_from_errno("strdup");
3041 goto done;
3044 s->start_id = got_object_id_dup(start_id);
3045 if (s->start_id == NULL) {
3046 err = got_error_from_errno("got_object_id_dup");
3047 goto done;
3049 s->log_branches = log_branches;
3051 STAILQ_INIT(&s->colors);
3052 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3053 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3054 get_color_value("TOG_COLOR_COMMIT"));
3055 if (err)
3056 goto done;
3057 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3058 get_color_value("TOG_COLOR_AUTHOR"));
3059 if (err) {
3060 free_colors(&s->colors);
3061 goto done;
3063 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3064 get_color_value("TOG_COLOR_DATE"));
3065 if (err) {
3066 free_colors(&s->colors);
3067 goto done;
3071 view->show = show_log_view;
3072 view->input = input_log_view;
3073 view->resize = resize_log_view;
3074 view->close = close_log_view;
3075 view->search_start = search_start_log_view;
3076 view->search_next = search_next_log_view;
3078 if (s->thread_args.pack_fds == NULL) {
3079 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3080 if (err)
3081 goto done;
3083 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3084 s->thread_args.pack_fds);
3085 if (err)
3086 goto done;
3087 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3088 !s->log_branches);
3089 if (err)
3090 goto done;
3091 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3092 s->repo, NULL, NULL);
3093 if (err)
3094 goto done;
3096 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3097 if (errcode) {
3098 err = got_error_set_errno(errcode, "pthread_cond_init");
3099 goto done;
3101 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3102 if (errcode) {
3103 err = got_error_set_errno(errcode, "pthread_cond_init");
3104 goto done;
3107 s->thread_args.commits_needed = view->nlines;
3108 s->thread_args.graph = thread_graph;
3109 s->thread_args.commits = &s->commits;
3110 s->thread_args.in_repo_path = s->in_repo_path;
3111 s->thread_args.start_id = s->start_id;
3112 s->thread_args.repo = thread_repo;
3113 s->thread_args.log_complete = 0;
3114 s->thread_args.quit = &s->quit;
3115 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3116 s->thread_args.selected_entry = &s->selected_entry;
3117 s->thread_args.searching = &view->searching;
3118 s->thread_args.search_next_done = &view->search_next_done;
3119 s->thread_args.regex = &view->regex;
3120 done:
3121 if (err)
3122 close_log_view(view);
3123 return err;
3126 static const struct got_error *
3127 show_log_view(struct tog_view *view)
3129 const struct got_error *err;
3130 struct tog_log_view_state *s = &view->state.log;
3132 if (s->thread == NULL) {
3133 int errcode = pthread_create(&s->thread, NULL, log_thread,
3134 &s->thread_args);
3135 if (errcode)
3136 return got_error_set_errno(errcode, "pthread_create");
3137 if (s->thread_args.commits_needed > 0) {
3138 err = trigger_log_thread(view, 1);
3139 if (err)
3140 return err;
3144 return draw_commits(view);
3147 static void
3148 log_move_cursor_up(struct tog_view *view, int page, int home)
3150 struct tog_log_view_state *s = &view->state.log;
3152 if (s->selected_entry->idx == 0)
3153 view->count = 0;
3154 if (s->first_displayed_entry == NULL)
3155 return;
3157 if ((page && TAILQ_FIRST(&s->commits.head) == s->first_displayed_entry)
3158 || home)
3159 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3161 if (!page && !home && s->selected > 0)
3162 --s->selected;
3163 else
3164 log_scroll_up(s, home ? s->commits.ncommits : MAX(page, 1));
3166 select_commit(s);
3167 return;
3170 static const struct got_error *
3171 log_move_cursor_down(struct tog_view *view, int page)
3173 struct tog_log_view_state *s = &view->state.log;
3174 const struct got_error *err = NULL;
3175 int eos = view->nlines - 2;
3177 if (s->thread_args.log_complete &&
3178 s->selected_entry->idx >= s->commits.ncommits - 1)
3179 return NULL;
3181 if (view_is_hsplit_top(view))
3182 --eos; /* border consumes the last line */
3184 if (!page) {
3185 if (s->selected < MIN(eos, s->commits.ncommits - 1))
3186 ++s->selected;
3187 else
3188 err = log_scroll_down(view, 1);
3189 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3190 struct commit_queue_entry *entry;
3191 int n;
3193 s->selected = 0;
3194 entry = TAILQ_LAST(&s->commits.head, commit_queue_head);
3195 s->last_displayed_entry = entry;
3196 for (n = 0; n <= eos; n++) {
3197 if (entry == NULL)
3198 break;
3199 s->first_displayed_entry = entry;
3200 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3202 if (n > 0)
3203 s->selected = n - 1;
3204 } else {
3205 if (s->last_displayed_entry->idx == s->commits.ncommits - 1 &&
3206 s->thread_args.log_complete)
3207 s->selected += MIN(page,
3208 s->commits.ncommits - s->selected_entry->idx - 1);
3209 else
3210 err = log_scroll_down(view, page);
3212 if (err)
3213 return err;
3216 * We might necessarily overshoot in horizontal
3217 * splits; if so, select the last displayed commit.
3219 if (s->first_displayed_entry && s->last_displayed_entry) {
3220 s->selected = MIN(s->selected,
3221 s->last_displayed_entry->idx -
3222 s->first_displayed_entry->idx);
3225 select_commit(s);
3227 if (s->thread_args.log_complete &&
3228 s->selected_entry->idx == s->commits.ncommits - 1)
3229 view->count = 0;
3231 return NULL;
3234 static void
3235 view_get_split(struct tog_view *view, int *y, int *x)
3237 *x = 0;
3238 *y = 0;
3240 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3241 if (view->child && view->child->resized_y)
3242 *y = view->child->resized_y;
3243 else if (view->resized_y)
3244 *y = view->resized_y;
3245 else
3246 *y = view_split_begin_y(view->lines);
3247 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3248 if (view->child && view->child->resized_x)
3249 *x = view->child->resized_x;
3250 else if (view->resized_x)
3251 *x = view->resized_x;
3252 else
3253 *x = view_split_begin_x(view->begin_x);
3257 /* Split view horizontally at y and offset view->state->selected line. */
3258 static const struct got_error *
3259 view_init_hsplit(struct tog_view *view, int y)
3261 const struct got_error *err = NULL;
3263 view->nlines = y;
3264 view->ncols = COLS;
3265 err = view_resize(view);
3266 if (err)
3267 return err;
3269 err = offset_selection_down(view);
3271 return err;
3274 static const struct got_error *
3275 log_goto_line(struct tog_view *view, int nlines)
3277 const struct got_error *err = NULL;
3278 struct tog_log_view_state *s = &view->state.log;
3279 int g, idx = s->selected_entry->idx;
3281 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3282 return NULL;
3284 g = view->gline;
3285 view->gline = 0;
3287 if (g >= s->first_displayed_entry->idx + 1 &&
3288 g <= s->last_displayed_entry->idx + 1 &&
3289 g - s->first_displayed_entry->idx - 1 < nlines) {
3290 s->selected = g - s->first_displayed_entry->idx - 1;
3291 select_commit(s);
3292 return NULL;
3295 if (idx + 1 < g) {
3296 err = log_move_cursor_down(view, g - idx - 1);
3297 if (!err && g > s->selected_entry->idx + 1)
3298 err = log_move_cursor_down(view,
3299 g - s->first_displayed_entry->idx - 1);
3300 if (err)
3301 return err;
3302 } else if (idx + 1 > g)
3303 log_move_cursor_up(view, idx - g + 1, 0);
3305 if (g < nlines && s->first_displayed_entry->idx == 0)
3306 s->selected = g - 1;
3308 select_commit(s);
3309 return NULL;
3313 static const struct got_error *
3314 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3316 const struct got_error *err = NULL;
3317 struct tog_log_view_state *s = &view->state.log;
3318 int eos, nscroll;
3320 if (s->thread_args.load_all) {
3321 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3322 s->thread_args.load_all = 0;
3323 else if (s->thread_args.log_complete) {
3324 err = log_move_cursor_down(view, s->commits.ncommits);
3325 s->thread_args.load_all = 0;
3327 if (err)
3328 return err;
3331 eos = nscroll = view->nlines - 1;
3332 if (view_is_hsplit_top(view))
3333 --eos; /* border */
3335 if (view->gline)
3336 return log_goto_line(view, eos);
3338 switch (ch) {
3339 case 'q':
3340 s->quit = 1;
3341 break;
3342 case '0':
3343 view->x = 0;
3344 break;
3345 case '$':
3346 view->x = MAX(view->maxx - view->ncols / 2, 0);
3347 view->count = 0;
3348 break;
3349 case KEY_RIGHT:
3350 case 'l':
3351 if (view->x + view->ncols / 2 < view->maxx)
3352 view->x += 2; /* move two columns right */
3353 else
3354 view->count = 0;
3355 break;
3356 case KEY_LEFT:
3357 case 'h':
3358 view->x -= MIN(view->x, 2); /* move two columns back */
3359 if (view->x <= 0)
3360 view->count = 0;
3361 break;
3362 case 'k':
3363 case KEY_UP:
3364 case '<':
3365 case ',':
3366 case CTRL('p'):
3367 log_move_cursor_up(view, 0, 0);
3368 break;
3369 case 'g':
3370 case KEY_HOME:
3371 log_move_cursor_up(view, 0, 1);
3372 view->count = 0;
3373 break;
3374 case CTRL('u'):
3375 case 'u':
3376 nscroll /= 2;
3377 /* FALL THROUGH */
3378 case KEY_PPAGE:
3379 case CTRL('b'):
3380 case 'b':
3381 log_move_cursor_up(view, nscroll, 0);
3382 break;
3383 case 'j':
3384 case KEY_DOWN:
3385 case '>':
3386 case '.':
3387 case CTRL('n'):
3388 err = log_move_cursor_down(view, 0);
3389 break;
3390 case '@':
3391 s->use_committer = !s->use_committer;
3392 break;
3393 case 'G':
3394 case KEY_END: {
3395 /* We don't know yet how many commits, so we're forced to
3396 * traverse them all. */
3397 view->count = 0;
3398 s->thread_args.load_all = 1;
3399 if (!s->thread_args.log_complete)
3400 return trigger_log_thread(view, 0);
3401 err = log_move_cursor_down(view, s->commits.ncommits);
3402 s->thread_args.load_all = 0;
3403 break;
3405 case CTRL('d'):
3406 case 'd':
3407 nscroll /= 2;
3408 /* FALL THROUGH */
3409 case KEY_NPAGE:
3410 case CTRL('f'):
3411 case 'f':
3412 case ' ':
3413 err = log_move_cursor_down(view, nscroll);
3414 break;
3415 case KEY_RESIZE:
3416 if (s->selected > view->nlines - 2)
3417 s->selected = view->nlines - 2;
3418 if (s->selected > s->commits.ncommits - 1)
3419 s->selected = s->commits.ncommits - 1;
3420 select_commit(s);
3421 if (s->commits.ncommits < view->nlines - 1 &&
3422 !s->thread_args.log_complete) {
3423 s->thread_args.commits_needed += (view->nlines - 1) -
3424 s->commits.ncommits;
3425 err = trigger_log_thread(view, 1);
3427 break;
3428 case KEY_ENTER:
3429 case '\r':
3430 view->count = 0;
3431 if (s->selected_entry == NULL)
3432 break;
3433 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
3434 break;
3435 case 'T':
3436 view->count = 0;
3437 if (s->selected_entry == NULL)
3438 break;
3439 err = view_request_new(new_view, view, TOG_VIEW_TREE);
3440 break;
3441 case KEY_BACKSPACE:
3442 case CTRL('l'):
3443 case 'B':
3444 view->count = 0;
3445 if (ch == KEY_BACKSPACE &&
3446 got_path_is_root_dir(s->in_repo_path))
3447 break;
3448 err = stop_log_thread(s);
3449 if (err)
3450 return err;
3451 if (ch == KEY_BACKSPACE) {
3452 char *parent_path;
3453 err = got_path_dirname(&parent_path, s->in_repo_path);
3454 if (err)
3455 return err;
3456 free(s->in_repo_path);
3457 s->in_repo_path = parent_path;
3458 s->thread_args.in_repo_path = s->in_repo_path;
3459 } else if (ch == CTRL('l')) {
3460 struct got_object_id *start_id;
3461 err = got_repo_match_object_id(&start_id, NULL,
3462 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3463 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3464 if (err)
3465 return err;
3466 free(s->start_id);
3467 s->start_id = start_id;
3468 s->thread_args.start_id = s->start_id;
3469 } else /* 'B' */
3470 s->log_branches = !s->log_branches;
3472 if (s->thread_args.pack_fds == NULL) {
3473 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3474 if (err)
3475 return err;
3477 err = got_repo_open(&s->thread_args.repo,
3478 got_repo_get_path(s->repo), NULL,
3479 s->thread_args.pack_fds);
3480 if (err)
3481 return err;
3482 tog_free_refs();
3483 err = tog_load_refs(s->repo, 0);
3484 if (err)
3485 return err;
3486 err = got_commit_graph_open(&s->thread_args.graph,
3487 s->in_repo_path, !s->log_branches);
3488 if (err)
3489 return err;
3490 err = got_commit_graph_iter_start(s->thread_args.graph,
3491 s->start_id, s->repo, NULL, NULL);
3492 if (err)
3493 return err;
3494 free_commits(&s->commits);
3495 s->first_displayed_entry = NULL;
3496 s->last_displayed_entry = NULL;
3497 s->selected_entry = NULL;
3498 s->selected = 0;
3499 s->thread_args.log_complete = 0;
3500 s->quit = 0;
3501 s->thread_args.commits_needed = view->lines;
3502 s->matched_entry = NULL;
3503 s->search_entry = NULL;
3504 view->offset = 0;
3505 break;
3506 case 'R':
3507 view->count = 0;
3508 err = view_request_new(new_view, view, TOG_VIEW_REF);
3509 break;
3510 default:
3511 view->count = 0;
3512 break;
3515 return err;
3518 static const struct got_error *
3519 apply_unveil(const char *repo_path, const char *worktree_path)
3521 const struct got_error *error;
3523 #ifdef PROFILE
3524 if (unveil("gmon.out", "rwc") != 0)
3525 return got_error_from_errno2("unveil", "gmon.out");
3526 #endif
3527 if (repo_path && unveil(repo_path, "r") != 0)
3528 return got_error_from_errno2("unveil", repo_path);
3530 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3531 return got_error_from_errno2("unveil", worktree_path);
3533 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3534 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3536 error = got_privsep_unveil_exec_helpers();
3537 if (error != NULL)
3538 return error;
3540 if (unveil(NULL, NULL) != 0)
3541 return got_error_from_errno("unveil");
3543 return NULL;
3546 static void
3547 init_curses(void)
3550 * Override default signal handlers before starting ncurses.
3551 * This should prevent ncurses from installing its own
3552 * broken cleanup() signal handler.
3554 signal(SIGWINCH, tog_sigwinch);
3555 signal(SIGPIPE, tog_sigpipe);
3556 signal(SIGCONT, tog_sigcont);
3557 signal(SIGINT, tog_sigint);
3558 signal(SIGTERM, tog_sigterm);
3560 initscr();
3561 cbreak();
3562 halfdelay(1); /* Do fast refresh while initial view is loading. */
3563 noecho();
3564 nonl();
3565 intrflush(stdscr, FALSE);
3566 keypad(stdscr, TRUE);
3567 curs_set(0);
3568 if (getenv("TOG_COLORS") != NULL) {
3569 start_color();
3570 use_default_colors();
3574 static const struct got_error *
3575 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
3576 struct got_repository *repo, struct got_worktree *worktree)
3578 const struct got_error *err = NULL;
3580 if (argc == 0) {
3581 *in_repo_path = strdup("/");
3582 if (*in_repo_path == NULL)
3583 return got_error_from_errno("strdup");
3584 return NULL;
3587 if (worktree) {
3588 const char *prefix = got_worktree_get_path_prefix(worktree);
3589 char *p;
3591 err = got_worktree_resolve_path(&p, worktree, argv[0]);
3592 if (err)
3593 return err;
3594 if (asprintf(in_repo_path, "%s%s%s", prefix,
3595 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
3596 p) == -1) {
3597 err = got_error_from_errno("asprintf");
3598 *in_repo_path = NULL;
3600 free(p);
3601 } else
3602 err = got_repo_map_path(in_repo_path, repo, argv[0]);
3604 return err;
3607 static const struct got_error *
3608 cmd_log(int argc, char *argv[])
3610 const struct got_error *error;
3611 struct got_repository *repo = NULL;
3612 struct got_worktree *worktree = NULL;
3613 struct got_object_id *start_id = NULL;
3614 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
3615 char *start_commit = NULL, *label = NULL;
3616 struct got_reference *ref = NULL;
3617 const char *head_ref_name = NULL;
3618 int ch, log_branches = 0;
3619 struct tog_view *view;
3620 int *pack_fds = NULL;
3622 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
3623 switch (ch) {
3624 case 'b':
3625 log_branches = 1;
3626 break;
3627 case 'c':
3628 start_commit = optarg;
3629 break;
3630 case 'r':
3631 repo_path = realpath(optarg, NULL);
3632 if (repo_path == NULL)
3633 return got_error_from_errno2("realpath",
3634 optarg);
3635 break;
3636 default:
3637 usage_log();
3638 /* NOTREACHED */
3642 argc -= optind;
3643 argv += optind;
3645 if (argc > 1)
3646 usage_log();
3648 error = got_repo_pack_fds_open(&pack_fds);
3649 if (error != NULL)
3650 goto done;
3652 if (repo_path == NULL) {
3653 cwd = getcwd(NULL, 0);
3654 if (cwd == NULL)
3655 return got_error_from_errno("getcwd");
3656 error = got_worktree_open(&worktree, cwd);
3657 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3658 goto done;
3659 if (worktree)
3660 repo_path =
3661 strdup(got_worktree_get_repo_path(worktree));
3662 else
3663 repo_path = strdup(cwd);
3664 if (repo_path == NULL) {
3665 error = got_error_from_errno("strdup");
3666 goto done;
3670 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3671 if (error != NULL)
3672 goto done;
3674 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
3675 repo, worktree);
3676 if (error)
3677 goto done;
3679 init_curses();
3681 error = apply_unveil(got_repo_get_path(repo),
3682 worktree ? got_worktree_get_root_path(worktree) : NULL);
3683 if (error)
3684 goto done;
3686 /* already loaded by tog_log_with_path()? */
3687 if (TAILQ_EMPTY(&tog_refs)) {
3688 error = tog_load_refs(repo, 0);
3689 if (error)
3690 goto done;
3693 if (start_commit == NULL) {
3694 error = got_repo_match_object_id(&start_id, &label,
3695 worktree ? got_worktree_get_head_ref_name(worktree) :
3696 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3697 if (error)
3698 goto done;
3699 head_ref_name = label;
3700 } else {
3701 error = got_ref_open(&ref, repo, start_commit, 0);
3702 if (error == NULL)
3703 head_ref_name = got_ref_get_name(ref);
3704 else if (error->code != GOT_ERR_NOT_REF)
3705 goto done;
3706 error = got_repo_match_object_id(&start_id, NULL,
3707 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3708 if (error)
3709 goto done;
3712 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
3713 if (view == NULL) {
3714 error = got_error_from_errno("view_open");
3715 goto done;
3717 error = open_log_view(view, start_id, repo, head_ref_name,
3718 in_repo_path, log_branches);
3719 if (error)
3720 goto done;
3721 if (worktree) {
3722 /* Release work tree lock. */
3723 got_worktree_close(worktree);
3724 worktree = NULL;
3726 error = view_loop(view);
3727 done:
3728 free(in_repo_path);
3729 free(repo_path);
3730 free(cwd);
3731 free(start_id);
3732 free(label);
3733 if (ref)
3734 got_ref_close(ref);
3735 if (repo) {
3736 const struct got_error *close_err = got_repo_close(repo);
3737 if (error == NULL)
3738 error = close_err;
3740 if (worktree)
3741 got_worktree_close(worktree);
3742 if (pack_fds) {
3743 const struct got_error *pack_err =
3744 got_repo_pack_fds_close(pack_fds);
3745 if (error == NULL)
3746 error = pack_err;
3748 tog_free_refs();
3749 return error;
3752 __dead static void
3753 usage_diff(void)
3755 endwin();
3756 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
3757 "object1 object2\n", getprogname());
3758 exit(1);
3761 static int
3762 match_line(const char *line, regex_t *regex, size_t nmatch,
3763 regmatch_t *regmatch)
3765 return regexec(regex, line, nmatch, regmatch, 0) == 0;
3768 static struct tog_color *
3769 match_color(struct tog_colors *colors, const char *line)
3771 struct tog_color *tc = NULL;
3773 STAILQ_FOREACH(tc, colors, entry) {
3774 if (match_line(line, &tc->regex, 0, NULL))
3775 return tc;
3778 return NULL;
3781 static const struct got_error *
3782 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
3783 WINDOW *window, int skipcol, regmatch_t *regmatch)
3785 const struct got_error *err = NULL;
3786 char *exstr = NULL;
3787 wchar_t *wline = NULL;
3788 int rme, rms, n, width, scrollx;
3789 int width0 = 0, width1 = 0, width2 = 0;
3790 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
3792 *wtotal = 0;
3794 rms = regmatch->rm_so;
3795 rme = regmatch->rm_eo;
3797 err = expand_tab(&exstr, line);
3798 if (err)
3799 return err;
3801 /* Split the line into 3 segments, according to match offsets. */
3802 seg0 = strndup(exstr, rms);
3803 if (seg0 == NULL) {
3804 err = got_error_from_errno("strndup");
3805 goto done;
3807 seg1 = strndup(exstr + rms, rme - rms);
3808 if (seg1 == NULL) {
3809 err = got_error_from_errno("strndup");
3810 goto done;
3812 seg2 = strdup(exstr + rme);
3813 if (seg2 == NULL) {
3814 err = got_error_from_errno("strndup");
3815 goto done;
3818 /* draw up to matched token if we haven't scrolled past it */
3819 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
3820 col_tab_align, 1);
3821 if (err)
3822 goto done;
3823 n = MAX(width0 - skipcol, 0);
3824 if (n) {
3825 free(wline);
3826 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
3827 wlimit, col_tab_align, 1);
3828 if (err)
3829 goto done;
3830 waddwstr(window, &wline[scrollx]);
3831 wlimit -= width;
3832 *wtotal += width;
3835 if (wlimit > 0) {
3836 int i = 0, w = 0;
3837 size_t wlen;
3839 free(wline);
3840 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
3841 col_tab_align, 1);
3842 if (err)
3843 goto done;
3844 wlen = wcslen(wline);
3845 while (i < wlen) {
3846 width = wcwidth(wline[i]);
3847 if (width == -1) {
3848 /* should not happen, tabs are expanded */
3849 err = got_error(GOT_ERR_RANGE);
3850 goto done;
3852 if (width0 + w + width > skipcol)
3853 break;
3854 w += width;
3855 i++;
3857 /* draw (visible part of) matched token (if scrolled into it) */
3858 if (width1 - w > 0) {
3859 wattron(window, A_STANDOUT);
3860 waddwstr(window, &wline[i]);
3861 wattroff(window, A_STANDOUT);
3862 wlimit -= (width1 - w);
3863 *wtotal += (width1 - w);
3867 if (wlimit > 0) { /* draw rest of line */
3868 free(wline);
3869 if (skipcol > width0 + width1) {
3870 err = format_line(&wline, &width2, &scrollx, seg2,
3871 skipcol - (width0 + width1), wlimit,
3872 col_tab_align, 1);
3873 if (err)
3874 goto done;
3875 waddwstr(window, &wline[scrollx]);
3876 } else {
3877 err = format_line(&wline, &width2, NULL, seg2, 0,
3878 wlimit, col_tab_align, 1);
3879 if (err)
3880 goto done;
3881 waddwstr(window, wline);
3883 *wtotal += width2;
3885 done:
3886 free(wline);
3887 free(exstr);
3888 free(seg0);
3889 free(seg1);
3890 free(seg2);
3891 return err;
3894 static int
3895 gotoline(struct tog_view *view, int *lineno, int *nprinted)
3897 FILE *f = NULL;
3898 int *eof, *first, *selected;
3900 if (view->type == TOG_VIEW_DIFF) {
3901 struct tog_diff_view_state *s = &view->state.diff;
3903 first = &s->first_displayed_line;
3904 selected = first;
3905 eof = &s->eof;
3906 f = s->f;
3907 } else if (view->type == TOG_VIEW_BLAME) {
3908 struct tog_blame_view_state *s = &view->state.blame;
3910 first = &s->first_displayed_line;
3911 selected = &s->selected_line;
3912 eof = &s->eof;
3913 f = s->blame.f;
3914 } else
3915 return 0;
3917 /* Center gline in the middle of the page like vi(1). */
3918 if (*lineno < view->gline - (view->nlines - 3) / 2)
3919 return 0;
3920 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
3921 rewind(f);
3922 *eof = 0;
3923 *first = 1;
3924 *lineno = 0;
3925 *nprinted = 0;
3926 return 0;
3929 *selected = view->gline <= (view->nlines - 3) / 2 ?
3930 view->gline : (view->nlines - 3) / 2 + 1;
3931 view->gline = 0;
3933 return 1;
3936 static const struct got_error *
3937 draw_file(struct tog_view *view, const char *header)
3939 struct tog_diff_view_state *s = &view->state.diff;
3940 regmatch_t *regmatch = &view->regmatch;
3941 const struct got_error *err;
3942 int nprinted = 0;
3943 char *line;
3944 size_t linesize = 0;
3945 ssize_t linelen;
3946 wchar_t *wline;
3947 int width;
3948 int max_lines = view->nlines;
3949 int nlines = s->nlines;
3950 off_t line_offset;
3952 s->lineno = s->first_displayed_line - 1;
3953 line_offset = s->lines[s->first_displayed_line - 1].offset;
3954 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
3955 return got_error_from_errno("fseek");
3957 werase(view->window);
3959 if (view->gline > s->nlines - 1)
3960 view->gline = s->nlines - 1;
3962 if (header) {
3963 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
3964 1 : view->gline - (view->nlines - 3) / 2 :
3965 s->lineno + s->selected_line;
3967 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
3968 return got_error_from_errno("asprintf");
3969 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
3970 0, 0);
3971 free(line);
3972 if (err)
3973 return err;
3975 if (view_needs_focus_indication(view))
3976 wstandout(view->window);
3977 waddwstr(view->window, wline);
3978 free(wline);
3979 wline = NULL;
3980 if (view_needs_focus_indication(view))
3981 wstandend(view->window);
3982 if (width <= view->ncols - 1)
3983 waddch(view->window, '\n');
3985 if (max_lines <= 1)
3986 return NULL;
3987 max_lines--;
3990 s->eof = 0;
3991 view->maxx = 0;
3992 line = NULL;
3993 while (max_lines > 0 && nprinted < max_lines) {
3994 enum got_diff_line_type linetype;
3995 attr_t attr = 0;
3997 linelen = getline(&line, &linesize, s->f);
3998 if (linelen == -1) {
3999 if (feof(s->f)) {
4000 s->eof = 1;
4001 break;
4003 free(line);
4004 return got_ferror(s->f, GOT_ERR_IO);
4007 if (++s->lineno < s->first_displayed_line)
4008 continue;
4009 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4010 continue;
4011 if (s->lineno == view->hiline)
4012 attr = A_STANDOUT;
4014 /* Set view->maxx based on full line length. */
4015 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4016 view->x ? 1 : 0);
4017 if (err) {
4018 free(line);
4019 return err;
4021 view->maxx = MAX(view->maxx, width);
4022 free(wline);
4023 wline = NULL;
4025 linetype = s->lines[s->lineno].type;
4026 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4027 linetype < GOT_DIFF_LINE_CONTEXT)
4028 attr |= COLOR_PAIR(linetype);
4029 if (attr)
4030 wattron(view->window, attr);
4031 if (s->first_displayed_line + nprinted == s->matched_line &&
4032 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4033 err = add_matched_line(&width, line, view->ncols, 0,
4034 view->window, view->x, regmatch);
4035 if (err) {
4036 free(line);
4037 return err;
4039 } else {
4040 int skip;
4041 err = format_line(&wline, &width, &skip, line,
4042 view->x, view->ncols, 0, view->x ? 1 : 0);
4043 if (err) {
4044 free(line);
4045 return err;
4047 waddwstr(view->window, &wline[skip]);
4048 free(wline);
4049 wline = NULL;
4051 if (s->lineno == view->hiline) {
4052 /* highlight full gline length */
4053 while (width++ < view->ncols)
4054 waddch(view->window, ' ');
4055 } else {
4056 if (width <= view->ncols - 1)
4057 waddch(view->window, '\n');
4059 if (attr)
4060 wattroff(view->window, attr);
4061 if (++nprinted == 1)
4062 s->first_displayed_line = s->lineno;
4064 free(line);
4065 if (nprinted >= 1)
4066 s->last_displayed_line = s->first_displayed_line +
4067 (nprinted - 1);
4068 else
4069 s->last_displayed_line = s->first_displayed_line;
4071 view_border(view);
4073 if (s->eof) {
4074 while (nprinted < view->nlines) {
4075 waddch(view->window, '\n');
4076 nprinted++;
4079 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4080 view->ncols, 0, 0);
4081 if (err) {
4082 return err;
4085 wstandout(view->window);
4086 waddwstr(view->window, wline);
4087 free(wline);
4088 wline = NULL;
4089 wstandend(view->window);
4092 return NULL;
4095 static char *
4096 get_datestr(time_t *time, char *datebuf)
4098 struct tm mytm, *tm;
4099 char *p, *s;
4101 tm = gmtime_r(time, &mytm);
4102 if (tm == NULL)
4103 return NULL;
4104 s = asctime_r(tm, datebuf);
4105 if (s == NULL)
4106 return NULL;
4107 p = strchr(s, '\n');
4108 if (p)
4109 *p = '\0';
4110 return s;
4113 static const struct got_error *
4114 get_changed_paths(struct got_pathlist_head *paths,
4115 struct got_commit_object *commit, struct got_repository *repo)
4117 const struct got_error *err = NULL;
4118 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
4119 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
4120 struct got_object_qid *qid;
4122 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
4123 if (qid != NULL) {
4124 struct got_commit_object *pcommit;
4125 err = got_object_open_as_commit(&pcommit, repo,
4126 &qid->id);
4127 if (err)
4128 return err;
4130 tree_id1 = got_object_id_dup(
4131 got_object_commit_get_tree_id(pcommit));
4132 if (tree_id1 == NULL) {
4133 got_object_commit_close(pcommit);
4134 return got_error_from_errno("got_object_id_dup");
4136 got_object_commit_close(pcommit);
4140 if (tree_id1) {
4141 err = got_object_open_as_tree(&tree1, repo, tree_id1);
4142 if (err)
4143 goto done;
4146 tree_id2 = got_object_commit_get_tree_id(commit);
4147 err = got_object_open_as_tree(&tree2, repo, tree_id2);
4148 if (err)
4149 goto done;
4151 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
4152 got_diff_tree_collect_changed_paths, paths, 0);
4153 done:
4154 if (tree1)
4155 got_object_tree_close(tree1);
4156 if (tree2)
4157 got_object_tree_close(tree2);
4158 free(tree_id1);
4159 return err;
4162 static const struct got_error *
4163 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4164 off_t off, uint8_t type)
4166 struct got_diff_line *p;
4168 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4169 if (p == NULL)
4170 return got_error_from_errno("reallocarray");
4171 *lines = p;
4172 (*lines)[*nlines].offset = off;
4173 (*lines)[*nlines].type = type;
4174 (*nlines)++;
4176 return NULL;
4179 static const struct got_error *
4180 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4181 struct got_object_id *commit_id, struct got_reflist_head *refs,
4182 struct got_repository *repo, FILE *outfile)
4184 const struct got_error *err = NULL;
4185 char datebuf[26], *datestr;
4186 struct got_commit_object *commit;
4187 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4188 time_t committer_time;
4189 const char *author, *committer;
4190 char *refs_str = NULL;
4191 struct got_pathlist_head changed_paths;
4192 struct got_pathlist_entry *pe;
4193 off_t outoff = 0;
4194 int n;
4196 TAILQ_INIT(&changed_paths);
4198 if (refs) {
4199 err = build_refs_str(&refs_str, refs, commit_id, repo);
4200 if (err)
4201 return err;
4204 err = got_object_open_as_commit(&commit, repo, commit_id);
4205 if (err)
4206 return err;
4208 err = got_object_id_str(&id_str, commit_id);
4209 if (err) {
4210 err = got_error_from_errno("got_object_id_str");
4211 goto done;
4214 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4215 if (err)
4216 goto done;
4218 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4219 refs_str ? refs_str : "", refs_str ? ")" : "");
4220 if (n < 0) {
4221 err = got_error_from_errno("fprintf");
4222 goto done;
4224 outoff += n;
4225 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4226 if (err)
4227 goto done;
4229 n = fprintf(outfile, "from: %s\n",
4230 got_object_commit_get_author(commit));
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, GOT_DIFF_LINE_AUTHOR);
4237 if (err)
4238 goto done;
4240 committer_time = got_object_commit_get_committer_time(commit);
4241 datestr = get_datestr(&committer_time, datebuf);
4242 if (datestr) {
4243 n = fprintf(outfile, "date: %s UTC\n", datestr);
4244 if (n < 0) {
4245 err = got_error_from_errno("fprintf");
4246 goto done;
4248 outoff += n;
4249 err = add_line_metadata(lines, nlines, outoff,
4250 GOT_DIFF_LINE_DATE);
4251 if (err)
4252 goto done;
4254 author = got_object_commit_get_author(commit);
4255 committer = got_object_commit_get_committer(commit);
4256 if (strcmp(author, committer) != 0) {
4257 n = fprintf(outfile, "via: %s\n", committer);
4258 if (n < 0) {
4259 err = got_error_from_errno("fprintf");
4260 goto done;
4262 outoff += n;
4263 err = add_line_metadata(lines, nlines, outoff,
4264 GOT_DIFF_LINE_AUTHOR);
4265 if (err)
4266 goto done;
4268 if (got_object_commit_get_nparents(commit) > 1) {
4269 const struct got_object_id_queue *parent_ids;
4270 struct got_object_qid *qid;
4271 int pn = 1;
4272 parent_ids = got_object_commit_get_parent_ids(commit);
4273 STAILQ_FOREACH(qid, parent_ids, entry) {
4274 err = got_object_id_str(&id_str, &qid->id);
4275 if (err)
4276 goto done;
4277 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4278 if (n < 0) {
4279 err = got_error_from_errno("fprintf");
4280 goto done;
4282 outoff += n;
4283 err = add_line_metadata(lines, nlines, outoff,
4284 GOT_DIFF_LINE_META);
4285 if (err)
4286 goto done;
4287 free(id_str);
4288 id_str = NULL;
4292 err = got_object_commit_get_logmsg(&logmsg, commit);
4293 if (err)
4294 goto done;
4295 s = logmsg;
4296 while ((line = strsep(&s, "\n")) != NULL) {
4297 n = fprintf(outfile, "%s\n", line);
4298 if (n < 0) {
4299 err = got_error_from_errno("fprintf");
4300 goto done;
4302 outoff += n;
4303 err = add_line_metadata(lines, nlines, outoff,
4304 GOT_DIFF_LINE_LOGMSG);
4305 if (err)
4306 goto done;
4309 err = get_changed_paths(&changed_paths, commit, repo);
4310 if (err)
4311 goto done;
4312 TAILQ_FOREACH(pe, &changed_paths, entry) {
4313 struct got_diff_changed_path *cp = pe->data;
4314 n = fprintf(outfile, "%c %s\n", cp->status, pe->path);
4315 if (n < 0) {
4316 err = got_error_from_errno("fprintf");
4317 goto done;
4319 outoff += n;
4320 err = add_line_metadata(lines, nlines, outoff,
4321 GOT_DIFF_LINE_CHANGES);
4322 if (err)
4323 goto done;
4324 free((char *)pe->path);
4325 free(pe->data);
4328 fputc('\n', outfile);
4329 outoff++;
4330 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4331 done:
4332 got_pathlist_free(&changed_paths);
4333 free(id_str);
4334 free(logmsg);
4335 free(refs_str);
4336 got_object_commit_close(commit);
4337 if (err) {
4338 free(*lines);
4339 *lines = NULL;
4340 *nlines = 0;
4342 return err;
4345 static const struct got_error *
4346 create_diff(struct tog_diff_view_state *s)
4348 const struct got_error *err = NULL;
4349 FILE *f = NULL;
4350 int obj_type;
4352 free(s->lines);
4353 s->lines = malloc(sizeof(*s->lines));
4354 if (s->lines == NULL)
4355 return got_error_from_errno("malloc");
4356 s->nlines = 0;
4358 f = got_opentemp();
4359 if (f == NULL) {
4360 err = got_error_from_errno("got_opentemp");
4361 goto done;
4363 if (s->f && fclose(s->f) == EOF) {
4364 err = got_error_from_errno("fclose");
4365 goto done;
4367 s->f = f;
4369 if (s->id1)
4370 err = got_object_get_type(&obj_type, s->repo, s->id1);
4371 else
4372 err = got_object_get_type(&obj_type, s->repo, s->id2);
4373 if (err)
4374 goto done;
4376 switch (obj_type) {
4377 case GOT_OBJ_TYPE_BLOB:
4378 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
4379 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4380 s->label1, s->label2, tog_diff_algo, s->diff_context,
4381 s->ignore_whitespace, s->force_text_diff, s->repo, s->f);
4382 break;
4383 case GOT_OBJ_TYPE_TREE:
4384 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
4385 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4386 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4387 s->force_text_diff, s->repo, s->f);
4388 break;
4389 case GOT_OBJ_TYPE_COMMIT: {
4390 const struct got_object_id_queue *parent_ids;
4391 struct got_object_qid *pid;
4392 struct got_commit_object *commit2;
4393 struct got_reflist_head *refs;
4395 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4396 if (err)
4397 goto done;
4398 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4399 /* Show commit info if we're diffing to a parent/root commit. */
4400 if (s->id1 == NULL) {
4401 err = write_commit_info(&s->lines, &s->nlines, s->id2,
4402 refs, s->repo, s->f);
4403 if (err)
4404 goto done;
4405 } else {
4406 parent_ids = got_object_commit_get_parent_ids(commit2);
4407 STAILQ_FOREACH(pid, parent_ids, entry) {
4408 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4409 err = write_commit_info(&s->lines,
4410 &s->nlines, s->id2, refs, s->repo,
4411 s->f);
4412 if (err)
4413 goto done;
4414 break;
4418 got_object_commit_close(commit2);
4420 err = got_diff_objects_as_commits(&s->lines, &s->nlines,
4421 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4422 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4423 s->force_text_diff, s->repo, s->f);
4424 break;
4426 default:
4427 err = got_error(GOT_ERR_OBJ_TYPE);
4428 break;
4430 done:
4431 if (s->f && fflush(s->f) != 0 && err == NULL)
4432 err = got_error_from_errno("fflush");
4433 return err;
4436 static void
4437 diff_view_indicate_progress(struct tog_view *view)
4439 mvwaddstr(view->window, 0, 0, "diffing...");
4440 update_panels();
4441 doupdate();
4444 static const struct got_error *
4445 search_start_diff_view(struct tog_view *view)
4447 struct tog_diff_view_state *s = &view->state.diff;
4449 s->matched_line = 0;
4450 return NULL;
4453 static const struct got_error *
4454 search_next_diff_view(struct tog_view *view)
4456 struct tog_diff_view_state *s = &view->state.diff;
4457 const struct got_error *err = NULL;
4458 int lineno;
4459 char *line = NULL;
4460 size_t linesize = 0;
4461 ssize_t linelen;
4463 if (!view->searching) {
4464 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4465 return NULL;
4468 if (s->matched_line) {
4469 if (view->searching == TOG_SEARCH_FORWARD)
4470 lineno = s->matched_line + 1;
4471 else
4472 lineno = s->matched_line - 1;
4473 } else
4474 lineno = s->first_displayed_line;
4476 while (1) {
4477 off_t offset;
4479 if (lineno <= 0 || lineno > s->nlines) {
4480 if (s->matched_line == 0) {
4481 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4482 break;
4485 if (view->searching == TOG_SEARCH_FORWARD)
4486 lineno = 1;
4487 else
4488 lineno = s->nlines;
4491 offset = s->lines[lineno - 1].offset;
4492 if (fseeko(s->f, offset, SEEK_SET) != 0) {
4493 free(line);
4494 return got_error_from_errno("fseeko");
4496 linelen = getline(&line, &linesize, s->f);
4497 if (linelen != -1) {
4498 char *exstr;
4499 err = expand_tab(&exstr, line);
4500 if (err)
4501 break;
4502 if (match_line(exstr, &view->regex, 1,
4503 &view->regmatch)) {
4504 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4505 s->matched_line = lineno;
4506 free(exstr);
4507 break;
4509 free(exstr);
4511 if (view->searching == TOG_SEARCH_FORWARD)
4512 lineno++;
4513 else
4514 lineno--;
4516 free(line);
4518 if (s->matched_line) {
4519 s->first_displayed_line = s->matched_line;
4520 s->selected_line = 1;
4523 return err;
4526 static const struct got_error *
4527 close_diff_view(struct tog_view *view)
4529 const struct got_error *err = NULL;
4530 struct tog_diff_view_state *s = &view->state.diff;
4532 free(s->id1);
4533 s->id1 = NULL;
4534 free(s->id2);
4535 s->id2 = NULL;
4536 if (s->f && fclose(s->f) == EOF)
4537 err = got_error_from_errno("fclose");
4538 s->f = NULL;
4539 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
4540 err = got_error_from_errno("fclose");
4541 s->f1 = NULL;
4542 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
4543 err = got_error_from_errno("fclose");
4544 s->f2 = NULL;
4545 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
4546 err = got_error_from_errno("close");
4547 s->fd1 = -1;
4548 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
4549 err = got_error_from_errno("close");
4550 s->fd2 = -1;
4551 free(s->lines);
4552 s->lines = NULL;
4553 s->nlines = 0;
4554 return err;
4557 static const struct got_error *
4558 open_diff_view(struct tog_view *view, struct got_object_id *id1,
4559 struct got_object_id *id2, const char *label1, const char *label2,
4560 int diff_context, int ignore_whitespace, int force_text_diff,
4561 struct tog_view *parent_view, struct got_repository *repo)
4563 const struct got_error *err;
4564 struct tog_diff_view_state *s = &view->state.diff;
4566 memset(s, 0, sizeof(*s));
4567 s->fd1 = -1;
4568 s->fd2 = -1;
4570 if (id1 != NULL && id2 != NULL) {
4571 int type1, type2;
4572 err = got_object_get_type(&type1, repo, id1);
4573 if (err)
4574 return err;
4575 err = got_object_get_type(&type2, repo, id2);
4576 if (err)
4577 return err;
4579 if (type1 != type2)
4580 return got_error(GOT_ERR_OBJ_TYPE);
4582 s->first_displayed_line = 1;
4583 s->last_displayed_line = view->nlines;
4584 s->selected_line = 1;
4585 s->repo = repo;
4586 s->id1 = id1;
4587 s->id2 = id2;
4588 s->label1 = label1;
4589 s->label2 = label2;
4591 if (id1) {
4592 s->id1 = got_object_id_dup(id1);
4593 if (s->id1 == NULL)
4594 return got_error_from_errno("got_object_id_dup");
4595 } else
4596 s->id1 = NULL;
4598 s->id2 = got_object_id_dup(id2);
4599 if (s->id2 == NULL) {
4600 err = got_error_from_errno("got_object_id_dup");
4601 goto done;
4604 s->f1 = got_opentemp();
4605 if (s->f1 == NULL) {
4606 err = got_error_from_errno("got_opentemp");
4607 goto done;
4610 s->f2 = got_opentemp();
4611 if (s->f2 == NULL) {
4612 err = got_error_from_errno("got_opentemp");
4613 goto done;
4616 s->fd1 = got_opentempfd();
4617 if (s->fd1 == -1) {
4618 err = got_error_from_errno("got_opentempfd");
4619 goto done;
4622 s->fd2 = got_opentempfd();
4623 if (s->fd2 == -1) {
4624 err = got_error_from_errno("got_opentempfd");
4625 goto done;
4628 s->first_displayed_line = 1;
4629 s->last_displayed_line = view->nlines;
4630 s->diff_context = diff_context;
4631 s->ignore_whitespace = ignore_whitespace;
4632 s->force_text_diff = force_text_diff;
4633 s->parent_view = parent_view;
4634 s->repo = repo;
4636 if (has_colors() && getenv("TOG_COLORS") != NULL) {
4637 int rc;
4639 rc = init_pair(GOT_DIFF_LINE_MINUS,
4640 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
4641 if (rc != ERR)
4642 rc = init_pair(GOT_DIFF_LINE_PLUS,
4643 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
4644 if (rc != ERR)
4645 rc = init_pair(GOT_DIFF_LINE_HUNK,
4646 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
4647 if (rc != ERR)
4648 rc = init_pair(GOT_DIFF_LINE_META,
4649 get_color_value("TOG_COLOR_DIFF_META"), -1);
4650 if (rc != ERR)
4651 rc = init_pair(GOT_DIFF_LINE_CHANGES,
4652 get_color_value("TOG_COLOR_DIFF_META"), -1);
4653 if (rc != ERR)
4654 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
4655 get_color_value("TOG_COLOR_DIFF_META"), -1);
4656 if (rc != ERR)
4657 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
4658 get_color_value("TOG_COLOR_DIFF_META"), -1);
4659 if (rc != ERR)
4660 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
4661 get_color_value("TOG_COLOR_AUTHOR"), -1);
4662 if (rc != ERR)
4663 rc = init_pair(GOT_DIFF_LINE_DATE,
4664 get_color_value("TOG_COLOR_DATE"), -1);
4665 if (rc == ERR) {
4666 err = got_error(GOT_ERR_RANGE);
4667 goto done;
4671 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
4672 view_is_splitscreen(view))
4673 show_log_view(parent_view); /* draw border */
4674 diff_view_indicate_progress(view);
4676 err = create_diff(s);
4678 view->show = show_diff_view;
4679 view->input = input_diff_view;
4680 view->reset = reset_diff_view;
4681 view->close = close_diff_view;
4682 view->search_start = search_start_diff_view;
4683 view->search_next = search_next_diff_view;
4684 done:
4685 if (err)
4686 close_diff_view(view);
4687 return err;
4690 static const struct got_error *
4691 show_diff_view(struct tog_view *view)
4693 const struct got_error *err;
4694 struct tog_diff_view_state *s = &view->state.diff;
4695 char *id_str1 = NULL, *id_str2, *header;
4696 const char *label1, *label2;
4698 if (s->id1) {
4699 err = got_object_id_str(&id_str1, s->id1);
4700 if (err)
4701 return err;
4702 label1 = s->label1 ? s->label1 : id_str1;
4703 } else
4704 label1 = "/dev/null";
4706 err = got_object_id_str(&id_str2, s->id2);
4707 if (err)
4708 return err;
4709 label2 = s->label2 ? s->label2 : id_str2;
4711 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
4712 err = got_error_from_errno("asprintf");
4713 free(id_str1);
4714 free(id_str2);
4715 return err;
4717 free(id_str1);
4718 free(id_str2);
4720 err = draw_file(view, header);
4721 free(header);
4722 return err;
4725 static const struct got_error *
4726 set_selected_commit(struct tog_diff_view_state *s,
4727 struct commit_queue_entry *entry)
4729 const struct got_error *err;
4730 const struct got_object_id_queue *parent_ids;
4731 struct got_commit_object *selected_commit;
4732 struct got_object_qid *pid;
4734 free(s->id2);
4735 s->id2 = got_object_id_dup(entry->id);
4736 if (s->id2 == NULL)
4737 return got_error_from_errno("got_object_id_dup");
4739 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
4740 if (err)
4741 return err;
4742 parent_ids = got_object_commit_get_parent_ids(selected_commit);
4743 free(s->id1);
4744 pid = STAILQ_FIRST(parent_ids);
4745 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
4746 got_object_commit_close(selected_commit);
4747 return NULL;
4750 static const struct got_error *
4751 reset_diff_view(struct tog_view *view)
4753 struct tog_diff_view_state *s = &view->state.diff;
4755 view->count = 0;
4756 wclear(view->window);
4757 s->first_displayed_line = 1;
4758 s->last_displayed_line = view->nlines;
4759 s->matched_line = 0;
4760 diff_view_indicate_progress(view);
4761 return create_diff(s);
4764 static void
4765 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
4767 int start, i;
4769 i = start = s->first_displayed_line - 1;
4771 while (s->lines[i].type != type) {
4772 if (i == 0)
4773 i = s->nlines - 1;
4774 if (--i == start)
4775 return; /* do nothing, requested type not in file */
4778 s->selected_line = 1;
4779 s->first_displayed_line = i;
4782 static void
4783 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
4785 int start, i;
4787 i = start = s->first_displayed_line + 1;
4789 while (s->lines[i].type != type) {
4790 if (i == s->nlines - 1)
4791 i = 0;
4792 if (++i == start)
4793 return; /* do nothing, requested type not in file */
4796 s->selected_line = 1;
4797 s->first_displayed_line = i;
4800 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
4801 int, int, int);
4802 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
4803 int, int);
4805 static const struct got_error *
4806 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
4808 const struct got_error *err = NULL;
4809 struct tog_diff_view_state *s = &view->state.diff;
4810 struct tog_log_view_state *ls;
4811 struct commit_queue_entry *old_selected_entry;
4812 char *line = NULL;
4813 size_t linesize = 0;
4814 ssize_t linelen;
4815 int i, nscroll = view->nlines - 1, up = 0;
4817 s->lineno = s->first_displayed_line - 1 + s->selected_line;
4819 switch (ch) {
4820 case '0':
4821 view->x = 0;
4822 break;
4823 case '$':
4824 view->x = MAX(view->maxx - view->ncols / 3, 0);
4825 view->count = 0;
4826 break;
4827 case KEY_RIGHT:
4828 case 'l':
4829 if (view->x + view->ncols / 3 < view->maxx)
4830 view->x += 2; /* move two columns right */
4831 else
4832 view->count = 0;
4833 break;
4834 case KEY_LEFT:
4835 case 'h':
4836 view->x -= MIN(view->x, 2); /* move two columns back */
4837 if (view->x <= 0)
4838 view->count = 0;
4839 break;
4840 case 'a':
4841 case 'w':
4842 if (ch == 'a')
4843 s->force_text_diff = !s->force_text_diff;
4844 if (ch == 'w')
4845 s->ignore_whitespace = !s->ignore_whitespace;
4846 err = reset_diff_view(view);
4847 break;
4848 case 'g':
4849 case KEY_HOME:
4850 s->first_displayed_line = 1;
4851 view->count = 0;
4852 break;
4853 case 'G':
4854 case KEY_END:
4855 view->count = 0;
4856 if (s->eof)
4857 break;
4859 s->first_displayed_line = (s->nlines - view->nlines) + 2;
4860 s->eof = 1;
4861 break;
4862 case 'k':
4863 case KEY_UP:
4864 case CTRL('p'):
4865 if (s->first_displayed_line > 1)
4866 s->first_displayed_line--;
4867 else
4868 view->count = 0;
4869 break;
4870 case CTRL('u'):
4871 case 'u':
4872 nscroll /= 2;
4873 /* FALL THROUGH */
4874 case KEY_PPAGE:
4875 case CTRL('b'):
4876 case 'b':
4877 if (s->first_displayed_line == 1) {
4878 view->count = 0;
4879 break;
4881 i = 0;
4882 while (i++ < nscroll && s->first_displayed_line > 1)
4883 s->first_displayed_line--;
4884 break;
4885 case 'j':
4886 case KEY_DOWN:
4887 case CTRL('n'):
4888 if (!s->eof)
4889 s->first_displayed_line++;
4890 else
4891 view->count = 0;
4892 break;
4893 case CTRL('d'):
4894 case 'd':
4895 nscroll /= 2;
4896 /* FALL THROUGH */
4897 case KEY_NPAGE:
4898 case CTRL('f'):
4899 case 'f':
4900 case ' ':
4901 if (s->eof) {
4902 view->count = 0;
4903 break;
4905 i = 0;
4906 while (!s->eof && i++ < nscroll) {
4907 linelen = getline(&line, &linesize, s->f);
4908 s->first_displayed_line++;
4909 if (linelen == -1) {
4910 if (feof(s->f)) {
4911 s->eof = 1;
4912 } else
4913 err = got_ferror(s->f, GOT_ERR_IO);
4914 break;
4917 free(line);
4918 break;
4919 case '(':
4920 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
4921 break;
4922 case ')':
4923 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
4924 break;
4925 case '{':
4926 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
4927 break;
4928 case '}':
4929 diff_next_index(s, GOT_DIFF_LINE_HUNK);
4930 break;
4931 case '[':
4932 if (s->diff_context > 0) {
4933 s->diff_context--;
4934 s->matched_line = 0;
4935 diff_view_indicate_progress(view);
4936 err = create_diff(s);
4937 if (s->first_displayed_line + view->nlines - 1 >
4938 s->nlines) {
4939 s->first_displayed_line = 1;
4940 s->last_displayed_line = view->nlines;
4942 } else
4943 view->count = 0;
4944 break;
4945 case ']':
4946 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
4947 s->diff_context++;
4948 s->matched_line = 0;
4949 diff_view_indicate_progress(view);
4950 err = create_diff(s);
4951 } else
4952 view->count = 0;
4953 break;
4954 case '<':
4955 case ',':
4956 case 'K':
4957 up = 1;
4958 /* FALL THROUGH */
4959 case '>':
4960 case '.':
4961 case 'J':
4962 if (s->parent_view == NULL) {
4963 view->count = 0;
4964 break;
4966 s->parent_view->count = view->count;
4968 if (s->parent_view->type == TOG_VIEW_LOG) {
4969 ls = &s->parent_view->state.log;
4970 old_selected_entry = ls->selected_entry;
4972 err = input_log_view(NULL, s->parent_view,
4973 up ? KEY_UP : KEY_DOWN);
4974 if (err)
4975 break;
4976 view->count = s->parent_view->count;
4978 if (old_selected_entry == ls->selected_entry)
4979 break;
4981 err = set_selected_commit(s, ls->selected_entry);
4982 if (err)
4983 break;
4984 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
4985 struct tog_blame_view_state *bs;
4986 struct got_object_id *id, *prev_id;
4988 bs = &s->parent_view->state.blame;
4989 prev_id = get_annotation_for_line(bs->blame.lines,
4990 bs->blame.nlines, bs->last_diffed_line);
4992 err = input_blame_view(&view, s->parent_view,
4993 up ? KEY_UP : KEY_DOWN);
4994 if (err)
4995 break;
4996 view->count = s->parent_view->count;
4998 if (prev_id == NULL)
4999 break;
5000 id = get_selected_commit_id(bs->blame.lines,
5001 bs->blame.nlines, bs->first_displayed_line,
5002 bs->selected_line);
5003 if (id == NULL)
5004 break;
5006 if (!got_object_id_cmp(prev_id, id))
5007 break;
5009 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5010 if (err)
5011 break;
5013 s->first_displayed_line = 1;
5014 s->last_displayed_line = view->nlines;
5015 s->matched_line = 0;
5016 view->x = 0;
5018 diff_view_indicate_progress(view);
5019 err = create_diff(s);
5020 break;
5021 default:
5022 view->count = 0;
5023 break;
5026 return err;
5029 static const struct got_error *
5030 cmd_diff(int argc, char *argv[])
5032 const struct got_error *error = NULL;
5033 struct got_repository *repo = NULL;
5034 struct got_worktree *worktree = NULL;
5035 struct got_object_id *id1 = NULL, *id2 = NULL;
5036 char *repo_path = NULL, *cwd = NULL;
5037 char *id_str1 = NULL, *id_str2 = NULL;
5038 char *label1 = NULL, *label2 = NULL;
5039 int diff_context = 3, ignore_whitespace = 0;
5040 int ch, force_text_diff = 0;
5041 const char *errstr;
5042 struct tog_view *view;
5043 int *pack_fds = NULL;
5045 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5046 switch (ch) {
5047 case 'a':
5048 force_text_diff = 1;
5049 break;
5050 case 'C':
5051 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5052 &errstr);
5053 if (errstr != NULL)
5054 errx(1, "number of context lines is %s: %s",
5055 errstr, errstr);
5056 break;
5057 case 'r':
5058 repo_path = realpath(optarg, NULL);
5059 if (repo_path == NULL)
5060 return got_error_from_errno2("realpath",
5061 optarg);
5062 got_path_strip_trailing_slashes(repo_path);
5063 break;
5064 case 'w':
5065 ignore_whitespace = 1;
5066 break;
5067 default:
5068 usage_diff();
5069 /* NOTREACHED */
5073 argc -= optind;
5074 argv += optind;
5076 if (argc == 0) {
5077 usage_diff(); /* TODO show local worktree changes */
5078 } else if (argc == 2) {
5079 id_str1 = argv[0];
5080 id_str2 = argv[1];
5081 } else
5082 usage_diff();
5084 error = got_repo_pack_fds_open(&pack_fds);
5085 if (error)
5086 goto done;
5088 if (repo_path == NULL) {
5089 cwd = getcwd(NULL, 0);
5090 if (cwd == NULL)
5091 return got_error_from_errno("getcwd");
5092 error = got_worktree_open(&worktree, cwd);
5093 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5094 goto done;
5095 if (worktree)
5096 repo_path =
5097 strdup(got_worktree_get_repo_path(worktree));
5098 else
5099 repo_path = strdup(cwd);
5100 if (repo_path == NULL) {
5101 error = got_error_from_errno("strdup");
5102 goto done;
5106 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5107 if (error)
5108 goto done;
5110 init_curses();
5112 error = apply_unveil(got_repo_get_path(repo), NULL);
5113 if (error)
5114 goto done;
5116 error = tog_load_refs(repo, 0);
5117 if (error)
5118 goto done;
5120 error = got_repo_match_object_id(&id1, &label1, id_str1,
5121 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5122 if (error)
5123 goto done;
5125 error = got_repo_match_object_id(&id2, &label2, id_str2,
5126 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5127 if (error)
5128 goto done;
5130 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5131 if (view == NULL) {
5132 error = got_error_from_errno("view_open");
5133 goto done;
5135 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5136 ignore_whitespace, force_text_diff, NULL, repo);
5137 if (error)
5138 goto done;
5139 error = view_loop(view);
5140 done:
5141 free(label1);
5142 free(label2);
5143 free(repo_path);
5144 free(cwd);
5145 if (repo) {
5146 const struct got_error *close_err = got_repo_close(repo);
5147 if (error == NULL)
5148 error = close_err;
5150 if (worktree)
5151 got_worktree_close(worktree);
5152 if (pack_fds) {
5153 const struct got_error *pack_err =
5154 got_repo_pack_fds_close(pack_fds);
5155 if (error == NULL)
5156 error = pack_err;
5158 tog_free_refs();
5159 return error;
5162 __dead static void
5163 usage_blame(void)
5165 endwin();
5166 fprintf(stderr,
5167 "usage: %s blame [-c commit] [-r repository-path] path\n",
5168 getprogname());
5169 exit(1);
5172 struct tog_blame_line {
5173 int annotated;
5174 struct got_object_id *id;
5177 static const struct got_error *
5178 draw_blame(struct tog_view *view)
5180 struct tog_blame_view_state *s = &view->state.blame;
5181 struct tog_blame *blame = &s->blame;
5182 regmatch_t *regmatch = &view->regmatch;
5183 const struct got_error *err;
5184 int lineno = 0, nprinted = 0;
5185 char *line = NULL;
5186 size_t linesize = 0;
5187 ssize_t linelen;
5188 wchar_t *wline;
5189 int width;
5190 struct tog_blame_line *blame_line;
5191 struct got_object_id *prev_id = NULL;
5192 char *id_str;
5193 struct tog_color *tc;
5195 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5196 if (err)
5197 return err;
5199 rewind(blame->f);
5200 werase(view->window);
5202 if (asprintf(&line, "commit %s", id_str) == -1) {
5203 err = got_error_from_errno("asprintf");
5204 free(id_str);
5205 return err;
5208 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5209 free(line);
5210 line = NULL;
5211 if (err)
5212 return err;
5213 if (view_needs_focus_indication(view))
5214 wstandout(view->window);
5215 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5216 if (tc)
5217 wattr_on(view->window,
5218 COLOR_PAIR(tc->colorpair), NULL);
5219 waddwstr(view->window, wline);
5220 if (tc)
5221 wattr_off(view->window,
5222 COLOR_PAIR(tc->colorpair), NULL);
5223 if (view_needs_focus_indication(view))
5224 wstandend(view->window);
5225 free(wline);
5226 wline = NULL;
5227 if (width < view->ncols - 1)
5228 waddch(view->window, '\n');
5230 if (view->gline > blame->nlines)
5231 view->gline = blame->nlines;
5233 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5234 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5235 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5236 free(id_str);
5237 return got_error_from_errno("asprintf");
5239 free(id_str);
5240 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5241 free(line);
5242 line = NULL;
5243 if (err)
5244 return err;
5245 waddwstr(view->window, wline);
5246 free(wline);
5247 wline = NULL;
5248 if (width < view->ncols - 1)
5249 waddch(view->window, '\n');
5251 s->eof = 0;
5252 view->maxx = 0;
5253 while (nprinted < view->nlines - 2) {
5254 linelen = getline(&line, &linesize, blame->f);
5255 if (linelen == -1) {
5256 if (feof(blame->f)) {
5257 s->eof = 1;
5258 break;
5260 free(line);
5261 return got_ferror(blame->f, GOT_ERR_IO);
5263 if (++lineno < s->first_displayed_line)
5264 continue;
5265 if (view->gline && !gotoline(view, &lineno, &nprinted))
5266 continue;
5268 /* Set view->maxx based on full line length. */
5269 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5270 if (err) {
5271 free(line);
5272 return err;
5274 free(wline);
5275 wline = NULL;
5276 view->maxx = MAX(view->maxx, width);
5278 if (nprinted == s->selected_line - 1)
5279 wstandout(view->window);
5281 if (blame->nlines > 0) {
5282 blame_line = &blame->lines[lineno - 1];
5283 if (blame_line->annotated && prev_id &&
5284 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5285 !(nprinted == s->selected_line - 1)) {
5286 waddstr(view->window, " ");
5287 } else if (blame_line->annotated) {
5288 char *id_str;
5289 err = got_object_id_str(&id_str,
5290 blame_line->id);
5291 if (err) {
5292 free(line);
5293 return err;
5295 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5296 if (tc)
5297 wattr_on(view->window,
5298 COLOR_PAIR(tc->colorpair), NULL);
5299 wprintw(view->window, "%.8s", id_str);
5300 if (tc)
5301 wattr_off(view->window,
5302 COLOR_PAIR(tc->colorpair), NULL);
5303 free(id_str);
5304 prev_id = blame_line->id;
5305 } else {
5306 waddstr(view->window, "........");
5307 prev_id = NULL;
5309 } else {
5310 waddstr(view->window, "........");
5311 prev_id = NULL;
5314 if (nprinted == s->selected_line - 1)
5315 wstandend(view->window);
5316 waddstr(view->window, " ");
5318 if (view->ncols <= 9) {
5319 width = 9;
5320 } else if (s->first_displayed_line + nprinted ==
5321 s->matched_line &&
5322 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5323 err = add_matched_line(&width, line, view->ncols - 9, 9,
5324 view->window, view->x, regmatch);
5325 if (err) {
5326 free(line);
5327 return err;
5329 width += 9;
5330 } else {
5331 int skip;
5332 err = format_line(&wline, &width, &skip, line,
5333 view->x, view->ncols - 9, 9, 1);
5334 if (err) {
5335 free(line);
5336 return err;
5338 waddwstr(view->window, &wline[skip]);
5339 width += 9;
5340 free(wline);
5341 wline = NULL;
5344 if (width <= view->ncols - 1)
5345 waddch(view->window, '\n');
5346 if (++nprinted == 1)
5347 s->first_displayed_line = lineno;
5349 free(line);
5350 s->last_displayed_line = lineno;
5352 view_border(view);
5354 return NULL;
5357 static const struct got_error *
5358 blame_cb(void *arg, int nlines, int lineno,
5359 struct got_commit_object *commit, struct got_object_id *id)
5361 const struct got_error *err = NULL;
5362 struct tog_blame_cb_args *a = arg;
5363 struct tog_blame_line *line;
5364 int errcode;
5366 if (nlines != a->nlines ||
5367 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5368 return got_error(GOT_ERR_RANGE);
5370 errcode = pthread_mutex_lock(&tog_mutex);
5371 if (errcode)
5372 return got_error_set_errno(errcode, "pthread_mutex_lock");
5374 if (*a->quit) { /* user has quit the blame view */
5375 err = got_error(GOT_ERR_ITER_COMPLETED);
5376 goto done;
5379 if (lineno == -1)
5380 goto done; /* no change in this commit */
5382 line = &a->lines[lineno - 1];
5383 if (line->annotated)
5384 goto done;
5386 line->id = got_object_id_dup(id);
5387 if (line->id == NULL) {
5388 err = got_error_from_errno("got_object_id_dup");
5389 goto done;
5391 line->annotated = 1;
5392 done:
5393 errcode = pthread_mutex_unlock(&tog_mutex);
5394 if (errcode)
5395 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5396 return err;
5399 static void *
5400 blame_thread(void *arg)
5402 const struct got_error *err, *close_err;
5403 struct tog_blame_thread_args *ta = arg;
5404 struct tog_blame_cb_args *a = ta->cb_args;
5405 int errcode, fd1 = -1, fd2 = -1;
5406 FILE *f1 = NULL, *f2 = NULL;
5408 fd1 = got_opentempfd();
5409 if (fd1 == -1)
5410 return (void *)got_error_from_errno("got_opentempfd");
5412 fd2 = got_opentempfd();
5413 if (fd2 == -1) {
5414 err = got_error_from_errno("got_opentempfd");
5415 goto done;
5418 f1 = got_opentemp();
5419 if (f1 == NULL) {
5420 err = (void *)got_error_from_errno("got_opentemp");
5421 goto done;
5423 f2 = got_opentemp();
5424 if (f2 == NULL) {
5425 err = (void *)got_error_from_errno("got_opentemp");
5426 goto done;
5429 err = block_signals_used_by_main_thread();
5430 if (err)
5431 goto done;
5433 err = got_blame(ta->path, a->commit_id, ta->repo,
5434 tog_diff_algo, blame_cb, ta->cb_args,
5435 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5436 if (err && err->code == GOT_ERR_CANCELLED)
5437 err = NULL;
5439 errcode = pthread_mutex_lock(&tog_mutex);
5440 if (errcode) {
5441 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5442 goto done;
5445 close_err = got_repo_close(ta->repo);
5446 if (err == NULL)
5447 err = close_err;
5448 ta->repo = NULL;
5449 *ta->complete = 1;
5451 errcode = pthread_mutex_unlock(&tog_mutex);
5452 if (errcode && err == NULL)
5453 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5455 done:
5456 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5457 err = got_error_from_errno("close");
5458 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5459 err = got_error_from_errno("close");
5460 if (f1 && fclose(f1) == EOF && err == NULL)
5461 err = got_error_from_errno("fclose");
5462 if (f2 && fclose(f2) == EOF && err == NULL)
5463 err = got_error_from_errno("fclose");
5465 return (void *)err;
5468 static struct got_object_id *
5469 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5470 int first_displayed_line, int selected_line)
5472 struct tog_blame_line *line;
5474 if (nlines <= 0)
5475 return NULL;
5477 line = &lines[first_displayed_line - 1 + selected_line - 1];
5478 if (!line->annotated)
5479 return NULL;
5481 return line->id;
5484 static struct got_object_id *
5485 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5486 int lineno)
5488 struct tog_blame_line *line;
5490 if (nlines <= 0 || lineno >= nlines)
5491 return NULL;
5493 line = &lines[lineno - 1];
5494 if (!line->annotated)
5495 return NULL;
5497 return line->id;
5500 static const struct got_error *
5501 stop_blame(struct tog_blame *blame)
5503 const struct got_error *err = NULL;
5504 int i;
5506 if (blame->thread) {
5507 int errcode;
5508 errcode = pthread_mutex_unlock(&tog_mutex);
5509 if (errcode)
5510 return got_error_set_errno(errcode,
5511 "pthread_mutex_unlock");
5512 errcode = pthread_join(blame->thread, (void **)&err);
5513 if (errcode)
5514 return got_error_set_errno(errcode, "pthread_join");
5515 errcode = pthread_mutex_lock(&tog_mutex);
5516 if (errcode)
5517 return got_error_set_errno(errcode,
5518 "pthread_mutex_lock");
5519 if (err && err->code == GOT_ERR_ITER_COMPLETED)
5520 err = NULL;
5521 blame->thread = NULL;
5523 if (blame->thread_args.repo) {
5524 const struct got_error *close_err;
5525 close_err = got_repo_close(blame->thread_args.repo);
5526 if (err == NULL)
5527 err = close_err;
5528 blame->thread_args.repo = NULL;
5530 if (blame->f) {
5531 if (fclose(blame->f) == EOF && err == NULL)
5532 err = got_error_from_errno("fclose");
5533 blame->f = NULL;
5535 if (blame->lines) {
5536 for (i = 0; i < blame->nlines; i++)
5537 free(blame->lines[i].id);
5538 free(blame->lines);
5539 blame->lines = NULL;
5541 free(blame->cb_args.commit_id);
5542 blame->cb_args.commit_id = NULL;
5543 if (blame->pack_fds) {
5544 const struct got_error *pack_err =
5545 got_repo_pack_fds_close(blame->pack_fds);
5546 if (err == NULL)
5547 err = pack_err;
5548 blame->pack_fds = NULL;
5550 return err;
5553 static const struct got_error *
5554 cancel_blame_view(void *arg)
5556 const struct got_error *err = NULL;
5557 int *done = arg;
5558 int errcode;
5560 errcode = pthread_mutex_lock(&tog_mutex);
5561 if (errcode)
5562 return got_error_set_errno(errcode,
5563 "pthread_mutex_unlock");
5565 if (*done)
5566 err = got_error(GOT_ERR_CANCELLED);
5568 errcode = pthread_mutex_unlock(&tog_mutex);
5569 if (errcode)
5570 return got_error_set_errno(errcode,
5571 "pthread_mutex_lock");
5573 return err;
5576 static const struct got_error *
5577 run_blame(struct tog_view *view)
5579 struct tog_blame_view_state *s = &view->state.blame;
5580 struct tog_blame *blame = &s->blame;
5581 const struct got_error *err = NULL;
5582 struct got_commit_object *commit = NULL;
5583 struct got_blob_object *blob = NULL;
5584 struct got_repository *thread_repo = NULL;
5585 struct got_object_id *obj_id = NULL;
5586 int obj_type, fd = -1;
5587 int *pack_fds = NULL;
5589 err = got_object_open_as_commit(&commit, s->repo,
5590 &s->blamed_commit->id);
5591 if (err)
5592 return err;
5594 fd = got_opentempfd();
5595 if (fd == -1) {
5596 err = got_error_from_errno("got_opentempfd");
5597 goto done;
5600 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
5601 if (err)
5602 goto done;
5604 err = got_object_get_type(&obj_type, s->repo, obj_id);
5605 if (err)
5606 goto done;
5608 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5609 err = got_error(GOT_ERR_OBJ_TYPE);
5610 goto done;
5613 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
5614 if (err)
5615 goto done;
5616 blame->f = got_opentemp();
5617 if (blame->f == NULL) {
5618 err = got_error_from_errno("got_opentemp");
5619 goto done;
5621 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
5622 &blame->line_offsets, blame->f, blob);
5623 if (err)
5624 goto done;
5625 if (blame->nlines == 0) {
5626 s->blame_complete = 1;
5627 goto done;
5630 /* Don't include \n at EOF in the blame line count. */
5631 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
5632 blame->nlines--;
5634 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
5635 if (blame->lines == NULL) {
5636 err = got_error_from_errno("calloc");
5637 goto done;
5640 err = got_repo_pack_fds_open(&pack_fds);
5641 if (err)
5642 goto done;
5643 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
5644 pack_fds);
5645 if (err)
5646 goto done;
5648 blame->pack_fds = pack_fds;
5649 blame->cb_args.view = view;
5650 blame->cb_args.lines = blame->lines;
5651 blame->cb_args.nlines = blame->nlines;
5652 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
5653 if (blame->cb_args.commit_id == NULL) {
5654 err = got_error_from_errno("got_object_id_dup");
5655 goto done;
5657 blame->cb_args.quit = &s->done;
5659 blame->thread_args.path = s->path;
5660 blame->thread_args.repo = thread_repo;
5661 blame->thread_args.cb_args = &blame->cb_args;
5662 blame->thread_args.complete = &s->blame_complete;
5663 blame->thread_args.cancel_cb = cancel_blame_view;
5664 blame->thread_args.cancel_arg = &s->done;
5665 s->blame_complete = 0;
5667 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
5668 s->first_displayed_line = 1;
5669 s->last_displayed_line = view->nlines;
5670 s->selected_line = 1;
5672 s->matched_line = 0;
5674 done:
5675 if (commit)
5676 got_object_commit_close(commit);
5677 if (fd != -1 && close(fd) == -1 && err == NULL)
5678 err = got_error_from_errno("close");
5679 if (blob)
5680 got_object_blob_close(blob);
5681 free(obj_id);
5682 if (err)
5683 stop_blame(blame);
5684 return err;
5687 static const struct got_error *
5688 open_blame_view(struct tog_view *view, char *path,
5689 struct got_object_id *commit_id, struct got_repository *repo)
5691 const struct got_error *err = NULL;
5692 struct tog_blame_view_state *s = &view->state.blame;
5694 STAILQ_INIT(&s->blamed_commits);
5696 s->path = strdup(path);
5697 if (s->path == NULL)
5698 return got_error_from_errno("strdup");
5700 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
5701 if (err) {
5702 free(s->path);
5703 return err;
5706 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
5707 s->first_displayed_line = 1;
5708 s->last_displayed_line = view->nlines;
5709 s->selected_line = 1;
5710 s->blame_complete = 0;
5711 s->repo = repo;
5712 s->commit_id = commit_id;
5713 memset(&s->blame, 0, sizeof(s->blame));
5715 STAILQ_INIT(&s->colors);
5716 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5717 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
5718 get_color_value("TOG_COLOR_COMMIT"));
5719 if (err)
5720 return err;
5723 view->show = show_blame_view;
5724 view->input = input_blame_view;
5725 view->reset = reset_blame_view;
5726 view->close = close_blame_view;
5727 view->search_start = search_start_blame_view;
5728 view->search_next = search_next_blame_view;
5730 return run_blame(view);
5733 static const struct got_error *
5734 close_blame_view(struct tog_view *view)
5736 const struct got_error *err = NULL;
5737 struct tog_blame_view_state *s = &view->state.blame;
5739 if (s->blame.thread)
5740 err = stop_blame(&s->blame);
5742 while (!STAILQ_EMPTY(&s->blamed_commits)) {
5743 struct got_object_qid *blamed_commit;
5744 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
5745 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5746 got_object_qid_free(blamed_commit);
5749 free(s->path);
5750 free_colors(&s->colors);
5751 return err;
5754 static const struct got_error *
5755 search_start_blame_view(struct tog_view *view)
5757 struct tog_blame_view_state *s = &view->state.blame;
5759 s->matched_line = 0;
5760 return NULL;
5763 static const struct got_error *
5764 search_next_blame_view(struct tog_view *view)
5766 struct tog_blame_view_state *s = &view->state.blame;
5767 const struct got_error *err = NULL;
5768 int lineno;
5769 char *line = NULL;
5770 size_t linesize = 0;
5771 ssize_t linelen;
5773 if (!view->searching) {
5774 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5775 return NULL;
5778 if (s->matched_line) {
5779 if (view->searching == TOG_SEARCH_FORWARD)
5780 lineno = s->matched_line + 1;
5781 else
5782 lineno = s->matched_line - 1;
5783 } else
5784 lineno = s->first_displayed_line - 1 + s->selected_line;
5786 while (1) {
5787 off_t offset;
5789 if (lineno <= 0 || lineno > s->blame.nlines) {
5790 if (s->matched_line == 0) {
5791 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5792 break;
5795 if (view->searching == TOG_SEARCH_FORWARD)
5796 lineno = 1;
5797 else
5798 lineno = s->blame.nlines;
5801 offset = s->blame.line_offsets[lineno - 1];
5802 if (fseeko(s->blame.f, offset, SEEK_SET) != 0) {
5803 free(line);
5804 return got_error_from_errno("fseeko");
5806 linelen = getline(&line, &linesize, s->blame.f);
5807 if (linelen != -1) {
5808 char *exstr;
5809 err = expand_tab(&exstr, line);
5810 if (err)
5811 break;
5812 if (match_line(exstr, &view->regex, 1,
5813 &view->regmatch)) {
5814 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5815 s->matched_line = lineno;
5816 free(exstr);
5817 break;
5819 free(exstr);
5821 if (view->searching == TOG_SEARCH_FORWARD)
5822 lineno++;
5823 else
5824 lineno--;
5826 free(line);
5828 if (s->matched_line) {
5829 s->first_displayed_line = s->matched_line;
5830 s->selected_line = 1;
5833 return err;
5836 static const struct got_error *
5837 show_blame_view(struct tog_view *view)
5839 const struct got_error *err = NULL;
5840 struct tog_blame_view_state *s = &view->state.blame;
5841 int errcode;
5843 if (s->blame.thread == NULL && !s->blame_complete) {
5844 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
5845 &s->blame.thread_args);
5846 if (errcode)
5847 return got_error_set_errno(errcode, "pthread_create");
5849 halfdelay(1); /* fast refresh while annotating */
5852 if (s->blame_complete)
5853 halfdelay(10); /* disable fast refresh */
5855 err = draw_blame(view);
5857 view_border(view);
5858 return err;
5861 static const struct got_error *
5862 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
5863 struct got_repository *repo, struct got_object_id *id)
5865 struct tog_view *log_view;
5866 const struct got_error *err = NULL;
5868 *new_view = NULL;
5870 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
5871 if (log_view == NULL)
5872 return got_error_from_errno("view_open");
5874 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
5875 if (err)
5876 view_close(log_view);
5877 else
5878 *new_view = log_view;
5880 return err;
5883 static const struct got_error *
5884 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
5886 const struct got_error *err = NULL, *thread_err = NULL;
5887 struct tog_view *diff_view;
5888 struct tog_blame_view_state *s = &view->state.blame;
5889 int eos, nscroll, begin_y = 0, begin_x = 0;
5891 eos = nscroll = view->nlines - 2;
5892 if (view_is_hsplit_top(view))
5893 --eos; /* border */
5895 switch (ch) {
5896 case '0':
5897 view->x = 0;
5898 break;
5899 case '$':
5900 view->x = MAX(view->maxx - view->ncols / 3, 0);
5901 view->count = 0;
5902 break;
5903 case KEY_RIGHT:
5904 case 'l':
5905 if (view->x + view->ncols / 3 < view->maxx)
5906 view->x += 2; /* move two columns right */
5907 else
5908 view->count = 0;
5909 break;
5910 case KEY_LEFT:
5911 case 'h':
5912 view->x -= MIN(view->x, 2); /* move two columns back */
5913 if (view->x <= 0)
5914 view->count = 0;
5915 break;
5916 case 'q':
5917 s->done = 1;
5918 break;
5919 case 'g':
5920 case KEY_HOME:
5921 s->selected_line = 1;
5922 s->first_displayed_line = 1;
5923 view->count = 0;
5924 break;
5925 case 'G':
5926 case KEY_END:
5927 if (s->blame.nlines < eos) {
5928 s->selected_line = s->blame.nlines;
5929 s->first_displayed_line = 1;
5930 } else {
5931 s->selected_line = eos;
5932 s->first_displayed_line = s->blame.nlines - (eos - 1);
5934 view->count = 0;
5935 break;
5936 case 'k':
5937 case KEY_UP:
5938 case CTRL('p'):
5939 if (s->selected_line > 1)
5940 s->selected_line--;
5941 else if (s->selected_line == 1 &&
5942 s->first_displayed_line > 1)
5943 s->first_displayed_line--;
5944 else
5945 view->count = 0;
5946 break;
5947 case CTRL('u'):
5948 case 'u':
5949 nscroll /= 2;
5950 /* FALL THROUGH */
5951 case KEY_PPAGE:
5952 case CTRL('b'):
5953 case 'b':
5954 if (s->first_displayed_line == 1) {
5955 if (view->count > 1)
5956 nscroll += nscroll;
5957 s->selected_line = MAX(1, s->selected_line - nscroll);
5958 view->count = 0;
5959 break;
5961 if (s->first_displayed_line > nscroll)
5962 s->first_displayed_line -= nscroll;
5963 else
5964 s->first_displayed_line = 1;
5965 break;
5966 case 'j':
5967 case KEY_DOWN:
5968 case CTRL('n'):
5969 if (s->selected_line < eos && s->first_displayed_line +
5970 s->selected_line <= s->blame.nlines)
5971 s->selected_line++;
5972 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
5973 s->first_displayed_line++;
5974 else
5975 view->count = 0;
5976 break;
5977 case 'c':
5978 case 'p': {
5979 struct got_object_id *id = NULL;
5981 view->count = 0;
5982 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5983 s->first_displayed_line, s->selected_line);
5984 if (id == NULL)
5985 break;
5986 if (ch == 'p') {
5987 struct got_commit_object *commit, *pcommit;
5988 struct got_object_qid *pid;
5989 struct got_object_id *blob_id = NULL;
5990 int obj_type;
5991 err = got_object_open_as_commit(&commit,
5992 s->repo, id);
5993 if (err)
5994 break;
5995 pid = STAILQ_FIRST(
5996 got_object_commit_get_parent_ids(commit));
5997 if (pid == NULL) {
5998 got_object_commit_close(commit);
5999 break;
6001 /* Check if path history ends here. */
6002 err = got_object_open_as_commit(&pcommit,
6003 s->repo, &pid->id);
6004 if (err)
6005 break;
6006 err = got_object_id_by_path(&blob_id, s->repo,
6007 pcommit, s->path);
6008 got_object_commit_close(pcommit);
6009 if (err) {
6010 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6011 err = NULL;
6012 got_object_commit_close(commit);
6013 break;
6015 err = got_object_get_type(&obj_type, s->repo,
6016 blob_id);
6017 free(blob_id);
6018 /* Can't blame non-blob type objects. */
6019 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6020 got_object_commit_close(commit);
6021 break;
6023 err = got_object_qid_alloc(&s->blamed_commit,
6024 &pid->id);
6025 got_object_commit_close(commit);
6026 } else {
6027 if (got_object_id_cmp(id,
6028 &s->blamed_commit->id) == 0)
6029 break;
6030 err = got_object_qid_alloc(&s->blamed_commit,
6031 id);
6033 if (err)
6034 break;
6035 s->done = 1;
6036 thread_err = stop_blame(&s->blame);
6037 s->done = 0;
6038 if (thread_err)
6039 break;
6040 STAILQ_INSERT_HEAD(&s->blamed_commits,
6041 s->blamed_commit, entry);
6042 err = run_blame(view);
6043 if (err)
6044 break;
6045 break;
6047 case 'C': {
6048 struct got_object_qid *first;
6050 view->count = 0;
6051 first = STAILQ_FIRST(&s->blamed_commits);
6052 if (!got_object_id_cmp(&first->id, s->commit_id))
6053 break;
6054 s->done = 1;
6055 thread_err = stop_blame(&s->blame);
6056 s->done = 0;
6057 if (thread_err)
6058 break;
6059 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6060 got_object_qid_free(s->blamed_commit);
6061 s->blamed_commit =
6062 STAILQ_FIRST(&s->blamed_commits);
6063 err = run_blame(view);
6064 if (err)
6065 break;
6066 break;
6068 case 'L':
6069 view->count = 0;
6070 s->id_to_log = get_selected_commit_id(s->blame.lines,
6071 s->blame.nlines, s->first_displayed_line, s->selected_line);
6072 if (s->id_to_log)
6073 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6074 break;
6075 case KEY_ENTER:
6076 case '\r': {
6077 struct got_object_id *id = NULL;
6078 struct got_object_qid *pid;
6079 struct got_commit_object *commit = NULL;
6081 view->count = 0;
6082 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6083 s->first_displayed_line, s->selected_line);
6084 if (id == NULL)
6085 break;
6086 err = got_object_open_as_commit(&commit, s->repo, id);
6087 if (err)
6088 break;
6089 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6090 if (*new_view) {
6091 /* traversed from diff view, release diff resources */
6092 err = close_diff_view(*new_view);
6093 if (err)
6094 break;
6095 diff_view = *new_view;
6096 } else {
6097 if (view_is_parent_view(view))
6098 view_get_split(view, &begin_y, &begin_x);
6100 diff_view = view_open(0, 0, begin_y, begin_x,
6101 TOG_VIEW_DIFF);
6102 if (diff_view == NULL) {
6103 got_object_commit_close(commit);
6104 err = got_error_from_errno("view_open");
6105 break;
6108 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6109 id, NULL, NULL, 3, 0, 0, view, s->repo);
6110 got_object_commit_close(commit);
6111 if (err) {
6112 view_close(diff_view);
6113 break;
6115 s->last_diffed_line = s->first_displayed_line - 1 +
6116 s->selected_line;
6117 if (*new_view)
6118 break; /* still open from active diff view */
6119 if (view_is_parent_view(view) &&
6120 view->mode == TOG_VIEW_SPLIT_HRZN) {
6121 err = view_init_hsplit(view, begin_y);
6122 if (err)
6123 break;
6126 view->focussed = 0;
6127 diff_view->focussed = 1;
6128 diff_view->mode = view->mode;
6129 diff_view->nlines = view->lines - begin_y;
6130 if (view_is_parent_view(view)) {
6131 view_transfer_size(diff_view, view);
6132 err = view_close_child(view);
6133 if (err)
6134 break;
6135 err = view_set_child(view, diff_view);
6136 if (err)
6137 break;
6138 view->focus_child = 1;
6139 } else
6140 *new_view = diff_view;
6141 if (err)
6142 break;
6143 break;
6145 case CTRL('d'):
6146 case 'd':
6147 nscroll /= 2;
6148 /* FALL THROUGH */
6149 case KEY_NPAGE:
6150 case CTRL('f'):
6151 case 'f':
6152 case ' ':
6153 if (s->last_displayed_line >= s->blame.nlines &&
6154 s->selected_line >= MIN(s->blame.nlines,
6155 view->nlines - 2)) {
6156 view->count = 0;
6157 break;
6159 if (s->last_displayed_line >= s->blame.nlines &&
6160 s->selected_line < view->nlines - 2) {
6161 s->selected_line +=
6162 MIN(nscroll, s->last_displayed_line -
6163 s->first_displayed_line - s->selected_line + 1);
6165 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6166 s->first_displayed_line += nscroll;
6167 else
6168 s->first_displayed_line =
6169 s->blame.nlines - (view->nlines - 3);
6170 break;
6171 case KEY_RESIZE:
6172 if (s->selected_line > view->nlines - 2) {
6173 s->selected_line = MIN(s->blame.nlines,
6174 view->nlines - 2);
6176 break;
6177 default:
6178 view->count = 0;
6179 break;
6181 return thread_err ? thread_err : err;
6184 static const struct got_error *
6185 reset_blame_view(struct tog_view *view)
6187 const struct got_error *err;
6188 struct tog_blame_view_state *s = &view->state.blame;
6190 view->count = 0;
6191 s->done = 1;
6192 err = stop_blame(&s->blame);
6193 s->done = 0;
6194 if (err)
6195 return err;
6196 return run_blame(view);
6199 static const struct got_error *
6200 cmd_blame(int argc, char *argv[])
6202 const struct got_error *error;
6203 struct got_repository *repo = NULL;
6204 struct got_worktree *worktree = NULL;
6205 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6206 char *link_target = NULL;
6207 struct got_object_id *commit_id = NULL;
6208 struct got_commit_object *commit = NULL;
6209 char *commit_id_str = NULL;
6210 int ch;
6211 struct tog_view *view;
6212 int *pack_fds = NULL;
6214 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6215 switch (ch) {
6216 case 'c':
6217 commit_id_str = optarg;
6218 break;
6219 case 'r':
6220 repo_path = realpath(optarg, NULL);
6221 if (repo_path == NULL)
6222 return got_error_from_errno2("realpath",
6223 optarg);
6224 break;
6225 default:
6226 usage_blame();
6227 /* NOTREACHED */
6231 argc -= optind;
6232 argv += optind;
6234 if (argc != 1)
6235 usage_blame();
6237 error = got_repo_pack_fds_open(&pack_fds);
6238 if (error != NULL)
6239 goto done;
6241 if (repo_path == NULL) {
6242 cwd = getcwd(NULL, 0);
6243 if (cwd == NULL)
6244 return got_error_from_errno("getcwd");
6245 error = got_worktree_open(&worktree, cwd);
6246 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6247 goto done;
6248 if (worktree)
6249 repo_path =
6250 strdup(got_worktree_get_repo_path(worktree));
6251 else
6252 repo_path = strdup(cwd);
6253 if (repo_path == NULL) {
6254 error = got_error_from_errno("strdup");
6255 goto done;
6259 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6260 if (error != NULL)
6261 goto done;
6263 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6264 worktree);
6265 if (error)
6266 goto done;
6268 init_curses();
6270 error = apply_unveil(got_repo_get_path(repo), NULL);
6271 if (error)
6272 goto done;
6274 error = tog_load_refs(repo, 0);
6275 if (error)
6276 goto done;
6278 if (commit_id_str == NULL) {
6279 struct got_reference *head_ref;
6280 error = got_ref_open(&head_ref, repo, worktree ?
6281 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6282 if (error != NULL)
6283 goto done;
6284 error = got_ref_resolve(&commit_id, repo, head_ref);
6285 got_ref_close(head_ref);
6286 } else {
6287 error = got_repo_match_object_id(&commit_id, NULL,
6288 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6290 if (error != NULL)
6291 goto done;
6293 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6294 if (view == NULL) {
6295 error = got_error_from_errno("view_open");
6296 goto done;
6299 error = got_object_open_as_commit(&commit, repo, commit_id);
6300 if (error)
6301 goto done;
6303 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6304 commit, repo);
6305 if (error)
6306 goto done;
6308 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6309 commit_id, repo);
6310 if (error)
6311 goto done;
6312 if (worktree) {
6313 /* Release work tree lock. */
6314 got_worktree_close(worktree);
6315 worktree = NULL;
6317 error = view_loop(view);
6318 done:
6319 free(repo_path);
6320 free(in_repo_path);
6321 free(link_target);
6322 free(cwd);
6323 free(commit_id);
6324 if (commit)
6325 got_object_commit_close(commit);
6326 if (worktree)
6327 got_worktree_close(worktree);
6328 if (repo) {
6329 const struct got_error *close_err = got_repo_close(repo);
6330 if (error == NULL)
6331 error = close_err;
6333 if (pack_fds) {
6334 const struct got_error *pack_err =
6335 got_repo_pack_fds_close(pack_fds);
6336 if (error == NULL)
6337 error = pack_err;
6339 tog_free_refs();
6340 return error;
6343 static const struct got_error *
6344 draw_tree_entries(struct tog_view *view, const char *parent_path)
6346 struct tog_tree_view_state *s = &view->state.tree;
6347 const struct got_error *err = NULL;
6348 struct got_tree_entry *te;
6349 wchar_t *wline;
6350 struct tog_color *tc;
6351 int width, n, nentries, i = 1;
6352 int limit = view->nlines;
6354 s->ndisplayed = 0;
6355 if (view_is_hsplit_top(view))
6356 --limit; /* border */
6358 werase(view->window);
6360 if (limit == 0)
6361 return NULL;
6363 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6364 0, 0);
6365 if (err)
6366 return err;
6367 if (view_needs_focus_indication(view))
6368 wstandout(view->window);
6369 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6370 if (tc)
6371 wattr_on(view->window,
6372 COLOR_PAIR(tc->colorpair), NULL);
6373 waddwstr(view->window, wline);
6374 if (tc)
6375 wattr_off(view->window,
6376 COLOR_PAIR(tc->colorpair), NULL);
6377 if (view_needs_focus_indication(view))
6378 wstandend(view->window);
6379 free(wline);
6380 wline = NULL;
6382 i += s->selected;
6383 if (s->first_displayed_entry) {
6384 i += got_tree_entry_get_index(s->first_displayed_entry);
6385 if (s->tree != s->root)
6386 ++i; /* account for ".." entry */
6388 nentries = got_object_tree_get_nentries(s->tree);
6389 wprintw(view->window, " [%d/%d]", i,
6390 nentries + (s->tree == s->root ? 0 : 1)); /* ".." in !root tree */
6392 if (width < view->ncols - 1)
6393 waddch(view->window, '\n');
6394 if (--limit <= 0)
6395 return NULL;
6396 err = format_line(&wline, &width, NULL, parent_path, 0, view->ncols,
6397 0, 0);
6398 if (err)
6399 return err;
6400 waddwstr(view->window, wline);
6401 free(wline);
6402 wline = NULL;
6403 if (width < view->ncols - 1)
6404 waddch(view->window, '\n');
6405 if (--limit <= 0)
6406 return NULL;
6407 waddch(view->window, '\n');
6408 if (--limit <= 0)
6409 return NULL;
6411 if (s->first_displayed_entry == NULL) {
6412 te = got_object_tree_get_first_entry(s->tree);
6413 if (s->selected == 0) {
6414 if (view->focussed)
6415 wstandout(view->window);
6416 s->selected_entry = NULL;
6418 waddstr(view->window, " ..\n"); /* parent directory */
6419 if (s->selected == 0 && view->focussed)
6420 wstandend(view->window);
6421 s->ndisplayed++;
6422 if (--limit <= 0)
6423 return NULL;
6424 n = 1;
6425 } else {
6426 n = 0;
6427 te = s->first_displayed_entry;
6430 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6431 char *line = NULL, *id_str = NULL, *link_target = NULL;
6432 const char *modestr = "";
6433 mode_t mode;
6435 te = got_object_tree_get_entry(s->tree, i);
6436 mode = got_tree_entry_get_mode(te);
6438 if (s->show_ids) {
6439 err = got_object_id_str(&id_str,
6440 got_tree_entry_get_id(te));
6441 if (err)
6442 return got_error_from_errno(
6443 "got_object_id_str");
6445 if (got_object_tree_entry_is_submodule(te))
6446 modestr = "$";
6447 else if (S_ISLNK(mode)) {
6448 int i;
6450 err = got_tree_entry_get_symlink_target(&link_target,
6451 te, s->repo);
6452 if (err) {
6453 free(id_str);
6454 return err;
6456 for (i = 0; i < strlen(link_target); i++) {
6457 if (!isprint((unsigned char)link_target[i]))
6458 link_target[i] = '?';
6460 modestr = "@";
6462 else if (S_ISDIR(mode))
6463 modestr = "/";
6464 else if (mode & S_IXUSR)
6465 modestr = "*";
6466 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6467 got_tree_entry_get_name(te), modestr,
6468 link_target ? " -> ": "",
6469 link_target ? link_target : "") == -1) {
6470 free(id_str);
6471 free(link_target);
6472 return got_error_from_errno("asprintf");
6474 free(id_str);
6475 free(link_target);
6476 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
6477 0, 0);
6478 if (err) {
6479 free(line);
6480 break;
6482 if (n == s->selected) {
6483 if (view->focussed)
6484 wstandout(view->window);
6485 s->selected_entry = te;
6487 tc = match_color(&s->colors, line);
6488 if (tc)
6489 wattr_on(view->window,
6490 COLOR_PAIR(tc->colorpair), NULL);
6491 waddwstr(view->window, wline);
6492 if (tc)
6493 wattr_off(view->window,
6494 COLOR_PAIR(tc->colorpair), NULL);
6495 if (width < view->ncols - 1)
6496 waddch(view->window, '\n');
6497 if (n == s->selected && view->focussed)
6498 wstandend(view->window);
6499 free(line);
6500 free(wline);
6501 wline = NULL;
6502 n++;
6503 s->ndisplayed++;
6504 s->last_displayed_entry = te;
6505 if (--limit <= 0)
6506 break;
6509 return err;
6512 static void
6513 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6515 struct got_tree_entry *te;
6516 int isroot = s->tree == s->root;
6517 int i = 0;
6519 if (s->first_displayed_entry == NULL)
6520 return;
6522 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6523 while (i++ < maxscroll) {
6524 if (te == NULL) {
6525 if (!isroot)
6526 s->first_displayed_entry = NULL;
6527 break;
6529 s->first_displayed_entry = te;
6530 te = got_tree_entry_get_prev(s->tree, te);
6534 static const struct got_error *
6535 tree_scroll_down(struct tog_view *view, int maxscroll)
6537 struct tog_tree_view_state *s = &view->state.tree;
6538 struct got_tree_entry *next, *last;
6539 int n = 0;
6541 if (s->first_displayed_entry)
6542 next = got_tree_entry_get_next(s->tree,
6543 s->first_displayed_entry);
6544 else
6545 next = got_object_tree_get_first_entry(s->tree);
6547 last = s->last_displayed_entry;
6548 while (next && n++ < maxscroll) {
6549 if (last) {
6550 s->last_displayed_entry = last;
6551 last = got_tree_entry_get_next(s->tree, last);
6553 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
6554 s->first_displayed_entry = next;
6555 next = got_tree_entry_get_next(s->tree, next);
6559 return NULL;
6562 static const struct got_error *
6563 tree_entry_path(char **path, struct tog_parent_trees *parents,
6564 struct got_tree_entry *te)
6566 const struct got_error *err = NULL;
6567 struct tog_parent_tree *pt;
6568 size_t len = 2; /* for leading slash and NUL */
6570 TAILQ_FOREACH(pt, parents, entry)
6571 len += strlen(got_tree_entry_get_name(pt->selected_entry))
6572 + 1 /* slash */;
6573 if (te)
6574 len += strlen(got_tree_entry_get_name(te));
6576 *path = calloc(1, len);
6577 if (path == NULL)
6578 return got_error_from_errno("calloc");
6580 (*path)[0] = '/';
6581 pt = TAILQ_LAST(parents, tog_parent_trees);
6582 while (pt) {
6583 const char *name = got_tree_entry_get_name(pt->selected_entry);
6584 if (strlcat(*path, name, len) >= len) {
6585 err = got_error(GOT_ERR_NO_SPACE);
6586 goto done;
6588 if (strlcat(*path, "/", len) >= len) {
6589 err = got_error(GOT_ERR_NO_SPACE);
6590 goto done;
6592 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
6594 if (te) {
6595 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
6596 err = got_error(GOT_ERR_NO_SPACE);
6597 goto done;
6600 done:
6601 if (err) {
6602 free(*path);
6603 *path = NULL;
6605 return err;
6608 static const struct got_error *
6609 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6610 struct got_tree_entry *te, struct tog_parent_trees *parents,
6611 struct got_object_id *commit_id, struct got_repository *repo)
6613 const struct got_error *err = NULL;
6614 char *path;
6615 struct tog_view *blame_view;
6617 *new_view = NULL;
6619 err = tree_entry_path(&path, parents, te);
6620 if (err)
6621 return err;
6623 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
6624 if (blame_view == NULL) {
6625 err = got_error_from_errno("view_open");
6626 goto done;
6629 err = open_blame_view(blame_view, path, commit_id, repo);
6630 if (err) {
6631 if (err->code == GOT_ERR_CANCELLED)
6632 err = NULL;
6633 view_close(blame_view);
6634 } else
6635 *new_view = blame_view;
6636 done:
6637 free(path);
6638 return err;
6641 static const struct got_error *
6642 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6643 struct tog_tree_view_state *s)
6645 struct tog_view *log_view;
6646 const struct got_error *err = NULL;
6647 char *path;
6649 *new_view = NULL;
6651 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6652 if (log_view == NULL)
6653 return got_error_from_errno("view_open");
6655 err = tree_entry_path(&path, &s->parents, s->selected_entry);
6656 if (err)
6657 return err;
6659 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
6660 path, 0);
6661 if (err)
6662 view_close(log_view);
6663 else
6664 *new_view = log_view;
6665 free(path);
6666 return err;
6669 static const struct got_error *
6670 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
6671 const char *head_ref_name, struct got_repository *repo)
6673 const struct got_error *err = NULL;
6674 char *commit_id_str = NULL;
6675 struct tog_tree_view_state *s = &view->state.tree;
6676 struct got_commit_object *commit = NULL;
6678 TAILQ_INIT(&s->parents);
6679 STAILQ_INIT(&s->colors);
6681 s->commit_id = got_object_id_dup(commit_id);
6682 if (s->commit_id == NULL)
6683 return got_error_from_errno("got_object_id_dup");
6685 err = got_object_open_as_commit(&commit, repo, commit_id);
6686 if (err)
6687 goto done;
6690 * The root is opened here and will be closed when the view is closed.
6691 * Any visited subtrees and their path-wise parents are opened and
6692 * closed on demand.
6694 err = got_object_open_as_tree(&s->root, repo,
6695 got_object_commit_get_tree_id(commit));
6696 if (err)
6697 goto done;
6698 s->tree = s->root;
6700 err = got_object_id_str(&commit_id_str, commit_id);
6701 if (err != NULL)
6702 goto done;
6704 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
6705 err = got_error_from_errno("asprintf");
6706 goto done;
6709 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
6710 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
6711 if (head_ref_name) {
6712 s->head_ref_name = strdup(head_ref_name);
6713 if (s->head_ref_name == NULL) {
6714 err = got_error_from_errno("strdup");
6715 goto done;
6718 s->repo = repo;
6720 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6721 err = add_color(&s->colors, "\\$$",
6722 TOG_COLOR_TREE_SUBMODULE,
6723 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
6724 if (err)
6725 goto done;
6726 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
6727 get_color_value("TOG_COLOR_TREE_SYMLINK"));
6728 if (err)
6729 goto done;
6730 err = add_color(&s->colors, "/$",
6731 TOG_COLOR_TREE_DIRECTORY,
6732 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
6733 if (err)
6734 goto done;
6736 err = add_color(&s->colors, "\\*$",
6737 TOG_COLOR_TREE_EXECUTABLE,
6738 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
6739 if (err)
6740 goto done;
6742 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
6743 get_color_value("TOG_COLOR_COMMIT"));
6744 if (err)
6745 goto done;
6748 view->show = show_tree_view;
6749 view->input = input_tree_view;
6750 view->close = close_tree_view;
6751 view->search_start = search_start_tree_view;
6752 view->search_next = search_next_tree_view;
6753 done:
6754 free(commit_id_str);
6755 if (commit)
6756 got_object_commit_close(commit);
6757 if (err)
6758 close_tree_view(view);
6759 return err;
6762 static const struct got_error *
6763 close_tree_view(struct tog_view *view)
6765 struct tog_tree_view_state *s = &view->state.tree;
6767 free_colors(&s->colors);
6768 free(s->tree_label);
6769 s->tree_label = NULL;
6770 free(s->commit_id);
6771 s->commit_id = NULL;
6772 free(s->head_ref_name);
6773 s->head_ref_name = NULL;
6774 while (!TAILQ_EMPTY(&s->parents)) {
6775 struct tog_parent_tree *parent;
6776 parent = TAILQ_FIRST(&s->parents);
6777 TAILQ_REMOVE(&s->parents, parent, entry);
6778 if (parent->tree != s->root)
6779 got_object_tree_close(parent->tree);
6780 free(parent);
6783 if (s->tree != NULL && s->tree != s->root)
6784 got_object_tree_close(s->tree);
6785 if (s->root)
6786 got_object_tree_close(s->root);
6787 return NULL;
6790 static const struct got_error *
6791 search_start_tree_view(struct tog_view *view)
6793 struct tog_tree_view_state *s = &view->state.tree;
6795 s->matched_entry = NULL;
6796 return NULL;
6799 static int
6800 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
6802 regmatch_t regmatch;
6804 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
6805 0) == 0;
6808 static const struct got_error *
6809 search_next_tree_view(struct tog_view *view)
6811 struct tog_tree_view_state *s = &view->state.tree;
6812 struct got_tree_entry *te = NULL;
6814 if (!view->searching) {
6815 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6816 return NULL;
6819 if (s->matched_entry) {
6820 if (view->searching == TOG_SEARCH_FORWARD) {
6821 if (s->selected_entry)
6822 te = got_tree_entry_get_next(s->tree,
6823 s->selected_entry);
6824 else
6825 te = got_object_tree_get_first_entry(s->tree);
6826 } else {
6827 if (s->selected_entry == NULL)
6828 te = got_object_tree_get_last_entry(s->tree);
6829 else
6830 te = got_tree_entry_get_prev(s->tree,
6831 s->selected_entry);
6833 } else {
6834 if (s->selected_entry)
6835 te = s->selected_entry;
6836 else if (view->searching == TOG_SEARCH_FORWARD)
6837 te = got_object_tree_get_first_entry(s->tree);
6838 else
6839 te = got_object_tree_get_last_entry(s->tree);
6842 while (1) {
6843 if (te == NULL) {
6844 if (s->matched_entry == NULL) {
6845 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6846 return NULL;
6848 if (view->searching == TOG_SEARCH_FORWARD)
6849 te = got_object_tree_get_first_entry(s->tree);
6850 else
6851 te = got_object_tree_get_last_entry(s->tree);
6854 if (match_tree_entry(te, &view->regex)) {
6855 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6856 s->matched_entry = te;
6857 break;
6860 if (view->searching == TOG_SEARCH_FORWARD)
6861 te = got_tree_entry_get_next(s->tree, te);
6862 else
6863 te = got_tree_entry_get_prev(s->tree, te);
6866 if (s->matched_entry) {
6867 s->first_displayed_entry = s->matched_entry;
6868 s->selected = 0;
6871 return NULL;
6874 static const struct got_error *
6875 show_tree_view(struct tog_view *view)
6877 const struct got_error *err = NULL;
6878 struct tog_tree_view_state *s = &view->state.tree;
6879 char *parent_path;
6881 err = tree_entry_path(&parent_path, &s->parents, NULL);
6882 if (err)
6883 return err;
6885 err = draw_tree_entries(view, parent_path);
6886 free(parent_path);
6888 view_border(view);
6889 return err;
6892 static const struct got_error *
6893 tree_goto_line(struct tog_view *view, int nlines)
6895 const struct got_error *err = NULL;
6896 struct tog_tree_view_state *s = &view->state.tree;
6897 struct got_tree_entry **fte, **lte, **ste;
6898 int g, last, first = 1, i = 1;
6899 int root = s->tree == s->root;
6900 int off = root ? 1 : 2;
6902 g = view->gline;
6903 view->gline = 0;
6905 if (g == 0)
6906 g = 1;
6907 else if (g > got_object_tree_get_nentries(s->tree))
6908 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
6910 fte = &s->first_displayed_entry;
6911 lte = &s->last_displayed_entry;
6912 ste = &s->selected_entry;
6914 if (*fte != NULL) {
6915 first = got_tree_entry_get_index(*fte);
6916 first += off; /* account for ".." */
6918 last = got_tree_entry_get_index(*lte);
6919 last += off;
6921 if (g >= first && g <= last && g - first < nlines) {
6922 s->selected = g - first;
6923 return NULL; /* gline is on the current page */
6926 if (*ste != NULL) {
6927 i = got_tree_entry_get_index(*ste);
6928 i += off;
6931 if (i < g) {
6932 err = tree_scroll_down(view, g - i);
6933 if (err)
6934 return err;
6935 if (got_tree_entry_get_index(*lte) >=
6936 got_object_tree_get_nentries(s->tree) - 1 &&
6937 first + s->selected < g &&
6938 s->selected < s->ndisplayed - 1) {
6939 first = got_tree_entry_get_index(*fte);
6940 first += off;
6941 s->selected = g - first;
6943 } else if (i > g)
6944 tree_scroll_up(s, i - g);
6946 if (g < nlines &&
6947 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
6948 s->selected = g - 1;
6950 return NULL;
6953 static const struct got_error *
6954 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
6956 const struct got_error *err = NULL;
6957 struct tog_tree_view_state *s = &view->state.tree;
6958 struct got_tree_entry *te;
6959 int n, nscroll = view->nlines - 3;
6961 if (view->gline)
6962 return tree_goto_line(view, nscroll);
6964 switch (ch) {
6965 case 'i':
6966 s->show_ids = !s->show_ids;
6967 view->count = 0;
6968 break;
6969 case 'L':
6970 view->count = 0;
6971 if (!s->selected_entry)
6972 break;
6973 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6974 break;
6975 case 'R':
6976 view->count = 0;
6977 err = view_request_new(new_view, view, TOG_VIEW_REF);
6978 break;
6979 case 'g':
6980 case KEY_HOME:
6981 s->selected = 0;
6982 view->count = 0;
6983 if (s->tree == s->root)
6984 s->first_displayed_entry =
6985 got_object_tree_get_first_entry(s->tree);
6986 else
6987 s->first_displayed_entry = NULL;
6988 break;
6989 case 'G':
6990 case KEY_END: {
6991 int eos = view->nlines - 3;
6993 if (view->mode == TOG_VIEW_SPLIT_HRZN)
6994 --eos; /* border */
6995 s->selected = 0;
6996 view->count = 0;
6997 te = got_object_tree_get_last_entry(s->tree);
6998 for (n = 0; n < eos; n++) {
6999 if (te == NULL) {
7000 if (s->tree != s->root) {
7001 s->first_displayed_entry = NULL;
7002 n++;
7004 break;
7006 s->first_displayed_entry = te;
7007 te = got_tree_entry_get_prev(s->tree, te);
7009 if (n > 0)
7010 s->selected = n - 1;
7011 break;
7013 case 'k':
7014 case KEY_UP:
7015 case CTRL('p'):
7016 if (s->selected > 0) {
7017 s->selected--;
7018 break;
7020 tree_scroll_up(s, 1);
7021 if (s->selected_entry == NULL ||
7022 (s->tree == s->root && s->selected_entry ==
7023 got_object_tree_get_first_entry(s->tree)))
7024 view->count = 0;
7025 break;
7026 case CTRL('u'):
7027 case 'u':
7028 nscroll /= 2;
7029 /* FALL THROUGH */
7030 case KEY_PPAGE:
7031 case CTRL('b'):
7032 case 'b':
7033 if (s->tree == s->root) {
7034 if (got_object_tree_get_first_entry(s->tree) ==
7035 s->first_displayed_entry)
7036 s->selected -= MIN(s->selected, nscroll);
7037 } else {
7038 if (s->first_displayed_entry == NULL)
7039 s->selected -= MIN(s->selected, nscroll);
7041 tree_scroll_up(s, MAX(0, nscroll));
7042 if (s->selected_entry == NULL ||
7043 (s->tree == s->root && s->selected_entry ==
7044 got_object_tree_get_first_entry(s->tree)))
7045 view->count = 0;
7046 break;
7047 case 'j':
7048 case KEY_DOWN:
7049 case CTRL('n'):
7050 if (s->selected < s->ndisplayed - 1) {
7051 s->selected++;
7052 break;
7054 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7055 == NULL) {
7056 /* can't scroll any further */
7057 view->count = 0;
7058 break;
7060 tree_scroll_down(view, 1);
7061 break;
7062 case CTRL('d'):
7063 case 'd':
7064 nscroll /= 2;
7065 /* FALL THROUGH */
7066 case KEY_NPAGE:
7067 case CTRL('f'):
7068 case 'f':
7069 case ' ':
7070 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7071 == NULL) {
7072 /* can't scroll any further; move cursor down */
7073 if (s->selected < s->ndisplayed - 1)
7074 s->selected += MIN(nscroll,
7075 s->ndisplayed - s->selected - 1);
7076 else
7077 view->count = 0;
7078 break;
7080 tree_scroll_down(view, nscroll);
7081 break;
7082 case KEY_ENTER:
7083 case '\r':
7084 case KEY_BACKSPACE:
7085 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7086 struct tog_parent_tree *parent;
7087 /* user selected '..' */
7088 if (s->tree == s->root) {
7089 view->count = 0;
7090 break;
7092 parent = TAILQ_FIRST(&s->parents);
7093 TAILQ_REMOVE(&s->parents, parent,
7094 entry);
7095 got_object_tree_close(s->tree);
7096 s->tree = parent->tree;
7097 s->first_displayed_entry =
7098 parent->first_displayed_entry;
7099 s->selected_entry =
7100 parent->selected_entry;
7101 s->selected = parent->selected;
7102 if (s->selected > view->nlines - 3) {
7103 err = offset_selection_down(view);
7104 if (err)
7105 break;
7107 free(parent);
7108 } else if (S_ISDIR(got_tree_entry_get_mode(
7109 s->selected_entry))) {
7110 struct got_tree_object *subtree;
7111 view->count = 0;
7112 err = got_object_open_as_tree(&subtree, s->repo,
7113 got_tree_entry_get_id(s->selected_entry));
7114 if (err)
7115 break;
7116 err = tree_view_visit_subtree(s, subtree);
7117 if (err) {
7118 got_object_tree_close(subtree);
7119 break;
7121 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7122 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7123 break;
7124 case KEY_RESIZE:
7125 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7126 s->selected = view->nlines - 4;
7127 view->count = 0;
7128 break;
7129 default:
7130 view->count = 0;
7131 break;
7134 return err;
7137 __dead static void
7138 usage_tree(void)
7140 endwin();
7141 fprintf(stderr,
7142 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7143 getprogname());
7144 exit(1);
7147 static const struct got_error *
7148 cmd_tree(int argc, char *argv[])
7150 const struct got_error *error;
7151 struct got_repository *repo = NULL;
7152 struct got_worktree *worktree = NULL;
7153 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7154 struct got_object_id *commit_id = NULL;
7155 struct got_commit_object *commit = NULL;
7156 const char *commit_id_arg = NULL;
7157 char *label = NULL;
7158 struct got_reference *ref = NULL;
7159 const char *head_ref_name = NULL;
7160 int ch;
7161 struct tog_view *view;
7162 int *pack_fds = NULL;
7164 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7165 switch (ch) {
7166 case 'c':
7167 commit_id_arg = optarg;
7168 break;
7169 case 'r':
7170 repo_path = realpath(optarg, NULL);
7171 if (repo_path == NULL)
7172 return got_error_from_errno2("realpath",
7173 optarg);
7174 break;
7175 default:
7176 usage_tree();
7177 /* NOTREACHED */
7181 argc -= optind;
7182 argv += optind;
7184 if (argc > 1)
7185 usage_tree();
7187 error = got_repo_pack_fds_open(&pack_fds);
7188 if (error != NULL)
7189 goto done;
7191 if (repo_path == NULL) {
7192 cwd = getcwd(NULL, 0);
7193 if (cwd == NULL)
7194 return got_error_from_errno("getcwd");
7195 error = got_worktree_open(&worktree, cwd);
7196 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7197 goto done;
7198 if (worktree)
7199 repo_path =
7200 strdup(got_worktree_get_repo_path(worktree));
7201 else
7202 repo_path = strdup(cwd);
7203 if (repo_path == NULL) {
7204 error = got_error_from_errno("strdup");
7205 goto done;
7209 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7210 if (error != NULL)
7211 goto done;
7213 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7214 repo, worktree);
7215 if (error)
7216 goto done;
7218 init_curses();
7220 error = apply_unveil(got_repo_get_path(repo), NULL);
7221 if (error)
7222 goto done;
7224 error = tog_load_refs(repo, 0);
7225 if (error)
7226 goto done;
7228 if (commit_id_arg == NULL) {
7229 error = got_repo_match_object_id(&commit_id, &label,
7230 worktree ? got_worktree_get_head_ref_name(worktree) :
7231 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7232 if (error)
7233 goto done;
7234 head_ref_name = label;
7235 } else {
7236 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7237 if (error == NULL)
7238 head_ref_name = got_ref_get_name(ref);
7239 else if (error->code != GOT_ERR_NOT_REF)
7240 goto done;
7241 error = got_repo_match_object_id(&commit_id, NULL,
7242 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7243 if (error)
7244 goto done;
7247 error = got_object_open_as_commit(&commit, repo, commit_id);
7248 if (error)
7249 goto done;
7251 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7252 if (view == NULL) {
7253 error = got_error_from_errno("view_open");
7254 goto done;
7256 error = open_tree_view(view, commit_id, head_ref_name, repo);
7257 if (error)
7258 goto done;
7259 if (!got_path_is_root_dir(in_repo_path)) {
7260 error = tree_view_walk_path(&view->state.tree, commit,
7261 in_repo_path);
7262 if (error)
7263 goto done;
7266 if (worktree) {
7267 /* Release work tree lock. */
7268 got_worktree_close(worktree);
7269 worktree = NULL;
7271 error = view_loop(view);
7272 done:
7273 free(repo_path);
7274 free(cwd);
7275 free(commit_id);
7276 free(label);
7277 if (ref)
7278 got_ref_close(ref);
7279 if (repo) {
7280 const struct got_error *close_err = got_repo_close(repo);
7281 if (error == NULL)
7282 error = close_err;
7284 if (pack_fds) {
7285 const struct got_error *pack_err =
7286 got_repo_pack_fds_close(pack_fds);
7287 if (error == NULL)
7288 error = pack_err;
7290 tog_free_refs();
7291 return error;
7294 static const struct got_error *
7295 ref_view_load_refs(struct tog_ref_view_state *s)
7297 struct got_reflist_entry *sre;
7298 struct tog_reflist_entry *re;
7300 s->nrefs = 0;
7301 TAILQ_FOREACH(sre, &tog_refs, entry) {
7302 if (strncmp(got_ref_get_name(sre->ref),
7303 "refs/got/", 9) == 0 &&
7304 strncmp(got_ref_get_name(sre->ref),
7305 "refs/got/backup/", 16) != 0)
7306 continue;
7308 re = malloc(sizeof(*re));
7309 if (re == NULL)
7310 return got_error_from_errno("malloc");
7312 re->ref = got_ref_dup(sre->ref);
7313 if (re->ref == NULL)
7314 return got_error_from_errno("got_ref_dup");
7315 re->idx = s->nrefs++;
7316 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7319 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7320 return NULL;
7323 static void
7324 ref_view_free_refs(struct tog_ref_view_state *s)
7326 struct tog_reflist_entry *re;
7328 while (!TAILQ_EMPTY(&s->refs)) {
7329 re = TAILQ_FIRST(&s->refs);
7330 TAILQ_REMOVE(&s->refs, re, entry);
7331 got_ref_close(re->ref);
7332 free(re);
7336 static const struct got_error *
7337 open_ref_view(struct tog_view *view, struct got_repository *repo)
7339 const struct got_error *err = NULL;
7340 struct tog_ref_view_state *s = &view->state.ref;
7342 s->selected_entry = 0;
7343 s->repo = repo;
7345 TAILQ_INIT(&s->refs);
7346 STAILQ_INIT(&s->colors);
7348 err = ref_view_load_refs(s);
7349 if (err)
7350 return err;
7352 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7353 err = add_color(&s->colors, "^refs/heads/",
7354 TOG_COLOR_REFS_HEADS,
7355 get_color_value("TOG_COLOR_REFS_HEADS"));
7356 if (err)
7357 goto done;
7359 err = add_color(&s->colors, "^refs/tags/",
7360 TOG_COLOR_REFS_TAGS,
7361 get_color_value("TOG_COLOR_REFS_TAGS"));
7362 if (err)
7363 goto done;
7365 err = add_color(&s->colors, "^refs/remotes/",
7366 TOG_COLOR_REFS_REMOTES,
7367 get_color_value("TOG_COLOR_REFS_REMOTES"));
7368 if (err)
7369 goto done;
7371 err = add_color(&s->colors, "^refs/got/backup/",
7372 TOG_COLOR_REFS_BACKUP,
7373 get_color_value("TOG_COLOR_REFS_BACKUP"));
7374 if (err)
7375 goto done;
7378 view->show = show_ref_view;
7379 view->input = input_ref_view;
7380 view->close = close_ref_view;
7381 view->search_start = search_start_ref_view;
7382 view->search_next = search_next_ref_view;
7383 done:
7384 if (err)
7385 free_colors(&s->colors);
7386 return err;
7389 static const struct got_error *
7390 close_ref_view(struct tog_view *view)
7392 struct tog_ref_view_state *s = &view->state.ref;
7394 ref_view_free_refs(s);
7395 free_colors(&s->colors);
7397 return NULL;
7400 static const struct got_error *
7401 resolve_reflist_entry(struct got_object_id **commit_id,
7402 struct tog_reflist_entry *re, struct got_repository *repo)
7404 const struct got_error *err = NULL;
7405 struct got_object_id *obj_id;
7406 struct got_tag_object *tag = NULL;
7407 int obj_type;
7409 *commit_id = NULL;
7411 err = got_ref_resolve(&obj_id, repo, re->ref);
7412 if (err)
7413 return err;
7415 err = got_object_get_type(&obj_type, repo, obj_id);
7416 if (err)
7417 goto done;
7419 switch (obj_type) {
7420 case GOT_OBJ_TYPE_COMMIT:
7421 *commit_id = obj_id;
7422 break;
7423 case GOT_OBJ_TYPE_TAG:
7424 err = got_object_open_as_tag(&tag, repo, obj_id);
7425 if (err)
7426 goto done;
7427 free(obj_id);
7428 err = got_object_get_type(&obj_type, repo,
7429 got_object_tag_get_object_id(tag));
7430 if (err)
7431 goto done;
7432 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7433 err = got_error(GOT_ERR_OBJ_TYPE);
7434 goto done;
7436 *commit_id = got_object_id_dup(
7437 got_object_tag_get_object_id(tag));
7438 if (*commit_id == NULL) {
7439 err = got_error_from_errno("got_object_id_dup");
7440 goto done;
7442 break;
7443 default:
7444 err = got_error(GOT_ERR_OBJ_TYPE);
7445 break;
7448 done:
7449 if (tag)
7450 got_object_tag_close(tag);
7451 if (err) {
7452 free(*commit_id);
7453 *commit_id = NULL;
7455 return err;
7458 static const struct got_error *
7459 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7460 struct tog_reflist_entry *re, struct got_repository *repo)
7462 struct tog_view *log_view;
7463 const struct got_error *err = NULL;
7464 struct got_object_id *commit_id = NULL;
7466 *new_view = NULL;
7468 err = resolve_reflist_entry(&commit_id, re, repo);
7469 if (err) {
7470 if (err->code != GOT_ERR_OBJ_TYPE)
7471 return err;
7472 else
7473 return NULL;
7476 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7477 if (log_view == NULL) {
7478 err = got_error_from_errno("view_open");
7479 goto done;
7482 err = open_log_view(log_view, commit_id, repo,
7483 got_ref_get_name(re->ref), "", 0);
7484 done:
7485 if (err)
7486 view_close(log_view);
7487 else
7488 *new_view = log_view;
7489 free(commit_id);
7490 return err;
7493 static void
7494 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7496 struct tog_reflist_entry *re;
7497 int i = 0;
7499 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7500 return;
7502 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7503 while (i++ < maxscroll) {
7504 if (re == NULL)
7505 break;
7506 s->first_displayed_entry = re;
7507 re = TAILQ_PREV(re, tog_reflist_head, entry);
7511 static const struct got_error *
7512 ref_scroll_down(struct tog_view *view, int maxscroll)
7514 struct tog_ref_view_state *s = &view->state.ref;
7515 struct tog_reflist_entry *next, *last;
7516 int n = 0;
7518 if (s->first_displayed_entry)
7519 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7520 else
7521 next = TAILQ_FIRST(&s->refs);
7523 last = s->last_displayed_entry;
7524 while (next && n++ < maxscroll) {
7525 if (last) {
7526 s->last_displayed_entry = last;
7527 last = TAILQ_NEXT(last, entry);
7529 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7530 s->first_displayed_entry = next;
7531 next = TAILQ_NEXT(next, entry);
7535 return NULL;
7538 static const struct got_error *
7539 search_start_ref_view(struct tog_view *view)
7541 struct tog_ref_view_state *s = &view->state.ref;
7543 s->matched_entry = NULL;
7544 return NULL;
7547 static int
7548 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
7550 regmatch_t regmatch;
7552 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
7553 0) == 0;
7556 static const struct got_error *
7557 search_next_ref_view(struct tog_view *view)
7559 struct tog_ref_view_state *s = &view->state.ref;
7560 struct tog_reflist_entry *re = NULL;
7562 if (!view->searching) {
7563 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7564 return NULL;
7567 if (s->matched_entry) {
7568 if (view->searching == TOG_SEARCH_FORWARD) {
7569 if (s->selected_entry)
7570 re = TAILQ_NEXT(s->selected_entry, entry);
7571 else
7572 re = TAILQ_PREV(s->selected_entry,
7573 tog_reflist_head, entry);
7574 } else {
7575 if (s->selected_entry == NULL)
7576 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7577 else
7578 re = TAILQ_PREV(s->selected_entry,
7579 tog_reflist_head, entry);
7581 } else {
7582 if (s->selected_entry)
7583 re = s->selected_entry;
7584 else if (view->searching == TOG_SEARCH_FORWARD)
7585 re = TAILQ_FIRST(&s->refs);
7586 else
7587 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7590 while (1) {
7591 if (re == NULL) {
7592 if (s->matched_entry == NULL) {
7593 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7594 return NULL;
7596 if (view->searching == TOG_SEARCH_FORWARD)
7597 re = TAILQ_FIRST(&s->refs);
7598 else
7599 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7602 if (match_reflist_entry(re, &view->regex)) {
7603 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7604 s->matched_entry = re;
7605 break;
7608 if (view->searching == TOG_SEARCH_FORWARD)
7609 re = TAILQ_NEXT(re, entry);
7610 else
7611 re = TAILQ_PREV(re, tog_reflist_head, entry);
7614 if (s->matched_entry) {
7615 s->first_displayed_entry = s->matched_entry;
7616 s->selected = 0;
7619 return NULL;
7622 static const struct got_error *
7623 show_ref_view(struct tog_view *view)
7625 const struct got_error *err = NULL;
7626 struct tog_ref_view_state *s = &view->state.ref;
7627 struct tog_reflist_entry *re;
7628 char *line = NULL;
7629 wchar_t *wline;
7630 struct tog_color *tc;
7631 int width, n;
7632 int limit = view->nlines;
7634 werase(view->window);
7636 s->ndisplayed = 0;
7637 if (view_is_hsplit_top(view))
7638 --limit; /* border */
7640 if (limit == 0)
7641 return NULL;
7643 re = s->first_displayed_entry;
7645 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
7646 s->nrefs) == -1)
7647 return got_error_from_errno("asprintf");
7649 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
7650 if (err) {
7651 free(line);
7652 return err;
7654 if (view_needs_focus_indication(view))
7655 wstandout(view->window);
7656 waddwstr(view->window, wline);
7657 if (view_needs_focus_indication(view))
7658 wstandend(view->window);
7659 free(wline);
7660 wline = NULL;
7661 free(line);
7662 line = NULL;
7663 if (width < view->ncols - 1)
7664 waddch(view->window, '\n');
7665 if (--limit <= 0)
7666 return NULL;
7668 n = 0;
7669 while (re && limit > 0) {
7670 char *line = NULL;
7671 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
7673 if (s->show_date) {
7674 struct got_commit_object *ci;
7675 struct got_tag_object *tag;
7676 struct got_object_id *id;
7677 struct tm tm;
7678 time_t t;
7680 err = got_ref_resolve(&id, s->repo, re->ref);
7681 if (err)
7682 return err;
7683 err = got_object_open_as_tag(&tag, s->repo, id);
7684 if (err) {
7685 if (err->code != GOT_ERR_OBJ_TYPE) {
7686 free(id);
7687 return err;
7689 err = got_object_open_as_commit(&ci, s->repo,
7690 id);
7691 if (err) {
7692 free(id);
7693 return err;
7695 t = got_object_commit_get_committer_time(ci);
7696 got_object_commit_close(ci);
7697 } else {
7698 t = got_object_tag_get_tagger_time(tag);
7699 got_object_tag_close(tag);
7701 free(id);
7702 if (gmtime_r(&t, &tm) == NULL)
7703 return got_error_from_errno("gmtime_r");
7704 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
7705 return got_error(GOT_ERR_NO_SPACE);
7707 if (got_ref_is_symbolic(re->ref)) {
7708 if (asprintf(&line, "%s%s -> %s", s->show_date ?
7709 ymd : "", got_ref_get_name(re->ref),
7710 got_ref_get_symref_target(re->ref)) == -1)
7711 return got_error_from_errno("asprintf");
7712 } else if (s->show_ids) {
7713 struct got_object_id *id;
7714 char *id_str;
7715 err = got_ref_resolve(&id, s->repo, re->ref);
7716 if (err)
7717 return err;
7718 err = got_object_id_str(&id_str, id);
7719 if (err) {
7720 free(id);
7721 return err;
7723 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
7724 got_ref_get_name(re->ref), id_str) == -1) {
7725 err = got_error_from_errno("asprintf");
7726 free(id);
7727 free(id_str);
7728 return err;
7730 free(id);
7731 free(id_str);
7732 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
7733 got_ref_get_name(re->ref)) == -1)
7734 return got_error_from_errno("asprintf");
7736 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
7737 0, 0);
7738 if (err) {
7739 free(line);
7740 return err;
7742 if (n == s->selected) {
7743 if (view->focussed)
7744 wstandout(view->window);
7745 s->selected_entry = re;
7747 tc = match_color(&s->colors, got_ref_get_name(re->ref));
7748 if (tc)
7749 wattr_on(view->window,
7750 COLOR_PAIR(tc->colorpair), NULL);
7751 waddwstr(view->window, wline);
7752 if (tc)
7753 wattr_off(view->window,
7754 COLOR_PAIR(tc->colorpair), NULL);
7755 if (width < view->ncols - 1)
7756 waddch(view->window, '\n');
7757 if (n == s->selected && view->focussed)
7758 wstandend(view->window);
7759 free(line);
7760 free(wline);
7761 wline = NULL;
7762 n++;
7763 s->ndisplayed++;
7764 s->last_displayed_entry = re;
7766 limit--;
7767 re = TAILQ_NEXT(re, entry);
7770 view_border(view);
7771 return err;
7774 static const struct got_error *
7775 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
7776 struct tog_reflist_entry *re, struct got_repository *repo)
7778 const struct got_error *err = NULL;
7779 struct got_object_id *commit_id = NULL;
7780 struct tog_view *tree_view;
7782 *new_view = NULL;
7784 err = resolve_reflist_entry(&commit_id, re, repo);
7785 if (err) {
7786 if (err->code != GOT_ERR_OBJ_TYPE)
7787 return err;
7788 else
7789 return NULL;
7793 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
7794 if (tree_view == NULL) {
7795 err = got_error_from_errno("view_open");
7796 goto done;
7799 err = open_tree_view(tree_view, commit_id,
7800 got_ref_get_name(re->ref), repo);
7801 if (err)
7802 goto done;
7804 *new_view = tree_view;
7805 done:
7806 free(commit_id);
7807 return err;
7810 static const struct got_error *
7811 ref_goto_line(struct tog_view *view, int nlines)
7813 const struct got_error *err = NULL;
7814 struct tog_ref_view_state *s = &view->state.ref;
7815 int g, idx = s->selected_entry->idx;
7817 g = view->gline;
7818 view->gline = 0;
7820 if (g == 0)
7821 g = 1;
7822 else if (g > s->nrefs)
7823 g = s->nrefs;
7825 if (g >= s->first_displayed_entry->idx + 1 &&
7826 g <= s->last_displayed_entry->idx + 1 &&
7827 g - s->first_displayed_entry->idx - 1 < nlines) {
7828 s->selected = g - s->first_displayed_entry->idx - 1;
7829 return NULL;
7832 if (idx + 1 < g) {
7833 err = ref_scroll_down(view, g - idx - 1);
7834 if (err)
7835 return err;
7836 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
7837 s->first_displayed_entry->idx + s->selected < g &&
7838 s->selected < s->ndisplayed - 1)
7839 s->selected = g - s->first_displayed_entry->idx - 1;
7840 } else if (idx + 1 > g)
7841 ref_scroll_up(s, idx - g + 1);
7843 if (g < nlines && s->first_displayed_entry->idx == 0)
7844 s->selected = g - 1;
7846 return NULL;
7850 static const struct got_error *
7851 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
7853 const struct got_error *err = NULL;
7854 struct tog_ref_view_state *s = &view->state.ref;
7855 struct tog_reflist_entry *re;
7856 int n, nscroll = view->nlines - 1;
7858 if (view->gline)
7859 return ref_goto_line(view, nscroll);
7861 switch (ch) {
7862 case 'i':
7863 s->show_ids = !s->show_ids;
7864 view->count = 0;
7865 break;
7866 case 'm':
7867 s->show_date = !s->show_date;
7868 view->count = 0;
7869 break;
7870 case 'o':
7871 s->sort_by_date = !s->sort_by_date;
7872 view->count = 0;
7873 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
7874 got_ref_cmp_by_commit_timestamp_descending :
7875 tog_ref_cmp_by_name, s->repo);
7876 if (err)
7877 break;
7878 got_reflist_object_id_map_free(tog_refs_idmap);
7879 err = got_reflist_object_id_map_create(&tog_refs_idmap,
7880 &tog_refs, s->repo);
7881 if (err)
7882 break;
7883 ref_view_free_refs(s);
7884 err = ref_view_load_refs(s);
7885 break;
7886 case KEY_ENTER:
7887 case '\r':
7888 view->count = 0;
7889 if (!s->selected_entry)
7890 break;
7891 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7892 break;
7893 case 'T':
7894 view->count = 0;
7895 if (!s->selected_entry)
7896 break;
7897 err = view_request_new(new_view, view, TOG_VIEW_TREE);
7898 break;
7899 case 'g':
7900 case KEY_HOME:
7901 s->selected = 0;
7902 view->count = 0;
7903 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7904 break;
7905 case 'G':
7906 case KEY_END: {
7907 int eos = view->nlines - 1;
7909 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7910 --eos; /* border */
7911 s->selected = 0;
7912 view->count = 0;
7913 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7914 for (n = 0; n < eos; n++) {
7915 if (re == NULL)
7916 break;
7917 s->first_displayed_entry = re;
7918 re = TAILQ_PREV(re, tog_reflist_head, entry);
7920 if (n > 0)
7921 s->selected = n - 1;
7922 break;
7924 case 'k':
7925 case KEY_UP:
7926 case CTRL('p'):
7927 if (s->selected > 0) {
7928 s->selected--;
7929 break;
7931 ref_scroll_up(s, 1);
7932 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7933 view->count = 0;
7934 break;
7935 case CTRL('u'):
7936 case 'u':
7937 nscroll /= 2;
7938 /* FALL THROUGH */
7939 case KEY_PPAGE:
7940 case CTRL('b'):
7941 case 'b':
7942 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7943 s->selected -= MIN(nscroll, s->selected);
7944 ref_scroll_up(s, MAX(0, nscroll));
7945 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7946 view->count = 0;
7947 break;
7948 case 'j':
7949 case KEY_DOWN:
7950 case CTRL('n'):
7951 if (s->selected < s->ndisplayed - 1) {
7952 s->selected++;
7953 break;
7955 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7956 /* can't scroll any further */
7957 view->count = 0;
7958 break;
7960 ref_scroll_down(view, 1);
7961 break;
7962 case CTRL('d'):
7963 case 'd':
7964 nscroll /= 2;
7965 /* FALL THROUGH */
7966 case KEY_NPAGE:
7967 case CTRL('f'):
7968 case 'f':
7969 case ' ':
7970 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7971 /* can't scroll any further; move cursor down */
7972 if (s->selected < s->ndisplayed - 1)
7973 s->selected += MIN(nscroll,
7974 s->ndisplayed - s->selected - 1);
7975 if (view->count > 1 && s->selected < s->ndisplayed - 1)
7976 s->selected += s->ndisplayed - s->selected - 1;
7977 view->count = 0;
7978 break;
7980 ref_scroll_down(view, nscroll);
7981 break;
7982 case CTRL('l'):
7983 view->count = 0;
7984 tog_free_refs();
7985 err = tog_load_refs(s->repo, s->sort_by_date);
7986 if (err)
7987 break;
7988 ref_view_free_refs(s);
7989 err = ref_view_load_refs(s);
7990 break;
7991 case KEY_RESIZE:
7992 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
7993 s->selected = view->nlines - 2;
7994 break;
7995 default:
7996 view->count = 0;
7997 break;
8000 return err;
8003 __dead static void
8004 usage_ref(void)
8006 endwin();
8007 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8008 getprogname());
8009 exit(1);
8012 static const struct got_error *
8013 cmd_ref(int argc, char *argv[])
8015 const struct got_error *error;
8016 struct got_repository *repo = NULL;
8017 struct got_worktree *worktree = NULL;
8018 char *cwd = NULL, *repo_path = NULL;
8019 int ch;
8020 struct tog_view *view;
8021 int *pack_fds = NULL;
8023 while ((ch = getopt(argc, argv, "r:")) != -1) {
8024 switch (ch) {
8025 case 'r':
8026 repo_path = realpath(optarg, NULL);
8027 if (repo_path == NULL)
8028 return got_error_from_errno2("realpath",
8029 optarg);
8030 break;
8031 default:
8032 usage_ref();
8033 /* NOTREACHED */
8037 argc -= optind;
8038 argv += optind;
8040 if (argc > 1)
8041 usage_ref();
8043 error = got_repo_pack_fds_open(&pack_fds);
8044 if (error != NULL)
8045 goto done;
8047 if (repo_path == NULL) {
8048 cwd = getcwd(NULL, 0);
8049 if (cwd == NULL)
8050 return got_error_from_errno("getcwd");
8051 error = got_worktree_open(&worktree, cwd);
8052 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8053 goto done;
8054 if (worktree)
8055 repo_path =
8056 strdup(got_worktree_get_repo_path(worktree));
8057 else
8058 repo_path = strdup(cwd);
8059 if (repo_path == NULL) {
8060 error = got_error_from_errno("strdup");
8061 goto done;
8065 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8066 if (error != NULL)
8067 goto done;
8069 init_curses();
8071 error = apply_unveil(got_repo_get_path(repo), NULL);
8072 if (error)
8073 goto done;
8075 error = tog_load_refs(repo, 0);
8076 if (error)
8077 goto done;
8079 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8080 if (view == NULL) {
8081 error = got_error_from_errno("view_open");
8082 goto done;
8085 error = open_ref_view(view, repo);
8086 if (error)
8087 goto done;
8089 if (worktree) {
8090 /* Release work tree lock. */
8091 got_worktree_close(worktree);
8092 worktree = NULL;
8094 error = view_loop(view);
8095 done:
8096 free(repo_path);
8097 free(cwd);
8098 if (repo) {
8099 const struct got_error *close_err = got_repo_close(repo);
8100 if (close_err)
8101 error = close_err;
8103 if (pack_fds) {
8104 const struct got_error *pack_err =
8105 got_repo_pack_fds_close(pack_fds);
8106 if (error == NULL)
8107 error = pack_err;
8109 tog_free_refs();
8110 return error;
8113 static const struct got_error *
8114 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
8115 enum tog_view_type request, int y, int x)
8117 const struct got_error *err = NULL;
8119 *new_view = NULL;
8121 switch (request) {
8122 case TOG_VIEW_DIFF:
8123 if (view->type == TOG_VIEW_LOG) {
8124 struct tog_log_view_state *s = &view->state.log;
8126 err = open_diff_view_for_commit(new_view, y, x,
8127 s->selected_entry->commit, s->selected_entry->id,
8128 view, s->repo);
8129 } else
8130 return got_error_msg(GOT_ERR_NOT_IMPL,
8131 "parent/child view pair not supported");
8132 break;
8133 case TOG_VIEW_BLAME:
8134 if (view->type == TOG_VIEW_TREE) {
8135 struct tog_tree_view_state *s = &view->state.tree;
8137 err = blame_tree_entry(new_view, y, x,
8138 s->selected_entry, &s->parents, s->commit_id,
8139 s->repo);
8140 } else
8141 return got_error_msg(GOT_ERR_NOT_IMPL,
8142 "parent/child view pair not supported");
8143 break;
8144 case TOG_VIEW_LOG:
8145 if (view->type == TOG_VIEW_BLAME)
8146 err = log_annotated_line(new_view, y, x,
8147 view->state.blame.repo, view->state.blame.id_to_log);
8148 else if (view->type == TOG_VIEW_TREE)
8149 err = log_selected_tree_entry(new_view, y, x,
8150 &view->state.tree);
8151 else if (view->type == TOG_VIEW_REF)
8152 err = log_ref_entry(new_view, y, x,
8153 view->state.ref.selected_entry,
8154 view->state.ref.repo);
8155 else
8156 return got_error_msg(GOT_ERR_NOT_IMPL,
8157 "parent/child view pair not supported");
8158 break;
8159 case TOG_VIEW_TREE:
8160 if (view->type == TOG_VIEW_LOG)
8161 err = browse_commit_tree(new_view, y, x,
8162 view->state.log.selected_entry,
8163 view->state.log.in_repo_path,
8164 view->state.log.head_ref_name,
8165 view->state.log.repo);
8166 else if (view->type == TOG_VIEW_REF)
8167 err = browse_ref_tree(new_view, y, x,
8168 view->state.ref.selected_entry,
8169 view->state.ref.repo);
8170 else
8171 return got_error_msg(GOT_ERR_NOT_IMPL,
8172 "parent/child view pair not supported");
8173 break;
8174 case TOG_VIEW_REF:
8175 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
8176 if (*new_view == NULL)
8177 return got_error_from_errno("view_open");
8178 if (view->type == TOG_VIEW_LOG)
8179 err = open_ref_view(*new_view, view->state.log.repo);
8180 else if (view->type == TOG_VIEW_TREE)
8181 err = open_ref_view(*new_view, view->state.tree.repo);
8182 else
8183 err = got_error_msg(GOT_ERR_NOT_IMPL,
8184 "parent/child view pair not supported");
8185 if (err)
8186 view_close(*new_view);
8187 break;
8188 default:
8189 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
8192 return err;
8196 * If view was scrolled down to move the selected line into view when opening a
8197 * horizontal split, scroll back up when closing the split/toggling fullscreen.
8199 static void
8200 offset_selection_up(struct tog_view *view)
8202 switch (view->type) {
8203 case TOG_VIEW_BLAME: {
8204 struct tog_blame_view_state *s = &view->state.blame;
8205 if (s->first_displayed_line == 1) {
8206 s->selected_line = MAX(s->selected_line - view->offset,
8207 1);
8208 break;
8210 if (s->first_displayed_line > view->offset)
8211 s->first_displayed_line -= view->offset;
8212 else
8213 s->first_displayed_line = 1;
8214 s->selected_line += view->offset;
8215 break;
8217 case TOG_VIEW_LOG:
8218 log_scroll_up(&view->state.log, view->offset);
8219 view->state.log.selected += view->offset;
8220 break;
8221 case TOG_VIEW_REF:
8222 ref_scroll_up(&view->state.ref, view->offset);
8223 view->state.ref.selected += view->offset;
8224 break;
8225 case TOG_VIEW_TREE:
8226 tree_scroll_up(&view->state.tree, view->offset);
8227 view->state.tree.selected += view->offset;
8228 break;
8229 default:
8230 break;
8233 view->offset = 0;
8237 * If the selected line is in the section of screen covered by the bottom split,
8238 * scroll down offset lines to move it into view and index its new position.
8240 static const struct got_error *
8241 offset_selection_down(struct tog_view *view)
8243 const struct got_error *err = NULL;
8244 const struct got_error *(*scrolld)(struct tog_view *, int);
8245 int *selected = NULL;
8246 int header, offset;
8248 switch (view->type) {
8249 case TOG_VIEW_BLAME: {
8250 struct tog_blame_view_state *s = &view->state.blame;
8251 header = 3;
8252 scrolld = NULL;
8253 if (s->selected_line > view->nlines - header) {
8254 offset = abs(view->nlines - s->selected_line - header);
8255 s->first_displayed_line += offset;
8256 s->selected_line -= offset;
8257 view->offset = offset;
8259 break;
8261 case TOG_VIEW_LOG: {
8262 struct tog_log_view_state *s = &view->state.log;
8263 scrolld = &log_scroll_down;
8264 header = view_is_parent_view(view) ? 3 : 2;
8265 selected = &s->selected;
8266 break;
8268 case TOG_VIEW_REF: {
8269 struct tog_ref_view_state *s = &view->state.ref;
8270 scrolld = &ref_scroll_down;
8271 header = 3;
8272 selected = &s->selected;
8273 break;
8275 case TOG_VIEW_TREE: {
8276 struct tog_tree_view_state *s = &view->state.tree;
8277 scrolld = &tree_scroll_down;
8278 header = 5;
8279 selected = &s->selected;
8280 break;
8282 default:
8283 selected = NULL;
8284 scrolld = NULL;
8285 header = 0;
8286 break;
8289 if (selected && *selected > view->nlines - header) {
8290 offset = abs(view->nlines - *selected - header);
8291 view->offset = offset;
8292 if (scrolld && offset) {
8293 err = scrolld(view, offset);
8294 *selected -= offset;
8298 return err;
8301 static void
8302 list_commands(FILE *fp)
8304 size_t i;
8306 fprintf(fp, "commands:");
8307 for (i = 0; i < nitems(tog_commands); i++) {
8308 const struct tog_cmd *cmd = &tog_commands[i];
8309 fprintf(fp, " %s", cmd->name);
8311 fputc('\n', fp);
8314 __dead static void
8315 usage(int hflag, int status)
8317 FILE *fp = (status == 0) ? stdout : stderr;
8319 fprintf(fp, "usage: %s [-h] [-V | --version] [command] [arg ...]\n",
8320 getprogname());
8321 if (hflag) {
8322 fprintf(fp, "lazy usage: %s path\n", getprogname());
8323 list_commands(fp);
8325 exit(status);
8328 static char **
8329 make_argv(int argc, ...)
8331 va_list ap;
8332 char **argv;
8333 int i;
8335 va_start(ap, argc);
8337 argv = calloc(argc, sizeof(char *));
8338 if (argv == NULL)
8339 err(1, "calloc");
8340 for (i = 0; i < argc; i++) {
8341 argv[i] = strdup(va_arg(ap, char *));
8342 if (argv[i] == NULL)
8343 err(1, "strdup");
8346 va_end(ap);
8347 return argv;
8351 * Try to convert 'tog path' into a 'tog log path' command.
8352 * The user could simply have mistyped the command rather than knowingly
8353 * provided a path. So check whether argv[0] can in fact be resolved
8354 * to a path in the HEAD commit and print a special error if not.
8355 * This hack is for mpi@ <3
8357 static const struct got_error *
8358 tog_log_with_path(int argc, char *argv[])
8360 const struct got_error *error = NULL, *close_err;
8361 const struct tog_cmd *cmd = NULL;
8362 struct got_repository *repo = NULL;
8363 struct got_worktree *worktree = NULL;
8364 struct got_object_id *commit_id = NULL, *id = NULL;
8365 struct got_commit_object *commit = NULL;
8366 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8367 char *commit_id_str = NULL, **cmd_argv = NULL;
8368 int *pack_fds = NULL;
8370 cwd = getcwd(NULL, 0);
8371 if (cwd == NULL)
8372 return got_error_from_errno("getcwd");
8374 error = got_repo_pack_fds_open(&pack_fds);
8375 if (error != NULL)
8376 goto done;
8378 error = got_worktree_open(&worktree, cwd);
8379 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8380 goto done;
8382 if (worktree)
8383 repo_path = strdup(got_worktree_get_repo_path(worktree));
8384 else
8385 repo_path = strdup(cwd);
8386 if (repo_path == NULL) {
8387 error = got_error_from_errno("strdup");
8388 goto done;
8391 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8392 if (error != NULL)
8393 goto done;
8395 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8396 repo, worktree);
8397 if (error)
8398 goto done;
8400 error = tog_load_refs(repo, 0);
8401 if (error)
8402 goto done;
8403 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
8404 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
8405 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8406 if (error)
8407 goto done;
8409 if (worktree) {
8410 got_worktree_close(worktree);
8411 worktree = NULL;
8414 error = got_object_open_as_commit(&commit, repo, commit_id);
8415 if (error)
8416 goto done;
8418 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
8419 if (error) {
8420 if (error->code != GOT_ERR_NO_TREE_ENTRY)
8421 goto done;
8422 fprintf(stderr, "%s: '%s' is no known command or path\n",
8423 getprogname(), argv[0]);
8424 usage(1, 1);
8425 /* not reached */
8428 error = got_object_id_str(&commit_id_str, commit_id);
8429 if (error)
8430 goto done;
8432 cmd = &tog_commands[0]; /* log */
8433 argc = 4;
8434 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
8435 error = cmd->cmd_main(argc, cmd_argv);
8436 done:
8437 if (repo) {
8438 close_err = got_repo_close(repo);
8439 if (error == NULL)
8440 error = close_err;
8442 if (commit)
8443 got_object_commit_close(commit);
8444 if (worktree)
8445 got_worktree_close(worktree);
8446 if (pack_fds) {
8447 const struct got_error *pack_err =
8448 got_repo_pack_fds_close(pack_fds);
8449 if (error == NULL)
8450 error = pack_err;
8452 free(id);
8453 free(commit_id_str);
8454 free(commit_id);
8455 free(cwd);
8456 free(repo_path);
8457 free(in_repo_path);
8458 if (cmd_argv) {
8459 int i;
8460 for (i = 0; i < argc; i++)
8461 free(cmd_argv[i]);
8462 free(cmd_argv);
8464 tog_free_refs();
8465 return error;
8468 int
8469 main(int argc, char *argv[])
8471 const struct got_error *error = NULL;
8472 const struct tog_cmd *cmd = NULL;
8473 int ch, hflag = 0, Vflag = 0;
8474 char **cmd_argv = NULL;
8475 static const struct option longopts[] = {
8476 { "version", no_argument, NULL, 'V' },
8477 { NULL, 0, NULL, 0}
8479 char *diff_algo_str = NULL;
8481 if (!isatty(STDIN_FILENO))
8482 errx(1, "standard input is not a tty");
8484 setlocale(LC_CTYPE, "");
8486 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
8487 switch (ch) {
8488 case 'h':
8489 hflag = 1;
8490 break;
8491 case 'V':
8492 Vflag = 1;
8493 break;
8494 default:
8495 usage(hflag, 1);
8496 /* NOTREACHED */
8500 argc -= optind;
8501 argv += optind;
8502 optind = 1;
8503 optreset = 1;
8505 if (Vflag) {
8506 got_version_print_str();
8507 return 0;
8510 #ifndef PROFILE
8511 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
8512 NULL) == -1)
8513 err(1, "pledge");
8514 #endif
8516 if (argc == 0) {
8517 if (hflag)
8518 usage(hflag, 0);
8519 /* Build an argument vector which runs a default command. */
8520 cmd = &tog_commands[0];
8521 argc = 1;
8522 cmd_argv = make_argv(argc, cmd->name);
8523 } else {
8524 size_t i;
8526 /* Did the user specify a command? */
8527 for (i = 0; i < nitems(tog_commands); i++) {
8528 if (strncmp(tog_commands[i].name, argv[0],
8529 strlen(argv[0])) == 0) {
8530 cmd = &tog_commands[i];
8531 break;
8536 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
8537 if (diff_algo_str) {
8538 if (strcasecmp(diff_algo_str, "patience") == 0)
8539 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
8540 if (strcasecmp(diff_algo_str, "myers") == 0)
8541 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
8544 if (cmd == NULL) {
8545 if (argc != 1)
8546 usage(0, 1);
8547 /* No command specified; try log with a path */
8548 error = tog_log_with_path(argc, argv);
8549 } else {
8550 if (hflag)
8551 cmd->cmd_usage();
8552 else
8553 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
8556 endwin();
8557 putchar('\n');
8558 if (cmd_argv) {
8559 int i;
8560 for (i = 0; i < argc; i++)
8561 free(cmd_argv[i]);
8562 free(cmd_argv);
8565 if (error && error->code != GOT_ERR_CANCELLED)
8566 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8567 return 0;