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;
3169 if (s->thread_args.log_complete &&
3170 s->selected_entry->idx >= s->commits.ncommits - 1)
3171 return NULL;
3173 if (!page) {
3174 int eos = view->nlines - 2;
3176 if (view_is_hsplit_top(view))
3177 --eos; /* border consumes the last line */
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) {
3183 if (s->last_displayed_entry->idx == s->commits.ncommits - 1)
3184 s->selected += MIN(s->last_displayed_entry->idx -
3185 s->selected_entry->idx, page + 1);
3186 else
3187 err = log_scroll_down(view, MIN(page,
3188 s->commits.ncommits - s->selected_entry->idx - 1));
3189 s->selected = MIN(view->nlines - 2, s->commits.ncommits - 1);
3190 } else {
3191 if (s->last_displayed_entry->idx == s->commits.ncommits - 1 &&
3192 s->thread_args.log_complete)
3193 s->selected += MIN(page,
3194 s->commits.ncommits - s->selected_entry->idx - 1);
3195 else
3196 err = log_scroll_down(view, page);
3198 if (err)
3199 return err;
3202 * We might necessarily overshoot in horizontal
3203 * splits; if so, select the last displayed commit.
3205 s->selected = MIN(s->selected,
3206 s->last_displayed_entry->idx - s->first_displayed_entry->idx);
3208 select_commit(s);
3210 if (s->thread_args.log_complete &&
3211 s->selected_entry->idx == s->commits.ncommits - 1)
3212 view->count = 0;
3214 return NULL;
3217 static void
3218 view_get_split(struct tog_view *view, int *y, int *x)
3220 *x = 0;
3221 *y = 0;
3223 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3224 if (view->child && view->child->resized_y)
3225 *y = view->child->resized_y;
3226 else if (view->resized_y)
3227 *y = view->resized_y;
3228 else
3229 *y = view_split_begin_y(view->lines);
3230 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3231 if (view->child && view->child->resized_x)
3232 *x = view->child->resized_x;
3233 else if (view->resized_x)
3234 *x = view->resized_x;
3235 else
3236 *x = view_split_begin_x(view->begin_x);
3240 /* Split view horizontally at y and offset view->state->selected line. */
3241 static const struct got_error *
3242 view_init_hsplit(struct tog_view *view, int y)
3244 const struct got_error *err = NULL;
3246 view->nlines = y;
3247 view->ncols = COLS;
3248 err = view_resize(view);
3249 if (err)
3250 return err;
3252 err = offset_selection_down(view);
3254 return err;
3257 static const struct got_error *
3258 log_goto_line(struct tog_view *view, int nlines)
3260 const struct got_error *err = NULL;
3261 struct tog_log_view_state *s = &view->state.log;
3262 int g, idx = s->selected_entry->idx;
3264 g = view->gline;
3265 view->gline = 0;
3267 if (g >= s->first_displayed_entry->idx + 1 &&
3268 g <= s->last_displayed_entry->idx + 1 &&
3269 g - s->first_displayed_entry->idx - 1 < nlines) {
3270 s->selected = g - s->first_displayed_entry->idx - 1;
3271 select_commit(s);
3272 return NULL;
3275 if (idx + 1 < g) {
3276 err = log_move_cursor_down(view, g - idx - 1);
3277 if (!err && g > s->selected_entry->idx + 1)
3278 err = log_move_cursor_down(view,
3279 g - s->first_displayed_entry->idx - 1);
3280 if (err)
3281 return err;
3282 } else if (idx + 1 > g)
3283 log_move_cursor_up(view, idx - g + 1, 0);
3285 if (g < nlines && s->first_displayed_entry->idx == 0)
3286 s->selected = g - 1;
3288 select_commit(s);
3289 return NULL;
3293 static const struct got_error *
3294 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3296 const struct got_error *err = NULL;
3297 struct tog_log_view_state *s = &view->state.log;
3298 struct commit_queue_entry *entry;
3299 int eos, n, nscroll;
3301 if (s->thread_args.load_all) {
3302 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3303 s->thread_args.load_all = 0;
3304 else if (s->thread_args.log_complete) {
3305 err = log_move_cursor_down(view, s->commits.ncommits);
3306 s->thread_args.load_all = 0;
3308 return err;
3311 eos = nscroll = view->nlines - 1;
3312 if (view_is_hsplit_top(view))
3313 --eos; /* border */
3315 if (view->gline)
3316 return log_goto_line(view, eos);
3318 switch (ch) {
3319 case 'q':
3320 s->quit = 1;
3321 break;
3322 case '0':
3323 view->x = 0;
3324 break;
3325 case '$':
3326 view->x = MAX(view->maxx - view->ncols / 2, 0);
3327 view->count = 0;
3328 break;
3329 case KEY_RIGHT:
3330 case 'l':
3331 if (view->x + view->ncols / 2 < view->maxx)
3332 view->x += 2; /* move two columns right */
3333 else
3334 view->count = 0;
3335 break;
3336 case KEY_LEFT:
3337 case 'h':
3338 view->x -= MIN(view->x, 2); /* move two columns back */
3339 if (view->x <= 0)
3340 view->count = 0;
3341 break;
3342 case 'k':
3343 case KEY_UP:
3344 case '<':
3345 case ',':
3346 case CTRL('p'):
3347 log_move_cursor_up(view, 0, 0);
3348 break;
3349 case 'g':
3350 case KEY_HOME:
3351 log_move_cursor_up(view, 0, 1);
3352 view->count = 0;
3353 break;
3354 case CTRL('u'):
3355 case 'u':
3356 nscroll /= 2;
3357 /* FALL THROUGH */
3358 case KEY_PPAGE:
3359 case CTRL('b'):
3360 case 'b':
3361 log_move_cursor_up(view, nscroll, 0);
3362 break;
3363 case 'j':
3364 case KEY_DOWN:
3365 case '>':
3366 case '.':
3367 case CTRL('n'):
3368 err = log_move_cursor_down(view, 0);
3369 break;
3370 case '@':
3371 s->use_committer = !s->use_committer;
3372 break;
3373 case 'G':
3374 case KEY_END: {
3375 /* We don't know yet how many commits, so we're forced to
3376 * traverse them all. */
3377 view->count = 0;
3378 if (!s->thread_args.log_complete) {
3379 s->thread_args.load_all = 1;
3380 return trigger_log_thread(view, 0);
3383 s->selected = 0;
3384 entry = TAILQ_LAST(&s->commits.head, commit_queue_head);
3385 for (n = 0; n < eos; n++) {
3386 if (entry == NULL)
3387 break;
3388 s->first_displayed_entry = entry;
3389 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3391 if (n > 0)
3392 s->selected = n - 1;
3393 select_commit(s);
3394 break;
3396 case CTRL('d'):
3397 case 'd':
3398 nscroll /= 2;
3399 /* FALL THROUGH */
3400 case KEY_NPAGE:
3401 case CTRL('f'):
3402 case 'f':
3403 case ' ':
3404 err = log_move_cursor_down(view, nscroll);
3405 break;
3406 case KEY_RESIZE:
3407 if (s->selected > view->nlines - 2)
3408 s->selected = view->nlines - 2;
3409 if (s->selected > s->commits.ncommits - 1)
3410 s->selected = s->commits.ncommits - 1;
3411 select_commit(s);
3412 if (s->commits.ncommits < view->nlines - 1 &&
3413 !s->thread_args.log_complete) {
3414 s->thread_args.commits_needed += (view->nlines - 1) -
3415 s->commits.ncommits;
3416 err = trigger_log_thread(view, 1);
3418 break;
3419 case KEY_ENTER:
3420 case '\r':
3421 view->count = 0;
3422 if (s->selected_entry == NULL)
3423 break;
3424 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
3425 break;
3426 case 'T':
3427 view->count = 0;
3428 if (s->selected_entry == NULL)
3429 break;
3430 err = view_request_new(new_view, view, TOG_VIEW_TREE);
3431 break;
3432 case KEY_BACKSPACE:
3433 case CTRL('l'):
3434 case 'B':
3435 view->count = 0;
3436 if (ch == KEY_BACKSPACE &&
3437 got_path_is_root_dir(s->in_repo_path))
3438 break;
3439 err = stop_log_thread(s);
3440 if (err)
3441 return err;
3442 if (ch == KEY_BACKSPACE) {
3443 char *parent_path;
3444 err = got_path_dirname(&parent_path, s->in_repo_path);
3445 if (err)
3446 return err;
3447 free(s->in_repo_path);
3448 s->in_repo_path = parent_path;
3449 s->thread_args.in_repo_path = s->in_repo_path;
3450 } else if (ch == CTRL('l')) {
3451 struct got_object_id *start_id;
3452 err = got_repo_match_object_id(&start_id, NULL,
3453 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3454 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3455 if (err)
3456 return err;
3457 free(s->start_id);
3458 s->start_id = start_id;
3459 s->thread_args.start_id = s->start_id;
3460 } else /* 'B' */
3461 s->log_branches = !s->log_branches;
3463 if (s->thread_args.pack_fds == NULL) {
3464 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3465 if (err)
3466 return err;
3468 err = got_repo_open(&s->thread_args.repo,
3469 got_repo_get_path(s->repo), NULL,
3470 s->thread_args.pack_fds);
3471 if (err)
3472 return err;
3473 tog_free_refs();
3474 err = tog_load_refs(s->repo, 0);
3475 if (err)
3476 return err;
3477 err = got_commit_graph_open(&s->thread_args.graph,
3478 s->in_repo_path, !s->log_branches);
3479 if (err)
3480 return err;
3481 err = got_commit_graph_iter_start(s->thread_args.graph,
3482 s->start_id, s->repo, NULL, NULL);
3483 if (err)
3484 return err;
3485 free_commits(&s->commits);
3486 s->first_displayed_entry = NULL;
3487 s->last_displayed_entry = NULL;
3488 s->selected_entry = NULL;
3489 s->selected = 0;
3490 s->thread_args.log_complete = 0;
3491 s->quit = 0;
3492 s->thread_args.commits_needed = view->lines;
3493 s->matched_entry = NULL;
3494 s->search_entry = NULL;
3495 view->offset = 0;
3496 break;
3497 case 'R':
3498 view->count = 0;
3499 err = view_request_new(new_view, view, TOG_VIEW_REF);
3500 break;
3501 default:
3502 view->count = 0;
3503 break;
3506 return err;
3509 static const struct got_error *
3510 apply_unveil(const char *repo_path, const char *worktree_path)
3512 const struct got_error *error;
3514 #ifdef PROFILE
3515 if (unveil("gmon.out", "rwc") != 0)
3516 return got_error_from_errno2("unveil", "gmon.out");
3517 #endif
3518 if (repo_path && unveil(repo_path, "r") != 0)
3519 return got_error_from_errno2("unveil", repo_path);
3521 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3522 return got_error_from_errno2("unveil", worktree_path);
3524 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3525 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3527 error = got_privsep_unveil_exec_helpers();
3528 if (error != NULL)
3529 return error;
3531 if (unveil(NULL, NULL) != 0)
3532 return got_error_from_errno("unveil");
3534 return NULL;
3537 static void
3538 init_curses(void)
3541 * Override default signal handlers before starting ncurses.
3542 * This should prevent ncurses from installing its own
3543 * broken cleanup() signal handler.
3545 signal(SIGWINCH, tog_sigwinch);
3546 signal(SIGPIPE, tog_sigpipe);
3547 signal(SIGCONT, tog_sigcont);
3548 signal(SIGINT, tog_sigint);
3549 signal(SIGTERM, tog_sigterm);
3551 initscr();
3552 cbreak();
3553 halfdelay(1); /* Do fast refresh while initial view is loading. */
3554 noecho();
3555 nonl();
3556 intrflush(stdscr, FALSE);
3557 keypad(stdscr, TRUE);
3558 curs_set(0);
3559 if (getenv("TOG_COLORS") != NULL) {
3560 start_color();
3561 use_default_colors();
3565 static const struct got_error *
3566 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
3567 struct got_repository *repo, struct got_worktree *worktree)
3569 const struct got_error *err = NULL;
3571 if (argc == 0) {
3572 *in_repo_path = strdup("/");
3573 if (*in_repo_path == NULL)
3574 return got_error_from_errno("strdup");
3575 return NULL;
3578 if (worktree) {
3579 const char *prefix = got_worktree_get_path_prefix(worktree);
3580 char *p;
3582 err = got_worktree_resolve_path(&p, worktree, argv[0]);
3583 if (err)
3584 return err;
3585 if (asprintf(in_repo_path, "%s%s%s", prefix,
3586 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
3587 p) == -1) {
3588 err = got_error_from_errno("asprintf");
3589 *in_repo_path = NULL;
3591 free(p);
3592 } else
3593 err = got_repo_map_path(in_repo_path, repo, argv[0]);
3595 return err;
3598 static const struct got_error *
3599 cmd_log(int argc, char *argv[])
3601 const struct got_error *error;
3602 struct got_repository *repo = NULL;
3603 struct got_worktree *worktree = NULL;
3604 struct got_object_id *start_id = NULL;
3605 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
3606 char *start_commit = NULL, *label = NULL;
3607 struct got_reference *ref = NULL;
3608 const char *head_ref_name = NULL;
3609 int ch, log_branches = 0;
3610 struct tog_view *view;
3611 int *pack_fds = NULL;
3613 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
3614 switch (ch) {
3615 case 'b':
3616 log_branches = 1;
3617 break;
3618 case 'c':
3619 start_commit = optarg;
3620 break;
3621 case 'r':
3622 repo_path = realpath(optarg, NULL);
3623 if (repo_path == NULL)
3624 return got_error_from_errno2("realpath",
3625 optarg);
3626 break;
3627 default:
3628 usage_log();
3629 /* NOTREACHED */
3633 argc -= optind;
3634 argv += optind;
3636 if (argc > 1)
3637 usage_log();
3639 error = got_repo_pack_fds_open(&pack_fds);
3640 if (error != NULL)
3641 goto done;
3643 if (repo_path == NULL) {
3644 cwd = getcwd(NULL, 0);
3645 if (cwd == NULL)
3646 return got_error_from_errno("getcwd");
3647 error = got_worktree_open(&worktree, cwd);
3648 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3649 goto done;
3650 if (worktree)
3651 repo_path =
3652 strdup(got_worktree_get_repo_path(worktree));
3653 else
3654 repo_path = strdup(cwd);
3655 if (repo_path == NULL) {
3656 error = got_error_from_errno("strdup");
3657 goto done;
3661 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3662 if (error != NULL)
3663 goto done;
3665 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
3666 repo, worktree);
3667 if (error)
3668 goto done;
3670 init_curses();
3672 error = apply_unveil(got_repo_get_path(repo),
3673 worktree ? got_worktree_get_root_path(worktree) : NULL);
3674 if (error)
3675 goto done;
3677 /* already loaded by tog_log_with_path()? */
3678 if (TAILQ_EMPTY(&tog_refs)) {
3679 error = tog_load_refs(repo, 0);
3680 if (error)
3681 goto done;
3684 if (start_commit == NULL) {
3685 error = got_repo_match_object_id(&start_id, &label,
3686 worktree ? got_worktree_get_head_ref_name(worktree) :
3687 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3688 if (error)
3689 goto done;
3690 head_ref_name = label;
3691 } else {
3692 error = got_ref_open(&ref, repo, start_commit, 0);
3693 if (error == NULL)
3694 head_ref_name = got_ref_get_name(ref);
3695 else if (error->code != GOT_ERR_NOT_REF)
3696 goto done;
3697 error = got_repo_match_object_id(&start_id, NULL,
3698 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3699 if (error)
3700 goto done;
3703 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
3704 if (view == NULL) {
3705 error = got_error_from_errno("view_open");
3706 goto done;
3708 error = open_log_view(view, start_id, repo, head_ref_name,
3709 in_repo_path, log_branches);
3710 if (error)
3711 goto done;
3712 if (worktree) {
3713 /* Release work tree lock. */
3714 got_worktree_close(worktree);
3715 worktree = NULL;
3717 error = view_loop(view);
3718 done:
3719 free(in_repo_path);
3720 free(repo_path);
3721 free(cwd);
3722 free(start_id);
3723 free(label);
3724 if (ref)
3725 got_ref_close(ref);
3726 if (repo) {
3727 const struct got_error *close_err = got_repo_close(repo);
3728 if (error == NULL)
3729 error = close_err;
3731 if (worktree)
3732 got_worktree_close(worktree);
3733 if (pack_fds) {
3734 const struct got_error *pack_err =
3735 got_repo_pack_fds_close(pack_fds);
3736 if (error == NULL)
3737 error = pack_err;
3739 tog_free_refs();
3740 return error;
3743 __dead static void
3744 usage_diff(void)
3746 endwin();
3747 fprintf(stderr, "usage: %s diff [-a] [-C number] [-r repository-path] "
3748 "[-w] object1 object2\n", getprogname());
3749 exit(1);
3752 static int
3753 match_line(const char *line, regex_t *regex, size_t nmatch,
3754 regmatch_t *regmatch)
3756 return regexec(regex, line, nmatch, regmatch, 0) == 0;
3759 static struct tog_color *
3760 match_color(struct tog_colors *colors, const char *line)
3762 struct tog_color *tc = NULL;
3764 STAILQ_FOREACH(tc, colors, entry) {
3765 if (match_line(line, &tc->regex, 0, NULL))
3766 return tc;
3769 return NULL;
3772 static const struct got_error *
3773 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
3774 WINDOW *window, int skipcol, regmatch_t *regmatch)
3776 const struct got_error *err = NULL;
3777 char *exstr = NULL;
3778 wchar_t *wline = NULL;
3779 int rme, rms, n, width, scrollx;
3780 int width0 = 0, width1 = 0, width2 = 0;
3781 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
3783 *wtotal = 0;
3785 rms = regmatch->rm_so;
3786 rme = regmatch->rm_eo;
3788 err = expand_tab(&exstr, line);
3789 if (err)
3790 return err;
3792 /* Split the line into 3 segments, according to match offsets. */
3793 seg0 = strndup(exstr, rms);
3794 if (seg0 == NULL) {
3795 err = got_error_from_errno("strndup");
3796 goto done;
3798 seg1 = strndup(exstr + rms, rme - rms);
3799 if (seg1 == NULL) {
3800 err = got_error_from_errno("strndup");
3801 goto done;
3803 seg2 = strdup(exstr + rme);
3804 if (seg2 == NULL) {
3805 err = got_error_from_errno("strndup");
3806 goto done;
3809 /* draw up to matched token if we haven't scrolled past it */
3810 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
3811 col_tab_align, 1);
3812 if (err)
3813 goto done;
3814 n = MAX(width0 - skipcol, 0);
3815 if (n) {
3816 free(wline);
3817 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
3818 wlimit, col_tab_align, 1);
3819 if (err)
3820 goto done;
3821 waddwstr(window, &wline[scrollx]);
3822 wlimit -= width;
3823 *wtotal += width;
3826 if (wlimit > 0) {
3827 int i = 0, w = 0;
3828 size_t wlen;
3830 free(wline);
3831 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
3832 col_tab_align, 1);
3833 if (err)
3834 goto done;
3835 wlen = wcslen(wline);
3836 while (i < wlen) {
3837 width = wcwidth(wline[i]);
3838 if (width == -1) {
3839 /* should not happen, tabs are expanded */
3840 err = got_error(GOT_ERR_RANGE);
3841 goto done;
3843 if (width0 + w + width > skipcol)
3844 break;
3845 w += width;
3846 i++;
3848 /* draw (visible part of) matched token (if scrolled into it) */
3849 if (width1 - w > 0) {
3850 wattron(window, A_STANDOUT);
3851 waddwstr(window, &wline[i]);
3852 wattroff(window, A_STANDOUT);
3853 wlimit -= (width1 - w);
3854 *wtotal += (width1 - w);
3858 if (wlimit > 0) { /* draw rest of line */
3859 free(wline);
3860 if (skipcol > width0 + width1) {
3861 err = format_line(&wline, &width2, &scrollx, seg2,
3862 skipcol - (width0 + width1), wlimit,
3863 col_tab_align, 1);
3864 if (err)
3865 goto done;
3866 waddwstr(window, &wline[scrollx]);
3867 } else {
3868 err = format_line(&wline, &width2, NULL, seg2, 0,
3869 wlimit, col_tab_align, 1);
3870 if (err)
3871 goto done;
3872 waddwstr(window, wline);
3874 *wtotal += width2;
3876 done:
3877 free(wline);
3878 free(exstr);
3879 free(seg0);
3880 free(seg1);
3881 free(seg2);
3882 return err;
3885 static int
3886 gotoline(struct tog_view *view, int *lineno, int *nprinted)
3888 FILE *f = NULL;
3889 int *eof, *first, *selected;
3891 if (view->type == TOG_VIEW_DIFF) {
3892 struct tog_diff_view_state *s = &view->state.diff;
3894 first = &s->first_displayed_line;
3895 selected = first;
3896 eof = &s->eof;
3897 f = s->f;
3898 } else if (view->type == TOG_VIEW_BLAME) {
3899 struct tog_blame_view_state *s = &view->state.blame;
3901 first = &s->first_displayed_line;
3902 selected = &s->selected_line;
3903 eof = &s->eof;
3904 f = s->blame.f;
3905 } else
3906 return 0;
3908 /* Center gline in the middle of the page like vi(1). */
3909 if (*lineno < view->gline - (view->nlines - 3) / 2)
3910 return 0;
3911 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
3912 rewind(f);
3913 *eof = 0;
3914 *first = 1;
3915 *lineno = 0;
3916 *nprinted = 0;
3917 return 0;
3920 *selected = view->gline <= (view->nlines - 3) / 2 ?
3921 view->gline : (view->nlines - 3) / 2 + 1;
3922 view->gline = 0;
3924 return 1;
3927 static const struct got_error *
3928 draw_file(struct tog_view *view, const char *header)
3930 struct tog_diff_view_state *s = &view->state.diff;
3931 regmatch_t *regmatch = &view->regmatch;
3932 const struct got_error *err;
3933 int nprinted = 0;
3934 char *line;
3935 size_t linesize = 0;
3936 ssize_t linelen;
3937 wchar_t *wline;
3938 int width;
3939 int max_lines = view->nlines;
3940 int nlines = s->nlines;
3941 off_t line_offset;
3943 s->lineno = s->first_displayed_line - 1;
3944 line_offset = s->lines[s->first_displayed_line - 1].offset;
3945 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
3946 return got_error_from_errno("fseek");
3948 werase(view->window);
3950 if (view->gline > s->nlines - 1)
3951 view->gline = s->nlines - 1;
3953 if (header) {
3954 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
3955 1 : view->gline - (view->nlines - 3) / 2 :
3956 s->lineno + s->selected_line;
3958 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
3959 return got_error_from_errno("asprintf");
3960 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
3961 0, 0);
3962 free(line);
3963 if (err)
3964 return err;
3966 if (view_needs_focus_indication(view))
3967 wstandout(view->window);
3968 waddwstr(view->window, wline);
3969 free(wline);
3970 wline = NULL;
3971 if (view_needs_focus_indication(view))
3972 wstandend(view->window);
3973 if (width <= view->ncols - 1)
3974 waddch(view->window, '\n');
3976 if (max_lines <= 1)
3977 return NULL;
3978 max_lines--;
3981 s->eof = 0;
3982 view->maxx = 0;
3983 line = NULL;
3984 while (max_lines > 0 && nprinted < max_lines) {
3985 enum got_diff_line_type linetype;
3986 attr_t attr = 0;
3988 linelen = getline(&line, &linesize, s->f);
3989 if (linelen == -1) {
3990 if (feof(s->f)) {
3991 s->eof = 1;
3992 break;
3994 free(line);
3995 return got_ferror(s->f, GOT_ERR_IO);
3998 if (++s->lineno < s->first_displayed_line)
3999 continue;
4000 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4001 continue;
4002 if (s->lineno == view->hiline)
4003 attr = A_STANDOUT;
4005 /* Set view->maxx based on full line length. */
4006 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4007 view->x ? 1 : 0);
4008 if (err) {
4009 free(line);
4010 return err;
4012 view->maxx = MAX(view->maxx, width);
4013 free(wline);
4014 wline = NULL;
4016 linetype = s->lines[s->lineno].type;
4017 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4018 linetype < GOT_DIFF_LINE_CONTEXT)
4019 attr |= COLOR_PAIR(linetype);
4020 if (attr)
4021 wattron(view->window, attr);
4022 if (s->first_displayed_line + nprinted == s->matched_line &&
4023 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4024 err = add_matched_line(&width, line, view->ncols, 0,
4025 view->window, view->x, regmatch);
4026 if (err) {
4027 free(line);
4028 return err;
4030 } else {
4031 int skip;
4032 err = format_line(&wline, &width, &skip, line,
4033 view->x, view->ncols, 0, view->x ? 1 : 0);
4034 if (err) {
4035 free(line);
4036 return err;
4038 waddwstr(view->window, &wline[skip]);
4039 free(wline);
4040 wline = NULL;
4042 if (s->lineno == view->hiline) {
4043 /* highlight full gline length */
4044 while (width++ < view->ncols)
4045 waddch(view->window, ' ');
4046 } else {
4047 if (width <= view->ncols - 1)
4048 waddch(view->window, '\n');
4050 if (attr)
4051 wattroff(view->window, attr);
4052 if (++nprinted == 1)
4053 s->first_displayed_line = s->lineno;
4055 free(line);
4056 if (nprinted >= 1)
4057 s->last_displayed_line = s->first_displayed_line +
4058 (nprinted - 1);
4059 else
4060 s->last_displayed_line = s->first_displayed_line;
4062 view_border(view);
4064 if (s->eof) {
4065 while (nprinted < view->nlines) {
4066 waddch(view->window, '\n');
4067 nprinted++;
4070 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4071 view->ncols, 0, 0);
4072 if (err) {
4073 return err;
4076 wstandout(view->window);
4077 waddwstr(view->window, wline);
4078 free(wline);
4079 wline = NULL;
4080 wstandend(view->window);
4083 return NULL;
4086 static char *
4087 get_datestr(time_t *time, char *datebuf)
4089 struct tm mytm, *tm;
4090 char *p, *s;
4092 tm = gmtime_r(time, &mytm);
4093 if (tm == NULL)
4094 return NULL;
4095 s = asctime_r(tm, datebuf);
4096 if (s == NULL)
4097 return NULL;
4098 p = strchr(s, '\n');
4099 if (p)
4100 *p = '\0';
4101 return s;
4104 static const struct got_error *
4105 get_changed_paths(struct got_pathlist_head *paths,
4106 struct got_commit_object *commit, struct got_repository *repo)
4108 const struct got_error *err = NULL;
4109 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
4110 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
4111 struct got_object_qid *qid;
4113 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
4114 if (qid != NULL) {
4115 struct got_commit_object *pcommit;
4116 err = got_object_open_as_commit(&pcommit, repo,
4117 &qid->id);
4118 if (err)
4119 return err;
4121 tree_id1 = got_object_id_dup(
4122 got_object_commit_get_tree_id(pcommit));
4123 if (tree_id1 == NULL) {
4124 got_object_commit_close(pcommit);
4125 return got_error_from_errno("got_object_id_dup");
4127 got_object_commit_close(pcommit);
4131 if (tree_id1) {
4132 err = got_object_open_as_tree(&tree1, repo, tree_id1);
4133 if (err)
4134 goto done;
4137 tree_id2 = got_object_commit_get_tree_id(commit);
4138 err = got_object_open_as_tree(&tree2, repo, tree_id2);
4139 if (err)
4140 goto done;
4142 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
4143 got_diff_tree_collect_changed_paths, paths, 0);
4144 done:
4145 if (tree1)
4146 got_object_tree_close(tree1);
4147 if (tree2)
4148 got_object_tree_close(tree2);
4149 free(tree_id1);
4150 return err;
4153 static const struct got_error *
4154 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4155 off_t off, uint8_t type)
4157 struct got_diff_line *p;
4159 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4160 if (p == NULL)
4161 return got_error_from_errno("reallocarray");
4162 *lines = p;
4163 (*lines)[*nlines].offset = off;
4164 (*lines)[*nlines].type = type;
4165 (*nlines)++;
4167 return NULL;
4170 static const struct got_error *
4171 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4172 struct got_object_id *commit_id, struct got_reflist_head *refs,
4173 struct got_repository *repo, FILE *outfile)
4175 const struct got_error *err = NULL;
4176 char datebuf[26], *datestr;
4177 struct got_commit_object *commit;
4178 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4179 time_t committer_time;
4180 const char *author, *committer;
4181 char *refs_str = NULL;
4182 struct got_pathlist_head changed_paths;
4183 struct got_pathlist_entry *pe;
4184 off_t outoff = 0;
4185 int n;
4187 TAILQ_INIT(&changed_paths);
4189 if (refs) {
4190 err = build_refs_str(&refs_str, refs, commit_id, repo);
4191 if (err)
4192 return err;
4195 err = got_object_open_as_commit(&commit, repo, commit_id);
4196 if (err)
4197 return err;
4199 err = got_object_id_str(&id_str, commit_id);
4200 if (err) {
4201 err = got_error_from_errno("got_object_id_str");
4202 goto done;
4205 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4206 if (err)
4207 goto done;
4209 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4210 refs_str ? refs_str : "", refs_str ? ")" : "");
4211 if (n < 0) {
4212 err = got_error_from_errno("fprintf");
4213 goto done;
4215 outoff += n;
4216 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4217 if (err)
4218 goto done;
4220 n = fprintf(outfile, "from: %s\n",
4221 got_object_commit_get_author(commit));
4222 if (n < 0) {
4223 err = got_error_from_errno("fprintf");
4224 goto done;
4226 outoff += n;
4227 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4228 if (err)
4229 goto done;
4231 committer_time = got_object_commit_get_committer_time(commit);
4232 datestr = get_datestr(&committer_time, datebuf);
4233 if (datestr) {
4234 n = fprintf(outfile, "date: %s UTC\n", datestr);
4235 if (n < 0) {
4236 err = got_error_from_errno("fprintf");
4237 goto done;
4239 outoff += n;
4240 err = add_line_metadata(lines, nlines, outoff,
4241 GOT_DIFF_LINE_DATE);
4242 if (err)
4243 goto done;
4245 author = got_object_commit_get_author(commit);
4246 committer = got_object_commit_get_committer(commit);
4247 if (strcmp(author, committer) != 0) {
4248 n = fprintf(outfile, "via: %s\n", committer);
4249 if (n < 0) {
4250 err = got_error_from_errno("fprintf");
4251 goto done;
4253 outoff += n;
4254 err = add_line_metadata(lines, nlines, outoff,
4255 GOT_DIFF_LINE_AUTHOR);
4256 if (err)
4257 goto done;
4259 if (got_object_commit_get_nparents(commit) > 1) {
4260 const struct got_object_id_queue *parent_ids;
4261 struct got_object_qid *qid;
4262 int pn = 1;
4263 parent_ids = got_object_commit_get_parent_ids(commit);
4264 STAILQ_FOREACH(qid, parent_ids, entry) {
4265 err = got_object_id_str(&id_str, &qid->id);
4266 if (err)
4267 goto done;
4268 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4269 if (n < 0) {
4270 err = got_error_from_errno("fprintf");
4271 goto done;
4273 outoff += n;
4274 err = add_line_metadata(lines, nlines, outoff,
4275 GOT_DIFF_LINE_META);
4276 if (err)
4277 goto done;
4278 free(id_str);
4279 id_str = NULL;
4283 err = got_object_commit_get_logmsg(&logmsg, commit);
4284 if (err)
4285 goto done;
4286 s = logmsg;
4287 while ((line = strsep(&s, "\n")) != NULL) {
4288 n = fprintf(outfile, "%s\n", line);
4289 if (n < 0) {
4290 err = got_error_from_errno("fprintf");
4291 goto done;
4293 outoff += n;
4294 err = add_line_metadata(lines, nlines, outoff,
4295 GOT_DIFF_LINE_LOGMSG);
4296 if (err)
4297 goto done;
4300 err = get_changed_paths(&changed_paths, commit, repo);
4301 if (err)
4302 goto done;
4303 TAILQ_FOREACH(pe, &changed_paths, entry) {
4304 struct got_diff_changed_path *cp = pe->data;
4305 n = fprintf(outfile, "%c %s\n", cp->status, pe->path);
4306 if (n < 0) {
4307 err = got_error_from_errno("fprintf");
4308 goto done;
4310 outoff += n;
4311 err = add_line_metadata(lines, nlines, outoff,
4312 GOT_DIFF_LINE_CHANGES);
4313 if (err)
4314 goto done;
4315 free((char *)pe->path);
4316 free(pe->data);
4319 fputc('\n', outfile);
4320 outoff++;
4321 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4322 done:
4323 got_pathlist_free(&changed_paths);
4324 free(id_str);
4325 free(logmsg);
4326 free(refs_str);
4327 got_object_commit_close(commit);
4328 if (err) {
4329 free(*lines);
4330 *lines = NULL;
4331 *nlines = 0;
4333 return err;
4336 static const struct got_error *
4337 create_diff(struct tog_diff_view_state *s)
4339 const struct got_error *err = NULL;
4340 FILE *f = NULL;
4341 int obj_type;
4343 free(s->lines);
4344 s->lines = malloc(sizeof(*s->lines));
4345 if (s->lines == NULL)
4346 return got_error_from_errno("malloc");
4347 s->nlines = 0;
4349 f = got_opentemp();
4350 if (f == NULL) {
4351 err = got_error_from_errno("got_opentemp");
4352 goto done;
4354 if (s->f && fclose(s->f) == EOF) {
4355 err = got_error_from_errno("fclose");
4356 goto done;
4358 s->f = f;
4360 if (s->id1)
4361 err = got_object_get_type(&obj_type, s->repo, s->id1);
4362 else
4363 err = got_object_get_type(&obj_type, s->repo, s->id2);
4364 if (err)
4365 goto done;
4367 switch (obj_type) {
4368 case GOT_OBJ_TYPE_BLOB:
4369 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
4370 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4371 s->label1, s->label2, tog_diff_algo, s->diff_context,
4372 s->ignore_whitespace, s->force_text_diff, s->repo, s->f);
4373 break;
4374 case GOT_OBJ_TYPE_TREE:
4375 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
4376 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4377 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4378 s->force_text_diff, s->repo, s->f);
4379 break;
4380 case GOT_OBJ_TYPE_COMMIT: {
4381 const struct got_object_id_queue *parent_ids;
4382 struct got_object_qid *pid;
4383 struct got_commit_object *commit2;
4384 struct got_reflist_head *refs;
4386 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4387 if (err)
4388 goto done;
4389 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4390 /* Show commit info if we're diffing to a parent/root commit. */
4391 if (s->id1 == NULL) {
4392 err = write_commit_info(&s->lines, &s->nlines, s->id2,
4393 refs, s->repo, s->f);
4394 if (err)
4395 goto done;
4396 } else {
4397 parent_ids = got_object_commit_get_parent_ids(commit2);
4398 STAILQ_FOREACH(pid, parent_ids, entry) {
4399 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4400 err = write_commit_info(&s->lines,
4401 &s->nlines, s->id2, refs, s->repo,
4402 s->f);
4403 if (err)
4404 goto done;
4405 break;
4409 got_object_commit_close(commit2);
4411 err = got_diff_objects_as_commits(&s->lines, &s->nlines,
4412 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4413 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4414 s->force_text_diff, s->repo, s->f);
4415 break;
4417 default:
4418 err = got_error(GOT_ERR_OBJ_TYPE);
4419 break;
4421 done:
4422 if (s->f && fflush(s->f) != 0 && err == NULL)
4423 err = got_error_from_errno("fflush");
4424 return err;
4427 static void
4428 diff_view_indicate_progress(struct tog_view *view)
4430 mvwaddstr(view->window, 0, 0, "diffing...");
4431 update_panels();
4432 doupdate();
4435 static const struct got_error *
4436 search_start_diff_view(struct tog_view *view)
4438 struct tog_diff_view_state *s = &view->state.diff;
4440 s->matched_line = 0;
4441 return NULL;
4444 static const struct got_error *
4445 search_next_diff_view(struct tog_view *view)
4447 struct tog_diff_view_state *s = &view->state.diff;
4448 const struct got_error *err = NULL;
4449 int lineno;
4450 char *line = NULL;
4451 size_t linesize = 0;
4452 ssize_t linelen;
4454 if (!view->searching) {
4455 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4456 return NULL;
4459 if (s->matched_line) {
4460 if (view->searching == TOG_SEARCH_FORWARD)
4461 lineno = s->matched_line + 1;
4462 else
4463 lineno = s->matched_line - 1;
4464 } else
4465 lineno = s->first_displayed_line;
4467 while (1) {
4468 off_t offset;
4470 if (lineno <= 0 || lineno > s->nlines) {
4471 if (s->matched_line == 0) {
4472 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4473 break;
4476 if (view->searching == TOG_SEARCH_FORWARD)
4477 lineno = 1;
4478 else
4479 lineno = s->nlines;
4482 offset = s->lines[lineno - 1].offset;
4483 if (fseeko(s->f, offset, SEEK_SET) != 0) {
4484 free(line);
4485 return got_error_from_errno("fseeko");
4487 linelen = getline(&line, &linesize, s->f);
4488 if (linelen != -1) {
4489 char *exstr;
4490 err = expand_tab(&exstr, line);
4491 if (err)
4492 break;
4493 if (match_line(exstr, &view->regex, 1,
4494 &view->regmatch)) {
4495 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4496 s->matched_line = lineno;
4497 free(exstr);
4498 break;
4500 free(exstr);
4502 if (view->searching == TOG_SEARCH_FORWARD)
4503 lineno++;
4504 else
4505 lineno--;
4507 free(line);
4509 if (s->matched_line) {
4510 s->first_displayed_line = s->matched_line;
4511 s->selected_line = 1;
4514 return err;
4517 static const struct got_error *
4518 close_diff_view(struct tog_view *view)
4520 const struct got_error *err = NULL;
4521 struct tog_diff_view_state *s = &view->state.diff;
4523 free(s->id1);
4524 s->id1 = NULL;
4525 free(s->id2);
4526 s->id2 = NULL;
4527 if (s->f && fclose(s->f) == EOF)
4528 err = got_error_from_errno("fclose");
4529 s->f = NULL;
4530 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
4531 err = got_error_from_errno("fclose");
4532 s->f1 = NULL;
4533 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
4534 err = got_error_from_errno("fclose");
4535 s->f2 = NULL;
4536 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
4537 err = got_error_from_errno("close");
4538 s->fd1 = -1;
4539 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
4540 err = got_error_from_errno("close");
4541 s->fd2 = -1;
4542 free(s->lines);
4543 s->lines = NULL;
4544 s->nlines = 0;
4545 return err;
4548 static const struct got_error *
4549 open_diff_view(struct tog_view *view, struct got_object_id *id1,
4550 struct got_object_id *id2, const char *label1, const char *label2,
4551 int diff_context, int ignore_whitespace, int force_text_diff,
4552 struct tog_view *parent_view, struct got_repository *repo)
4554 const struct got_error *err;
4555 struct tog_diff_view_state *s = &view->state.diff;
4557 memset(s, 0, sizeof(*s));
4558 s->fd1 = -1;
4559 s->fd2 = -1;
4561 if (id1 != NULL && id2 != NULL) {
4562 int type1, type2;
4563 err = got_object_get_type(&type1, repo, id1);
4564 if (err)
4565 return err;
4566 err = got_object_get_type(&type2, repo, id2);
4567 if (err)
4568 return err;
4570 if (type1 != type2)
4571 return got_error(GOT_ERR_OBJ_TYPE);
4573 s->first_displayed_line = 1;
4574 s->last_displayed_line = view->nlines;
4575 s->selected_line = 1;
4576 s->repo = repo;
4577 s->id1 = id1;
4578 s->id2 = id2;
4579 s->label1 = label1;
4580 s->label2 = label2;
4582 if (id1) {
4583 s->id1 = got_object_id_dup(id1);
4584 if (s->id1 == NULL)
4585 return got_error_from_errno("got_object_id_dup");
4586 } else
4587 s->id1 = NULL;
4589 s->id2 = got_object_id_dup(id2);
4590 if (s->id2 == NULL) {
4591 err = got_error_from_errno("got_object_id_dup");
4592 goto done;
4595 s->f1 = got_opentemp();
4596 if (s->f1 == NULL) {
4597 err = got_error_from_errno("got_opentemp");
4598 goto done;
4601 s->f2 = got_opentemp();
4602 if (s->f2 == NULL) {
4603 err = got_error_from_errno("got_opentemp");
4604 goto done;
4607 s->fd1 = got_opentempfd();
4608 if (s->fd1 == -1) {
4609 err = got_error_from_errno("got_opentempfd");
4610 goto done;
4613 s->fd2 = got_opentempfd();
4614 if (s->fd2 == -1) {
4615 err = got_error_from_errno("got_opentempfd");
4616 goto done;
4619 s->first_displayed_line = 1;
4620 s->last_displayed_line = view->nlines;
4621 s->diff_context = diff_context;
4622 s->ignore_whitespace = ignore_whitespace;
4623 s->force_text_diff = force_text_diff;
4624 s->parent_view = parent_view;
4625 s->repo = repo;
4627 if (has_colors() && getenv("TOG_COLORS") != NULL) {
4628 int rc;
4630 rc = init_pair(GOT_DIFF_LINE_MINUS,
4631 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
4632 if (rc != ERR)
4633 rc = init_pair(GOT_DIFF_LINE_PLUS,
4634 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
4635 if (rc != ERR)
4636 rc = init_pair(GOT_DIFF_LINE_HUNK,
4637 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
4638 if (rc != ERR)
4639 rc = init_pair(GOT_DIFF_LINE_META,
4640 get_color_value("TOG_COLOR_DIFF_META"), -1);
4641 if (rc != ERR)
4642 rc = init_pair(GOT_DIFF_LINE_CHANGES,
4643 get_color_value("TOG_COLOR_DIFF_META"), -1);
4644 if (rc != ERR)
4645 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
4646 get_color_value("TOG_COLOR_DIFF_META"), -1);
4647 if (rc != ERR)
4648 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
4649 get_color_value("TOG_COLOR_DIFF_META"), -1);
4650 if (rc != ERR)
4651 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
4652 get_color_value("TOG_COLOR_AUTHOR"), -1);
4653 if (rc != ERR)
4654 rc = init_pair(GOT_DIFF_LINE_DATE,
4655 get_color_value("TOG_COLOR_DATE"), -1);
4656 if (rc == ERR) {
4657 err = got_error(GOT_ERR_RANGE);
4658 goto done;
4662 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
4663 view_is_splitscreen(view))
4664 show_log_view(parent_view); /* draw border */
4665 diff_view_indicate_progress(view);
4667 err = create_diff(s);
4669 view->show = show_diff_view;
4670 view->input = input_diff_view;
4671 view->reset = reset_diff_view;
4672 view->close = close_diff_view;
4673 view->search_start = search_start_diff_view;
4674 view->search_next = search_next_diff_view;
4675 done:
4676 if (err)
4677 close_diff_view(view);
4678 return err;
4681 static const struct got_error *
4682 show_diff_view(struct tog_view *view)
4684 const struct got_error *err;
4685 struct tog_diff_view_state *s = &view->state.diff;
4686 char *id_str1 = NULL, *id_str2, *header;
4687 const char *label1, *label2;
4689 if (s->id1) {
4690 err = got_object_id_str(&id_str1, s->id1);
4691 if (err)
4692 return err;
4693 label1 = s->label1 ? : id_str1;
4694 } else
4695 label1 = "/dev/null";
4697 err = got_object_id_str(&id_str2, s->id2);
4698 if (err)
4699 return err;
4700 label2 = s->label2 ? : id_str2;
4702 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
4703 err = got_error_from_errno("asprintf");
4704 free(id_str1);
4705 free(id_str2);
4706 return err;
4708 free(id_str1);
4709 free(id_str2);
4711 err = draw_file(view, header);
4712 free(header);
4713 return err;
4716 static const struct got_error *
4717 set_selected_commit(struct tog_diff_view_state *s,
4718 struct commit_queue_entry *entry)
4720 const struct got_error *err;
4721 const struct got_object_id_queue *parent_ids;
4722 struct got_commit_object *selected_commit;
4723 struct got_object_qid *pid;
4725 free(s->id2);
4726 s->id2 = got_object_id_dup(entry->id);
4727 if (s->id2 == NULL)
4728 return got_error_from_errno("got_object_id_dup");
4730 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
4731 if (err)
4732 return err;
4733 parent_ids = got_object_commit_get_parent_ids(selected_commit);
4734 free(s->id1);
4735 pid = STAILQ_FIRST(parent_ids);
4736 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
4737 got_object_commit_close(selected_commit);
4738 return NULL;
4741 static const struct got_error *
4742 reset_diff_view(struct tog_view *view)
4744 struct tog_diff_view_state *s = &view->state.diff;
4746 view->count = 0;
4747 wclear(view->window);
4748 s->first_displayed_line = 1;
4749 s->last_displayed_line = view->nlines;
4750 s->matched_line = 0;
4751 diff_view_indicate_progress(view);
4752 return create_diff(s);
4755 static void
4756 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
4758 int start, i;
4760 i = start = s->first_displayed_line - 1;
4762 while (s->lines[i].type != type) {
4763 if (i == 0)
4764 i = s->nlines - 1;
4765 if (--i == start)
4766 return; /* do nothing, requested type not in file */
4769 s->selected_line = 1;
4770 s->first_displayed_line = i;
4773 static void
4774 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
4776 int start, i;
4778 i = start = s->first_displayed_line + 1;
4780 while (s->lines[i].type != type) {
4781 if (i == s->nlines - 1)
4782 i = 0;
4783 if (++i == start)
4784 return; /* do nothing, requested type not in file */
4787 s->selected_line = 1;
4788 s->first_displayed_line = i;
4791 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
4792 int, int, int);
4793 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
4794 int, int);
4796 static const struct got_error *
4797 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
4799 const struct got_error *err = NULL;
4800 struct tog_diff_view_state *s = &view->state.diff;
4801 struct tog_log_view_state *ls;
4802 struct commit_queue_entry *old_selected_entry;
4803 char *line = NULL;
4804 size_t linesize = 0;
4805 ssize_t linelen;
4806 int i, nscroll = view->nlines - 1, up = 0;
4808 s->lineno = s->first_displayed_line - 1 + s->selected_line;
4810 switch (ch) {
4811 case '0':
4812 view->x = 0;
4813 break;
4814 case '$':
4815 view->x = MAX(view->maxx - view->ncols / 3, 0);
4816 view->count = 0;
4817 break;
4818 case KEY_RIGHT:
4819 case 'l':
4820 if (view->x + view->ncols / 3 < view->maxx)
4821 view->x += 2; /* move two columns right */
4822 else
4823 view->count = 0;
4824 break;
4825 case KEY_LEFT:
4826 case 'h':
4827 view->x -= MIN(view->x, 2); /* move two columns back */
4828 if (view->x <= 0)
4829 view->count = 0;
4830 break;
4831 case 'a':
4832 case 'w':
4833 if (ch == 'a')
4834 s->force_text_diff = !s->force_text_diff;
4835 if (ch == 'w')
4836 s->ignore_whitespace = !s->ignore_whitespace;
4837 err = reset_diff_view(view);
4838 break;
4839 case 'g':
4840 case KEY_HOME:
4841 s->first_displayed_line = 1;
4842 view->count = 0;
4843 break;
4844 case 'G':
4845 case KEY_END:
4846 view->count = 0;
4847 if (s->eof)
4848 break;
4850 s->first_displayed_line = (s->nlines - view->nlines) + 2;
4851 s->eof = 1;
4852 break;
4853 case 'k':
4854 case KEY_UP:
4855 case CTRL('p'):
4856 if (s->first_displayed_line > 1)
4857 s->first_displayed_line--;
4858 else
4859 view->count = 0;
4860 break;
4861 case CTRL('u'):
4862 case 'u':
4863 nscroll /= 2;
4864 /* FALL THROUGH */
4865 case KEY_PPAGE:
4866 case CTRL('b'):
4867 case 'b':
4868 if (s->first_displayed_line == 1) {
4869 view->count = 0;
4870 break;
4872 i = 0;
4873 while (i++ < nscroll && s->first_displayed_line > 1)
4874 s->first_displayed_line--;
4875 break;
4876 case 'j':
4877 case KEY_DOWN:
4878 case CTRL('n'):
4879 if (!s->eof)
4880 s->first_displayed_line++;
4881 else
4882 view->count = 0;
4883 break;
4884 case CTRL('d'):
4885 case 'd':
4886 nscroll /= 2;
4887 /* FALL THROUGH */
4888 case KEY_NPAGE:
4889 case CTRL('f'):
4890 case 'f':
4891 case ' ':
4892 if (s->eof) {
4893 view->count = 0;
4894 break;
4896 i = 0;
4897 while (!s->eof && i++ < nscroll) {
4898 linelen = getline(&line, &linesize, s->f);
4899 s->first_displayed_line++;
4900 if (linelen == -1) {
4901 if (feof(s->f)) {
4902 s->eof = 1;
4903 } else
4904 err = got_ferror(s->f, GOT_ERR_IO);
4905 break;
4908 free(line);
4909 break;
4910 case '(':
4911 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
4912 break;
4913 case ')':
4914 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
4915 break;
4916 case '{':
4917 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
4918 break;
4919 case '}':
4920 diff_next_index(s, GOT_DIFF_LINE_HUNK);
4921 break;
4922 case '[':
4923 if (s->diff_context > 0) {
4924 s->diff_context--;
4925 s->matched_line = 0;
4926 diff_view_indicate_progress(view);
4927 err = create_diff(s);
4928 if (s->first_displayed_line + view->nlines - 1 >
4929 s->nlines) {
4930 s->first_displayed_line = 1;
4931 s->last_displayed_line = view->nlines;
4933 } else
4934 view->count = 0;
4935 break;
4936 case ']':
4937 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
4938 s->diff_context++;
4939 s->matched_line = 0;
4940 diff_view_indicate_progress(view);
4941 err = create_diff(s);
4942 } else
4943 view->count = 0;
4944 break;
4945 case '<':
4946 case ',':
4947 case 'K':
4948 up = 1;
4949 /* FALL THROUGH */
4950 case '>':
4951 case '.':
4952 case 'J':
4953 if (s->parent_view == NULL) {
4954 view->count = 0;
4955 break;
4957 s->parent_view->count = view->count;
4959 if (s->parent_view->type == TOG_VIEW_LOG) {
4960 ls = &s->parent_view->state.log;
4961 old_selected_entry = ls->selected_entry;
4963 err = input_log_view(NULL, s->parent_view,
4964 up ? KEY_UP : KEY_DOWN);
4965 if (err)
4966 break;
4967 view->count = s->parent_view->count;
4969 if (old_selected_entry == ls->selected_entry)
4970 break;
4972 err = set_selected_commit(s, ls->selected_entry);
4973 if (err)
4974 break;
4975 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
4976 struct tog_blame_view_state *bs;
4977 struct got_object_id *id, *prev_id;
4979 bs = &s->parent_view->state.blame;
4980 prev_id = get_annotation_for_line(bs->blame.lines,
4981 bs->blame.nlines, bs->last_diffed_line);
4983 err = input_blame_view(&view, s->parent_view,
4984 up ? KEY_UP : KEY_DOWN);
4985 if (err)
4986 break;
4987 view->count = s->parent_view->count;
4989 if (prev_id == NULL)
4990 break;
4991 id = get_selected_commit_id(bs->blame.lines,
4992 bs->blame.nlines, bs->first_displayed_line,
4993 bs->selected_line);
4994 if (id == NULL)
4995 break;
4997 if (!got_object_id_cmp(prev_id, id))
4998 break;
5000 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5001 if (err)
5002 break;
5004 s->first_displayed_line = 1;
5005 s->last_displayed_line = view->nlines;
5006 s->matched_line = 0;
5007 view->x = 0;
5009 diff_view_indicate_progress(view);
5010 err = create_diff(s);
5011 break;
5012 default:
5013 view->count = 0;
5014 break;
5017 return err;
5020 static const struct got_error *
5021 cmd_diff(int argc, char *argv[])
5023 const struct got_error *error = NULL;
5024 struct got_repository *repo = NULL;
5025 struct got_worktree *worktree = NULL;
5026 struct got_object_id *id1 = NULL, *id2 = NULL;
5027 char *repo_path = NULL, *cwd = NULL;
5028 char *id_str1 = NULL, *id_str2 = NULL;
5029 char *label1 = NULL, *label2 = NULL;
5030 int diff_context = 3, ignore_whitespace = 0;
5031 int ch, force_text_diff = 0;
5032 const char *errstr;
5033 struct tog_view *view;
5034 int *pack_fds = NULL;
5036 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5037 switch (ch) {
5038 case 'a':
5039 force_text_diff = 1;
5040 break;
5041 case 'C':
5042 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5043 &errstr);
5044 if (errstr != NULL)
5045 errx(1, "number of context lines is %s: %s",
5046 errstr, errstr);
5047 break;
5048 case 'r':
5049 repo_path = realpath(optarg, NULL);
5050 if (repo_path == NULL)
5051 return got_error_from_errno2("realpath",
5052 optarg);
5053 got_path_strip_trailing_slashes(repo_path);
5054 break;
5055 case 'w':
5056 ignore_whitespace = 1;
5057 break;
5058 default:
5059 usage_diff();
5060 /* NOTREACHED */
5064 argc -= optind;
5065 argv += optind;
5067 if (argc == 0) {
5068 usage_diff(); /* TODO show local worktree changes */
5069 } else if (argc == 2) {
5070 id_str1 = argv[0];
5071 id_str2 = argv[1];
5072 } else
5073 usage_diff();
5075 error = got_repo_pack_fds_open(&pack_fds);
5076 if (error)
5077 goto done;
5079 if (repo_path == NULL) {
5080 cwd = getcwd(NULL, 0);
5081 if (cwd == NULL)
5082 return got_error_from_errno("getcwd");
5083 error = got_worktree_open(&worktree, cwd);
5084 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5085 goto done;
5086 if (worktree)
5087 repo_path =
5088 strdup(got_worktree_get_repo_path(worktree));
5089 else
5090 repo_path = strdup(cwd);
5091 if (repo_path == NULL) {
5092 error = got_error_from_errno("strdup");
5093 goto done;
5097 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5098 if (error)
5099 goto done;
5101 init_curses();
5103 error = apply_unveil(got_repo_get_path(repo), NULL);
5104 if (error)
5105 goto done;
5107 error = tog_load_refs(repo, 0);
5108 if (error)
5109 goto done;
5111 error = got_repo_match_object_id(&id1, &label1, id_str1,
5112 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5113 if (error)
5114 goto done;
5116 error = got_repo_match_object_id(&id2, &label2, id_str2,
5117 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5118 if (error)
5119 goto done;
5121 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5122 if (view == NULL) {
5123 error = got_error_from_errno("view_open");
5124 goto done;
5126 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5127 ignore_whitespace, force_text_diff, NULL, repo);
5128 if (error)
5129 goto done;
5130 error = view_loop(view);
5131 done:
5132 free(label1);
5133 free(label2);
5134 free(repo_path);
5135 free(cwd);
5136 if (repo) {
5137 const struct got_error *close_err = got_repo_close(repo);
5138 if (error == NULL)
5139 error = close_err;
5141 if (worktree)
5142 got_worktree_close(worktree);
5143 if (pack_fds) {
5144 const struct got_error *pack_err =
5145 got_repo_pack_fds_close(pack_fds);
5146 if (error == NULL)
5147 error = pack_err;
5149 tog_free_refs();
5150 return error;
5153 __dead static void
5154 usage_blame(void)
5156 endwin();
5157 fprintf(stderr,
5158 "usage: %s blame [-c commit] [-r repository-path] path\n",
5159 getprogname());
5160 exit(1);
5163 struct tog_blame_line {
5164 int annotated;
5165 struct got_object_id *id;
5168 static const struct got_error *
5169 draw_blame(struct tog_view *view)
5171 struct tog_blame_view_state *s = &view->state.blame;
5172 struct tog_blame *blame = &s->blame;
5173 regmatch_t *regmatch = &view->regmatch;
5174 const struct got_error *err;
5175 int lineno = 0, nprinted = 0;
5176 char *line = NULL;
5177 size_t linesize = 0;
5178 ssize_t linelen;
5179 wchar_t *wline;
5180 int width;
5181 struct tog_blame_line *blame_line;
5182 struct got_object_id *prev_id = NULL;
5183 char *id_str;
5184 struct tog_color *tc;
5186 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5187 if (err)
5188 return err;
5190 rewind(blame->f);
5191 werase(view->window);
5193 if (asprintf(&line, "commit %s", id_str) == -1) {
5194 err = got_error_from_errno("asprintf");
5195 free(id_str);
5196 return err;
5199 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5200 free(line);
5201 line = NULL;
5202 if (err)
5203 return err;
5204 if (view_needs_focus_indication(view))
5205 wstandout(view->window);
5206 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5207 if (tc)
5208 wattr_on(view->window,
5209 COLOR_PAIR(tc->colorpair), NULL);
5210 waddwstr(view->window, wline);
5211 if (tc)
5212 wattr_off(view->window,
5213 COLOR_PAIR(tc->colorpair), NULL);
5214 if (view_needs_focus_indication(view))
5215 wstandend(view->window);
5216 free(wline);
5217 wline = NULL;
5218 if (width < view->ncols - 1)
5219 waddch(view->window, '\n');
5221 if (view->gline > blame->nlines)
5222 view->gline = blame->nlines;
5224 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5225 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5226 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5227 free(id_str);
5228 return got_error_from_errno("asprintf");
5230 free(id_str);
5231 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5232 free(line);
5233 line = NULL;
5234 if (err)
5235 return err;
5236 waddwstr(view->window, wline);
5237 free(wline);
5238 wline = NULL;
5239 if (width < view->ncols - 1)
5240 waddch(view->window, '\n');
5242 s->eof = 0;
5243 view->maxx = 0;
5244 while (nprinted < view->nlines - 2) {
5245 linelen = getline(&line, &linesize, blame->f);
5246 if (linelen == -1) {
5247 if (feof(blame->f)) {
5248 s->eof = 1;
5249 break;
5251 free(line);
5252 return got_ferror(blame->f, GOT_ERR_IO);
5254 if (++lineno < s->first_displayed_line)
5255 continue;
5256 if (view->gline && !gotoline(view, &lineno, &nprinted))
5257 continue;
5259 /* Set view->maxx based on full line length. */
5260 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5261 if (err) {
5262 free(line);
5263 return err;
5265 free(wline);
5266 wline = NULL;
5267 view->maxx = MAX(view->maxx, width);
5269 if (nprinted == s->selected_line - 1)
5270 wstandout(view->window);
5272 if (blame->nlines > 0) {
5273 blame_line = &blame->lines[lineno - 1];
5274 if (blame_line->annotated && prev_id &&
5275 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5276 !(nprinted == s->selected_line - 1)) {
5277 waddstr(view->window, " ");
5278 } else if (blame_line->annotated) {
5279 char *id_str;
5280 err = got_object_id_str(&id_str,
5281 blame_line->id);
5282 if (err) {
5283 free(line);
5284 return err;
5286 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5287 if (tc)
5288 wattr_on(view->window,
5289 COLOR_PAIR(tc->colorpair), NULL);
5290 wprintw(view->window, "%.8s", id_str);
5291 if (tc)
5292 wattr_off(view->window,
5293 COLOR_PAIR(tc->colorpair), NULL);
5294 free(id_str);
5295 prev_id = blame_line->id;
5296 } else {
5297 waddstr(view->window, "........");
5298 prev_id = NULL;
5300 } else {
5301 waddstr(view->window, "........");
5302 prev_id = NULL;
5305 if (nprinted == s->selected_line - 1)
5306 wstandend(view->window);
5307 waddstr(view->window, " ");
5309 if (view->ncols <= 9) {
5310 width = 9;
5311 } else if (s->first_displayed_line + nprinted ==
5312 s->matched_line &&
5313 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5314 err = add_matched_line(&width, line, view->ncols - 9, 9,
5315 view->window, view->x, regmatch);
5316 if (err) {
5317 free(line);
5318 return err;
5320 width += 9;
5321 } else {
5322 int skip;
5323 err = format_line(&wline, &width, &skip, line,
5324 view->x, view->ncols - 9, 9, 1);
5325 if (err) {
5326 free(line);
5327 return err;
5329 waddwstr(view->window, &wline[skip]);
5330 width += 9;
5331 free(wline);
5332 wline = NULL;
5335 if (width <= view->ncols - 1)
5336 waddch(view->window, '\n');
5337 if (++nprinted == 1)
5338 s->first_displayed_line = lineno;
5340 free(line);
5341 s->last_displayed_line = lineno;
5343 view_border(view);
5345 return NULL;
5348 static const struct got_error *
5349 blame_cb(void *arg, int nlines, int lineno,
5350 struct got_commit_object *commit, struct got_object_id *id)
5352 const struct got_error *err = NULL;
5353 struct tog_blame_cb_args *a = arg;
5354 struct tog_blame_line *line;
5355 int errcode;
5357 if (nlines != a->nlines ||
5358 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5359 return got_error(GOT_ERR_RANGE);
5361 errcode = pthread_mutex_lock(&tog_mutex);
5362 if (errcode)
5363 return got_error_set_errno(errcode, "pthread_mutex_lock");
5365 if (*a->quit) { /* user has quit the blame view */
5366 err = got_error(GOT_ERR_ITER_COMPLETED);
5367 goto done;
5370 if (lineno == -1)
5371 goto done; /* no change in this commit */
5373 line = &a->lines[lineno - 1];
5374 if (line->annotated)
5375 goto done;
5377 line->id = got_object_id_dup(id);
5378 if (line->id == NULL) {
5379 err = got_error_from_errno("got_object_id_dup");
5380 goto done;
5382 line->annotated = 1;
5383 done:
5384 errcode = pthread_mutex_unlock(&tog_mutex);
5385 if (errcode)
5386 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5387 return err;
5390 static void *
5391 blame_thread(void *arg)
5393 const struct got_error *err, *close_err;
5394 struct tog_blame_thread_args *ta = arg;
5395 struct tog_blame_cb_args *a = ta->cb_args;
5396 int errcode, fd1 = -1, fd2 = -1;
5397 FILE *f1 = NULL, *f2 = NULL;
5399 fd1 = got_opentempfd();
5400 if (fd1 == -1)
5401 return (void *)got_error_from_errno("got_opentempfd");
5403 fd2 = got_opentempfd();
5404 if (fd2 == -1) {
5405 err = got_error_from_errno("got_opentempfd");
5406 goto done;
5409 f1 = got_opentemp();
5410 if (f1 == NULL) {
5411 err = (void *)got_error_from_errno("got_opentemp");
5412 goto done;
5414 f2 = got_opentemp();
5415 if (f2 == NULL) {
5416 err = (void *)got_error_from_errno("got_opentemp");
5417 goto done;
5420 err = block_signals_used_by_main_thread();
5421 if (err)
5422 goto done;
5424 err = got_blame(ta->path, a->commit_id, ta->repo,
5425 tog_diff_algo, blame_cb, ta->cb_args,
5426 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5427 if (err && err->code == GOT_ERR_CANCELLED)
5428 err = NULL;
5430 errcode = pthread_mutex_lock(&tog_mutex);
5431 if (errcode) {
5432 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5433 goto done;
5436 close_err = got_repo_close(ta->repo);
5437 if (err == NULL)
5438 err = close_err;
5439 ta->repo = NULL;
5440 *ta->complete = 1;
5442 errcode = pthread_mutex_unlock(&tog_mutex);
5443 if (errcode && err == NULL)
5444 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5446 done:
5447 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5448 err = got_error_from_errno("close");
5449 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5450 err = got_error_from_errno("close");
5451 if (f1 && fclose(f1) == EOF && err == NULL)
5452 err = got_error_from_errno("fclose");
5453 if (f2 && fclose(f2) == EOF && err == NULL)
5454 err = got_error_from_errno("fclose");
5456 return (void *)err;
5459 static struct got_object_id *
5460 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5461 int first_displayed_line, int selected_line)
5463 struct tog_blame_line *line;
5465 if (nlines <= 0)
5466 return NULL;
5468 line = &lines[first_displayed_line - 1 + selected_line - 1];
5469 if (!line->annotated)
5470 return NULL;
5472 return line->id;
5475 static struct got_object_id *
5476 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5477 int lineno)
5479 struct tog_blame_line *line;
5481 if (nlines <= 0 || lineno >= nlines)
5482 return NULL;
5484 line = &lines[lineno - 1];
5485 if (!line->annotated)
5486 return NULL;
5488 return line->id;
5491 static const struct got_error *
5492 stop_blame(struct tog_blame *blame)
5494 const struct got_error *err = NULL;
5495 int i;
5497 if (blame->thread) {
5498 int errcode;
5499 errcode = pthread_mutex_unlock(&tog_mutex);
5500 if (errcode)
5501 return got_error_set_errno(errcode,
5502 "pthread_mutex_unlock");
5503 errcode = pthread_join(blame->thread, (void **)&err);
5504 if (errcode)
5505 return got_error_set_errno(errcode, "pthread_join");
5506 errcode = pthread_mutex_lock(&tog_mutex);
5507 if (errcode)
5508 return got_error_set_errno(errcode,
5509 "pthread_mutex_lock");
5510 if (err && err->code == GOT_ERR_ITER_COMPLETED)
5511 err = NULL;
5512 blame->thread = NULL;
5514 if (blame->thread_args.repo) {
5515 const struct got_error *close_err;
5516 close_err = got_repo_close(blame->thread_args.repo);
5517 if (err == NULL)
5518 err = close_err;
5519 blame->thread_args.repo = NULL;
5521 if (blame->f) {
5522 if (fclose(blame->f) == EOF && err == NULL)
5523 err = got_error_from_errno("fclose");
5524 blame->f = NULL;
5526 if (blame->lines) {
5527 for (i = 0; i < blame->nlines; i++)
5528 free(blame->lines[i].id);
5529 free(blame->lines);
5530 blame->lines = NULL;
5532 free(blame->cb_args.commit_id);
5533 blame->cb_args.commit_id = NULL;
5534 if (blame->pack_fds) {
5535 const struct got_error *pack_err =
5536 got_repo_pack_fds_close(blame->pack_fds);
5537 if (err == NULL)
5538 err = pack_err;
5539 blame->pack_fds = NULL;
5541 return err;
5544 static const struct got_error *
5545 cancel_blame_view(void *arg)
5547 const struct got_error *err = NULL;
5548 int *done = arg;
5549 int errcode;
5551 errcode = pthread_mutex_lock(&tog_mutex);
5552 if (errcode)
5553 return got_error_set_errno(errcode,
5554 "pthread_mutex_unlock");
5556 if (*done)
5557 err = got_error(GOT_ERR_CANCELLED);
5559 errcode = pthread_mutex_unlock(&tog_mutex);
5560 if (errcode)
5561 return got_error_set_errno(errcode,
5562 "pthread_mutex_lock");
5564 return err;
5567 static const struct got_error *
5568 run_blame(struct tog_view *view)
5570 struct tog_blame_view_state *s = &view->state.blame;
5571 struct tog_blame *blame = &s->blame;
5572 const struct got_error *err = NULL;
5573 struct got_commit_object *commit = NULL;
5574 struct got_blob_object *blob = NULL;
5575 struct got_repository *thread_repo = NULL;
5576 struct got_object_id *obj_id = NULL;
5577 int obj_type, fd = -1;
5578 int *pack_fds = NULL;
5580 err = got_object_open_as_commit(&commit, s->repo,
5581 &s->blamed_commit->id);
5582 if (err)
5583 return err;
5585 fd = got_opentempfd();
5586 if (fd == -1) {
5587 err = got_error_from_errno("got_opentempfd");
5588 goto done;
5591 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
5592 if (err)
5593 goto done;
5595 err = got_object_get_type(&obj_type, s->repo, obj_id);
5596 if (err)
5597 goto done;
5599 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5600 err = got_error(GOT_ERR_OBJ_TYPE);
5601 goto done;
5604 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
5605 if (err)
5606 goto done;
5607 blame->f = got_opentemp();
5608 if (blame->f == NULL) {
5609 err = got_error_from_errno("got_opentemp");
5610 goto done;
5612 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
5613 &blame->line_offsets, blame->f, blob);
5614 if (err)
5615 goto done;
5616 if (blame->nlines == 0) {
5617 s->blame_complete = 1;
5618 goto done;
5621 /* Don't include \n at EOF in the blame line count. */
5622 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
5623 blame->nlines--;
5625 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
5626 if (blame->lines == NULL) {
5627 err = got_error_from_errno("calloc");
5628 goto done;
5631 err = got_repo_pack_fds_open(&pack_fds);
5632 if (err)
5633 goto done;
5634 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
5635 pack_fds);
5636 if (err)
5637 goto done;
5639 blame->pack_fds = pack_fds;
5640 blame->cb_args.view = view;
5641 blame->cb_args.lines = blame->lines;
5642 blame->cb_args.nlines = blame->nlines;
5643 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
5644 if (blame->cb_args.commit_id == NULL) {
5645 err = got_error_from_errno("got_object_id_dup");
5646 goto done;
5648 blame->cb_args.quit = &s->done;
5650 blame->thread_args.path = s->path;
5651 blame->thread_args.repo = thread_repo;
5652 blame->thread_args.cb_args = &blame->cb_args;
5653 blame->thread_args.complete = &s->blame_complete;
5654 blame->thread_args.cancel_cb = cancel_blame_view;
5655 blame->thread_args.cancel_arg = &s->done;
5656 s->blame_complete = 0;
5658 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
5659 s->first_displayed_line = 1;
5660 s->last_displayed_line = view->nlines;
5661 s->selected_line = 1;
5663 s->matched_line = 0;
5665 done:
5666 if (commit)
5667 got_object_commit_close(commit);
5668 if (fd != -1 && close(fd) == -1 && err == NULL)
5669 err = got_error_from_errno("close");
5670 if (blob)
5671 got_object_blob_close(blob);
5672 free(obj_id);
5673 if (err)
5674 stop_blame(blame);
5675 return err;
5678 static const struct got_error *
5679 open_blame_view(struct tog_view *view, char *path,
5680 struct got_object_id *commit_id, struct got_repository *repo)
5682 const struct got_error *err = NULL;
5683 struct tog_blame_view_state *s = &view->state.blame;
5685 STAILQ_INIT(&s->blamed_commits);
5687 s->path = strdup(path);
5688 if (s->path == NULL)
5689 return got_error_from_errno("strdup");
5691 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
5692 if (err) {
5693 free(s->path);
5694 return err;
5697 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
5698 s->first_displayed_line = 1;
5699 s->last_displayed_line = view->nlines;
5700 s->selected_line = 1;
5701 s->blame_complete = 0;
5702 s->repo = repo;
5703 s->commit_id = commit_id;
5704 memset(&s->blame, 0, sizeof(s->blame));
5706 STAILQ_INIT(&s->colors);
5707 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5708 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
5709 get_color_value("TOG_COLOR_COMMIT"));
5710 if (err)
5711 return err;
5714 view->show = show_blame_view;
5715 view->input = input_blame_view;
5716 view->reset = reset_blame_view;
5717 view->close = close_blame_view;
5718 view->search_start = search_start_blame_view;
5719 view->search_next = search_next_blame_view;
5721 return run_blame(view);
5724 static const struct got_error *
5725 close_blame_view(struct tog_view *view)
5727 const struct got_error *err = NULL;
5728 struct tog_blame_view_state *s = &view->state.blame;
5730 if (s->blame.thread)
5731 err = stop_blame(&s->blame);
5733 while (!STAILQ_EMPTY(&s->blamed_commits)) {
5734 struct got_object_qid *blamed_commit;
5735 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
5736 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5737 got_object_qid_free(blamed_commit);
5740 free(s->path);
5741 free_colors(&s->colors);
5742 return err;
5745 static const struct got_error *
5746 search_start_blame_view(struct tog_view *view)
5748 struct tog_blame_view_state *s = &view->state.blame;
5750 s->matched_line = 0;
5751 return NULL;
5754 static const struct got_error *
5755 search_next_blame_view(struct tog_view *view)
5757 struct tog_blame_view_state *s = &view->state.blame;
5758 const struct got_error *err = NULL;
5759 int lineno;
5760 char *line = NULL;
5761 size_t linesize = 0;
5762 ssize_t linelen;
5764 if (!view->searching) {
5765 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5766 return NULL;
5769 if (s->matched_line) {
5770 if (view->searching == TOG_SEARCH_FORWARD)
5771 lineno = s->matched_line + 1;
5772 else
5773 lineno = s->matched_line - 1;
5774 } else
5775 lineno = s->first_displayed_line - 1 + s->selected_line;
5777 while (1) {
5778 off_t offset;
5780 if (lineno <= 0 || lineno > s->blame.nlines) {
5781 if (s->matched_line == 0) {
5782 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5783 break;
5786 if (view->searching == TOG_SEARCH_FORWARD)
5787 lineno = 1;
5788 else
5789 lineno = s->blame.nlines;
5792 offset = s->blame.line_offsets[lineno - 1];
5793 if (fseeko(s->blame.f, offset, SEEK_SET) != 0) {
5794 free(line);
5795 return got_error_from_errno("fseeko");
5797 linelen = getline(&line, &linesize, s->blame.f);
5798 if (linelen != -1) {
5799 char *exstr;
5800 err = expand_tab(&exstr, line);
5801 if (err)
5802 break;
5803 if (match_line(exstr, &view->regex, 1,
5804 &view->regmatch)) {
5805 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5806 s->matched_line = lineno;
5807 free(exstr);
5808 break;
5810 free(exstr);
5812 if (view->searching == TOG_SEARCH_FORWARD)
5813 lineno++;
5814 else
5815 lineno--;
5817 free(line);
5819 if (s->matched_line) {
5820 s->first_displayed_line = s->matched_line;
5821 s->selected_line = 1;
5824 return err;
5827 static const struct got_error *
5828 show_blame_view(struct tog_view *view)
5830 const struct got_error *err = NULL;
5831 struct tog_blame_view_state *s = &view->state.blame;
5832 int errcode;
5834 if (s->blame.thread == NULL && !s->blame_complete) {
5835 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
5836 &s->blame.thread_args);
5837 if (errcode)
5838 return got_error_set_errno(errcode, "pthread_create");
5840 halfdelay(1); /* fast refresh while annotating */
5843 if (s->blame_complete)
5844 halfdelay(10); /* disable fast refresh */
5846 err = draw_blame(view);
5848 view_border(view);
5849 return err;
5852 static const struct got_error *
5853 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
5854 struct got_repository *repo, struct got_object_id *id)
5856 struct tog_view *log_view;
5857 const struct got_error *err = NULL;
5859 *new_view = NULL;
5861 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
5862 if (log_view == NULL)
5863 return got_error_from_errno("view_open");
5865 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
5866 if (err)
5867 view_close(log_view);
5868 else
5869 *new_view = log_view;
5871 return err;
5874 static const struct got_error *
5875 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
5877 const struct got_error *err = NULL, *thread_err = NULL;
5878 struct tog_view *diff_view;
5879 struct tog_blame_view_state *s = &view->state.blame;
5880 int eos, nscroll, begin_y = 0, begin_x = 0;
5882 eos = nscroll = view->nlines - 2;
5883 if (view_is_hsplit_top(view))
5884 --eos; /* border */
5886 switch (ch) {
5887 case '0':
5888 view->x = 0;
5889 break;
5890 case '$':
5891 view->x = MAX(view->maxx - view->ncols / 3, 0);
5892 view->count = 0;
5893 break;
5894 case KEY_RIGHT:
5895 case 'l':
5896 if (view->x + view->ncols / 3 < view->maxx)
5897 view->x += 2; /* move two columns right */
5898 else
5899 view->count = 0;
5900 break;
5901 case KEY_LEFT:
5902 case 'h':
5903 view->x -= MIN(view->x, 2); /* move two columns back */
5904 if (view->x <= 0)
5905 view->count = 0;
5906 break;
5907 case 'q':
5908 s->done = 1;
5909 break;
5910 case 'g':
5911 case KEY_HOME:
5912 s->selected_line = 1;
5913 s->first_displayed_line = 1;
5914 view->count = 0;
5915 break;
5916 case 'G':
5917 case KEY_END:
5918 if (s->blame.nlines < eos) {
5919 s->selected_line = s->blame.nlines;
5920 s->first_displayed_line = 1;
5921 } else {
5922 s->selected_line = eos;
5923 s->first_displayed_line = s->blame.nlines - (eos - 1);
5925 view->count = 0;
5926 break;
5927 case 'k':
5928 case KEY_UP:
5929 case CTRL('p'):
5930 if (s->selected_line > 1)
5931 s->selected_line--;
5932 else if (s->selected_line == 1 &&
5933 s->first_displayed_line > 1)
5934 s->first_displayed_line--;
5935 else
5936 view->count = 0;
5937 break;
5938 case CTRL('u'):
5939 case 'u':
5940 nscroll /= 2;
5941 /* FALL THROUGH */
5942 case KEY_PPAGE:
5943 case CTRL('b'):
5944 case 'b':
5945 if (s->first_displayed_line == 1) {
5946 if (view->count > 1)
5947 nscroll += nscroll;
5948 s->selected_line = MAX(1, s->selected_line - nscroll);
5949 view->count = 0;
5950 break;
5952 if (s->first_displayed_line > nscroll)
5953 s->first_displayed_line -= nscroll;
5954 else
5955 s->first_displayed_line = 1;
5956 break;
5957 case 'j':
5958 case KEY_DOWN:
5959 case CTRL('n'):
5960 if (s->selected_line < eos && s->first_displayed_line +
5961 s->selected_line <= s->blame.nlines)
5962 s->selected_line++;
5963 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
5964 s->first_displayed_line++;
5965 else
5966 view->count = 0;
5967 break;
5968 case 'c':
5969 case 'p': {
5970 struct got_object_id *id = NULL;
5972 view->count = 0;
5973 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5974 s->first_displayed_line, s->selected_line);
5975 if (id == NULL)
5976 break;
5977 if (ch == 'p') {
5978 struct got_commit_object *commit, *pcommit;
5979 struct got_object_qid *pid;
5980 struct got_object_id *blob_id = NULL;
5981 int obj_type;
5982 err = got_object_open_as_commit(&commit,
5983 s->repo, id);
5984 if (err)
5985 break;
5986 pid = STAILQ_FIRST(
5987 got_object_commit_get_parent_ids(commit));
5988 if (pid == NULL) {
5989 got_object_commit_close(commit);
5990 break;
5992 /* Check if path history ends here. */
5993 err = got_object_open_as_commit(&pcommit,
5994 s->repo, &pid->id);
5995 if (err)
5996 break;
5997 err = got_object_id_by_path(&blob_id, s->repo,
5998 pcommit, s->path);
5999 got_object_commit_close(pcommit);
6000 if (err) {
6001 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6002 err = NULL;
6003 got_object_commit_close(commit);
6004 break;
6006 err = got_object_get_type(&obj_type, s->repo,
6007 blob_id);
6008 free(blob_id);
6009 /* Can't blame non-blob type objects. */
6010 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6011 got_object_commit_close(commit);
6012 break;
6014 err = got_object_qid_alloc(&s->blamed_commit,
6015 &pid->id);
6016 got_object_commit_close(commit);
6017 } else {
6018 if (got_object_id_cmp(id,
6019 &s->blamed_commit->id) == 0)
6020 break;
6021 err = got_object_qid_alloc(&s->blamed_commit,
6022 id);
6024 if (err)
6025 break;
6026 s->done = 1;
6027 thread_err = stop_blame(&s->blame);
6028 s->done = 0;
6029 if (thread_err)
6030 break;
6031 STAILQ_INSERT_HEAD(&s->blamed_commits,
6032 s->blamed_commit, entry);
6033 err = run_blame(view);
6034 if (err)
6035 break;
6036 break;
6038 case 'C': {
6039 struct got_object_qid *first;
6041 view->count = 0;
6042 first = STAILQ_FIRST(&s->blamed_commits);
6043 if (!got_object_id_cmp(&first->id, s->commit_id))
6044 break;
6045 s->done = 1;
6046 thread_err = stop_blame(&s->blame);
6047 s->done = 0;
6048 if (thread_err)
6049 break;
6050 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6051 got_object_qid_free(s->blamed_commit);
6052 s->blamed_commit =
6053 STAILQ_FIRST(&s->blamed_commits);
6054 err = run_blame(view);
6055 if (err)
6056 break;
6057 break;
6059 case 'L':
6060 view->count = 0;
6061 s->id_to_log = get_selected_commit_id(s->blame.lines,
6062 s->blame.nlines, s->first_displayed_line, s->selected_line);
6063 if (s->id_to_log)
6064 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6065 break;
6066 case KEY_ENTER:
6067 case '\r': {
6068 struct got_object_id *id = NULL;
6069 struct got_object_qid *pid;
6070 struct got_commit_object *commit = NULL;
6072 view->count = 0;
6073 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6074 s->first_displayed_line, s->selected_line);
6075 if (id == NULL)
6076 break;
6077 err = got_object_open_as_commit(&commit, s->repo, id);
6078 if (err)
6079 break;
6080 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6081 if (*new_view) {
6082 /* traversed from diff view, release diff resources */
6083 err = close_diff_view(*new_view);
6084 if (err)
6085 break;
6086 diff_view = *new_view;
6087 } else {
6088 if (view_is_parent_view(view))
6089 view_get_split(view, &begin_y, &begin_x);
6091 diff_view = view_open(0, 0, begin_y, begin_x,
6092 TOG_VIEW_DIFF);
6093 if (diff_view == NULL) {
6094 got_object_commit_close(commit);
6095 err = got_error_from_errno("view_open");
6096 break;
6099 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6100 id, NULL, NULL, 3, 0, 0, view, s->repo);
6101 got_object_commit_close(commit);
6102 if (err) {
6103 view_close(diff_view);
6104 break;
6106 s->last_diffed_line = s->first_displayed_line - 1 +
6107 s->selected_line;
6108 if (*new_view)
6109 break; /* still open from active diff view */
6110 if (view_is_parent_view(view) &&
6111 view->mode == TOG_VIEW_SPLIT_HRZN) {
6112 err = view_init_hsplit(view, begin_y);
6113 if (err)
6114 break;
6117 view->focussed = 0;
6118 diff_view->focussed = 1;
6119 diff_view->mode = view->mode;
6120 diff_view->nlines = view->lines - begin_y;
6121 if (view_is_parent_view(view)) {
6122 view_transfer_size(diff_view, view);
6123 err = view_close_child(view);
6124 if (err)
6125 break;
6126 err = view_set_child(view, diff_view);
6127 if (err)
6128 break;
6129 view->focus_child = 1;
6130 } else
6131 *new_view = diff_view;
6132 if (err)
6133 break;
6134 break;
6136 case CTRL('d'):
6137 case 'd':
6138 nscroll /= 2;
6139 /* FALL THROUGH */
6140 case KEY_NPAGE:
6141 case CTRL('f'):
6142 case 'f':
6143 case ' ':
6144 if (s->last_displayed_line >= s->blame.nlines &&
6145 s->selected_line >= MIN(s->blame.nlines,
6146 view->nlines - 2)) {
6147 view->count = 0;
6148 break;
6150 if (s->last_displayed_line >= s->blame.nlines &&
6151 s->selected_line < view->nlines - 2) {
6152 s->selected_line +=
6153 MIN(nscroll, s->last_displayed_line -
6154 s->first_displayed_line - s->selected_line + 1);
6156 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6157 s->first_displayed_line += nscroll;
6158 else
6159 s->first_displayed_line =
6160 s->blame.nlines - (view->nlines - 3);
6161 break;
6162 case KEY_RESIZE:
6163 if (s->selected_line > view->nlines - 2) {
6164 s->selected_line = MIN(s->blame.nlines,
6165 view->nlines - 2);
6167 break;
6168 default:
6169 view->count = 0;
6170 break;
6172 return thread_err ? thread_err : err;
6175 static const struct got_error *
6176 reset_blame_view(struct tog_view *view)
6178 const struct got_error *err;
6179 struct tog_blame_view_state *s = &view->state.blame;
6181 view->count = 0;
6182 s->done = 1;
6183 err = stop_blame(&s->blame);
6184 s->done = 0;
6185 if (err)
6186 return err;
6187 return run_blame(view);
6190 static const struct got_error *
6191 cmd_blame(int argc, char *argv[])
6193 const struct got_error *error;
6194 struct got_repository *repo = NULL;
6195 struct got_worktree *worktree = NULL;
6196 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6197 char *link_target = NULL;
6198 struct got_object_id *commit_id = NULL;
6199 struct got_commit_object *commit = NULL;
6200 char *commit_id_str = NULL;
6201 int ch;
6202 struct tog_view *view;
6203 int *pack_fds = NULL;
6205 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6206 switch (ch) {
6207 case 'c':
6208 commit_id_str = optarg;
6209 break;
6210 case 'r':
6211 repo_path = realpath(optarg, NULL);
6212 if (repo_path == NULL)
6213 return got_error_from_errno2("realpath",
6214 optarg);
6215 break;
6216 default:
6217 usage_blame();
6218 /* NOTREACHED */
6222 argc -= optind;
6223 argv += optind;
6225 if (argc != 1)
6226 usage_blame();
6228 error = got_repo_pack_fds_open(&pack_fds);
6229 if (error != NULL)
6230 goto done;
6232 if (repo_path == NULL) {
6233 cwd = getcwd(NULL, 0);
6234 if (cwd == NULL)
6235 return got_error_from_errno("getcwd");
6236 error = got_worktree_open(&worktree, cwd);
6237 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6238 goto done;
6239 if (worktree)
6240 repo_path =
6241 strdup(got_worktree_get_repo_path(worktree));
6242 else
6243 repo_path = strdup(cwd);
6244 if (repo_path == NULL) {
6245 error = got_error_from_errno("strdup");
6246 goto done;
6250 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6251 if (error != NULL)
6252 goto done;
6254 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6255 worktree);
6256 if (error)
6257 goto done;
6259 init_curses();
6261 error = apply_unveil(got_repo_get_path(repo), NULL);
6262 if (error)
6263 goto done;
6265 error = tog_load_refs(repo, 0);
6266 if (error)
6267 goto done;
6269 if (commit_id_str == NULL) {
6270 struct got_reference *head_ref;
6271 error = got_ref_open(&head_ref, repo, worktree ?
6272 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6273 if (error != NULL)
6274 goto done;
6275 error = got_ref_resolve(&commit_id, repo, head_ref);
6276 got_ref_close(head_ref);
6277 } else {
6278 error = got_repo_match_object_id(&commit_id, NULL,
6279 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6281 if (error != NULL)
6282 goto done;
6284 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6285 if (view == NULL) {
6286 error = got_error_from_errno("view_open");
6287 goto done;
6290 error = got_object_open_as_commit(&commit, repo, commit_id);
6291 if (error)
6292 goto done;
6294 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6295 commit, repo);
6296 if (error)
6297 goto done;
6299 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6300 commit_id, repo);
6301 if (error)
6302 goto done;
6303 if (worktree) {
6304 /* Release work tree lock. */
6305 got_worktree_close(worktree);
6306 worktree = NULL;
6308 error = view_loop(view);
6309 done:
6310 free(repo_path);
6311 free(in_repo_path);
6312 free(link_target);
6313 free(cwd);
6314 free(commit_id);
6315 if (commit)
6316 got_object_commit_close(commit);
6317 if (worktree)
6318 got_worktree_close(worktree);
6319 if (repo) {
6320 const struct got_error *close_err = got_repo_close(repo);
6321 if (error == NULL)
6322 error = close_err;
6324 if (pack_fds) {
6325 const struct got_error *pack_err =
6326 got_repo_pack_fds_close(pack_fds);
6327 if (error == NULL)
6328 error = pack_err;
6330 tog_free_refs();
6331 return error;
6334 static const struct got_error *
6335 draw_tree_entries(struct tog_view *view, const char *parent_path)
6337 struct tog_tree_view_state *s = &view->state.tree;
6338 const struct got_error *err = NULL;
6339 struct got_tree_entry *te;
6340 wchar_t *wline;
6341 struct tog_color *tc;
6342 int width, n, nentries, i = 1;
6343 int limit = view->nlines;
6345 s->ndisplayed = 0;
6346 if (view_is_hsplit_top(view))
6347 --limit; /* border */
6349 werase(view->window);
6351 if (limit == 0)
6352 return NULL;
6354 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6355 0, 0);
6356 if (err)
6357 return err;
6358 if (view_needs_focus_indication(view))
6359 wstandout(view->window);
6360 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6361 if (tc)
6362 wattr_on(view->window,
6363 COLOR_PAIR(tc->colorpair), NULL);
6364 waddwstr(view->window, wline);
6365 if (tc)
6366 wattr_off(view->window,
6367 COLOR_PAIR(tc->colorpair), NULL);
6368 if (view_needs_focus_indication(view))
6369 wstandend(view->window);
6370 free(wline);
6371 wline = NULL;
6373 if (s->selected_entry) {
6374 i = got_tree_entry_get_index(s->selected_entry);
6375 i += s->tree == s->root ? 1 : 2; /* account for ".." entry */
6377 nentries = got_object_tree_get_nentries(s->tree);
6378 wprintw(view->window, " [%d/%d]", i,
6379 nentries + (s->tree == s->root ? 0 : 1)); /* ".." in !root tree */
6381 if (width < view->ncols - 1)
6382 waddch(view->window, '\n');
6383 if (--limit <= 0)
6384 return NULL;
6385 err = format_line(&wline, &width, NULL, parent_path, 0, view->ncols,
6386 0, 0);
6387 if (err)
6388 return err;
6389 waddwstr(view->window, wline);
6390 free(wline);
6391 wline = NULL;
6392 if (width < view->ncols - 1)
6393 waddch(view->window, '\n');
6394 if (--limit <= 0)
6395 return NULL;
6396 waddch(view->window, '\n');
6397 if (--limit <= 0)
6398 return NULL;
6400 if (s->first_displayed_entry == NULL) {
6401 te = got_object_tree_get_first_entry(s->tree);
6402 if (s->selected == 0) {
6403 if (view->focussed)
6404 wstandout(view->window);
6405 s->selected_entry = NULL;
6407 waddstr(view->window, " ..\n"); /* parent directory */
6408 if (s->selected == 0 && view->focussed)
6409 wstandend(view->window);
6410 s->ndisplayed++;
6411 if (--limit <= 0)
6412 return NULL;
6413 n = 1;
6414 } else {
6415 n = 0;
6416 te = s->first_displayed_entry;
6419 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6420 char *line = NULL, *id_str = NULL, *link_target = NULL;
6421 const char *modestr = "";
6422 mode_t mode;
6424 te = got_object_tree_get_entry(s->tree, i);
6425 mode = got_tree_entry_get_mode(te);
6427 if (s->show_ids) {
6428 err = got_object_id_str(&id_str,
6429 got_tree_entry_get_id(te));
6430 if (err)
6431 return got_error_from_errno(
6432 "got_object_id_str");
6434 if (got_object_tree_entry_is_submodule(te))
6435 modestr = "$";
6436 else if (S_ISLNK(mode)) {
6437 int i;
6439 err = got_tree_entry_get_symlink_target(&link_target,
6440 te, s->repo);
6441 if (err) {
6442 free(id_str);
6443 return err;
6445 for (i = 0; i < strlen(link_target); i++) {
6446 if (!isprint((unsigned char)link_target[i]))
6447 link_target[i] = '?';
6449 modestr = "@";
6451 else if (S_ISDIR(mode))
6452 modestr = "/";
6453 else if (mode & S_IXUSR)
6454 modestr = "*";
6455 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6456 got_tree_entry_get_name(te), modestr,
6457 link_target ? " -> ": "",
6458 link_target ? link_target : "") == -1) {
6459 free(id_str);
6460 free(link_target);
6461 return got_error_from_errno("asprintf");
6463 free(id_str);
6464 free(link_target);
6465 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
6466 0, 0);
6467 if (err) {
6468 free(line);
6469 break;
6471 if (n == s->selected) {
6472 if (view->focussed)
6473 wstandout(view->window);
6474 s->selected_entry = te;
6476 tc = match_color(&s->colors, line);
6477 if (tc)
6478 wattr_on(view->window,
6479 COLOR_PAIR(tc->colorpair), NULL);
6480 waddwstr(view->window, wline);
6481 if (tc)
6482 wattr_off(view->window,
6483 COLOR_PAIR(tc->colorpair), NULL);
6484 if (width < view->ncols - 1)
6485 waddch(view->window, '\n');
6486 if (n == s->selected && view->focussed)
6487 wstandend(view->window);
6488 free(line);
6489 free(wline);
6490 wline = NULL;
6491 n++;
6492 s->ndisplayed++;
6493 s->last_displayed_entry = te;
6494 if (--limit <= 0)
6495 break;
6498 return err;
6501 static void
6502 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6504 struct got_tree_entry *te;
6505 int isroot = s->tree == s->root;
6506 int i = 0;
6508 if (s->first_displayed_entry == NULL)
6509 return;
6511 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6512 while (i++ < maxscroll) {
6513 if (te == NULL) {
6514 if (!isroot)
6515 s->first_displayed_entry = NULL;
6516 break;
6518 s->first_displayed_entry = te;
6519 te = got_tree_entry_get_prev(s->tree, te);
6523 static const struct got_error *
6524 tree_scroll_down(struct tog_view *view, int maxscroll)
6526 struct tog_tree_view_state *s = &view->state.tree;
6527 struct got_tree_entry *next, *last;
6528 int n = 0;
6530 if (s->first_displayed_entry)
6531 next = got_tree_entry_get_next(s->tree,
6532 s->first_displayed_entry);
6533 else
6534 next = got_object_tree_get_first_entry(s->tree);
6536 last = s->last_displayed_entry;
6537 while (next && n++ < maxscroll) {
6538 if (last) {
6539 s->last_displayed_entry = last;
6540 last = got_tree_entry_get_next(s->tree, last);
6542 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
6543 s->first_displayed_entry = next;
6544 next = got_tree_entry_get_next(s->tree, next);
6548 return NULL;
6551 static const struct got_error *
6552 tree_entry_path(char **path, struct tog_parent_trees *parents,
6553 struct got_tree_entry *te)
6555 const struct got_error *err = NULL;
6556 struct tog_parent_tree *pt;
6557 size_t len = 2; /* for leading slash and NUL */
6559 TAILQ_FOREACH(pt, parents, entry)
6560 len += strlen(got_tree_entry_get_name(pt->selected_entry))
6561 + 1 /* slash */;
6562 if (te)
6563 len += strlen(got_tree_entry_get_name(te));
6565 *path = calloc(1, len);
6566 if (path == NULL)
6567 return got_error_from_errno("calloc");
6569 (*path)[0] = '/';
6570 pt = TAILQ_LAST(parents, tog_parent_trees);
6571 while (pt) {
6572 const char *name = got_tree_entry_get_name(pt->selected_entry);
6573 if (strlcat(*path, name, len) >= len) {
6574 err = got_error(GOT_ERR_NO_SPACE);
6575 goto done;
6577 if (strlcat(*path, "/", len) >= len) {
6578 err = got_error(GOT_ERR_NO_SPACE);
6579 goto done;
6581 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
6583 if (te) {
6584 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
6585 err = got_error(GOT_ERR_NO_SPACE);
6586 goto done;
6589 done:
6590 if (err) {
6591 free(*path);
6592 *path = NULL;
6594 return err;
6597 static const struct got_error *
6598 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6599 struct got_tree_entry *te, struct tog_parent_trees *parents,
6600 struct got_object_id *commit_id, struct got_repository *repo)
6602 const struct got_error *err = NULL;
6603 char *path;
6604 struct tog_view *blame_view;
6606 *new_view = NULL;
6608 err = tree_entry_path(&path, parents, te);
6609 if (err)
6610 return err;
6612 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
6613 if (blame_view == NULL) {
6614 err = got_error_from_errno("view_open");
6615 goto done;
6618 err = open_blame_view(blame_view, path, commit_id, repo);
6619 if (err) {
6620 if (err->code == GOT_ERR_CANCELLED)
6621 err = NULL;
6622 view_close(blame_view);
6623 } else
6624 *new_view = blame_view;
6625 done:
6626 free(path);
6627 return err;
6630 static const struct got_error *
6631 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6632 struct tog_tree_view_state *s)
6634 struct tog_view *log_view;
6635 const struct got_error *err = NULL;
6636 char *path;
6638 *new_view = NULL;
6640 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6641 if (log_view == NULL)
6642 return got_error_from_errno("view_open");
6644 err = tree_entry_path(&path, &s->parents, s->selected_entry);
6645 if (err)
6646 return err;
6648 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
6649 path, 0);
6650 if (err)
6651 view_close(log_view);
6652 else
6653 *new_view = log_view;
6654 free(path);
6655 return err;
6658 static const struct got_error *
6659 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
6660 const char *head_ref_name, struct got_repository *repo)
6662 const struct got_error *err = NULL;
6663 char *commit_id_str = NULL;
6664 struct tog_tree_view_state *s = &view->state.tree;
6665 struct got_commit_object *commit = NULL;
6667 TAILQ_INIT(&s->parents);
6668 STAILQ_INIT(&s->colors);
6670 s->commit_id = got_object_id_dup(commit_id);
6671 if (s->commit_id == NULL)
6672 return got_error_from_errno("got_object_id_dup");
6674 err = got_object_open_as_commit(&commit, repo, commit_id);
6675 if (err)
6676 goto done;
6679 * The root is opened here and will be closed when the view is closed.
6680 * Any visited subtrees and their path-wise parents are opened and
6681 * closed on demand.
6683 err = got_object_open_as_tree(&s->root, repo,
6684 got_object_commit_get_tree_id(commit));
6685 if (err)
6686 goto done;
6687 s->tree = s->root;
6689 err = got_object_id_str(&commit_id_str, commit_id);
6690 if (err != NULL)
6691 goto done;
6693 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
6694 err = got_error_from_errno("asprintf");
6695 goto done;
6698 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
6699 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
6700 if (head_ref_name) {
6701 s->head_ref_name = strdup(head_ref_name);
6702 if (s->head_ref_name == NULL) {
6703 err = got_error_from_errno("strdup");
6704 goto done;
6707 s->repo = repo;
6709 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6710 err = add_color(&s->colors, "\\$$",
6711 TOG_COLOR_TREE_SUBMODULE,
6712 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
6713 if (err)
6714 goto done;
6715 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
6716 get_color_value("TOG_COLOR_TREE_SYMLINK"));
6717 if (err)
6718 goto done;
6719 err = add_color(&s->colors, "/$",
6720 TOG_COLOR_TREE_DIRECTORY,
6721 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
6722 if (err)
6723 goto done;
6725 err = add_color(&s->colors, "\\*$",
6726 TOG_COLOR_TREE_EXECUTABLE,
6727 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
6728 if (err)
6729 goto done;
6731 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
6732 get_color_value("TOG_COLOR_COMMIT"));
6733 if (err)
6734 goto done;
6737 view->show = show_tree_view;
6738 view->input = input_tree_view;
6739 view->close = close_tree_view;
6740 view->search_start = search_start_tree_view;
6741 view->search_next = search_next_tree_view;
6742 done:
6743 free(commit_id_str);
6744 if (commit)
6745 got_object_commit_close(commit);
6746 if (err)
6747 close_tree_view(view);
6748 return err;
6751 static const struct got_error *
6752 close_tree_view(struct tog_view *view)
6754 struct tog_tree_view_state *s = &view->state.tree;
6756 free_colors(&s->colors);
6757 free(s->tree_label);
6758 s->tree_label = NULL;
6759 free(s->commit_id);
6760 s->commit_id = NULL;
6761 free(s->head_ref_name);
6762 s->head_ref_name = NULL;
6763 while (!TAILQ_EMPTY(&s->parents)) {
6764 struct tog_parent_tree *parent;
6765 parent = TAILQ_FIRST(&s->parents);
6766 TAILQ_REMOVE(&s->parents, parent, entry);
6767 if (parent->tree != s->root)
6768 got_object_tree_close(parent->tree);
6769 free(parent);
6772 if (s->tree != NULL && s->tree != s->root)
6773 got_object_tree_close(s->tree);
6774 if (s->root)
6775 got_object_tree_close(s->root);
6776 return NULL;
6779 static const struct got_error *
6780 search_start_tree_view(struct tog_view *view)
6782 struct tog_tree_view_state *s = &view->state.tree;
6784 s->matched_entry = NULL;
6785 return NULL;
6788 static int
6789 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
6791 regmatch_t regmatch;
6793 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
6794 0) == 0;
6797 static const struct got_error *
6798 search_next_tree_view(struct tog_view *view)
6800 struct tog_tree_view_state *s = &view->state.tree;
6801 struct got_tree_entry *te = NULL;
6803 if (!view->searching) {
6804 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6805 return NULL;
6808 if (s->matched_entry) {
6809 if (view->searching == TOG_SEARCH_FORWARD) {
6810 if (s->selected_entry)
6811 te = got_tree_entry_get_next(s->tree,
6812 s->selected_entry);
6813 else
6814 te = got_object_tree_get_first_entry(s->tree);
6815 } else {
6816 if (s->selected_entry == NULL)
6817 te = got_object_tree_get_last_entry(s->tree);
6818 else
6819 te = got_tree_entry_get_prev(s->tree,
6820 s->selected_entry);
6822 } else {
6823 if (s->selected_entry)
6824 te = s->selected_entry;
6825 else if (view->searching == TOG_SEARCH_FORWARD)
6826 te = got_object_tree_get_first_entry(s->tree);
6827 else
6828 te = got_object_tree_get_last_entry(s->tree);
6831 while (1) {
6832 if (te == NULL) {
6833 if (s->matched_entry == NULL) {
6834 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6835 return NULL;
6837 if (view->searching == TOG_SEARCH_FORWARD)
6838 te = got_object_tree_get_first_entry(s->tree);
6839 else
6840 te = got_object_tree_get_last_entry(s->tree);
6843 if (match_tree_entry(te, &view->regex)) {
6844 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6845 s->matched_entry = te;
6846 break;
6849 if (view->searching == TOG_SEARCH_FORWARD)
6850 te = got_tree_entry_get_next(s->tree, te);
6851 else
6852 te = got_tree_entry_get_prev(s->tree, te);
6855 if (s->matched_entry) {
6856 s->first_displayed_entry = s->matched_entry;
6857 s->selected = 0;
6860 return NULL;
6863 static const struct got_error *
6864 show_tree_view(struct tog_view *view)
6866 const struct got_error *err = NULL;
6867 struct tog_tree_view_state *s = &view->state.tree;
6868 char *parent_path;
6870 err = tree_entry_path(&parent_path, &s->parents, NULL);
6871 if (err)
6872 return err;
6874 err = draw_tree_entries(view, parent_path);
6875 free(parent_path);
6877 view_border(view);
6878 return err;
6881 static const struct got_error *
6882 tree_goto_line(struct tog_view *view, int nlines)
6884 const struct got_error *err = NULL;
6885 struct tog_tree_view_state *s = &view->state.tree;
6886 struct got_tree_entry **fte, **lte, **ste;
6887 int g, last, first = 1, i = 1;
6888 int root = s->tree == s->root;
6889 int off = root ? 1 : 2;
6891 g = view->gline;
6892 view->gline = 0;
6894 if (g == 0)
6895 g = 1;
6896 else if (g > got_object_tree_get_nentries(s->tree))
6897 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
6899 fte = &s->first_displayed_entry;
6900 lte = &s->last_displayed_entry;
6901 ste = &s->selected_entry;
6903 if (*fte != NULL) {
6904 first = got_tree_entry_get_index(*fte);
6905 first += off; /* account for ".." */
6907 last = got_tree_entry_get_index(*lte);
6908 last += off;
6910 if (g >= first && g <= last && g - first < nlines) {
6911 s->selected = g - first;
6912 return NULL; /* gline is on the current page */
6915 if (*ste != NULL) {
6916 i = got_tree_entry_get_index(*ste);
6917 i += off;
6920 if (i < g) {
6921 err = tree_scroll_down(view, g - i);
6922 if (err)
6923 return err;
6924 if (got_tree_entry_get_index(*lte) >=
6925 got_object_tree_get_nentries(s->tree) - 1 &&
6926 first + s->selected < g &&
6927 s->selected < s->ndisplayed - 1) {
6928 first = got_tree_entry_get_index(*fte);
6929 first += off;
6930 s->selected = g - first;
6932 } else if (i > g)
6933 tree_scroll_up(s, i - g);
6935 if (g < nlines &&
6936 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
6937 s->selected = g - 1;
6939 return NULL;
6942 static const struct got_error *
6943 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
6945 const struct got_error *err = NULL;
6946 struct tog_tree_view_state *s = &view->state.tree;
6947 struct got_tree_entry *te;
6948 int n, nscroll = view->nlines - 3;
6950 if (view->gline)
6951 return tree_goto_line(view, nscroll);
6953 switch (ch) {
6954 case 'i':
6955 s->show_ids = !s->show_ids;
6956 view->count = 0;
6957 break;
6958 case 'L':
6959 view->count = 0;
6960 if (!s->selected_entry)
6961 break;
6962 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6963 break;
6964 case 'R':
6965 view->count = 0;
6966 err = view_request_new(new_view, view, TOG_VIEW_REF);
6967 break;
6968 case 'g':
6969 case KEY_HOME:
6970 s->selected = 0;
6971 view->count = 0;
6972 if (s->tree == s->root)
6973 s->first_displayed_entry =
6974 got_object_tree_get_first_entry(s->tree);
6975 else
6976 s->first_displayed_entry = NULL;
6977 break;
6978 case 'G':
6979 case KEY_END: {
6980 int eos = view->nlines - 3;
6982 if (view->mode == TOG_VIEW_SPLIT_HRZN)
6983 --eos; /* border */
6984 s->selected = 0;
6985 view->count = 0;
6986 te = got_object_tree_get_last_entry(s->tree);
6987 for (n = 0; n < eos; n++) {
6988 if (te == NULL) {
6989 if (s->tree != s->root) {
6990 s->first_displayed_entry = NULL;
6991 n++;
6993 break;
6995 s->first_displayed_entry = te;
6996 te = got_tree_entry_get_prev(s->tree, te);
6998 if (n > 0)
6999 s->selected = n - 1;
7000 break;
7002 case 'k':
7003 case KEY_UP:
7004 case CTRL('p'):
7005 if (s->selected > 0) {
7006 s->selected--;
7007 break;
7009 tree_scroll_up(s, 1);
7010 if (s->selected_entry == NULL ||
7011 (s->tree == s->root && s->selected_entry ==
7012 got_object_tree_get_first_entry(s->tree)))
7013 view->count = 0;
7014 break;
7015 case CTRL('u'):
7016 case 'u':
7017 nscroll /= 2;
7018 /* FALL THROUGH */
7019 case KEY_PPAGE:
7020 case CTRL('b'):
7021 case 'b':
7022 if (s->tree == s->root) {
7023 if (got_object_tree_get_first_entry(s->tree) ==
7024 s->first_displayed_entry)
7025 s->selected -= MIN(s->selected, nscroll);
7026 } else {
7027 if (s->first_displayed_entry == NULL)
7028 s->selected -= MIN(s->selected, nscroll);
7030 tree_scroll_up(s, MAX(0, nscroll));
7031 if (s->selected_entry == NULL ||
7032 (s->tree == s->root && s->selected_entry ==
7033 got_object_tree_get_first_entry(s->tree)))
7034 view->count = 0;
7035 break;
7036 case 'j':
7037 case KEY_DOWN:
7038 case CTRL('n'):
7039 if (s->selected < s->ndisplayed - 1) {
7040 s->selected++;
7041 break;
7043 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7044 == NULL) {
7045 /* can't scroll any further */
7046 view->count = 0;
7047 break;
7049 tree_scroll_down(view, 1);
7050 break;
7051 case CTRL('d'):
7052 case 'd':
7053 nscroll /= 2;
7054 /* FALL THROUGH */
7055 case KEY_NPAGE:
7056 case CTRL('f'):
7057 case 'f':
7058 case ' ':
7059 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7060 == NULL) {
7061 /* can't scroll any further; move cursor down */
7062 if (s->selected < s->ndisplayed - 1)
7063 s->selected += MIN(nscroll,
7064 s->ndisplayed - s->selected - 1);
7065 else
7066 view->count = 0;
7067 break;
7069 tree_scroll_down(view, nscroll);
7070 break;
7071 case KEY_ENTER:
7072 case '\r':
7073 case KEY_BACKSPACE:
7074 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7075 struct tog_parent_tree *parent;
7076 /* user selected '..' */
7077 if (s->tree == s->root) {
7078 view->count = 0;
7079 break;
7081 parent = TAILQ_FIRST(&s->parents);
7082 TAILQ_REMOVE(&s->parents, parent,
7083 entry);
7084 got_object_tree_close(s->tree);
7085 s->tree = parent->tree;
7086 s->first_displayed_entry =
7087 parent->first_displayed_entry;
7088 s->selected_entry =
7089 parent->selected_entry;
7090 s->selected = parent->selected;
7091 if (s->selected > view->nlines - 3) {
7092 err = offset_selection_down(view);
7093 if (err)
7094 break;
7096 free(parent);
7097 } else if (S_ISDIR(got_tree_entry_get_mode(
7098 s->selected_entry))) {
7099 struct got_tree_object *subtree;
7100 view->count = 0;
7101 err = got_object_open_as_tree(&subtree, s->repo,
7102 got_tree_entry_get_id(s->selected_entry));
7103 if (err)
7104 break;
7105 err = tree_view_visit_subtree(s, subtree);
7106 if (err) {
7107 got_object_tree_close(subtree);
7108 break;
7110 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7111 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7112 break;
7113 case KEY_RESIZE:
7114 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7115 s->selected = view->nlines - 4;
7116 view->count = 0;
7117 break;
7118 default:
7119 view->count = 0;
7120 break;
7123 return err;
7126 __dead static void
7127 usage_tree(void)
7129 endwin();
7130 fprintf(stderr,
7131 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7132 getprogname());
7133 exit(1);
7136 static const struct got_error *
7137 cmd_tree(int argc, char *argv[])
7139 const struct got_error *error;
7140 struct got_repository *repo = NULL;
7141 struct got_worktree *worktree = NULL;
7142 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7143 struct got_object_id *commit_id = NULL;
7144 struct got_commit_object *commit = NULL;
7145 const char *commit_id_arg = NULL;
7146 char *label = NULL;
7147 struct got_reference *ref = NULL;
7148 const char *head_ref_name = NULL;
7149 int ch;
7150 struct tog_view *view;
7151 int *pack_fds = NULL;
7153 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7154 switch (ch) {
7155 case 'c':
7156 commit_id_arg = optarg;
7157 break;
7158 case 'r':
7159 repo_path = realpath(optarg, NULL);
7160 if (repo_path == NULL)
7161 return got_error_from_errno2("realpath",
7162 optarg);
7163 break;
7164 default:
7165 usage_tree();
7166 /* NOTREACHED */
7170 argc -= optind;
7171 argv += optind;
7173 if (argc > 1)
7174 usage_tree();
7176 error = got_repo_pack_fds_open(&pack_fds);
7177 if (error != NULL)
7178 goto done;
7180 if (repo_path == NULL) {
7181 cwd = getcwd(NULL, 0);
7182 if (cwd == NULL)
7183 return got_error_from_errno("getcwd");
7184 error = got_worktree_open(&worktree, cwd);
7185 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7186 goto done;
7187 if (worktree)
7188 repo_path =
7189 strdup(got_worktree_get_repo_path(worktree));
7190 else
7191 repo_path = strdup(cwd);
7192 if (repo_path == NULL) {
7193 error = got_error_from_errno("strdup");
7194 goto done;
7198 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7199 if (error != NULL)
7200 goto done;
7202 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7203 repo, worktree);
7204 if (error)
7205 goto done;
7207 init_curses();
7209 error = apply_unveil(got_repo_get_path(repo), NULL);
7210 if (error)
7211 goto done;
7213 error = tog_load_refs(repo, 0);
7214 if (error)
7215 goto done;
7217 if (commit_id_arg == NULL) {
7218 error = got_repo_match_object_id(&commit_id, &label,
7219 worktree ? got_worktree_get_head_ref_name(worktree) :
7220 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7221 if (error)
7222 goto done;
7223 head_ref_name = label;
7224 } else {
7225 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7226 if (error == NULL)
7227 head_ref_name = got_ref_get_name(ref);
7228 else if (error->code != GOT_ERR_NOT_REF)
7229 goto done;
7230 error = got_repo_match_object_id(&commit_id, NULL,
7231 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7232 if (error)
7233 goto done;
7236 error = got_object_open_as_commit(&commit, repo, commit_id);
7237 if (error)
7238 goto done;
7240 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7241 if (view == NULL) {
7242 error = got_error_from_errno("view_open");
7243 goto done;
7245 error = open_tree_view(view, commit_id, head_ref_name, repo);
7246 if (error)
7247 goto done;
7248 if (!got_path_is_root_dir(in_repo_path)) {
7249 error = tree_view_walk_path(&view->state.tree, commit,
7250 in_repo_path);
7251 if (error)
7252 goto done;
7255 if (worktree) {
7256 /* Release work tree lock. */
7257 got_worktree_close(worktree);
7258 worktree = NULL;
7260 error = view_loop(view);
7261 done:
7262 free(repo_path);
7263 free(cwd);
7264 free(commit_id);
7265 free(label);
7266 if (ref)
7267 got_ref_close(ref);
7268 if (repo) {
7269 const struct got_error *close_err = got_repo_close(repo);
7270 if (error == NULL)
7271 error = close_err;
7273 if (pack_fds) {
7274 const struct got_error *pack_err =
7275 got_repo_pack_fds_close(pack_fds);
7276 if (error == NULL)
7277 error = pack_err;
7279 tog_free_refs();
7280 return error;
7283 static const struct got_error *
7284 ref_view_load_refs(struct tog_ref_view_state *s)
7286 struct got_reflist_entry *sre;
7287 struct tog_reflist_entry *re;
7289 s->nrefs = 0;
7290 TAILQ_FOREACH(sre, &tog_refs, entry) {
7291 if (strncmp(got_ref_get_name(sre->ref),
7292 "refs/got/", 9) == 0 &&
7293 strncmp(got_ref_get_name(sre->ref),
7294 "refs/got/backup/", 16) != 0)
7295 continue;
7297 re = malloc(sizeof(*re));
7298 if (re == NULL)
7299 return got_error_from_errno("malloc");
7301 re->ref = got_ref_dup(sre->ref);
7302 if (re->ref == NULL)
7303 return got_error_from_errno("got_ref_dup");
7304 re->idx = s->nrefs++;
7305 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7308 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7309 return NULL;
7312 static void
7313 ref_view_free_refs(struct tog_ref_view_state *s)
7315 struct tog_reflist_entry *re;
7317 while (!TAILQ_EMPTY(&s->refs)) {
7318 re = TAILQ_FIRST(&s->refs);
7319 TAILQ_REMOVE(&s->refs, re, entry);
7320 got_ref_close(re->ref);
7321 free(re);
7325 static const struct got_error *
7326 open_ref_view(struct tog_view *view, struct got_repository *repo)
7328 const struct got_error *err = NULL;
7329 struct tog_ref_view_state *s = &view->state.ref;
7331 s->selected_entry = 0;
7332 s->repo = repo;
7334 TAILQ_INIT(&s->refs);
7335 STAILQ_INIT(&s->colors);
7337 err = ref_view_load_refs(s);
7338 if (err)
7339 return err;
7341 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7342 err = add_color(&s->colors, "^refs/heads/",
7343 TOG_COLOR_REFS_HEADS,
7344 get_color_value("TOG_COLOR_REFS_HEADS"));
7345 if (err)
7346 goto done;
7348 err = add_color(&s->colors, "^refs/tags/",
7349 TOG_COLOR_REFS_TAGS,
7350 get_color_value("TOG_COLOR_REFS_TAGS"));
7351 if (err)
7352 goto done;
7354 err = add_color(&s->colors, "^refs/remotes/",
7355 TOG_COLOR_REFS_REMOTES,
7356 get_color_value("TOG_COLOR_REFS_REMOTES"));
7357 if (err)
7358 goto done;
7360 err = add_color(&s->colors, "^refs/got/backup/",
7361 TOG_COLOR_REFS_BACKUP,
7362 get_color_value("TOG_COLOR_REFS_BACKUP"));
7363 if (err)
7364 goto done;
7367 view->show = show_ref_view;
7368 view->input = input_ref_view;
7369 view->close = close_ref_view;
7370 view->search_start = search_start_ref_view;
7371 view->search_next = search_next_ref_view;
7372 done:
7373 if (err)
7374 free_colors(&s->colors);
7375 return err;
7378 static const struct got_error *
7379 close_ref_view(struct tog_view *view)
7381 struct tog_ref_view_state *s = &view->state.ref;
7383 ref_view_free_refs(s);
7384 free_colors(&s->colors);
7386 return NULL;
7389 static const struct got_error *
7390 resolve_reflist_entry(struct got_object_id **commit_id,
7391 struct tog_reflist_entry *re, struct got_repository *repo)
7393 const struct got_error *err = NULL;
7394 struct got_object_id *obj_id;
7395 struct got_tag_object *tag = NULL;
7396 int obj_type;
7398 *commit_id = NULL;
7400 err = got_ref_resolve(&obj_id, repo, re->ref);
7401 if (err)
7402 return err;
7404 err = got_object_get_type(&obj_type, repo, obj_id);
7405 if (err)
7406 goto done;
7408 switch (obj_type) {
7409 case GOT_OBJ_TYPE_COMMIT:
7410 *commit_id = obj_id;
7411 break;
7412 case GOT_OBJ_TYPE_TAG:
7413 err = got_object_open_as_tag(&tag, repo, obj_id);
7414 if (err)
7415 goto done;
7416 free(obj_id);
7417 err = got_object_get_type(&obj_type, repo,
7418 got_object_tag_get_object_id(tag));
7419 if (err)
7420 goto done;
7421 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7422 err = got_error(GOT_ERR_OBJ_TYPE);
7423 goto done;
7425 *commit_id = got_object_id_dup(
7426 got_object_tag_get_object_id(tag));
7427 if (*commit_id == NULL) {
7428 err = got_error_from_errno("got_object_id_dup");
7429 goto done;
7431 break;
7432 default:
7433 err = got_error(GOT_ERR_OBJ_TYPE);
7434 break;
7437 done:
7438 if (tag)
7439 got_object_tag_close(tag);
7440 if (err) {
7441 free(*commit_id);
7442 *commit_id = NULL;
7444 return err;
7447 static const struct got_error *
7448 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7449 struct tog_reflist_entry *re, struct got_repository *repo)
7451 struct tog_view *log_view;
7452 const struct got_error *err = NULL;
7453 struct got_object_id *commit_id = NULL;
7455 *new_view = NULL;
7457 err = resolve_reflist_entry(&commit_id, re, repo);
7458 if (err) {
7459 if (err->code != GOT_ERR_OBJ_TYPE)
7460 return err;
7461 else
7462 return NULL;
7465 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7466 if (log_view == NULL) {
7467 err = got_error_from_errno("view_open");
7468 goto done;
7471 err = open_log_view(log_view, commit_id, repo,
7472 got_ref_get_name(re->ref), "", 0);
7473 done:
7474 if (err)
7475 view_close(log_view);
7476 else
7477 *new_view = log_view;
7478 free(commit_id);
7479 return err;
7482 static void
7483 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7485 struct tog_reflist_entry *re;
7486 int i = 0;
7488 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7489 return;
7491 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7492 while (i++ < maxscroll) {
7493 if (re == NULL)
7494 break;
7495 s->first_displayed_entry = re;
7496 re = TAILQ_PREV(re, tog_reflist_head, entry);
7500 static const struct got_error *
7501 ref_scroll_down(struct tog_view *view, int maxscroll)
7503 struct tog_ref_view_state *s = &view->state.ref;
7504 struct tog_reflist_entry *next, *last;
7505 int n = 0;
7507 if (s->first_displayed_entry)
7508 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7509 else
7510 next = TAILQ_FIRST(&s->refs);
7512 last = s->last_displayed_entry;
7513 while (next && n++ < maxscroll) {
7514 if (last) {
7515 s->last_displayed_entry = last;
7516 last = TAILQ_NEXT(last, entry);
7518 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7519 s->first_displayed_entry = next;
7520 next = TAILQ_NEXT(next, entry);
7524 return NULL;
7527 static const struct got_error *
7528 search_start_ref_view(struct tog_view *view)
7530 struct tog_ref_view_state *s = &view->state.ref;
7532 s->matched_entry = NULL;
7533 return NULL;
7536 static int
7537 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
7539 regmatch_t regmatch;
7541 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
7542 0) == 0;
7545 static const struct got_error *
7546 search_next_ref_view(struct tog_view *view)
7548 struct tog_ref_view_state *s = &view->state.ref;
7549 struct tog_reflist_entry *re = NULL;
7551 if (!view->searching) {
7552 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7553 return NULL;
7556 if (s->matched_entry) {
7557 if (view->searching == TOG_SEARCH_FORWARD) {
7558 if (s->selected_entry)
7559 re = TAILQ_NEXT(s->selected_entry, entry);
7560 else
7561 re = TAILQ_PREV(s->selected_entry,
7562 tog_reflist_head, entry);
7563 } else {
7564 if (s->selected_entry == NULL)
7565 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7566 else
7567 re = TAILQ_PREV(s->selected_entry,
7568 tog_reflist_head, entry);
7570 } else {
7571 if (s->selected_entry)
7572 re = s->selected_entry;
7573 else if (view->searching == TOG_SEARCH_FORWARD)
7574 re = TAILQ_FIRST(&s->refs);
7575 else
7576 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7579 while (1) {
7580 if (re == NULL) {
7581 if (s->matched_entry == NULL) {
7582 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7583 return NULL;
7585 if (view->searching == TOG_SEARCH_FORWARD)
7586 re = TAILQ_FIRST(&s->refs);
7587 else
7588 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7591 if (match_reflist_entry(re, &view->regex)) {
7592 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7593 s->matched_entry = re;
7594 break;
7597 if (view->searching == TOG_SEARCH_FORWARD)
7598 re = TAILQ_NEXT(re, entry);
7599 else
7600 re = TAILQ_PREV(re, tog_reflist_head, entry);
7603 if (s->matched_entry) {
7604 s->first_displayed_entry = s->matched_entry;
7605 s->selected = 0;
7608 return NULL;
7611 static const struct got_error *
7612 show_ref_view(struct tog_view *view)
7614 const struct got_error *err = NULL;
7615 struct tog_ref_view_state *s = &view->state.ref;
7616 struct tog_reflist_entry *re;
7617 char *line = NULL;
7618 wchar_t *wline;
7619 struct tog_color *tc;
7620 int width, n;
7621 int limit = view->nlines;
7623 werase(view->window);
7625 s->ndisplayed = 0;
7626 if (view_is_hsplit_top(view))
7627 --limit; /* border */
7629 if (limit == 0)
7630 return NULL;
7632 re = s->first_displayed_entry;
7634 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
7635 s->nrefs) == -1)
7636 return got_error_from_errno("asprintf");
7638 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
7639 if (err) {
7640 free(line);
7641 return err;
7643 if (view_needs_focus_indication(view))
7644 wstandout(view->window);
7645 waddwstr(view->window, wline);
7646 if (view_needs_focus_indication(view))
7647 wstandend(view->window);
7648 free(wline);
7649 wline = NULL;
7650 free(line);
7651 line = NULL;
7652 if (width < view->ncols - 1)
7653 waddch(view->window, '\n');
7654 if (--limit <= 0)
7655 return NULL;
7657 n = 0;
7658 while (re && limit > 0) {
7659 char *line = NULL;
7660 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
7662 if (s->show_date) {
7663 struct got_commit_object *ci;
7664 struct got_tag_object *tag;
7665 struct got_object_id *id;
7666 struct tm tm;
7667 time_t t;
7669 err = got_ref_resolve(&id, s->repo, re->ref);
7670 if (err)
7671 return err;
7672 err = got_object_open_as_tag(&tag, s->repo, id);
7673 if (err) {
7674 if (err->code != GOT_ERR_OBJ_TYPE) {
7675 free(id);
7676 return err;
7678 err = got_object_open_as_commit(&ci, s->repo,
7679 id);
7680 if (err) {
7681 free(id);
7682 return err;
7684 t = got_object_commit_get_committer_time(ci);
7685 got_object_commit_close(ci);
7686 } else {
7687 t = got_object_tag_get_tagger_time(tag);
7688 got_object_tag_close(tag);
7690 free(id);
7691 if (gmtime_r(&t, &tm) == NULL)
7692 return got_error_from_errno("gmtime_r");
7693 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
7694 return got_error(GOT_ERR_NO_SPACE);
7696 if (got_ref_is_symbolic(re->ref)) {
7697 if (asprintf(&line, "%s%s -> %s", s->show_date ?
7698 ymd : "", got_ref_get_name(re->ref),
7699 got_ref_get_symref_target(re->ref)) == -1)
7700 return got_error_from_errno("asprintf");
7701 } else if (s->show_ids) {
7702 struct got_object_id *id;
7703 char *id_str;
7704 err = got_ref_resolve(&id, s->repo, re->ref);
7705 if (err)
7706 return err;
7707 err = got_object_id_str(&id_str, id);
7708 if (err) {
7709 free(id);
7710 return err;
7712 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
7713 got_ref_get_name(re->ref), id_str) == -1) {
7714 err = got_error_from_errno("asprintf");
7715 free(id);
7716 free(id_str);
7717 return err;
7719 free(id);
7720 free(id_str);
7721 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
7722 got_ref_get_name(re->ref)) == -1)
7723 return got_error_from_errno("asprintf");
7725 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
7726 0, 0);
7727 if (err) {
7728 free(line);
7729 return err;
7731 if (n == s->selected) {
7732 if (view->focussed)
7733 wstandout(view->window);
7734 s->selected_entry = re;
7736 tc = match_color(&s->colors, got_ref_get_name(re->ref));
7737 if (tc)
7738 wattr_on(view->window,
7739 COLOR_PAIR(tc->colorpair), NULL);
7740 waddwstr(view->window, wline);
7741 if (tc)
7742 wattr_off(view->window,
7743 COLOR_PAIR(tc->colorpair), NULL);
7744 if (width < view->ncols - 1)
7745 waddch(view->window, '\n');
7746 if (n == s->selected && view->focussed)
7747 wstandend(view->window);
7748 free(line);
7749 free(wline);
7750 wline = NULL;
7751 n++;
7752 s->ndisplayed++;
7753 s->last_displayed_entry = re;
7755 limit--;
7756 re = TAILQ_NEXT(re, entry);
7759 view_border(view);
7760 return err;
7763 static const struct got_error *
7764 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
7765 struct tog_reflist_entry *re, struct got_repository *repo)
7767 const struct got_error *err = NULL;
7768 struct got_object_id *commit_id = NULL;
7769 struct tog_view *tree_view;
7771 *new_view = NULL;
7773 err = resolve_reflist_entry(&commit_id, re, repo);
7774 if (err) {
7775 if (err->code != GOT_ERR_OBJ_TYPE)
7776 return err;
7777 else
7778 return NULL;
7782 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
7783 if (tree_view == NULL) {
7784 err = got_error_from_errno("view_open");
7785 goto done;
7788 err = open_tree_view(tree_view, commit_id,
7789 got_ref_get_name(re->ref), repo);
7790 if (err)
7791 goto done;
7793 *new_view = tree_view;
7794 done:
7795 free(commit_id);
7796 return err;
7799 static const struct got_error *
7800 ref_goto_line(struct tog_view *view, int nlines)
7802 const struct got_error *err = NULL;
7803 struct tog_ref_view_state *s = &view->state.ref;
7804 int g, idx = s->selected_entry->idx;
7806 g = view->gline;
7807 view->gline = 0;
7809 if (g == 0)
7810 g = 1;
7811 else if (g > s->nrefs)
7812 g = s->nrefs;
7814 if (g >= s->first_displayed_entry->idx + 1 &&
7815 g <= s->last_displayed_entry->idx + 1 &&
7816 g - s->first_displayed_entry->idx - 1 < nlines) {
7817 s->selected = g - s->first_displayed_entry->idx - 1;
7818 return NULL;
7821 if (idx + 1 < g) {
7822 err = ref_scroll_down(view, g - idx - 1);
7823 if (err)
7824 return err;
7825 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
7826 s->first_displayed_entry->idx + s->selected < g &&
7827 s->selected < s->ndisplayed - 1)
7828 s->selected = g - s->first_displayed_entry->idx - 1;
7829 } else if (idx + 1 > g)
7830 ref_scroll_up(s, idx - g + 1);
7832 if (g < nlines && s->first_displayed_entry->idx == 0)
7833 s->selected = g - 1;
7835 return NULL;
7839 static const struct got_error *
7840 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
7842 const struct got_error *err = NULL;
7843 struct tog_ref_view_state *s = &view->state.ref;
7844 struct tog_reflist_entry *re;
7845 int n, nscroll = view->nlines - 1;
7847 if (view->gline)
7848 return ref_goto_line(view, nscroll);
7850 switch (ch) {
7851 case 'i':
7852 s->show_ids = !s->show_ids;
7853 view->count = 0;
7854 break;
7855 case 'm':
7856 s->show_date = !s->show_date;
7857 view->count = 0;
7858 break;
7859 case 'o':
7860 s->sort_by_date = !s->sort_by_date;
7861 view->count = 0;
7862 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
7863 got_ref_cmp_by_commit_timestamp_descending :
7864 tog_ref_cmp_by_name, s->repo);
7865 if (err)
7866 break;
7867 got_reflist_object_id_map_free(tog_refs_idmap);
7868 err = got_reflist_object_id_map_create(&tog_refs_idmap,
7869 &tog_refs, s->repo);
7870 if (err)
7871 break;
7872 ref_view_free_refs(s);
7873 err = ref_view_load_refs(s);
7874 break;
7875 case KEY_ENTER:
7876 case '\r':
7877 view->count = 0;
7878 if (!s->selected_entry)
7879 break;
7880 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7881 break;
7882 case 'T':
7883 view->count = 0;
7884 if (!s->selected_entry)
7885 break;
7886 err = view_request_new(new_view, view, TOG_VIEW_TREE);
7887 break;
7888 case 'g':
7889 case KEY_HOME:
7890 s->selected = 0;
7891 view->count = 0;
7892 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7893 break;
7894 case 'G':
7895 case KEY_END: {
7896 int eos = view->nlines - 1;
7898 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7899 --eos; /* border */
7900 s->selected = 0;
7901 view->count = 0;
7902 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7903 for (n = 0; n < eos; n++) {
7904 if (re == NULL)
7905 break;
7906 s->first_displayed_entry = re;
7907 re = TAILQ_PREV(re, tog_reflist_head, entry);
7909 if (n > 0)
7910 s->selected = n - 1;
7911 break;
7913 case 'k':
7914 case KEY_UP:
7915 case CTRL('p'):
7916 if (s->selected > 0) {
7917 s->selected--;
7918 break;
7920 ref_scroll_up(s, 1);
7921 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7922 view->count = 0;
7923 break;
7924 case CTRL('u'):
7925 case 'u':
7926 nscroll /= 2;
7927 /* FALL THROUGH */
7928 case KEY_PPAGE:
7929 case CTRL('b'):
7930 case 'b':
7931 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7932 s->selected -= MIN(nscroll, s->selected);
7933 ref_scroll_up(s, MAX(0, nscroll));
7934 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7935 view->count = 0;
7936 break;
7937 case 'j':
7938 case KEY_DOWN:
7939 case CTRL('n'):
7940 if (s->selected < s->ndisplayed - 1) {
7941 s->selected++;
7942 break;
7944 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7945 /* can't scroll any further */
7946 view->count = 0;
7947 break;
7949 ref_scroll_down(view, 1);
7950 break;
7951 case CTRL('d'):
7952 case 'd':
7953 nscroll /= 2;
7954 /* FALL THROUGH */
7955 case KEY_NPAGE:
7956 case CTRL('f'):
7957 case 'f':
7958 case ' ':
7959 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7960 /* can't scroll any further; move cursor down */
7961 if (s->selected < s->ndisplayed - 1)
7962 s->selected += MIN(nscroll,
7963 s->ndisplayed - s->selected - 1);
7964 if (view->count > 1 && s->selected < s->ndisplayed - 1)
7965 s->selected += s->ndisplayed - s->selected - 1;
7966 view->count = 0;
7967 break;
7969 ref_scroll_down(view, nscroll);
7970 break;
7971 case CTRL('l'):
7972 view->count = 0;
7973 tog_free_refs();
7974 err = tog_load_refs(s->repo, s->sort_by_date);
7975 if (err)
7976 break;
7977 ref_view_free_refs(s);
7978 err = ref_view_load_refs(s);
7979 break;
7980 case KEY_RESIZE:
7981 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
7982 s->selected = view->nlines - 2;
7983 break;
7984 default:
7985 view->count = 0;
7986 break;
7989 return err;
7992 __dead static void
7993 usage_ref(void)
7995 endwin();
7996 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
7997 getprogname());
7998 exit(1);
8001 static const struct got_error *
8002 cmd_ref(int argc, char *argv[])
8004 const struct got_error *error;
8005 struct got_repository *repo = NULL;
8006 struct got_worktree *worktree = NULL;
8007 char *cwd = NULL, *repo_path = NULL;
8008 int ch;
8009 struct tog_view *view;
8010 int *pack_fds = NULL;
8012 while ((ch = getopt(argc, argv, "r:")) != -1) {
8013 switch (ch) {
8014 case 'r':
8015 repo_path = realpath(optarg, NULL);
8016 if (repo_path == NULL)
8017 return got_error_from_errno2("realpath",
8018 optarg);
8019 break;
8020 default:
8021 usage_ref();
8022 /* NOTREACHED */
8026 argc -= optind;
8027 argv += optind;
8029 if (argc > 1)
8030 usage_ref();
8032 error = got_repo_pack_fds_open(&pack_fds);
8033 if (error != NULL)
8034 goto done;
8036 if (repo_path == NULL) {
8037 cwd = getcwd(NULL, 0);
8038 if (cwd == NULL)
8039 return got_error_from_errno("getcwd");
8040 error = got_worktree_open(&worktree, cwd);
8041 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8042 goto done;
8043 if (worktree)
8044 repo_path =
8045 strdup(got_worktree_get_repo_path(worktree));
8046 else
8047 repo_path = strdup(cwd);
8048 if (repo_path == NULL) {
8049 error = got_error_from_errno("strdup");
8050 goto done;
8054 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8055 if (error != NULL)
8056 goto done;
8058 init_curses();
8060 error = apply_unveil(got_repo_get_path(repo), NULL);
8061 if (error)
8062 goto done;
8064 error = tog_load_refs(repo, 0);
8065 if (error)
8066 goto done;
8068 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8069 if (view == NULL) {
8070 error = got_error_from_errno("view_open");
8071 goto done;
8074 error = open_ref_view(view, repo);
8075 if (error)
8076 goto done;
8078 if (worktree) {
8079 /* Release work tree lock. */
8080 got_worktree_close(worktree);
8081 worktree = NULL;
8083 error = view_loop(view);
8084 done:
8085 free(repo_path);
8086 free(cwd);
8087 if (repo) {
8088 const struct got_error *close_err = got_repo_close(repo);
8089 if (close_err)
8090 error = close_err;
8092 if (pack_fds) {
8093 const struct got_error *pack_err =
8094 got_repo_pack_fds_close(pack_fds);
8095 if (error == NULL)
8096 error = pack_err;
8098 tog_free_refs();
8099 return error;
8102 static const struct got_error *
8103 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
8104 enum tog_view_type request, int y, int x)
8106 const struct got_error *err = NULL;
8108 *new_view = NULL;
8110 switch (request) {
8111 case TOG_VIEW_DIFF:
8112 if (view->type == TOG_VIEW_LOG) {
8113 struct tog_log_view_state *s = &view->state.log;
8115 err = open_diff_view_for_commit(new_view, y, x,
8116 s->selected_entry->commit, s->selected_entry->id,
8117 view, s->repo);
8118 } else
8119 return got_error_msg(GOT_ERR_NOT_IMPL,
8120 "parent/child view pair not supported");
8121 break;
8122 case TOG_VIEW_BLAME:
8123 if (view->type == TOG_VIEW_TREE) {
8124 struct tog_tree_view_state *s = &view->state.tree;
8126 err = blame_tree_entry(new_view, y, x,
8127 s->selected_entry, &s->parents, s->commit_id,
8128 s->repo);
8129 } else
8130 return got_error_msg(GOT_ERR_NOT_IMPL,
8131 "parent/child view pair not supported");
8132 break;
8133 case TOG_VIEW_LOG:
8134 if (view->type == TOG_VIEW_BLAME)
8135 err = log_annotated_line(new_view, y, x,
8136 view->state.blame.repo, view->state.blame.id_to_log);
8137 else if (view->type == TOG_VIEW_TREE)
8138 err = log_selected_tree_entry(new_view, y, x,
8139 &view->state.tree);
8140 else if (view->type == TOG_VIEW_REF)
8141 err = log_ref_entry(new_view, y, x,
8142 view->state.ref.selected_entry,
8143 view->state.ref.repo);
8144 else
8145 return got_error_msg(GOT_ERR_NOT_IMPL,
8146 "parent/child view pair not supported");
8147 break;
8148 case TOG_VIEW_TREE:
8149 if (view->type == TOG_VIEW_LOG)
8150 err = browse_commit_tree(new_view, y, x,
8151 view->state.log.selected_entry,
8152 view->state.log.in_repo_path,
8153 view->state.log.head_ref_name,
8154 view->state.log.repo);
8155 else if (view->type == TOG_VIEW_REF)
8156 err = browse_ref_tree(new_view, y, x,
8157 view->state.ref.selected_entry,
8158 view->state.ref.repo);
8159 else
8160 return got_error_msg(GOT_ERR_NOT_IMPL,
8161 "parent/child view pair not supported");
8162 break;
8163 case TOG_VIEW_REF:
8164 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
8165 if (*new_view == NULL)
8166 return got_error_from_errno("view_open");
8167 if (view->type == TOG_VIEW_LOG)
8168 err = open_ref_view(*new_view, view->state.log.repo);
8169 else if (view->type == TOG_VIEW_TREE)
8170 err = open_ref_view(*new_view, view->state.tree.repo);
8171 else
8172 err = got_error_msg(GOT_ERR_NOT_IMPL,
8173 "parent/child view pair not supported");
8174 if (err)
8175 view_close(*new_view);
8176 break;
8177 default:
8178 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
8181 return err;
8185 * If view was scrolled down to move the selected line into view when opening a
8186 * horizontal split, scroll back up when closing the split/toggling fullscreen.
8188 static void
8189 offset_selection_up(struct tog_view *view)
8191 switch (view->type) {
8192 case TOG_VIEW_BLAME: {
8193 struct tog_blame_view_state *s = &view->state.blame;
8194 if (s->first_displayed_line == 1) {
8195 s->selected_line = MAX(s->selected_line - view->offset,
8196 1);
8197 break;
8199 if (s->first_displayed_line > view->offset)
8200 s->first_displayed_line -= view->offset;
8201 else
8202 s->first_displayed_line = 1;
8203 s->selected_line += view->offset;
8204 break;
8206 case TOG_VIEW_LOG:
8207 log_scroll_up(&view->state.log, view->offset);
8208 view->state.log.selected += view->offset;
8209 break;
8210 case TOG_VIEW_REF:
8211 ref_scroll_up(&view->state.ref, view->offset);
8212 view->state.ref.selected += view->offset;
8213 break;
8214 case TOG_VIEW_TREE:
8215 tree_scroll_up(&view->state.tree, view->offset);
8216 view->state.tree.selected += view->offset;
8217 break;
8218 default:
8219 break;
8222 view->offset = 0;
8226 * If the selected line is in the section of screen covered by the bottom split,
8227 * scroll down offset lines to move it into view and index its new position.
8229 static const struct got_error *
8230 offset_selection_down(struct tog_view *view)
8232 const struct got_error *err = NULL;
8233 const struct got_error *(*scrolld)(struct tog_view *, int);
8234 int *selected = NULL;
8235 int header, offset;
8237 switch (view->type) {
8238 case TOG_VIEW_BLAME: {
8239 struct tog_blame_view_state *s = &view->state.blame;
8240 header = 3;
8241 scrolld = NULL;
8242 if (s->selected_line > view->nlines - header) {
8243 offset = abs(view->nlines - s->selected_line - header);
8244 s->first_displayed_line += offset;
8245 s->selected_line -= offset;
8246 view->offset = offset;
8248 break;
8250 case TOG_VIEW_LOG: {
8251 struct tog_log_view_state *s = &view->state.log;
8252 scrolld = &log_scroll_down;
8253 header = view_is_parent_view(view) ? 3 : 2;
8254 selected = &s->selected;
8255 break;
8257 case TOG_VIEW_REF: {
8258 struct tog_ref_view_state *s = &view->state.ref;
8259 scrolld = &ref_scroll_down;
8260 header = 3;
8261 selected = &s->selected;
8262 break;
8264 case TOG_VIEW_TREE: {
8265 struct tog_tree_view_state *s = &view->state.tree;
8266 scrolld = &tree_scroll_down;
8267 header = 5;
8268 selected = &s->selected;
8269 break;
8271 default:
8272 selected = NULL;
8273 scrolld = NULL;
8274 header = 0;
8275 break;
8278 if (selected && *selected > view->nlines - header) {
8279 offset = abs(view->nlines - *selected - header);
8280 view->offset = offset;
8281 if (scrolld && offset) {
8282 err = scrolld(view, offset);
8283 *selected -= offset;
8287 return err;
8290 static void
8291 list_commands(FILE *fp)
8293 size_t i;
8295 fprintf(fp, "commands:");
8296 for (i = 0; i < nitems(tog_commands); i++) {
8297 const struct tog_cmd *cmd = &tog_commands[i];
8298 fprintf(fp, " %s", cmd->name);
8300 fputc('\n', fp);
8303 __dead static void
8304 usage(int hflag, int status)
8306 FILE *fp = (status == 0) ? stdout : stderr;
8308 fprintf(fp, "usage: %s [-h] [-V | --version] [command] [arg ...]\n",
8309 getprogname());
8310 if (hflag) {
8311 fprintf(fp, "lazy usage: %s path\n", getprogname());
8312 list_commands(fp);
8314 exit(status);
8317 static char **
8318 make_argv(int argc, ...)
8320 va_list ap;
8321 char **argv;
8322 int i;
8324 va_start(ap, argc);
8326 argv = calloc(argc, sizeof(char *));
8327 if (argv == NULL)
8328 err(1, "calloc");
8329 for (i = 0; i < argc; i++) {
8330 argv[i] = strdup(va_arg(ap, char *));
8331 if (argv[i] == NULL)
8332 err(1, "strdup");
8335 va_end(ap);
8336 return argv;
8340 * Try to convert 'tog path' into a 'tog log path' command.
8341 * The user could simply have mistyped the command rather than knowingly
8342 * provided a path. So check whether argv[0] can in fact be resolved
8343 * to a path in the HEAD commit and print a special error if not.
8344 * This hack is for mpi@ <3
8346 static const struct got_error *
8347 tog_log_with_path(int argc, char *argv[])
8349 const struct got_error *error = NULL, *close_err;
8350 const struct tog_cmd *cmd = NULL;
8351 struct got_repository *repo = NULL;
8352 struct got_worktree *worktree = NULL;
8353 struct got_object_id *commit_id = NULL, *id = NULL;
8354 struct got_commit_object *commit = NULL;
8355 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8356 char *commit_id_str = NULL, **cmd_argv = NULL;
8357 int *pack_fds = NULL;
8359 cwd = getcwd(NULL, 0);
8360 if (cwd == NULL)
8361 return got_error_from_errno("getcwd");
8363 error = got_repo_pack_fds_open(&pack_fds);
8364 if (error != NULL)
8365 goto done;
8367 error = got_worktree_open(&worktree, cwd);
8368 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8369 goto done;
8371 if (worktree)
8372 repo_path = strdup(got_worktree_get_repo_path(worktree));
8373 else
8374 repo_path = strdup(cwd);
8375 if (repo_path == NULL) {
8376 error = got_error_from_errno("strdup");
8377 goto done;
8380 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8381 if (error != NULL)
8382 goto done;
8384 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8385 repo, worktree);
8386 if (error)
8387 goto done;
8389 error = tog_load_refs(repo, 0);
8390 if (error)
8391 goto done;
8392 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
8393 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
8394 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8395 if (error)
8396 goto done;
8398 if (worktree) {
8399 got_worktree_close(worktree);
8400 worktree = NULL;
8403 error = got_object_open_as_commit(&commit, repo, commit_id);
8404 if (error)
8405 goto done;
8407 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
8408 if (error) {
8409 if (error->code != GOT_ERR_NO_TREE_ENTRY)
8410 goto done;
8411 fprintf(stderr, "%s: '%s' is no known command or path\n",
8412 getprogname(), argv[0]);
8413 usage(1, 1);
8414 /* not reached */
8417 error = got_object_id_str(&commit_id_str, commit_id);
8418 if (error)
8419 goto done;
8421 cmd = &tog_commands[0]; /* log */
8422 argc = 4;
8423 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
8424 error = cmd->cmd_main(argc, cmd_argv);
8425 done:
8426 if (repo) {
8427 close_err = got_repo_close(repo);
8428 if (error == NULL)
8429 error = close_err;
8431 if (commit)
8432 got_object_commit_close(commit);
8433 if (worktree)
8434 got_worktree_close(worktree);
8435 if (pack_fds) {
8436 const struct got_error *pack_err =
8437 got_repo_pack_fds_close(pack_fds);
8438 if (error == NULL)
8439 error = pack_err;
8441 free(id);
8442 free(commit_id_str);
8443 free(commit_id);
8444 free(cwd);
8445 free(repo_path);
8446 free(in_repo_path);
8447 if (cmd_argv) {
8448 int i;
8449 for (i = 0; i < argc; i++)
8450 free(cmd_argv[i]);
8451 free(cmd_argv);
8453 tog_free_refs();
8454 return error;
8457 int
8458 main(int argc, char *argv[])
8460 const struct got_error *error = NULL;
8461 const struct tog_cmd *cmd = NULL;
8462 int ch, hflag = 0, Vflag = 0;
8463 char **cmd_argv = NULL;
8464 static const struct option longopts[] = {
8465 { "version", no_argument, NULL, 'V' },
8466 { NULL, 0, NULL, 0}
8468 char *diff_algo_str = NULL;
8470 setlocale(LC_CTYPE, "");
8472 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
8473 switch (ch) {
8474 case 'h':
8475 hflag = 1;
8476 break;
8477 case 'V':
8478 Vflag = 1;
8479 break;
8480 default:
8481 usage(hflag, 1);
8482 /* NOTREACHED */
8486 argc -= optind;
8487 argv += optind;
8488 optind = 1;
8489 optreset = 1;
8491 if (Vflag) {
8492 got_version_print_str();
8493 return 0;
8496 #ifndef PROFILE
8497 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
8498 NULL) == -1)
8499 err(1, "pledge");
8500 #endif
8502 if (argc == 0) {
8503 if (hflag)
8504 usage(hflag, 0);
8505 /* Build an argument vector which runs a default command. */
8506 cmd = &tog_commands[0];
8507 argc = 1;
8508 cmd_argv = make_argv(argc, cmd->name);
8509 } else {
8510 size_t i;
8512 /* Did the user specify a command? */
8513 for (i = 0; i < nitems(tog_commands); i++) {
8514 if (strncmp(tog_commands[i].name, argv[0],
8515 strlen(argv[0])) == 0) {
8516 cmd = &tog_commands[i];
8517 break;
8522 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
8523 if (diff_algo_str) {
8524 if (strcasecmp(diff_algo_str, "patience") == 0)
8525 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
8526 if (strcasecmp(diff_algo_str, "myers") == 0)
8527 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
8530 if (cmd == NULL) {
8531 if (argc != 1)
8532 usage(0, 1);
8533 /* No command specified; try log with a path */
8534 error = tog_log_with_path(argc, argv);
8535 } else {
8536 if (hflag)
8537 cmd->cmd_usage();
8538 else
8539 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
8542 endwin();
8543 putchar('\n');
8544 if (cmd_argv) {
8545 int i;
8546 for (i = 0; i < argc; i++)
8547 free(cmd_argv[i]);
8548 free(cmd_argv);
8551 if (error && error->code != GOT_ERR_CANCELLED)
8552 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8553 return 0;