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 #if defined(__FreeBSD__) || defined(__APPLE__)
24 #define _XOPEN_SOURCE_EXTENDED /* for ncurses wide-character functions */
25 #endif
26 #include <curses.h>
27 #include <panel.h>
28 #include <locale.h>
29 #include <signal.h>
30 #include <stdlib.h>
31 #include <stdarg.h>
32 #include <stdio.h>
33 #include <getopt.h>
34 #include <string.h>
35 #include <err.h>
36 #include <unistd.h>
37 #include <limits.h>
38 #include <wchar.h>
39 #include <time.h>
40 #include <pthread.h>
41 #include <libgen.h>
42 #include <regex.h>
43 #include <sched.h>
45 #include "got_compat.h"
47 #include "got_version.h"
48 #include "got_error.h"
49 #include "got_object.h"
50 #include "got_reference.h"
51 #include "got_repository.h"
52 #include "got_diff.h"
53 #include "got_opentemp.h"
54 #include "got_utf8.h"
55 #include "got_cancel.h"
56 #include "got_commit_graph.h"
57 #include "got_blame.h"
58 #include "got_privsep.h"
59 #include "got_path.h"
60 #include "got_worktree.h"
62 #ifndef MIN
63 #define MIN(_a,_b) ((_a) < (_b) ? (_a) : (_b))
64 #endif
66 #ifndef MAX
67 #define MAX(_a,_b) ((_a) > (_b) ? (_a) : (_b))
68 #endif
70 #ifndef CTRL
71 #define CTRL(x) ((x) & 0x1f)
72 #endif
74 #ifndef nitems
75 #define nitems(_a) (sizeof((_a)) / sizeof((_a)[0]))
76 #endif
78 struct tog_cmd {
79 const char *name;
80 const struct got_error *(*cmd_main)(int, char *[]);
81 void (*cmd_usage)(void);
82 };
84 __dead static void usage(int, int);
85 __dead static void usage_log(void);
86 __dead static void usage_diff(void);
87 __dead static void usage_blame(void);
88 __dead static void usage_tree(void);
89 __dead static void usage_ref(void);
91 static const struct got_error* cmd_log(int, char *[]);
92 static const struct got_error* cmd_diff(int, char *[]);
93 static const struct got_error* cmd_blame(int, char *[]);
94 static const struct got_error* cmd_tree(int, char *[]);
95 static const struct got_error* cmd_ref(int, char *[]);
97 static const struct tog_cmd tog_commands[] = {
98 { "log", cmd_log, usage_log },
99 { "diff", cmd_diff, usage_diff },
100 { "blame", cmd_blame, usage_blame },
101 { "tree", cmd_tree, usage_tree },
102 { "ref", cmd_ref, usage_ref },
103 };
105 enum tog_view_type {
106 TOG_VIEW_DIFF,
107 TOG_VIEW_LOG,
108 TOG_VIEW_BLAME,
109 TOG_VIEW_TREE,
110 TOG_VIEW_REF,
111 };
113 enum tog_view_mode {
114 TOG_VIEW_SPLIT_NONE,
115 TOG_VIEW_SPLIT_VERT,
116 TOG_VIEW_SPLIT_HRZN
117 };
119 #define HSPLIT_SCALE 0.3 /* default horizontal split scale */
121 #define TOG_EOF_STRING "(END)"
123 struct commit_queue_entry {
124 TAILQ_ENTRY(commit_queue_entry) entry;
125 struct got_object_id *id;
126 struct got_commit_object *commit;
127 int idx;
128 };
129 TAILQ_HEAD(commit_queue_head, commit_queue_entry);
130 struct commit_queue {
131 int ncommits;
132 struct commit_queue_head head;
133 };
135 struct tog_color {
136 STAILQ_ENTRY(tog_color) entry;
137 regex_t regex;
138 short colorpair;
139 };
140 STAILQ_HEAD(tog_colors, tog_color);
142 static struct got_reflist_head tog_refs = TAILQ_HEAD_INITIALIZER(tog_refs);
143 static struct got_reflist_object_id_map *tog_refs_idmap;
144 static enum got_diff_algorithm tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
146 static const struct got_error *
147 tog_ref_cmp_by_name(void *arg, int *cmp, struct got_reference *re1,
148 struct got_reference* re2)
150 const char *name1 = got_ref_get_name(re1);
151 const char *name2 = got_ref_get_name(re2);
152 int isbackup1, isbackup2;
154 /* Sort backup refs towards the bottom of the list. */
155 isbackup1 = strncmp(name1, "refs/got/backup/", 16) == 0;
156 isbackup2 = strncmp(name2, "refs/got/backup/", 16) == 0;
157 if (!isbackup1 && isbackup2) {
158 *cmp = -1;
159 return NULL;
160 } else if (isbackup1 && !isbackup2) {
161 *cmp = 1;
162 return NULL;
165 *cmp = got_path_cmp(name1, name2, strlen(name1), strlen(name2));
166 return NULL;
169 static const struct got_error *
170 tog_load_refs(struct got_repository *repo, int sort_by_date)
172 const struct got_error *err;
174 err = got_ref_list(&tog_refs, repo, NULL, sort_by_date ?
175 got_ref_cmp_by_commit_timestamp_descending : tog_ref_cmp_by_name,
176 repo);
177 if (err)
178 return err;
180 return got_reflist_object_id_map_create(&tog_refs_idmap, &tog_refs,
181 repo);
184 static void
185 tog_free_refs(void)
187 if (tog_refs_idmap) {
188 got_reflist_object_id_map_free(tog_refs_idmap);
189 tog_refs_idmap = NULL;
191 got_ref_list_free(&tog_refs);
194 static const struct got_error *
195 add_color(struct tog_colors *colors, const char *pattern,
196 int idx, short color)
198 const struct got_error *err = NULL;
199 struct tog_color *tc;
200 int regerr = 0;
202 if (idx < 1 || idx > COLOR_PAIRS - 1)
203 return NULL;
205 init_pair(idx, color, -1);
207 tc = calloc(1, sizeof(*tc));
208 if (tc == NULL)
209 return got_error_from_errno("calloc");
210 regerr = regcomp(&tc->regex, pattern,
211 REG_EXTENDED | REG_NOSUB | REG_NEWLINE);
212 if (regerr) {
213 static char regerr_msg[512];
214 static char err_msg[512];
215 regerror(regerr, &tc->regex, regerr_msg,
216 sizeof(regerr_msg));
217 snprintf(err_msg, sizeof(err_msg), "regcomp: %s",
218 regerr_msg);
219 err = got_error_msg(GOT_ERR_REGEX, err_msg);
220 free(tc);
221 return err;
223 tc->colorpair = idx;
224 STAILQ_INSERT_HEAD(colors, tc, entry);
225 return NULL;
228 static void
229 free_colors(struct tog_colors *colors)
231 struct tog_color *tc;
233 while (!STAILQ_EMPTY(colors)) {
234 tc = STAILQ_FIRST(colors);
235 STAILQ_REMOVE_HEAD(colors, entry);
236 regfree(&tc->regex);
237 free(tc);
241 static struct tog_color *
242 get_color(struct tog_colors *colors, int colorpair)
244 struct tog_color *tc = NULL;
246 STAILQ_FOREACH(tc, colors, entry) {
247 if (tc->colorpair == colorpair)
248 return tc;
251 return NULL;
254 static int
255 default_color_value(const char *envvar)
257 if (strcmp(envvar, "TOG_COLOR_DIFF_MINUS") == 0)
258 return COLOR_MAGENTA;
259 if (strcmp(envvar, "TOG_COLOR_DIFF_PLUS") == 0)
260 return COLOR_CYAN;
261 if (strcmp(envvar, "TOG_COLOR_DIFF_CHUNK_HEADER") == 0)
262 return COLOR_YELLOW;
263 if (strcmp(envvar, "TOG_COLOR_DIFF_META") == 0)
264 return COLOR_GREEN;
265 if (strcmp(envvar, "TOG_COLOR_TREE_SUBMODULE") == 0)
266 return COLOR_MAGENTA;
267 if (strcmp(envvar, "TOG_COLOR_TREE_SYMLINK") == 0)
268 return COLOR_MAGENTA;
269 if (strcmp(envvar, "TOG_COLOR_TREE_DIRECTORY") == 0)
270 return COLOR_CYAN;
271 if (strcmp(envvar, "TOG_COLOR_TREE_EXECUTABLE") == 0)
272 return COLOR_GREEN;
273 if (strcmp(envvar, "TOG_COLOR_COMMIT") == 0)
274 return COLOR_GREEN;
275 if (strcmp(envvar, "TOG_COLOR_AUTHOR") == 0)
276 return COLOR_CYAN;
277 if (strcmp(envvar, "TOG_COLOR_DATE") == 0)
278 return COLOR_YELLOW;
279 if (strcmp(envvar, "TOG_COLOR_REFS_HEADS") == 0)
280 return COLOR_GREEN;
281 if (strcmp(envvar, "TOG_COLOR_REFS_TAGS") == 0)
282 return COLOR_MAGENTA;
283 if (strcmp(envvar, "TOG_COLOR_REFS_REMOTES") == 0)
284 return COLOR_YELLOW;
285 if (strcmp(envvar, "TOG_COLOR_REFS_BACKUP") == 0)
286 return COLOR_CYAN;
288 return -1;
291 static int
292 get_color_value(const char *envvar)
294 const char *val = getenv(envvar);
296 if (val == NULL)
297 return default_color_value(envvar);
299 if (strcasecmp(val, "black") == 0)
300 return COLOR_BLACK;
301 if (strcasecmp(val, "red") == 0)
302 return COLOR_RED;
303 if (strcasecmp(val, "green") == 0)
304 return COLOR_GREEN;
305 if (strcasecmp(val, "yellow") == 0)
306 return COLOR_YELLOW;
307 if (strcasecmp(val, "blue") == 0)
308 return COLOR_BLUE;
309 if (strcasecmp(val, "magenta") == 0)
310 return COLOR_MAGENTA;
311 if (strcasecmp(val, "cyan") == 0)
312 return COLOR_CYAN;
313 if (strcasecmp(val, "white") == 0)
314 return COLOR_WHITE;
315 if (strcasecmp(val, "default") == 0)
316 return -1;
318 return default_color_value(envvar);
321 struct tog_diff_view_state {
322 struct got_object_id *id1, *id2;
323 const char *label1, *label2;
324 FILE *f, *f1, *f2;
325 int fd1, fd2;
326 int lineno;
327 int first_displayed_line;
328 int last_displayed_line;
329 int eof;
330 int diff_context;
331 int ignore_whitespace;
332 int force_text_diff;
333 struct got_repository *repo;
334 struct got_diff_line *lines;
335 size_t nlines;
336 int matched_line;
337 int selected_line;
339 /* passed from log or blame view; may be NULL */
340 struct tog_view *parent_view;
341 };
343 pthread_mutex_t tog_mutex = PTHREAD_MUTEX_INITIALIZER;
344 static volatile sig_atomic_t tog_thread_error;
346 struct tog_log_thread_args {
347 pthread_cond_t need_commits;
348 pthread_cond_t commit_loaded;
349 int commits_needed;
350 int load_all;
351 struct got_commit_graph *graph;
352 struct commit_queue *commits;
353 const char *in_repo_path;
354 struct got_object_id *start_id;
355 struct got_repository *repo;
356 int *pack_fds;
357 int log_complete;
358 sig_atomic_t *quit;
359 struct commit_queue_entry **first_displayed_entry;
360 struct commit_queue_entry **selected_entry;
361 int *searching;
362 int *search_next_done;
363 regex_t *regex;
364 };
366 struct tog_log_view_state {
367 struct commit_queue commits;
368 struct commit_queue_entry *first_displayed_entry;
369 struct commit_queue_entry *last_displayed_entry;
370 struct commit_queue_entry *selected_entry;
371 int selected;
372 char *in_repo_path;
373 char *head_ref_name;
374 int log_branches;
375 struct got_repository *repo;
376 struct got_object_id *start_id;
377 sig_atomic_t quit;
378 pthread_t thread;
379 struct tog_log_thread_args thread_args;
380 struct commit_queue_entry *matched_entry;
381 struct commit_queue_entry *search_entry;
382 struct tog_colors colors;
383 int use_committer;
384 };
386 #define TOG_COLOR_DIFF_MINUS 1
387 #define TOG_COLOR_DIFF_PLUS 2
388 #define TOG_COLOR_DIFF_CHUNK_HEADER 3
389 #define TOG_COLOR_DIFF_META 4
390 #define TOG_COLOR_TREE_SUBMODULE 5
391 #define TOG_COLOR_TREE_SYMLINK 6
392 #define TOG_COLOR_TREE_DIRECTORY 7
393 #define TOG_COLOR_TREE_EXECUTABLE 8
394 #define TOG_COLOR_COMMIT 9
395 #define TOG_COLOR_AUTHOR 10
396 #define TOG_COLOR_DATE 11
397 #define TOG_COLOR_REFS_HEADS 12
398 #define TOG_COLOR_REFS_TAGS 13
399 #define TOG_COLOR_REFS_REMOTES 14
400 #define TOG_COLOR_REFS_BACKUP 15
402 struct tog_blame_cb_args {
403 struct tog_blame_line *lines; /* one per line */
404 int nlines;
406 struct tog_view *view;
407 struct got_object_id *commit_id;
408 int *quit;
409 };
411 struct tog_blame_thread_args {
412 const char *path;
413 struct got_repository *repo;
414 struct tog_blame_cb_args *cb_args;
415 int *complete;
416 got_cancel_cb cancel_cb;
417 void *cancel_arg;
418 };
420 struct tog_blame {
421 FILE *f;
422 off_t filesize;
423 struct tog_blame_line *lines;
424 int nlines;
425 off_t *line_offsets;
426 pthread_t thread;
427 struct tog_blame_thread_args thread_args;
428 struct tog_blame_cb_args cb_args;
429 const char *path;
430 int *pack_fds;
431 };
433 struct tog_blame_view_state {
434 int first_displayed_line;
435 int last_displayed_line;
436 int selected_line;
437 int last_diffed_line;
438 int blame_complete;
439 int eof;
440 int done;
441 struct got_object_id_queue blamed_commits;
442 struct got_object_qid *blamed_commit;
443 char *path;
444 struct got_repository *repo;
445 struct got_object_id *commit_id;
446 struct got_object_id *id_to_log;
447 struct tog_blame blame;
448 int matched_line;
449 struct tog_colors colors;
450 };
452 struct tog_parent_tree {
453 TAILQ_ENTRY(tog_parent_tree) entry;
454 struct got_tree_object *tree;
455 struct got_tree_entry *first_displayed_entry;
456 struct got_tree_entry *selected_entry;
457 int selected;
458 };
460 TAILQ_HEAD(tog_parent_trees, tog_parent_tree);
462 struct tog_tree_view_state {
463 char *tree_label;
464 struct got_object_id *commit_id;/* commit which this tree belongs to */
465 struct got_tree_object *root; /* the commit's root tree entry */
466 struct got_tree_object *tree; /* currently displayed (sub-)tree */
467 struct got_tree_entry *first_displayed_entry;
468 struct got_tree_entry *last_displayed_entry;
469 struct got_tree_entry *selected_entry;
470 int ndisplayed, selected, show_ids;
471 struct tog_parent_trees parents; /* parent trees of current sub-tree */
472 char *head_ref_name;
473 struct got_repository *repo;
474 struct got_tree_entry *matched_entry;
475 struct tog_colors colors;
476 };
478 struct tog_reflist_entry {
479 TAILQ_ENTRY(tog_reflist_entry) entry;
480 struct got_reference *ref;
481 int idx;
482 };
484 TAILQ_HEAD(tog_reflist_head, tog_reflist_entry);
486 struct tog_ref_view_state {
487 struct tog_reflist_head refs;
488 struct tog_reflist_entry *first_displayed_entry;
489 struct tog_reflist_entry *last_displayed_entry;
490 struct tog_reflist_entry *selected_entry;
491 int nrefs, ndisplayed, selected, show_date, show_ids, sort_by_date;
492 struct got_repository *repo;
493 struct tog_reflist_entry *matched_entry;
494 struct tog_colors colors;
495 };
497 /*
498 * We implement two types of views: parent views and child views.
500 * The 'Tab' key switches focus between a parent view and its child view.
501 * Child views are shown side-by-side to their parent view, provided
502 * there is enough screen estate.
504 * When a new view is opened from within a parent view, this new view
505 * becomes a child view of the parent view, replacing any existing child.
507 * When a new view is opened from within a child view, this new view
508 * becomes a parent view which will obscure the views below until the
509 * user quits the new parent view by typing 'q'.
511 * This list of views contains parent views only.
512 * Child views are only pointed to by their parent view.
513 */
514 TAILQ_HEAD(tog_view_list_head, tog_view);
516 struct tog_view {
517 TAILQ_ENTRY(tog_view) entry;
518 WINDOW *window;
519 PANEL *panel;
520 int nlines, ncols, begin_y, begin_x; /* based on split height/width */
521 int resized_y, resized_x; /* begin_y/x based on user resizing */
522 int maxx, x; /* max column and current start column */
523 int lines, cols; /* copies of LINES and COLS */
524 int nscrolled, offset; /* lines scrolled and hsplit line offset */
525 int gline, hiline; /* navigate to and highlight this nG line */
526 int ch, count; /* current keymap and count prefix */
527 int resized; /* set when in a resize event */
528 int focussed; /* Only set on one parent or child view at a time. */
529 int dying;
530 struct tog_view *parent;
531 struct tog_view *child;
533 /*
534 * This flag is initially set on parent views when a new child view
535 * is created. It gets toggled when the 'Tab' key switches focus
536 * between parent and child.
537 * The flag indicates whether focus should be passed on to our child
538 * view if this parent view gets picked for focus after another parent
539 * view was closed. This prevents child views from losing focus in such
540 * situations.
541 */
542 int focus_child;
544 enum tog_view_mode mode;
545 /* type-specific state */
546 enum tog_view_type type;
547 union {
548 struct tog_diff_view_state diff;
549 struct tog_log_view_state log;
550 struct tog_blame_view_state blame;
551 struct tog_tree_view_state tree;
552 struct tog_ref_view_state ref;
553 } state;
555 const struct got_error *(*show)(struct tog_view *);
556 const struct got_error *(*input)(struct tog_view **,
557 struct tog_view *, int);
558 const struct got_error *(*reset)(struct tog_view *);
559 const struct got_error *(*resize)(struct tog_view *, int);
560 const struct got_error *(*close)(struct tog_view *);
562 const struct got_error *(*search_start)(struct tog_view *);
563 const struct got_error *(*search_next)(struct tog_view *);
564 int search_started;
565 int searching;
566 #define TOG_SEARCH_FORWARD 1
567 #define TOG_SEARCH_BACKWARD 2
568 int search_next_done;
569 #define TOG_SEARCH_HAVE_MORE 1
570 #define TOG_SEARCH_NO_MORE 2
571 #define TOG_SEARCH_HAVE_NONE 3
572 regex_t regex;
573 regmatch_t regmatch;
574 };
576 static const struct got_error *open_diff_view(struct tog_view *,
577 struct got_object_id *, struct got_object_id *,
578 const char *, const char *, int, int, int, struct tog_view *,
579 struct got_repository *);
580 static const struct got_error *show_diff_view(struct tog_view *);
581 static const struct got_error *input_diff_view(struct tog_view **,
582 struct tog_view *, int);
583 static const struct got_error *reset_diff_view(struct tog_view *);
584 static const struct got_error* close_diff_view(struct tog_view *);
585 static const struct got_error *search_start_diff_view(struct tog_view *);
586 static const struct got_error *search_next_diff_view(struct tog_view *);
588 static const struct got_error *open_log_view(struct tog_view *,
589 struct got_object_id *, struct got_repository *,
590 const char *, const char *, int);
591 static const struct got_error * show_log_view(struct tog_view *);
592 static const struct got_error *input_log_view(struct tog_view **,
593 struct tog_view *, int);
594 static const struct got_error *resize_log_view(struct tog_view *, int);
595 static const struct got_error *close_log_view(struct tog_view *);
596 static const struct got_error *search_start_log_view(struct tog_view *);
597 static const struct got_error *search_next_log_view(struct tog_view *);
599 static const struct got_error *open_blame_view(struct tog_view *, char *,
600 struct got_object_id *, struct got_repository *);
601 static const struct got_error *show_blame_view(struct tog_view *);
602 static const struct got_error *input_blame_view(struct tog_view **,
603 struct tog_view *, int);
604 static const struct got_error *reset_blame_view(struct tog_view *);
605 static const struct got_error *close_blame_view(struct tog_view *);
606 static const struct got_error *search_start_blame_view(struct tog_view *);
607 static const struct got_error *search_next_blame_view(struct tog_view *);
609 static const struct got_error *open_tree_view(struct tog_view *,
610 struct got_object_id *, const char *, struct got_repository *);
611 static const struct got_error *show_tree_view(struct tog_view *);
612 static const struct got_error *input_tree_view(struct tog_view **,
613 struct tog_view *, int);
614 static const struct got_error *close_tree_view(struct tog_view *);
615 static const struct got_error *search_start_tree_view(struct tog_view *);
616 static const struct got_error *search_next_tree_view(struct tog_view *);
618 static const struct got_error *open_ref_view(struct tog_view *,
619 struct got_repository *);
620 static const struct got_error *show_ref_view(struct tog_view *);
621 static const struct got_error *input_ref_view(struct tog_view **,
622 struct tog_view *, int);
623 static const struct got_error *close_ref_view(struct tog_view *);
624 static const struct got_error *search_start_ref_view(struct tog_view *);
625 static const struct got_error *search_next_ref_view(struct tog_view *);
627 static volatile sig_atomic_t tog_sigwinch_received;
628 static volatile sig_atomic_t tog_sigpipe_received;
629 static volatile sig_atomic_t tog_sigcont_received;
630 static volatile sig_atomic_t tog_sigint_received;
631 static volatile sig_atomic_t tog_sigterm_received;
633 static void
634 tog_sigwinch(int signo)
636 tog_sigwinch_received = 1;
639 static void
640 tog_sigpipe(int signo)
642 tog_sigpipe_received = 1;
645 static void
646 tog_sigcont(int signo)
648 tog_sigcont_received = 1;
651 static void
652 tog_sigint(int signo)
654 tog_sigint_received = 1;
657 static void
658 tog_sigterm(int signo)
660 tog_sigterm_received = 1;
663 static int
664 tog_fatal_signal_received(void)
666 return (tog_sigpipe_received ||
667 tog_sigint_received || tog_sigint_received);
670 static const struct got_error *
671 view_close(struct tog_view *view)
673 const struct got_error *err = NULL, *child_err = NULL;
675 if (view->child) {
676 child_err = view_close(view->child);
677 view->child = NULL;
679 if (view->close)
680 err = view->close(view);
681 if (view->panel)
682 del_panel(view->panel);
683 if (view->window)
684 delwin(view->window);
685 free(view);
686 return err ? err : child_err;
689 static struct tog_view *
690 view_open(int nlines, int ncols, int begin_y, int begin_x,
691 enum tog_view_type type)
693 struct tog_view *view = calloc(1, sizeof(*view));
695 if (view == NULL)
696 return NULL;
698 view->type = type;
699 view->lines = LINES;
700 view->cols = COLS;
701 view->nlines = nlines ? nlines : LINES - begin_y;
702 view->ncols = ncols ? ncols : COLS - begin_x;
703 view->begin_y = begin_y;
704 view->begin_x = begin_x;
705 view->window = newwin(nlines, ncols, begin_y, begin_x);
706 if (view->window == NULL) {
707 view_close(view);
708 return NULL;
710 view->panel = new_panel(view->window);
711 if (view->panel == NULL ||
712 set_panel_userptr(view->panel, view) != OK) {
713 view_close(view);
714 return NULL;
717 keypad(view->window, TRUE);
718 return view;
721 static int
722 view_split_begin_x(int begin_x)
724 if (begin_x > 0 || COLS < 120)
725 return 0;
726 return (COLS - MAX(COLS / 2, 80));
729 /* XXX Stub till we decide what to do. */
730 static int
731 view_split_begin_y(int lines)
733 return lines * HSPLIT_SCALE;
736 static const struct got_error *view_resize(struct tog_view *);
738 static const struct got_error *
739 view_splitscreen(struct tog_view *view)
741 const struct got_error *err = NULL;
743 if (!view->resized && view->mode == TOG_VIEW_SPLIT_HRZN) {
744 if (view->resized_y && view->resized_y < view->lines)
745 view->begin_y = view->resized_y;
746 else
747 view->begin_y = view_split_begin_y(view->nlines);
748 view->begin_x = 0;
749 } else if (!view->resized) {
750 if (view->resized_x && view->resized_x < view->cols - 1 &&
751 view->cols > 119)
752 view->begin_x = view->resized_x;
753 else
754 view->begin_x = view_split_begin_x(0);
755 view->begin_y = 0;
757 view->nlines = LINES - view->begin_y;
758 view->ncols = COLS - view->begin_x;
759 view->lines = LINES;
760 view->cols = COLS;
761 err = view_resize(view);
762 if (err)
763 return err;
765 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN)
766 view->parent->nlines = view->begin_y;
768 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
769 return got_error_from_errno("mvwin");
771 return NULL;
774 static const struct got_error *
775 view_fullscreen(struct tog_view *view)
777 const struct got_error *err = NULL;
779 view->begin_x = 0;
780 view->begin_y = view->resized ? view->begin_y : 0;
781 view->nlines = view->resized ? view->nlines : LINES;
782 view->ncols = COLS;
783 view->lines = LINES;
784 view->cols = COLS;
785 err = view_resize(view);
786 if (err)
787 return err;
789 if (mvwin(view->window, view->begin_y, view->begin_x) == ERR)
790 return got_error_from_errno("mvwin");
792 return NULL;
795 static int
796 view_is_parent_view(struct tog_view *view)
798 return view->parent == NULL;
801 static int
802 view_is_splitscreen(struct tog_view *view)
804 return view->begin_x > 0 || view->begin_y > 0;
807 static int
808 view_is_fullscreen(struct tog_view *view)
810 return view->nlines == LINES && view->ncols == COLS;
813 static int
814 view_is_hsplit_top(struct tog_view *view)
816 return view->mode == TOG_VIEW_SPLIT_HRZN && view->child &&
817 view_is_splitscreen(view->child);
820 static void
821 view_border(struct tog_view *view)
823 PANEL *panel;
824 const struct tog_view *view_above;
826 if (view->parent)
827 return view_border(view->parent);
829 panel = panel_above(view->panel);
830 if (panel == NULL)
831 return;
833 view_above = panel_userptr(panel);
834 if (view->mode == TOG_VIEW_SPLIT_HRZN)
835 mvwhline(view->window, view_above->begin_y - 1,
836 view->begin_x, got_locale_is_utf8() ?
837 ACS_HLINE : '-', view->ncols);
838 else
839 mvwvline(view->window, view->begin_y, view_above->begin_x - 1,
840 got_locale_is_utf8() ? ACS_VLINE : '|', view->nlines);
843 static const struct got_error *view_init_hsplit(struct tog_view *, int);
844 static const struct got_error *request_log_commits(struct tog_view *);
845 static const struct got_error *offset_selection_down(struct tog_view *);
846 static void offset_selection_up(struct tog_view *);
847 static void view_get_split(struct tog_view *, int *, int *);
849 static const struct got_error *
850 view_resize(struct tog_view *view)
852 const struct got_error *err = NULL;
853 int dif, nlines, ncols;
855 dif = LINES - view->lines; /* line difference */
857 if (view->lines > LINES)
858 nlines = view->nlines - (view->lines - LINES);
859 else
860 nlines = view->nlines + (LINES - view->lines);
861 if (view->cols > COLS)
862 ncols = view->ncols - (view->cols - COLS);
863 else
864 ncols = view->ncols + (COLS - view->cols);
866 if (view->child) {
867 int hs = view->child->begin_y;
869 if (!view_is_fullscreen(view))
870 view->child->begin_x = view_split_begin_x(view->begin_x);
871 if (view->mode == TOG_VIEW_SPLIT_HRZN ||
872 view->child->begin_x == 0) {
873 ncols = COLS;
875 view_fullscreen(view->child);
876 if (view->child->focussed)
877 show_panel(view->child->panel);
878 else
879 show_panel(view->panel);
880 } else {
881 ncols = view->child->begin_x;
883 view_splitscreen(view->child);
884 show_panel(view->child->panel);
886 /*
887 * XXX This is ugly and needs to be moved into the above
888 * logic but "works" for now and my attempts at moving it
889 * break either 'tab' or 'F' key maps in horizontal splits.
890 */
891 if (hs) {
892 err = view_splitscreen(view->child);
893 if (err)
894 return err;
895 if (dif < 0) { /* top split decreased */
896 err = offset_selection_down(view);
897 if (err)
898 return err;
900 view_border(view);
901 update_panels();
902 doupdate();
903 show_panel(view->child->panel);
904 nlines = view->nlines;
906 } else if (view->parent == NULL)
907 ncols = COLS;
909 if (view->resize && dif > 0) {
910 err = view->resize(view, dif);
911 if (err)
912 return err;
915 if (wresize(view->window, nlines, ncols) == ERR)
916 return got_error_from_errno("wresize");
917 if (replace_panel(view->panel, view->window) == ERR)
918 return got_error_from_errno("replace_panel");
919 wclear(view->window);
921 view->nlines = nlines;
922 view->ncols = ncols;
923 view->lines = LINES;
924 view->cols = COLS;
926 return NULL;
929 static const struct got_error *
930 resize_log_view(struct tog_view *view, int increase)
932 struct tog_log_view_state *s = &view->state.log;
933 const struct got_error *err = NULL;
934 int n = 0;
936 if (s->selected_entry)
937 n = s->selected_entry->idx + view->lines - s->selected;
939 /*
940 * Request commits to account for the increased
941 * height so we have enough to populate the view.
942 */
943 if (s->commits.ncommits < n) {
944 view->nscrolled = n - s->commits.ncommits + increase + 1;
945 err = request_log_commits(view);
948 return err;
951 static void
952 view_adjust_offset(struct tog_view *view, int n)
954 if (n == 0)
955 return;
957 if (view->parent && view->parent->offset) {
958 if (view->parent->offset + n >= 0)
959 view->parent->offset += n;
960 else
961 view->parent->offset = 0;
962 } else if (view->offset) {
963 if (view->offset - n >= 0)
964 view->offset -= n;
965 else
966 view->offset = 0;
970 static const struct got_error *
971 view_resize_split(struct tog_view *view, int resize)
973 const struct got_error *err = NULL;
974 struct tog_view *v = NULL;
976 if (view->parent)
977 v = view->parent;
978 else
979 v = view;
981 if (!v->child || !view_is_splitscreen(v->child))
982 return NULL;
984 v->resized = v->child->resized = resize; /* lock for resize event */
986 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
987 if (v->child->resized_y)
988 v->child->begin_y = v->child->resized_y;
989 if (view->parent)
990 v->child->begin_y -= resize;
991 else
992 v->child->begin_y += resize;
993 if (v->child->begin_y < 3) {
994 view->count = 0;
995 v->child->begin_y = 3;
996 } else if (v->child->begin_y > LINES - 1) {
997 view->count = 0;
998 v->child->begin_y = LINES - 1;
1000 v->ncols = COLS;
1001 v->child->ncols = COLS;
1002 view_adjust_offset(view, resize);
1003 err = view_init_hsplit(v, v->child->begin_y);
1004 if (err)
1005 return err;
1006 v->child->resized_y = v->child->begin_y;
1007 } else {
1008 if (v->child->resized_x)
1009 v->child->begin_x = v->child->resized_x;
1010 if (view->parent)
1011 v->child->begin_x -= resize;
1012 else
1013 v->child->begin_x += resize;
1014 if (v->child->begin_x < 11) {
1015 view->count = 0;
1016 v->child->begin_x = 11;
1017 } else if (v->child->begin_x > COLS - 1) {
1018 view->count = 0;
1019 v->child->begin_x = COLS - 1;
1021 v->child->resized_x = v->child->begin_x;
1024 v->child->mode = v->mode;
1025 v->child->nlines = v->lines - v->child->begin_y;
1026 v->child->ncols = v->cols - v->child->begin_x;
1027 v->focus_child = 1;
1029 err = view_fullscreen(v);
1030 if (err)
1031 return err;
1032 err = view_splitscreen(v->child);
1033 if (err)
1034 return err;
1036 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1037 err = offset_selection_down(v->child);
1038 if (err)
1039 return err;
1042 if (v->resize)
1043 err = v->resize(v, 0);
1044 else if (v->child->resize)
1045 err = v->child->resize(v->child, 0);
1047 v->resized = v->child->resized = 0;
1049 return err;
1052 static void
1053 view_transfer_size(struct tog_view *dst, struct tog_view *src)
1055 struct tog_view *v = src->child ? src->child : src;
1057 dst->resized_x = v->resized_x;
1058 dst->resized_y = v->resized_y;
1061 static const struct got_error *
1062 view_close_child(struct tog_view *view)
1064 const struct got_error *err = NULL;
1066 if (view->child == NULL)
1067 return NULL;
1069 err = view_close(view->child);
1070 view->child = NULL;
1071 return err;
1074 static const struct got_error *
1075 view_set_child(struct tog_view *view, struct tog_view *child)
1077 const struct got_error *err = NULL;
1079 view->child = child;
1080 child->parent = view;
1082 err = view_resize(view);
1083 if (err)
1084 return err;
1086 if (view->child->resized_x || view->child->resized_y)
1087 err = view_resize_split(view, 0);
1089 return err;
1092 static const struct got_error *view_dispatch_request(struct tog_view **,
1093 struct tog_view *, enum tog_view_type, int, int);
1095 static const struct got_error *
1096 view_request_new(struct tog_view **requested, struct tog_view *view,
1097 enum tog_view_type request)
1099 struct tog_view *new_view = NULL;
1100 const struct got_error *err;
1101 int y = 0, x = 0;
1103 *requested = NULL;
1105 if (view_is_parent_view(view))
1106 view_get_split(view, &y, &x);
1108 err = view_dispatch_request(&new_view, view, request, y, x);
1109 if (err)
1110 return err;
1112 if (view_is_parent_view(view) && view->mode == TOG_VIEW_SPLIT_HRZN) {
1113 err = view_init_hsplit(view, y);
1114 if (err)
1115 return err;
1118 view->focussed = 0;
1119 new_view->focussed = 1;
1120 new_view->mode = view->mode;
1121 new_view->nlines = view->lines - y;
1123 if (view_is_parent_view(view)) {
1124 view_transfer_size(new_view, view);
1125 err = view_close_child(view);
1126 if (err)
1127 return err;
1128 err = view_set_child(view, new_view);
1129 if (err)
1130 return err;
1131 view->focus_child = 1;
1132 } else
1133 *requested = new_view;
1135 return NULL;
1138 static void
1139 tog_resizeterm(void)
1141 int cols, lines;
1142 struct winsize size;
1144 if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &size) < 0) {
1145 cols = 80; /* Default */
1146 lines = 24;
1147 } else {
1148 cols = size.ws_col;
1149 lines = size.ws_row;
1151 resize_term(lines, cols);
1154 static const struct got_error *
1155 view_search_start(struct tog_view *view)
1157 const struct got_error *err = NULL;
1158 struct tog_view *v = view;
1159 char pattern[1024];
1160 int ret;
1162 if (view->search_started) {
1163 regfree(&view->regex);
1164 view->searching = 0;
1165 memset(&view->regmatch, 0, sizeof(view->regmatch));
1167 view->search_started = 0;
1169 if (view->nlines < 1)
1170 return NULL;
1172 if (view_is_hsplit_top(view))
1173 v = view->child;
1175 mvwaddstr(v->window, v->nlines - 1, 0, "/");
1176 wclrtoeol(v->window);
1178 nodelay(view->window, FALSE); /* block for search term input */
1179 nocbreak();
1180 echo();
1181 ret = wgetnstr(v->window, pattern, sizeof(pattern));
1182 wrefresh(v->window);
1183 cbreak();
1184 noecho();
1185 nodelay(view->window, TRUE);
1186 if (ret == ERR)
1187 return NULL;
1189 if (regcomp(&view->regex, pattern, REG_EXTENDED | REG_NEWLINE) == 0) {
1190 err = view->search_start(view);
1191 if (err) {
1192 regfree(&view->regex);
1193 return err;
1195 view->search_started = 1;
1196 view->searching = TOG_SEARCH_FORWARD;
1197 view->search_next_done = 0;
1198 view->search_next(view);
1201 return NULL;
1204 /* Switch split mode. If view is a parent or child, draw the new splitscreen. */
1205 static const struct got_error *
1206 switch_split(struct tog_view *view)
1208 const struct got_error *err = NULL;
1209 struct tog_view *v = NULL;
1211 if (view->parent)
1212 v = view->parent;
1213 else
1214 v = view;
1216 if (v->mode == TOG_VIEW_SPLIT_HRZN)
1217 v->mode = TOG_VIEW_SPLIT_VERT;
1218 else
1219 v->mode = TOG_VIEW_SPLIT_HRZN;
1221 if (!v->child)
1222 return NULL;
1223 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->cols < 120)
1224 v->mode = TOG_VIEW_SPLIT_NONE;
1226 view_get_split(v, &v->child->begin_y, &v->child->begin_x);
1227 if (v->mode == TOG_VIEW_SPLIT_HRZN && v->child->resized_y)
1228 v->child->begin_y = v->child->resized_y;
1229 else if (v->mode == TOG_VIEW_SPLIT_VERT && v->child->resized_x)
1230 v->child->begin_x = v->child->resized_x;
1233 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1234 v->ncols = COLS;
1235 v->child->ncols = COLS;
1236 v->child->nscrolled = LINES - v->child->nlines;
1238 err = view_init_hsplit(v, v->child->begin_y);
1239 if (err)
1240 return err;
1242 v->child->mode = v->mode;
1243 v->child->nlines = v->lines - v->child->begin_y;
1244 v->focus_child = 1;
1246 err = view_fullscreen(v);
1247 if (err)
1248 return err;
1249 err = view_splitscreen(v->child);
1250 if (err)
1251 return err;
1253 if (v->mode == TOG_VIEW_SPLIT_NONE)
1254 v->mode = TOG_VIEW_SPLIT_VERT;
1255 if (v->mode == TOG_VIEW_SPLIT_HRZN) {
1256 err = offset_selection_down(v);
1257 if (err)
1258 return err;
1259 err = offset_selection_down(v->child);
1260 if (err)
1261 return err;
1262 } else {
1263 offset_selection_up(v);
1264 offset_selection_up(v->child);
1266 if (v->resize)
1267 err = v->resize(v, 0);
1268 else if (v->child->resize)
1269 err = v->child->resize(v->child, 0);
1271 return err;
1275 * Compute view->count from numeric input. Assign total to view->count and
1276 * return first non-numeric key entered.
1278 static int
1279 get_compound_key(struct tog_view *view, int c)
1281 struct tog_view *v = view;
1282 int x, n = 0;
1284 if (view_is_hsplit_top(view))
1285 v = view->child;
1286 else if (view->mode == TOG_VIEW_SPLIT_VERT && view->parent)
1287 v = view->parent;
1289 view->count = 0;
1290 cbreak(); /* block for input */
1291 nodelay(view->window, FALSE);
1292 wmove(v->window, v->nlines - 1, 0);
1293 wclrtoeol(v->window);
1294 waddch(v->window, ':');
1296 do {
1297 x = getcurx(v->window);
1298 if (x != ERR && x < view->ncols) {
1299 waddch(v->window, c);
1300 wrefresh(v->window);
1304 * Don't overflow. Max valid request should be the greatest
1305 * between the longest and total lines; cap at 10 million.
1307 if (n >= 9999999)
1308 n = 9999999;
1309 else
1310 n = n * 10 + (c - '0');
1311 } while (((c = wgetch(view->window))) >= '0' && c <= '9' && c != ERR);
1313 if (c == 'G' || c == 'g') { /* nG key map */
1314 view->gline = view->hiline = n;
1315 n = 0;
1316 c = 0;
1319 /* Massage excessive or inapplicable values at the input handler. */
1320 view->count = n;
1322 return c;
1325 static const struct got_error *
1326 view_input(struct tog_view **new, int *done, struct tog_view *view,
1327 struct tog_view_list_head *views)
1329 const struct got_error *err = NULL;
1330 struct tog_view *v;
1331 int ch, errcode;
1333 *new = NULL;
1335 /* Clear "no matches" indicator. */
1336 if (view->search_next_done == TOG_SEARCH_NO_MORE ||
1337 view->search_next_done == TOG_SEARCH_HAVE_NONE) {
1338 view->search_next_done = TOG_SEARCH_HAVE_MORE;
1339 view->count = 0;
1342 if (view->searching && !view->search_next_done) {
1343 errcode = pthread_mutex_unlock(&tog_mutex);
1344 if (errcode)
1345 return got_error_set_errno(errcode,
1346 "pthread_mutex_unlock");
1347 sched_yield();
1348 errcode = pthread_mutex_lock(&tog_mutex);
1349 if (errcode)
1350 return got_error_set_errno(errcode,
1351 "pthread_mutex_lock");
1352 view->search_next(view);
1353 return NULL;
1356 /* Allow threads to make progress while we are waiting for input. */
1357 errcode = pthread_mutex_unlock(&tog_mutex);
1358 if (errcode)
1359 return got_error_set_errno(errcode, "pthread_mutex_unlock");
1360 /* If we have an unfinished count, let C-g or backspace abort. */
1361 if (view->count && --view->count) {
1362 cbreak();
1363 nodelay(view->window, TRUE);
1364 ch = wgetch(view->window);
1365 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
1366 view->count = 0;
1367 else
1368 ch = view->ch;
1369 } else {
1370 ch = wgetch(view->window);
1371 if (ch >= '1' && ch <= '9')
1372 view->ch = ch = get_compound_key(view, ch);
1374 if (view->hiline && ch != ERR && ch != 0)
1375 view->hiline = 0; /* key pressed, clear line highlight */
1376 nodelay(view->window, TRUE);
1377 errcode = pthread_mutex_lock(&tog_mutex);
1378 if (errcode)
1379 return got_error_set_errno(errcode, "pthread_mutex_lock");
1381 if (tog_sigwinch_received || tog_sigcont_received) {
1382 tog_resizeterm();
1383 tog_sigwinch_received = 0;
1384 tog_sigcont_received = 0;
1385 TAILQ_FOREACH(v, views, entry) {
1386 err = view_resize(v);
1387 if (err)
1388 return err;
1389 err = v->input(new, v, KEY_RESIZE);
1390 if (err)
1391 return err;
1392 if (v->child) {
1393 err = view_resize(v->child);
1394 if (err)
1395 return err;
1396 err = v->child->input(new, v->child,
1397 KEY_RESIZE);
1398 if (err)
1399 return err;
1400 if (v->child->resized_x || v->child->resized_y) {
1401 err = view_resize_split(v, 0);
1402 if (err)
1403 return err;
1409 switch (ch) {
1410 case '\t':
1411 view->count = 0;
1412 if (view->child) {
1413 view->focussed = 0;
1414 view->child->focussed = 1;
1415 view->focus_child = 1;
1416 } else if (view->parent) {
1417 view->focussed = 0;
1418 view->parent->focussed = 1;
1419 view->parent->focus_child = 0;
1420 if (!view_is_splitscreen(view)) {
1421 if (view->parent->resize) {
1422 err = view->parent->resize(view->parent,
1423 0);
1424 if (err)
1425 return err;
1427 offset_selection_up(view->parent);
1428 err = view_fullscreen(view->parent);
1429 if (err)
1430 return err;
1433 break;
1434 case 'q':
1435 if (view->parent && view->mode == TOG_VIEW_SPLIT_HRZN) {
1436 if (view->parent->resize) {
1437 /* might need more commits to fill fullscreen */
1438 err = view->parent->resize(view->parent, 0);
1439 if (err)
1440 break;
1442 offset_selection_up(view->parent);
1444 err = view->input(new, view, ch);
1445 view->dying = 1;
1446 break;
1447 case 'Q':
1448 *done = 1;
1449 break;
1450 case 'F':
1451 view->count = 0;
1452 if (view_is_parent_view(view)) {
1453 if (view->child == NULL)
1454 break;
1455 if (view_is_splitscreen(view->child)) {
1456 view->focussed = 0;
1457 view->child->focussed = 1;
1458 err = view_fullscreen(view->child);
1459 } else {
1460 err = view_splitscreen(view->child);
1461 if (!err)
1462 err = view_resize_split(view, 0);
1464 if (err)
1465 break;
1466 err = view->child->input(new, view->child,
1467 KEY_RESIZE);
1468 } else {
1469 if (view_is_splitscreen(view)) {
1470 view->parent->focussed = 0;
1471 view->focussed = 1;
1472 err = view_fullscreen(view);
1473 } else {
1474 err = view_splitscreen(view);
1475 if (!err && view->mode != TOG_VIEW_SPLIT_HRZN)
1476 err = view_resize(view->parent);
1477 if (!err)
1478 err = view_resize_split(view, 0);
1480 if (err)
1481 break;
1482 err = view->input(new, view, KEY_RESIZE);
1484 if (err)
1485 break;
1486 if (view->resize) {
1487 err = view->resize(view, 0);
1488 if (err)
1489 break;
1491 if (view->parent)
1492 err = offset_selection_down(view->parent);
1493 if (!err)
1494 err = offset_selection_down(view);
1495 break;
1496 case 'S':
1497 view->count = 0;
1498 err = switch_split(view);
1499 break;
1500 case '-':
1501 err = view_resize_split(view, -1);
1502 break;
1503 case '+':
1504 err = view_resize_split(view, 1);
1505 break;
1506 case KEY_RESIZE:
1507 break;
1508 case '/':
1509 view->count = 0;
1510 if (view->search_start)
1511 view_search_start(view);
1512 else
1513 err = view->input(new, view, ch);
1514 break;
1515 case 'N':
1516 case 'n':
1517 if (view->search_started && view->search_next) {
1518 view->searching = (ch == 'n' ?
1519 TOG_SEARCH_FORWARD : TOG_SEARCH_BACKWARD);
1520 view->search_next_done = 0;
1521 view->search_next(view);
1522 } else
1523 err = view->input(new, view, ch);
1524 break;
1525 case 'A':
1526 if (tog_diff_algo == GOT_DIFF_ALGORITHM_MYERS)
1527 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
1528 else
1529 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
1530 TAILQ_FOREACH(v, views, entry) {
1531 if (v->reset) {
1532 err = v->reset(v);
1533 if (err)
1534 return err;
1536 if (v->child && v->child->reset) {
1537 err = v->child->reset(v->child);
1538 if (err)
1539 return err;
1542 break;
1543 default:
1544 err = view->input(new, view, ch);
1545 break;
1548 return err;
1551 static int
1552 view_needs_focus_indication(struct tog_view *view)
1554 if (view_is_parent_view(view)) {
1555 if (view->child == NULL || view->child->focussed)
1556 return 0;
1557 if (!view_is_splitscreen(view->child))
1558 return 0;
1559 } else if (!view_is_splitscreen(view))
1560 return 0;
1562 return view->focussed;
1565 static const struct got_error *
1566 view_loop(struct tog_view *view)
1568 const struct got_error *err = NULL;
1569 struct tog_view_list_head views;
1570 struct tog_view *new_view;
1571 char *mode;
1572 int fast_refresh = 10;
1573 int done = 0, errcode;
1575 mode = getenv("TOG_VIEW_SPLIT_MODE");
1576 if (!mode || !(*mode == 'h' || *mode == 'H'))
1577 view->mode = TOG_VIEW_SPLIT_VERT;
1578 else
1579 view->mode = TOG_VIEW_SPLIT_HRZN;
1581 errcode = pthread_mutex_lock(&tog_mutex);
1582 if (errcode)
1583 return got_error_set_errno(errcode, "pthread_mutex_lock");
1585 TAILQ_INIT(&views);
1586 TAILQ_INSERT_HEAD(&views, view, entry);
1588 view->focussed = 1;
1589 err = view->show(view);
1590 if (err)
1591 return err;
1592 update_panels();
1593 doupdate();
1594 while (!TAILQ_EMPTY(&views) && !done && !tog_thread_error &&
1595 !tog_fatal_signal_received()) {
1596 /* Refresh fast during initialization, then become slower. */
1597 if (fast_refresh && fast_refresh-- == 0)
1598 halfdelay(10); /* switch to once per second */
1600 err = view_input(&new_view, &done, view, &views);
1601 if (err)
1602 break;
1603 if (view->dying) {
1604 struct tog_view *v, *prev = NULL;
1606 if (view_is_parent_view(view))
1607 prev = TAILQ_PREV(view, tog_view_list_head,
1608 entry);
1609 else if (view->parent)
1610 prev = view->parent;
1612 if (view->parent) {
1613 view->parent->child = NULL;
1614 view->parent->focus_child = 0;
1615 /* Restore fullscreen line height. */
1616 view->parent->nlines = view->parent->lines;
1617 err = view_resize(view->parent);
1618 if (err)
1619 break;
1620 /* Make resized splits persist. */
1621 view_transfer_size(view->parent, view);
1622 } else
1623 TAILQ_REMOVE(&views, view, entry);
1625 err = view_close(view);
1626 if (err)
1627 goto done;
1629 view = NULL;
1630 TAILQ_FOREACH(v, &views, entry) {
1631 if (v->focussed)
1632 break;
1634 if (view == NULL && new_view == NULL) {
1635 /* No view has focus. Try to pick one. */
1636 if (prev)
1637 view = prev;
1638 else if (!TAILQ_EMPTY(&views)) {
1639 view = TAILQ_LAST(&views,
1640 tog_view_list_head);
1642 if (view) {
1643 if (view->focus_child) {
1644 view->child->focussed = 1;
1645 view = view->child;
1646 } else
1647 view->focussed = 1;
1651 if (new_view) {
1652 struct tog_view *v, *t;
1653 /* Only allow one parent view per type. */
1654 TAILQ_FOREACH_SAFE(v, &views, entry, t) {
1655 if (v->type != new_view->type)
1656 continue;
1657 TAILQ_REMOVE(&views, v, entry);
1658 err = view_close(v);
1659 if (err)
1660 goto done;
1661 break;
1663 TAILQ_INSERT_TAIL(&views, new_view, entry);
1664 view = new_view;
1666 if (view) {
1667 if (view_is_parent_view(view)) {
1668 if (view->child && view->child->focussed)
1669 view = view->child;
1670 } else {
1671 if (view->parent && view->parent->focussed)
1672 view = view->parent;
1674 show_panel(view->panel);
1675 if (view->child && view_is_splitscreen(view->child))
1676 show_panel(view->child->panel);
1677 if (view->parent && view_is_splitscreen(view)) {
1678 err = view->parent->show(view->parent);
1679 if (err)
1680 goto done;
1682 err = view->show(view);
1683 if (err)
1684 goto done;
1685 if (view->child) {
1686 err = view->child->show(view->child);
1687 if (err)
1688 goto done;
1690 update_panels();
1691 doupdate();
1694 done:
1695 while (!TAILQ_EMPTY(&views)) {
1696 const struct got_error *close_err;
1697 view = TAILQ_FIRST(&views);
1698 TAILQ_REMOVE(&views, view, entry);
1699 close_err = view_close(view);
1700 if (close_err && err == NULL)
1701 err = close_err;
1704 errcode = pthread_mutex_unlock(&tog_mutex);
1705 if (errcode && err == NULL)
1706 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
1708 return err;
1711 __dead static void
1712 usage_log(void)
1714 endwin();
1715 fprintf(stderr,
1716 "usage: %s log [-b] [-c commit] [-r repository-path] [path]\n",
1717 getprogname());
1718 exit(1);
1721 /* Create newly allocated wide-character string equivalent to a byte string. */
1722 static const struct got_error *
1723 mbs2ws(wchar_t **ws, size_t *wlen, const char *s)
1725 char *vis = NULL;
1726 const struct got_error *err = NULL;
1728 *ws = NULL;
1729 *wlen = mbstowcs(NULL, s, 0);
1730 if (*wlen == (size_t)-1) {
1731 int vislen;
1732 if (errno != EILSEQ)
1733 return got_error_from_errno("mbstowcs");
1735 /* byte string invalid in current encoding; try to "fix" it */
1736 err = got_mbsavis(&vis, &vislen, s);
1737 if (err)
1738 return err;
1739 *wlen = mbstowcs(NULL, vis, 0);
1740 if (*wlen == (size_t)-1) {
1741 err = got_error_from_errno("mbstowcs"); /* give up */
1742 goto done;
1746 *ws = calloc(*wlen + 1, sizeof(**ws));
1747 if (*ws == NULL) {
1748 err = got_error_from_errno("calloc");
1749 goto done;
1752 if (mbstowcs(*ws, vis ? vis : s, *wlen) != *wlen)
1753 err = got_error_from_errno("mbstowcs");
1754 done:
1755 free(vis);
1756 if (err) {
1757 free(*ws);
1758 *ws = NULL;
1759 *wlen = 0;
1761 return err;
1764 static const struct got_error *
1765 expand_tab(char **ptr, const char *src)
1767 char *dst;
1768 size_t len, n, idx = 0, sz = 0;
1770 *ptr = NULL;
1771 n = len = strlen(src);
1772 dst = malloc(n + 1);
1773 if (dst == NULL)
1774 return got_error_from_errno("malloc");
1776 while (idx < len && src[idx]) {
1777 const char c = src[idx];
1779 if (c == '\t') {
1780 size_t nb = TABSIZE - sz % TABSIZE;
1781 char *p;
1783 p = realloc(dst, n + nb);
1784 if (p == NULL) {
1785 free(dst);
1786 return got_error_from_errno("realloc");
1789 dst = p;
1790 n += nb;
1791 memset(dst + sz, ' ', nb);
1792 sz += nb;
1793 } else
1794 dst[sz++] = src[idx];
1795 ++idx;
1798 dst[sz] = '\0';
1799 *ptr = dst;
1800 return NULL;
1804 * Advance at most n columns from wline starting at offset off.
1805 * Return the index to the first character after the span operation.
1806 * Return the combined column width of all spanned wide character in
1807 * *rcol.
1809 static int
1810 span_wline(int *rcol, int off, wchar_t *wline, int n, int col_tab_align)
1812 int width, i, cols = 0;
1814 if (n == 0) {
1815 *rcol = cols;
1816 return off;
1819 for (i = off; wline[i] != L'\0'; ++i) {
1820 if (wline[i] == L'\t')
1821 width = TABSIZE - ((cols + col_tab_align) % TABSIZE);
1822 else
1823 width = wcwidth(wline[i]);
1825 if (width == -1) {
1826 width = 1;
1827 wline[i] = L'.';
1830 if (cols + width > n)
1831 break;
1832 cols += width;
1835 *rcol = cols;
1836 return i;
1840 * Format a line for display, ensuring that it won't overflow a width limit.
1841 * With scrolling, the width returned refers to the scrolled version of the
1842 * line, which starts at (*wlinep)[*scrollxp]. The caller must free *wlinep.
1844 static const struct got_error *
1845 format_line(wchar_t **wlinep, int *widthp, int *scrollxp,
1846 const char *line, int nscroll, int wlimit, int col_tab_align, int expand)
1848 const struct got_error *err = NULL;
1849 int cols;
1850 wchar_t *wline = NULL;
1851 char *exstr = NULL;
1852 size_t wlen;
1853 int i, scrollx;
1855 *wlinep = NULL;
1856 *widthp = 0;
1858 if (expand) {
1859 err = expand_tab(&exstr, line);
1860 if (err)
1861 return err;
1864 err = mbs2ws(&wline, &wlen, expand ? exstr : line);
1865 free(exstr);
1866 if (err)
1867 return err;
1869 scrollx = span_wline(&cols, 0, wline, nscroll, col_tab_align);
1871 if (wlen > 0 && wline[wlen - 1] == L'\n') {
1872 wline[wlen - 1] = L'\0';
1873 wlen--;
1875 if (wlen > 0 && wline[wlen - 1] == L'\r') {
1876 wline[wlen - 1] = L'\0';
1877 wlen--;
1880 i = span_wline(&cols, scrollx, wline, wlimit, col_tab_align);
1881 wline[i] = L'\0';
1883 if (widthp)
1884 *widthp = cols;
1885 if (scrollxp)
1886 *scrollxp = scrollx;
1887 if (err)
1888 free(wline);
1889 else
1890 *wlinep = wline;
1891 return err;
1894 static const struct got_error*
1895 build_refs_str(char **refs_str, struct got_reflist_head *refs,
1896 struct got_object_id *id, struct got_repository *repo)
1898 static const struct got_error *err = NULL;
1899 struct got_reflist_entry *re;
1900 char *s;
1901 const char *name;
1903 *refs_str = NULL;
1905 TAILQ_FOREACH(re, refs, entry) {
1906 struct got_tag_object *tag = NULL;
1907 struct got_object_id *ref_id;
1908 int cmp;
1910 name = got_ref_get_name(re->ref);
1911 if (strcmp(name, GOT_REF_HEAD) == 0)
1912 continue;
1913 if (strncmp(name, "refs/", 5) == 0)
1914 name += 5;
1915 if (strncmp(name, "got/", 4) == 0 &&
1916 strncmp(name, "got/backup/", 11) != 0)
1917 continue;
1918 if (strncmp(name, "heads/", 6) == 0)
1919 name += 6;
1920 if (strncmp(name, "remotes/", 8) == 0) {
1921 name += 8;
1922 s = strstr(name, "/" GOT_REF_HEAD);
1923 if (s != NULL && s[strlen(s)] == '\0')
1924 continue;
1926 err = got_ref_resolve(&ref_id, repo, re->ref);
1927 if (err)
1928 break;
1929 if (strncmp(name, "tags/", 5) == 0) {
1930 err = got_object_open_as_tag(&tag, repo, ref_id);
1931 if (err) {
1932 if (err->code != GOT_ERR_OBJ_TYPE) {
1933 free(ref_id);
1934 break;
1936 /* Ref points at something other than a tag. */
1937 err = NULL;
1938 tag = NULL;
1941 cmp = got_object_id_cmp(tag ?
1942 got_object_tag_get_object_id(tag) : ref_id, id);
1943 free(ref_id);
1944 if (tag)
1945 got_object_tag_close(tag);
1946 if (cmp != 0)
1947 continue;
1948 s = *refs_str;
1949 if (asprintf(refs_str, "%s%s%s", s ? s : "",
1950 s ? ", " : "", name) == -1) {
1951 err = got_error_from_errno("asprintf");
1952 free(s);
1953 *refs_str = NULL;
1954 break;
1956 free(s);
1959 return err;
1962 static const struct got_error *
1963 format_author(wchar_t **wauthor, int *author_width, char *author, int limit,
1964 int col_tab_align)
1966 char *smallerthan;
1968 smallerthan = strchr(author, '<');
1969 if (smallerthan && smallerthan[1] != '\0')
1970 author = smallerthan + 1;
1971 author[strcspn(author, "@>")] = '\0';
1972 return format_line(wauthor, author_width, NULL, author, 0, limit,
1973 col_tab_align, 0);
1976 static const struct got_error *
1977 draw_commit(struct tog_view *view, struct got_commit_object *commit,
1978 struct got_object_id *id, const size_t date_display_cols,
1979 int author_display_cols)
1981 struct tog_log_view_state *s = &view->state.log;
1982 const struct got_error *err = NULL;
1983 char datebuf[12]; /* YYYY-MM-DD + SPACE + NUL */
1984 char *logmsg0 = NULL, *logmsg = NULL;
1985 char *author = NULL;
1986 wchar_t *wlogmsg = NULL, *wauthor = NULL;
1987 int author_width, logmsg_width;
1988 char *newline, *line = NULL;
1989 int col, limit, scrollx;
1990 const int avail = view->ncols;
1991 struct tm tm;
1992 time_t committer_time;
1993 struct tog_color *tc;
1995 committer_time = got_object_commit_get_committer_time(commit);
1996 if (gmtime_r(&committer_time, &tm) == NULL)
1997 return got_error_from_errno("gmtime_r");
1998 if (strftime(datebuf, sizeof(datebuf), "%G-%m-%d ", &tm) == 0)
1999 return got_error(GOT_ERR_NO_SPACE);
2001 if (avail <= date_display_cols)
2002 limit = MIN(sizeof(datebuf) - 1, avail);
2003 else
2004 limit = MIN(date_display_cols, sizeof(datebuf) - 1);
2005 tc = get_color(&s->colors, TOG_COLOR_DATE);
2006 if (tc)
2007 wattr_on(view->window,
2008 COLOR_PAIR(tc->colorpair), NULL);
2009 waddnstr(view->window, datebuf, limit);
2010 if (tc)
2011 wattr_off(view->window,
2012 COLOR_PAIR(tc->colorpair), NULL);
2013 col = limit;
2014 if (col > avail)
2015 goto done;
2017 if (avail >= 120) {
2018 char *id_str;
2019 err = got_object_id_str(&id_str, id);
2020 if (err)
2021 goto done;
2022 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2023 if (tc)
2024 wattr_on(view->window,
2025 COLOR_PAIR(tc->colorpair), NULL);
2026 wprintw(view->window, "%.8s ", id_str);
2027 if (tc)
2028 wattr_off(view->window,
2029 COLOR_PAIR(tc->colorpair), NULL);
2030 free(id_str);
2031 col += 9;
2032 if (col > avail)
2033 goto done;
2036 if (s->use_committer)
2037 author = strdup(got_object_commit_get_committer(commit));
2038 else
2039 author = strdup(got_object_commit_get_author(commit));
2040 if (author == NULL) {
2041 err = got_error_from_errno("strdup");
2042 goto done;
2044 err = format_author(&wauthor, &author_width, author, avail - col, col);
2045 if (err)
2046 goto done;
2047 tc = get_color(&s->colors, TOG_COLOR_AUTHOR);
2048 if (tc)
2049 wattr_on(view->window,
2050 COLOR_PAIR(tc->colorpair), NULL);
2051 waddwstr(view->window, wauthor);
2052 if (tc)
2053 wattr_off(view->window,
2054 COLOR_PAIR(tc->colorpair), NULL);
2055 col += author_width;
2056 while (col < avail && author_width < author_display_cols + 2) {
2057 waddch(view->window, ' ');
2058 col++;
2059 author_width++;
2061 if (col > avail)
2062 goto done;
2064 err = got_object_commit_get_logmsg(&logmsg0, commit);
2065 if (err)
2066 goto done;
2067 logmsg = logmsg0;
2068 while (*logmsg == '\n')
2069 logmsg++;
2070 newline = strchr(logmsg, '\n');
2071 if (newline)
2072 *newline = '\0';
2073 limit = avail - col;
2074 if (view->child && !view_is_hsplit_top(view) && limit > 0)
2075 limit--; /* for the border */
2076 err = format_line(&wlogmsg, &logmsg_width, &scrollx, logmsg, view->x,
2077 limit, col, 1);
2078 if (err)
2079 goto done;
2080 waddwstr(view->window, &wlogmsg[scrollx]);
2081 col += MAX(logmsg_width, 0);
2082 while (col < avail) {
2083 waddch(view->window, ' ');
2084 col++;
2086 done:
2087 free(logmsg0);
2088 free(wlogmsg);
2089 free(author);
2090 free(wauthor);
2091 free(line);
2092 return err;
2095 static struct commit_queue_entry *
2096 alloc_commit_queue_entry(struct got_commit_object *commit,
2097 struct got_object_id *id)
2099 struct commit_queue_entry *entry;
2100 struct got_object_id *dup;
2102 entry = calloc(1, sizeof(*entry));
2103 if (entry == NULL)
2104 return NULL;
2106 dup = got_object_id_dup(id);
2107 if (dup == NULL) {
2108 free(entry);
2109 return NULL;
2112 entry->id = dup;
2113 entry->commit = commit;
2114 return entry;
2117 static void
2118 pop_commit(struct commit_queue *commits)
2120 struct commit_queue_entry *entry;
2122 entry = TAILQ_FIRST(&commits->head);
2123 TAILQ_REMOVE(&commits->head, entry, entry);
2124 got_object_commit_close(entry->commit);
2125 commits->ncommits--;
2126 free(entry->id);
2127 free(entry);
2130 static void
2131 free_commits(struct commit_queue *commits)
2133 while (!TAILQ_EMPTY(&commits->head))
2134 pop_commit(commits);
2137 static const struct got_error *
2138 match_commit(int *have_match, struct got_object_id *id,
2139 struct got_commit_object *commit, regex_t *regex)
2141 const struct got_error *err = NULL;
2142 regmatch_t regmatch;
2143 char *id_str = NULL, *logmsg = NULL;
2145 *have_match = 0;
2147 err = got_object_id_str(&id_str, id);
2148 if (err)
2149 return err;
2151 err = got_object_commit_get_logmsg(&logmsg, commit);
2152 if (err)
2153 goto done;
2155 if (regexec(regex, got_object_commit_get_author(commit), 1,
2156 &regmatch, 0) == 0 ||
2157 regexec(regex, got_object_commit_get_committer(commit), 1,
2158 &regmatch, 0) == 0 ||
2159 regexec(regex, id_str, 1, &regmatch, 0) == 0 ||
2160 regexec(regex, logmsg, 1, &regmatch, 0) == 0)
2161 *have_match = 1;
2162 done:
2163 free(id_str);
2164 free(logmsg);
2165 return err;
2168 static const struct got_error *
2169 queue_commits(struct tog_log_thread_args *a)
2171 const struct got_error *err = NULL;
2174 * We keep all commits open throughout the lifetime of the log
2175 * view in order to avoid having to re-fetch commits from disk
2176 * while updating the display.
2178 do {
2179 struct got_object_id *id;
2180 struct got_commit_object *commit;
2181 struct commit_queue_entry *entry;
2182 int errcode;
2184 err = got_commit_graph_iter_next(&id, a->graph, a->repo,
2185 NULL, NULL);
2186 if (err || id == NULL)
2187 break;
2189 err = got_object_open_as_commit(&commit, a->repo, id);
2190 if (err)
2191 break;
2192 entry = alloc_commit_queue_entry(commit, id);
2193 if (entry == NULL) {
2194 err = got_error_from_errno("alloc_commit_queue_entry");
2195 break;
2198 errcode = pthread_mutex_lock(&tog_mutex);
2199 if (errcode) {
2200 err = got_error_set_errno(errcode,
2201 "pthread_mutex_lock");
2202 break;
2205 entry->idx = a->commits->ncommits;
2206 TAILQ_INSERT_TAIL(&a->commits->head, entry, entry);
2207 a->commits->ncommits++;
2209 if (*a->searching == TOG_SEARCH_FORWARD &&
2210 !*a->search_next_done) {
2211 int have_match;
2212 err = match_commit(&have_match, id, commit, a->regex);
2213 if (err)
2214 break;
2215 if (have_match)
2216 *a->search_next_done = TOG_SEARCH_HAVE_MORE;
2219 errcode = pthread_mutex_unlock(&tog_mutex);
2220 if (errcode && err == NULL)
2221 err = got_error_set_errno(errcode,
2222 "pthread_mutex_unlock");
2223 if (err)
2224 break;
2225 } while (*a->searching == TOG_SEARCH_FORWARD && !*a->search_next_done);
2227 return err;
2230 static void
2231 select_commit(struct tog_log_view_state *s)
2233 struct commit_queue_entry *entry;
2234 int ncommits = 0;
2236 entry = s->first_displayed_entry;
2237 while (entry) {
2238 if (ncommits == s->selected) {
2239 s->selected_entry = entry;
2240 break;
2242 entry = TAILQ_NEXT(entry, entry);
2243 ncommits++;
2247 static const struct got_error *
2248 draw_commits(struct tog_view *view)
2250 const struct got_error *err = NULL;
2251 struct tog_log_view_state *s = &view->state.log;
2252 struct commit_queue_entry *entry = s->selected_entry;
2253 int limit = view->nlines;
2254 int width;
2255 int ncommits, author_cols = 4;
2256 char *id_str = NULL, *header = NULL, *ncommits_str = NULL;
2257 char *refs_str = NULL;
2258 wchar_t *wline;
2259 struct tog_color *tc;
2260 static const size_t date_display_cols = 12;
2262 if (view_is_hsplit_top(view))
2263 --limit; /* account for border */
2265 if (s->selected_entry &&
2266 !(view->searching && view->search_next_done == 0)) {
2267 struct got_reflist_head *refs;
2268 err = got_object_id_str(&id_str, s->selected_entry->id);
2269 if (err)
2270 return err;
2271 refs = got_reflist_object_id_map_lookup(tog_refs_idmap,
2272 s->selected_entry->id);
2273 if (refs) {
2274 err = build_refs_str(&refs_str, refs,
2275 s->selected_entry->id, s->repo);
2276 if (err)
2277 goto done;
2281 if (s->thread_args.commits_needed == 0)
2282 halfdelay(10); /* disable fast refresh */
2284 if (s->thread_args.commits_needed > 0 || s->thread_args.load_all) {
2285 if (asprintf(&ncommits_str, " [%d/%d] %s",
2286 entry ? entry->idx + 1 : 0, s->commits.ncommits,
2287 (view->searching && !view->search_next_done) ?
2288 "searching..." : "loading...") == -1) {
2289 err = got_error_from_errno("asprintf");
2290 goto done;
2292 } else {
2293 const char *search_str = NULL;
2295 if (view->searching) {
2296 if (view->search_next_done == TOG_SEARCH_NO_MORE)
2297 search_str = "no more matches";
2298 else if (view->search_next_done == TOG_SEARCH_HAVE_NONE)
2299 search_str = "no matches found";
2300 else if (!view->search_next_done)
2301 search_str = "searching...";
2304 if (asprintf(&ncommits_str, " [%d/%d] %s",
2305 entry ? entry->idx + 1 : 0, s->commits.ncommits,
2306 search_str ? search_str :
2307 (refs_str ? refs_str : "")) == -1) {
2308 err = got_error_from_errno("asprintf");
2309 goto done;
2313 if (s->in_repo_path && strcmp(s->in_repo_path, "/") != 0) {
2314 if (asprintf(&header, "commit %s %s%s", id_str ? id_str :
2315 "........................................",
2316 s->in_repo_path, ncommits_str) == -1) {
2317 err = got_error_from_errno("asprintf");
2318 header = NULL;
2319 goto done;
2321 } else if (asprintf(&header, "commit %s%s",
2322 id_str ? id_str : "........................................",
2323 ncommits_str) == -1) {
2324 err = got_error_from_errno("asprintf");
2325 header = NULL;
2326 goto done;
2328 err = format_line(&wline, &width, NULL, header, 0, view->ncols, 0, 0);
2329 if (err)
2330 goto done;
2332 werase(view->window);
2334 if (view_needs_focus_indication(view))
2335 wstandout(view->window);
2336 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
2337 if (tc)
2338 wattr_on(view->window,
2339 COLOR_PAIR(tc->colorpair), NULL);
2340 waddwstr(view->window, wline);
2341 if (tc)
2342 wattr_off(view->window,
2343 COLOR_PAIR(tc->colorpair), NULL);
2344 while (width < view->ncols) {
2345 waddch(view->window, ' ');
2346 width++;
2348 if (view_needs_focus_indication(view))
2349 wstandend(view->window);
2350 free(wline);
2351 if (limit <= 1)
2352 goto done;
2354 /* Grow author column size if necessary, and set view->maxx. */
2355 entry = s->first_displayed_entry;
2356 ncommits = 0;
2357 view->maxx = 0;
2358 while (entry) {
2359 struct got_commit_object *c = entry->commit;
2360 char *author, *eol, *msg, *msg0;
2361 wchar_t *wauthor, *wmsg;
2362 int width;
2363 if (ncommits >= limit - 1)
2364 break;
2365 if (s->use_committer)
2366 author = strdup(got_object_commit_get_committer(c));
2367 else
2368 author = strdup(got_object_commit_get_author(c));
2369 if (author == NULL) {
2370 err = got_error_from_errno("strdup");
2371 goto done;
2373 err = format_author(&wauthor, &width, author, COLS,
2374 date_display_cols);
2375 if (author_cols < width)
2376 author_cols = width;
2377 free(wauthor);
2378 free(author);
2379 if (err)
2380 goto done;
2381 err = got_object_commit_get_logmsg(&msg0, c);
2382 if (err)
2383 goto done;
2384 msg = msg0;
2385 while (*msg == '\n')
2386 ++msg;
2387 if ((eol = strchr(msg, '\n')))
2388 *eol = '\0';
2389 err = format_line(&wmsg, &width, NULL, msg, 0, INT_MAX,
2390 date_display_cols + author_cols, 0);
2391 if (err)
2392 goto done;
2393 view->maxx = MAX(view->maxx, width);
2394 free(msg0);
2395 free(wmsg);
2396 ncommits++;
2397 entry = TAILQ_NEXT(entry, entry);
2400 entry = s->first_displayed_entry;
2401 s->last_displayed_entry = s->first_displayed_entry;
2402 ncommits = 0;
2403 while (entry) {
2404 if (ncommits >= limit - 1)
2405 break;
2406 if (ncommits == s->selected)
2407 wstandout(view->window);
2408 err = draw_commit(view, entry->commit, entry->id,
2409 date_display_cols, author_cols);
2410 if (ncommits == s->selected)
2411 wstandend(view->window);
2412 if (err)
2413 goto done;
2414 ncommits++;
2415 s->last_displayed_entry = entry;
2416 entry = TAILQ_NEXT(entry, entry);
2419 view_border(view);
2420 done:
2421 free(id_str);
2422 free(refs_str);
2423 free(ncommits_str);
2424 free(header);
2425 return err;
2428 static void
2429 log_scroll_up(struct tog_log_view_state *s, int maxscroll)
2431 struct commit_queue_entry *entry;
2432 int nscrolled = 0;
2434 entry = TAILQ_FIRST(&s->commits.head);
2435 if (s->first_displayed_entry == entry)
2436 return;
2438 entry = s->first_displayed_entry;
2439 while (entry && nscrolled < maxscroll) {
2440 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2441 if (entry) {
2442 s->first_displayed_entry = entry;
2443 nscrolled++;
2448 static const struct got_error *
2449 trigger_log_thread(struct tog_view *view, int wait)
2451 struct tog_log_thread_args *ta = &view->state.log.thread_args;
2452 int errcode;
2454 halfdelay(1); /* fast refresh while loading commits */
2456 while (!ta->log_complete && !tog_thread_error &&
2457 (ta->commits_needed > 0 || ta->load_all)) {
2458 /* Wake the log thread. */
2459 errcode = pthread_cond_signal(&ta->need_commits);
2460 if (errcode)
2461 return got_error_set_errno(errcode,
2462 "pthread_cond_signal");
2465 * The mutex will be released while the view loop waits
2466 * in wgetch(), at which time the log thread will run.
2468 if (!wait)
2469 break;
2471 /* Display progress update in log view. */
2472 show_log_view(view);
2473 update_panels();
2474 doupdate();
2476 /* Wait right here while next commit is being loaded. */
2477 errcode = pthread_cond_wait(&ta->commit_loaded, &tog_mutex);
2478 if (errcode)
2479 return got_error_set_errno(errcode,
2480 "pthread_cond_wait");
2482 /* Display progress update in log view. */
2483 show_log_view(view);
2484 update_panels();
2485 doupdate();
2488 return NULL;
2491 static const struct got_error *
2492 request_log_commits(struct tog_view *view)
2494 struct tog_log_view_state *state = &view->state.log;
2495 const struct got_error *err = NULL;
2497 if (state->thread_args.log_complete)
2498 return NULL;
2500 state->thread_args.commits_needed += view->nscrolled;
2501 err = trigger_log_thread(view, 1);
2502 view->nscrolled = 0;
2504 return err;
2507 static const struct got_error *
2508 log_scroll_down(struct tog_view *view, int maxscroll)
2510 struct tog_log_view_state *s = &view->state.log;
2511 const struct got_error *err = NULL;
2512 struct commit_queue_entry *pentry;
2513 int nscrolled = 0, ncommits_needed;
2515 if (s->last_displayed_entry == NULL)
2516 return NULL;
2518 ncommits_needed = s->last_displayed_entry->idx + 1 + maxscroll;
2519 if (s->commits.ncommits < ncommits_needed &&
2520 !s->thread_args.log_complete) {
2522 * Ask the log thread for required amount of commits.
2524 s->thread_args.commits_needed +=
2525 ncommits_needed - s->commits.ncommits;
2526 err = trigger_log_thread(view, 1);
2527 if (err)
2528 return err;
2531 do {
2532 pentry = TAILQ_NEXT(s->last_displayed_entry, entry);
2533 if (pentry == NULL && view->mode != TOG_VIEW_SPLIT_HRZN)
2534 break;
2536 s->last_displayed_entry = pentry ?
2537 pentry : s->last_displayed_entry;;
2539 pentry = TAILQ_NEXT(s->first_displayed_entry, entry);
2540 if (pentry == NULL)
2541 break;
2542 s->first_displayed_entry = pentry;
2543 } while (++nscrolled < maxscroll);
2545 if (view->mode == TOG_VIEW_SPLIT_HRZN && !s->thread_args.log_complete)
2546 view->nscrolled += nscrolled;
2547 else
2548 view->nscrolled = 0;
2550 return err;
2553 static const struct got_error *
2554 open_diff_view_for_commit(struct tog_view **new_view, int begin_y, int begin_x,
2555 struct got_commit_object *commit, struct got_object_id *commit_id,
2556 struct tog_view *log_view, struct got_repository *repo)
2558 const struct got_error *err;
2559 struct got_object_qid *parent_id;
2560 struct tog_view *diff_view;
2562 diff_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_DIFF);
2563 if (diff_view == NULL)
2564 return got_error_from_errno("view_open");
2566 parent_id = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
2567 err = open_diff_view(diff_view, parent_id ? &parent_id->id : NULL,
2568 commit_id, NULL, NULL, 3, 0, 0, log_view, repo);
2569 if (err == NULL)
2570 *new_view = diff_view;
2571 return err;
2574 static const struct got_error *
2575 tree_view_visit_subtree(struct tog_tree_view_state *s,
2576 struct got_tree_object *subtree)
2578 struct tog_parent_tree *parent;
2580 parent = calloc(1, sizeof(*parent));
2581 if (parent == NULL)
2582 return got_error_from_errno("calloc");
2584 parent->tree = s->tree;
2585 parent->first_displayed_entry = s->first_displayed_entry;
2586 parent->selected_entry = s->selected_entry;
2587 parent->selected = s->selected;
2588 TAILQ_INSERT_HEAD(&s->parents, parent, entry);
2589 s->tree = subtree;
2590 s->selected = 0;
2591 s->first_displayed_entry = NULL;
2592 return NULL;
2595 static const struct got_error *
2596 tree_view_walk_path(struct tog_tree_view_state *s,
2597 struct got_commit_object *commit, const char *path)
2599 const struct got_error *err = NULL;
2600 struct got_tree_object *tree = NULL;
2601 const char *p;
2602 char *slash, *subpath = NULL;
2604 /* Walk the path and open corresponding tree objects. */
2605 p = path;
2606 while (*p) {
2607 struct got_tree_entry *te;
2608 struct got_object_id *tree_id;
2609 char *te_name;
2611 while (p[0] == '/')
2612 p++;
2614 /* Ensure the correct subtree entry is selected. */
2615 slash = strchr(p, '/');
2616 if (slash == NULL)
2617 te_name = strdup(p);
2618 else
2619 te_name = strndup(p, slash - p);
2620 if (te_name == NULL) {
2621 err = got_error_from_errno("strndup");
2622 break;
2624 te = got_object_tree_find_entry(s->tree, te_name);
2625 if (te == NULL) {
2626 err = got_error_path(te_name, GOT_ERR_NO_TREE_ENTRY);
2627 free(te_name);
2628 break;
2630 free(te_name);
2631 s->first_displayed_entry = s->selected_entry = te;
2633 if (!S_ISDIR(got_tree_entry_get_mode(s->selected_entry)))
2634 break; /* jump to this file's entry */
2636 slash = strchr(p, '/');
2637 if (slash)
2638 subpath = strndup(path, slash - path);
2639 else
2640 subpath = strdup(path);
2641 if (subpath == NULL) {
2642 err = got_error_from_errno("strdup");
2643 break;
2646 err = got_object_id_by_path(&tree_id, s->repo, commit,
2647 subpath);
2648 if (err)
2649 break;
2651 err = got_object_open_as_tree(&tree, s->repo, tree_id);
2652 free(tree_id);
2653 if (err)
2654 break;
2656 err = tree_view_visit_subtree(s, tree);
2657 if (err) {
2658 got_object_tree_close(tree);
2659 break;
2661 if (slash == NULL)
2662 break;
2663 free(subpath);
2664 subpath = NULL;
2665 p = slash;
2668 free(subpath);
2669 return err;
2672 static const struct got_error *
2673 browse_commit_tree(struct tog_view **new_view, int begin_y, int begin_x,
2674 struct commit_queue_entry *entry, const char *path,
2675 const char *head_ref_name, struct got_repository *repo)
2677 const struct got_error *err = NULL;
2678 struct tog_tree_view_state *s;
2679 struct tog_view *tree_view;
2681 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
2682 if (tree_view == NULL)
2683 return got_error_from_errno("view_open");
2685 err = open_tree_view(tree_view, entry->id, head_ref_name, repo);
2686 if (err)
2687 return err;
2688 s = &tree_view->state.tree;
2690 *new_view = tree_view;
2692 if (got_path_is_root_dir(path))
2693 return NULL;
2695 return tree_view_walk_path(s, entry->commit, path);
2698 static const struct got_error *
2699 block_signals_used_by_main_thread(void)
2701 sigset_t sigset;
2702 int errcode;
2704 if (sigemptyset(&sigset) == -1)
2705 return got_error_from_errno("sigemptyset");
2707 /* tog handles SIGWINCH, SIGCONT, SIGINT, SIGTERM */
2708 if (sigaddset(&sigset, SIGWINCH) == -1)
2709 return got_error_from_errno("sigaddset");
2710 if (sigaddset(&sigset, SIGCONT) == -1)
2711 return got_error_from_errno("sigaddset");
2712 if (sigaddset(&sigset, SIGINT) == -1)
2713 return got_error_from_errno("sigaddset");
2714 if (sigaddset(&sigset, SIGTERM) == -1)
2715 return got_error_from_errno("sigaddset");
2717 /* ncurses handles SIGTSTP */
2718 if (sigaddset(&sigset, SIGTSTP) == -1)
2719 return got_error_from_errno("sigaddset");
2721 errcode = pthread_sigmask(SIG_BLOCK, &sigset, NULL);
2722 if (errcode)
2723 return got_error_set_errno(errcode, "pthread_sigmask");
2725 return NULL;
2728 static void *
2729 log_thread(void *arg)
2731 const struct got_error *err = NULL;
2732 int errcode = 0;
2733 struct tog_log_thread_args *a = arg;
2734 int done = 0;
2737 * Sync startup with main thread such that we begin our
2738 * work once view_input() has released the mutex.
2740 errcode = pthread_mutex_lock(&tog_mutex);
2741 if (errcode) {
2742 err = got_error_set_errno(errcode, "pthread_mutex_lock");
2743 return (void *)err;
2746 err = block_signals_used_by_main_thread();
2747 if (err) {
2748 pthread_mutex_unlock(&tog_mutex);
2749 goto done;
2752 while (!done && !err && !tog_fatal_signal_received()) {
2753 errcode = pthread_mutex_unlock(&tog_mutex);
2754 if (errcode) {
2755 err = got_error_set_errno(errcode,
2756 "pthread_mutex_unlock");
2757 goto done;
2759 err = queue_commits(a);
2760 if (err) {
2761 if (err->code != GOT_ERR_ITER_COMPLETED)
2762 goto done;
2763 err = NULL;
2764 done = 1;
2765 } else if (a->commits_needed > 0 && !a->load_all)
2766 a->commits_needed--;
2768 errcode = pthread_mutex_lock(&tog_mutex);
2769 if (errcode) {
2770 err = got_error_set_errno(errcode,
2771 "pthread_mutex_lock");
2772 goto done;
2773 } else if (*a->quit)
2774 done = 1;
2775 else if (*a->first_displayed_entry == NULL) {
2776 *a->first_displayed_entry =
2777 TAILQ_FIRST(&a->commits->head);
2778 *a->selected_entry = *a->first_displayed_entry;
2781 errcode = pthread_cond_signal(&a->commit_loaded);
2782 if (errcode) {
2783 err = got_error_set_errno(errcode,
2784 "pthread_cond_signal");
2785 pthread_mutex_unlock(&tog_mutex);
2786 goto done;
2789 if (done)
2790 a->commits_needed = 0;
2791 else {
2792 if (a->commits_needed == 0 && !a->load_all) {
2793 errcode = pthread_cond_wait(&a->need_commits,
2794 &tog_mutex);
2795 if (errcode) {
2796 err = got_error_set_errno(errcode,
2797 "pthread_cond_wait");
2798 pthread_mutex_unlock(&tog_mutex);
2799 goto done;
2801 if (*a->quit)
2802 done = 1;
2806 a->log_complete = 1;
2807 errcode = pthread_mutex_unlock(&tog_mutex);
2808 if (errcode)
2809 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
2810 done:
2811 if (err) {
2812 tog_thread_error = 1;
2813 pthread_cond_signal(&a->commit_loaded);
2815 return (void *)err;
2818 static const struct got_error *
2819 stop_log_thread(struct tog_log_view_state *s)
2821 const struct got_error *err = NULL, *thread_err = NULL;
2822 int errcode;
2824 if (s->thread) {
2825 s->quit = 1;
2826 errcode = pthread_cond_signal(&s->thread_args.need_commits);
2827 if (errcode)
2828 return got_error_set_errno(errcode,
2829 "pthread_cond_signal");
2830 errcode = pthread_mutex_unlock(&tog_mutex);
2831 if (errcode)
2832 return got_error_set_errno(errcode,
2833 "pthread_mutex_unlock");
2834 errcode = pthread_join(s->thread, (void **)&thread_err);
2835 if (errcode)
2836 return got_error_set_errno(errcode, "pthread_join");
2837 errcode = pthread_mutex_lock(&tog_mutex);
2838 if (errcode)
2839 return got_error_set_errno(errcode,
2840 "pthread_mutex_lock");
2841 s->thread = 0; //NULL;
2844 if (s->thread_args.repo) {
2845 err = got_repo_close(s->thread_args.repo);
2846 s->thread_args.repo = NULL;
2849 if (s->thread_args.pack_fds) {
2850 const struct got_error *pack_err =
2851 got_repo_pack_fds_close(s->thread_args.pack_fds);
2852 if (err == NULL)
2853 err = pack_err;
2854 s->thread_args.pack_fds = NULL;
2857 if (s->thread_args.graph) {
2858 got_commit_graph_close(s->thread_args.graph);
2859 s->thread_args.graph = NULL;
2862 return err ? err : thread_err;
2865 static const struct got_error *
2866 close_log_view(struct tog_view *view)
2868 const struct got_error *err = NULL;
2869 struct tog_log_view_state *s = &view->state.log;
2870 int errcode;
2872 err = stop_log_thread(s);
2874 errcode = pthread_cond_destroy(&s->thread_args.need_commits);
2875 if (errcode && err == NULL)
2876 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2878 errcode = pthread_cond_destroy(&s->thread_args.commit_loaded);
2879 if (errcode && err == NULL)
2880 err = got_error_set_errno(errcode, "pthread_cond_destroy");
2882 free_commits(&s->commits);
2883 free(s->in_repo_path);
2884 s->in_repo_path = NULL;
2885 free(s->start_id);
2886 s->start_id = NULL;
2887 free(s->head_ref_name);
2888 s->head_ref_name = NULL;
2889 return err;
2892 static const struct got_error *
2893 search_start_log_view(struct tog_view *view)
2895 struct tog_log_view_state *s = &view->state.log;
2897 s->matched_entry = NULL;
2898 s->search_entry = NULL;
2899 return NULL;
2902 static const struct got_error *
2903 search_next_log_view(struct tog_view *view)
2905 const struct got_error *err = NULL;
2906 struct tog_log_view_state *s = &view->state.log;
2907 struct commit_queue_entry *entry;
2909 /* Display progress update in log view. */
2910 show_log_view(view);
2911 update_panels();
2912 doupdate();
2914 if (s->search_entry) {
2915 int errcode, ch;
2916 errcode = pthread_mutex_unlock(&tog_mutex);
2917 if (errcode)
2918 return got_error_set_errno(errcode,
2919 "pthread_mutex_unlock");
2920 ch = wgetch(view->window);
2921 errcode = pthread_mutex_lock(&tog_mutex);
2922 if (errcode)
2923 return got_error_set_errno(errcode,
2924 "pthread_mutex_lock");
2925 if (ch == CTRL('g') || ch == KEY_BACKSPACE) {
2926 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2927 return NULL;
2929 if (view->searching == TOG_SEARCH_FORWARD)
2930 entry = TAILQ_NEXT(s->search_entry, entry);
2931 else
2932 entry = TAILQ_PREV(s->search_entry,
2933 commit_queue_head, entry);
2934 } else if (s->matched_entry) {
2935 int matched_idx = s->matched_entry->idx;
2936 int selected_idx = s->selected_entry->idx;
2939 * If the user has moved the cursor after we hit a match,
2940 * the position from where we should continue searching
2941 * might have changed.
2943 if (view->searching == TOG_SEARCH_FORWARD) {
2944 if (matched_idx > selected_idx)
2945 entry = TAILQ_NEXT(s->selected_entry, entry);
2946 else
2947 entry = TAILQ_NEXT(s->matched_entry, entry);
2948 } else {
2949 if (matched_idx < selected_idx)
2950 entry = TAILQ_PREV(s->selected_entry,
2951 commit_queue_head, entry);
2952 else
2953 entry = TAILQ_PREV(s->matched_entry,
2954 commit_queue_head, entry);
2956 } else {
2957 entry = s->selected_entry;
2960 while (1) {
2961 int have_match = 0;
2963 if (entry == NULL) {
2964 if (s->thread_args.log_complete ||
2965 view->searching == TOG_SEARCH_BACKWARD) {
2966 view->search_next_done =
2967 (s->matched_entry == NULL ?
2968 TOG_SEARCH_HAVE_NONE : TOG_SEARCH_NO_MORE);
2969 s->search_entry = NULL;
2970 return NULL;
2973 * Poke the log thread for more commits and return,
2974 * allowing the main loop to make progress. Search
2975 * will resume at s->search_entry once we come back.
2977 s->thread_args.commits_needed++;
2978 return trigger_log_thread(view, 0);
2981 err = match_commit(&have_match, entry->id, entry->commit,
2982 &view->regex);
2983 if (err)
2984 break;
2985 if (have_match) {
2986 view->search_next_done = TOG_SEARCH_HAVE_MORE;
2987 s->matched_entry = entry;
2988 break;
2991 s->search_entry = entry;
2992 if (view->searching == TOG_SEARCH_FORWARD)
2993 entry = TAILQ_NEXT(entry, entry);
2994 else
2995 entry = TAILQ_PREV(entry, commit_queue_head, entry);
2998 if (s->matched_entry) {
2999 int cur = s->selected_entry->idx;
3000 while (cur < s->matched_entry->idx) {
3001 err = input_log_view(NULL, view, KEY_DOWN);
3002 if (err)
3003 return err;
3004 cur++;
3006 while (cur > s->matched_entry->idx) {
3007 err = input_log_view(NULL, view, KEY_UP);
3008 if (err)
3009 return err;
3010 cur--;
3014 s->search_entry = NULL;
3016 return NULL;
3019 static const struct got_error *
3020 open_log_view(struct tog_view *view, struct got_object_id *start_id,
3021 struct got_repository *repo, const char *head_ref_name,
3022 const char *in_repo_path, int log_branches)
3024 const struct got_error *err = NULL;
3025 struct tog_log_view_state *s = &view->state.log;
3026 struct got_repository *thread_repo = NULL;
3027 struct got_commit_graph *thread_graph = NULL;
3028 int errcode;
3030 if (in_repo_path != s->in_repo_path) {
3031 free(s->in_repo_path);
3032 s->in_repo_path = strdup(in_repo_path);
3033 if (s->in_repo_path == NULL)
3034 return got_error_from_errno("strdup");
3037 /* The commit queue only contains commits being displayed. */
3038 TAILQ_INIT(&s->commits.head);
3039 s->commits.ncommits = 0;
3041 s->repo = repo;
3042 if (head_ref_name) {
3043 s->head_ref_name = strdup(head_ref_name);
3044 if (s->head_ref_name == NULL) {
3045 err = got_error_from_errno("strdup");
3046 goto done;
3049 s->start_id = got_object_id_dup(start_id);
3050 if (s->start_id == NULL) {
3051 err = got_error_from_errno("got_object_id_dup");
3052 goto done;
3054 s->log_branches = log_branches;
3056 STAILQ_INIT(&s->colors);
3057 if (has_colors() && getenv("TOG_COLORS") != NULL) {
3058 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
3059 get_color_value("TOG_COLOR_COMMIT"));
3060 if (err)
3061 goto done;
3062 err = add_color(&s->colors, "^$", TOG_COLOR_AUTHOR,
3063 get_color_value("TOG_COLOR_AUTHOR"));
3064 if (err) {
3065 free_colors(&s->colors);
3066 goto done;
3068 err = add_color(&s->colors, "^$", TOG_COLOR_DATE,
3069 get_color_value("TOG_COLOR_DATE"));
3070 if (err) {
3071 free_colors(&s->colors);
3072 goto done;
3076 view->show = show_log_view;
3077 view->input = input_log_view;
3078 view->resize = resize_log_view;
3079 view->close = close_log_view;
3080 view->search_start = search_start_log_view;
3081 view->search_next = search_next_log_view;
3083 if (s->thread_args.pack_fds == NULL) {
3084 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3085 if (err)
3086 goto done;
3088 err = got_repo_open(&thread_repo, got_repo_get_path(repo), NULL,
3089 s->thread_args.pack_fds);
3090 if (err)
3091 goto done;
3092 err = got_commit_graph_open(&thread_graph, s->in_repo_path,
3093 !s->log_branches);
3094 if (err)
3095 goto done;
3096 err = got_commit_graph_iter_start(thread_graph, s->start_id,
3097 s->repo, NULL, NULL);
3098 if (err)
3099 goto done;
3101 errcode = pthread_cond_init(&s->thread_args.need_commits, NULL);
3102 if (errcode) {
3103 err = got_error_set_errno(errcode, "pthread_cond_init");
3104 goto done;
3106 errcode = pthread_cond_init(&s->thread_args.commit_loaded, NULL);
3107 if (errcode) {
3108 err = got_error_set_errno(errcode, "pthread_cond_init");
3109 goto done;
3112 s->thread_args.commits_needed = view->nlines;
3113 s->thread_args.graph = thread_graph;
3114 s->thread_args.commits = &s->commits;
3115 s->thread_args.in_repo_path = s->in_repo_path;
3116 s->thread_args.start_id = s->start_id;
3117 s->thread_args.repo = thread_repo;
3118 s->thread_args.log_complete = 0;
3119 s->thread_args.quit = &s->quit;
3120 s->thread_args.first_displayed_entry = &s->first_displayed_entry;
3121 s->thread_args.selected_entry = &s->selected_entry;
3122 s->thread_args.searching = &view->searching;
3123 s->thread_args.search_next_done = &view->search_next_done;
3124 s->thread_args.regex = &view->regex;
3125 done:
3126 if (err)
3127 close_log_view(view);
3128 return err;
3131 static const struct got_error *
3132 show_log_view(struct tog_view *view)
3134 const struct got_error *err;
3135 struct tog_log_view_state *s = &view->state.log;
3137 if (s->thread == 0) { //NULL) {
3138 int errcode = pthread_create(&s->thread, NULL, log_thread,
3139 &s->thread_args);
3140 if (errcode)
3141 return got_error_set_errno(errcode, "pthread_create");
3142 if (s->thread_args.commits_needed > 0) {
3143 err = trigger_log_thread(view, 1);
3144 if (err)
3145 return err;
3149 return draw_commits(view);
3152 static void
3153 log_move_cursor_up(struct tog_view *view, int page, int home)
3155 struct tog_log_view_state *s = &view->state.log;
3157 if (s->selected_entry->idx == 0)
3158 view->count = 0;
3159 if (s->first_displayed_entry == NULL)
3160 return;
3162 if ((page && TAILQ_FIRST(&s->commits.head) == s->first_displayed_entry)
3163 || home)
3164 s->selected = home ? 0 : MAX(0, s->selected - page - 1);
3166 if (!page && !home && s->selected > 0)
3167 --s->selected;
3168 else
3169 log_scroll_up(s, home ? s->commits.ncommits : MAX(page, 1));
3171 select_commit(s);
3172 return;
3175 static const struct got_error *
3176 log_move_cursor_down(struct tog_view *view, int page)
3178 struct tog_log_view_state *s = &view->state.log;
3179 const struct got_error *err = NULL;
3180 int eos = view->nlines - 2;
3182 if (s->thread_args.log_complete &&
3183 s->selected_entry->idx >= s->commits.ncommits - 1)
3184 return NULL;
3186 if (view_is_hsplit_top(view))
3187 --eos; /* border consumes the last line */
3189 if (!page) {
3190 if (s->selected < MIN(eos, s->commits.ncommits - 1))
3191 ++s->selected;
3192 else
3193 err = log_scroll_down(view, 1);
3194 } else if (s->thread_args.load_all && s->thread_args.log_complete) {
3195 struct commit_queue_entry *entry;
3196 int n;
3198 s->selected = 0;
3199 entry = TAILQ_LAST(&s->commits.head, commit_queue_head);
3200 s->last_displayed_entry = entry;
3201 for (n = 0; n <= eos; n++) {
3202 if (entry == NULL)
3203 break;
3204 s->first_displayed_entry = entry;
3205 entry = TAILQ_PREV(entry, commit_queue_head, entry);
3207 if (n > 0)
3208 s->selected = n - 1;
3209 } else {
3210 if (s->last_displayed_entry->idx == s->commits.ncommits - 1 &&
3211 s->thread_args.log_complete)
3212 s->selected += MIN(page,
3213 s->commits.ncommits - s->selected_entry->idx - 1);
3214 else
3215 err = log_scroll_down(view, page);
3217 if (err)
3218 return err;
3221 * We might necessarily overshoot in horizontal
3222 * splits; if so, select the last displayed commit.
3224 if (s->first_displayed_entry && s->last_displayed_entry) {
3225 s->selected = MIN(s->selected,
3226 s->last_displayed_entry->idx -
3227 s->first_displayed_entry->idx);
3230 select_commit(s);
3232 if (s->thread_args.log_complete &&
3233 s->selected_entry->idx == s->commits.ncommits - 1)
3234 view->count = 0;
3236 return NULL;
3239 static void
3240 view_get_split(struct tog_view *view, int *y, int *x)
3242 *x = 0;
3243 *y = 0;
3245 if (view->mode == TOG_VIEW_SPLIT_HRZN) {
3246 if (view->child && view->child->resized_y)
3247 *y = view->child->resized_y;
3248 else if (view->resized_y)
3249 *y = view->resized_y;
3250 else
3251 *y = view_split_begin_y(view->lines);
3252 } else if (view->mode == TOG_VIEW_SPLIT_VERT) {
3253 if (view->child && view->child->resized_x)
3254 *x = view->child->resized_x;
3255 else if (view->resized_x)
3256 *x = view->resized_x;
3257 else
3258 *x = view_split_begin_x(view->begin_x);
3262 /* Split view horizontally at y and offset view->state->selected line. */
3263 static const struct got_error *
3264 view_init_hsplit(struct tog_view *view, int y)
3266 const struct got_error *err = NULL;
3268 view->nlines = y;
3269 view->ncols = COLS;
3270 err = view_resize(view);
3271 if (err)
3272 return err;
3274 err = offset_selection_down(view);
3276 return err;
3279 static const struct got_error *
3280 log_goto_line(struct tog_view *view, int nlines)
3282 const struct got_error *err = NULL;
3283 struct tog_log_view_state *s = &view->state.log;
3284 int g, idx = s->selected_entry->idx;
3286 if (s->first_displayed_entry == NULL || s->last_displayed_entry == NULL)
3287 return NULL;
3289 g = view->gline;
3290 view->gline = 0;
3292 if (g >= s->first_displayed_entry->idx + 1 &&
3293 g <= s->last_displayed_entry->idx + 1 &&
3294 g - s->first_displayed_entry->idx - 1 < nlines) {
3295 s->selected = g - s->first_displayed_entry->idx - 1;
3296 select_commit(s);
3297 return NULL;
3300 if (idx + 1 < g) {
3301 err = log_move_cursor_down(view, g - idx - 1);
3302 if (!err && g > s->selected_entry->idx + 1)
3303 err = log_move_cursor_down(view,
3304 g - s->first_displayed_entry->idx - 1);
3305 if (err)
3306 return err;
3307 } else if (idx + 1 > g)
3308 log_move_cursor_up(view, idx - g + 1, 0);
3310 if (g < nlines && s->first_displayed_entry->idx == 0)
3311 s->selected = g - 1;
3313 select_commit(s);
3314 return NULL;
3318 static const struct got_error *
3319 input_log_view(struct tog_view **new_view, struct tog_view *view, int ch)
3321 const struct got_error *err = NULL;
3322 struct tog_log_view_state *s = &view->state.log;
3323 int eos, nscroll;
3325 if (s->thread_args.load_all) {
3326 if (ch == CTRL('g') || ch == KEY_BACKSPACE)
3327 s->thread_args.load_all = 0;
3328 else if (s->thread_args.log_complete) {
3329 err = log_move_cursor_down(view, s->commits.ncommits);
3330 s->thread_args.load_all = 0;
3332 if (err)
3333 return err;
3336 eos = nscroll = view->nlines - 1;
3337 if (view_is_hsplit_top(view))
3338 --eos; /* border */
3340 if (view->gline)
3341 return log_goto_line(view, eos);
3343 switch (ch) {
3344 case 'q':
3345 s->quit = 1;
3346 break;
3347 case '0':
3348 view->x = 0;
3349 break;
3350 case '$':
3351 view->x = MAX(view->maxx - view->ncols / 2, 0);
3352 view->count = 0;
3353 break;
3354 case KEY_RIGHT:
3355 case 'l':
3356 if (view->x + view->ncols / 2 < view->maxx)
3357 view->x += 2; /* move two columns right */
3358 else
3359 view->count = 0;
3360 break;
3361 case KEY_LEFT:
3362 case 'h':
3363 view->x -= MIN(view->x, 2); /* move two columns back */
3364 if (view->x <= 0)
3365 view->count = 0;
3366 break;
3367 case 'k':
3368 case KEY_UP:
3369 case '<':
3370 case ',':
3371 case CTRL('p'):
3372 log_move_cursor_up(view, 0, 0);
3373 break;
3374 case 'g':
3375 case KEY_HOME:
3376 log_move_cursor_up(view, 0, 1);
3377 view->count = 0;
3378 break;
3379 case CTRL('u'):
3380 case 'u':
3381 nscroll /= 2;
3382 /* FALL THROUGH */
3383 case KEY_PPAGE:
3384 case CTRL('b'):
3385 case 'b':
3386 log_move_cursor_up(view, nscroll, 0);
3387 break;
3388 case 'j':
3389 case KEY_DOWN:
3390 case '>':
3391 case '.':
3392 case CTRL('n'):
3393 err = log_move_cursor_down(view, 0);
3394 break;
3395 case '@':
3396 s->use_committer = !s->use_committer;
3397 break;
3398 case 'G':
3399 case KEY_END: {
3400 /* We don't know yet how many commits, so we're forced to
3401 * traverse them all. */
3402 view->count = 0;
3403 s->thread_args.load_all = 1;
3404 if (!s->thread_args.log_complete)
3405 return trigger_log_thread(view, 0);
3406 err = log_move_cursor_down(view, s->commits.ncommits);
3407 s->thread_args.load_all = 0;
3408 break;
3410 case CTRL('d'):
3411 case 'd':
3412 nscroll /= 2;
3413 /* FALL THROUGH */
3414 case KEY_NPAGE:
3415 case CTRL('f'):
3416 case 'f':
3417 case ' ':
3418 err = log_move_cursor_down(view, nscroll);
3419 break;
3420 case KEY_RESIZE:
3421 if (s->selected > view->nlines - 2)
3422 s->selected = view->nlines - 2;
3423 if (s->selected > s->commits.ncommits - 1)
3424 s->selected = s->commits.ncommits - 1;
3425 select_commit(s);
3426 if (s->commits.ncommits < view->nlines - 1 &&
3427 !s->thread_args.log_complete) {
3428 s->thread_args.commits_needed += (view->nlines - 1) -
3429 s->commits.ncommits;
3430 err = trigger_log_thread(view, 1);
3432 break;
3433 case KEY_ENTER:
3434 case '\r':
3435 view->count = 0;
3436 if (s->selected_entry == NULL)
3437 break;
3438 err = view_request_new(new_view, view, TOG_VIEW_DIFF);
3439 break;
3440 case 'T':
3441 view->count = 0;
3442 if (s->selected_entry == NULL)
3443 break;
3444 err = view_request_new(new_view, view, TOG_VIEW_TREE);
3445 break;
3446 case KEY_BACKSPACE:
3447 case CTRL('l'):
3448 case 'B':
3449 view->count = 0;
3450 if (ch == KEY_BACKSPACE &&
3451 got_path_is_root_dir(s->in_repo_path))
3452 break;
3453 err = stop_log_thread(s);
3454 if (err)
3455 return err;
3456 if (ch == KEY_BACKSPACE) {
3457 char *parent_path;
3458 err = got_path_dirname(&parent_path, s->in_repo_path);
3459 if (err)
3460 return err;
3461 free(s->in_repo_path);
3462 s->in_repo_path = parent_path;
3463 s->thread_args.in_repo_path = s->in_repo_path;
3464 } else if (ch == CTRL('l')) {
3465 struct got_object_id *start_id;
3466 err = got_repo_match_object_id(&start_id, NULL,
3467 s->head_ref_name ? s->head_ref_name : GOT_REF_HEAD,
3468 GOT_OBJ_TYPE_COMMIT, &tog_refs, s->repo);
3469 if (err)
3470 return err;
3471 free(s->start_id);
3472 s->start_id = start_id;
3473 s->thread_args.start_id = s->start_id;
3474 } else /* 'B' */
3475 s->log_branches = !s->log_branches;
3477 if (s->thread_args.pack_fds == NULL) {
3478 err = got_repo_pack_fds_open(&s->thread_args.pack_fds);
3479 if (err)
3480 return err;
3482 err = got_repo_open(&s->thread_args.repo,
3483 got_repo_get_path(s->repo), NULL,
3484 s->thread_args.pack_fds);
3485 if (err)
3486 return err;
3487 tog_free_refs();
3488 err = tog_load_refs(s->repo, 0);
3489 if (err)
3490 return err;
3491 err = got_commit_graph_open(&s->thread_args.graph,
3492 s->in_repo_path, !s->log_branches);
3493 if (err)
3494 return err;
3495 err = got_commit_graph_iter_start(s->thread_args.graph,
3496 s->start_id, s->repo, NULL, NULL);
3497 if (err)
3498 return err;
3499 free_commits(&s->commits);
3500 s->first_displayed_entry = NULL;
3501 s->last_displayed_entry = NULL;
3502 s->selected_entry = NULL;
3503 s->selected = 0;
3504 s->thread_args.log_complete = 0;
3505 s->quit = 0;
3506 s->thread_args.commits_needed = view->lines;
3507 s->matched_entry = NULL;
3508 s->search_entry = NULL;
3509 view->offset = 0;
3510 break;
3511 case 'R':
3512 view->count = 0;
3513 err = view_request_new(new_view, view, TOG_VIEW_REF);
3514 break;
3515 default:
3516 view->count = 0;
3517 break;
3520 return err;
3523 static const struct got_error *
3524 apply_unveil(const char *repo_path, const char *worktree_path)
3526 const struct got_error *error;
3528 #ifdef PROFILE
3529 if (unveil("gmon.out", "rwc") != 0)
3530 return got_error_from_errno2("unveil", "gmon.out");
3531 #endif
3532 if (repo_path && unveil(repo_path, "r") != 0)
3533 return got_error_from_errno2("unveil", repo_path);
3535 if (worktree_path && unveil(worktree_path, "rwc") != 0)
3536 return got_error_from_errno2("unveil", worktree_path);
3538 if (unveil(GOT_TMPDIR_STR, "rwc") != 0)
3539 return got_error_from_errno2("unveil", GOT_TMPDIR_STR);
3541 error = got_privsep_unveil_exec_helpers();
3542 if (error != NULL)
3543 return error;
3545 if (unveil(NULL, NULL) != 0)
3546 return got_error_from_errno("unveil");
3548 return NULL;
3551 static void
3552 init_curses(void)
3555 * Override default signal handlers before starting ncurses.
3556 * This should prevent ncurses from installing its own
3557 * broken cleanup() signal handler.
3559 signal(SIGWINCH, tog_sigwinch);
3560 signal(SIGPIPE, tog_sigpipe);
3561 signal(SIGCONT, tog_sigcont);
3562 signal(SIGINT, tog_sigint);
3563 signal(SIGTERM, tog_sigterm);
3565 initscr();
3566 cbreak();
3567 halfdelay(1); /* Do fast refresh while initial view is loading. */
3568 noecho();
3569 nonl();
3570 intrflush(stdscr, FALSE);
3571 keypad(stdscr, TRUE);
3572 curs_set(0);
3573 if (getenv("TOG_COLORS") != NULL) {
3574 start_color();
3575 use_default_colors();
3579 static const struct got_error *
3580 get_in_repo_path_from_argv0(char **in_repo_path, int argc, char *argv[],
3581 struct got_repository *repo, struct got_worktree *worktree)
3583 const struct got_error *err = NULL;
3585 if (argc == 0) {
3586 *in_repo_path = strdup("/");
3587 if (*in_repo_path == NULL)
3588 return got_error_from_errno("strdup");
3589 return NULL;
3592 if (worktree) {
3593 const char *prefix = got_worktree_get_path_prefix(worktree);
3594 char *p;
3596 err = got_worktree_resolve_path(&p, worktree, argv[0]);
3597 if (err)
3598 return err;
3599 if (asprintf(in_repo_path, "%s%s%s", prefix,
3600 (p[0] != '\0' && !got_path_is_root_dir(prefix)) ? "/" : "",
3601 p) == -1) {
3602 err = got_error_from_errno("asprintf");
3603 *in_repo_path = NULL;
3605 free(p);
3606 } else
3607 err = got_repo_map_path(in_repo_path, repo, argv[0]);
3609 return err;
3612 static const struct got_error *
3613 cmd_log(int argc, char *argv[])
3615 const struct got_error *error;
3616 struct got_repository *repo = NULL;
3617 struct got_worktree *worktree = NULL;
3618 struct got_object_id *start_id = NULL;
3619 char *in_repo_path = NULL, *repo_path = NULL, *cwd = NULL;
3620 char *start_commit = NULL, *label = NULL;
3621 struct got_reference *ref = NULL;
3622 const char *head_ref_name = NULL;
3623 int ch, log_branches = 0;
3624 struct tog_view *view;
3625 int *pack_fds = NULL;
3627 while ((ch = getopt(argc, argv, "bc:r:")) != -1) {
3628 switch (ch) {
3629 case 'b':
3630 log_branches = 1;
3631 break;
3632 case 'c':
3633 start_commit = optarg;
3634 break;
3635 case 'r':
3636 repo_path = realpath(optarg, NULL);
3637 if (repo_path == NULL)
3638 return got_error_from_errno2("realpath",
3639 optarg);
3640 break;
3641 default:
3642 usage_log();
3643 /* NOTREACHED */
3647 argc -= optind;
3648 argv += optind;
3650 if (argc > 1)
3651 usage_log();
3653 error = got_repo_pack_fds_open(&pack_fds);
3654 if (error != NULL)
3655 goto done;
3657 if (repo_path == NULL) {
3658 cwd = getcwd(NULL, 0);
3659 if (cwd == NULL)
3660 return got_error_from_errno("getcwd");
3661 error = got_worktree_open(&worktree, cwd);
3662 if (error && error->code != GOT_ERR_NOT_WORKTREE)
3663 goto done;
3664 if (worktree)
3665 repo_path =
3666 strdup(got_worktree_get_repo_path(worktree));
3667 else
3668 repo_path = strdup(cwd);
3669 if (repo_path == NULL) {
3670 error = got_error_from_errno("strdup");
3671 goto done;
3675 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
3676 if (error != NULL)
3677 goto done;
3679 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
3680 repo, worktree);
3681 if (error)
3682 goto done;
3684 init_curses();
3686 error = apply_unveil(got_repo_get_path(repo),
3687 worktree ? got_worktree_get_root_path(worktree) : NULL);
3688 if (error)
3689 goto done;
3691 /* already loaded by tog_log_with_path()? */
3692 if (TAILQ_EMPTY(&tog_refs)) {
3693 error = tog_load_refs(repo, 0);
3694 if (error)
3695 goto done;
3698 if (start_commit == NULL) {
3699 error = got_repo_match_object_id(&start_id, &label,
3700 worktree ? got_worktree_get_head_ref_name(worktree) :
3701 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3702 if (error)
3703 goto done;
3704 head_ref_name = label;
3705 } else {
3706 error = got_ref_open(&ref, repo, start_commit, 0);
3707 if (error == NULL)
3708 head_ref_name = got_ref_get_name(ref);
3709 else if (error->code != GOT_ERR_NOT_REF)
3710 goto done;
3711 error = got_repo_match_object_id(&start_id, NULL,
3712 start_commit, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
3713 if (error)
3714 goto done;
3717 view = view_open(0, 0, 0, 0, TOG_VIEW_LOG);
3718 if (view == NULL) {
3719 error = got_error_from_errno("view_open");
3720 goto done;
3722 error = open_log_view(view, start_id, repo, head_ref_name,
3723 in_repo_path, log_branches);
3724 if (error)
3725 goto done;
3726 if (worktree) {
3727 /* Release work tree lock. */
3728 got_worktree_close(worktree);
3729 worktree = NULL;
3731 error = view_loop(view);
3732 done:
3733 free(in_repo_path);
3734 free(repo_path);
3735 free(cwd);
3736 free(start_id);
3737 free(label);
3738 if (ref)
3739 got_ref_close(ref);
3740 if (repo) {
3741 const struct got_error *close_err = got_repo_close(repo);
3742 if (error == NULL)
3743 error = close_err;
3745 if (worktree)
3746 got_worktree_close(worktree);
3747 if (pack_fds) {
3748 const struct got_error *pack_err =
3749 got_repo_pack_fds_close(pack_fds);
3750 if (error == NULL)
3751 error = pack_err;
3753 tog_free_refs();
3754 return error;
3757 __dead static void
3758 usage_diff(void)
3760 endwin();
3761 fprintf(stderr, "usage: %s diff [-aw] [-C number] [-r repository-path] "
3762 "object1 object2\n", getprogname());
3763 exit(1);
3766 static int
3767 match_line(const char *line, regex_t *regex, size_t nmatch,
3768 regmatch_t *regmatch)
3770 return regexec(regex, line, nmatch, regmatch, 0) == 0;
3773 static struct tog_color *
3774 match_color(struct tog_colors *colors, const char *line)
3776 struct tog_color *tc = NULL;
3778 STAILQ_FOREACH(tc, colors, entry) {
3779 if (match_line(line, &tc->regex, 0, NULL))
3780 return tc;
3783 return NULL;
3786 static const struct got_error *
3787 add_matched_line(int *wtotal, const char *line, int wlimit, int col_tab_align,
3788 WINDOW *window, int skipcol, regmatch_t *regmatch)
3790 const struct got_error *err = NULL;
3791 char *exstr = NULL;
3792 wchar_t *wline = NULL;
3793 int rme, rms, n, width, scrollx;
3794 int width0 = 0, width1 = 0, width2 = 0;
3795 char *seg0 = NULL, *seg1 = NULL, *seg2 = NULL;
3797 *wtotal = 0;
3799 rms = regmatch->rm_so;
3800 rme = regmatch->rm_eo;
3802 err = expand_tab(&exstr, line);
3803 if (err)
3804 return err;
3806 /* Split the line into 3 segments, according to match offsets. */
3807 seg0 = strndup(exstr, rms);
3808 if (seg0 == NULL) {
3809 err = got_error_from_errno("strndup");
3810 goto done;
3812 seg1 = strndup(exstr + rms, rme - rms);
3813 if (seg1 == NULL) {
3814 err = got_error_from_errno("strndup");
3815 goto done;
3817 seg2 = strdup(exstr + rme);
3818 if (seg2 == NULL) {
3819 err = got_error_from_errno("strndup");
3820 goto done;
3823 /* draw up to matched token if we haven't scrolled past it */
3824 err = format_line(&wline, &width0, NULL, seg0, 0, wlimit,
3825 col_tab_align, 1);
3826 if (err)
3827 goto done;
3828 n = MAX(width0 - skipcol, 0);
3829 if (n) {
3830 free(wline);
3831 err = format_line(&wline, &width, &scrollx, seg0, skipcol,
3832 wlimit, col_tab_align, 1);
3833 if (err)
3834 goto done;
3835 waddwstr(window, &wline[scrollx]);
3836 wlimit -= width;
3837 *wtotal += width;
3840 if (wlimit > 0) {
3841 int i = 0, w = 0;
3842 size_t wlen;
3844 free(wline);
3845 err = format_line(&wline, &width1, NULL, seg1, 0, wlimit,
3846 col_tab_align, 1);
3847 if (err)
3848 goto done;
3849 wlen = wcslen(wline);
3850 while (i < wlen) {
3851 width = wcwidth(wline[i]);
3852 if (width == -1) {
3853 /* should not happen, tabs are expanded */
3854 err = got_error(GOT_ERR_RANGE);
3855 goto done;
3857 if (width0 + w + width > skipcol)
3858 break;
3859 w += width;
3860 i++;
3862 /* draw (visible part of) matched token (if scrolled into it) */
3863 if (width1 - w > 0) {
3864 wattron(window, A_STANDOUT);
3865 waddwstr(window, &wline[i]);
3866 wattroff(window, A_STANDOUT);
3867 wlimit -= (width1 - w);
3868 *wtotal += (width1 - w);
3872 if (wlimit > 0) { /* draw rest of line */
3873 free(wline);
3874 if (skipcol > width0 + width1) {
3875 err = format_line(&wline, &width2, &scrollx, seg2,
3876 skipcol - (width0 + width1), wlimit,
3877 col_tab_align, 1);
3878 if (err)
3879 goto done;
3880 waddwstr(window, &wline[scrollx]);
3881 } else {
3882 err = format_line(&wline, &width2, NULL, seg2, 0,
3883 wlimit, col_tab_align, 1);
3884 if (err)
3885 goto done;
3886 waddwstr(window, wline);
3888 *wtotal += width2;
3890 done:
3891 free(wline);
3892 free(exstr);
3893 free(seg0);
3894 free(seg1);
3895 free(seg2);
3896 return err;
3899 static int
3900 gotoline(struct tog_view *view, int *lineno, int *nprinted)
3902 FILE *f = NULL;
3903 int *eof, *first, *selected;
3905 if (view->type == TOG_VIEW_DIFF) {
3906 struct tog_diff_view_state *s = &view->state.diff;
3908 first = &s->first_displayed_line;
3909 selected = first;
3910 eof = &s->eof;
3911 f = s->f;
3912 } else if (view->type == TOG_VIEW_BLAME) {
3913 struct tog_blame_view_state *s = &view->state.blame;
3915 first = &s->first_displayed_line;
3916 selected = &s->selected_line;
3917 eof = &s->eof;
3918 f = s->blame.f;
3919 } else
3920 return 0;
3922 /* Center gline in the middle of the page like vi(1). */
3923 if (*lineno < view->gline - (view->nlines - 3) / 2)
3924 return 0;
3925 if (*first != 1 && (*lineno > view->gline - (view->nlines - 3) / 2)) {
3926 rewind(f);
3927 *eof = 0;
3928 *first = 1;
3929 *lineno = 0;
3930 *nprinted = 0;
3931 return 0;
3934 *selected = view->gline <= (view->nlines - 3) / 2 ?
3935 view->gline : (view->nlines - 3) / 2 + 1;
3936 view->gline = 0;
3938 return 1;
3941 static const struct got_error *
3942 draw_file(struct tog_view *view, const char *header)
3944 struct tog_diff_view_state *s = &view->state.diff;
3945 regmatch_t *regmatch = &view->regmatch;
3946 const struct got_error *err;
3947 int nprinted = 0;
3948 char *line;
3949 size_t linesize = 0;
3950 ssize_t linelen;
3951 wchar_t *wline;
3952 int width;
3953 int max_lines = view->nlines;
3954 int nlines = s->nlines;
3955 off_t line_offset;
3957 s->lineno = s->first_displayed_line - 1;
3958 line_offset = s->lines[s->first_displayed_line - 1].offset;
3959 if (fseeko(s->f, line_offset, SEEK_SET) == -1)
3960 return got_error_from_errno("fseek");
3962 werase(view->window);
3964 if (view->gline > s->nlines - 1)
3965 view->gline = s->nlines - 1;
3967 if (header) {
3968 int ln = view->gline ? view->gline <= (view->nlines - 3) / 2 ?
3969 1 : view->gline - (view->nlines - 3) / 2 :
3970 s->lineno + s->selected_line;
3972 if (asprintf(&line, "[%d/%d] %s", ln, nlines, header) == -1)
3973 return got_error_from_errno("asprintf");
3974 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
3975 0, 0);
3976 free(line);
3977 if (err)
3978 return err;
3980 if (view_needs_focus_indication(view))
3981 wstandout(view->window);
3982 waddwstr(view->window, wline);
3983 free(wline);
3984 wline = NULL;
3985 if (view_needs_focus_indication(view))
3986 wstandend(view->window);
3987 if (width <= view->ncols - 1)
3988 waddch(view->window, '\n');
3990 if (max_lines <= 1)
3991 return NULL;
3992 max_lines--;
3995 s->eof = 0;
3996 view->maxx = 0;
3997 line = NULL;
3998 while (max_lines > 0 && nprinted < max_lines) {
3999 enum got_diff_line_type linetype;
4000 attr_t attr = 0;
4002 linelen = getline(&line, &linesize, s->f);
4003 if (linelen == -1) {
4004 if (feof(s->f)) {
4005 s->eof = 1;
4006 break;
4008 free(line);
4009 return got_ferror(s->f, GOT_ERR_IO);
4012 if (++s->lineno < s->first_displayed_line)
4013 continue;
4014 if (view->gline && !gotoline(view, &s->lineno, &nprinted))
4015 continue;
4016 if (s->lineno == view->hiline)
4017 attr = A_STANDOUT;
4019 /* Set view->maxx based on full line length. */
4020 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 0,
4021 view->x ? 1 : 0);
4022 if (err) {
4023 free(line);
4024 return err;
4026 view->maxx = MAX(view->maxx, width);
4027 free(wline);
4028 wline = NULL;
4030 linetype = s->lines[s->lineno].type;
4031 if (linetype > GOT_DIFF_LINE_LOGMSG &&
4032 linetype < GOT_DIFF_LINE_CONTEXT)
4033 attr |= COLOR_PAIR(linetype);
4034 if (attr)
4035 wattron(view->window, attr);
4036 if (s->first_displayed_line + nprinted == s->matched_line &&
4037 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
4038 err = add_matched_line(&width, line, view->ncols, 0,
4039 view->window, view->x, regmatch);
4040 if (err) {
4041 free(line);
4042 return err;
4044 } else {
4045 int skip;
4046 err = format_line(&wline, &width, &skip, line,
4047 view->x, view->ncols, 0, view->x ? 1 : 0);
4048 if (err) {
4049 free(line);
4050 return err;
4052 waddwstr(view->window, &wline[skip]);
4053 free(wline);
4054 wline = NULL;
4056 if (s->lineno == view->hiline) {
4057 /* highlight full gline length */
4058 while (width++ < view->ncols)
4059 waddch(view->window, ' ');
4060 } else {
4061 if (width <= view->ncols - 1)
4062 waddch(view->window, '\n');
4064 if (attr)
4065 wattroff(view->window, attr);
4066 if (++nprinted == 1)
4067 s->first_displayed_line = s->lineno;
4069 free(line);
4070 if (nprinted >= 1)
4071 s->last_displayed_line = s->first_displayed_line +
4072 (nprinted - 1);
4073 else
4074 s->last_displayed_line = s->first_displayed_line;
4076 view_border(view);
4078 if (s->eof) {
4079 while (nprinted < view->nlines) {
4080 waddch(view->window, '\n');
4081 nprinted++;
4084 err = format_line(&wline, &width, NULL, TOG_EOF_STRING, 0,
4085 view->ncols, 0, 0);
4086 if (err) {
4087 return err;
4090 wstandout(view->window);
4091 waddwstr(view->window, wline);
4092 free(wline);
4093 wline = NULL;
4094 wstandend(view->window);
4097 return NULL;
4100 static char *
4101 get_datestr(time_t *time, char *datebuf)
4103 struct tm mytm, *tm;
4104 char *p, *s;
4106 tm = gmtime_r(time, &mytm);
4107 if (tm == NULL)
4108 return NULL;
4109 s = asctime_r(tm, datebuf);
4110 if (s == NULL)
4111 return NULL;
4112 p = strchr(s, '\n');
4113 if (p)
4114 *p = '\0';
4115 return s;
4118 static const struct got_error *
4119 get_changed_paths(struct got_pathlist_head *paths,
4120 struct got_commit_object *commit, struct got_repository *repo)
4122 const struct got_error *err = NULL;
4123 struct got_object_id *tree_id1 = NULL, *tree_id2 = NULL;
4124 struct got_tree_object *tree1 = NULL, *tree2 = NULL;
4125 struct got_object_qid *qid;
4127 qid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
4128 if (qid != NULL) {
4129 struct got_commit_object *pcommit;
4130 err = got_object_open_as_commit(&pcommit, repo,
4131 &qid->id);
4132 if (err)
4133 return err;
4135 tree_id1 = got_object_id_dup(
4136 got_object_commit_get_tree_id(pcommit));
4137 if (tree_id1 == NULL) {
4138 got_object_commit_close(pcommit);
4139 return got_error_from_errno("got_object_id_dup");
4141 got_object_commit_close(pcommit);
4145 if (tree_id1) {
4146 err = got_object_open_as_tree(&tree1, repo, tree_id1);
4147 if (err)
4148 goto done;
4151 tree_id2 = got_object_commit_get_tree_id(commit);
4152 err = got_object_open_as_tree(&tree2, repo, tree_id2);
4153 if (err)
4154 goto done;
4156 err = got_diff_tree(tree1, tree2, NULL, NULL, -1, -1, "", "", repo,
4157 got_diff_tree_collect_changed_paths, paths, 0);
4158 done:
4159 if (tree1)
4160 got_object_tree_close(tree1);
4161 if (tree2)
4162 got_object_tree_close(tree2);
4163 free(tree_id1);
4164 return err;
4167 static const struct got_error *
4168 add_line_metadata(struct got_diff_line **lines, size_t *nlines,
4169 off_t off, uint8_t type)
4171 struct got_diff_line *p;
4173 p = reallocarray(*lines, *nlines + 1, sizeof(**lines));
4174 if (p == NULL)
4175 return got_error_from_errno("reallocarray");
4176 *lines = p;
4177 (*lines)[*nlines].offset = off;
4178 (*lines)[*nlines].type = type;
4179 (*nlines)++;
4181 return NULL;
4184 static const struct got_error *
4185 write_commit_info(struct got_diff_line **lines, size_t *nlines,
4186 struct got_object_id *commit_id, struct got_reflist_head *refs,
4187 struct got_repository *repo, FILE *outfile)
4189 const struct got_error *err = NULL;
4190 char datebuf[26], *datestr;
4191 struct got_commit_object *commit;
4192 char *id_str = NULL, *logmsg = NULL, *s = NULL, *line;
4193 time_t committer_time;
4194 const char *author, *committer;
4195 char *refs_str = NULL;
4196 struct got_pathlist_head changed_paths;
4197 struct got_pathlist_entry *pe;
4198 off_t outoff = 0;
4199 int n;
4201 TAILQ_INIT(&changed_paths);
4203 if (refs) {
4204 err = build_refs_str(&refs_str, refs, commit_id, repo);
4205 if (err)
4206 return err;
4209 err = got_object_open_as_commit(&commit, repo, commit_id);
4210 if (err)
4211 return err;
4213 err = got_object_id_str(&id_str, commit_id);
4214 if (err) {
4215 err = got_error_from_errno("got_object_id_str");
4216 goto done;
4219 err = add_line_metadata(lines, nlines, 0, GOT_DIFF_LINE_NONE);
4220 if (err)
4221 goto done;
4223 n = fprintf(outfile, "commit %s%s%s%s\n", id_str, refs_str ? " (" : "",
4224 refs_str ? refs_str : "", refs_str ? ")" : "");
4225 if (n < 0) {
4226 err = got_error_from_errno("fprintf");
4227 goto done;
4229 outoff += n;
4230 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_META);
4231 if (err)
4232 goto done;
4234 n = fprintf(outfile, "from: %s\n",
4235 got_object_commit_get_author(commit));
4236 if (n < 0) {
4237 err = got_error_from_errno("fprintf");
4238 goto done;
4240 outoff += n;
4241 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_AUTHOR);
4242 if (err)
4243 goto done;
4245 committer_time = got_object_commit_get_committer_time(commit);
4246 datestr = get_datestr(&committer_time, datebuf);
4247 if (datestr) {
4248 n = fprintf(outfile, "date: %s UTC\n", datestr);
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_DATE);
4256 if (err)
4257 goto done;
4259 author = got_object_commit_get_author(commit);
4260 committer = got_object_commit_get_committer(commit);
4261 if (strcmp(author, committer) != 0) {
4262 n = fprintf(outfile, "via: %s\n", committer);
4263 if (n < 0) {
4264 err = got_error_from_errno("fprintf");
4265 goto done;
4267 outoff += n;
4268 err = add_line_metadata(lines, nlines, outoff,
4269 GOT_DIFF_LINE_AUTHOR);
4270 if (err)
4271 goto done;
4273 if (got_object_commit_get_nparents(commit) > 1) {
4274 const struct got_object_id_queue *parent_ids;
4275 struct got_object_qid *qid;
4276 int pn = 1;
4277 parent_ids = got_object_commit_get_parent_ids(commit);
4278 STAILQ_FOREACH(qid, parent_ids, entry) {
4279 err = got_object_id_str(&id_str, &qid->id);
4280 if (err)
4281 goto done;
4282 n = fprintf(outfile, "parent %d: %s\n", pn++, id_str);
4283 if (n < 0) {
4284 err = got_error_from_errno("fprintf");
4285 goto done;
4287 outoff += n;
4288 err = add_line_metadata(lines, nlines, outoff,
4289 GOT_DIFF_LINE_META);
4290 if (err)
4291 goto done;
4292 free(id_str);
4293 id_str = NULL;
4297 err = got_object_commit_get_logmsg(&logmsg, commit);
4298 if (err)
4299 goto done;
4300 s = logmsg;
4301 while ((line = strsep(&s, "\n")) != NULL) {
4302 n = fprintf(outfile, "%s\n", line);
4303 if (n < 0) {
4304 err = got_error_from_errno("fprintf");
4305 goto done;
4307 outoff += n;
4308 err = add_line_metadata(lines, nlines, outoff,
4309 GOT_DIFF_LINE_LOGMSG);
4310 if (err)
4311 goto done;
4314 err = get_changed_paths(&changed_paths, commit, repo);
4315 if (err)
4316 goto done;
4317 TAILQ_FOREACH(pe, &changed_paths, entry) {
4318 struct got_diff_changed_path *cp = pe->data;
4319 n = fprintf(outfile, "%c %s\n", cp->status, pe->path);
4320 if (n < 0) {
4321 err = got_error_from_errno("fprintf");
4322 goto done;
4324 outoff += n;
4325 err = add_line_metadata(lines, nlines, outoff,
4326 GOT_DIFF_LINE_CHANGES);
4327 if (err)
4328 goto done;
4329 free((char *)pe->path);
4330 free(pe->data);
4333 fputc('\n', outfile);
4334 outoff++;
4335 err = add_line_metadata(lines, nlines, outoff, GOT_DIFF_LINE_NONE);
4336 done:
4337 got_pathlist_free(&changed_paths);
4338 free(id_str);
4339 free(logmsg);
4340 free(refs_str);
4341 got_object_commit_close(commit);
4342 if (err) {
4343 free(*lines);
4344 *lines = NULL;
4345 *nlines = 0;
4347 return err;
4350 static const struct got_error *
4351 create_diff(struct tog_diff_view_state *s)
4353 const struct got_error *err = NULL;
4354 FILE *f = NULL;
4355 int obj_type;
4357 free(s->lines);
4358 s->lines = malloc(sizeof(*s->lines));
4359 if (s->lines == NULL)
4360 return got_error_from_errno("malloc");
4361 s->nlines = 0;
4363 f = got_opentemp();
4364 if (f == NULL) {
4365 err = got_error_from_errno("got_opentemp");
4366 goto done;
4368 if (s->f && fclose(s->f) == EOF) {
4369 err = got_error_from_errno("fclose");
4370 goto done;
4372 s->f = f;
4374 if (s->id1)
4375 err = got_object_get_type(&obj_type, s->repo, s->id1);
4376 else
4377 err = got_object_get_type(&obj_type, s->repo, s->id2);
4378 if (err)
4379 goto done;
4381 switch (obj_type) {
4382 case GOT_OBJ_TYPE_BLOB:
4383 err = got_diff_objects_as_blobs(&s->lines, &s->nlines,
4384 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2,
4385 s->label1, s->label2, tog_diff_algo, s->diff_context,
4386 s->ignore_whitespace, s->force_text_diff, s->repo, s->f);
4387 break;
4388 case GOT_OBJ_TYPE_TREE:
4389 err = got_diff_objects_as_trees(&s->lines, &s->nlines,
4390 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL, "", "",
4391 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4392 s->force_text_diff, s->repo, s->f);
4393 break;
4394 case GOT_OBJ_TYPE_COMMIT: {
4395 const struct got_object_id_queue *parent_ids;
4396 struct got_object_qid *pid;
4397 struct got_commit_object *commit2;
4398 struct got_reflist_head *refs;
4400 err = got_object_open_as_commit(&commit2, s->repo, s->id2);
4401 if (err)
4402 goto done;
4403 refs = got_reflist_object_id_map_lookup(tog_refs_idmap, s->id2);
4404 /* Show commit info if we're diffing to a parent/root commit. */
4405 if (s->id1 == NULL) {
4406 err = write_commit_info(&s->lines, &s->nlines, s->id2,
4407 refs, s->repo, s->f);
4408 if (err)
4409 goto done;
4410 } else {
4411 parent_ids = got_object_commit_get_parent_ids(commit2);
4412 STAILQ_FOREACH(pid, parent_ids, entry) {
4413 if (got_object_id_cmp(s->id1, &pid->id) == 0) {
4414 err = write_commit_info(&s->lines,
4415 &s->nlines, s->id2, refs, s->repo,
4416 s->f);
4417 if (err)
4418 goto done;
4419 break;
4423 got_object_commit_close(commit2);
4425 err = got_diff_objects_as_commits(&s->lines, &s->nlines,
4426 s->f1, s->f2, s->fd1, s->fd2, s->id1, s->id2, NULL,
4427 tog_diff_algo, s->diff_context, s->ignore_whitespace,
4428 s->force_text_diff, s->repo, s->f);
4429 break;
4431 default:
4432 err = got_error(GOT_ERR_OBJ_TYPE);
4433 break;
4435 done:
4436 if (s->f && fflush(s->f) != 0 && err == NULL)
4437 err = got_error_from_errno("fflush");
4438 return err;
4441 static void
4442 diff_view_indicate_progress(struct tog_view *view)
4444 mvwaddstr(view->window, 0, 0, "diffing...");
4445 update_panels();
4446 doupdate();
4449 static const struct got_error *
4450 search_start_diff_view(struct tog_view *view)
4452 struct tog_diff_view_state *s = &view->state.diff;
4454 s->matched_line = 0;
4455 return NULL;
4458 static const struct got_error *
4459 search_next_diff_view(struct tog_view *view)
4461 struct tog_diff_view_state *s = &view->state.diff;
4462 const struct got_error *err = NULL;
4463 int lineno;
4464 char *line = NULL;
4465 size_t linesize = 0;
4466 ssize_t linelen;
4468 if (!view->searching) {
4469 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4470 return NULL;
4473 if (s->matched_line) {
4474 if (view->searching == TOG_SEARCH_FORWARD)
4475 lineno = s->matched_line + 1;
4476 else
4477 lineno = s->matched_line - 1;
4478 } else
4479 lineno = s->first_displayed_line;
4481 while (1) {
4482 off_t offset;
4484 if (lineno <= 0 || lineno > s->nlines) {
4485 if (s->matched_line == 0) {
4486 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4487 break;
4490 if (view->searching == TOG_SEARCH_FORWARD)
4491 lineno = 1;
4492 else
4493 lineno = s->nlines;
4496 offset = s->lines[lineno - 1].offset;
4497 if (fseeko(s->f, offset, SEEK_SET) != 0) {
4498 free(line);
4499 return got_error_from_errno("fseeko");
4501 linelen = getline(&line, &linesize, s->f);
4502 if (linelen != -1) {
4503 char *exstr;
4504 err = expand_tab(&exstr, line);
4505 if (err)
4506 break;
4507 if (match_line(exstr, &view->regex, 1,
4508 &view->regmatch)) {
4509 view->search_next_done = TOG_SEARCH_HAVE_MORE;
4510 s->matched_line = lineno;
4511 free(exstr);
4512 break;
4514 free(exstr);
4516 if (view->searching == TOG_SEARCH_FORWARD)
4517 lineno++;
4518 else
4519 lineno--;
4521 free(line);
4523 if (s->matched_line) {
4524 s->first_displayed_line = s->matched_line;
4525 s->selected_line = 1;
4528 return err;
4531 static const struct got_error *
4532 close_diff_view(struct tog_view *view)
4534 const struct got_error *err = NULL;
4535 struct tog_diff_view_state *s = &view->state.diff;
4537 free(s->id1);
4538 s->id1 = NULL;
4539 free(s->id2);
4540 s->id2 = NULL;
4541 if (s->f && fclose(s->f) == EOF)
4542 err = got_error_from_errno("fclose");
4543 s->f = NULL;
4544 if (s->f1 && fclose(s->f1) == EOF && err == NULL)
4545 err = got_error_from_errno("fclose");
4546 s->f1 = NULL;
4547 if (s->f2 && fclose(s->f2) == EOF && err == NULL)
4548 err = got_error_from_errno("fclose");
4549 s->f2 = NULL;
4550 if (s->fd1 != -1 && close(s->fd1) == -1 && err == NULL)
4551 err = got_error_from_errno("close");
4552 s->fd1 = -1;
4553 if (s->fd2 != -1 && close(s->fd2) == -1 && err == NULL)
4554 err = got_error_from_errno("close");
4555 s->fd2 = -1;
4556 free(s->lines);
4557 s->lines = NULL;
4558 s->nlines = 0;
4559 return err;
4562 static const struct got_error *
4563 open_diff_view(struct tog_view *view, struct got_object_id *id1,
4564 struct got_object_id *id2, const char *label1, const char *label2,
4565 int diff_context, int ignore_whitespace, int force_text_diff,
4566 struct tog_view *parent_view, struct got_repository *repo)
4568 const struct got_error *err;
4569 struct tog_diff_view_state *s = &view->state.diff;
4571 memset(s, 0, sizeof(*s));
4572 s->fd1 = -1;
4573 s->fd2 = -1;
4575 if (id1 != NULL && id2 != NULL) {
4576 int type1, type2;
4577 err = got_object_get_type(&type1, repo, id1);
4578 if (err)
4579 return err;
4580 err = got_object_get_type(&type2, repo, id2);
4581 if (err)
4582 return err;
4584 if (type1 != type2)
4585 return got_error(GOT_ERR_OBJ_TYPE);
4587 s->first_displayed_line = 1;
4588 s->last_displayed_line = view->nlines;
4589 s->selected_line = 1;
4590 s->repo = repo;
4591 s->id1 = id1;
4592 s->id2 = id2;
4593 s->label1 = label1;
4594 s->label2 = label2;
4596 if (id1) {
4597 s->id1 = got_object_id_dup(id1);
4598 if (s->id1 == NULL)
4599 return got_error_from_errno("got_object_id_dup");
4600 } else
4601 s->id1 = NULL;
4603 s->id2 = got_object_id_dup(id2);
4604 if (s->id2 == NULL) {
4605 err = got_error_from_errno("got_object_id_dup");
4606 goto done;
4609 s->f1 = got_opentemp();
4610 if (s->f1 == NULL) {
4611 err = got_error_from_errno("got_opentemp");
4612 goto done;
4615 s->f2 = got_opentemp();
4616 if (s->f2 == NULL) {
4617 err = got_error_from_errno("got_opentemp");
4618 goto done;
4621 s->fd1 = got_opentempfd();
4622 if (s->fd1 == -1) {
4623 err = got_error_from_errno("got_opentempfd");
4624 goto done;
4627 s->fd2 = got_opentempfd();
4628 if (s->fd2 == -1) {
4629 err = got_error_from_errno("got_opentempfd");
4630 goto done;
4633 s->first_displayed_line = 1;
4634 s->last_displayed_line = view->nlines;
4635 s->diff_context = diff_context;
4636 s->ignore_whitespace = ignore_whitespace;
4637 s->force_text_diff = force_text_diff;
4638 s->parent_view = parent_view;
4639 s->repo = repo;
4641 if (has_colors() && getenv("TOG_COLORS") != NULL) {
4642 int rc;
4644 rc = init_pair(GOT_DIFF_LINE_MINUS,
4645 get_color_value("TOG_COLOR_DIFF_MINUS"), -1);
4646 if (rc != ERR)
4647 rc = init_pair(GOT_DIFF_LINE_PLUS,
4648 get_color_value("TOG_COLOR_DIFF_PLUS"), -1);
4649 if (rc != ERR)
4650 rc = init_pair(GOT_DIFF_LINE_HUNK,
4651 get_color_value("TOG_COLOR_DIFF_CHUNK_HEADER"), -1);
4652 if (rc != ERR)
4653 rc = init_pair(GOT_DIFF_LINE_META,
4654 get_color_value("TOG_COLOR_DIFF_META"), -1);
4655 if (rc != ERR)
4656 rc = init_pair(GOT_DIFF_LINE_CHANGES,
4657 get_color_value("TOG_COLOR_DIFF_META"), -1);
4658 if (rc != ERR)
4659 rc = init_pair(GOT_DIFF_LINE_BLOB_MIN,
4660 get_color_value("TOG_COLOR_DIFF_META"), -1);
4661 if (rc != ERR)
4662 rc = init_pair(GOT_DIFF_LINE_BLOB_PLUS,
4663 get_color_value("TOG_COLOR_DIFF_META"), -1);
4664 if (rc != ERR)
4665 rc = init_pair(GOT_DIFF_LINE_AUTHOR,
4666 get_color_value("TOG_COLOR_AUTHOR"), -1);
4667 if (rc != ERR)
4668 rc = init_pair(GOT_DIFF_LINE_DATE,
4669 get_color_value("TOG_COLOR_DATE"), -1);
4670 if (rc == ERR) {
4671 err = got_error(GOT_ERR_RANGE);
4672 goto done;
4676 if (parent_view && parent_view->type == TOG_VIEW_LOG &&
4677 view_is_splitscreen(view))
4678 show_log_view(parent_view); /* draw border */
4679 diff_view_indicate_progress(view);
4681 err = create_diff(s);
4683 view->show = show_diff_view;
4684 view->input = input_diff_view;
4685 view->reset = reset_diff_view;
4686 view->close = close_diff_view;
4687 view->search_start = search_start_diff_view;
4688 view->search_next = search_next_diff_view;
4689 done:
4690 if (err)
4691 close_diff_view(view);
4692 return err;
4695 static const struct got_error *
4696 show_diff_view(struct tog_view *view)
4698 const struct got_error *err;
4699 struct tog_diff_view_state *s = &view->state.diff;
4700 char *id_str1 = NULL, *id_str2, *header;
4701 const char *label1, *label2;
4703 if (s->id1) {
4704 err = got_object_id_str(&id_str1, s->id1);
4705 if (err)
4706 return err;
4707 label1 = s->label1 ? s->label1 : id_str1;
4708 } else
4709 label1 = "/dev/null";
4711 err = got_object_id_str(&id_str2, s->id2);
4712 if (err)
4713 return err;
4714 label2 = s->label2 ? s->label2 : id_str2;
4716 if (asprintf(&header, "diff %s %s", label1, label2) == -1) {
4717 err = got_error_from_errno("asprintf");
4718 free(id_str1);
4719 free(id_str2);
4720 return err;
4722 free(id_str1);
4723 free(id_str2);
4725 err = draw_file(view, header);
4726 free(header);
4727 return err;
4730 static const struct got_error *
4731 set_selected_commit(struct tog_diff_view_state *s,
4732 struct commit_queue_entry *entry)
4734 const struct got_error *err;
4735 const struct got_object_id_queue *parent_ids;
4736 struct got_commit_object *selected_commit;
4737 struct got_object_qid *pid;
4739 free(s->id2);
4740 s->id2 = got_object_id_dup(entry->id);
4741 if (s->id2 == NULL)
4742 return got_error_from_errno("got_object_id_dup");
4744 err = got_object_open_as_commit(&selected_commit, s->repo, entry->id);
4745 if (err)
4746 return err;
4747 parent_ids = got_object_commit_get_parent_ids(selected_commit);
4748 free(s->id1);
4749 pid = STAILQ_FIRST(parent_ids);
4750 s->id1 = pid ? got_object_id_dup(&pid->id) : NULL;
4751 got_object_commit_close(selected_commit);
4752 return NULL;
4755 static const struct got_error *
4756 reset_diff_view(struct tog_view *view)
4758 struct tog_diff_view_state *s = &view->state.diff;
4760 view->count = 0;
4761 wclear(view->window);
4762 s->first_displayed_line = 1;
4763 s->last_displayed_line = view->nlines;
4764 s->matched_line = 0;
4765 diff_view_indicate_progress(view);
4766 return create_diff(s);
4769 static void
4770 diff_prev_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
4772 int start, i;
4774 i = start = s->first_displayed_line - 1;
4776 while (s->lines[i].type != type) {
4777 if (i == 0)
4778 i = s->nlines - 1;
4779 if (--i == start)
4780 return; /* do nothing, requested type not in file */
4783 s->selected_line = 1;
4784 s->first_displayed_line = i;
4787 static void
4788 diff_next_index(struct tog_diff_view_state *s, enum got_diff_line_type type)
4790 int start, i;
4792 i = start = s->first_displayed_line + 1;
4794 while (s->lines[i].type != type) {
4795 if (i == s->nlines - 1)
4796 i = 0;
4797 if (++i == start)
4798 return; /* do nothing, requested type not in file */
4801 s->selected_line = 1;
4802 s->first_displayed_line = i;
4805 static struct got_object_id *get_selected_commit_id(struct tog_blame_line *,
4806 int, int, int);
4807 static struct got_object_id *get_annotation_for_line(struct tog_blame_line *,
4808 int, int);
4810 static const struct got_error *
4811 input_diff_view(struct tog_view **new_view, struct tog_view *view, int ch)
4813 const struct got_error *err = NULL;
4814 struct tog_diff_view_state *s = &view->state.diff;
4815 struct tog_log_view_state *ls;
4816 struct commit_queue_entry *old_selected_entry;
4817 char *line = NULL;
4818 size_t linesize = 0;
4819 ssize_t linelen;
4820 int i, nscroll = view->nlines - 1, up = 0;
4822 s->lineno = s->first_displayed_line - 1 + s->selected_line;
4824 switch (ch) {
4825 case '0':
4826 view->x = 0;
4827 break;
4828 case '$':
4829 view->x = MAX(view->maxx - view->ncols / 3, 0);
4830 view->count = 0;
4831 break;
4832 case KEY_RIGHT:
4833 case 'l':
4834 if (view->x + view->ncols / 3 < view->maxx)
4835 view->x += 2; /* move two columns right */
4836 else
4837 view->count = 0;
4838 break;
4839 case KEY_LEFT:
4840 case 'h':
4841 view->x -= MIN(view->x, 2); /* move two columns back */
4842 if (view->x <= 0)
4843 view->count = 0;
4844 break;
4845 case 'a':
4846 case 'w':
4847 if (ch == 'a')
4848 s->force_text_diff = !s->force_text_diff;
4849 if (ch == 'w')
4850 s->ignore_whitespace = !s->ignore_whitespace;
4851 err = reset_diff_view(view);
4852 break;
4853 case 'g':
4854 case KEY_HOME:
4855 s->first_displayed_line = 1;
4856 view->count = 0;
4857 break;
4858 case 'G':
4859 case KEY_END:
4860 view->count = 0;
4861 if (s->eof)
4862 break;
4864 s->first_displayed_line = (s->nlines - view->nlines) + 2;
4865 s->eof = 1;
4866 break;
4867 case 'k':
4868 case KEY_UP:
4869 case CTRL('p'):
4870 if (s->first_displayed_line > 1)
4871 s->first_displayed_line--;
4872 else
4873 view->count = 0;
4874 break;
4875 case CTRL('u'):
4876 case 'u':
4877 nscroll /= 2;
4878 /* FALL THROUGH */
4879 case KEY_PPAGE:
4880 case CTRL('b'):
4881 case 'b':
4882 if (s->first_displayed_line == 1) {
4883 view->count = 0;
4884 break;
4886 i = 0;
4887 while (i++ < nscroll && s->first_displayed_line > 1)
4888 s->first_displayed_line--;
4889 break;
4890 case 'j':
4891 case KEY_DOWN:
4892 case CTRL('n'):
4893 if (!s->eof)
4894 s->first_displayed_line++;
4895 else
4896 view->count = 0;
4897 break;
4898 case CTRL('d'):
4899 case 'd':
4900 nscroll /= 2;
4901 /* FALL THROUGH */
4902 case KEY_NPAGE:
4903 case CTRL('f'):
4904 case 'f':
4905 case ' ':
4906 if (s->eof) {
4907 view->count = 0;
4908 break;
4910 i = 0;
4911 while (!s->eof && i++ < nscroll) {
4912 linelen = getline(&line, &linesize, s->f);
4913 s->first_displayed_line++;
4914 if (linelen == -1) {
4915 if (feof(s->f)) {
4916 s->eof = 1;
4917 } else
4918 err = got_ferror(s->f, GOT_ERR_IO);
4919 break;
4922 free(line);
4923 break;
4924 case '(':
4925 diff_prev_index(s, GOT_DIFF_LINE_BLOB_MIN);
4926 break;
4927 case ')':
4928 diff_next_index(s, GOT_DIFF_LINE_BLOB_MIN);
4929 break;
4930 case '{':
4931 diff_prev_index(s, GOT_DIFF_LINE_HUNK);
4932 break;
4933 case '}':
4934 diff_next_index(s, GOT_DIFF_LINE_HUNK);
4935 break;
4936 case '[':
4937 if (s->diff_context > 0) {
4938 s->diff_context--;
4939 s->matched_line = 0;
4940 diff_view_indicate_progress(view);
4941 err = create_diff(s);
4942 if (s->first_displayed_line + view->nlines - 1 >
4943 s->nlines) {
4944 s->first_displayed_line = 1;
4945 s->last_displayed_line = view->nlines;
4947 } else
4948 view->count = 0;
4949 break;
4950 case ']':
4951 if (s->diff_context < GOT_DIFF_MAX_CONTEXT) {
4952 s->diff_context++;
4953 s->matched_line = 0;
4954 diff_view_indicate_progress(view);
4955 err = create_diff(s);
4956 } else
4957 view->count = 0;
4958 break;
4959 case '<':
4960 case ',':
4961 case 'K':
4962 up = 1;
4963 /* FALL THROUGH */
4964 case '>':
4965 case '.':
4966 case 'J':
4967 if (s->parent_view == NULL) {
4968 view->count = 0;
4969 break;
4971 s->parent_view->count = view->count;
4973 if (s->parent_view->type == TOG_VIEW_LOG) {
4974 ls = &s->parent_view->state.log;
4975 old_selected_entry = ls->selected_entry;
4977 err = input_log_view(NULL, s->parent_view,
4978 up ? KEY_UP : KEY_DOWN);
4979 if (err)
4980 break;
4981 view->count = s->parent_view->count;
4983 if (old_selected_entry == ls->selected_entry)
4984 break;
4986 err = set_selected_commit(s, ls->selected_entry);
4987 if (err)
4988 break;
4989 } else if (s->parent_view->type == TOG_VIEW_BLAME) {
4990 struct tog_blame_view_state *bs;
4991 struct got_object_id *id, *prev_id;
4993 bs = &s->parent_view->state.blame;
4994 prev_id = get_annotation_for_line(bs->blame.lines,
4995 bs->blame.nlines, bs->last_diffed_line);
4997 err = input_blame_view(&view, s->parent_view,
4998 up ? KEY_UP : KEY_DOWN);
4999 if (err)
5000 break;
5001 view->count = s->parent_view->count;
5003 if (prev_id == NULL)
5004 break;
5005 id = get_selected_commit_id(bs->blame.lines,
5006 bs->blame.nlines, bs->first_displayed_line,
5007 bs->selected_line);
5008 if (id == NULL)
5009 break;
5011 if (!got_object_id_cmp(prev_id, id))
5012 break;
5014 err = input_blame_view(&view, s->parent_view, KEY_ENTER);
5015 if (err)
5016 break;
5018 s->first_displayed_line = 1;
5019 s->last_displayed_line = view->nlines;
5020 s->matched_line = 0;
5021 view->x = 0;
5023 diff_view_indicate_progress(view);
5024 err = create_diff(s);
5025 break;
5026 default:
5027 view->count = 0;
5028 break;
5031 return err;
5034 static const struct got_error *
5035 cmd_diff(int argc, char *argv[])
5037 const struct got_error *error = NULL;
5038 struct got_repository *repo = NULL;
5039 struct got_worktree *worktree = NULL;
5040 struct got_object_id *id1 = NULL, *id2 = NULL;
5041 char *repo_path = NULL, *cwd = NULL;
5042 char *id_str1 = NULL, *id_str2 = NULL;
5043 char *label1 = NULL, *label2 = NULL;
5044 int diff_context = 3, ignore_whitespace = 0;
5045 int ch, force_text_diff = 0;
5046 const char *errstr;
5047 struct tog_view *view;
5048 int *pack_fds = NULL;
5050 while ((ch = getopt(argc, argv, "aC:r:w")) != -1) {
5051 switch (ch) {
5052 case 'a':
5053 force_text_diff = 1;
5054 break;
5055 case 'C':
5056 diff_context = strtonum(optarg, 0, GOT_DIFF_MAX_CONTEXT,
5057 &errstr);
5058 if (errstr != NULL)
5059 errx(1, "number of context lines is %s: %s",
5060 errstr, errstr);
5061 break;
5062 case 'r':
5063 repo_path = realpath(optarg, NULL);
5064 if (repo_path == NULL)
5065 return got_error_from_errno2("realpath",
5066 optarg);
5067 got_path_strip_trailing_slashes(repo_path);
5068 break;
5069 case 'w':
5070 ignore_whitespace = 1;
5071 break;
5072 default:
5073 usage_diff();
5074 /* NOTREACHED */
5078 argc -= optind;
5079 argv += optind;
5081 if (argc == 0) {
5082 usage_diff(); /* TODO show local worktree changes */
5083 } else if (argc == 2) {
5084 id_str1 = argv[0];
5085 id_str2 = argv[1];
5086 } else
5087 usage_diff();
5089 error = got_repo_pack_fds_open(&pack_fds);
5090 if (error)
5091 goto done;
5093 if (repo_path == NULL) {
5094 cwd = getcwd(NULL, 0);
5095 if (cwd == NULL)
5096 return got_error_from_errno("getcwd");
5097 error = got_worktree_open(&worktree, cwd);
5098 if (error && error->code != GOT_ERR_NOT_WORKTREE)
5099 goto done;
5100 if (worktree)
5101 repo_path =
5102 strdup(got_worktree_get_repo_path(worktree));
5103 else
5104 repo_path = strdup(cwd);
5105 if (repo_path == NULL) {
5106 error = got_error_from_errno("strdup");
5107 goto done;
5111 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
5112 if (error)
5113 goto done;
5115 init_curses();
5117 error = apply_unveil(got_repo_get_path(repo), NULL);
5118 if (error)
5119 goto done;
5121 error = tog_load_refs(repo, 0);
5122 if (error)
5123 goto done;
5125 error = got_repo_match_object_id(&id1, &label1, id_str1,
5126 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5127 if (error)
5128 goto done;
5130 error = got_repo_match_object_id(&id2, &label2, id_str2,
5131 GOT_OBJ_TYPE_ANY, &tog_refs, repo);
5132 if (error)
5133 goto done;
5135 view = view_open(0, 0, 0, 0, TOG_VIEW_DIFF);
5136 if (view == NULL) {
5137 error = got_error_from_errno("view_open");
5138 goto done;
5140 error = open_diff_view(view, id1, id2, label1, label2, diff_context,
5141 ignore_whitespace, force_text_diff, NULL, repo);
5142 if (error)
5143 goto done;
5144 error = view_loop(view);
5145 done:
5146 free(label1);
5147 free(label2);
5148 free(repo_path);
5149 free(cwd);
5150 if (repo) {
5151 const struct got_error *close_err = got_repo_close(repo);
5152 if (error == NULL)
5153 error = close_err;
5155 if (worktree)
5156 got_worktree_close(worktree);
5157 if (pack_fds) {
5158 const struct got_error *pack_err =
5159 got_repo_pack_fds_close(pack_fds);
5160 if (error == NULL)
5161 error = pack_err;
5163 tog_free_refs();
5164 return error;
5167 __dead static void
5168 usage_blame(void)
5170 endwin();
5171 fprintf(stderr,
5172 "usage: %s blame [-c commit] [-r repository-path] path\n",
5173 getprogname());
5174 exit(1);
5177 struct tog_blame_line {
5178 int annotated;
5179 struct got_object_id *id;
5182 static const struct got_error *
5183 draw_blame(struct tog_view *view)
5185 struct tog_blame_view_state *s = &view->state.blame;
5186 struct tog_blame *blame = &s->blame;
5187 regmatch_t *regmatch = &view->regmatch;
5188 const struct got_error *err;
5189 int lineno = 0, nprinted = 0;
5190 char *line = NULL;
5191 size_t linesize = 0;
5192 ssize_t linelen;
5193 wchar_t *wline;
5194 int width;
5195 struct tog_blame_line *blame_line;
5196 struct got_object_id *prev_id = NULL;
5197 char *id_str;
5198 struct tog_color *tc;
5200 err = got_object_id_str(&id_str, &s->blamed_commit->id);
5201 if (err)
5202 return err;
5204 rewind(blame->f);
5205 werase(view->window);
5207 if (asprintf(&line, "commit %s", id_str) == -1) {
5208 err = got_error_from_errno("asprintf");
5209 free(id_str);
5210 return err;
5213 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5214 free(line);
5215 line = NULL;
5216 if (err)
5217 return err;
5218 if (view_needs_focus_indication(view))
5219 wstandout(view->window);
5220 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5221 if (tc)
5222 wattr_on(view->window,
5223 COLOR_PAIR(tc->colorpair), NULL);
5224 waddwstr(view->window, wline);
5225 if (tc)
5226 wattr_off(view->window,
5227 COLOR_PAIR(tc->colorpair), NULL);
5228 if (view_needs_focus_indication(view))
5229 wstandend(view->window);
5230 free(wline);
5231 wline = NULL;
5232 if (width < view->ncols - 1)
5233 waddch(view->window, '\n');
5235 if (view->gline > blame->nlines)
5236 view->gline = blame->nlines;
5238 if (asprintf(&line, "[%d/%d] %s%s", view->gline ? view->gline :
5239 s->first_displayed_line - 1 + s->selected_line, blame->nlines,
5240 s->blame_complete ? "" : "annotating... ", s->path) == -1) {
5241 free(id_str);
5242 return got_error_from_errno("asprintf");
5244 free(id_str);
5245 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
5246 free(line);
5247 line = NULL;
5248 if (err)
5249 return err;
5250 waddwstr(view->window, wline);
5251 free(wline);
5252 wline = NULL;
5253 if (width < view->ncols - 1)
5254 waddch(view->window, '\n');
5256 s->eof = 0;
5257 view->maxx = 0;
5258 while (nprinted < view->nlines - 2) {
5259 linelen = getline(&line, &linesize, blame->f);
5260 if (linelen == -1) {
5261 if (feof(blame->f)) {
5262 s->eof = 1;
5263 break;
5265 free(line);
5266 return got_ferror(blame->f, GOT_ERR_IO);
5268 if (++lineno < s->first_displayed_line)
5269 continue;
5270 if (view->gline && !gotoline(view, &lineno, &nprinted))
5271 continue;
5273 /* Set view->maxx based on full line length. */
5274 err = format_line(&wline, &width, NULL, line, 0, INT_MAX, 9, 1);
5275 if (err) {
5276 free(line);
5277 return err;
5279 free(wline);
5280 wline = NULL;
5281 view->maxx = MAX(view->maxx, width);
5283 if (nprinted == s->selected_line - 1)
5284 wstandout(view->window);
5286 if (blame->nlines > 0) {
5287 blame_line = &blame->lines[lineno - 1];
5288 if (blame_line->annotated && prev_id &&
5289 got_object_id_cmp(prev_id, blame_line->id) == 0 &&
5290 !(nprinted == s->selected_line - 1)) {
5291 waddstr(view->window, " ");
5292 } else if (blame_line->annotated) {
5293 char *id_str;
5294 err = got_object_id_str(&id_str,
5295 blame_line->id);
5296 if (err) {
5297 free(line);
5298 return err;
5300 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
5301 if (tc)
5302 wattr_on(view->window,
5303 COLOR_PAIR(tc->colorpair), NULL);
5304 wprintw(view->window, "%.8s", id_str);
5305 if (tc)
5306 wattr_off(view->window,
5307 COLOR_PAIR(tc->colorpair), NULL);
5308 free(id_str);
5309 prev_id = blame_line->id;
5310 } else {
5311 waddstr(view->window, "........");
5312 prev_id = NULL;
5314 } else {
5315 waddstr(view->window, "........");
5316 prev_id = NULL;
5319 if (nprinted == s->selected_line - 1)
5320 wstandend(view->window);
5321 waddstr(view->window, " ");
5323 if (view->ncols <= 9) {
5324 width = 9;
5325 } else if (s->first_displayed_line + nprinted ==
5326 s->matched_line &&
5327 regmatch->rm_so >= 0 && regmatch->rm_so < regmatch->rm_eo) {
5328 err = add_matched_line(&width, line, view->ncols - 9, 9,
5329 view->window, view->x, regmatch);
5330 if (err) {
5331 free(line);
5332 return err;
5334 width += 9;
5335 } else {
5336 int skip;
5337 err = format_line(&wline, &width, &skip, line,
5338 view->x, view->ncols - 9, 9, 1);
5339 if (err) {
5340 free(line);
5341 return err;
5343 waddwstr(view->window, &wline[skip]);
5344 width += 9;
5345 free(wline);
5346 wline = NULL;
5349 if (width <= view->ncols - 1)
5350 waddch(view->window, '\n');
5351 if (++nprinted == 1)
5352 s->first_displayed_line = lineno;
5354 free(line);
5355 s->last_displayed_line = lineno;
5357 view_border(view);
5359 return NULL;
5362 static const struct got_error *
5363 blame_cb(void *arg, int nlines, int lineno,
5364 struct got_commit_object *commit, struct got_object_id *id)
5366 const struct got_error *err = NULL;
5367 struct tog_blame_cb_args *a = arg;
5368 struct tog_blame_line *line;
5369 int errcode;
5371 if (nlines != a->nlines ||
5372 (lineno != -1 && lineno < 1) || lineno > a->nlines)
5373 return got_error(GOT_ERR_RANGE);
5375 errcode = pthread_mutex_lock(&tog_mutex);
5376 if (errcode)
5377 return got_error_set_errno(errcode, "pthread_mutex_lock");
5379 if (*a->quit) { /* user has quit the blame view */
5380 err = got_error(GOT_ERR_ITER_COMPLETED);
5381 goto done;
5384 if (lineno == -1)
5385 goto done; /* no change in this commit */
5387 line = &a->lines[lineno - 1];
5388 if (line->annotated)
5389 goto done;
5391 line->id = got_object_id_dup(id);
5392 if (line->id == NULL) {
5393 err = got_error_from_errno("got_object_id_dup");
5394 goto done;
5396 line->annotated = 1;
5397 done:
5398 errcode = pthread_mutex_unlock(&tog_mutex);
5399 if (errcode)
5400 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5401 return err;
5404 static void *
5405 blame_thread(void *arg)
5407 const struct got_error *err, *close_err;
5408 struct tog_blame_thread_args *ta = arg;
5409 struct tog_blame_cb_args *a = ta->cb_args;
5410 int errcode, fd1 = -1, fd2 = -1;
5411 FILE *f1 = NULL, *f2 = NULL;
5413 fd1 = got_opentempfd();
5414 if (fd1 == -1)
5415 return (void *)got_error_from_errno("got_opentempfd");
5417 fd2 = got_opentempfd();
5418 if (fd2 == -1) {
5419 err = got_error_from_errno("got_opentempfd");
5420 goto done;
5423 f1 = got_opentemp();
5424 if (f1 == NULL) {
5425 err = (void *)got_error_from_errno("got_opentemp");
5426 goto done;
5428 f2 = got_opentemp();
5429 if (f2 == NULL) {
5430 err = (void *)got_error_from_errno("got_opentemp");
5431 goto done;
5434 err = block_signals_used_by_main_thread();
5435 if (err)
5436 goto done;
5438 err = got_blame(ta->path, a->commit_id, ta->repo,
5439 tog_diff_algo, blame_cb, ta->cb_args,
5440 ta->cancel_cb, ta->cancel_arg, fd1, fd2, f1, f2);
5441 if (err && err->code == GOT_ERR_CANCELLED)
5442 err = NULL;
5444 errcode = pthread_mutex_lock(&tog_mutex);
5445 if (errcode) {
5446 err = got_error_set_errno(errcode, "pthread_mutex_lock");
5447 goto done;
5450 close_err = got_repo_close(ta->repo);
5451 if (err == NULL)
5452 err = close_err;
5453 ta->repo = NULL;
5454 *ta->complete = 1;
5456 errcode = pthread_mutex_unlock(&tog_mutex);
5457 if (errcode && err == NULL)
5458 err = got_error_set_errno(errcode, "pthread_mutex_unlock");
5460 done:
5461 if (fd1 != -1 && close(fd1) == -1 && err == NULL)
5462 err = got_error_from_errno("close");
5463 if (fd2 != -1 && close(fd2) == -1 && err == NULL)
5464 err = got_error_from_errno("close");
5465 if (f1 && fclose(f1) == EOF && err == NULL)
5466 err = got_error_from_errno("fclose");
5467 if (f2 && fclose(f2) == EOF && err == NULL)
5468 err = got_error_from_errno("fclose");
5470 return (void *)err;
5473 static struct got_object_id *
5474 get_selected_commit_id(struct tog_blame_line *lines, int nlines,
5475 int first_displayed_line, int selected_line)
5477 struct tog_blame_line *line;
5479 if (nlines <= 0)
5480 return NULL;
5482 line = &lines[first_displayed_line - 1 + selected_line - 1];
5483 if (!line->annotated)
5484 return NULL;
5486 return line->id;
5489 static struct got_object_id *
5490 get_annotation_for_line(struct tog_blame_line *lines, int nlines,
5491 int lineno)
5493 struct tog_blame_line *line;
5495 if (nlines <= 0 || lineno >= nlines)
5496 return NULL;
5498 line = &lines[lineno - 1];
5499 if (!line->annotated)
5500 return NULL;
5502 return line->id;
5505 static const struct got_error *
5506 stop_blame(struct tog_blame *blame)
5508 const struct got_error *err = NULL;
5509 int i;
5511 if (blame->thread) {
5512 int errcode;
5513 errcode = pthread_mutex_unlock(&tog_mutex);
5514 if (errcode)
5515 return got_error_set_errno(errcode,
5516 "pthread_mutex_unlock");
5517 errcode = pthread_join(blame->thread, (void **)&err);
5518 if (errcode)
5519 return got_error_set_errno(errcode, "pthread_join");
5520 errcode = pthread_mutex_lock(&tog_mutex);
5521 if (errcode)
5522 return got_error_set_errno(errcode,
5523 "pthread_mutex_lock");
5524 if (err && err->code == GOT_ERR_ITER_COMPLETED)
5525 err = NULL;
5526 blame->thread = 0; //NULL;
5528 if (blame->thread_args.repo) {
5529 const struct got_error *close_err;
5530 close_err = got_repo_close(blame->thread_args.repo);
5531 if (err == NULL)
5532 err = close_err;
5533 blame->thread_args.repo = NULL;
5535 if (blame->f) {
5536 if (fclose(blame->f) == EOF && err == NULL)
5537 err = got_error_from_errno("fclose");
5538 blame->f = NULL;
5540 if (blame->lines) {
5541 for (i = 0; i < blame->nlines; i++)
5542 free(blame->lines[i].id);
5543 free(blame->lines);
5544 blame->lines = NULL;
5546 free(blame->cb_args.commit_id);
5547 blame->cb_args.commit_id = NULL;
5548 if (blame->pack_fds) {
5549 const struct got_error *pack_err =
5550 got_repo_pack_fds_close(blame->pack_fds);
5551 if (err == NULL)
5552 err = pack_err;
5553 blame->pack_fds = NULL;
5555 return err;
5558 static const struct got_error *
5559 cancel_blame_view(void *arg)
5561 const struct got_error *err = NULL;
5562 int *done = arg;
5563 int errcode;
5565 errcode = pthread_mutex_lock(&tog_mutex);
5566 if (errcode)
5567 return got_error_set_errno(errcode,
5568 "pthread_mutex_unlock");
5570 if (*done)
5571 err = got_error(GOT_ERR_CANCELLED);
5573 errcode = pthread_mutex_unlock(&tog_mutex);
5574 if (errcode)
5575 return got_error_set_errno(errcode,
5576 "pthread_mutex_lock");
5578 return err;
5581 static const struct got_error *
5582 run_blame(struct tog_view *view)
5584 struct tog_blame_view_state *s = &view->state.blame;
5585 struct tog_blame *blame = &s->blame;
5586 const struct got_error *err = NULL;
5587 struct got_commit_object *commit = NULL;
5588 struct got_blob_object *blob = NULL;
5589 struct got_repository *thread_repo = NULL;
5590 struct got_object_id *obj_id = NULL;
5591 int obj_type, fd = -1;
5592 int *pack_fds = NULL;
5594 err = got_object_open_as_commit(&commit, s->repo,
5595 &s->blamed_commit->id);
5596 if (err)
5597 return err;
5599 fd = got_opentempfd();
5600 if (fd == -1) {
5601 err = got_error_from_errno("got_opentempfd");
5602 goto done;
5605 err = got_object_id_by_path(&obj_id, s->repo, commit, s->path);
5606 if (err)
5607 goto done;
5609 err = got_object_get_type(&obj_type, s->repo, obj_id);
5610 if (err)
5611 goto done;
5613 if (obj_type != GOT_OBJ_TYPE_BLOB) {
5614 err = got_error(GOT_ERR_OBJ_TYPE);
5615 goto done;
5618 err = got_object_open_as_blob(&blob, s->repo, obj_id, 8192, fd);
5619 if (err)
5620 goto done;
5621 blame->f = got_opentemp();
5622 if (blame->f == NULL) {
5623 err = got_error_from_errno("got_opentemp");
5624 goto done;
5626 err = got_object_blob_dump_to_file(&blame->filesize, &blame->nlines,
5627 &blame->line_offsets, blame->f, blob);
5628 if (err)
5629 goto done;
5630 if (blame->nlines == 0) {
5631 s->blame_complete = 1;
5632 goto done;
5635 /* Don't include \n at EOF in the blame line count. */
5636 if (blame->line_offsets[blame->nlines - 1] == blame->filesize)
5637 blame->nlines--;
5639 blame->lines = calloc(blame->nlines, sizeof(*blame->lines));
5640 if (blame->lines == NULL) {
5641 err = got_error_from_errno("calloc");
5642 goto done;
5645 err = got_repo_pack_fds_open(&pack_fds);
5646 if (err)
5647 goto done;
5648 err = got_repo_open(&thread_repo, got_repo_get_path(s->repo), NULL,
5649 pack_fds);
5650 if (err)
5651 goto done;
5653 blame->pack_fds = pack_fds;
5654 blame->cb_args.view = view;
5655 blame->cb_args.lines = blame->lines;
5656 blame->cb_args.nlines = blame->nlines;
5657 blame->cb_args.commit_id = got_object_id_dup(&s->blamed_commit->id);
5658 if (blame->cb_args.commit_id == NULL) {
5659 err = got_error_from_errno("got_object_id_dup");
5660 goto done;
5662 blame->cb_args.quit = &s->done;
5664 blame->thread_args.path = s->path;
5665 blame->thread_args.repo = thread_repo;
5666 blame->thread_args.cb_args = &blame->cb_args;
5667 blame->thread_args.complete = &s->blame_complete;
5668 blame->thread_args.cancel_cb = cancel_blame_view;
5669 blame->thread_args.cancel_arg = &s->done;
5670 s->blame_complete = 0;
5672 if (s->first_displayed_line + view->nlines - 1 > blame->nlines) {
5673 s->first_displayed_line = 1;
5674 s->last_displayed_line = view->nlines;
5675 s->selected_line = 1;
5677 s->matched_line = 0;
5679 done:
5680 if (commit)
5681 got_object_commit_close(commit);
5682 if (fd != -1 && close(fd) == -1 && err == NULL)
5683 err = got_error_from_errno("close");
5684 if (blob)
5685 got_object_blob_close(blob);
5686 free(obj_id);
5687 if (err)
5688 stop_blame(blame);
5689 return err;
5692 static const struct got_error *
5693 open_blame_view(struct tog_view *view, char *path,
5694 struct got_object_id *commit_id, struct got_repository *repo)
5696 const struct got_error *err = NULL;
5697 struct tog_blame_view_state *s = &view->state.blame;
5699 STAILQ_INIT(&s->blamed_commits);
5701 s->path = strdup(path);
5702 if (s->path == NULL)
5703 return got_error_from_errno("strdup");
5705 err = got_object_qid_alloc(&s->blamed_commit, commit_id);
5706 if (err) {
5707 free(s->path);
5708 return err;
5711 STAILQ_INSERT_HEAD(&s->blamed_commits, s->blamed_commit, entry);
5712 s->first_displayed_line = 1;
5713 s->last_displayed_line = view->nlines;
5714 s->selected_line = 1;
5715 s->blame_complete = 0;
5716 s->repo = repo;
5717 s->commit_id = commit_id;
5718 memset(&s->blame, 0, sizeof(s->blame));
5720 STAILQ_INIT(&s->colors);
5721 if (has_colors() && getenv("TOG_COLORS") != NULL) {
5722 err = add_color(&s->colors, "^", TOG_COLOR_COMMIT,
5723 get_color_value("TOG_COLOR_COMMIT"));
5724 if (err)
5725 return err;
5728 view->show = show_blame_view;
5729 view->input = input_blame_view;
5730 view->reset = reset_blame_view;
5731 view->close = close_blame_view;
5732 view->search_start = search_start_blame_view;
5733 view->search_next = search_next_blame_view;
5735 return run_blame(view);
5738 static const struct got_error *
5739 close_blame_view(struct tog_view *view)
5741 const struct got_error *err = NULL;
5742 struct tog_blame_view_state *s = &view->state.blame;
5744 if (s->blame.thread)
5745 err = stop_blame(&s->blame);
5747 while (!STAILQ_EMPTY(&s->blamed_commits)) {
5748 struct got_object_qid *blamed_commit;
5749 blamed_commit = STAILQ_FIRST(&s->blamed_commits);
5750 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
5751 got_object_qid_free(blamed_commit);
5754 free(s->path);
5755 free_colors(&s->colors);
5756 return err;
5759 static const struct got_error *
5760 search_start_blame_view(struct tog_view *view)
5762 struct tog_blame_view_state *s = &view->state.blame;
5764 s->matched_line = 0;
5765 return NULL;
5768 static const struct got_error *
5769 search_next_blame_view(struct tog_view *view)
5771 struct tog_blame_view_state *s = &view->state.blame;
5772 const struct got_error *err = NULL;
5773 int lineno;
5774 char *line = NULL;
5775 size_t linesize = 0;
5776 ssize_t linelen;
5778 if (!view->searching) {
5779 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5780 return NULL;
5783 if (s->matched_line) {
5784 if (view->searching == TOG_SEARCH_FORWARD)
5785 lineno = s->matched_line + 1;
5786 else
5787 lineno = s->matched_line - 1;
5788 } else
5789 lineno = s->first_displayed_line - 1 + s->selected_line;
5791 while (1) {
5792 off_t offset;
5794 if (lineno <= 0 || lineno > s->blame.nlines) {
5795 if (s->matched_line == 0) {
5796 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5797 break;
5800 if (view->searching == TOG_SEARCH_FORWARD)
5801 lineno = 1;
5802 else
5803 lineno = s->blame.nlines;
5806 offset = s->blame.line_offsets[lineno - 1];
5807 if (fseeko(s->blame.f, offset, SEEK_SET) != 0) {
5808 free(line);
5809 return got_error_from_errno("fseeko");
5811 linelen = getline(&line, &linesize, s->blame.f);
5812 if (linelen != -1) {
5813 char *exstr;
5814 err = expand_tab(&exstr, line);
5815 if (err)
5816 break;
5817 if (match_line(exstr, &view->regex, 1,
5818 &view->regmatch)) {
5819 view->search_next_done = TOG_SEARCH_HAVE_MORE;
5820 s->matched_line = lineno;
5821 free(exstr);
5822 break;
5824 free(exstr);
5826 if (view->searching == TOG_SEARCH_FORWARD)
5827 lineno++;
5828 else
5829 lineno--;
5831 free(line);
5833 if (s->matched_line) {
5834 s->first_displayed_line = s->matched_line;
5835 s->selected_line = 1;
5838 return err;
5841 static const struct got_error *
5842 show_blame_view(struct tog_view *view)
5844 const struct got_error *err = NULL;
5845 struct tog_blame_view_state *s = &view->state.blame;
5846 int errcode;
5848 if (s->blame.thread == 0 && !s->blame_complete) {
5849 errcode = pthread_create(&s->blame.thread, NULL, blame_thread,
5850 &s->blame.thread_args);
5851 if (errcode)
5852 return got_error_set_errno(errcode, "pthread_create");
5854 halfdelay(1); /* fast refresh while annotating */
5857 if (s->blame_complete)
5858 halfdelay(10); /* disable fast refresh */
5860 err = draw_blame(view);
5862 view_border(view);
5863 return err;
5866 static const struct got_error *
5867 log_annotated_line(struct tog_view **new_view, int begin_y, int begin_x,
5868 struct got_repository *repo, struct got_object_id *id)
5870 struct tog_view *log_view;
5871 const struct got_error *err = NULL;
5873 *new_view = NULL;
5875 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
5876 if (log_view == NULL)
5877 return got_error_from_errno("view_open");
5879 err = open_log_view(log_view, id, repo, GOT_REF_HEAD, "", 0);
5880 if (err)
5881 view_close(log_view);
5882 else
5883 *new_view = log_view;
5885 return err;
5888 static const struct got_error *
5889 input_blame_view(struct tog_view **new_view, struct tog_view *view, int ch)
5891 const struct got_error *err = NULL, *thread_err = NULL;
5892 struct tog_view *diff_view;
5893 struct tog_blame_view_state *s = &view->state.blame;
5894 int eos, nscroll, begin_y = 0, begin_x = 0;
5896 eos = nscroll = view->nlines - 2;
5897 if (view_is_hsplit_top(view))
5898 --eos; /* border */
5900 switch (ch) {
5901 case '0':
5902 view->x = 0;
5903 break;
5904 case '$':
5905 view->x = MAX(view->maxx - view->ncols / 3, 0);
5906 view->count = 0;
5907 break;
5908 case KEY_RIGHT:
5909 case 'l':
5910 if (view->x + view->ncols / 3 < view->maxx)
5911 view->x += 2; /* move two columns right */
5912 else
5913 view->count = 0;
5914 break;
5915 case KEY_LEFT:
5916 case 'h':
5917 view->x -= MIN(view->x, 2); /* move two columns back */
5918 if (view->x <= 0)
5919 view->count = 0;
5920 break;
5921 case 'q':
5922 s->done = 1;
5923 break;
5924 case 'g':
5925 case KEY_HOME:
5926 s->selected_line = 1;
5927 s->first_displayed_line = 1;
5928 view->count = 0;
5929 break;
5930 case 'G':
5931 case KEY_END:
5932 if (s->blame.nlines < eos) {
5933 s->selected_line = s->blame.nlines;
5934 s->first_displayed_line = 1;
5935 } else {
5936 s->selected_line = eos;
5937 s->first_displayed_line = s->blame.nlines - (eos - 1);
5939 view->count = 0;
5940 break;
5941 case 'k':
5942 case KEY_UP:
5943 case CTRL('p'):
5944 if (s->selected_line > 1)
5945 s->selected_line--;
5946 else if (s->selected_line == 1 &&
5947 s->first_displayed_line > 1)
5948 s->first_displayed_line--;
5949 else
5950 view->count = 0;
5951 break;
5952 case CTRL('u'):
5953 case 'u':
5954 nscroll /= 2;
5955 /* FALL THROUGH */
5956 case KEY_PPAGE:
5957 case CTRL('b'):
5958 case 'b':
5959 if (s->first_displayed_line == 1) {
5960 if (view->count > 1)
5961 nscroll += nscroll;
5962 s->selected_line = MAX(1, s->selected_line - nscroll);
5963 view->count = 0;
5964 break;
5966 if (s->first_displayed_line > nscroll)
5967 s->first_displayed_line -= nscroll;
5968 else
5969 s->first_displayed_line = 1;
5970 break;
5971 case 'j':
5972 case KEY_DOWN:
5973 case CTRL('n'):
5974 if (s->selected_line < eos && s->first_displayed_line +
5975 s->selected_line <= s->blame.nlines)
5976 s->selected_line++;
5977 else if (s->first_displayed_line < s->blame.nlines - (eos - 1))
5978 s->first_displayed_line++;
5979 else
5980 view->count = 0;
5981 break;
5982 case 'c':
5983 case 'p': {
5984 struct got_object_id *id = NULL;
5986 view->count = 0;
5987 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
5988 s->first_displayed_line, s->selected_line);
5989 if (id == NULL)
5990 break;
5991 if (ch == 'p') {
5992 struct got_commit_object *commit, *pcommit;
5993 struct got_object_qid *pid;
5994 struct got_object_id *blob_id = NULL;
5995 int obj_type;
5996 err = got_object_open_as_commit(&commit,
5997 s->repo, id);
5998 if (err)
5999 break;
6000 pid = STAILQ_FIRST(
6001 got_object_commit_get_parent_ids(commit));
6002 if (pid == NULL) {
6003 got_object_commit_close(commit);
6004 break;
6006 /* Check if path history ends here. */
6007 err = got_object_open_as_commit(&pcommit,
6008 s->repo, &pid->id);
6009 if (err)
6010 break;
6011 err = got_object_id_by_path(&blob_id, s->repo,
6012 pcommit, s->path);
6013 got_object_commit_close(pcommit);
6014 if (err) {
6015 if (err->code == GOT_ERR_NO_TREE_ENTRY)
6016 err = NULL;
6017 got_object_commit_close(commit);
6018 break;
6020 err = got_object_get_type(&obj_type, s->repo,
6021 blob_id);
6022 free(blob_id);
6023 /* Can't blame non-blob type objects. */
6024 if (obj_type != GOT_OBJ_TYPE_BLOB) {
6025 got_object_commit_close(commit);
6026 break;
6028 err = got_object_qid_alloc(&s->blamed_commit,
6029 &pid->id);
6030 got_object_commit_close(commit);
6031 } else {
6032 if (got_object_id_cmp(id,
6033 &s->blamed_commit->id) == 0)
6034 break;
6035 err = got_object_qid_alloc(&s->blamed_commit,
6036 id);
6038 if (err)
6039 break;
6040 s->done = 1;
6041 thread_err = stop_blame(&s->blame);
6042 s->done = 0;
6043 if (thread_err)
6044 break;
6045 STAILQ_INSERT_HEAD(&s->blamed_commits,
6046 s->blamed_commit, entry);
6047 err = run_blame(view);
6048 if (err)
6049 break;
6050 break;
6052 case 'C': {
6053 struct got_object_qid *first;
6055 view->count = 0;
6056 first = STAILQ_FIRST(&s->blamed_commits);
6057 if (!got_object_id_cmp(&first->id, s->commit_id))
6058 break;
6059 s->done = 1;
6060 thread_err = stop_blame(&s->blame);
6061 s->done = 0;
6062 if (thread_err)
6063 break;
6064 STAILQ_REMOVE_HEAD(&s->blamed_commits, entry);
6065 got_object_qid_free(s->blamed_commit);
6066 s->blamed_commit =
6067 STAILQ_FIRST(&s->blamed_commits);
6068 err = run_blame(view);
6069 if (err)
6070 break;
6071 break;
6073 case 'L':
6074 view->count = 0;
6075 s->id_to_log = get_selected_commit_id(s->blame.lines,
6076 s->blame.nlines, s->first_displayed_line, s->selected_line);
6077 if (s->id_to_log)
6078 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6079 break;
6080 case KEY_ENTER:
6081 case '\r': {
6082 struct got_object_id *id = NULL;
6083 struct got_object_qid *pid;
6084 struct got_commit_object *commit = NULL;
6086 view->count = 0;
6087 id = get_selected_commit_id(s->blame.lines, s->blame.nlines,
6088 s->first_displayed_line, s->selected_line);
6089 if (id == NULL)
6090 break;
6091 err = got_object_open_as_commit(&commit, s->repo, id);
6092 if (err)
6093 break;
6094 pid = STAILQ_FIRST(got_object_commit_get_parent_ids(commit));
6095 if (*new_view) {
6096 /* traversed from diff view, release diff resources */
6097 err = close_diff_view(*new_view);
6098 if (err)
6099 break;
6100 diff_view = *new_view;
6101 } else {
6102 if (view_is_parent_view(view))
6103 view_get_split(view, &begin_y, &begin_x);
6105 diff_view = view_open(0, 0, begin_y, begin_x,
6106 TOG_VIEW_DIFF);
6107 if (diff_view == NULL) {
6108 got_object_commit_close(commit);
6109 err = got_error_from_errno("view_open");
6110 break;
6113 err = open_diff_view(diff_view, pid ? &pid->id : NULL,
6114 id, NULL, NULL, 3, 0, 0, view, s->repo);
6115 got_object_commit_close(commit);
6116 if (err) {
6117 view_close(diff_view);
6118 break;
6120 s->last_diffed_line = s->first_displayed_line - 1 +
6121 s->selected_line;
6122 if (*new_view)
6123 break; /* still open from active diff view */
6124 if (view_is_parent_view(view) &&
6125 view->mode == TOG_VIEW_SPLIT_HRZN) {
6126 err = view_init_hsplit(view, begin_y);
6127 if (err)
6128 break;
6131 view->focussed = 0;
6132 diff_view->focussed = 1;
6133 diff_view->mode = view->mode;
6134 diff_view->nlines = view->lines - begin_y;
6135 if (view_is_parent_view(view)) {
6136 view_transfer_size(diff_view, view);
6137 err = view_close_child(view);
6138 if (err)
6139 break;
6140 err = view_set_child(view, diff_view);
6141 if (err)
6142 break;
6143 view->focus_child = 1;
6144 } else
6145 *new_view = diff_view;
6146 if (err)
6147 break;
6148 break;
6150 case CTRL('d'):
6151 case 'd':
6152 nscroll /= 2;
6153 /* FALL THROUGH */
6154 case KEY_NPAGE:
6155 case CTRL('f'):
6156 case 'f':
6157 case ' ':
6158 if (s->last_displayed_line >= s->blame.nlines &&
6159 s->selected_line >= MIN(s->blame.nlines,
6160 view->nlines - 2)) {
6161 view->count = 0;
6162 break;
6164 if (s->last_displayed_line >= s->blame.nlines &&
6165 s->selected_line < view->nlines - 2) {
6166 s->selected_line +=
6167 MIN(nscroll, s->last_displayed_line -
6168 s->first_displayed_line - s->selected_line + 1);
6170 if (s->last_displayed_line + nscroll <= s->blame.nlines)
6171 s->first_displayed_line += nscroll;
6172 else
6173 s->first_displayed_line =
6174 s->blame.nlines - (view->nlines - 3);
6175 break;
6176 case KEY_RESIZE:
6177 if (s->selected_line > view->nlines - 2) {
6178 s->selected_line = MIN(s->blame.nlines,
6179 view->nlines - 2);
6181 break;
6182 default:
6183 view->count = 0;
6184 break;
6186 return thread_err ? thread_err : err;
6189 static const struct got_error *
6190 reset_blame_view(struct tog_view *view)
6192 const struct got_error *err;
6193 struct tog_blame_view_state *s = &view->state.blame;
6195 view->count = 0;
6196 s->done = 1;
6197 err = stop_blame(&s->blame);
6198 s->done = 0;
6199 if (err)
6200 return err;
6201 return run_blame(view);
6204 static const struct got_error *
6205 cmd_blame(int argc, char *argv[])
6207 const struct got_error *error;
6208 struct got_repository *repo = NULL;
6209 struct got_worktree *worktree = NULL;
6210 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
6211 char *link_target = NULL;
6212 struct got_object_id *commit_id = NULL;
6213 struct got_commit_object *commit = NULL;
6214 char *commit_id_str = NULL;
6215 int ch;
6216 struct tog_view *view;
6217 int *pack_fds = NULL;
6219 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
6220 switch (ch) {
6221 case 'c':
6222 commit_id_str = optarg;
6223 break;
6224 case 'r':
6225 repo_path = realpath(optarg, NULL);
6226 if (repo_path == NULL)
6227 return got_error_from_errno2("realpath",
6228 optarg);
6229 break;
6230 default:
6231 usage_blame();
6232 /* NOTREACHED */
6236 argc -= optind;
6237 argv += optind;
6239 if (argc != 1)
6240 usage_blame();
6242 error = got_repo_pack_fds_open(&pack_fds);
6243 if (error != NULL)
6244 goto done;
6246 if (repo_path == NULL) {
6247 cwd = getcwd(NULL, 0);
6248 if (cwd == NULL)
6249 return got_error_from_errno("getcwd");
6250 error = got_worktree_open(&worktree, cwd);
6251 if (error && error->code != GOT_ERR_NOT_WORKTREE)
6252 goto done;
6253 if (worktree)
6254 repo_path =
6255 strdup(got_worktree_get_repo_path(worktree));
6256 else
6257 repo_path = strdup(cwd);
6258 if (repo_path == NULL) {
6259 error = got_error_from_errno("strdup");
6260 goto done;
6264 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
6265 if (error != NULL)
6266 goto done;
6268 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv, repo,
6269 worktree);
6270 if (error)
6271 goto done;
6273 init_curses();
6275 error = apply_unveil(got_repo_get_path(repo), NULL);
6276 if (error)
6277 goto done;
6279 error = tog_load_refs(repo, 0);
6280 if (error)
6281 goto done;
6283 if (commit_id_str == NULL) {
6284 struct got_reference *head_ref;
6285 error = got_ref_open(&head_ref, repo, worktree ?
6286 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD, 0);
6287 if (error != NULL)
6288 goto done;
6289 error = got_ref_resolve(&commit_id, repo, head_ref);
6290 got_ref_close(head_ref);
6291 } else {
6292 error = got_repo_match_object_id(&commit_id, NULL,
6293 commit_id_str, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
6295 if (error != NULL)
6296 goto done;
6298 view = view_open(0, 0, 0, 0, TOG_VIEW_BLAME);
6299 if (view == NULL) {
6300 error = got_error_from_errno("view_open");
6301 goto done;
6304 error = got_object_open_as_commit(&commit, repo, commit_id);
6305 if (error)
6306 goto done;
6308 error = got_object_resolve_symlinks(&link_target, in_repo_path,
6309 commit, repo);
6310 if (error)
6311 goto done;
6313 error = open_blame_view(view, link_target ? link_target : in_repo_path,
6314 commit_id, repo);
6315 if (error)
6316 goto done;
6317 if (worktree) {
6318 /* Release work tree lock. */
6319 got_worktree_close(worktree);
6320 worktree = NULL;
6322 error = view_loop(view);
6323 done:
6324 free(repo_path);
6325 free(in_repo_path);
6326 free(link_target);
6327 free(cwd);
6328 free(commit_id);
6329 if (commit)
6330 got_object_commit_close(commit);
6331 if (worktree)
6332 got_worktree_close(worktree);
6333 if (repo) {
6334 const struct got_error *close_err = got_repo_close(repo);
6335 if (error == NULL)
6336 error = close_err;
6338 if (pack_fds) {
6339 const struct got_error *pack_err =
6340 got_repo_pack_fds_close(pack_fds);
6341 if (error == NULL)
6342 error = pack_err;
6344 tog_free_refs();
6345 return error;
6348 static const struct got_error *
6349 draw_tree_entries(struct tog_view *view, const char *parent_path)
6351 struct tog_tree_view_state *s = &view->state.tree;
6352 const struct got_error *err = NULL;
6353 struct got_tree_entry *te;
6354 wchar_t *wline;
6355 struct tog_color *tc;
6356 int width, n, nentries, i = 1;
6357 int limit = view->nlines;
6359 s->ndisplayed = 0;
6360 if (view_is_hsplit_top(view))
6361 --limit; /* border */
6363 werase(view->window);
6365 if (limit == 0)
6366 return NULL;
6368 err = format_line(&wline, &width, NULL, s->tree_label, 0, view->ncols,
6369 0, 0);
6370 if (err)
6371 return err;
6372 if (view_needs_focus_indication(view))
6373 wstandout(view->window);
6374 tc = get_color(&s->colors, TOG_COLOR_COMMIT);
6375 if (tc)
6376 wattr_on(view->window,
6377 COLOR_PAIR(tc->colorpair), NULL);
6378 waddwstr(view->window, wline);
6379 if (tc)
6380 wattr_off(view->window,
6381 COLOR_PAIR(tc->colorpair), NULL);
6382 if (view_needs_focus_indication(view))
6383 wstandend(view->window);
6384 free(wline);
6385 wline = NULL;
6387 i += s->selected;
6388 if (s->first_displayed_entry) {
6389 i += got_tree_entry_get_index(s->first_displayed_entry);
6390 if (s->tree != s->root)
6391 ++i; /* account for ".." entry */
6393 nentries = got_object_tree_get_nentries(s->tree);
6394 wprintw(view->window, " [%d/%d]", i,
6395 nentries + (s->tree == s->root ? 0 : 1)); /* ".." in !root tree */
6397 if (width < view->ncols - 1)
6398 waddch(view->window, '\n');
6399 if (--limit <= 0)
6400 return NULL;
6401 err = format_line(&wline, &width, NULL, parent_path, 0, view->ncols,
6402 0, 0);
6403 if (err)
6404 return err;
6405 waddwstr(view->window, wline);
6406 free(wline);
6407 wline = NULL;
6408 if (width < view->ncols - 1)
6409 waddch(view->window, '\n');
6410 if (--limit <= 0)
6411 return NULL;
6412 waddch(view->window, '\n');
6413 if (--limit <= 0)
6414 return NULL;
6416 if (s->first_displayed_entry == NULL) {
6417 te = got_object_tree_get_first_entry(s->tree);
6418 if (s->selected == 0) {
6419 if (view->focussed)
6420 wstandout(view->window);
6421 s->selected_entry = NULL;
6423 waddstr(view->window, " ..\n"); /* parent directory */
6424 if (s->selected == 0 && view->focussed)
6425 wstandend(view->window);
6426 s->ndisplayed++;
6427 if (--limit <= 0)
6428 return NULL;
6429 n = 1;
6430 } else {
6431 n = 0;
6432 te = s->first_displayed_entry;
6435 for (i = got_tree_entry_get_index(te); i < nentries; i++) {
6436 char *line = NULL, *id_str = NULL, *link_target = NULL;
6437 const char *modestr = "";
6438 mode_t mode;
6440 te = got_object_tree_get_entry(s->tree, i);
6441 mode = got_tree_entry_get_mode(te);
6443 if (s->show_ids) {
6444 err = got_object_id_str(&id_str,
6445 got_tree_entry_get_id(te));
6446 if (err)
6447 return got_error_from_errno(
6448 "got_object_id_str");
6450 if (got_object_tree_entry_is_submodule(te))
6451 modestr = "$";
6452 else if (S_ISLNK(mode)) {
6453 int i;
6455 err = got_tree_entry_get_symlink_target(&link_target,
6456 te, s->repo);
6457 if (err) {
6458 free(id_str);
6459 return err;
6461 for (i = 0; i < strlen(link_target); i++) {
6462 if (!isprint((unsigned char)link_target[i]))
6463 link_target[i] = '?';
6465 modestr = "@";
6467 else if (S_ISDIR(mode))
6468 modestr = "/";
6469 else if (mode & S_IXUSR)
6470 modestr = "*";
6471 if (asprintf(&line, "%s %s%s%s%s", id_str ? id_str : "",
6472 got_tree_entry_get_name(te), modestr,
6473 link_target ? " -> ": "",
6474 link_target ? link_target : "") == -1) {
6475 free(id_str);
6476 free(link_target);
6477 return got_error_from_errno("asprintf");
6479 free(id_str);
6480 free(link_target);
6481 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
6482 0, 0);
6483 if (err) {
6484 free(line);
6485 break;
6487 if (n == s->selected) {
6488 if (view->focussed)
6489 wstandout(view->window);
6490 s->selected_entry = te;
6492 tc = match_color(&s->colors, line);
6493 if (tc)
6494 wattr_on(view->window,
6495 COLOR_PAIR(tc->colorpair), NULL);
6496 waddwstr(view->window, wline);
6497 if (tc)
6498 wattr_off(view->window,
6499 COLOR_PAIR(tc->colorpair), NULL);
6500 if (width < view->ncols - 1)
6501 waddch(view->window, '\n');
6502 if (n == s->selected && view->focussed)
6503 wstandend(view->window);
6504 free(line);
6505 free(wline);
6506 wline = NULL;
6507 n++;
6508 s->ndisplayed++;
6509 s->last_displayed_entry = te;
6510 if (--limit <= 0)
6511 break;
6514 return err;
6517 static void
6518 tree_scroll_up(struct tog_tree_view_state *s, int maxscroll)
6520 struct got_tree_entry *te;
6521 int isroot = s->tree == s->root;
6522 int i = 0;
6524 if (s->first_displayed_entry == NULL)
6525 return;
6527 te = got_tree_entry_get_prev(s->tree, s->first_displayed_entry);
6528 while (i++ < maxscroll) {
6529 if (te == NULL) {
6530 if (!isroot)
6531 s->first_displayed_entry = NULL;
6532 break;
6534 s->first_displayed_entry = te;
6535 te = got_tree_entry_get_prev(s->tree, te);
6539 static const struct got_error *
6540 tree_scroll_down(struct tog_view *view, int maxscroll)
6542 struct tog_tree_view_state *s = &view->state.tree;
6543 struct got_tree_entry *next, *last;
6544 int n = 0;
6546 if (s->first_displayed_entry)
6547 next = got_tree_entry_get_next(s->tree,
6548 s->first_displayed_entry);
6549 else
6550 next = got_object_tree_get_first_entry(s->tree);
6552 last = s->last_displayed_entry;
6553 while (next && n++ < maxscroll) {
6554 if (last) {
6555 s->last_displayed_entry = last;
6556 last = got_tree_entry_get_next(s->tree, last);
6558 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN && next)) {
6559 s->first_displayed_entry = next;
6560 next = got_tree_entry_get_next(s->tree, next);
6564 return NULL;
6567 static const struct got_error *
6568 tree_entry_path(char **path, struct tog_parent_trees *parents,
6569 struct got_tree_entry *te)
6571 const struct got_error *err = NULL;
6572 struct tog_parent_tree *pt;
6573 size_t len = 2; /* for leading slash and NUL */
6575 TAILQ_FOREACH(pt, parents, entry)
6576 len += strlen(got_tree_entry_get_name(pt->selected_entry))
6577 + 1 /* slash */;
6578 if (te)
6579 len += strlen(got_tree_entry_get_name(te));
6581 *path = calloc(1, len);
6582 if (path == NULL)
6583 return got_error_from_errno("calloc");
6585 (*path)[0] = '/';
6586 pt = TAILQ_LAST(parents, tog_parent_trees);
6587 while (pt) {
6588 const char *name = got_tree_entry_get_name(pt->selected_entry);
6589 if (strlcat(*path, name, len) >= len) {
6590 err = got_error(GOT_ERR_NO_SPACE);
6591 goto done;
6593 if (strlcat(*path, "/", len) >= len) {
6594 err = got_error(GOT_ERR_NO_SPACE);
6595 goto done;
6597 pt = TAILQ_PREV(pt, tog_parent_trees, entry);
6599 if (te) {
6600 if (strlcat(*path, got_tree_entry_get_name(te), len) >= len) {
6601 err = got_error(GOT_ERR_NO_SPACE);
6602 goto done;
6605 done:
6606 if (err) {
6607 free(*path);
6608 *path = NULL;
6610 return err;
6613 static const struct got_error *
6614 blame_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6615 struct got_tree_entry *te, struct tog_parent_trees *parents,
6616 struct got_object_id *commit_id, struct got_repository *repo)
6618 const struct got_error *err = NULL;
6619 char *path;
6620 struct tog_view *blame_view;
6622 *new_view = NULL;
6624 err = tree_entry_path(&path, parents, te);
6625 if (err)
6626 return err;
6628 blame_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_BLAME);
6629 if (blame_view == NULL) {
6630 err = got_error_from_errno("view_open");
6631 goto done;
6634 err = open_blame_view(blame_view, path, commit_id, repo);
6635 if (err) {
6636 if (err->code == GOT_ERR_CANCELLED)
6637 err = NULL;
6638 view_close(blame_view);
6639 } else
6640 *new_view = blame_view;
6641 done:
6642 free(path);
6643 return err;
6646 static const struct got_error *
6647 log_selected_tree_entry(struct tog_view **new_view, int begin_y, int begin_x,
6648 struct tog_tree_view_state *s)
6650 struct tog_view *log_view;
6651 const struct got_error *err = NULL;
6652 char *path;
6654 *new_view = NULL;
6656 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
6657 if (log_view == NULL)
6658 return got_error_from_errno("view_open");
6660 err = tree_entry_path(&path, &s->parents, s->selected_entry);
6661 if (err)
6662 return err;
6664 err = open_log_view(log_view, s->commit_id, s->repo, s->head_ref_name,
6665 path, 0);
6666 if (err)
6667 view_close(log_view);
6668 else
6669 *new_view = log_view;
6670 free(path);
6671 return err;
6674 static const struct got_error *
6675 open_tree_view(struct tog_view *view, struct got_object_id *commit_id,
6676 const char *head_ref_name, struct got_repository *repo)
6678 const struct got_error *err = NULL;
6679 char *commit_id_str = NULL;
6680 struct tog_tree_view_state *s = &view->state.tree;
6681 struct got_commit_object *commit = NULL;
6683 TAILQ_INIT(&s->parents);
6684 STAILQ_INIT(&s->colors);
6686 s->commit_id = got_object_id_dup(commit_id);
6687 if (s->commit_id == NULL)
6688 return got_error_from_errno("got_object_id_dup");
6690 err = got_object_open_as_commit(&commit, repo, commit_id);
6691 if (err)
6692 goto done;
6695 * The root is opened here and will be closed when the view is closed.
6696 * Any visited subtrees and their path-wise parents are opened and
6697 * closed on demand.
6699 err = got_object_open_as_tree(&s->root, repo,
6700 got_object_commit_get_tree_id(commit));
6701 if (err)
6702 goto done;
6703 s->tree = s->root;
6705 err = got_object_id_str(&commit_id_str, commit_id);
6706 if (err != NULL)
6707 goto done;
6709 if (asprintf(&s->tree_label, "commit %s", commit_id_str) == -1) {
6710 err = got_error_from_errno("asprintf");
6711 goto done;
6714 s->first_displayed_entry = got_object_tree_get_entry(s->tree, 0);
6715 s->selected_entry = got_object_tree_get_entry(s->tree, 0);
6716 if (head_ref_name) {
6717 s->head_ref_name = strdup(head_ref_name);
6718 if (s->head_ref_name == NULL) {
6719 err = got_error_from_errno("strdup");
6720 goto done;
6723 s->repo = repo;
6725 if (has_colors() && getenv("TOG_COLORS") != NULL) {
6726 err = add_color(&s->colors, "\\$$",
6727 TOG_COLOR_TREE_SUBMODULE,
6728 get_color_value("TOG_COLOR_TREE_SUBMODULE"));
6729 if (err)
6730 goto done;
6731 err = add_color(&s->colors, "@$", TOG_COLOR_TREE_SYMLINK,
6732 get_color_value("TOG_COLOR_TREE_SYMLINK"));
6733 if (err)
6734 goto done;
6735 err = add_color(&s->colors, "/$",
6736 TOG_COLOR_TREE_DIRECTORY,
6737 get_color_value("TOG_COLOR_TREE_DIRECTORY"));
6738 if (err)
6739 goto done;
6741 err = add_color(&s->colors, "\\*$",
6742 TOG_COLOR_TREE_EXECUTABLE,
6743 get_color_value("TOG_COLOR_TREE_EXECUTABLE"));
6744 if (err)
6745 goto done;
6747 err = add_color(&s->colors, "^$", TOG_COLOR_COMMIT,
6748 get_color_value("TOG_COLOR_COMMIT"));
6749 if (err)
6750 goto done;
6753 view->show = show_tree_view;
6754 view->input = input_tree_view;
6755 view->close = close_tree_view;
6756 view->search_start = search_start_tree_view;
6757 view->search_next = search_next_tree_view;
6758 done:
6759 free(commit_id_str);
6760 if (commit)
6761 got_object_commit_close(commit);
6762 if (err)
6763 close_tree_view(view);
6764 return err;
6767 static const struct got_error *
6768 close_tree_view(struct tog_view *view)
6770 struct tog_tree_view_state *s = &view->state.tree;
6772 free_colors(&s->colors);
6773 free(s->tree_label);
6774 s->tree_label = NULL;
6775 free(s->commit_id);
6776 s->commit_id = NULL;
6777 free(s->head_ref_name);
6778 s->head_ref_name = NULL;
6779 while (!TAILQ_EMPTY(&s->parents)) {
6780 struct tog_parent_tree *parent;
6781 parent = TAILQ_FIRST(&s->parents);
6782 TAILQ_REMOVE(&s->parents, parent, entry);
6783 if (parent->tree != s->root)
6784 got_object_tree_close(parent->tree);
6785 free(parent);
6788 if (s->tree != NULL && s->tree != s->root)
6789 got_object_tree_close(s->tree);
6790 if (s->root)
6791 got_object_tree_close(s->root);
6792 return NULL;
6795 static const struct got_error *
6796 search_start_tree_view(struct tog_view *view)
6798 struct tog_tree_view_state *s = &view->state.tree;
6800 s->matched_entry = NULL;
6801 return NULL;
6804 static int
6805 match_tree_entry(struct got_tree_entry *te, regex_t *regex)
6807 regmatch_t regmatch;
6809 return regexec(regex, got_tree_entry_get_name(te), 1, &regmatch,
6810 0) == 0;
6813 static const struct got_error *
6814 search_next_tree_view(struct tog_view *view)
6816 struct tog_tree_view_state *s = &view->state.tree;
6817 struct got_tree_entry *te = NULL;
6819 if (!view->searching) {
6820 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6821 return NULL;
6824 if (s->matched_entry) {
6825 if (view->searching == TOG_SEARCH_FORWARD) {
6826 if (s->selected_entry)
6827 te = got_tree_entry_get_next(s->tree,
6828 s->selected_entry);
6829 else
6830 te = got_object_tree_get_first_entry(s->tree);
6831 } else {
6832 if (s->selected_entry == NULL)
6833 te = got_object_tree_get_last_entry(s->tree);
6834 else
6835 te = got_tree_entry_get_prev(s->tree,
6836 s->selected_entry);
6838 } else {
6839 if (s->selected_entry)
6840 te = s->selected_entry;
6841 else if (view->searching == TOG_SEARCH_FORWARD)
6842 te = got_object_tree_get_first_entry(s->tree);
6843 else
6844 te = got_object_tree_get_last_entry(s->tree);
6847 while (1) {
6848 if (te == NULL) {
6849 if (s->matched_entry == NULL) {
6850 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6851 return NULL;
6853 if (view->searching == TOG_SEARCH_FORWARD)
6854 te = got_object_tree_get_first_entry(s->tree);
6855 else
6856 te = got_object_tree_get_last_entry(s->tree);
6859 if (match_tree_entry(te, &view->regex)) {
6860 view->search_next_done = TOG_SEARCH_HAVE_MORE;
6861 s->matched_entry = te;
6862 break;
6865 if (view->searching == TOG_SEARCH_FORWARD)
6866 te = got_tree_entry_get_next(s->tree, te);
6867 else
6868 te = got_tree_entry_get_prev(s->tree, te);
6871 if (s->matched_entry) {
6872 s->first_displayed_entry = s->matched_entry;
6873 s->selected = 0;
6876 return NULL;
6879 static const struct got_error *
6880 show_tree_view(struct tog_view *view)
6882 const struct got_error *err = NULL;
6883 struct tog_tree_view_state *s = &view->state.tree;
6884 char *parent_path;
6886 err = tree_entry_path(&parent_path, &s->parents, NULL);
6887 if (err)
6888 return err;
6890 err = draw_tree_entries(view, parent_path);
6891 free(parent_path);
6893 view_border(view);
6894 return err;
6897 static const struct got_error *
6898 tree_goto_line(struct tog_view *view, int nlines)
6900 const struct got_error *err = NULL;
6901 struct tog_tree_view_state *s = &view->state.tree;
6902 struct got_tree_entry **fte, **lte, **ste;
6903 int g, last, first = 1, i = 1;
6904 int root = s->tree == s->root;
6905 int off = root ? 1 : 2;
6907 g = view->gline;
6908 view->gline = 0;
6910 if (g == 0)
6911 g = 1;
6912 else if (g > got_object_tree_get_nentries(s->tree))
6913 g = got_object_tree_get_nentries(s->tree) + (root ? 0 : 1);
6915 fte = &s->first_displayed_entry;
6916 lte = &s->last_displayed_entry;
6917 ste = &s->selected_entry;
6919 if (*fte != NULL) {
6920 first = got_tree_entry_get_index(*fte);
6921 first += off; /* account for ".." */
6923 last = got_tree_entry_get_index(*lte);
6924 last += off;
6926 if (g >= first && g <= last && g - first < nlines) {
6927 s->selected = g - first;
6928 return NULL; /* gline is on the current page */
6931 if (*ste != NULL) {
6932 i = got_tree_entry_get_index(*ste);
6933 i += off;
6936 if (i < g) {
6937 err = tree_scroll_down(view, g - i);
6938 if (err)
6939 return err;
6940 if (got_tree_entry_get_index(*lte) >=
6941 got_object_tree_get_nentries(s->tree) - 1 &&
6942 first + s->selected < g &&
6943 s->selected < s->ndisplayed - 1) {
6944 first = got_tree_entry_get_index(*fte);
6945 first += off;
6946 s->selected = g - first;
6948 } else if (i > g)
6949 tree_scroll_up(s, i - g);
6951 if (g < nlines &&
6952 (*fte == NULL || (root && !got_tree_entry_get_index(*fte))))
6953 s->selected = g - 1;
6955 return NULL;
6958 static const struct got_error *
6959 input_tree_view(struct tog_view **new_view, struct tog_view *view, int ch)
6961 const struct got_error *err = NULL;
6962 struct tog_tree_view_state *s = &view->state.tree;
6963 struct got_tree_entry *te;
6964 int n, nscroll = view->nlines - 3;
6966 if (view->gline)
6967 return tree_goto_line(view, nscroll);
6969 switch (ch) {
6970 case 'i':
6971 s->show_ids = !s->show_ids;
6972 view->count = 0;
6973 break;
6974 case 'L':
6975 view->count = 0;
6976 if (!s->selected_entry)
6977 break;
6978 err = view_request_new(new_view, view, TOG_VIEW_LOG);
6979 break;
6980 case 'R':
6981 view->count = 0;
6982 err = view_request_new(new_view, view, TOG_VIEW_REF);
6983 break;
6984 case 'g':
6985 case KEY_HOME:
6986 s->selected = 0;
6987 view->count = 0;
6988 if (s->tree == s->root)
6989 s->first_displayed_entry =
6990 got_object_tree_get_first_entry(s->tree);
6991 else
6992 s->first_displayed_entry = NULL;
6993 break;
6994 case 'G':
6995 case KEY_END: {
6996 int eos = view->nlines - 3;
6998 if (view->mode == TOG_VIEW_SPLIT_HRZN)
6999 --eos; /* border */
7000 s->selected = 0;
7001 view->count = 0;
7002 te = got_object_tree_get_last_entry(s->tree);
7003 for (n = 0; n < eos; n++) {
7004 if (te == NULL) {
7005 if (s->tree != s->root) {
7006 s->first_displayed_entry = NULL;
7007 n++;
7009 break;
7011 s->first_displayed_entry = te;
7012 te = got_tree_entry_get_prev(s->tree, te);
7014 if (n > 0)
7015 s->selected = n - 1;
7016 break;
7018 case 'k':
7019 case KEY_UP:
7020 case CTRL('p'):
7021 if (s->selected > 0) {
7022 s->selected--;
7023 break;
7025 tree_scroll_up(s, 1);
7026 if (s->selected_entry == NULL ||
7027 (s->tree == s->root && s->selected_entry ==
7028 got_object_tree_get_first_entry(s->tree)))
7029 view->count = 0;
7030 break;
7031 case CTRL('u'):
7032 case 'u':
7033 nscroll /= 2;
7034 /* FALL THROUGH */
7035 case KEY_PPAGE:
7036 case CTRL('b'):
7037 case 'b':
7038 if (s->tree == s->root) {
7039 if (got_object_tree_get_first_entry(s->tree) ==
7040 s->first_displayed_entry)
7041 s->selected -= MIN(s->selected, nscroll);
7042 } else {
7043 if (s->first_displayed_entry == NULL)
7044 s->selected -= MIN(s->selected, nscroll);
7046 tree_scroll_up(s, MAX(0, nscroll));
7047 if (s->selected_entry == NULL ||
7048 (s->tree == s->root && s->selected_entry ==
7049 got_object_tree_get_first_entry(s->tree)))
7050 view->count = 0;
7051 break;
7052 case 'j':
7053 case KEY_DOWN:
7054 case CTRL('n'):
7055 if (s->selected < s->ndisplayed - 1) {
7056 s->selected++;
7057 break;
7059 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7060 == NULL) {
7061 /* can't scroll any further */
7062 view->count = 0;
7063 break;
7065 tree_scroll_down(view, 1);
7066 break;
7067 case CTRL('d'):
7068 case 'd':
7069 nscroll /= 2;
7070 /* FALL THROUGH */
7071 case KEY_NPAGE:
7072 case CTRL('f'):
7073 case 'f':
7074 case ' ':
7075 if (got_tree_entry_get_next(s->tree, s->last_displayed_entry)
7076 == NULL) {
7077 /* can't scroll any further; move cursor down */
7078 if (s->selected < s->ndisplayed - 1)
7079 s->selected += MIN(nscroll,
7080 s->ndisplayed - s->selected - 1);
7081 else
7082 view->count = 0;
7083 break;
7085 tree_scroll_down(view, nscroll);
7086 break;
7087 case KEY_ENTER:
7088 case '\r':
7089 case KEY_BACKSPACE:
7090 if (s->selected_entry == NULL || ch == KEY_BACKSPACE) {
7091 struct tog_parent_tree *parent;
7092 /* user selected '..' */
7093 if (s->tree == s->root) {
7094 view->count = 0;
7095 break;
7097 parent = TAILQ_FIRST(&s->parents);
7098 TAILQ_REMOVE(&s->parents, parent,
7099 entry);
7100 got_object_tree_close(s->tree);
7101 s->tree = parent->tree;
7102 s->first_displayed_entry =
7103 parent->first_displayed_entry;
7104 s->selected_entry =
7105 parent->selected_entry;
7106 s->selected = parent->selected;
7107 if (s->selected > view->nlines - 3) {
7108 err = offset_selection_down(view);
7109 if (err)
7110 break;
7112 free(parent);
7113 } else if (S_ISDIR(got_tree_entry_get_mode(
7114 s->selected_entry))) {
7115 struct got_tree_object *subtree;
7116 view->count = 0;
7117 err = got_object_open_as_tree(&subtree, s->repo,
7118 got_tree_entry_get_id(s->selected_entry));
7119 if (err)
7120 break;
7121 err = tree_view_visit_subtree(s, subtree);
7122 if (err) {
7123 got_object_tree_close(subtree);
7124 break;
7126 } else if (S_ISREG(got_tree_entry_get_mode(s->selected_entry)))
7127 err = view_request_new(new_view, view, TOG_VIEW_BLAME);
7128 break;
7129 case KEY_RESIZE:
7130 if (view->nlines >= 4 && s->selected >= view->nlines - 3)
7131 s->selected = view->nlines - 4;
7132 view->count = 0;
7133 break;
7134 default:
7135 view->count = 0;
7136 break;
7139 return err;
7142 __dead static void
7143 usage_tree(void)
7145 endwin();
7146 fprintf(stderr,
7147 "usage: %s tree [-c commit] [-r repository-path] [path]\n",
7148 getprogname());
7149 exit(1);
7152 static const struct got_error *
7153 cmd_tree(int argc, char *argv[])
7155 const struct got_error *error;
7156 struct got_repository *repo = NULL;
7157 struct got_worktree *worktree = NULL;
7158 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
7159 struct got_object_id *commit_id = NULL;
7160 struct got_commit_object *commit = NULL;
7161 const char *commit_id_arg = NULL;
7162 char *label = NULL;
7163 struct got_reference *ref = NULL;
7164 const char *head_ref_name = NULL;
7165 int ch;
7166 struct tog_view *view;
7167 int *pack_fds = NULL;
7169 while ((ch = getopt(argc, argv, "c:r:")) != -1) {
7170 switch (ch) {
7171 case 'c':
7172 commit_id_arg = optarg;
7173 break;
7174 case 'r':
7175 repo_path = realpath(optarg, NULL);
7176 if (repo_path == NULL)
7177 return got_error_from_errno2("realpath",
7178 optarg);
7179 break;
7180 default:
7181 usage_tree();
7182 /* NOTREACHED */
7186 argc -= optind;
7187 argv += optind;
7189 if (argc > 1)
7190 usage_tree();
7192 error = got_repo_pack_fds_open(&pack_fds);
7193 if (error != NULL)
7194 goto done;
7196 if (repo_path == NULL) {
7197 cwd = getcwd(NULL, 0);
7198 if (cwd == NULL)
7199 return got_error_from_errno("getcwd");
7200 error = got_worktree_open(&worktree, cwd);
7201 if (error && error->code != GOT_ERR_NOT_WORKTREE)
7202 goto done;
7203 if (worktree)
7204 repo_path =
7205 strdup(got_worktree_get_repo_path(worktree));
7206 else
7207 repo_path = strdup(cwd);
7208 if (repo_path == NULL) {
7209 error = got_error_from_errno("strdup");
7210 goto done;
7214 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
7215 if (error != NULL)
7216 goto done;
7218 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
7219 repo, worktree);
7220 if (error)
7221 goto done;
7223 init_curses();
7225 error = apply_unveil(got_repo_get_path(repo), NULL);
7226 if (error)
7227 goto done;
7229 error = tog_load_refs(repo, 0);
7230 if (error)
7231 goto done;
7233 if (commit_id_arg == NULL) {
7234 error = got_repo_match_object_id(&commit_id, &label,
7235 worktree ? got_worktree_get_head_ref_name(worktree) :
7236 GOT_REF_HEAD, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7237 if (error)
7238 goto done;
7239 head_ref_name = label;
7240 } else {
7241 error = got_ref_open(&ref, repo, commit_id_arg, 0);
7242 if (error == NULL)
7243 head_ref_name = got_ref_get_name(ref);
7244 else if (error->code != GOT_ERR_NOT_REF)
7245 goto done;
7246 error = got_repo_match_object_id(&commit_id, NULL,
7247 commit_id_arg, GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
7248 if (error)
7249 goto done;
7252 error = got_object_open_as_commit(&commit, repo, commit_id);
7253 if (error)
7254 goto done;
7256 view = view_open(0, 0, 0, 0, TOG_VIEW_TREE);
7257 if (view == NULL) {
7258 error = got_error_from_errno("view_open");
7259 goto done;
7261 error = open_tree_view(view, commit_id, head_ref_name, repo);
7262 if (error)
7263 goto done;
7264 if (!got_path_is_root_dir(in_repo_path)) {
7265 error = tree_view_walk_path(&view->state.tree, commit,
7266 in_repo_path);
7267 if (error)
7268 goto done;
7271 if (worktree) {
7272 /* Release work tree lock. */
7273 got_worktree_close(worktree);
7274 worktree = NULL;
7276 error = view_loop(view);
7277 done:
7278 free(repo_path);
7279 free(cwd);
7280 free(commit_id);
7281 free(label);
7282 if (ref)
7283 got_ref_close(ref);
7284 if (repo) {
7285 const struct got_error *close_err = got_repo_close(repo);
7286 if (error == NULL)
7287 error = close_err;
7289 if (pack_fds) {
7290 const struct got_error *pack_err =
7291 got_repo_pack_fds_close(pack_fds);
7292 if (error == NULL)
7293 error = pack_err;
7295 tog_free_refs();
7296 return error;
7299 static const struct got_error *
7300 ref_view_load_refs(struct tog_ref_view_state *s)
7302 struct got_reflist_entry *sre;
7303 struct tog_reflist_entry *re;
7305 s->nrefs = 0;
7306 TAILQ_FOREACH(sre, &tog_refs, entry) {
7307 if (strncmp(got_ref_get_name(sre->ref),
7308 "refs/got/", 9) == 0 &&
7309 strncmp(got_ref_get_name(sre->ref),
7310 "refs/got/backup/", 16) != 0)
7311 continue;
7313 re = malloc(sizeof(*re));
7314 if (re == NULL)
7315 return got_error_from_errno("malloc");
7317 re->ref = got_ref_dup(sre->ref);
7318 if (re->ref == NULL)
7319 return got_error_from_errno("got_ref_dup");
7320 re->idx = s->nrefs++;
7321 TAILQ_INSERT_TAIL(&s->refs, re, entry);
7324 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7325 return NULL;
7328 static void
7329 ref_view_free_refs(struct tog_ref_view_state *s)
7331 struct tog_reflist_entry *re;
7333 while (!TAILQ_EMPTY(&s->refs)) {
7334 re = TAILQ_FIRST(&s->refs);
7335 TAILQ_REMOVE(&s->refs, re, entry);
7336 got_ref_close(re->ref);
7337 free(re);
7341 static const struct got_error *
7342 open_ref_view(struct tog_view *view, struct got_repository *repo)
7344 const struct got_error *err = NULL;
7345 struct tog_ref_view_state *s = &view->state.ref;
7347 s->selected_entry = 0;
7348 s->repo = repo;
7350 TAILQ_INIT(&s->refs);
7351 STAILQ_INIT(&s->colors);
7353 err = ref_view_load_refs(s);
7354 if (err)
7355 return err;
7357 if (has_colors() && getenv("TOG_COLORS") != NULL) {
7358 err = add_color(&s->colors, "^refs/heads/",
7359 TOG_COLOR_REFS_HEADS,
7360 get_color_value("TOG_COLOR_REFS_HEADS"));
7361 if (err)
7362 goto done;
7364 err = add_color(&s->colors, "^refs/tags/",
7365 TOG_COLOR_REFS_TAGS,
7366 get_color_value("TOG_COLOR_REFS_TAGS"));
7367 if (err)
7368 goto done;
7370 err = add_color(&s->colors, "^refs/remotes/",
7371 TOG_COLOR_REFS_REMOTES,
7372 get_color_value("TOG_COLOR_REFS_REMOTES"));
7373 if (err)
7374 goto done;
7376 err = add_color(&s->colors, "^refs/got/backup/",
7377 TOG_COLOR_REFS_BACKUP,
7378 get_color_value("TOG_COLOR_REFS_BACKUP"));
7379 if (err)
7380 goto done;
7383 view->show = show_ref_view;
7384 view->input = input_ref_view;
7385 view->close = close_ref_view;
7386 view->search_start = search_start_ref_view;
7387 view->search_next = search_next_ref_view;
7388 done:
7389 if (err)
7390 free_colors(&s->colors);
7391 return err;
7394 static const struct got_error *
7395 close_ref_view(struct tog_view *view)
7397 struct tog_ref_view_state *s = &view->state.ref;
7399 ref_view_free_refs(s);
7400 free_colors(&s->colors);
7402 return NULL;
7405 static const struct got_error *
7406 resolve_reflist_entry(struct got_object_id **commit_id,
7407 struct tog_reflist_entry *re, struct got_repository *repo)
7409 const struct got_error *err = NULL;
7410 struct got_object_id *obj_id;
7411 struct got_tag_object *tag = NULL;
7412 int obj_type;
7414 *commit_id = NULL;
7416 err = got_ref_resolve(&obj_id, repo, re->ref);
7417 if (err)
7418 return err;
7420 err = got_object_get_type(&obj_type, repo, obj_id);
7421 if (err)
7422 goto done;
7424 switch (obj_type) {
7425 case GOT_OBJ_TYPE_COMMIT:
7426 *commit_id = obj_id;
7427 break;
7428 case GOT_OBJ_TYPE_TAG:
7429 err = got_object_open_as_tag(&tag, repo, obj_id);
7430 if (err)
7431 goto done;
7432 free(obj_id);
7433 err = got_object_get_type(&obj_type, repo,
7434 got_object_tag_get_object_id(tag));
7435 if (err)
7436 goto done;
7437 if (obj_type != GOT_OBJ_TYPE_COMMIT) {
7438 err = got_error(GOT_ERR_OBJ_TYPE);
7439 goto done;
7441 *commit_id = got_object_id_dup(
7442 got_object_tag_get_object_id(tag));
7443 if (*commit_id == NULL) {
7444 err = got_error_from_errno("got_object_id_dup");
7445 goto done;
7447 break;
7448 default:
7449 err = got_error(GOT_ERR_OBJ_TYPE);
7450 break;
7453 done:
7454 if (tag)
7455 got_object_tag_close(tag);
7456 if (err) {
7457 free(*commit_id);
7458 *commit_id = NULL;
7460 return err;
7463 static const struct got_error *
7464 log_ref_entry(struct tog_view **new_view, int begin_y, int begin_x,
7465 struct tog_reflist_entry *re, struct got_repository *repo)
7467 struct tog_view *log_view;
7468 const struct got_error *err = NULL;
7469 struct got_object_id *commit_id = NULL;
7471 *new_view = NULL;
7473 err = resolve_reflist_entry(&commit_id, re, repo);
7474 if (err) {
7475 if (err->code != GOT_ERR_OBJ_TYPE)
7476 return err;
7477 else
7478 return NULL;
7481 log_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_LOG);
7482 if (log_view == NULL) {
7483 err = got_error_from_errno("view_open");
7484 goto done;
7487 err = open_log_view(log_view, commit_id, repo,
7488 got_ref_get_name(re->ref), "", 0);
7489 done:
7490 if (err)
7491 view_close(log_view);
7492 else
7493 *new_view = log_view;
7494 free(commit_id);
7495 return err;
7498 static void
7499 ref_scroll_up(struct tog_ref_view_state *s, int maxscroll)
7501 struct tog_reflist_entry *re;
7502 int i = 0;
7504 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7505 return;
7507 re = TAILQ_PREV(s->first_displayed_entry, tog_reflist_head, entry);
7508 while (i++ < maxscroll) {
7509 if (re == NULL)
7510 break;
7511 s->first_displayed_entry = re;
7512 re = TAILQ_PREV(re, tog_reflist_head, entry);
7516 static const struct got_error *
7517 ref_scroll_down(struct tog_view *view, int maxscroll)
7519 struct tog_ref_view_state *s = &view->state.ref;
7520 struct tog_reflist_entry *next, *last;
7521 int n = 0;
7523 if (s->first_displayed_entry)
7524 next = TAILQ_NEXT(s->first_displayed_entry, entry);
7525 else
7526 next = TAILQ_FIRST(&s->refs);
7528 last = s->last_displayed_entry;
7529 while (next && n++ < maxscroll) {
7530 if (last) {
7531 s->last_displayed_entry = last;
7532 last = TAILQ_NEXT(last, entry);
7534 if (last || (view->mode == TOG_VIEW_SPLIT_HRZN)) {
7535 s->first_displayed_entry = next;
7536 next = TAILQ_NEXT(next, entry);
7540 return NULL;
7543 static const struct got_error *
7544 search_start_ref_view(struct tog_view *view)
7546 struct tog_ref_view_state *s = &view->state.ref;
7548 s->matched_entry = NULL;
7549 return NULL;
7552 static int
7553 match_reflist_entry(struct tog_reflist_entry *re, regex_t *regex)
7555 regmatch_t regmatch;
7557 return regexec(regex, got_ref_get_name(re->ref), 1, &regmatch,
7558 0) == 0;
7561 static const struct got_error *
7562 search_next_ref_view(struct tog_view *view)
7564 struct tog_ref_view_state *s = &view->state.ref;
7565 struct tog_reflist_entry *re = NULL;
7567 if (!view->searching) {
7568 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7569 return NULL;
7572 if (s->matched_entry) {
7573 if (view->searching == TOG_SEARCH_FORWARD) {
7574 if (s->selected_entry)
7575 re = TAILQ_NEXT(s->selected_entry, entry);
7576 else
7577 re = TAILQ_PREV(s->selected_entry,
7578 tog_reflist_head, entry);
7579 } else {
7580 if (s->selected_entry == NULL)
7581 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7582 else
7583 re = TAILQ_PREV(s->selected_entry,
7584 tog_reflist_head, entry);
7586 } else {
7587 if (s->selected_entry)
7588 re = s->selected_entry;
7589 else if (view->searching == TOG_SEARCH_FORWARD)
7590 re = TAILQ_FIRST(&s->refs);
7591 else
7592 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7595 while (1) {
7596 if (re == NULL) {
7597 if (s->matched_entry == NULL) {
7598 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7599 return NULL;
7601 if (view->searching == TOG_SEARCH_FORWARD)
7602 re = TAILQ_FIRST(&s->refs);
7603 else
7604 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7607 if (match_reflist_entry(re, &view->regex)) {
7608 view->search_next_done = TOG_SEARCH_HAVE_MORE;
7609 s->matched_entry = re;
7610 break;
7613 if (view->searching == TOG_SEARCH_FORWARD)
7614 re = TAILQ_NEXT(re, entry);
7615 else
7616 re = TAILQ_PREV(re, tog_reflist_head, entry);
7619 if (s->matched_entry) {
7620 s->first_displayed_entry = s->matched_entry;
7621 s->selected = 0;
7624 return NULL;
7627 static const struct got_error *
7628 show_ref_view(struct tog_view *view)
7630 const struct got_error *err = NULL;
7631 struct tog_ref_view_state *s = &view->state.ref;
7632 struct tog_reflist_entry *re;
7633 char *line = NULL;
7634 wchar_t *wline;
7635 struct tog_color *tc;
7636 int width, n;
7637 int limit = view->nlines;
7639 werase(view->window);
7641 s->ndisplayed = 0;
7642 if (view_is_hsplit_top(view))
7643 --limit; /* border */
7645 if (limit == 0)
7646 return NULL;
7648 re = s->first_displayed_entry;
7650 if (asprintf(&line, "references [%d/%d]", re->idx + s->selected + 1,
7651 s->nrefs) == -1)
7652 return got_error_from_errno("asprintf");
7654 err = format_line(&wline, &width, NULL, line, 0, view->ncols, 0, 0);
7655 if (err) {
7656 free(line);
7657 return err;
7659 if (view_needs_focus_indication(view))
7660 wstandout(view->window);
7661 waddwstr(view->window, wline);
7662 if (view_needs_focus_indication(view))
7663 wstandend(view->window);
7664 free(wline);
7665 wline = NULL;
7666 free(line);
7667 line = NULL;
7668 if (width < view->ncols - 1)
7669 waddch(view->window, '\n');
7670 if (--limit <= 0)
7671 return NULL;
7673 n = 0;
7674 while (re && limit > 0) {
7675 char *line = NULL;
7676 char ymd[13]; /* YYYY-MM-DD + " " + NUL */
7678 if (s->show_date) {
7679 struct got_commit_object *ci;
7680 struct got_tag_object *tag;
7681 struct got_object_id *id;
7682 struct tm tm;
7683 time_t t;
7685 err = got_ref_resolve(&id, s->repo, re->ref);
7686 if (err)
7687 return err;
7688 err = got_object_open_as_tag(&tag, s->repo, id);
7689 if (err) {
7690 if (err->code != GOT_ERR_OBJ_TYPE) {
7691 free(id);
7692 return err;
7694 err = got_object_open_as_commit(&ci, s->repo,
7695 id);
7696 if (err) {
7697 free(id);
7698 return err;
7700 t = got_object_commit_get_committer_time(ci);
7701 got_object_commit_close(ci);
7702 } else {
7703 t = got_object_tag_get_tagger_time(tag);
7704 got_object_tag_close(tag);
7706 free(id);
7707 if (gmtime_r(&t, &tm) == NULL)
7708 return got_error_from_errno("gmtime_r");
7709 if (strftime(ymd, sizeof(ymd), "%G-%m-%d ", &tm) == 0)
7710 return got_error(GOT_ERR_NO_SPACE);
7712 if (got_ref_is_symbolic(re->ref)) {
7713 if (asprintf(&line, "%s%s -> %s", s->show_date ?
7714 ymd : "", got_ref_get_name(re->ref),
7715 got_ref_get_symref_target(re->ref)) == -1)
7716 return got_error_from_errno("asprintf");
7717 } else if (s->show_ids) {
7718 struct got_object_id *id;
7719 char *id_str;
7720 err = got_ref_resolve(&id, s->repo, re->ref);
7721 if (err)
7722 return err;
7723 err = got_object_id_str(&id_str, id);
7724 if (err) {
7725 free(id);
7726 return err;
7728 if (asprintf(&line, "%s%s: %s", s->show_date ? ymd : "",
7729 got_ref_get_name(re->ref), id_str) == -1) {
7730 err = got_error_from_errno("asprintf");
7731 free(id);
7732 free(id_str);
7733 return err;
7735 free(id);
7736 free(id_str);
7737 } else if (asprintf(&line, "%s%s", s->show_date ? ymd : "",
7738 got_ref_get_name(re->ref)) == -1)
7739 return got_error_from_errno("asprintf");
7741 err = format_line(&wline, &width, NULL, line, 0, view->ncols,
7742 0, 0);
7743 if (err) {
7744 free(line);
7745 return err;
7747 if (n == s->selected) {
7748 if (view->focussed)
7749 wstandout(view->window);
7750 s->selected_entry = re;
7752 tc = match_color(&s->colors, got_ref_get_name(re->ref));
7753 if (tc)
7754 wattr_on(view->window,
7755 COLOR_PAIR(tc->colorpair), NULL);
7756 waddwstr(view->window, wline);
7757 if (tc)
7758 wattr_off(view->window,
7759 COLOR_PAIR(tc->colorpair), NULL);
7760 if (width < view->ncols - 1)
7761 waddch(view->window, '\n');
7762 if (n == s->selected && view->focussed)
7763 wstandend(view->window);
7764 free(line);
7765 free(wline);
7766 wline = NULL;
7767 n++;
7768 s->ndisplayed++;
7769 s->last_displayed_entry = re;
7771 limit--;
7772 re = TAILQ_NEXT(re, entry);
7775 view_border(view);
7776 return err;
7779 static const struct got_error *
7780 browse_ref_tree(struct tog_view **new_view, int begin_y, int begin_x,
7781 struct tog_reflist_entry *re, struct got_repository *repo)
7783 const struct got_error *err = NULL;
7784 struct got_object_id *commit_id = NULL;
7785 struct tog_view *tree_view;
7787 *new_view = NULL;
7789 err = resolve_reflist_entry(&commit_id, re, repo);
7790 if (err) {
7791 if (err->code != GOT_ERR_OBJ_TYPE)
7792 return err;
7793 else
7794 return NULL;
7798 tree_view = view_open(0, 0, begin_y, begin_x, TOG_VIEW_TREE);
7799 if (tree_view == NULL) {
7800 err = got_error_from_errno("view_open");
7801 goto done;
7804 err = open_tree_view(tree_view, commit_id,
7805 got_ref_get_name(re->ref), repo);
7806 if (err)
7807 goto done;
7809 *new_view = tree_view;
7810 done:
7811 free(commit_id);
7812 return err;
7815 static const struct got_error *
7816 ref_goto_line(struct tog_view *view, int nlines)
7818 const struct got_error *err = NULL;
7819 struct tog_ref_view_state *s = &view->state.ref;
7820 int g, idx = s->selected_entry->idx;
7822 g = view->gline;
7823 view->gline = 0;
7825 if (g == 0)
7826 g = 1;
7827 else if (g > s->nrefs)
7828 g = s->nrefs;
7830 if (g >= s->first_displayed_entry->idx + 1 &&
7831 g <= s->last_displayed_entry->idx + 1 &&
7832 g - s->first_displayed_entry->idx - 1 < nlines) {
7833 s->selected = g - s->first_displayed_entry->idx - 1;
7834 return NULL;
7837 if (idx + 1 < g) {
7838 err = ref_scroll_down(view, g - idx - 1);
7839 if (err)
7840 return err;
7841 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL &&
7842 s->first_displayed_entry->idx + s->selected < g &&
7843 s->selected < s->ndisplayed - 1)
7844 s->selected = g - s->first_displayed_entry->idx - 1;
7845 } else if (idx + 1 > g)
7846 ref_scroll_up(s, idx - g + 1);
7848 if (g < nlines && s->first_displayed_entry->idx == 0)
7849 s->selected = g - 1;
7851 return NULL;
7855 static const struct got_error *
7856 input_ref_view(struct tog_view **new_view, struct tog_view *view, int ch)
7858 const struct got_error *err = NULL;
7859 struct tog_ref_view_state *s = &view->state.ref;
7860 struct tog_reflist_entry *re;
7861 int n, nscroll = view->nlines - 1;
7863 if (view->gline)
7864 return ref_goto_line(view, nscroll);
7866 switch (ch) {
7867 case 'i':
7868 s->show_ids = !s->show_ids;
7869 view->count = 0;
7870 break;
7871 case 'm':
7872 s->show_date = !s->show_date;
7873 view->count = 0;
7874 break;
7875 case 'o':
7876 s->sort_by_date = !s->sort_by_date;
7877 view->count = 0;
7878 err = got_reflist_sort(&tog_refs, s->sort_by_date ?
7879 got_ref_cmp_by_commit_timestamp_descending :
7880 tog_ref_cmp_by_name, s->repo);
7881 if (err)
7882 break;
7883 got_reflist_object_id_map_free(tog_refs_idmap);
7884 err = got_reflist_object_id_map_create(&tog_refs_idmap,
7885 &tog_refs, s->repo);
7886 if (err)
7887 break;
7888 ref_view_free_refs(s);
7889 err = ref_view_load_refs(s);
7890 break;
7891 case KEY_ENTER:
7892 case '\r':
7893 view->count = 0;
7894 if (!s->selected_entry)
7895 break;
7896 err = view_request_new(new_view, view, TOG_VIEW_LOG);
7897 break;
7898 case 'T':
7899 view->count = 0;
7900 if (!s->selected_entry)
7901 break;
7902 err = view_request_new(new_view, view, TOG_VIEW_TREE);
7903 break;
7904 case 'g':
7905 case KEY_HOME:
7906 s->selected = 0;
7907 view->count = 0;
7908 s->first_displayed_entry = TAILQ_FIRST(&s->refs);
7909 break;
7910 case 'G':
7911 case KEY_END: {
7912 int eos = view->nlines - 1;
7914 if (view->mode == TOG_VIEW_SPLIT_HRZN)
7915 --eos; /* border */
7916 s->selected = 0;
7917 view->count = 0;
7918 re = TAILQ_LAST(&s->refs, tog_reflist_head);
7919 for (n = 0; n < eos; n++) {
7920 if (re == NULL)
7921 break;
7922 s->first_displayed_entry = re;
7923 re = TAILQ_PREV(re, tog_reflist_head, entry);
7925 if (n > 0)
7926 s->selected = n - 1;
7927 break;
7929 case 'k':
7930 case KEY_UP:
7931 case CTRL('p'):
7932 if (s->selected > 0) {
7933 s->selected--;
7934 break;
7936 ref_scroll_up(s, 1);
7937 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7938 view->count = 0;
7939 break;
7940 case CTRL('u'):
7941 case 'u':
7942 nscroll /= 2;
7943 /* FALL THROUGH */
7944 case KEY_PPAGE:
7945 case CTRL('b'):
7946 case 'b':
7947 if (s->first_displayed_entry == TAILQ_FIRST(&s->refs))
7948 s->selected -= MIN(nscroll, s->selected);
7949 ref_scroll_up(s, MAX(0, nscroll));
7950 if (s->selected_entry == TAILQ_FIRST(&s->refs))
7951 view->count = 0;
7952 break;
7953 case 'j':
7954 case KEY_DOWN:
7955 case CTRL('n'):
7956 if (s->selected < s->ndisplayed - 1) {
7957 s->selected++;
7958 break;
7960 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7961 /* can't scroll any further */
7962 view->count = 0;
7963 break;
7965 ref_scroll_down(view, 1);
7966 break;
7967 case CTRL('d'):
7968 case 'd':
7969 nscroll /= 2;
7970 /* FALL THROUGH */
7971 case KEY_NPAGE:
7972 case CTRL('f'):
7973 case 'f':
7974 case ' ':
7975 if (TAILQ_NEXT(s->last_displayed_entry, entry) == NULL) {
7976 /* can't scroll any further; move cursor down */
7977 if (s->selected < s->ndisplayed - 1)
7978 s->selected += MIN(nscroll,
7979 s->ndisplayed - s->selected - 1);
7980 if (view->count > 1 && s->selected < s->ndisplayed - 1)
7981 s->selected += s->ndisplayed - s->selected - 1;
7982 view->count = 0;
7983 break;
7985 ref_scroll_down(view, nscroll);
7986 break;
7987 case CTRL('l'):
7988 view->count = 0;
7989 tog_free_refs();
7990 err = tog_load_refs(s->repo, s->sort_by_date);
7991 if (err)
7992 break;
7993 ref_view_free_refs(s);
7994 err = ref_view_load_refs(s);
7995 break;
7996 case KEY_RESIZE:
7997 if (view->nlines >= 2 && s->selected >= view->nlines - 1)
7998 s->selected = view->nlines - 2;
7999 break;
8000 default:
8001 view->count = 0;
8002 break;
8005 return err;
8008 __dead static void
8009 usage_ref(void)
8011 endwin();
8012 fprintf(stderr, "usage: %s ref [-r repository-path]\n",
8013 getprogname());
8014 exit(1);
8017 static const struct got_error *
8018 cmd_ref(int argc, char *argv[])
8020 const struct got_error *error;
8021 struct got_repository *repo = NULL;
8022 struct got_worktree *worktree = NULL;
8023 char *cwd = NULL, *repo_path = NULL;
8024 int ch;
8025 struct tog_view *view;
8026 int *pack_fds = NULL;
8028 while ((ch = getopt(argc, argv, "r:")) != -1) {
8029 switch (ch) {
8030 case 'r':
8031 repo_path = realpath(optarg, NULL);
8032 if (repo_path == NULL)
8033 return got_error_from_errno2("realpath",
8034 optarg);
8035 break;
8036 default:
8037 usage_ref();
8038 /* NOTREACHED */
8042 argc -= optind;
8043 argv += optind;
8045 if (argc > 1)
8046 usage_ref();
8048 error = got_repo_pack_fds_open(&pack_fds);
8049 if (error != NULL)
8050 goto done;
8052 if (repo_path == NULL) {
8053 cwd = getcwd(NULL, 0);
8054 if (cwd == NULL)
8055 return got_error_from_errno("getcwd");
8056 error = got_worktree_open(&worktree, cwd);
8057 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8058 goto done;
8059 if (worktree)
8060 repo_path =
8061 strdup(got_worktree_get_repo_path(worktree));
8062 else
8063 repo_path = strdup(cwd);
8064 if (repo_path == NULL) {
8065 error = got_error_from_errno("strdup");
8066 goto done;
8070 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8071 if (error != NULL)
8072 goto done;
8074 init_curses();
8076 error = apply_unveil(got_repo_get_path(repo), NULL);
8077 if (error)
8078 goto done;
8080 error = tog_load_refs(repo, 0);
8081 if (error)
8082 goto done;
8084 view = view_open(0, 0, 0, 0, TOG_VIEW_REF);
8085 if (view == NULL) {
8086 error = got_error_from_errno("view_open");
8087 goto done;
8090 error = open_ref_view(view, repo);
8091 if (error)
8092 goto done;
8094 if (worktree) {
8095 /* Release work tree lock. */
8096 got_worktree_close(worktree);
8097 worktree = NULL;
8099 error = view_loop(view);
8100 done:
8101 free(repo_path);
8102 free(cwd);
8103 if (repo) {
8104 const struct got_error *close_err = got_repo_close(repo);
8105 if (close_err)
8106 error = close_err;
8108 if (pack_fds) {
8109 const struct got_error *pack_err =
8110 got_repo_pack_fds_close(pack_fds);
8111 if (error == NULL)
8112 error = pack_err;
8114 tog_free_refs();
8115 return error;
8118 static const struct got_error *
8119 view_dispatch_request(struct tog_view **new_view, struct tog_view *view,
8120 enum tog_view_type request, int y, int x)
8122 const struct got_error *err = NULL;
8124 *new_view = NULL;
8126 switch (request) {
8127 case TOG_VIEW_DIFF:
8128 if (view->type == TOG_VIEW_LOG) {
8129 struct tog_log_view_state *s = &view->state.log;
8131 err = open_diff_view_for_commit(new_view, y, x,
8132 s->selected_entry->commit, s->selected_entry->id,
8133 view, s->repo);
8134 } else
8135 return got_error_msg(GOT_ERR_NOT_IMPL,
8136 "parent/child view pair not supported");
8137 break;
8138 case TOG_VIEW_BLAME:
8139 if (view->type == TOG_VIEW_TREE) {
8140 struct tog_tree_view_state *s = &view->state.tree;
8142 err = blame_tree_entry(new_view, y, x,
8143 s->selected_entry, &s->parents, s->commit_id,
8144 s->repo);
8145 } else
8146 return got_error_msg(GOT_ERR_NOT_IMPL,
8147 "parent/child view pair not supported");
8148 break;
8149 case TOG_VIEW_LOG:
8150 if (view->type == TOG_VIEW_BLAME)
8151 err = log_annotated_line(new_view, y, x,
8152 view->state.blame.repo, view->state.blame.id_to_log);
8153 else if (view->type == TOG_VIEW_TREE)
8154 err = log_selected_tree_entry(new_view, y, x,
8155 &view->state.tree);
8156 else if (view->type == TOG_VIEW_REF)
8157 err = log_ref_entry(new_view, y, x,
8158 view->state.ref.selected_entry,
8159 view->state.ref.repo);
8160 else
8161 return got_error_msg(GOT_ERR_NOT_IMPL,
8162 "parent/child view pair not supported");
8163 break;
8164 case TOG_VIEW_TREE:
8165 if (view->type == TOG_VIEW_LOG)
8166 err = browse_commit_tree(new_view, y, x,
8167 view->state.log.selected_entry,
8168 view->state.log.in_repo_path,
8169 view->state.log.head_ref_name,
8170 view->state.log.repo);
8171 else if (view->type == TOG_VIEW_REF)
8172 err = browse_ref_tree(new_view, y, x,
8173 view->state.ref.selected_entry,
8174 view->state.ref.repo);
8175 else
8176 return got_error_msg(GOT_ERR_NOT_IMPL,
8177 "parent/child view pair not supported");
8178 break;
8179 case TOG_VIEW_REF:
8180 *new_view = view_open(0, 0, y, x, TOG_VIEW_REF);
8181 if (*new_view == NULL)
8182 return got_error_from_errno("view_open");
8183 if (view->type == TOG_VIEW_LOG)
8184 err = open_ref_view(*new_view, view->state.log.repo);
8185 else if (view->type == TOG_VIEW_TREE)
8186 err = open_ref_view(*new_view, view->state.tree.repo);
8187 else
8188 err = got_error_msg(GOT_ERR_NOT_IMPL,
8189 "parent/child view pair not supported");
8190 if (err)
8191 view_close(*new_view);
8192 break;
8193 default:
8194 return got_error_msg(GOT_ERR_NOT_IMPL, "invalid view");
8197 return err;
8201 * If view was scrolled down to move the selected line into view when opening a
8202 * horizontal split, scroll back up when closing the split/toggling fullscreen.
8204 static void
8205 offset_selection_up(struct tog_view *view)
8207 switch (view->type) {
8208 case TOG_VIEW_BLAME: {
8209 struct tog_blame_view_state *s = &view->state.blame;
8210 if (s->first_displayed_line == 1) {
8211 s->selected_line = MAX(s->selected_line - view->offset,
8212 1);
8213 break;
8215 if (s->first_displayed_line > view->offset)
8216 s->first_displayed_line -= view->offset;
8217 else
8218 s->first_displayed_line = 1;
8219 s->selected_line += view->offset;
8220 break;
8222 case TOG_VIEW_LOG:
8223 log_scroll_up(&view->state.log, view->offset);
8224 view->state.log.selected += view->offset;
8225 break;
8226 case TOG_VIEW_REF:
8227 ref_scroll_up(&view->state.ref, view->offset);
8228 view->state.ref.selected += view->offset;
8229 break;
8230 case TOG_VIEW_TREE:
8231 tree_scroll_up(&view->state.tree, view->offset);
8232 view->state.tree.selected += view->offset;
8233 break;
8234 default:
8235 break;
8238 view->offset = 0;
8242 * If the selected line is in the section of screen covered by the bottom split,
8243 * scroll down offset lines to move it into view and index its new position.
8245 static const struct got_error *
8246 offset_selection_down(struct tog_view *view)
8248 const struct got_error *err = NULL;
8249 const struct got_error *(*scrolld)(struct tog_view *, int);
8250 int *selected = NULL;
8251 int header, offset;
8253 switch (view->type) {
8254 case TOG_VIEW_BLAME: {
8255 struct tog_blame_view_state *s = &view->state.blame;
8256 header = 3;
8257 scrolld = NULL;
8258 if (s->selected_line > view->nlines - header) {
8259 offset = abs(view->nlines - s->selected_line - header);
8260 s->first_displayed_line += offset;
8261 s->selected_line -= offset;
8262 view->offset = offset;
8264 break;
8266 case TOG_VIEW_LOG: {
8267 struct tog_log_view_state *s = &view->state.log;
8268 scrolld = &log_scroll_down;
8269 header = view_is_parent_view(view) ? 3 : 2;
8270 selected = &s->selected;
8271 break;
8273 case TOG_VIEW_REF: {
8274 struct tog_ref_view_state *s = &view->state.ref;
8275 scrolld = &ref_scroll_down;
8276 header = 3;
8277 selected = &s->selected;
8278 break;
8280 case TOG_VIEW_TREE: {
8281 struct tog_tree_view_state *s = &view->state.tree;
8282 scrolld = &tree_scroll_down;
8283 header = 5;
8284 selected = &s->selected;
8285 break;
8287 default:
8288 selected = NULL;
8289 scrolld = NULL;
8290 header = 0;
8291 break;
8294 if (selected && *selected > view->nlines - header) {
8295 offset = abs(view->nlines - *selected - header);
8296 view->offset = offset;
8297 if (scrolld && offset) {
8298 err = scrolld(view, offset);
8299 *selected -= offset;
8303 return err;
8306 static void
8307 list_commands(FILE *fp)
8309 size_t i;
8311 fprintf(fp, "commands:");
8312 for (i = 0; i < nitems(tog_commands); i++) {
8313 const struct tog_cmd *cmd = &tog_commands[i];
8314 fprintf(fp, " %s", cmd->name);
8316 fputc('\n', fp);
8319 __dead static void
8320 usage(int hflag, int status)
8322 FILE *fp = (status == 0) ? stdout : stderr;
8324 fprintf(fp, "usage: %s [-h] [-V | --version] [command] [arg ...]\n",
8325 getprogname());
8326 if (hflag) {
8327 fprintf(fp, "lazy usage: %s path\n", getprogname());
8328 list_commands(fp);
8330 exit(status);
8333 static char **
8334 make_argv(int argc, ...)
8336 va_list ap;
8337 char **argv;
8338 int i;
8340 va_start(ap, argc);
8342 argv = calloc(argc, sizeof(char *));
8343 if (argv == NULL)
8344 err(1, "calloc");
8345 for (i = 0; i < argc; i++) {
8346 argv[i] = strdup(va_arg(ap, char *));
8347 if (argv[i] == NULL)
8348 err(1, "strdup");
8351 va_end(ap);
8352 return argv;
8356 * Try to convert 'tog path' into a 'tog log path' command.
8357 * The user could simply have mistyped the command rather than knowingly
8358 * provided a path. So check whether argv[0] can in fact be resolved
8359 * to a path in the HEAD commit and print a special error if not.
8360 * This hack is for mpi@ <3
8362 static const struct got_error *
8363 tog_log_with_path(int argc, char *argv[])
8365 const struct got_error *error = NULL, *close_err;
8366 const struct tog_cmd *cmd = NULL;
8367 struct got_repository *repo = NULL;
8368 struct got_worktree *worktree = NULL;
8369 struct got_object_id *commit_id = NULL, *id = NULL;
8370 struct got_commit_object *commit = NULL;
8371 char *cwd = NULL, *repo_path = NULL, *in_repo_path = NULL;
8372 char *commit_id_str = NULL, **cmd_argv = NULL;
8373 int *pack_fds = NULL;
8375 cwd = getcwd(NULL, 0);
8376 if (cwd == NULL)
8377 return got_error_from_errno("getcwd");
8379 error = got_repo_pack_fds_open(&pack_fds);
8380 if (error != NULL)
8381 goto done;
8383 error = got_worktree_open(&worktree, cwd);
8384 if (error && error->code != GOT_ERR_NOT_WORKTREE)
8385 goto done;
8387 if (worktree)
8388 repo_path = strdup(got_worktree_get_repo_path(worktree));
8389 else
8390 repo_path = strdup(cwd);
8391 if (repo_path == NULL) {
8392 error = got_error_from_errno("strdup");
8393 goto done;
8396 error = got_repo_open(&repo, repo_path, NULL, pack_fds);
8397 if (error != NULL)
8398 goto done;
8400 error = get_in_repo_path_from_argv0(&in_repo_path, argc, argv,
8401 repo, worktree);
8402 if (error)
8403 goto done;
8405 error = tog_load_refs(repo, 0);
8406 if (error)
8407 goto done;
8408 error = got_repo_match_object_id(&commit_id, NULL, worktree ?
8409 got_worktree_get_head_ref_name(worktree) : GOT_REF_HEAD,
8410 GOT_OBJ_TYPE_COMMIT, &tog_refs, repo);
8411 if (error)
8412 goto done;
8414 if (worktree) {
8415 got_worktree_close(worktree);
8416 worktree = NULL;
8419 error = got_object_open_as_commit(&commit, repo, commit_id);
8420 if (error)
8421 goto done;
8423 error = got_object_id_by_path(&id, repo, commit, in_repo_path);
8424 if (error) {
8425 if (error->code != GOT_ERR_NO_TREE_ENTRY)
8426 goto done;
8427 fprintf(stderr, "%s: '%s' is no known command or path\n",
8428 getprogname(), argv[0]);
8429 usage(1, 1);
8430 /* not reached */
8433 error = got_object_id_str(&commit_id_str, commit_id);
8434 if (error)
8435 goto done;
8437 cmd = &tog_commands[0]; /* log */
8438 argc = 4;
8439 cmd_argv = make_argv(argc, cmd->name, "-c", commit_id_str, argv[0]);
8440 error = cmd->cmd_main(argc, cmd_argv);
8441 done:
8442 if (repo) {
8443 close_err = got_repo_close(repo);
8444 if (error == NULL)
8445 error = close_err;
8447 if (commit)
8448 got_object_commit_close(commit);
8449 if (worktree)
8450 got_worktree_close(worktree);
8451 if (pack_fds) {
8452 const struct got_error *pack_err =
8453 got_repo_pack_fds_close(pack_fds);
8454 if (error == NULL)
8455 error = pack_err;
8457 free(id);
8458 free(commit_id_str);
8459 free(commit_id);
8460 free(cwd);
8461 free(repo_path);
8462 free(in_repo_path);
8463 if (cmd_argv) {
8464 int i;
8465 for (i = 0; i < argc; i++)
8466 free(cmd_argv[i]);
8467 free(cmd_argv);
8469 tog_free_refs();
8470 return error;
8473 int
8474 main(int argc, char *argv[])
8476 const struct got_error *error = NULL;
8477 const struct tog_cmd *cmd = NULL;
8478 int ch, hflag = 0, Vflag = 0;
8479 char **cmd_argv = NULL;
8480 static const struct option longopts[] = {
8481 { "version", no_argument, NULL, 'V' },
8482 { NULL, 0, NULL, 0}
8484 char *diff_algo_str = NULL;
8486 if (!isatty(STDIN_FILENO))
8487 errx(1, "standard input is not a tty");
8489 setlocale(LC_CTYPE, "");
8491 while ((ch = getopt_long(argc, argv, "+hV", longopts, NULL)) != -1) {
8492 switch (ch) {
8493 case 'h':
8494 hflag = 1;
8495 break;
8496 case 'V':
8497 Vflag = 1;
8498 break;
8499 default:
8500 usage(hflag, 1);
8501 /* NOTREACHED */
8505 argc -= optind;
8506 argv += optind;
8507 optind = 1;
8508 optreset = 1;
8510 if (Vflag) {
8511 got_version_print_str();
8512 return 0;
8515 #ifndef PROFILE
8516 if (pledge("stdio rpath wpath cpath flock proc tty exec sendfd unveil",
8517 NULL) == -1)
8518 err(1, "pledge");
8519 #endif
8521 if (argc == 0) {
8522 if (hflag)
8523 usage(hflag, 0);
8524 /* Build an argument vector which runs a default command. */
8525 cmd = &tog_commands[0];
8526 argc = 1;
8527 cmd_argv = make_argv(argc, cmd->name);
8528 } else {
8529 size_t i;
8531 /* Did the user specify a command? */
8532 for (i = 0; i < nitems(tog_commands); i++) {
8533 if (strncmp(tog_commands[i].name, argv[0],
8534 strlen(argv[0])) == 0) {
8535 cmd = &tog_commands[i];
8536 break;
8541 diff_algo_str = getenv("TOG_DIFF_ALGORITHM");
8542 if (diff_algo_str) {
8543 if (strcasecmp(diff_algo_str, "patience") == 0)
8544 tog_diff_algo = GOT_DIFF_ALGORITHM_PATIENCE;
8545 if (strcasecmp(diff_algo_str, "myers") == 0)
8546 tog_diff_algo = GOT_DIFF_ALGORITHM_MYERS;
8549 if (cmd == NULL) {
8550 if (argc != 1)
8551 usage(0, 1);
8552 /* No command specified; try log with a path */
8553 error = tog_log_with_path(argc, argv);
8554 } else {
8555 if (hflag)
8556 cmd->cmd_usage();
8557 else
8558 error = cmd->cmd_main(argc, cmd_argv ? cmd_argv : argv);
8561 endwin();
8562 putchar('\n');
8563 if (cmd_argv) {
8564 int i;
8565 for (i = 0; i < argc; i++)
8566 free(cmd_argv[i]);
8567 free(cmd_argv);
8570 if (error && error->code != GOT_ERR_CANCELLED)
8571 fprintf(stderr, "%s: %s\n", getprogname(), error->msg);
8572 return 0;