Blob


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